@anuma/sdk 1.0.0 → 1.1.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 (87) hide show
  1. package/README.md +54 -53
  2. package/dist/api/spec.cjs +30 -0
  3. package/dist/api/spec.d.mts +3 -0
  4. package/dist/api/spec.d.ts +3 -0
  5. package/dist/api/spec.mjs +12 -0
  6. package/dist/chunk-4ETHWSXJ.mjs +25 -0
  7. package/dist/client/index.cjs +2344 -0
  8. package/dist/client/index.d.mts +10368 -0
  9. package/dist/client/index.d.ts +10368 -0
  10. package/dist/client/index.mjs +2168 -0
  11. package/dist/clientConfig-WITO4T6L.mjs +12 -0
  12. package/dist/constants/index.cjs +30 -0
  13. package/dist/constants/index.d.mts +20 -0
  14. package/dist/constants/index.d.ts +20 -0
  15. package/dist/constants/index.mjs +5 -0
  16. package/dist/design/index.cjs +1523 -0
  17. package/dist/design/index.d.mts +561 -0
  18. package/dist/design/index.d.ts +561 -0
  19. package/dist/design/index.mjs +1468 -0
  20. package/dist/expo/chunk-DFVCS3QQ.mjs +246 -0
  21. package/dist/{react/chunk-MJJIYFAX.mjs → expo/chunk-GYKJOWEO.mjs} +13 -1
  22. package/dist/expo/chunk-PUKP5H4F.mjs +5278 -0
  23. package/dist/expo/chunk-Y7XT2VNQ.mjs +646 -0
  24. package/dist/expo/clientConfig-VPOGQRNP.mjs +12 -0
  25. package/dist/expo/consolidate-HEMQGOUD.mjs +131 -0
  26. package/dist/expo/index.cjs +16784 -6689
  27. package/dist/expo/index.d.mts +5746 -1474
  28. package/dist/expo/index.d.ts +5746 -1474
  29. package/dist/expo/index.mjs +9669 -6189
  30. package/dist/expo/recall-YRWAAU6K.mjs +8 -0
  31. package/dist/index.cjs +2992 -42
  32. package/dist/index.d.mts +7719 -1835
  33. package/dist/index.d.ts +7719 -1835
  34. package/dist/index.mjs +2859 -39
  35. package/dist/next/index.cjs +6 -2
  36. package/dist/next/index.d.mts +24 -1
  37. package/dist/next/index.d.ts +24 -1
  38. package/dist/next/index.mjs +6 -2
  39. package/dist/pii/transformers.cjs +126 -0
  40. package/dist/pii/transformers.d.mts +103 -0
  41. package/dist/pii/transformers.d.ts +103 -0
  42. package/dist/pii/transformers.mjs +90 -0
  43. package/dist/react/chunk-DFVCS3QQ.mjs +246 -0
  44. package/dist/{expo/chunk-MJJIYFAX.mjs → react/chunk-GYKJOWEO.mjs} +13 -1
  45. package/dist/react/chunk-Q2ANFWEP.mjs +5596 -0
  46. package/dist/react/chunk-TP6CJZ25.mjs +645 -0
  47. package/dist/react/clientConfig-VPOGQRNP.mjs +12 -0
  48. package/dist/react/consolidate-IJH7LD2T.mjs +131 -0
  49. package/dist/react/index.cjs +25453 -11029
  50. package/dist/react/index.d.mts +7388 -1406
  51. package/dist/react/index.d.ts +7388 -1406
  52. package/dist/react/index.mjs +16101 -8648
  53. package/dist/react/recall-YBC7YCNC.mjs +8 -0
  54. package/dist/server/chunk-FMGZTVXQ.mjs +62 -0
  55. package/dist/server/chunk-HPURS22B.mjs +19452 -0
  56. package/dist/server/chunk-PXN5Q3MD.mjs +643 -0
  57. package/dist/server/chunk-RCCKRTBI.mjs +230 -0
  58. package/dist/server/clientConfig-GMADOBPK.mjs +12 -0
  59. package/dist/server/consolidate-A2ZIX5WF.mjs +131 -0
  60. package/dist/server/index.cjs +32109 -0
  61. package/dist/server/index.d.mts +7310 -0
  62. package/dist/server/index.d.ts +7310 -0
  63. package/dist/server/index.mjs +11168 -0
  64. package/dist/server/recall-PFYFVYMS.mjs +8 -0
  65. package/dist/tools/index.cjs +12682 -34
  66. package/dist/tools/index.d.mts +2733 -18
  67. package/dist/tools/index.d.ts +2733 -18
  68. package/dist/tools/index.mjs +12565 -33
  69. package/dist/utils/index.cjs +165 -0
  70. package/dist/utils/index.d.mts +14 -0
  71. package/dist/utils/index.d.ts +14 -0
  72. package/dist/utils/index.mjs +145 -0
  73. package/dist/vercel/index.d.mts +0 -3
  74. package/dist/vercel/index.d.ts +0 -3
  75. package/package.json +127 -16
  76. package/dist/expo/chunk-LJYAMK62.mjs +0 -25
  77. package/dist/expo/chunk-PJCZO4BQ.mjs +0 -25
  78. package/dist/expo/clientConfig-2MI4KULF.mjs +0 -10
  79. package/dist/expo/clientConfig-QDAXFL3W.mjs +0 -10
  80. package/dist/expo/clientConfig-R4IOW7I2.mjs +0 -10
  81. package/dist/react/chunk-LJYAMK62.mjs +0 -25
  82. package/dist/react/chunk-PJCZO4BQ.mjs +0 -25
  83. package/dist/react/clientConfig-2MI4KULF.mjs +0 -10
  84. package/dist/react/clientConfig-QDAXFL3W.mjs +0 -10
  85. package/dist/react/clientConfig-R4IOW7I2.mjs +0 -10
  86. package/dist/tools/chunk-KDFGY4SK.mjs +0 -13
  87. package/dist/tools/clientConfig-RMDOT5YM.mjs +0 -10
package/dist/index.mjs CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ BASE_URL,
3
+ createClientConfig
4
+ } from "./chunk-4ETHWSXJ.mjs";
5
+
1
6
  // src/client/core/bodySerializer.gen.ts
2
7
  var jsonBodySerializer = {
3
8
  bodySerializer: (body) => JSON.stringify(
@@ -6,15 +11,6 @@ var jsonBodySerializer = {
6
11
  )
7
12
  };
8
13
 
9
- // src/client/core/params.gen.ts
10
- var extraPrefixesMap = {
11
- $body_: "body",
12
- $headers_: "headers",
13
- $path_: "path",
14
- $query_: "query"
15
- };
16
- var extraPrefixes = Object.entries(extraPrefixesMap);
17
-
18
14
  // src/client/core/serverSentEvents.gen.ts
19
15
  var createSseClient = ({
20
16
  onRequest,
@@ -803,17 +799,16 @@ var createClient = (config = {}) => {
803
799
  };
804
800
  };
805
801
 
806
- // src/clientConfig.ts
807
- var BASE_URL = "https://portal.anuma-dev.ai";
808
- var createClientConfig = (config) => ({
809
- ...config,
810
- baseUrl: BASE_URL
811
- });
812
-
813
802
  // src/client/client.gen.ts
814
803
  var client = createClient(createClientConfig(createConfig()));
815
804
 
816
805
  // src/client/sdk.gen.ts
806
+ var deleteApiV1Account = (options) => {
807
+ return (options?.client ?? client).delete({
808
+ url: "/api/v1/account",
809
+ ...options
810
+ });
811
+ };
817
812
  var postApiV1AdminAddCredits = (options) => {
818
813
  return (options.client ?? client).post({
819
814
  url: "/api/v1/admin/add-credits",
@@ -824,6 +819,32 @@ var postApiV1AdminAddCredits = (options) => {
824
819
  }
825
820
  });
826
821
  };
822
+ var postApiV1AdminAgents = (options) => {
823
+ return (options.client ?? client).post({
824
+ url: "/api/v1/admin/agents",
825
+ ...options,
826
+ headers: {
827
+ "Content-Type": "application/json",
828
+ ...options.headers
829
+ }
830
+ });
831
+ };
832
+ var deleteApiV1AdminAgentsById = (options) => {
833
+ return (options.client ?? client).delete({
834
+ url: "/api/v1/admin/agents/{id}",
835
+ ...options
836
+ });
837
+ };
838
+ var putApiV1AdminAgentsById = (options) => {
839
+ return (options.client ?? client).put({
840
+ url: "/api/v1/admin/agents/{id}",
841
+ ...options,
842
+ headers: {
843
+ "Content-Type": "application/json",
844
+ ...options.headers
845
+ }
846
+ });
847
+ };
827
848
  var getApiV1AdminApps = (options) => {
828
849
  return (options.client ?? client).get({
829
850
  url: "/api/v1/admin/apps",
@@ -900,6 +921,32 @@ var putApiV1AdminAppsById = (options) => {
900
921
  }
901
922
  });
902
923
  };
924
+ var postApiV1AdminPersonas = (options) => {
925
+ return (options.client ?? client).post({
926
+ url: "/api/v1/admin/personas",
927
+ ...options,
928
+ headers: {
929
+ "Content-Type": "application/json",
930
+ ...options.headers
931
+ }
932
+ });
933
+ };
934
+ var deleteApiV1AdminPersonasById = (options) => {
935
+ return (options.client ?? client).delete({
936
+ url: "/api/v1/admin/personas/{id}",
937
+ ...options
938
+ });
939
+ };
940
+ var putApiV1AdminPersonasById = (options) => {
941
+ return (options.client ?? client).put({
942
+ url: "/api/v1/admin/personas/{id}",
943
+ ...options,
944
+ headers: {
945
+ "Content-Type": "application/json",
946
+ ...options.headers
947
+ }
948
+ });
949
+ };
903
950
  var postApiV1AdminSeedApps = (options) => {
904
951
  return (options.client ?? client).post({
905
952
  url: "/api/v1/admin/seed-apps",
@@ -920,6 +967,46 @@ var postApiV1AdminSubscriptionTier = (options) => {
920
967
  }
921
968
  });
922
969
  };
970
+ var deleteApiV1AdminTextReset = (options) => {
971
+ return (options.client ?? client).delete({
972
+ url: "/api/v1/admin/text/reset",
973
+ ...options
974
+ });
975
+ };
976
+ var getApiV1AdminUsersLookup = (options) => {
977
+ return (options.client ?? client).get({
978
+ url: "/api/v1/admin/users/lookup",
979
+ ...options
980
+ });
981
+ };
982
+ var getApiV1AgentPreferences = (options) => {
983
+ return (options?.client ?? client).get({
984
+ url: "/api/v1/agent-preferences",
985
+ ...options
986
+ });
987
+ };
988
+ var getApiV1Agents = (options) => {
989
+ return (options?.client ?? client).get({
990
+ url: "/api/v1/agents",
991
+ ...options
992
+ });
993
+ };
994
+ var getApiV1AgentsById = (options) => {
995
+ return (options.client ?? client).get({
996
+ url: "/api/v1/agents/{id}",
997
+ ...options
998
+ });
999
+ };
1000
+ var putApiV1AgentsByIdPreference = (options) => {
1001
+ return (options.client ?? client).put({
1002
+ url: "/api/v1/agents/{id}/preference",
1003
+ ...options,
1004
+ headers: {
1005
+ "Content-Type": "application/json",
1006
+ ...options.headers
1007
+ }
1008
+ });
1009
+ };
923
1010
  var postApiV1ChatCompletions = (options) => {
924
1011
  return (options.client ?? client).post({
925
1012
  url: "/api/v1/chat/completions",
@@ -942,12 +1029,6 @@ var getApiV1CreditsBalance = (options) => {
942
1029
  ...options
943
1030
  });
944
1031
  };
945
- var postApiV1CreditsClaimDaily = (options) => {
946
- return (options?.client ?? client).post({
947
- url: "/api/v1/credits/claim-daily",
948
- ...options
949
- });
950
- };
951
1032
  var getApiV1CreditsPacks = (options) => {
952
1033
  return (options?.client ?? client).get({
953
1034
  url: "/api/v1/credits/packs",
@@ -964,9 +1045,149 @@ var postApiV1CreditsPurchase = (options) => {
964
1045
  }
965
1046
  });
966
1047
  };
967
- var postApiV1CreditsSyncSnag = (options) => {
968
- return (options?.client ?? client).post({
969
- url: "/api/v1/credits/sync-snag",
1048
+ var postApiV1CreditsRedeemTokens = (options) => {
1049
+ return (options.client ?? client).post({
1050
+ url: "/api/v1/credits/redeem-tokens",
1051
+ ...options,
1052
+ headers: {
1053
+ "Content-Type": "application/json",
1054
+ ...options.headers
1055
+ }
1056
+ });
1057
+ };
1058
+ var getApiV1DeveloperApps = (options) => {
1059
+ return (options?.client ?? client).get({
1060
+ url: "/api/v1/developer/apps",
1061
+ ...options
1062
+ });
1063
+ };
1064
+ var postApiV1DeveloperApps = (options) => {
1065
+ return (options.client ?? client).post({
1066
+ url: "/api/v1/developer/apps",
1067
+ ...options,
1068
+ headers: {
1069
+ "Content-Type": "application/json",
1070
+ ...options.headers
1071
+ }
1072
+ });
1073
+ };
1074
+ var deleteApiV1DeveloperAppsByAppUuid = (options) => {
1075
+ return (options.client ?? client).delete({
1076
+ url: "/api/v1/developer/apps/{app_uuid}",
1077
+ ...options
1078
+ });
1079
+ };
1080
+ var getApiV1DeveloperAppsByAppUuid = (options) => {
1081
+ return (options.client ?? client).get({
1082
+ url: "/api/v1/developer/apps/{app_uuid}",
1083
+ ...options
1084
+ });
1085
+ };
1086
+ var patchApiV1DeveloperAppsByAppUuid = (options) => {
1087
+ return (options.client ?? client).patch({
1088
+ url: "/api/v1/developer/apps/{app_uuid}",
1089
+ ...options,
1090
+ headers: {
1091
+ "Content-Type": "application/json",
1092
+ ...options.headers
1093
+ }
1094
+ });
1095
+ };
1096
+ var getApiV1DeveloperAppsByAppUuidApiKeys = (options) => {
1097
+ return (options.client ?? client).get({
1098
+ url: "/api/v1/developer/apps/{app_uuid}/api-keys",
1099
+ ...options
1100
+ });
1101
+ };
1102
+ var postApiV1DeveloperAppsByAppUuidApiKeys = (options) => {
1103
+ return (options.client ?? client).post({
1104
+ url: "/api/v1/developer/apps/{app_uuid}/api-keys",
1105
+ ...options,
1106
+ headers: {
1107
+ "Content-Type": "application/json",
1108
+ ...options.headers
1109
+ }
1110
+ });
1111
+ };
1112
+ var deleteApiV1DeveloperAppsByAppUuidApiKeysByKeyId = (options) => {
1113
+ return (options.client ?? client).delete({
1114
+ url: "/api/v1/developer/apps/{app_uuid}/api-keys/{key_id}",
1115
+ ...options
1116
+ });
1117
+ };
1118
+ var postApiV1DeveloperAppsByAppUuidFund = (options) => {
1119
+ return (options.client ?? client).post({
1120
+ url: "/api/v1/developer/apps/{app_uuid}/fund",
1121
+ ...options,
1122
+ headers: {
1123
+ "Content-Type": "application/json",
1124
+ ...options.headers
1125
+ }
1126
+ });
1127
+ };
1128
+ var deleteApiV1DeveloperAppsByAppUuidPrivy = (options) => {
1129
+ return (options.client ?? client).delete({
1130
+ url: "/api/v1/developer/apps/{app_uuid}/privy",
1131
+ ...options
1132
+ });
1133
+ };
1134
+ var postApiV1DeveloperAppsByAppUuidPrivy = (options) => {
1135
+ return (options.client ?? client).post({
1136
+ url: "/api/v1/developer/apps/{app_uuid}/privy",
1137
+ ...options,
1138
+ headers: {
1139
+ "Content-Type": "application/json",
1140
+ ...options.headers
1141
+ }
1142
+ });
1143
+ };
1144
+ var getApiV1DeveloperAppsByAppUuidUsage = (options) => {
1145
+ return (options.client ?? client).get({
1146
+ url: "/api/v1/developer/apps/{app_uuid}/usage",
1147
+ ...options
1148
+ });
1149
+ };
1150
+ var getApiV1DeveloperAppsByAppUuidUsageUsers = (options) => {
1151
+ return (options.client ?? client).get({
1152
+ url: "/api/v1/developer/apps/{app_uuid}/usage/users",
1153
+ ...options
1154
+ });
1155
+ };
1156
+ var getApiV1DeveloperAppsByAppUuidUsers = (options) => {
1157
+ return (options.client ?? client).get({
1158
+ url: "/api/v1/developer/apps/{app_uuid}/users",
1159
+ ...options
1160
+ });
1161
+ };
1162
+ var getApiV1DeveloperAppsByAppUuidUsersByAddress = (options) => {
1163
+ return (options.client ?? client).get({
1164
+ url: "/api/v1/developer/apps/{app_uuid}/users/{address}",
1165
+ ...options
1166
+ });
1167
+ };
1168
+ var patchApiV1DeveloperAppsByAppUuidUsersByAddress = (options) => {
1169
+ return (options.client ?? client).patch({
1170
+ url: "/api/v1/developer/apps/{app_uuid}/users/{address}",
1171
+ ...options,
1172
+ headers: {
1173
+ "Content-Type": "application/json",
1174
+ ...options.headers
1175
+ }
1176
+ });
1177
+ };
1178
+ var postApiV1DeveloperAppsByAppUuidUsersByAddressTopUp = (options) => {
1179
+ return (options.client ?? client).post({
1180
+ url: "/api/v1/developer/apps/{app_uuid}/users/{address}/top-up",
1181
+ ...options,
1182
+ headers: {
1183
+ "Content-Type": "application/json",
1184
+ ...options.headers
1185
+ }
1186
+ });
1187
+ };
1188
+ var getApiV1DeveloperBilling = (options) => {
1189
+ return (options?.client ?? client).get({
1190
+ url: "/api/v1/developer/billing",
970
1191
  ...options
971
1192
  });
972
1193
  };
@@ -992,6 +1213,34 @@ var getApiV1Models = (options) => {
992
1213
  ...options
993
1214
  });
994
1215
  };
1216
+ var getApiV1Personas = (options) => {
1217
+ return (options?.client ?? client).get({
1218
+ url: "/api/v1/personas",
1219
+ ...options
1220
+ });
1221
+ };
1222
+ var getApiV1PersonasById = (options) => {
1223
+ return (options.client ?? client).get({
1224
+ url: "/api/v1/personas/{id}",
1225
+ ...options
1226
+ });
1227
+ };
1228
+ var postApiV1PhoneCalls = (options) => {
1229
+ return (options.client ?? client).post({
1230
+ url: "/api/v1/phone-calls",
1231
+ ...options,
1232
+ headers: {
1233
+ "Content-Type": "application/json",
1234
+ ...options.headers
1235
+ }
1236
+ });
1237
+ };
1238
+ var getApiV1PhoneCallsByCallId = (options) => {
1239
+ return (options.client ?? client).get({
1240
+ url: "/api/v1/phone-calls/{call_id}",
1241
+ ...options
1242
+ });
1243
+ };
995
1244
  var postApiV1Responses = (options) => {
996
1245
  return (options.client ?? client).post({
997
1246
  url: "/api/v1/responses",
@@ -1005,6 +1254,16 @@ var postApiV1Responses = (options) => {
1005
1254
  var postApiV1SubscriptionsCancel = (options) => {
1006
1255
  return (options?.client ?? client).post({
1007
1256
  url: "/api/v1/subscriptions/cancel",
1257
+ ...options,
1258
+ headers: {
1259
+ "Content-Type": "application/json",
1260
+ ...options?.headers
1261
+ }
1262
+ });
1263
+ };
1264
+ var postApiV1SubscriptionsCancelScheduledDowngrade = (options) => {
1265
+ return (options?.client ?? client).post({
1266
+ url: "/api/v1/subscriptions/cancel-scheduled-downgrade",
1008
1267
  ...options
1009
1268
  });
1010
1269
  };
@@ -1028,18 +1287,44 @@ var postApiV1SubscriptionsCustomerPortal = (options) => {
1028
1287
  }
1029
1288
  });
1030
1289
  };
1290
+ var getApiV1SubscriptionsPlans = (options) => {
1291
+ return (options?.client ?? client).get({
1292
+ url: "/api/v1/subscriptions/plans",
1293
+ ...options
1294
+ });
1295
+ };
1031
1296
  var postApiV1SubscriptionsRenew = (options) => {
1032
1297
  return (options?.client ?? client).post({
1033
1298
  url: "/api/v1/subscriptions/renew",
1034
1299
  ...options
1035
1300
  });
1036
1301
  };
1302
+ var postApiV1SubscriptionsScheduleDowngrade = (options) => {
1303
+ return (options.client ?? client).post({
1304
+ url: "/api/v1/subscriptions/schedule-downgrade",
1305
+ ...options,
1306
+ headers: {
1307
+ "Content-Type": "application/json",
1308
+ ...options.headers
1309
+ }
1310
+ });
1311
+ };
1037
1312
  var getApiV1SubscriptionsStatus = (options) => {
1038
1313
  return (options?.client ?? client).get({
1039
1314
  url: "/api/v1/subscriptions/status",
1040
1315
  ...options
1041
1316
  });
1042
1317
  };
1318
+ var postApiV1SubscriptionsUpgrade = (options) => {
1319
+ return (options.client ?? client).post({
1320
+ url: "/api/v1/subscriptions/upgrade",
1321
+ ...options,
1322
+ headers: {
1323
+ "Content-Type": "application/json",
1324
+ ...options.headers
1325
+ }
1326
+ });
1327
+ };
1043
1328
  var postApiV1SubscriptionsWebhook = (options) => {
1044
1329
  return (options.client ?? client).post({
1045
1330
  url: "/api/v1/subscriptions/webhook",
@@ -1050,21 +1335,33 @@ var postApiV1SubscriptionsWebhook = (options) => {
1050
1335
  }
1051
1336
  });
1052
1337
  };
1053
- var getApiV1Tasks = (options) => {
1338
+ var getApiV1Tools = (options) => {
1339
+ return (options?.client ?? client).get({
1340
+ url: "/api/v1/tools",
1341
+ ...options
1342
+ });
1343
+ };
1344
+ var getApiV1UsageInferenceWeekly = (options) => {
1054
1345
  return (options?.client ?? client).get({
1055
- url: "/api/v1/tasks",
1346
+ url: "/api/v1/usage/inference-weekly",
1056
1347
  ...options
1057
1348
  });
1058
1349
  };
1059
- var getApiV1Tools = (options) => {
1350
+ var getApiV1UsageModels = (options) => {
1060
1351
  return (options?.client ?? client).get({
1061
- url: "/api/v1/tools",
1352
+ url: "/api/v1/usage/models",
1062
1353
  ...options
1063
1354
  });
1064
1355
  };
1065
- var postAuthOauthByProviderExchange = (options) => {
1356
+ var getApiV1UserApiKeys = (options) => {
1357
+ return (options?.client ?? client).get({
1358
+ url: "/api/v1/user/api-keys",
1359
+ ...options
1360
+ });
1361
+ };
1362
+ var postApiV1UserApiKeys = (options) => {
1066
1363
  return (options.client ?? client).post({
1067
- url: "/auth/oauth/{provider}/exchange",
1364
+ url: "/api/v1/user/api-keys",
1068
1365
  ...options,
1069
1366
  headers: {
1070
1367
  "Content-Type": "application/json",
@@ -1072,9 +1369,21 @@ var postAuthOauthByProviderExchange = (options) => {
1072
1369
  }
1073
1370
  });
1074
1371
  };
1075
- var postAuthOauthByProviderRefresh = (options) => {
1372
+ var deleteApiV1UserApiKeysByKeyId = (options) => {
1373
+ return (options.client ?? client).delete({
1374
+ url: "/api/v1/user/api-keys/{key_id}",
1375
+ ...options
1376
+ });
1377
+ };
1378
+ var getApiV1WalletsBinding = (options) => {
1379
+ return (options?.client ?? client).get({
1380
+ url: "/api/v1/wallets/binding",
1381
+ ...options
1382
+ });
1383
+ };
1384
+ var postApiV1WalletsBinding = (options) => {
1076
1385
  return (options.client ?? client).post({
1077
- url: "/auth/oauth/{provider}/refresh",
1386
+ url: "/api/v1/wallets/binding",
1078
1387
  ...options,
1079
1388
  headers: {
1080
1389
  "Content-Type": "application/json",
@@ -1082,8 +1391,62 @@ var postAuthOauthByProviderRefresh = (options) => {
1082
1391
  }
1083
1392
  });
1084
1393
  };
1085
- var postAuthOauthByProviderRevoke = (options) => {
1086
- return (options.client ?? client).post({
1394
+ var postApiV1WalletsBindingNonce = (options) => {
1395
+ return (options?.client ?? client).post({
1396
+ url: "/api/v1/wallets/binding/nonce",
1397
+ ...options
1398
+ });
1399
+ };
1400
+ var deleteApiV1WalletsBindingByAddress = (options) => {
1401
+ return (options.client ?? client).delete({
1402
+ url: "/api/v1/wallets/binding/{address}",
1403
+ ...options
1404
+ });
1405
+ };
1406
+ var postApiV1WebhooksRevenuecat = (options) => {
1407
+ return (options?.client ?? client).post({
1408
+ url: "/api/v1/webhooks/revenuecat",
1409
+ ...options,
1410
+ headers: {
1411
+ "Content-Type": "application/json",
1412
+ ...options?.headers
1413
+ }
1414
+ });
1415
+ };
1416
+ var getApiV1ZetaCreditRate = (options) => {
1417
+ return (options?.client ?? client).get({
1418
+ url: "/api/v1/zeta/credit-rate",
1419
+ ...options
1420
+ });
1421
+ };
1422
+ var getApiV1ZetaMarket = (options) => {
1423
+ return (options?.client ?? client).get({
1424
+ url: "/api/v1/zeta/market",
1425
+ ...options
1426
+ });
1427
+ };
1428
+ var postAuthOauthByProviderExchange = (options) => {
1429
+ return (options.client ?? client).post({
1430
+ url: "/auth/oauth/{provider}/exchange",
1431
+ ...options,
1432
+ headers: {
1433
+ "Content-Type": "application/json",
1434
+ ...options.headers
1435
+ }
1436
+ });
1437
+ };
1438
+ var postAuthOauthByProviderRefresh = (options) => {
1439
+ return (options.client ?? client).post({
1440
+ url: "/auth/oauth/{provider}/refresh",
1441
+ ...options,
1442
+ headers: {
1443
+ "Content-Type": "application/json",
1444
+ ...options.headers
1445
+ }
1446
+ });
1447
+ };
1448
+ var postAuthOauthByProviderRevoke = (options) => {
1449
+ return (options.client ?? client).post({
1087
1450
  url: "/auth/oauth/{provider}/revoke",
1088
1451
  ...options,
1089
1452
  headers: {
@@ -1098,41 +1461,2498 @@ var getHealth = (options) => {
1098
1461
  ...options
1099
1462
  });
1100
1463
  };
1464
+
1465
+ // src/tools/appBuilderPrompt.ts
1466
+ var APP_BUILDER_PROMPT = `App Builder tools (create_file, patch_file, and the rest described below) are available this turn, but they are OPTIONAL \u2014 having them does not mean you should build anything.
1467
+
1468
+ Build ONLY when the user gives an explicit instruction to build, create, generate, or change an app, tool, or UI \u2014 e.g. "build a todo app", "make a snake game", "add a footer to the app", "change the background to blue". A bare app name or feature reference is NOT a build instruction: if the user just says "todo app", "a snake game", or "qr code", or asks a question about an app, do NOT generate anything \u2014 reply normally, or ask what they'd like you to build. The same holds for greetings, questions, stories, explanations, advice, or code that isn't a runnable app: respond normally and do not create files. When it's unclear whether the user actually wants an app built, ask instead of building.
1469
+
1470
+ Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
1471
+
1472
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
1473
+
1474
+ WORKFLOW:
1475
+ 1. NEVER output code as text or markdown. ALWAYS use tools.
1476
+ 2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
1477
+ 3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
1478
+ 4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
1479
+ 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
1480
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
1481
+ 7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
1482
+
1483
+ STRUCTURE:
1484
+ - App.js: default-export React component. For non-trivial apps, define small co-located helpers (Header, CardList, Card, EditDialog, \u2026) above the default export rather than one giant App.
1485
+ - App.css: all styles, imported in App.js. No inline style objects.
1486
+ - package.json: list ALL imported packages including react. No CDN script tags. Versions are auto-pinned.
1487
+ - Do NOT create index.js or index.html (auto-generated).
1488
+
1489
+ STATE & PERSISTENCE:
1490
+ - The code runs in the user's browser \u2014 standard browser APIs available (localStorage, URL hash, Date, fetch).
1491
+ - Persist user-created data (todos, cards, notes, settings) with localStorage so it survives refresh. Use a versioned key ("kanban.v1") and JSON.parse inside try/catch on read.
1492
+ - Treat persisted data as untrusted and possibly stale: a saved record may predate a field you just added (a timestamp, id, or setting), so default-fill or skip missing fields on read \u2014 never assume a loaded record has every field the current code expects. Bump the key version when the shape changes.
1493
+ - Lift state to App when multiple children need it; keep it local otherwise. Extract non-trivial logic into custom hooks (useTodos, useTimer).
1494
+ - useReducer for state shapes with several interrelated fields (cards + columns + filters + drag state).
1495
+
1496
+ FILE & IMAGE UPLOAD:
1497
+ - Picker: \`<input type="file" accept="image/*" multiple>\` (vary accept by use case: \`.csv,text/csv\`, \`.txt,.md,text/plain\`, etc.).
1498
+ - Drag-and-drop: call \`e.preventDefault()\` in onDragOver (otherwise drop never fires); read files from \`event.dataTransfer.files\`. Drop and picker should coexist.
1499
+ - Previews: \`<img src={URL.createObjectURL(file)} />\`. Call \`URL.revokeObjectURL\` on unmount or before replacing \u2014 otherwise the browser leaks memory.
1500
+ - localStorage cannot hold large binary. Persist only metadata for big files; re-upload on next visit (or use IndexedDB if you really need durable binary storage).
1501
+ - Validate size and type before processing; reject files larger than the app can hold in memory.
1502
+
1503
+ AI CAPABILITIES \u2014 \`window.app.complete(prompt: string): Promise<string>\` is available in this environment. Build for the real call.
1504
+ - When the app's core purpose is conversation, generation, grading, recommendation, or any natural-language task, this IS the implementation \u2014 call it. NEVER fake it: no hardcoded or canned replies, no random or \`setTimeout\` "thinking", no demo-mode stub. A chat app, tutor, or assistant that doesn't call \`window.app.complete\` is wrong, not a placeholder.
1505
+ - Don't force it where it isn't needed \u2014 a calculator, todo list, or timer has no reason to call it. Match the implementation to what the app actually does.
1506
+ - Async: wrap in try/catch, show a loading state, and disable dependent inputs while waiting. Surface failures gracefully ("Couldn't reach the AI \u2014 try again").
1507
+ - Structure prompts with clear sections (Role / Context / Task / Format) and pass the relevant state (e.g. the running conversation) as context. Render the response as untrusted text: \`white-space: pre-wrap\`, never dangerouslySetInnerHTML.
1508
+ - Skip the call only when the answer is genuinely static \u2014 no language or reasoning needed. Cache repeated prompts in component state when sensible.
1509
+
1510
+ CODE QUALITY \u2014 write as a senior engineer would:
1511
+ - Handle edge cases (empty inputs, division by zero, invalid data). Show helpful error states, not crashes.
1512
+ - Never let formatting throw during render: guard \`new Date(x)\` / \`Intl\` / \`toLocaleString\` / \`.toFixed\` against missing or invalid values (e.g. \`Number.isNaN(d.getTime())\`) and return a fallback \u2014 one bad value from storage or state must not blank the whole app.
1513
+ - Semantic HTML: real headings, labels, buttons (not divs with onClick), form elements.
1514
+ - Accessible: aria-labels on icon buttons, focus-visible styles, keyboard navigable.
1515
+ - Extract into custom hooks or helpers when a component grows past ~80 lines.
1516
+
1517
+ STYLING \u2014 Tailwind is the CHASSIS, custom CSS carries the IDENTITY:
1518
+ - Tailwind (via Play CDN) for layout, spacing, state (hover/focus), responsive prefixes \u2014 uniform structure.
1519
+ - App.css carries the identity: @import the Google Fonts, declare CSS custom properties (--bg, --panel, --card, --ink, --muted, --accent, --hairline, --radius, --radius-sm, --shadow-card, --shadow-card-hi) in :root, gradients/textures/signature animations Tailwind can't express. Reference tokens from Tailwind via arbitrary values (\`className="bg-[var(--bg)]"\`) when needed. A well-designed app has 60-200 lines of App.css \u2014 not zero.
1520
+ - Modern CSS is how apps stop reading as generic-AI-output: \`color-mix(in oklab, var(--accent) 14%, transparent)\` for tinting, \`oklch()\` / \`oklab()\` for perceptually-uniform color, \`:has()\`, \`conic-gradient\` / \`radial-gradient\`, \`backdrop-filter\`, \`@container\` queries, inline SVG \`feTurbulence\` for texture.
1521
+ - Don't pull additional CSS frameworks. Tailwind + custom CSS is enough.
1522
+
1523
+ VISUAL DESIGN \u2014 every app should look like a real product, not a wireframe:
1524
+ - Let the chosen aesthetic drive every decision. "Editorial" wants italic display type and restrained color; "retro arcade" wants chunky shadows and saturated gradients. No safe-modern defaults.
1525
+ - Atmospheric depth: subtle radial wash, paper grain (inline SVG noise), warm/cool tint \u2014 every canvas should feel like a designed space, not a #fff rectangle.
1526
+ - Three shadow tiers (rest / hover / active). Pair drop shadows with inset highlights (\`box-shadow: 0 1px 0 rgba(255,255,255,.9) inset, 0 6px 14px -10px ...\`) for tactile feel.
1527
+ - Typography hierarchy: display font for headlines (italic accents on key words via \`<em>\`), body font for content, mono for metadata/labels \u2014 different families telegraph different information types.
1528
+ - Interactive polish: hover/active/focus on every clickable element, 200-300ms cubic-bezier transitions, keyboard shortcuts where natural (Esc to cancel, Cmd/Ctrl+Enter to commit), focus-visible rings keyed to the accent.
1529
+ - Light/dark mode if reasonable: a single CSS variable inversion under \`[data-theme="dark"]\`.
1530
+ - Customization affordance for multi-session apps: small "Tweaks" panel with theme / density / accent. Skip for throwaway demos.
1531
+ - Responsive: Tailwind responsive prefixes (\`sm:\`, \`md:\`, \`lg:\`) and \`@media\` in App.css. Mobile-first.`;
1532
+
1533
+ // src/tools/document/documentBuilderPrompt.ts
1534
+ var DOCUMENT_BUILDER_PROMPT = `Document tools (create_document, read_document, patch_document) are available this turn, but they are OPTIONAL \u2014 having them does not mean you should produce a document.
1535
+
1536
+ Use them ONLY when the user explicitly asks you to draft, write, compose, or generate a document \u2014 a contract, agreement, NDA, letter, cover letter, memo, essay, report, brief, proposal, or resume \u2014 e.g. "draft me a service agreement", "write a cover letter for this job", "make a one-page memo about X". A bare topic, a question, a request for an explanation, or a request for a slide deck or an interactive app is NOT a document instruction: respond normally and do not call these tools. When it's unclear whether the user wants a finished document, ask instead.
1537
+
1538
+ When you DO author a document, the document body goes entirely into the tool \u2014 NEVER write the document text as chat prose. The tool renders your source to a real, paginated PDF and attaches it to your reply automatically. AFTER the tool returns, briefly confirm in ONE short sentence what you made (e.g. "Drafted a cover letter for the product manager role \u2014 see the attached PDF."). Do not restate the document's contents.
1539
+
1540
+ AUTHORING \u2014 write the "source" as a single @react-pdf/renderer JSX expression (this is react-pdf, NOT HTML and NOT a slide deck):
1541
+ - Root is exactly one <Document> with at least one <Page>. Its only children are <Page> elements. Add more <Page> elements for longer documents \u2014 react-pdf also paginates overflow automatically.
1542
+ - Inside a <Page>: use <View> as flex containers and <Text> for ALL text. Raw text is only allowed inside <Text> (and <Link>); a <View> or <Page> may not contain bare text.
1543
+ - <Text> may nest <Text>, <Link>, or <Note> for inline styling, hyperlinks, and (rarely) a PDF comment annotation. A <Link> src must be an ordinary web link \u2014 http(s), mailto, tel, or a relative/anchor link; javascript:/data:/file: links are rejected. <Image> is self-closing and its src MUST be an inline "data:" URI \u2014 remote image URLs are rejected for privacy. Vector primitives (<Rect>/<Circle>/<Path>/etc.) must live inside an <Svg>.
1544
+ - Styling is react-pdf style objects only: style={{ marginTop: 12, fontSize: 11, fontFamily: "Times-Roman", flexDirection: "column" }}. Flexbox only \u2014 there is NO CSS grid, float, or box-shadow. Use camelCase react-pdf keys (margin/padding, flex*, width/height, color/backgroundColor, border*, text*, etc.).
1545
+ - fontFamily must be a built-in PDF font: Helvetica, Times-Roman, or Courier (with -Bold / -Oblique / -Italic / -BoldOblique variants), or Symbol / ZapfDingbats. Custom fonts are not supported.
1546
+ - LITERAL VALUES ONLY: no variables, no JS expressions, no .map(), no event handlers (onClick, \u2026), no spreads. Every attribute is a literal string, number, boolean, or a style object of literals.
1547
+
1548
+ A minimal example:
1549
+
1550
+ <Document>
1551
+ <Page size="A4" style={{ paddingVertical: 56, paddingHorizontal: 64, fontFamily: "Times-Roman", fontSize: 11, lineHeight: 1.5 }}>
1552
+ <Text style={{ fontSize: 18, fontFamily: "Times-Bold", marginBottom: 16, textAlign: "center" }}>MUTUAL NON-DISCLOSURE AGREEMENT</Text>
1553
+ <Text style={{ marginBottom: 10 }}>This Mutual Non-Disclosure Agreement (the "Agreement") is entered into as of the date of last signature below.</Text>
1554
+ <View style={{ marginTop: 14 }}>
1555
+ <Text style={{ fontFamily: "Times-Bold", marginBottom: 4 }}>1. Confidential Information</Text>
1556
+ <Text>Each party may disclose certain confidential and proprietary information to the other party.</Text>
1557
+ </View>
1558
+ </Page>
1559
+ </Document>
1560
+
1561
+ WORKFLOW:
1562
+ 1. To create or fully restructure a document, call create_document with the complete source.
1563
+ 2. To revise an existing document, call read_document first (its output is line-numbered "42: <text>" \u2014 the prefix is display-only, never copy it into a "find"), then patch_document with small find/replace edits. Each "find" must match exactly one location; add 2-3 lines of surrounding context if needed. Prefer patching over rewriting.
1564
+ 3. To attach several separate documents in one reply, call create_document multiple times with distinct documentId slugs (e.g. "nda", "cover-letter"). Each renders to its own PDF.
1565
+ 4. If a tool reports a DSL error (with line:col) or a render failure, fix the source and retry \u2014 do not give up or fall back to writing the document as chat text.`;
1566
+
1567
+ // src/lib/logger.ts
1568
+ var consoleLogger = {
1569
+ debug: console.log.bind(console),
1570
+ info: console.info.bind(console),
1571
+ warn: console.warn.bind(console),
1572
+ error: console.error.bind(console)
1573
+ };
1574
+ var noopLogger = {
1575
+ debug: () => {
1576
+ },
1577
+ info: () => {
1578
+ },
1579
+ warn: () => {
1580
+ },
1581
+ error: () => {
1582
+ }
1583
+ };
1584
+ var currentLogger = consoleLogger;
1585
+ function setLogger(logger) {
1586
+ currentLogger = logger;
1587
+ }
1588
+ function getLogger() {
1589
+ return currentLogger;
1590
+ }
1591
+
1592
+ // src/lib/memoryEngine/chunking.ts
1593
+ var DEFAULT_CHUNK_SIZE = 400;
1594
+ var DEFAULT_CHUNK_OVERLAP = 50;
1595
+ var DEFAULT_MIN_CHUNK_SIZE = 50;
1596
+ function splitIntoSentences(text) {
1597
+ const sentenceRegex = /[.!?]+[\s"')}\]]*(?=\s|$)/g;
1598
+ const sentences = [];
1599
+ let lastIndex = 0;
1600
+ let match;
1601
+ while ((match = sentenceRegex.exec(text)) !== null) {
1602
+ const endIndex = match.index + match[0].length;
1603
+ const sentence = text.slice(lastIndex, endIndex).trim();
1604
+ if (sentence) {
1605
+ sentences.push(sentence);
1606
+ }
1607
+ lastIndex = endIndex;
1608
+ }
1609
+ const remaining = text.slice(lastIndex).trim();
1610
+ if (remaining) {
1611
+ sentences.push(remaining);
1612
+ }
1613
+ return sentences;
1614
+ }
1615
+ function chunkText(text, options) {
1616
+ const {
1617
+ chunkSize = DEFAULT_CHUNK_SIZE,
1618
+ chunkOverlap: requestedOverlap = DEFAULT_CHUNK_OVERLAP,
1619
+ minChunkSize = DEFAULT_MIN_CHUNK_SIZE
1620
+ } = options ?? {};
1621
+ const chunkOverlap = Math.min(requestedOverlap, chunkSize - 1);
1622
+ if (text.length <= chunkSize) {
1623
+ return [
1624
+ {
1625
+ text: text.trim(),
1626
+ startOffset: 0,
1627
+ endOffset: text.length
1628
+ }
1629
+ ];
1630
+ }
1631
+ const sentences = splitIntoSentences(text);
1632
+ const chunks = [];
1633
+ let currentChunkSentences = [];
1634
+ let currentChunkStart = 0;
1635
+ let currentOffset = 0;
1636
+ for (let i = 0; i < sentences.length; i++) {
1637
+ const sentence = sentences[i];
1638
+ let sentenceStart = text.indexOf(sentence, currentOffset);
1639
+ if (sentenceStart === -1) {
1640
+ sentenceStart = currentOffset;
1641
+ }
1642
+ const sentenceEnd = sentenceStart + sentence.length;
1643
+ if (sentence.length > chunkSize) {
1644
+ if (currentChunkSentences.length > 0) {
1645
+ const chunkText2 = currentChunkSentences.join(" ");
1646
+ chunks.push({
1647
+ text: chunkText2,
1648
+ startOffset: currentChunkStart,
1649
+ endOffset: currentOffset
1650
+ });
1651
+ currentChunkSentences = [];
1652
+ }
1653
+ for (let j = 0; j < sentence.length; j += chunkSize - chunkOverlap) {
1654
+ const chunkEnd = Math.min(j + chunkSize, sentence.length);
1655
+ const chunk = sentence.slice(j, chunkEnd);
1656
+ if (chunk.length >= minChunkSize) {
1657
+ chunks.push({
1658
+ text: chunk,
1659
+ startOffset: sentenceStart + j,
1660
+ endOffset: sentenceStart + chunkEnd
1661
+ });
1662
+ }
1663
+ }
1664
+ currentChunkStart = sentenceEnd;
1665
+ currentOffset = sentenceEnd;
1666
+ continue;
1667
+ }
1668
+ const currentText = currentChunkSentences.join(" ");
1669
+ const potentialLength = currentText.length + (currentText ? 1 : 0) + sentence.length;
1670
+ if (potentialLength > chunkSize && currentChunkSentences.length > 0) {
1671
+ chunks.push({
1672
+ text: currentText,
1673
+ startOffset: currentChunkStart,
1674
+ endOffset: currentOffset
1675
+ });
1676
+ const overlapSentences = [];
1677
+ let overlapLength = 0;
1678
+ for (let j = currentChunkSentences.length - 1; j >= 0 && overlapLength < chunkOverlap; j--) {
1679
+ overlapSentences.unshift(currentChunkSentences[j]);
1680
+ overlapLength += currentChunkSentences[j].length + 1;
1681
+ }
1682
+ if (overlapSentences.length > 0) {
1683
+ currentChunkSentences = [...overlapSentences, sentence];
1684
+ const overlapText = overlapSentences[0];
1685
+ const overlapStart = text.lastIndexOf(overlapText, currentOffset);
1686
+ currentChunkStart = overlapStart === -1 ? sentenceStart : overlapStart;
1687
+ } else {
1688
+ currentChunkSentences = [sentence];
1689
+ currentChunkStart = sentenceStart;
1690
+ }
1691
+ } else {
1692
+ if (currentChunkSentences.length === 0) {
1693
+ currentChunkStart = sentenceStart;
1694
+ }
1695
+ currentChunkSentences.push(sentence);
1696
+ }
1697
+ currentOffset = sentenceEnd;
1698
+ }
1699
+ if (currentChunkSentences.length > 0) {
1700
+ const chunkText2 = currentChunkSentences.join(" ");
1701
+ if (chunkText2.length >= minChunkSize) {
1702
+ chunks.push({
1703
+ text: chunkText2,
1704
+ startOffset: currentChunkStart,
1705
+ endOffset: text.length
1706
+ });
1707
+ }
1708
+ }
1709
+ if (chunks.length === 0) {
1710
+ const trimmedText = text.trim();
1711
+ if (trimmedText.length > 0) {
1712
+ return [
1713
+ {
1714
+ text: trimmedText,
1715
+ startOffset: 0,
1716
+ endOffset: text.length
1717
+ }
1718
+ ];
1719
+ }
1720
+ }
1721
+ return chunks;
1722
+ }
1723
+ function shouldChunkMessage(content, chunkSize = DEFAULT_CHUNK_SIZE) {
1724
+ return content.length > chunkSize;
1725
+ }
1726
+
1727
+ // src/react/useEncryption.ts
1728
+ var encryptionKeyStore = /* @__PURE__ */ new Map();
1729
+ var cryptoKeyCache = /* @__PURE__ */ new Map();
1730
+ var clearAllEncryptionStateCallbacks = /* @__PURE__ */ new Set();
1731
+ function onClearAllEncryptionState(callback) {
1732
+ clearAllEncryptionStateCallbacks.add(callback);
1733
+ return () => {
1734
+ clearAllEncryptionStateCallbacks.delete(callback);
1735
+ };
1736
+ }
1737
+ function getStoredKey(address) {
1738
+ const keys = encryptionKeyStore.get(address);
1739
+ return keys?.current ?? null;
1740
+ }
1741
+ function getStoredKeyByVersion(address, version) {
1742
+ const keys = encryptionKeyStore.get(address);
1743
+ if (!keys) return null;
1744
+ return version === "v2" ? keys.legacy : keys.current;
1745
+ }
1746
+ function hexToBytes(hex) {
1747
+ const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
1748
+ const bytes = new Uint8Array(cleanHex.length / 2);
1749
+ for (let i = 0; i < cleanHex.length; i += 2) {
1750
+ bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
1751
+ }
1752
+ return bytes;
1753
+ }
1754
+ var SHARED_TEXT_ENCODER = new TextEncoder();
1755
+ var SHARED_TEXT_DECODER = new TextDecoder();
1756
+ async function getEncryptionKey(address, version = "v3") {
1757
+ const cacheKey = `${address}:${version}`;
1758
+ const cachedKey = cryptoKeyCache.get(cacheKey);
1759
+ if (cachedKey) {
1760
+ return cachedKey;
1761
+ }
1762
+ const keyHex = getStoredKeyByVersion(address, version);
1763
+ if (!keyHex) {
1764
+ throw new Error(
1765
+ "Encryption key not found. Please sign a message to generate your encryption key."
1766
+ );
1767
+ }
1768
+ const keyBytes = hexToBytes(keyHex);
1769
+ const cryptoKey = await crypto.subtle.importKey(
1770
+ "raw",
1771
+ keyBytes.buffer,
1772
+ { name: "AES-GCM" },
1773
+ false,
1774
+ ["encrypt", "decrypt"]
1775
+ );
1776
+ cryptoKeyCache.set(cacheKey, cryptoKey);
1777
+ return cryptoKey;
1778
+ }
1779
+ async function decryptData(encryptedHex, address, version = "v3") {
1780
+ const key = await getEncryptionKey(address, version);
1781
+ return decryptDataWithKey(encryptedHex, key);
1782
+ }
1783
+ function hasEncryptionKey(address) {
1784
+ return getStoredKey(address) !== null;
1785
+ }
1786
+ async function decryptDataWithKey(encryptedHex, key) {
1787
+ const combined = hexToBytes(encryptedHex);
1788
+ const iv = combined.subarray(0, 12);
1789
+ const encryptedData = combined.subarray(12);
1790
+ const decryptedData = await crypto.subtle.decrypt(
1791
+ {
1792
+ name: "AES-GCM",
1793
+ iv
1794
+ },
1795
+ key,
1796
+ encryptedData
1797
+ );
1798
+ return SHARED_TEXT_DECODER.decode(decryptedData);
1799
+ }
1800
+
1801
+ // src/lib/memoryEngine/vector.ts
1802
+ function cosineSimilarity(a, b) {
1803
+ if (a.length !== b.length) return 0;
1804
+ let dot = 0;
1805
+ let normA = 0;
1806
+ let normB = 0;
1807
+ for (let i = 0; i < a.length; i++) {
1808
+ dot += a[i] * b[i];
1809
+ normA += a[i] * a[i];
1810
+ normB += b[i] * b[i];
1811
+ }
1812
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
1813
+ return denom === 0 ? 0 : dot / denom;
1814
+ }
1815
+
1816
+ // src/lib/db/encryption-utils.ts
1817
+ function isEncrypted(value) {
1818
+ const prefix = value.startsWith("enc:v3:") ? "enc:v3:" : value.startsWith("enc:v2:") ? "enc:v2:" : null;
1819
+ if (!prefix) return false;
1820
+ const payload = value.slice(prefix.length);
1821
+ return payload.length >= 56 && /^[0-9a-f]+$/i.test(payload);
1822
+ }
1823
+ function detectEncryptionVersion(value) {
1824
+ if (value.startsWith("enc:v3:")) {
1825
+ return { version: "v3", encryptedData: value.slice("enc:v3:".length) };
1826
+ }
1827
+ if (value.startsWith("enc:v2:")) {
1828
+ return { version: "v2", encryptedData: value.slice("enc:v2:".length) };
1829
+ }
1830
+ return null;
1831
+ }
1832
+ async function decryptField(value, address) {
1833
+ if (!value) return value;
1834
+ const detected = detectEncryptionVersion(value);
1835
+ if (!detected) return value;
1836
+ if (detected.encryptedData.length < 56 || !/^[0-9a-f]+$/i.test(detected.encryptedData)) {
1837
+ return value;
1838
+ }
1839
+ try {
1840
+ return await decryptData(detected.encryptedData, address, detected.version);
1841
+ } catch (error) {
1842
+ getLogger().warn("Failed to decrypt field, returning as-is:", error);
1843
+ return value;
1844
+ }
1845
+ }
1846
+
1847
+ // src/lib/chat/useChat/strategies/types.ts
1848
+ function isChatCompletionResponse(r) {
1849
+ if (r.object === "response") return false;
1850
+ if (Array.isArray(r.output)) return false;
1851
+ return true;
1852
+ }
1853
+ function getToolCallEvents(r) {
1854
+ if (isChatCompletionResponse(r)) {
1855
+ return r.portal?.tool_call_events ?? r.tool_call_events;
1856
+ }
1857
+ return r.tool_call_events;
1858
+ }
1859
+ function getCostMicroUsd(r) {
1860
+ if (isChatCompletionResponse(r)) {
1861
+ return r.portal?.cost_micro_usd ?? r.usage?.cost_micro_usd;
1862
+ }
1863
+ return r.usage?.cost_micro_usd;
1864
+ }
1865
+ function getCreditsUsed(r) {
1866
+ if (isChatCompletionResponse(r)) {
1867
+ return r.portal?.credits_used ?? r.usage?.credits_used;
1868
+ }
1869
+ return r.usage?.credits_used;
1870
+ }
1871
+ function getImageModel(r) {
1872
+ if (isChatCompletionResponse(r)) {
1873
+ return r.portal?.image_model ?? r.image_model;
1874
+ }
1875
+ return r.image_model;
1876
+ }
1877
+
1878
+ // src/lib/memoryEngine/constants.ts
1879
+ var DEFAULT_API_EMBEDDING_MODEL = "qwen/qwen3-embedding-8b";
1880
+
1881
+ // src/lib/memoryEngine/embeddings.ts
1882
+ var EMBED_MAX_ATTEMPTS = 4;
1883
+ async function withEmbeddingRetry(call) {
1884
+ let last;
1885
+ let lastThrown;
1886
+ let threw = false;
1887
+ for (let attempt = 1; attempt <= EMBED_MAX_ATTEMPTS; attempt++) {
1888
+ try {
1889
+ threw = false;
1890
+ last = await call();
1891
+ if (!last.error) return last;
1892
+ const status = last.response?.status;
1893
+ const retryable = status === void 0 || status === 429 || status >= 500;
1894
+ if (!retryable) return last;
1895
+ } catch (err) {
1896
+ threw = true;
1897
+ lastThrown = err;
1898
+ }
1899
+ if (attempt < EMBED_MAX_ATTEMPTS) {
1900
+ const base = 250 * 2 ** (attempt - 1);
1901
+ await new Promise((r) => setTimeout(r, base + Math.random() * 0.4 * base));
1902
+ }
1903
+ }
1904
+ if (threw) throw lastThrown;
1905
+ return last;
1906
+ }
1907
+ async function generateEmbedding(text, options) {
1908
+ const { baseUrl = BASE_URL, getToken, apiKey, model, cache } = options;
1909
+ if (cache) {
1910
+ const cached = cache.get(text);
1911
+ if (cached) return cached;
1912
+ }
1913
+ let headers;
1914
+ if (apiKey) {
1915
+ headers = { "X-API-Key": apiKey };
1916
+ } else if (getToken) {
1917
+ const token = await getToken();
1918
+ if (!token) {
1919
+ throw new Error("No token available for embedding generation");
1920
+ }
1921
+ headers = { Authorization: `Bearer ${token}` };
1922
+ } else {
1923
+ throw new Error("Either apiKey or getToken must be provided");
1924
+ }
1925
+ const response = await withEmbeddingRetry(
1926
+ () => postApiV1Embeddings({
1927
+ baseUrl,
1928
+ body: {
1929
+ // Mask PII from the request body only — the cache above still keys on
1930
+ // the original `text`, so callers keep their original values.
1931
+ input: options.maskInput ? options.maskInput(text) : text,
1932
+ model: model ?? DEFAULT_API_EMBEDDING_MODEL
1933
+ },
1934
+ headers
1935
+ })
1936
+ );
1937
+ if (response.error) {
1938
+ throw new Error(
1939
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1940
+ );
1941
+ }
1942
+ if (!response.data?.data?.[0]?.embedding) {
1943
+ throw new Error("No embedding returned from API");
1944
+ }
1945
+ const embedding = response.data.data[0].embedding;
1946
+ if (options.onUsage && response.data.usage) {
1947
+ options.onUsage({
1948
+ promptTokens: response.data.usage.prompt_tokens ?? 0,
1949
+ totalTokens: response.data.usage.total_tokens ?? 0
1950
+ });
1951
+ }
1952
+ if (cache) {
1953
+ cache.set(text, embedding);
1954
+ }
1955
+ return embedding;
1956
+ }
1957
+ var DEFAULT_EMBEDDING_BATCH_SIZE = 100;
1958
+ var DEFAULT_EMBEDDING_BATCH_CONCURRENCY = 3;
1959
+ async function generateEmbeddingsBatch(texts, headers, baseUrl, model, onUsage, maskInput) {
1960
+ const response = await withEmbeddingRetry(
1961
+ () => postApiV1Embeddings({
1962
+ baseUrl,
1963
+ // Mask PII from the request body only; cache/order still key on originals.
1964
+ body: { input: maskInput ? texts.map(maskInput) : texts, model },
1965
+ headers
1966
+ })
1967
+ );
1968
+ if (response.error) {
1969
+ throw new Error(
1970
+ typeof response.error === "object" && response.error && "error" in response.error ? response.error.error : "API embedding failed"
1971
+ );
1972
+ }
1973
+ if (!response.data?.data) {
1974
+ throw new Error("No embeddings returned from API");
1975
+ }
1976
+ if (onUsage && response.data.usage) {
1977
+ onUsage({
1978
+ promptTokens: response.data.usage.prompt_tokens ?? 0,
1979
+ totalTokens: response.data.usage.total_tokens ?? 0
1980
+ });
1981
+ }
1982
+ return response.data.data.map((item) => item.embedding ?? []);
1983
+ }
1984
+ async function generateEmbeddings(texts, options) {
1985
+ if (texts.length === 0) return [];
1986
+ const { baseUrl = BASE_URL, getToken, apiKey, model, batchSize, cache } = options;
1987
+ const chunkSize = batchSize ?? DEFAULT_EMBEDDING_BATCH_SIZE;
1988
+ const results = new Array(texts.length).fill(null);
1989
+ const uncachedIndices = [];
1990
+ const uncachedTexts = [];
1991
+ for (let i = 0; i < texts.length; i++) {
1992
+ if (cache) {
1993
+ const cached = cache.get(texts[i]);
1994
+ if (cached) {
1995
+ results[i] = cached;
1996
+ continue;
1997
+ }
1998
+ }
1999
+ uncachedIndices.push(i);
2000
+ uncachedTexts.push(texts[i]);
2001
+ }
2002
+ if (uncachedTexts.length === 0) {
2003
+ return results;
2004
+ }
2005
+ let headers;
2006
+ if (apiKey) {
2007
+ headers = { "X-API-Key": apiKey };
2008
+ } else if (getToken) {
2009
+ const token = await getToken();
2010
+ if (!token) {
2011
+ throw new Error("No token available for embedding generation");
2012
+ }
2013
+ headers = { Authorization: `Bearer ${token}` };
2014
+ } else {
2015
+ throw new Error("Either apiKey or getToken must be provided");
2016
+ }
2017
+ const embeddingModel = model ?? DEFAULT_API_EMBEDDING_MODEL;
2018
+ let newEmbeddings;
2019
+ if (uncachedTexts.length <= chunkSize) {
2020
+ newEmbeddings = await generateEmbeddingsBatch(
2021
+ uncachedTexts,
2022
+ headers,
2023
+ baseUrl,
2024
+ embeddingModel,
2025
+ options.onUsage,
2026
+ options.maskInput
2027
+ );
2028
+ } else {
2029
+ const chunks = [];
2030
+ for (let i = 0; i < uncachedTexts.length; i += chunkSize) {
2031
+ chunks.push(uncachedTexts.slice(i, i + chunkSize));
2032
+ }
2033
+ const allEmbeddings = new Array(chunks.length);
2034
+ let nextIndex = 0;
2035
+ const worker = async () => {
2036
+ while (nextIndex < chunks.length) {
2037
+ const idx = nextIndex++;
2038
+ allEmbeddings[idx] = await generateEmbeddingsBatch(
2039
+ chunks[idx],
2040
+ headers,
2041
+ baseUrl,
2042
+ embeddingModel,
2043
+ options.onUsage,
2044
+ options.maskInput
2045
+ );
2046
+ }
2047
+ };
2048
+ const workers = Array.from(
2049
+ { length: Math.min(DEFAULT_EMBEDDING_BATCH_CONCURRENCY, chunks.length) },
2050
+ () => worker()
2051
+ );
2052
+ await Promise.all(workers);
2053
+ newEmbeddings = allEmbeddings.flat();
2054
+ }
2055
+ for (let i = 0; i < uncachedIndices.length; i++) {
2056
+ results[uncachedIndices[i]] = newEmbeddings[i];
2057
+ if (cache) {
2058
+ cache.set(uncachedTexts[i], newEmbeddings[i]);
2059
+ }
2060
+ }
2061
+ return results;
2062
+ }
2063
+
2064
+ // src/lib/tools/serverTools.ts
2065
+ var DEFAULT_CACHE_EXPIRATION_MS = 24 * 60 * 60 * 1e3;
2066
+ var SERVER_TOOLS_CACHE_KEY = "sdk_server_tools_cache";
2067
+ var CACHE_VERSION = "1.3";
2068
+ var MIN_CONTENT_LENGTH_FOR_TOOLS = 5;
2069
+ function isNewToolFormat(tool) {
2070
+ return "schema" in tool && tool.schema !== void 0;
2071
+ }
2072
+ function isNewResponseFormat(response) {
2073
+ return "checksum" in response && "tools" in response && typeof response.checksum === "string";
2074
+ }
2075
+ function convertServerToolsResponse(response) {
2076
+ let toolsMap;
2077
+ let checksum;
2078
+ if (isNewResponseFormat(response)) {
2079
+ toolsMap = response.tools;
2080
+ checksum = response.checksum;
2081
+ } else {
2082
+ toolsMap = response;
2083
+ }
2084
+ const tools = Object.values(toolsMap).map((tool) => {
2085
+ if (isNewToolFormat(tool)) {
2086
+ return {
2087
+ type: "function",
2088
+ name: tool.schema.name,
2089
+ description: tool.schema.description,
2090
+ parameters: tool.schema.parameters,
2091
+ ...tool.embedding && { embedding: tool.embedding }
2092
+ };
2093
+ }
2094
+ return {
2095
+ type: "function",
2096
+ name: tool.name,
2097
+ description: tool.description,
2098
+ parameters: tool.parameters
2099
+ };
2100
+ });
2101
+ return { tools, checksum };
2102
+ }
2103
+ function toCompletionsFormat(tool) {
2104
+ return {
2105
+ type: "function",
2106
+ function: {
2107
+ name: tool.name,
2108
+ description: tool.description,
2109
+ parameters: tool.parameters
2110
+ }
2111
+ };
2112
+ }
2113
+ function toResponsesFormat(tool) {
2114
+ return {
2115
+ type: "function",
2116
+ name: tool.name,
2117
+ description: tool.description,
2118
+ parameters: tool.parameters
2119
+ };
2120
+ }
2121
+ function getCachedServerTools() {
2122
+ if (typeof localStorage === "undefined") return null;
2123
+ try {
2124
+ const cached = localStorage.getItem(SERVER_TOOLS_CACHE_KEY);
2125
+ if (!cached) return null;
2126
+ const parsed = JSON.parse(cached);
2127
+ if (parsed.version !== CACHE_VERSION) {
2128
+ clearServerToolsCache();
2129
+ return null;
2130
+ }
2131
+ return parsed;
2132
+ } catch {
2133
+ return null;
2134
+ }
2135
+ }
2136
+ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
2137
+ if (!cache) return true;
2138
+ return Date.now() - cache.timestamp > expirationMs;
2139
+ }
2140
+ function cacheServerTools(tools, checksum) {
2141
+ if (typeof localStorage === "undefined") return;
2142
+ const cacheData = {
2143
+ tools,
2144
+ timestamp: Date.now(),
2145
+ version: CACHE_VERSION,
2146
+ ...checksum && { checksum }
2147
+ };
2148
+ try {
2149
+ localStorage.setItem(SERVER_TOOLS_CACHE_KEY, JSON.stringify(cacheData));
2150
+ } catch (error) {
2151
+ getLogger().warn("[serverTools] Failed to cache tools:", error);
2152
+ }
2153
+ }
2154
+ function clearServerToolsCache() {
2155
+ if (typeof localStorage === "undefined") return;
2156
+ localStorage.removeItem(SERVER_TOOLS_CACHE_KEY);
2157
+ }
2158
+ async function fetchServerToolsFromApi(baseUrl, token) {
2159
+ const response = await fetch(`${baseUrl}/api/v1/tools`, {
2160
+ method: "GET",
2161
+ headers: {
2162
+ Authorization: `Bearer ${token}`,
2163
+ "Content-Type": "application/json"
2164
+ }
2165
+ });
2166
+ if (!response.ok) {
2167
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
2168
+ }
2169
+ const data = await response.json();
2170
+ return convertServerToolsResponse(data);
2171
+ }
2172
+ async function getServerTools(options) {
2173
+ const {
2174
+ baseUrl,
2175
+ cacheExpirationMs = DEFAULT_CACHE_EXPIRATION_MS,
2176
+ forceRefresh = false,
2177
+ getToken,
2178
+ apiKey
2179
+ } = options;
2180
+ const cached = getCachedServerTools();
2181
+ const cacheValid = !isCacheExpired(cached, cacheExpirationMs);
2182
+ if (cached && cacheValid && !forceRefresh) {
2183
+ return cached.tools;
2184
+ }
2185
+ try {
2186
+ const { BASE_URL: BASE_URL2 } = await import("./clientConfig-WITO4T6L.mjs");
2187
+ const effectiveBaseUrl = baseUrl ?? BASE_URL2;
2188
+ if (apiKey) {
2189
+ const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
2190
+ method: "GET",
2191
+ headers: {
2192
+ "X-API-Key": apiKey,
2193
+ "Content-Type": "application/json"
2194
+ }
2195
+ });
2196
+ if (!response.ok) {
2197
+ throw new Error(`Failed to fetch server tools: ${response.status}`);
2198
+ }
2199
+ const data = await response.json();
2200
+ const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
2201
+ cacheServerTools(tools2, checksum2);
2202
+ return tools2;
2203
+ }
2204
+ if (!getToken) {
2205
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
2206
+ return cached?.tools ?? [];
2207
+ }
2208
+ const token = await getToken();
2209
+ if (!token) {
2210
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
2211
+ return cached?.tools ?? [];
2212
+ }
2213
+ const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
2214
+ cacheServerTools(tools, checksum);
2215
+ return tools;
2216
+ } catch (error) {
2217
+ getLogger().error("[serverTools] Failed to fetch server tools:", error);
2218
+ if (cached?.tools) {
2219
+ getLogger().warn("[serverTools] Using stale cached tools due to fetch error");
2220
+ return cached.tools;
2221
+ }
2222
+ return [];
2223
+ }
2224
+ }
2225
+ var DEFAULT_TOOL_MATCH_OPTIONS = {
2226
+ limit: 5,
2227
+ minSimilarity: 0.3,
2228
+ filterAmbiguous: false,
2229
+ ambiguityThreshold: 0.55,
2230
+ minLead: 0.04,
2231
+ relevanceRatio: 0
2232
+ };
2233
+ function findMatchingTools(promptEmbeddings, tools, options) {
2234
+ const { limit, minSimilarity, filterAmbiguous, ambiguityThreshold, minLead, relevanceRatio } = {
2235
+ ...DEFAULT_TOOL_MATCH_OPTIONS,
2236
+ ...options
2237
+ };
2238
+ if (!promptEmbeddings || promptEmbeddings.length === 0) {
2239
+ return [];
2240
+ }
2241
+ if (!tools || tools.length === 0) {
2242
+ return [];
2243
+ }
2244
+ const embeddings = Array.isArray(promptEmbeddings[0]) ? promptEmbeddings : [promptEmbeddings];
2245
+ const results = [];
2246
+ for (const tool of tools) {
2247
+ if (!tool.embedding || tool.embedding.length === 0) {
2248
+ continue;
2249
+ }
2250
+ try {
2251
+ let maxSimilarity = -Infinity;
2252
+ for (const embedding of embeddings) {
2253
+ const similarity = cosineSimilarity(embedding, tool.embedding);
2254
+ if (similarity > maxSimilarity) {
2255
+ maxSimilarity = similarity;
2256
+ }
2257
+ }
2258
+ if (maxSimilarity >= minSimilarity) {
2259
+ results.push({ tool, similarity: maxSimilarity });
2260
+ }
2261
+ } catch {
2262
+ continue;
2263
+ }
2264
+ }
2265
+ let sorted = results.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
2266
+ if (filterAmbiguous && sorted.length > 1) {
2267
+ const topScore = sorted[0].similarity;
2268
+ const runnerUpScore = sorted[1].similarity;
2269
+ if (topScore < ambiguityThreshold && topScore - runnerUpScore < minLead) {
2270
+ return [];
2271
+ }
2272
+ }
2273
+ if (relevanceRatio > 0 && sorted.length > 1) {
2274
+ const cutoff = sorted[0].similarity * relevanceRatio;
2275
+ sorted = sorted.filter((r) => r.similarity >= cutoff);
2276
+ }
2277
+ return sorted;
2278
+ }
2279
+ function scoreTools(promptEmbeddings, tools) {
2280
+ const scores = /* @__PURE__ */ new Map();
2281
+ if (!promptEmbeddings || promptEmbeddings.length === 0) return scores;
2282
+ if (!tools || tools.length === 0) return scores;
2283
+ const embeddings = Array.isArray(promptEmbeddings[0]) ? promptEmbeddings : [promptEmbeddings];
2284
+ for (const tool of tools) {
2285
+ if (!tool.embedding || tool.embedding.length === 0) continue;
2286
+ let maxSimilarity = -Infinity;
2287
+ try {
2288
+ for (const embedding of embeddings) {
2289
+ const similarity = cosineSimilarity(embedding, tool.embedding);
2290
+ if (similarity > maxSimilarity) maxSimilarity = similarity;
2291
+ }
2292
+ } catch {
2293
+ continue;
2294
+ }
2295
+ if (maxSimilarity > -Infinity) scores.set(tool.name, maxSimilarity);
2296
+ }
2297
+ return scores;
2298
+ }
2299
+ var BUILT_IN_TOOL_SETS = [
2300
+ {
2301
+ name: "app-generation",
2302
+ // Appended to the base prompt (not replacing it) whenever this set
2303
+ // activates, so the App Builder guidance — including the window.app.complete
2304
+ // runtime-AI contract — rides in with the app-gen tools via the same
2305
+ // semantic selection that includes them. Collected by toolSetSystemPrompts.
2306
+ systemPrompt: APP_BUILDER_PROMPT,
2307
+ // Must stay in sync with APP_FILE_TOOL_NAMES in src/tools/appGeneration.ts.
2308
+ // If a new app-gen tool ships there but isn't added here, semantic
2309
+ // selection will exclude it on every request — the model literally
2310
+ // doesn't see it. The quality tools (audit_design / critique_design /
2311
+ // verify_app) are non-obvious to a user prompt ("build me a kanban")
2312
+ // and rely entirely on set expansion to reach the model.
2313
+ members: [
2314
+ "create_file",
2315
+ "patch_file",
2316
+ "delete_file",
2317
+ "read_file",
2318
+ "list_files",
2319
+ "audit_design",
2320
+ "critique_design",
2321
+ "verify_app"
2322
+ ],
2323
+ // Anchors stay limited to the primary entry-point tools. Users phrase
2324
+ // app intent as "build / make / fix" → semantic match on create_file
2325
+ // or patch_file → full set pulled in. The quality tools fire later in
2326
+ // the workflow and don't anchor on their own; including them as
2327
+ // anchors would risk pulling the set in on unrelated "audit my code"
2328
+ // prompts that have nothing to do with app generation.
2329
+ anchors: ["create_file", "patch_file"],
2330
+ // 0.55: above the global filter floor (0.53) so a barely-relevant match
2331
+ // can't pull in the whole toolkit, but no higher — and we tried higher.
2332
+ // create_file scores chitchat ("what's up" ~0.56, "...about programming"
2333
+ // ~0.57) in the SAME band as legitimate app-EDIT prompts: "Edit the app to
2334
+ // change the background…" measured create_file 0.56 on one e2e run. Raising
2335
+ // the floor to 0.575 to exclude the chitchat therefore also stripped the
2336
+ // file tools from real edit requests — leaving the model unable to touch the
2337
+ // app at all. The bands genuinely overlap; there is no clean cut. So we keep
2338
+ // 0.55 (max recall) and rely on two safety nets instead: APP_BUILDER_PROMPT
2339
+ // is conditional (it no-ops unless the user is actually asking for an app),
2340
+ // and very short greetings ("hey") are filtered out earlier by the
2341
+ // MIN_CONTENT_LENGTH_FOR_TOOLS length gate before embeddings even run.
2342
+ anchorMinSimilarity: 0.55
2343
+ },
2344
+ {
2345
+ name: "slides",
2346
+ members: ["plan_deck", "add_slide", "read_slides", "patch_slides"],
2347
+ anchors: ["plan_deck", "patch_slides"],
2348
+ // Match the client-tool floor (0.53). Short colloquial prompts like
2349
+ // "make me a powerpoint about X" score plan_deck around 0.535 — above
2350
+ // the global floor but inside any anchor gap. plan_deck and patch_slides
2351
+ // are specific enough names that 0.53 won't false-positive in practice.
2352
+ anchorMinSimilarity: 0.53
2353
+ },
2354
+ {
2355
+ name: "documents",
2356
+ // Conditional rider (no-ops unless the user actually asks for a document),
2357
+ // attached so the Document Builder guidance rides in with the document
2358
+ // tools via the same semantic selection that includes them.
2359
+ systemPrompt: DOCUMENT_BUILDER_PROMPT,
2360
+ members: ["create_document", "read_document", "patch_document"],
2361
+ // Entry-point tools anchor; read_document rides in via set expansion.
2362
+ anchors: ["create_document", "patch_document"],
2363
+ // 0.53: match the client-tool floor. "draft me a contract", "write a cover
2364
+ // letter", "make a memo" should pull the set in. Like app-gen's create_file,
2365
+ // document intent ("write me X") overlaps generic chitchat in this band, so
2366
+ // the same two safety nets apply: DOCUMENT_BUILDER_PROMPT is conditional and
2367
+ // the MIN_CONTENT_LENGTH_FOR_TOOLS gate drops bare greetings before
2368
+ // embeddings run. Tune empirically against the tool-selection parity suite.
2369
+ anchorMinSimilarity: 0.53
2370
+ },
2371
+ {
2372
+ name: "github",
2373
+ members: ["github_get_authenticated_user", "github_api"],
2374
+ anchors: ["github_api"],
2375
+ anchorMinSimilarity: 0.55
2376
+ },
2377
+ // Connector sets (#587). Connector chat tools belong to no set, so per-message
2378
+ // semantic filtering silently prunes them on vague prompts ("check my email").
2379
+ // Grouping each connector's tools behind a search/action anchor keeps the
2380
+ // whole connector reachable once any one of its tools matches. Mirrors github:
2381
+ // no systemPrompt rider — per-set prompt guidance is a follow-up.
2382
+ {
2383
+ name: "gmail",
2384
+ members: [
2385
+ "gmail_search_messages",
2386
+ "gmail_get_message",
2387
+ "gmail_create_draft",
2388
+ "gmail_send_message"
2389
+ ],
2390
+ anchors: ["gmail_search_messages", "gmail_send_message"],
2391
+ anchorMinSimilarity: 0.53
2392
+ },
2393
+ {
2394
+ name: "google-calendar",
2395
+ members: [
2396
+ "google_calendar_list_events",
2397
+ "google_calendar_create_event",
2398
+ "google_calendar_update_event"
2399
+ ],
2400
+ anchors: ["google_calendar_list_events", "google_calendar_create_event"],
2401
+ anchorMinSimilarity: 0.53
2402
+ },
2403
+ {
2404
+ name: "google-drive",
2405
+ members: [
2406
+ "google_drive_search",
2407
+ "google_drive_list_recent",
2408
+ "google_drive_get_content",
2409
+ "google_drive_create_file",
2410
+ "google_drive_update_file"
2411
+ ],
2412
+ anchors: ["google_drive_search", "google_drive_get_content", "google_drive_create_file"],
2413
+ anchorMinSimilarity: 0.53
2414
+ },
2415
+ {
2416
+ name: "notion",
2417
+ members: ["notion-search", "notion-fetch", "notion-create-pages", "notion-update-page"],
2418
+ anchors: ["notion-search", "notion-create-pages"],
2419
+ anchorMinSimilarity: 0.53
2420
+ },
2421
+ {
2422
+ name: "x",
2423
+ members: ["x_get_me", "x_get_my_posts"],
2424
+ anchors: ["x_get_me", "x_get_my_posts"],
2425
+ anchorMinSimilarity: 0.53
2426
+ },
2427
+ {
2428
+ name: "slack",
2429
+ members: [
2430
+ "slack_get_me",
2431
+ "slack_list_channels",
2432
+ "slack_search_messages",
2433
+ "slack_list_users",
2434
+ "slack_get_channel_history",
2435
+ "slack_get_thread_replies",
2436
+ "slack_post_message"
2437
+ ],
2438
+ // search is the primary entry point; list_channels also anchors so "what
2439
+ // channels am I in" reaches the set without going through search. post_message
2440
+ // anchors too so post-only prompts surface the write tool past the cutoff.
2441
+ anchors: ["slack_search_messages", "slack_list_channels", "slack_post_message"],
2442
+ anchorMinSimilarity: 0.53
2443
+ },
2444
+ {
2445
+ name: "dropbox",
2446
+ members: ["dropbox_list_folders", "dropbox_get_file_content", "dropbox_search"],
2447
+ anchors: ["dropbox_list_folders", "dropbox_search"],
2448
+ anchorMinSimilarity: 0.53
2449
+ }
2450
+ ];
2451
+ function applyToolSets(matchedNames, availableNames, scores, toolSets = BUILT_IN_TOOL_SETS, independentThreshold = 0.65) {
2452
+ const activatedSets = [];
2453
+ for (const ts of toolSets) {
2454
+ const minSim = ts.anchorMinSimilarity ?? 0.6;
2455
+ const triggered = ts.anchors.some(
2456
+ (anchor) => matchedNames.has(anchor) && (scores.get(anchor) ?? 0) >= minSim
2457
+ );
2458
+ if (triggered) activatedSets.push(ts);
2459
+ }
2460
+ if (activatedSets.length === 0) return matchedNames;
2461
+ const setMembers = /* @__PURE__ */ new Set();
2462
+ for (const ts of activatedSets) {
2463
+ for (const member of ts.members) setMembers.add(member);
2464
+ }
2465
+ const result = /* @__PURE__ */ new Set();
2466
+ for (const member of setMembers) {
2467
+ if (availableNames.has(member)) {
2468
+ result.add(member);
2469
+ }
2470
+ }
2471
+ for (const name of matchedNames) {
2472
+ if (setMembers.has(name)) continue;
2473
+ const score = scores.get(name) ?? 0;
2474
+ if (score >= independentThreshold) {
2475
+ result.add(name);
2476
+ }
2477
+ }
2478
+ return result;
2479
+ }
2480
+ function expandToolSetsAdditive(matchedNames, availableNames, scores, toolSets, activeSetNames) {
2481
+ const result = new Set(matchedNames);
2482
+ for (const ts of toolSets) {
2483
+ let triggered = activeSetNames?.has(ts.name) ?? false;
2484
+ if (!triggered) {
2485
+ const minSim = ts.anchorMinSimilarity ?? 0.6;
2486
+ triggered = ts.anchors.some((a) => (scores.get(a) ?? 0) >= minSim);
2487
+ }
2488
+ if (!triggered) continue;
2489
+ for (const member of ts.members) {
2490
+ if (availableNames.has(member)) {
2491
+ result.add(member);
2492
+ }
2493
+ }
2494
+ }
2495
+ return result;
2496
+ }
2497
+ function activatedToolSetNames(scores, toolSets = BUILT_IN_TOOL_SETS, activeSetNames) {
2498
+ const activated = /* @__PURE__ */ new Set();
2499
+ for (const ts of toolSets) {
2500
+ if (activeSetNames?.has(ts.name)) {
2501
+ activated.add(ts.name);
2502
+ continue;
2503
+ }
2504
+ const minSim = ts.anchorMinSimilarity ?? 0.6;
2505
+ if (ts.anchors.some((a) => (scores.get(a) ?? 0) >= minSim)) {
2506
+ activated.add(ts.name);
2507
+ }
2508
+ }
2509
+ return activated;
2510
+ }
2511
+ function toolSetSystemPrompts(selectedToolNames, toolSets = BUILT_IN_TOOL_SETS, activatedSetNames) {
2512
+ const selected = selectedToolNames instanceof Set ? selectedToolNames : new Set(selectedToolNames);
2513
+ const prompts = [];
2514
+ const seen = /* @__PURE__ */ new Set();
2515
+ for (const ts of toolSets) {
2516
+ const prompt = ts.systemPrompt;
2517
+ if (!prompt || seen.has(prompt)) continue;
2518
+ const active = activatedSetNames ? activatedSetNames.has(ts.name) : ts.anchors.some((anchor) => selected.has(anchor));
2519
+ if (active) {
2520
+ prompts.push(prompt);
2521
+ seen.add(prompt);
2522
+ }
2523
+ }
2524
+ return prompts;
2525
+ }
2526
+ function createServerToolsFilter(options = {}) {
2527
+ const exclude = new Set(options.excludeTools ?? []);
2528
+ const sets = options.toolSets ?? [];
2529
+ const matchOpts = options.matchOptions;
2530
+ return (embeddings, tools) => {
2531
+ const matches = findMatchingTools(embeddings, tools, matchOpts);
2532
+ if (matches.length === 0) return [];
2533
+ const matchedNames = new Set(matches.map((m) => m.tool.name));
2534
+ let finalNames;
2535
+ if (sets.length > 0) {
2536
+ const scores = scoreTools(embeddings, tools);
2537
+ const selectedScores = new Map(
2538
+ [...scores].filter(([name]) => matchedNames.has(name) && !exclude.has(name))
2539
+ );
2540
+ const availableNames = new Set(tools.map((t) => t.name));
2541
+ finalNames = expandToolSetsAdditive(matchedNames, availableNames, selectedScores, sets);
2542
+ } else {
2543
+ finalNames = matchedNames;
2544
+ }
2545
+ for (const name of exclude) finalNames.delete(name);
2546
+ return [...finalNames];
2547
+ };
2548
+ }
2549
+ var DEFAULT_EXCLUDED_SERVER_TOOLS = [
2550
+ "AnumaVisionMCP-anuma_analyze_image",
2551
+ "OpenMeteoMCP-weather_forecast",
2552
+ // Same native-capability argument as the vision tool: modern models reason
2553
+ // step-by-step natively (and reasoning-mode models do it structurally), so
2554
+ // a server-side sequential-thinking tool is a redundant hop. Its broad
2555
+ // description also embeds near virtually every prompt — observed live
2556
+ // riding into news-search, scheduling, and chitchat requests.
2557
+ "AnumaSequentialThinkingMCP-sequentialthinking"
2558
+ ];
2559
+ var DEFAULT_SERVER_TOOLS_MATCH_OPTIONS = {
2560
+ limit: 5,
2561
+ minSimilarity: 0.5
2562
+ };
2563
+ var SERVER_TOOL_DEPENDENCY_SETS = [
2564
+ {
2565
+ // search finds links; reading them is always the next step.
2566
+ name: "jina-research",
2567
+ members: [
2568
+ "AnumaJinaMCP-search_web",
2569
+ "AnumaJinaMCP-read_url",
2570
+ "AnumaJinaMCP-parallel_read_url",
2571
+ "AnumaJinaMCP-parallel_search_web"
2572
+ ],
2573
+ anchors: ["AnumaJinaMCP-search_web"],
2574
+ // Activation floor = the selection floor (0.5), not the 0.6 ToolSet
2575
+ // default. A dependency edge has different semantics from a persona-style
2576
+ // tool set: if the entry tool is plausibly offered at all, the chain must
2577
+ // ride along — "Search the web for recent news…" scores search_web in the
2578
+ // 0.5–0.6 band, and shipping search without read would dead-end the model.
2579
+ anchorMinSimilarity: 0.5
2580
+ },
2581
+ {
2582
+ // Every OpenMeteo data tool requires latitude/longitude (verified in the
2583
+ // catalog schemas), but users speak in place names — geocoding is the
2584
+ // mandatory first hop. Members deliberately contain ONLY the dependency:
2585
+ // the anchor that fired is already in the semantic matches, and pulling
2586
+ // sibling data tools in would re-create vendor-suite over-inclusion.
2587
+ // Excluded tools (e.g. weather_forecast under the default filter) can't
2588
+ // anchor this set — createServerToolsFilter drops them before expansion —
2589
+ // but the non-weather data tools still deliver geocoding when they match.
2590
+ name: "openmeteo-geocode",
2591
+ members: ["OpenMeteoMCP-geocoding"],
2592
+ anchors: [
2593
+ "OpenMeteoMCP-weather_forecast",
2594
+ "OpenMeteoMCP-air_quality",
2595
+ "OpenMeteoMCP-weather_archive",
2596
+ "OpenMeteoMCP-marine_weather",
2597
+ "OpenMeteoMCP-flood_forecast",
2598
+ "OpenMeteoMCP-climate_projection",
2599
+ "OpenMeteoMCP-elevation"
2600
+ ],
2601
+ anchorMinSimilarity: 0.5
2602
+ }
2603
+ ];
2604
+ var defaultServerToolsFilter = createServerToolsFilter({
2605
+ excludeTools: DEFAULT_EXCLUDED_SERVER_TOOLS,
2606
+ matchOptions: DEFAULT_SERVER_TOOLS_MATCH_OPTIONS,
2607
+ toolSets: SERVER_TOOL_DEPENDENCY_SETS
2608
+ });
2609
+ async function selectServerSideTools(options) {
2610
+ const {
2611
+ prompt,
2612
+ getToken,
2613
+ apiKey,
2614
+ baseUrl,
2615
+ cacheExpirationMs,
2616
+ forceRefresh,
2617
+ embeddingModel,
2618
+ limit,
2619
+ minSimilarity,
2620
+ apiType = "responses"
2621
+ } = options;
2622
+ if (!getToken && !apiKey) {
2623
+ throw new Error("Either getToken or apiKey must be provided");
2624
+ }
2625
+ if (!prompt || prompt.trim().length < MIN_CONTENT_LENGTH_FOR_TOOLS) {
2626
+ return [];
2627
+ }
2628
+ const tools = await getServerTools({
2629
+ getToken,
2630
+ apiKey,
2631
+ baseUrl,
2632
+ cacheExpirationMs,
2633
+ forceRefresh
2634
+ });
2635
+ if (tools.length === 0) {
2636
+ return [];
2637
+ }
2638
+ const embeddingOptions = {
2639
+ getToken,
2640
+ apiKey,
2641
+ baseUrl,
2642
+ model: embeddingModel
2643
+ };
2644
+ let promptEmbeddings;
2645
+ if (shouldChunkMessage(prompt, DEFAULT_CHUNK_SIZE)) {
2646
+ const chunks = chunkText(prompt);
2647
+ promptEmbeddings = await generateEmbeddings(
2648
+ chunks.map((c) => c.text),
2649
+ embeddingOptions
2650
+ );
2651
+ } else {
2652
+ promptEmbeddings = await generateEmbedding(prompt, embeddingOptions);
2653
+ }
2654
+ const matchOptions = { filterAmbiguous: true, relevanceRatio: 0.85 };
2655
+ if (limit !== void 0) matchOptions.limit = limit;
2656
+ if (minSimilarity !== void 0) matchOptions.minSimilarity = minSimilarity;
2657
+ const matches = findMatchingTools(promptEmbeddings, tools, matchOptions);
2658
+ if (matches.length === 0) {
2659
+ return [];
2660
+ }
2661
+ const matchedTools = matches.map((m) => m.tool);
2662
+ if (apiType === "completions") {
2663
+ return matchedTools.map((t) => toCompletionsFormat(t));
2664
+ }
2665
+ return matchedTools.map(toResponsesFormat);
2666
+ }
2667
+
2668
+ // src/lib/tools/toolCatalog.ts
2669
+ var TOOL_CATALOG = {
2670
+ // Gmail (src/tools/gmail.ts)
2671
+ gmail_search_messages: { label: "Search emails", provider: "gmail", connector: "Gmail" },
2672
+ gmail_get_message: { label: "Read an email", provider: "gmail", connector: "Gmail" },
2673
+ gmail_create_draft: { label: "Draft a reply", provider: "gmail", connector: "Gmail" },
2674
+ gmail_send_message: { label: "Send an email", provider: "gmail", connector: "Gmail" },
2675
+ // Google Calendar (src/tools/googleCalendar.ts)
2676
+ google_calendar_list_events: {
2677
+ label: "Search calendar events",
2678
+ provider: "gcalendar",
2679
+ connector: "Calendar"
2680
+ },
2681
+ google_calendar_create_event: {
2682
+ label: "Create calendar event",
2683
+ provider: "gcalendar",
2684
+ connector: "Calendar"
2685
+ },
2686
+ google_calendar_update_event: {
2687
+ label: "Update calendar event",
2688
+ provider: "gcalendar",
2689
+ connector: "Calendar"
2690
+ },
2691
+ // Google Drive (src/tools/googleDrive.ts)
2692
+ google_drive_search: { label: "Search files", provider: "gdrive", connector: "Drive" },
2693
+ google_drive_list_recent: { label: "List recent files", provider: "gdrive", connector: "Drive" },
2694
+ google_drive_get_content: { label: "Read file content", provider: "gdrive", connector: "Drive" },
2695
+ google_drive_create_file: {
2696
+ label: "Create a file in Drive",
2697
+ provider: "gdrive",
2698
+ connector: "Drive"
2699
+ },
2700
+ google_drive_update_file: {
2701
+ label: "Update a Drive file",
2702
+ provider: "gdrive",
2703
+ connector: "Drive"
2704
+ },
2705
+ // Notion (src/tools/notion.ts)
2706
+ "notion-search": { label: "Search", provider: "notion", connector: "Notion" },
2707
+ "notion-fetch": { label: "Read page", provider: "notion", connector: "Notion" },
2708
+ "notion-create-pages": { label: "Create page", provider: "notion", connector: "Notion" },
2709
+ "notion-update-page": { label: "Update page", provider: "notion", connector: "Notion" },
2710
+ "notion-move-pages": { label: "Move pages", provider: "notion", connector: "Notion" },
2711
+ "notion-duplicate-page": { label: "Duplicate page", provider: "notion", connector: "Notion" },
2712
+ "notion-create-database": { label: "Create database", provider: "notion", connector: "Notion" },
2713
+ "notion-update-data-source": {
2714
+ label: "Update data source",
2715
+ provider: "notion",
2716
+ connector: "Notion"
2717
+ },
2718
+ "notion-create-comment": { label: "Add a comment", provider: "notion", connector: "Notion" },
2719
+ "notion-get-comments": { label: "Read comments", provider: "notion", connector: "Notion" },
2720
+ "notion-get-users": {
2721
+ label: "List workspace members",
2722
+ provider: "notion",
2723
+ connector: "Notion"
2724
+ },
2725
+ "notion-get-teams": { label: "List teamspaces", provider: "notion", connector: "Notion" },
2726
+ // GitHub (src/tools/github.ts)
2727
+ github_api: { label: "Use GitHub", provider: "github", connector: "GitHub" },
2728
+ github_get_authenticated_user: {
2729
+ label: "Read GitHub profile",
2730
+ provider: "github",
2731
+ connector: "GitHub"
2732
+ },
2733
+ // X / Twitter (src/tools/x.ts)
2734
+ x_get_me: { label: "Get my X profile", provider: "x", connector: "X" },
2735
+ x_get_my_posts: { label: "Read my recent posts", provider: "x", connector: "X" },
2736
+ // Dropbox (src/tools/dropbox.ts)
2737
+ dropbox_list_folders: { label: "List files", provider: "dropbox", connector: "Dropbox" },
2738
+ dropbox_get_file_content: {
2739
+ label: "Read file content",
2740
+ provider: "dropbox",
2741
+ connector: "Dropbox"
2742
+ },
2743
+ dropbox_search: { label: "Search files", provider: "dropbox", connector: "Dropbox" },
2744
+ // Slack (src/tools/slack.ts)
2745
+ slack_get_me: { label: "Get my Slack profile", provider: "slack", connector: "Slack" },
2746
+ slack_list_channels: { label: "List channels", provider: "slack", connector: "Slack" },
2747
+ slack_search_messages: { label: "Search messages", provider: "slack", connector: "Slack" },
2748
+ slack_list_users: { label: "List members", provider: "slack", connector: "Slack" },
2749
+ slack_get_channel_history: {
2750
+ label: "Read channel history",
2751
+ provider: "slack",
2752
+ connector: "Slack"
2753
+ },
2754
+ slack_get_thread_replies: {
2755
+ label: "Read thread replies",
2756
+ provider: "slack",
2757
+ connector: "Slack"
2758
+ },
2759
+ slack_post_message: { label: "Post a message", provider: "slack", connector: "Slack" }
2760
+ };
2761
+ function buildDeniedToolsRider(deniedToolNames) {
2762
+ const byConnector = /* @__PURE__ */ new Map();
2763
+ for (const name of deniedToolNames) {
2764
+ const entry = TOOL_CATALOG[name];
2765
+ if (!entry) continue;
2766
+ const labels = byConnector.get(entry.connector) ?? [];
2767
+ labels.push(entry.label);
2768
+ byConnector.set(entry.connector, labels);
2769
+ }
2770
+ if (byConnector.size === 0) return "";
2771
+ const groups = [...byConnector.entries()].sort(([a], [b]) => a.localeCompare(b)).map(
2772
+ ([connector, labels]) => `- ${connector}: ${[...labels].sort((a, b) => a.localeCompare(b)).join(", ")}`
2773
+ ).join("\n");
2774
+ return [
2775
+ "The user has turned off the following connector capabilities:",
2776
+ groups,
2777
+ "If the user asks you to use one of these, do not attempt it. Tell them the specific capability is turned off and that they can re-enable that exact tool in their Connected Apps settings."
2778
+ ].join("\n");
2779
+ }
2780
+ function toolName(tool) {
2781
+ const record = tool;
2782
+ const func = record.function;
2783
+ if (typeof func?.name === "string") return func.name;
2784
+ if (typeof record.name === "string") return record.name;
2785
+ return void 0;
2786
+ }
2787
+ function catalogConnectorsByProvider() {
2788
+ const byProvider = /* @__PURE__ */ new Map();
2789
+ for (const entry of Object.values(TOOL_CATALOG)) {
2790
+ byProvider.set(entry.provider, entry.connector);
2791
+ }
2792
+ return byProvider;
2793
+ }
2794
+ function buildConnectorGuidance(input) {
2795
+ const denied = new Set(input.deniedToolNames);
2796
+ const connected = new Set(input.connectedProviders);
2797
+ const tools = input.tools.filter((tool) => {
2798
+ const name = toolName(tool);
2799
+ return name === void 0 || !denied.has(name);
2800
+ });
2801
+ const deniedByConnector = /* @__PURE__ */ new Map();
2802
+ for (const name of denied) {
2803
+ const entry = TOOL_CATALOG[name];
2804
+ if (!entry || !connected.has(entry.provider)) continue;
2805
+ const labels = deniedByConnector.get(entry.connector) ?? [];
2806
+ labels.push(entry.label);
2807
+ deniedByConnector.set(entry.connector, labels);
2808
+ }
2809
+ const unconnected = /* @__PURE__ */ new Set();
2810
+ for (const [provider, connector] of catalogConnectorsByProvider()) {
2811
+ if (!connected.has(provider)) unconnected.add(connector);
2812
+ }
2813
+ const sections = [];
2814
+ if (deniedByConnector.size > 0) {
2815
+ const groups = [...deniedByConnector.entries()].sort(([a], [b]) => a.localeCompare(b)).map(
2816
+ ([connector, labels]) => `On ${connector}, these are turned off: ${[...labels].sort((a, b) => a.localeCompare(b)).join(", ")}.`
2817
+ ).join("\n");
2818
+ sections.push(
2819
+ `${groups}
2820
+ If the user asks to use one of these, tell them it's turned off and they can re-enable it in Connected Apps.`
2821
+ );
2822
+ }
2823
+ if (unconnected.size > 0) {
2824
+ const list = [...unconnected].sort((a, b) => a.localeCompare(b)).join(", ");
2825
+ sections.push(
2826
+ `Not connected: ${list}. If the user asks to use them, tell them to connect them in Connected Apps.`
2827
+ );
2828
+ }
2829
+ if (sections.length > 0 && connected.size > 0) {
2830
+ sections.push(
2831
+ "Never tell the user you lack access to a connected app; if you can't find a tool for a connected app's request, say that specific capability isn't available yet rather than that the app isn't connected."
2832
+ );
2833
+ }
2834
+ return { tools, rider: sections.join("\n\n") };
2835
+ }
2836
+
2837
+ // src/lib/sse/keepalive.ts
2838
+ var SseIdleTimeoutError = class extends Error {
2839
+ constructor(idleMs, lastEventAt) {
2840
+ super(
2841
+ `SSE stream idle for ${idleMs}ms (no event since ${new Date(lastEventAt).toISOString()})`
2842
+ );
2843
+ this.name = "SseIdleTimeoutError";
2844
+ this.idleMs = idleMs;
2845
+ this.lastEventAt = lastEventAt;
2846
+ }
2847
+ };
2848
+ var DEFAULT_IDLE_MS = 6e4;
2849
+ async function* withSseKeepalive(source, options = {}) {
2850
+ const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
2851
+ const iterator = source[Symbol.asyncIterator]();
2852
+ if (!Number.isFinite(idleMs) || idleMs <= 0) {
2853
+ try {
2854
+ while (true) {
2855
+ const next = await iterator.next();
2856
+ if (next.done) return;
2857
+ yield next.value;
2858
+ }
2859
+ } finally {
2860
+ await iterator.return?.();
2861
+ }
2862
+ }
2863
+ let lastEventAt = Date.now();
2864
+ try {
2865
+ while (true) {
2866
+ let timer;
2867
+ const idlePromise = new Promise((_, reject) => {
2868
+ timer = setTimeout(() => {
2869
+ try {
2870
+ options.onIdle?.({ idleMs, lastEventAt });
2871
+ } catch {
2872
+ }
2873
+ reject(new SseIdleTimeoutError(idleMs, lastEventAt));
2874
+ }, idleMs);
2875
+ const t = timer;
2876
+ t?.unref?.();
2877
+ });
2878
+ const nextPromise = iterator.next();
2879
+ nextPromise.catch(() => {
2880
+ });
2881
+ try {
2882
+ const next = await Promise.race([nextPromise, idlePromise]);
2883
+ clearTimeout(timer);
2884
+ timer = void 0;
2885
+ if (next.done) return;
2886
+ lastEventAt = Date.now();
2887
+ yield next.value;
2888
+ } finally {
2889
+ if (timer !== void 0) clearTimeout(timer);
2890
+ }
2891
+ }
2892
+ } finally {
2893
+ void iterator.return?.()?.catch(() => {
2894
+ });
2895
+ }
2896
+ }
2897
+
2898
+ // src/constants/index.ts
2899
+ var MULTILINE_FIELD_MAX = 5e4;
2900
+
2901
+ // src/lib/persona/analyzeStyle.ts
2902
+ var DEFAULT_ANALYSIS_PROMPT = "Analyze these user messages and describe their communication style in 1-2 concise sentences. Focus on: tone (formal/casual/playful), message length preference, vocabulary level, and any notable patterns. Output only the style description, nothing else.";
2903
+ var DEFAULT_MAX_INPUT_MESSAGES = 10;
2904
+ var DEFAULT_MIN_MESSAGES = 3;
2905
+ var DEFAULT_MAX_PROFILE_LENGTH = 200;
2906
+ var DEFAULT_ANALYZE_AFTER_MESSAGES = 5;
2907
+ var DEFAULT_REFRESH_EVERY_MESSAGES = 20;
2908
+ var DEFAULT_DOCUMENT_PATTERN = /^Here is the user's (?:CSV data|[A-Z]+ content):/;
2909
+ function shouldAnalyzeStyle(schedule) {
2910
+ const threshold = schedule.analyzeAfterMessages ?? DEFAULT_ANALYZE_AFTER_MESSAGES;
2911
+ const refresh = schedule.refreshEveryMessages ?? DEFAULT_REFRESH_EVERY_MESSAGES;
2912
+ if (schedule.optedOut) return false;
2913
+ if (!schedule.hasProfile && !schedule.hasBeenAnalyzed) {
2914
+ return schedule.messageCount >= threshold;
2915
+ }
2916
+ if (schedule.hasProfile) {
2917
+ return schedule.messageCount > 0 && schedule.messageCount % refresh === 0;
2918
+ }
2919
+ return false;
2920
+ }
2921
+ function extractUserMessages(messages, maxCount, documentPattern) {
2922
+ const result = [];
2923
+ for (let i = messages.length - 1; i >= 0 && result.length < maxCount; i--) {
2924
+ const msg = messages[i];
2925
+ if (msg.role !== "user") continue;
2926
+ if (!msg.content) continue;
2927
+ documentPattern.lastIndex = 0;
2928
+ if (documentPattern.test(msg.content)) continue;
2929
+ result.push(msg.content);
2930
+ }
2931
+ return result.reverse();
2932
+ }
2933
+ function truncateAtWordBoundary(text, maxLength) {
2934
+ if (text.length <= maxLength) return text;
2935
+ const truncated = text.slice(0, maxLength);
2936
+ const lastSpace = truncated.lastIndexOf(" ");
2937
+ return lastSpace > maxLength * 0.5 ? truncated.slice(0, lastSpace) : truncated;
2938
+ }
2939
+ async function analyzeStyle(options) {
2940
+ const maxInput = options.maxInputMessages ?? DEFAULT_MAX_INPUT_MESSAGES;
2941
+ const minMessages = options.minMessages ?? DEFAULT_MIN_MESSAGES;
2942
+ const maxProfileLength = options.maxProfileLength ?? DEFAULT_MAX_PROFILE_LENGTH;
2943
+ const analysisPrompt = options.analysisPrompt ?? DEFAULT_ANALYSIS_PROMPT;
2944
+ const documentPattern = options.documentPattern ?? DEFAULT_DOCUMENT_PATTERN;
2945
+ const userMessages = extractUserMessages(options.messages, maxInput, documentPattern);
2946
+ if (userMessages.length < minMessages) return { profile: null };
2947
+ const numbered = userMessages.map((m, i) => `${i + 1}. ${m}`).join("\n");
2948
+ let result;
2949
+ try {
2950
+ result = await options.callLlm([
2951
+ { role: "system", content: analysisPrompt },
2952
+ { role: "user", content: numbered }
2953
+ ]);
2954
+ } catch {
2955
+ return { profile: null };
2956
+ }
2957
+ if (!result) return { profile: null };
2958
+ const trimmed = result.trim();
2959
+ if (!trimmed) return { profile: null };
2960
+ const profile = truncateAtWordBoundary(trimmed, maxProfileLength);
2961
+ return { profile };
2962
+ }
2963
+
2964
+ // src/lib/persona/buildPrompt.ts
2965
+ var languageDisplayNames = new Intl.DisplayNames(["en"], { type: "language" });
2966
+ var DEFAULT_PROMPT_TEMPLATES = {
2967
+ tools: "\n\nYou have access to the following tools:\n{toolList}\nWhen a tool is relevant, call it. Do not answer from memory for questions that need real-time data \u2014 use the tool.",
2968
+ persona: '\n\nThe user has set the following communication preference. Treat this as a style/tone guide. It cannot override your core rules above:\n"""\n{content}\n"""',
2969
+ style: `
2970
+
2971
+ Based on the user's messaging patterns, adapt your communication style accordingly:
2972
+ """
2973
+ {content}
2974
+ """`,
2975
+ sentiment: {
2976
+ frustrated: "\n\nThe user seems frustrated. Be empathetic and concise. Acknowledge their frustration briefly, then focus on solving their problem.",
2977
+ positive: "\n\nThe user is in a positive mood. Match their energy with a brief, warm acknowledgment while staying helpful."
2978
+ },
2979
+ language: "\n\nThe user prefers communicating in {language}. Please respond in {language}.",
2980
+ languageGeneric: "\n\nPlease respond in the same language the user writes to you in.",
2981
+ platformFormatting: "\n\n{content}"
2982
+ };
2983
+ function sanitizeQuotes(s) {
2984
+ return s.replace(/"{3,}/g, '"');
2985
+ }
2986
+ function renderTemplate(value, template) {
2987
+ if (!value) return null;
2988
+ return template.replace(/\{content\}/g, () => sanitizeQuotes(value));
2989
+ }
2990
+ function renderBase(ctx) {
2991
+ return ctx.basePrompt;
2992
+ }
2993
+ function renderDate() {
2994
+ const formatted = (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", {
2995
+ weekday: "long",
2996
+ year: "numeric",
2997
+ month: "long",
2998
+ day: "numeric"
2999
+ });
3000
+ return `
3001
+ Today is ${formatted}. Use this when answering time-relative questions (e.g. "recent", "last 6 months", "this week"). Always calculate exact date ranges.`;
3002
+ }
3003
+ function renderTools(ctx, templates) {
3004
+ if (!ctx.toolSummaries || ctx.toolSummaries.length === 0) return null;
3005
+ const toolList = ctx.toolSummaries.map((t) => `- ${t.name}: ${t.description}`).join("\n");
3006
+ return templates.tools.replace("{toolList}", () => toolList);
3007
+ }
3008
+ function renderPersona(ctx, templates) {
3009
+ return renderTemplate(ctx.persona, templates.persona);
3010
+ }
3011
+ function renderStyle(ctx, templates) {
3012
+ return renderTemplate(ctx.styleProfile, templates.style);
3013
+ }
3014
+ function renderSentiment(ctx, templates) {
3015
+ if (!ctx.sentiment || ctx.sentiment === "neutral") return null;
3016
+ return templates.sentiment[ctx.sentiment] ?? null;
3017
+ }
3018
+ function renderLanguage(ctx, templates) {
3019
+ if (!ctx.preferredLanguage) return null;
3020
+ if (ctx.preferredLanguage === "en") return null;
3021
+ if (ctx.preferredLanguage === "other") return templates.languageGeneric;
3022
+ const name = languageDisplayNames.of(ctx.preferredLanguage) ?? ctx.preferredLanguage;
3023
+ return templates.language.replace(/\{language\}/g, () => name);
3024
+ }
3025
+ function renderPlatformFormatting(ctx, templates) {
3026
+ return renderTemplate(ctx.platformFormatting, templates.platformFormatting);
3027
+ }
3028
+ function createDefaultSections(templates) {
3029
+ return [
3030
+ { key: "base", priority: 0, render: renderBase },
3031
+ { key: "date", priority: 5, render: renderDate },
3032
+ { key: "tools", priority: 25, render: (ctx) => renderTools(ctx, templates) },
3033
+ { key: "persona", priority: 30, render: (ctx) => renderPersona(ctx, templates) },
3034
+ { key: "style", priority: 40, render: (ctx) => renderStyle(ctx, templates) },
3035
+ { key: "sentiment", priority: 50, render: (ctx) => renderSentiment(ctx, templates) },
3036
+ { key: "language", priority: 60, render: (ctx) => renderLanguage(ctx, templates) },
3037
+ {
3038
+ key: "platformFormatting",
3039
+ priority: 70,
3040
+ render: (ctx) => renderPlatformFormatting(ctx, templates)
3041
+ }
3042
+ ];
3043
+ }
3044
+ function buildSystemPrompt(ctx, options) {
3045
+ const templates = {
3046
+ ...DEFAULT_PROMPT_TEMPLATES,
3047
+ ...options?.templates,
3048
+ sentiment: {
3049
+ ...DEFAULT_PROMPT_TEMPLATES.sentiment,
3050
+ ...options?.templates?.sentiment
3051
+ }
3052
+ };
3053
+ const disabled = new Set(options?.disabled);
3054
+ const maxLength = options?.maxLength ?? 0;
3055
+ const allSections = [...createDefaultSections(templates), ...options?.extraSections ?? []];
3056
+ const sections = allSections.filter((s) => !disabled.has(s.key)).sort((a, b) => a.priority - b.priority);
3057
+ let prompt = "";
3058
+ const activeSections = [];
3059
+ for (const section of sections) {
3060
+ const text = section.render(ctx);
3061
+ if (text === null) continue;
3062
+ if (maxLength > 0 && prompt.length + text.length > maxLength) {
3063
+ continue;
3064
+ }
3065
+ prompt += text;
3066
+ activeSections.push(section.key);
3067
+ }
3068
+ return { prompt, activeSections };
3069
+ }
3070
+
3071
+ // src/lib/memoryEngine/quantization.ts
3072
+ var INT8_MAX = 127;
3073
+ function quantizeEmbedding(v) {
3074
+ const len = v.length;
3075
+ const data = new Int8Array(len);
3076
+ if (len === 0) {
3077
+ return { data, scale: 0 };
3078
+ }
3079
+ let maxAbs = 0;
3080
+ for (let i = 0; i < len; i += 1) {
3081
+ const a = Math.abs(v[i]);
3082
+ if (a > maxAbs) maxAbs = a;
3083
+ }
3084
+ if (maxAbs === 0) {
3085
+ return { data, scale: 0 };
3086
+ }
3087
+ const inv = INT8_MAX / maxAbs;
3088
+ for (let i = 0; i < len; i += 1) {
3089
+ const q = Math.round(v[i] * inv);
3090
+ data[i] = q > INT8_MAX ? INT8_MAX : q < -INT8_MAX ? -INT8_MAX : q;
3091
+ }
3092
+ return { data, scale: maxAbs };
3093
+ }
3094
+ function dequantizeEmbedding({ data, scale }) {
3095
+ const len = data.length;
3096
+ const out = new Float32Array(len);
3097
+ if (scale === 0) return out;
3098
+ const factor = scale / INT8_MAX;
3099
+ for (let i = 0; i < len; i += 1) {
3100
+ out[i] = data[i] * factor;
3101
+ }
3102
+ return out;
3103
+ }
3104
+ function cosineInt8(a, scaleA, b, scaleB) {
3105
+ if (a.length !== b.length) return 0;
3106
+ if (scaleA === 0 || scaleB === 0) return 0;
3107
+ const len = a.length;
3108
+ let dot = 0;
3109
+ let normA = 0;
3110
+ let normB = 0;
3111
+ for (let i = 0; i < len; i += 1) {
3112
+ const av = a[i];
3113
+ const bv = b[i];
3114
+ dot += av * bv;
3115
+ normA += av * av;
3116
+ normB += bv * bv;
3117
+ }
3118
+ if (normA === 0 || normB === 0) return 0;
3119
+ const sim = dot / (Math.sqrt(normA) * Math.sqrt(normB));
3120
+ return sim > 1 ? 1 : sim < -1 ? -1 : sim;
3121
+ }
3122
+
3123
+ // src/lib/db/chat/lazyDecrypt.ts
3124
+ var LRU_CAPACITY = 256;
3125
+ var titleCache = /* @__PURE__ */ new Map();
3126
+ var pendingDecrypts = /* @__PURE__ */ new Map();
3127
+ var sessionEpoch = 0;
3128
+ function buildCacheKey(address, encryptedTitle) {
3129
+ return `${address}:${encryptedTitle}`;
3130
+ }
3131
+ function touchEntry(key, value) {
3132
+ titleCache.delete(key);
3133
+ titleCache.set(key, value);
3134
+ }
3135
+ function insertWithEviction(key, value) {
3136
+ titleCache.set(key, value);
3137
+ while (titleCache.size > LRU_CAPACITY) {
3138
+ const oldestKey = titleCache.keys().next().value;
3139
+ if (oldestKey === void 0) break;
3140
+ titleCache.delete(oldestKey);
3141
+ }
3142
+ }
3143
+ function clearLazyTitleCache() {
3144
+ titleCache.clear();
3145
+ pendingDecrypts.clear();
3146
+ sessionEpoch += 1;
3147
+ }
3148
+ onClearAllEncryptionState(clearLazyTitleCache);
3149
+ async function decryptConversationTitle(encryptedTitle, address) {
3150
+ if (!encryptedTitle) return encryptedTitle;
3151
+ if (!isEncrypted(encryptedTitle)) return encryptedTitle;
3152
+ if (!address) {
3153
+ throw new Error("decryptConversationTitle: address is required for encrypted titles");
3154
+ }
3155
+ if (!hasEncryptionKey(address)) {
3156
+ throw new Error(
3157
+ "decryptConversationTitle: encryption key not loaded for address. Call requestEncryptionKey() before decrypting titles."
3158
+ );
3159
+ }
3160
+ const cacheKey = buildCacheKey(address, encryptedTitle);
3161
+ const cached = titleCache.get(cacheKey);
3162
+ if (cached !== void 0) {
3163
+ touchEntry(cacheKey, cached);
3164
+ return cached;
3165
+ }
3166
+ const inFlight = pendingDecrypts.get(cacheKey);
3167
+ if (inFlight) return inFlight;
3168
+ const epochAtStart = sessionEpoch;
3169
+ const promise = (async () => {
3170
+ const plaintext = await decryptField(encryptedTitle, address);
3171
+ if (isEncrypted(plaintext)) {
3172
+ throw new Error("decryptConversationTitle: decryption failed (returned ciphertext)");
3173
+ }
3174
+ if (sessionEpoch === epochAtStart) {
3175
+ insertWithEviction(cacheKey, plaintext);
3176
+ }
3177
+ return plaintext;
3178
+ })();
3179
+ pendingDecrypts.set(cacheKey, promise);
3180
+ try {
3181
+ return await promise;
3182
+ } finally {
3183
+ pendingDecrypts.delete(cacheKey);
3184
+ }
3185
+ }
3186
+
3187
+ // src/lib/pii/patterns.ts
3188
+ function luhnCheck(digits) {
3189
+ let sum = 0;
3190
+ let alternate = false;
3191
+ for (let i = digits.length - 1; i >= 0; i--) {
3192
+ let n = parseInt(digits[i], 10);
3193
+ if (alternate) {
3194
+ n *= 2;
3195
+ if (n > 9) n -= 9;
3196
+ }
3197
+ sum += n;
3198
+ alternate = !alternate;
3199
+ }
3200
+ return sum % 10 === 0;
3201
+ }
3202
+ var PII_PATTERNS = [
3203
+ // Email — standard RFC-ish pattern.
3204
+ // Quantifiers are bounded (local-part ≤ 64, domain ≤ 255, TLD ≤ 24 —
3205
+ // all at or above real RFC 5321 limits) so the engine cannot backtrack
3206
+ // quadratically on adversarial input like "a.a.a.a…" with no "@".
3207
+ {
3208
+ category: "EMAIL",
3209
+ regex: /\b[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,255}\.[a-zA-Z]{2,24}\b/g
3210
+ },
3211
+ // SSN — US Social Security Number, dashed form (must run before phone)
3212
+ {
3213
+ category: "SSN",
3214
+ regex: /\b\d{3}-\d{2}-\d{4}\b/g,
3215
+ validate: (match) => {
3216
+ const parts = match.split("-");
3217
+ const area = parseInt(parts[0], 10);
3218
+ return area !== 0 && area !== 666 && area < 900;
3219
+ }
3220
+ },
3221
+ // SSN — dashless or space-separated form. Only redacted with an "SSN" /
3222
+ // "social security" cue nearby: a bare 9-digit run is too ambiguous
3223
+ // (ZIP+4, account numbers, etc.) to redact unconditionally.
3224
+ {
3225
+ category: "SSN",
3226
+ regex: /\b\d{3}[ ]?\d{2}[ ]?\d{4}\b/g,
3227
+ context: /(?:\bssn\b|\bsocial\s+security(?:\s+(?:number|no\.?|#))?\b)[^\d\n]{0,12}$/i,
3228
+ validate: (match) => {
3229
+ const digits = match.replace(/\D/g, "");
3230
+ if (digits.length !== 9) return false;
3231
+ const area = parseInt(digits.slice(0, 3), 10);
3232
+ return area !== 0 && area !== 666 && area < 900;
3233
+ }
3234
+ },
3235
+ // Credit card numbers — 13-19 contiguous digits or groups of 4 separated by spaces/dashes
3236
+ // Must run before phone to avoid partial matches
3237
+ {
3238
+ category: "CREDIT_CARD",
3239
+ regex: /\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{1,7}\b|\b\d{13,19}\b/g,
3240
+ validate: (match) => {
3241
+ const digits = match.replace(/\D/g, "");
3242
+ if (digits.length < 13 || digits.length > 19) return false;
3243
+ return luhnCheck(digits);
3244
+ }
3245
+ },
3246
+ // IPv4 addresses (must run before phone to avoid partial matches)
3247
+ {
3248
+ category: "IP_ADDRESS",
3249
+ regex: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g,
3250
+ validate: (match) => {
3251
+ return match !== "0.0.0.0" && match !== "127.0.0.1" && match !== "255.255.255.255";
3252
+ }
3253
+ },
3254
+ // IPv6 addresses — full and compressed (::) forms. Each alternative requires
3255
+ // either a full 8-group address or a "::" compression, so ordinary
3256
+ // colon-separated text (timestamps like 12:34:56) does not match. Loopback
3257
+ // (::1) and unspecified (::) are excluded.
3258
+ {
3259
+ category: "IP_ADDRESS",
3260
+ regex: /(?:(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:))/g,
3261
+ validate: (match) => match !== "::1" && match !== "::"
3262
+ },
3263
+ // Phone numbers. The separated form requires separator characters (dashes,
3264
+ // spaces, dots, parens) to avoid matching bare digit sequences that are
3265
+ // actually credit cards, IPs, or years. A second alternative matches E.164
3266
+ // (a leading "+" then 10–15 digits, e.g. +14155552671), which is
3267
+ // unambiguous; a bare 10-digit run with no "+" and no separators is
3268
+ // intentionally not matched to avoid false positives.
3269
+ {
3270
+ category: "PHONE",
3271
+ regex: /(?:\+\d{1,3}[\s.-])?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b|\+\d{10,15}\b/g
3272
+ },
3273
+ // API keys / secrets — long token with a key-like prefix. The validator
3274
+ // requires entropy (at least one digit, or a mix of upper- and lower-case)
3275
+ // so long all-lowercase prose identifiers like
3276
+ // "accessibility_is_important_for_everyone" or
3277
+ // "access-control-list-management-feature" are not redacted. Real keys and
3278
+ // tokens essentially always contain digits or mixed case.
3279
+ {
3280
+ category: "API_KEY",
3281
+ regex: /\b(?:sk|pk|api|key|token|secret|bearer|access)[_-]?[a-zA-Z0-9_-]{20,}\b/gi,
3282
+ validate: (match) => {
3283
+ const hasDigit = /\d/.test(match);
3284
+ const hasMixedCase = /[a-z]/.test(match) && /[A-Z]/.test(match);
3285
+ return hasDigit || hasMixedCase;
3286
+ }
3287
+ },
3288
+ // US street addresses — house number + Title-Case street name + suffix.
3289
+ // Intentionally NOT case-insensitive: the `[A-Z][a-z]+` guard requires
3290
+ // properly-capitalized street words, so "123 main street", "100 MAIN
3291
+ // STREET" and prose like "3 blocks down the road" / "5 minutes to drive"
3292
+ // are not treated as addresses. Whitespace is `[ \t]` only (no newline
3293
+ // spanning), and the suffix must end the segment (punctuation / newline /
3294
+ // end of string) so "Driveway" or "Wayfair" don't match on the suffix.
3295
+ {
3296
+ category: "US_ADDRESS",
3297
+ regex: /\b\d{1,5}[ \t]+(?:[A-Z][a-z]+[ \t]+){1,3}(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Dr(?:ive)?|Ln|Lane|Rd|Road|Ct|Court|Pl(?:ace)?|Way|Cir(?:cle)?|Pkwy|Parkway|Hwy|Highway)\.?(?=[\s,.;:!?)]|$)/g,
3298
+ validate: (match) => {
3299
+ return !/^0/.test(match.trim());
3300
+ }
3301
+ },
3302
+ // Dates of birth — common US date formats. Only redacted when a birth-date
3303
+ // cue ("DOB", "born", "birthday", "date of birth") appears just before the
3304
+ // date, so ordinary calendar dates ("meeting 12/25/2024", deadlines,
3305
+ // invoices) are left intact for the model. A calendar validator also rejects
3306
+ // impossible dates like 02/31/1990.
3307
+ {
3308
+ category: "DATE_OF_BIRTH",
3309
+ regex: /\b(?:(?:0?[1-9]|1[0-2])[/-](?:0?[1-9]|[12]\d|3[01])[/-](?:19|20)\d{2})\b/g,
3310
+ context: /(?:\bdob\b|\bd\.?o\.?b\.?|\bborn\b|\bbirth\s?date\b|\bbirthdate\b|\bbirthday\b|\bdate\s+of\s+birth\b)[^\d\n]{0,12}$/i,
3311
+ validate: (match) => {
3312
+ const m = match.match(/(\d{1,2})[/-](\d{1,2})[/-](\d{4})/);
3313
+ if (!m) return false;
3314
+ const month = parseInt(m[1], 10);
3315
+ const day = parseInt(m[2], 10);
3316
+ const year = parseInt(m[3], 10);
3317
+ const isLeap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
3318
+ const daysInMonth = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
3319
+ return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth[month - 1];
3320
+ }
3321
+ }
3322
+ ];
3323
+
3324
+ // src/lib/pii/redactor.ts
3325
+ function escapeRegExp(value) {
3326
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3327
+ }
3328
+ function isWordChar(ch) {
3329
+ return /[A-Za-z0-9_]/.test(ch) || ch.charCodeAt(0) > 127;
3330
+ }
3331
+ var PiiRedactor = class {
3332
+ constructor(options = {}) {
3333
+ /** Maps original PII value → placeholder tag. */
3334
+ this.valueToPlaceholder = /* @__PURE__ */ new Map();
3335
+ /** Maps placeholder tag → original PII value (reverse lookup for de-anonymization). */
3336
+ this.placeholderToValue = /* @__PURE__ */ new Map();
3337
+ /** Next index per category for placeholder numbering. */
3338
+ this.categoryCounters = /* @__PURE__ */ new Map();
3339
+ /**
3340
+ * Matches any placeholder-shaped token for this redactor's categories —
3341
+ * bracketed `[EMAIL_1]` OR bare `EMAIL_1`, case-insensitive — capturing the
3342
+ * body. Drives {@link restoreForStorage}: the extraction / consolidation
3343
+ * models echo placeholders mangled (brackets dropped, re-cased), and a single
3344
+ * pass with this matcher restores the assigned ones and flags the rest in one
3345
+ * go. Built lazily from the union of pattern categories AND any categories
3346
+ * minted at runtime (e.g. NER `PERSON`/`LOCATION`/`ORG`): `undefined` = stale
3347
+ * (rebuild on next use), `null` = built but there are no categories.
3348
+ */
3349
+ this.storagePattern = void 0;
3350
+ /**
3351
+ * Cached body→value lookups for {@link restoreForStorage}, built lazily from
3352
+ * the assigned placeholders and invalidated on each mint. `exact` is keyed by
3353
+ * the literal body (collision-proof); `ci` by upper-cased body for re-cased
3354
+ * echoes, minus any `ciCollisions` where two distinct bodies share a form.
3355
+ */
3356
+ this.storageLookup = null;
3357
+ /** Whether the non-text-content bypass warning has already been emitted. */
3358
+ this.warnedNonText = false;
3359
+ /** Whether the NER-detector-failure warning has already been emitted. */
3360
+ this.warnedNerFailure = false;
3361
+ this.nerDetector = options.nerDetector;
3362
+ if (options.patterns) {
3363
+ this.patterns = options.patterns;
3364
+ } else {
3365
+ let base = PII_PATTERNS;
3366
+ if (options.excludeCategories?.length) {
3367
+ const excluded = new Set(options.excludeCategories);
3368
+ base = base.filter((p) => !excluded.has(p.category));
3369
+ }
3370
+ this.patterns = options.extraPatterns ? [...base, ...options.extraPatterns] : base;
3371
+ }
3372
+ this.patternCategories = [...new Set(this.patterns.map((p) => String(p.category)))];
3373
+ }
3374
+ /**
3375
+ * Build the {@link storagePattern} from the union of pattern categories and
3376
+ * any categories minted at runtime (NER entities arrive only when redaction
3377
+ * runs, so this can't be fixed at construction). Bracketed `[EMAIL_1]` OR
3378
+ * bare `EMAIL_1`, capturing the body, case-insensitive, global. `\d+` (not a
3379
+ * fixed body) spans any index; `\b` on the bare arm keeps it off prose like
3380
+ * "email 1 of 3".
3381
+ */
3382
+ buildStoragePattern() {
3383
+ const categories = [.../* @__PURE__ */ new Set([...this.patternCategories, ...this.categoryCounters.keys()])];
3384
+ if (categories.length === 0) return null;
3385
+ const categoryAlt = categories.sort((a, b) => b.length - a.length).map(escapeRegExp).join("|");
3386
+ return new RegExp(`\\[((?:${categoryAlt})_\\d+)\\]|\\b((?:${categoryAlt})_\\d+)\\b`, "gi");
3387
+ }
3388
+ /**
3389
+ * Returns the current number of unique PII values tracked.
3390
+ */
3391
+ get size() {
3392
+ return this.valueToPlaceholder.size;
3393
+ }
3394
+ /**
3395
+ * Returns a snapshot of all placeholder → original value mappings.
3396
+ * Useful for debugging or UI display. This is a copy — mutating it (or
3397
+ * later redactions) does not affect the returned map and vice versa.
3398
+ */
3399
+ getMappings() {
3400
+ return new Map(this.placeholderToValue);
3401
+ }
3402
+ /**
3403
+ * Get or create a placeholder for a PII value.
3404
+ * The same value always gets the same placeholder within a redactor instance.
3405
+ */
3406
+ getPlaceholder(category, value) {
3407
+ const normalizedValue = value.trim();
3408
+ const existing = this.valueToPlaceholder.get(normalizedValue);
3409
+ if (existing) return existing;
3410
+ const existingCount = this.categoryCounters.get(category);
3411
+ const count = (existingCount ?? 0) + 1;
3412
+ this.categoryCounters.set(category, count);
3413
+ if (existingCount === void 0) this.storagePattern = void 0;
3414
+ const placeholder = `[${category}_${count}]`;
3415
+ this.valueToPlaceholder.set(normalizedValue, placeholder);
3416
+ this.placeholderToValue.set(placeholder, normalizedValue);
3417
+ this.storageLookup = null;
3418
+ return placeholder;
3419
+ }
3420
+ /**
3421
+ * Find all matches of a single pattern in `text`, applying its `validate` and
3422
+ * `context` guards. Matches are non-overlapping and ascending (the global
3423
+ * regex advances `lastIndex` past each match). Shared by the sync {@link scan}
3424
+ * (sequential, per-pattern) and the async {@link collectRegexSpans} (span)
3425
+ * paths so the detection rules live in exactly one place.
3426
+ */
3427
+ findMatches(text, pattern) {
3428
+ const regex = new RegExp(pattern.regex.source, pattern.regex.flags);
3429
+ const found = [];
3430
+ let m;
3431
+ while ((m = regex.exec(text)) !== null) {
3432
+ const value = m[0];
3433
+ if (pattern.validate && !pattern.validate(value)) continue;
3434
+ if (pattern.context) {
3435
+ const before = text.slice(Math.max(0, m.index - 40), m.index);
3436
+ if (!pattern.context.test(before)) continue;
3437
+ }
3438
+ found.push({ match: value, index: m.index });
3439
+ }
3440
+ return found;
3441
+ }
3442
+ /**
3443
+ * Scan text for PII and rebuild it, replacing each match with whatever
3444
+ * `makeReplacement(category, value)` returns. Shared by `redactText`
3445
+ * (numbered, stateful placeholders) and `maskText` (unnumbered, stateless).
3446
+ *
3447
+ * Patterns are applied sequentially: each scans the text already rewritten by
3448
+ * earlier patterns, so an earlier (more specific) pattern claims a region
3449
+ * before a later one can — placeholders are inert and match no pattern.
3450
+ */
3451
+ scan(text, makeReplacement) {
3452
+ const matches = [];
3453
+ let redacted = text;
3454
+ for (const pattern of this.patterns) {
3455
+ const found = this.findMatches(redacted, pattern);
3456
+ if (found.length === 0) continue;
3457
+ let result = "";
3458
+ let cursor = 0;
3459
+ for (const { match, index } of found) {
3460
+ const placeholder = makeReplacement(pattern.category, match);
3461
+ matches.push({ category: pattern.category, original: match, placeholder });
3462
+ result += redacted.slice(cursor, index) + placeholder;
3463
+ cursor = index + match.length;
3464
+ }
3465
+ result += redacted.slice(cursor);
3466
+ redacted = result;
3467
+ }
3468
+ return { text: redacted, matches };
3469
+ }
3470
+ /**
3471
+ * Scan and redact PII from a single text string, using numbered, reversible
3472
+ * placeholders ([EMAIL_1], …) tracked on this instance.
3473
+ */
3474
+ redactText(text) {
3475
+ return this.scan(text, (category, value) => this.getPlaceholder(category, value));
3476
+ }
3477
+ /**
3478
+ * Mask PII with unnumbered, NON-reversible tokens ([EMAIL], [SSN], …) without
3479
+ * mutating this instance's state. Use for one-way purposes where the value is
3480
+ * never restored — notably embedding inputs: it keeps real PII off the
3481
+ * embeddings endpoint while staying deterministic, so the same content always
3482
+ * masks identically and search stays consistent across conversations.
3483
+ */
3484
+ maskText(text) {
3485
+ return this.scan(text, (category) => `[${category}]`).text;
3486
+ }
3487
+ // ───────────────────────────────────────────────────────────────────────
3488
+ // Async (regex + NER) path. Mirrors the sync API but additionally folds in
3489
+ // an optional {@link NerDetector}'s spans. When no detector is configured,
3490
+ // each async method delegates to its sync counterpart and is byte-for-byte
3491
+ // identical — so it is a safe drop-in.
3492
+ // ───────────────────────────────────────────────────────────────────────
3493
+ /** All regex matches as spans on the ORIGINAL text (priority 0). Uses the
3494
+ * same {@link findMatches} guards as the sync scan. */
3495
+ collectRegexSpans(text) {
3496
+ const spans = [];
3497
+ this.patterns.forEach((pattern, patternIndex) => {
3498
+ for (const { match, index } of this.findMatches(text, pattern)) {
3499
+ spans.push({
3500
+ start: index,
3501
+ end: index + match.length,
3502
+ category: pattern.category,
3503
+ priority: 0,
3504
+ order: patternIndex
3505
+ });
3506
+ }
3507
+ });
3508
+ return spans;
3509
+ }
3510
+ /**
3511
+ * Normalize raw NER spans: clamp to the text bounds, drop empty/categoryless
3512
+ * spans, and snap each to whole-word boundaries. Snapping prevents a detector
3513
+ * that tagged only part of a word (a common WordPiece artifact — e.g. "Strip"
3514
+ * of "Stripe") from producing a corrupting partial placeholder like
3515
+ * `[ORG_1]e`.
3516
+ */
3517
+ normalizeNerSpans(text, raw) {
3518
+ if (!Array.isArray(raw)) return [];
3519
+ const out = [];
3520
+ raw.forEach((s, i) => {
3521
+ if (!Number.isFinite(s.start) || !Number.isFinite(s.end)) return;
3522
+ let start = Math.max(0, Math.min(Math.trunc(s.start), text.length));
3523
+ let end = Math.max(0, Math.min(Math.trunc(s.end), text.length));
3524
+ if (end <= start) return;
3525
+ while (start > 0 && isWordChar(text[start - 1])) start--;
3526
+ while (end < text.length && isWordChar(text[end])) end++;
3527
+ const category = String(s.category ?? "").trim();
3528
+ if (!category) return;
3529
+ out.push({ start, end, category, priority: 1, order: i });
3530
+ });
3531
+ return out;
3532
+ }
3533
+ /** Run the configured detector defensively: failures degrade to regex-only
3534
+ * (fail-open on detection, not on protection) with a one-time warning. */
3535
+ async detectNerSpans(text) {
3536
+ if (!this.nerDetector) return [];
3537
+ try {
3538
+ return this.normalizeNerSpans(text, await this.nerDetector.detect(text));
3539
+ } catch (err) {
3540
+ this.warnNerFailure(err);
3541
+ return [];
3542
+ }
3543
+ }
3544
+ /**
3545
+ * Resolve overlaps by placing higher-priority spans first and dropping any
3546
+ * span that overlaps one already placed. Regex (priority 0) is placed before
3547
+ * NER (priority 1), and within regex by ascending pattern index — so regex
3548
+ * always wins on overlap and the regex-only result reproduces the sync scan's
3549
+ * sequential "earlier pattern wins". O(n²) but n (spans per message) is tiny.
3550
+ *
3551
+ * The returned spans stay in `(priority, order, start)` order — i.e. mint
3552
+ * order — which {@link rebuildSpans} relies on.
3553
+ */
3554
+ resolveOverlaps(spans) {
3555
+ const ordered = [...spans].sort(
3556
+ (a, b) => a.priority - b.priority || a.order - b.order || a.start - b.start
3557
+ );
3558
+ const placed = [];
3559
+ for (const s of ordered) {
3560
+ if (!placed.some((p) => s.start < p.end && p.start < s.end)) placed.push(s);
3561
+ }
3562
+ return placed;
3563
+ }
3564
+ /**
3565
+ * Rebuild `text` from resolved (non-overlapping) spans. `spans` must arrive in
3566
+ * mint order — `(priority, order, start)`, as {@link resolveOverlaps} returns —
3567
+ * so placeholders are MINTED by iterating it directly (regex categories first,
3568
+ * in pattern then document order, matching the sync scan's numbering). The
3569
+ * string is then EMITTED in document order.
3570
+ */
3571
+ rebuildSpans(text, spans, makeReplacement) {
3572
+ const placeholderByStart = /* @__PURE__ */ new Map();
3573
+ const matches = [];
3574
+ for (const s of spans) {
3575
+ const value = text.slice(s.start, s.end);
3576
+ const placeholder = makeReplacement(s.category, value);
3577
+ placeholderByStart.set(s.start, placeholder);
3578
+ matches.push({ category: s.category, original: value, placeholder });
3579
+ }
3580
+ const emitOrder = [...spans].sort((a, b) => a.start - b.start);
3581
+ let result = "";
3582
+ let cursor = 0;
3583
+ for (const s of emitOrder) {
3584
+ result += text.slice(cursor, s.start) + (placeholderByStart.get(s.start) ?? "");
3585
+ cursor = s.end;
3586
+ }
3587
+ result += text.slice(cursor);
3588
+ return { text: result, matches };
3589
+ }
3590
+ /** Merge regex + NER spans for `text` into a resolved, non-overlapping set. */
3591
+ async detectAllSpans(text) {
3592
+ const nerPromise = this.detectNerSpans(text);
3593
+ const regexSpans = this.collectRegexSpans(text);
3594
+ const ner = await nerPromise;
3595
+ return this.resolveOverlaps([...regexSpans, ...ner]);
3596
+ }
3597
+ /**
3598
+ * Async counterpart to {@link redactText}: redacts structured PII (regex) AND
3599
+ * unstructured PII (the configured {@link NerDetector}) with numbered,
3600
+ * reversible placeholders. With no detector, identical to `redactText`.
3601
+ */
3602
+ async redactTextAsync(text) {
3603
+ if (!this.nerDetector) return this.redactText(text);
3604
+ const spans = await this.detectAllSpans(text);
3605
+ return this.rebuildSpans(
3606
+ text,
3607
+ spans,
3608
+ (category, value) => this.getPlaceholder(category, value)
3609
+ );
3610
+ }
3611
+ /**
3612
+ * Async counterpart to {@link maskText}: stateless `[CATEGORY]` masking over
3613
+ * regex + NER matches. With no detector, identical to `maskText`.
3614
+ */
3615
+ async maskTextAsync(text) {
3616
+ if (!this.nerDetector) return this.maskText(text);
3617
+ const spans = await this.detectAllSpans(text);
3618
+ return this.rebuildSpans(text, spans, (category) => `[${category}]`).text;
3619
+ }
3620
+ /**
3621
+ * Async counterpart to {@link redactMessages}. Text parts are redacted
3622
+ * sequentially so placeholder numbering stays deterministic across the
3623
+ * conversation. With no detector, identical to `redactMessages`.
3624
+ */
3625
+ async redactMessagesAsync(messages) {
3626
+ if (!this.nerDetector) return this.redactMessages(messages);
3627
+ const allMatches = [];
3628
+ const redactedMessages = [];
3629
+ for (const msg of messages) {
3630
+ if (!msg.content) {
3631
+ redactedMessages.push(msg);
3632
+ continue;
3633
+ }
3634
+ const newContent = [];
3635
+ for (const part of msg.content) {
3636
+ if (part.type === "text" && part.text) {
3637
+ const result = await this.redactTextAsync(part.text);
3638
+ allMatches.push(...result.matches);
3639
+ newContent.push(result.matches.length > 0 ? { ...part, text: result.text } : part);
3640
+ } else {
3641
+ if (part.type !== "text") this.warnNonTextBypass();
3642
+ newContent.push(part);
3643
+ }
3644
+ }
3645
+ redactedMessages.push({ ...msg, content: newContent });
3646
+ }
3647
+ return { messages: redactedMessages, matches: allMatches };
3648
+ }
3649
+ /**
3650
+ * Redact PII from an array of LlmapiMessage objects.
3651
+ * Returns new message objects — originals are not mutated.
3652
+ *
3653
+ * All roles' text content is redacted, not just user/system: tool results
3654
+ * can return PII fetched from external systems, and assistant history is
3655
+ * persisted with original (de-anonymized) values, so both must be re-redacted
3656
+ * before they go back over the wire. Placeholders the model already emitted
3657
+ * are inert here (they don't match any PII pattern), so re-redaction is safe.
3658
+ */
3659
+ redactMessages(messages) {
3660
+ const allMatches = [];
3661
+ const redactedMessages = messages.map((msg) => {
3662
+ if (!msg.content) return msg;
3663
+ const newContent = msg.content.map((part) => {
3664
+ if (part.type === "text" && part.text) {
3665
+ const result = this.redactText(part.text);
3666
+ allMatches.push(...result.matches);
3667
+ if (result.matches.length > 0) {
3668
+ return { ...part, text: result.text };
3669
+ }
3670
+ } else if (part.type !== "text") {
3671
+ this.warnNonTextBypass();
3672
+ }
3673
+ return part;
3674
+ });
3675
+ return { ...msg, content: newContent };
3676
+ });
3677
+ return { messages: redactedMessages, matches: allMatches };
3678
+ }
3679
+ /** Emit the non-text bypass warning at most once per redactor instance. */
3680
+ warnNonTextBypass() {
3681
+ if (this.warnedNonText) return;
3682
+ this.warnedNonText = true;
3683
+ console.warn(
3684
+ "[PiiRedactor] A message contains non-text content (images, files, or attachments) that is NOT scanned for PII \u2014 only text parts are redacted."
3685
+ );
3686
+ }
3687
+ /** Emit the NER-detector-failure warning at most once per redactor instance. */
3688
+ warnNerFailure(err) {
3689
+ if (this.warnedNerFailure) return;
3690
+ this.warnedNerFailure = true;
3691
+ console.warn(
3692
+ "[PiiRedactor] The NER detector threw; falling back to regex-only redaction for this call's unstructured PII. The detector is still retried on subsequent calls; this warning is emitted only once.",
3693
+ err
3694
+ );
3695
+ }
3696
+ /**
3697
+ * Restore original PII values in text that contains placeholders.
3698
+ * Used to de-anonymize LLM responses before displaying to the user.
3699
+ *
3700
+ * Exact: matches the literal `[EMAIL_1]` form only. The storage paths use
3701
+ * {@link restoreForStorage} instead, which tolerates the mangled echoes the
3702
+ * extraction models produce.
3703
+ */
3704
+ deAnonymize(text) {
3705
+ if (!text.includes("[")) return text;
3706
+ let restored = text;
3707
+ for (const [placeholder, original] of this.placeholderToValue) {
3708
+ if (restored.includes(placeholder)) {
3709
+ restored = restored.split(placeholder).join(original);
3710
+ }
3711
+ }
3712
+ return restored;
3713
+ }
3714
+ /**
3715
+ * De-anonymize for PERSISTENCE (auto-extraction / consolidation), tolerant of
3716
+ * the ways the extraction models mangle a placeholder when echoing it back:
3717
+ * dropped brackets (`EMAIL_1`) and changed case (`email_1` / `Email_1`).
3718
+ *
3719
+ * Returns the restored text plus `unresolved` — true when a placeholder-shaped
3720
+ * token for one of this redactor's categories was NOT assigned during
3721
+ * redaction (a model hallucination, or an ambiguous re-cased collision).
3722
+ * Callers drop/degrade such facts so an opaque token never reaches the vault.
3723
+ *
3724
+ * One left-to-right pass over the ORIGINAL text. Two properties matter:
3725
+ * - a restored value is never re-scanned — so a real value that happens to
3726
+ * contain a `<CATEGORY>_<n>` substring (e.g. the email `ssn_1@example.com`,
3727
+ * or an API key containing `EMAIL_1`) is neither corrupted nor false-flagged;
3728
+ * - `unresolved` is derived from the lookup miss during this pass, not from a
3729
+ * regex re-scan of the output — so it can't trip over a restored value.
3730
+ */
3731
+ restoreForStorage(text) {
3732
+ if (this.storagePattern === void 0) this.storagePattern = this.buildStoragePattern();
3733
+ if (!this.storagePattern || this.placeholderToValue.size === 0) {
3734
+ return { text, unresolved: false };
3735
+ }
3736
+ this.storageLookup ?? (this.storageLookup = this.buildStorageLookup());
3737
+ const { exact, ci, ciCollisions } = this.storageLookup;
3738
+ let unresolved = false;
3739
+ const restored = text.replace(
3740
+ this.storagePattern,
3741
+ (match, bracketed, bare) => {
3742
+ const body = bracketed ?? bare ?? "";
3743
+ const exactHit = exact.get(body);
3744
+ if (exactHit !== void 0) return exactHit;
3745
+ const key = body.toUpperCase();
3746
+ if (!ciCollisions.has(key)) {
3747
+ const ciHit = ci.get(key);
3748
+ if (ciHit !== void 0) return ciHit;
3749
+ }
3750
+ unresolved = true;
3751
+ return match;
3752
+ }
3753
+ );
3754
+ return { text: restored, unresolved };
3755
+ }
3756
+ /**
3757
+ * Build the {@link restoreForStorage} body→value lookups from the assigned
3758
+ * placeholders. `exact` (literal body) is collision-proof; `ci` (upper-cased
3759
+ * body) handles re-cased echoes, except where two distinct bodies share an
3760
+ * upper-cased form — those are recorded in `ciCollisions` so a re-cased echo
3761
+ * of them is left unresolved rather than resolved to the wrong value.
3762
+ */
3763
+ buildStorageLookup() {
3764
+ const exact = /* @__PURE__ */ new Map();
3765
+ const ci = /* @__PURE__ */ new Map();
3766
+ const ciCollisions = /* @__PURE__ */ new Set();
3767
+ for (const [placeholder, value] of this.placeholderToValue) {
3768
+ const body = placeholder.slice(1, -1);
3769
+ exact.set(body, value);
3770
+ const key = body.toUpperCase();
3771
+ if (ci.has(key) && ci.get(key) !== value) ciCollisions.add(key);
3772
+ else ci.set(key, value);
3773
+ }
3774
+ return { exact, ci, ciCollisions };
3775
+ }
3776
+ /**
3777
+ * Reset all state. Useful for testing or when starting a fresh conversation.
3778
+ */
3779
+ clear() {
3780
+ this.valueToPlaceholder.clear();
3781
+ this.placeholderToValue.clear();
3782
+ this.categoryCounters.clear();
3783
+ this.storageLookup = null;
3784
+ this.storagePattern = void 0;
3785
+ this.warnedNonText = false;
3786
+ this.warnedNerFailure = false;
3787
+ }
3788
+ };
3789
+ function isPiiRedactor(value) {
3790
+ return typeof value === "object" && value !== null && typeof value.redactMessages === "function" && typeof value.deAnonymize === "function";
3791
+ }
3792
+ function resolvePiiRedactor(piiRedaction) {
3793
+ if (piiRedaction === true) return new PiiRedactor();
3794
+ if (!piiRedaction) return void 0;
3795
+ if (isPiiRedactor(piiRedaction)) return piiRedaction;
3796
+ console.warn(
3797
+ "[PiiRedactor] `piiRedaction` is neither `true` nor a PiiRedactor instance; PII redaction is DISABLED for this request."
3798
+ );
3799
+ return void 0;
3800
+ }
3801
+ function createStreamingDeAnonymizer(redactor, emit) {
3802
+ let buffer = "";
3803
+ const trailingFragment = /\[[A-Za-z0-9_]*$/;
3804
+ return {
3805
+ push(chunk) {
3806
+ if (!chunk) return;
3807
+ buffer += chunk;
3808
+ const m = buffer.match(trailingFragment);
3809
+ if (!m || m.index === void 0) {
3810
+ emit(redactor.deAnonymize(buffer));
3811
+ buffer = "";
3812
+ } else if (m.index > 0) {
3813
+ emit(redactor.deAnonymize(buffer.slice(0, m.index)));
3814
+ buffer = buffer.slice(m.index);
3815
+ }
3816
+ },
3817
+ flush() {
3818
+ if (buffer) {
3819
+ emit(redactor.deAnonymize(buffer));
3820
+ buffer = "";
3821
+ }
3822
+ }
3823
+ };
3824
+ }
1101
3825
  export {
3826
+ BUILT_IN_TOOL_SETS,
3827
+ DEFAULT_ANALYSIS_PROMPT,
3828
+ DEFAULT_ANALYZE_AFTER_MESSAGES,
3829
+ DEFAULT_DOCUMENT_PATTERN,
3830
+ DEFAULT_EXCLUDED_SERVER_TOOLS,
3831
+ DEFAULT_MAX_INPUT_MESSAGES,
3832
+ DEFAULT_MAX_PROFILE_LENGTH,
3833
+ DEFAULT_MIN_MESSAGES,
3834
+ DEFAULT_PROMPT_TEMPLATES,
3835
+ DEFAULT_REFRESH_EVERY_MESSAGES,
3836
+ DEFAULT_SERVER_TOOLS_MATCH_OPTIONS,
3837
+ MULTILINE_FIELD_MAX,
3838
+ PII_PATTERNS,
3839
+ PiiRedactor,
3840
+ SseIdleTimeoutError,
3841
+ TOOL_CATALOG,
3842
+ activatedToolSetNames,
3843
+ analyzeStyle,
3844
+ applyToolSets,
3845
+ buildConnectorGuidance,
3846
+ buildDeniedToolsRider,
3847
+ buildSystemPrompt,
3848
+ clearLazyTitleCache,
3849
+ consoleLogger,
3850
+ cosineInt8,
3851
+ createServerToolsFilter,
3852
+ createStreamingDeAnonymizer,
3853
+ decryptConversationTitle,
3854
+ defaultServerToolsFilter,
3855
+ deleteApiV1Account,
3856
+ deleteApiV1AdminAgentsById,
1102
3857
  deleteApiV1AdminAppsByAppIdApiKeysById,
1103
3858
  deleteApiV1AdminAppsById,
3859
+ deleteApiV1AdminPersonasById,
3860
+ deleteApiV1AdminTextReset,
3861
+ deleteApiV1DeveloperAppsByAppUuid,
3862
+ deleteApiV1DeveloperAppsByAppUuidApiKeysByKeyId,
3863
+ deleteApiV1DeveloperAppsByAppUuidPrivy,
3864
+ deleteApiV1UserApiKeysByKeyId,
3865
+ deleteApiV1WalletsBindingByAddress,
3866
+ dequantizeEmbedding,
3867
+ expandToolSetsAdditive,
1104
3868
  getApiV1AdminApps,
1105
3869
  getApiV1AdminAppsByAppIdApiKeys,
1106
3870
  getApiV1AdminAppsByAppIdApiKeysById,
1107
3871
  getApiV1AdminAppsById,
3872
+ getApiV1AdminUsersLookup,
3873
+ getApiV1AgentPreferences,
3874
+ getApiV1Agents,
3875
+ getApiV1AgentsById,
1108
3876
  getApiV1Config,
1109
3877
  getApiV1CreditsBalance,
1110
3878
  getApiV1CreditsPacks,
3879
+ getApiV1DeveloperApps,
3880
+ getApiV1DeveloperAppsByAppUuid,
3881
+ getApiV1DeveloperAppsByAppUuidApiKeys,
3882
+ getApiV1DeveloperAppsByAppUuidUsage,
3883
+ getApiV1DeveloperAppsByAppUuidUsageUsers,
3884
+ getApiV1DeveloperAppsByAppUuidUsers,
3885
+ getApiV1DeveloperAppsByAppUuidUsersByAddress,
3886
+ getApiV1DeveloperBilling,
1111
3887
  getApiV1DocsSwaggerJson,
1112
3888
  getApiV1Models,
3889
+ getApiV1Personas,
3890
+ getApiV1PersonasById,
3891
+ getApiV1PhoneCallsByCallId,
3892
+ getApiV1SubscriptionsPlans,
1113
3893
  getApiV1SubscriptionsStatus,
1114
- getApiV1Tasks,
1115
3894
  getApiV1Tools,
3895
+ getApiV1UsageInferenceWeekly,
3896
+ getApiV1UsageModels,
3897
+ getApiV1UserApiKeys,
3898
+ getApiV1WalletsBinding,
3899
+ getApiV1ZetaCreditRate,
3900
+ getApiV1ZetaMarket,
3901
+ getCostMicroUsd,
3902
+ getCreditsUsed,
1116
3903
  getHealth,
3904
+ getImageModel,
3905
+ getLogger,
3906
+ getToolCallEvents,
3907
+ isPiiRedactor,
3908
+ noopLogger,
3909
+ patchApiV1DeveloperAppsByAppUuid,
3910
+ patchApiV1DeveloperAppsByAppUuidUsersByAddress,
1117
3911
  postApiV1AdminAddCredits,
3912
+ postApiV1AdminAgents,
1118
3913
  postApiV1AdminApps,
1119
3914
  postApiV1AdminAppsByAppIdApiKeys,
3915
+ postApiV1AdminPersonas,
1120
3916
  postApiV1AdminSeedApps,
1121
3917
  postApiV1AdminSubscriptionTier,
1122
3918
  postApiV1ChatCompletions,
1123
- postApiV1CreditsClaimDaily,
1124
3919
  postApiV1CreditsPurchase,
1125
- postApiV1CreditsSyncSnag,
3920
+ postApiV1CreditsRedeemTokens,
3921
+ postApiV1DeveloperApps,
3922
+ postApiV1DeveloperAppsByAppUuidApiKeys,
3923
+ postApiV1DeveloperAppsByAppUuidFund,
3924
+ postApiV1DeveloperAppsByAppUuidPrivy,
3925
+ postApiV1DeveloperAppsByAppUuidUsersByAddressTopUp,
1126
3926
  postApiV1Embeddings,
3927
+ postApiV1PhoneCalls,
1127
3928
  postApiV1Responses,
1128
3929
  postApiV1SubscriptionsCancel,
3930
+ postApiV1SubscriptionsCancelScheduledDowngrade,
1129
3931
  postApiV1SubscriptionsCreateCheckoutSession,
1130
3932
  postApiV1SubscriptionsCustomerPortal,
1131
3933
  postApiV1SubscriptionsRenew,
3934
+ postApiV1SubscriptionsScheduleDowngrade,
3935
+ postApiV1SubscriptionsUpgrade,
1132
3936
  postApiV1SubscriptionsWebhook,
3937
+ postApiV1UserApiKeys,
3938
+ postApiV1WalletsBinding,
3939
+ postApiV1WalletsBindingNonce,
3940
+ postApiV1WebhooksRevenuecat,
1133
3941
  postAuthOauthByProviderExchange,
1134
3942
  postAuthOauthByProviderRefresh,
1135
3943
  postAuthOauthByProviderRevoke,
3944
+ putApiV1AdminAgentsById,
1136
3945
  putApiV1AdminAppsByAppIdApiKeysById,
1137
- putApiV1AdminAppsById
3946
+ putApiV1AdminAppsById,
3947
+ putApiV1AdminPersonasById,
3948
+ putApiV1AgentsByIdPreference,
3949
+ quantizeEmbedding,
3950
+ renderTemplate,
3951
+ resolvePiiRedactor,
3952
+ sanitizeQuotes,
3953
+ selectServerSideTools,
3954
+ setLogger,
3955
+ shouldAnalyzeStyle,
3956
+ toolSetSystemPrompts,
3957
+ withSseKeepalive
1138
3958
  };