@canonry/canonry 7.52.0 → 7.54.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 (147) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +24 -1
  2. package/assets/assets/AgentSetupPage-Dr7UsGcq.js +17 -0
  3. package/assets/assets/AuditHistoryPanel-Dg9ZNNQw.js +1 -0
  4. package/assets/assets/BacklinksPage-DSgwyFCi.js +1 -0
  5. package/assets/assets/{HistoryPage-aOd198dT.js → HistoryPage-DaX20IWP.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-FGhKdZAP.js +4 -0
  7. package/assets/assets/ProjectPage-BTJYS9gc.js +7 -0
  8. package/assets/assets/RunsPage-D06GJ47B.js +1 -0
  9. package/assets/assets/SettingsPage-MSgC8Zrc.js +1 -0
  10. package/assets/assets/SiteHealthSection-4PXTNjon.js +2 -0
  11. package/assets/assets/ToneBadge-AoUA_EpE.js +60 -0
  12. package/assets/assets/TrafficPage-DikPWmaU.js +40 -0
  13. package/assets/assets/TrafficSourceDetailPage-C1hfimWW.js +1 -0
  14. package/assets/assets/account-context-CHtJm4fz.js +1 -0
  15. package/assets/assets/card-BO6dtEV9.js +1 -0
  16. package/assets/assets/extract-error-message-Q9pkEqUE.js +1 -0
  17. package/assets/assets/{format-helpers-BWnMmkiO.js → format-helpers-Gj1ekh6p.js} +1 -1
  18. package/assets/assets/index-B8W65ejO.css +1 -0
  19. package/assets/assets/index-BBfEsbxI.js +56 -0
  20. package/assets/assets/query-client-C22j0Z7h.js +1 -0
  21. package/assets/assets/react-query-BLKqSvlU.js +1 -0
  22. package/assets/assets/{react-sigma_core.esm.min-hGyOC4V_.js → react-sigma_core.esm.min-j5DWE8Rk.js} +1 -1
  23. package/assets/assets/service-2DEngBCR.js +1 -0
  24. package/assets/index.html +9 -7
  25. package/dist/{ads-MREK2AGL.js → ads-A5S2NQBZ.js} +3 -3
  26. package/dist/{agent-4RUZ3MC4.js → agent-BV7G7QN7.js} +7 -7
  27. package/dist/{agent-ask-YLTYBEYH.js → agent-ask-5ALAHZ6T.js} +3 -3
  28. package/dist/{agent-conversations-QA6IKDGR.js → agent-conversations-MJPQCJYR.js} +3 -3
  29. package/dist/{agent-memory-MEQAJOB3.js → agent-memory-Z3VPA5KH.js} +3 -3
  30. package/dist/{agent-providers-AXYPDJHL.js → agent-providers-FP3LAZPG.js} +3 -3
  31. package/dist/{agent-transcript-SMNQNYCD.js → agent-transcript-4GXCOC73.js} +3 -3
  32. package/dist/{analytics-4OR64IGV.js → analytics-TOLSUYSN.js} +3 -3
  33. package/dist/{apply-CQXCFXAH.js → apply-EU5JAFVZ.js} +3 -3
  34. package/dist/{backfill-TMXCNVOB.js → backfill-3263IYJH.js} +9 -9
  35. package/dist/{backlinks-6KFAQGYV.js → backlinks-XQ5JTN6W.js} +3 -3
  36. package/dist/{bing-HFCACTAC.js → bing-LYHRD7BF.js} +3 -3
  37. package/dist/{bootstrap-SQVQXOJC.js → bootstrap-AKWTIMMH.js} +17 -9
  38. package/dist/{cdp-IACL7EXU.js → cdp-N4PQJWGQ.js} +7 -7
  39. package/dist/{chunk-K5I45PZI.js → chunk-2SY2FYFW.js} +556 -255
  40. package/dist/{chunk-KXAOMTXN.js → chunk-4LVJFSPH.js} +5 -5
  41. package/dist/{chunk-GNKOBKPW.js → chunk-5P7DSHNK.js} +4 -4
  42. package/dist/{chunk-6BPZHNDC.js → chunk-6WTSWWP6.js} +2 -2
  43. package/dist/{chunk-MJNUSPO4.js → chunk-75CFTTBF.js} +2 -2
  44. package/dist/{chunk-TALC5DX5.js → chunk-B37SDIGU.js} +1 -1
  45. package/dist/chunk-BQKKAPMW.js +1211 -0
  46. package/dist/{chunk-LK2BG6EX.js → chunk-D234NBWI.js} +11 -1
  47. package/dist/{chunk-QLPLENDT.js → chunk-EIG2V6UI.js} +1 -1
  48. package/dist/{chunk-MKAC7HKH.js → chunk-GFRIXUDK.js} +38 -4
  49. package/dist/{chunk-BBOHY2DQ.js → chunk-H6EQMYGT.js} +1 -1
  50. package/dist/{chunk-EGIZNSDA.js → chunk-J7VN3FZ3.js} +1 -1
  51. package/dist/{chunk-DSNSD5J3.js → chunk-K5MBEK4S.js} +19 -9
  52. package/dist/{chunk-SNFBJKAW.js → chunk-LCTYTGSE.js} +3 -3
  53. package/dist/{chunk-5N6245R7.js → chunk-MARVEIWH.js} +4 -4
  54. package/dist/{chunk-7XE2IRBG.js → chunk-OHVXKFQI.js} +1 -1
  55. package/dist/{chunk-O4RMPA6H.js → chunk-OMXWBR2R.js} +7294 -6533
  56. package/dist/{chunk-O77IBNVO.js → chunk-PFPTUCMG.js} +326 -324
  57. package/dist/{chunk-YSEC6TIB.js → chunk-PRNO5TLE.js} +1206 -405
  58. package/dist/{chunk-7244X3K6.js → chunk-QFKDFU73.js} +2 -2
  59. package/dist/chunk-R4AFXPM4.js +959 -0
  60. package/dist/{chunk-V5D4XNWV.js → chunk-RHCDUPD6.js} +39 -2
  61. package/dist/{chunk-AWCWIQAU.js → chunk-SKZVEZZK.js} +231 -5
  62. package/dist/{chunk-RVUCY4ZV.js → chunk-T63KVDWY.js} +6 -4
  63. package/dist/{chunk-IIOEAJTV.js → chunk-VB47PTY7.js} +3 -3
  64. package/dist/{chunk-ILDT4LPB.js → chunk-VCTP2RG6.js} +26 -240
  65. package/dist/{chunk-JY3RLZGB.js → chunk-VF7XGX2I.js} +1 -1
  66. package/dist/{chunk-I6KNMZ77.js → chunk-VMCVLESK.js} +4 -4
  67. package/dist/{chunk-R2J4SNKF.js → chunk-WDJMIIY2.js} +1 -1
  68. package/dist/{chunk-BU3VAG5J.js → chunk-XJVCTI2N.js} +3 -3
  69. package/dist/{chunk-HEGXGCGL.js → chunk-Y2YBRLSS.js} +3 -3
  70. package/dist/{chunk-Y4GK7GCV.js → chunk-YOZ35ZTT.js} +1 -1
  71. package/dist/{chunk-BYOK6Z4F.js → chunk-ZA7D7CCN.js} +2 -2
  72. package/dist/{chunk-FC4XND45.js → chunk-ZILJZNMQ.js} +1 -1
  73. package/dist/{citations-NSBBWRZ4.js → citations-JK3ZMAR7.js} +3 -3
  74. package/dist/{cli-catalog-OFWJMNMD.js → cli-catalog-P2I6IYNI.js} +3 -3
  75. package/dist/{cli-commands-WVBL337U.js → cli-commands-YDRKG6OC.js} +7 -7
  76. package/dist/cli.js +13 -13
  77. package/dist/{competitor-V4OHORBC.js → competitor-5CJPM36M.js} +3 -3
  78. package/dist/{content-RUXRI5IC.js → content-5FEDXNHR.js} +3 -3
  79. package/dist/{dashboard-JXB2YAQJ.js → dashboard-ME7MBJTX.js} +6 -6
  80. package/dist/{demo-55ZNUOXU.js → demo-N7MEASQP.js} +1 -1
  81. package/dist/{demo-server-XO7PHM4I.js → demo-server-IGTBANDC.js} +11 -11
  82. package/dist/{discover-JJQ564HS.js → discover-EAISVTA6.js} +3 -3
  83. package/dist/{discover-eval-KLEKZ6U4.js → discover-eval-JIBKK44Q.js} +3 -3
  84. package/dist/{doctor-JAMQZCMZ.js → doctor-HSQYOZ4C.js} +3 -3
  85. package/dist/{evidence-YRSB7GFE.js → evidence-PSYAWKPP.js} +3 -3
  86. package/dist/{export-cmd-MHML4OYU.js → export-cmd-MWJN6H7W.js} +3 -3
  87. package/dist/{ga-LSXPE2MN.js → ga-WSQWECYY.js} +3 -3
  88. package/dist/{gbp-RMKMLOC7.js → gbp-OD26AEPF.js} +3 -3
  89. package/dist/{google-JQ4T6JTQ.js → google-FMJ7IWAF.js} +4 -4
  90. package/dist/{google-marketing-J6SEODYC.js → google-marketing-66JL4V24.js} +1 -1
  91. package/dist/{health-cmd-MV2JM2C3.js → health-cmd-2RO5LAI4.js} +3 -3
  92. package/dist/{history-SRRH7A2E.js → history-X6CNPW7G.js} +3 -3
  93. package/dist/index.d.ts +518 -50
  94. package/dist/index.js +24 -23
  95. package/dist/{init-ZJZFUERV.js → init-25III66S.js} +11 -11
  96. package/dist/{insights-PMMGNWZH.js → insights-6IWWA6JU.js} +3 -3
  97. package/dist/intelligence-service-N334P6FH.js +15 -0
  98. package/dist/{keys-TS7NZANS.js → keys-ABXAPISY.js} +3 -3
  99. package/dist/{keyword-VNCKDUGC.js → keyword-LERAVMI3.js} +3 -3
  100. package/dist/{logs-VH3WOTZJ.js → logs-BTAB5SNZ.js} +3 -3
  101. package/dist/{mcp-DG2RROB3.js → mcp-5E42RT6R.js} +2 -2
  102. package/dist/mcp.js +9 -9
  103. package/dist/{measurement-plan-4T35TUGG.js → measurement-plan-MRZRNBJG.js} +5 -5
  104. package/dist/{notify-BWHUSKL7.js → notify-YQYGC5UZ.js} +3 -3
  105. package/dist/{organic-evidence-QX4SXXJP.js → organic-evidence-6QT4YT3K.js} +3 -3
  106. package/dist/{overview-7IHUTKUV.js → overview-EHZ3FTS2.js} +4 -4
  107. package/dist/{project-JXLSWDE2.js → project-RNLV2ARE.js} +3 -3
  108. package/dist/{query-S75EL25H.js → query-IM2RXI4L.js} +3 -3
  109. package/dist/{research-KFTV3IP4.js → research-4FALR336.js} +25 -10
  110. package/dist/{results-export-GTKVBU34.js → results-export-4ETSRUGO.js} +3 -3
  111. package/dist/{run-26HDIRHF.js → run-QL7226N7.js} +4 -4
  112. package/dist/{schedule-N6G4SVHQ.js → schedule-GJE634VO.js} +3 -3
  113. package/dist/{search-MI32EPYM.js → search-7OQL67R6.js} +3 -3
  114. package/dist/{serve-XLGE42AG.js → serve-UN2OEK2Q.js} +25 -24
  115. package/dist/{session-W5DXWIYM.js → session-5M54TVY5.js} +16 -15
  116. package/dist/{settings-T7WI2UVE.js → settings-2QOL7YBM.js} +15 -3
  117. package/dist/{skills-F3WPKPTK.js → skills-GPLAAU3I.js} +2 -2
  118. package/dist/{snapshot-PD3EAVEX.js → snapshot-5YMJFRJS.js} +8 -6
  119. package/dist/{src-XDUXMJC3.js → src-YF3JLURF.js} +2 -2
  120. package/dist/{status-PUH7JFZ4.js → status-WGWC6FLN.js} +33 -5
  121. package/dist/{technical-aeo-AUFWWJIP.js → technical-aeo-RNMLD7OL.js} +3 -3
  122. package/dist/{telemetry-XBYT7G2K.js → telemetry-7U3ZICU4.js} +4 -4
  123. package/dist/{tools-GVHIRWSN.js → tools-CSKTZTKT.js} +11 -11
  124. package/dist/{traffic-B3HW2ZWG.js → traffic-QIAXLW6J.js} +5 -5
  125. package/dist/{users-M5HNQZYI.js → users-I6X5P5AO.js} +3 -3
  126. package/dist/{visibility-stats-Y7GJKMHN.js → visibility-stats-33OUKQQL.js} +3 -3
  127. package/dist/{wordpress-GCIURYPN.js → wordpress-3IO3O27D.js} +3 -3
  128. package/package.json +3 -1
  129. package/assets/assets/AccessControls-CteIuEGI.js +0 -1
  130. package/assets/assets/AuditHistoryPanel-DqJGiLsf.js +0 -1
  131. package/assets/assets/BacklinksPage-DotWEPQt.js +0 -1
  132. package/assets/assets/MeasurementPropertyPage-CuaKVK8x.js +0 -4
  133. package/assets/assets/ProjectPage-O9oufMgi.js +0 -8
  134. package/assets/assets/RunsPage-DIXMrc-N.js +0 -1
  135. package/assets/assets/SettingsPage-BuGb6AGa.js +0 -1
  136. package/assets/assets/SiteHealthSection-CweaKjCo.js +0 -2
  137. package/assets/assets/TrafficPage-B7MaQalp.js +0 -40
  138. package/assets/assets/TrafficSourceDetailPage-BPtjnF9s.js +0 -1
  139. package/assets/assets/card-DoV-8Txo.js +0 -60
  140. package/assets/assets/extract-error-message-DKQJJlZ-.js +0 -1
  141. package/assets/assets/index-CsPsaUr7.css +0 -1
  142. package/assets/assets/index-Z63c4PeO.js +0 -39
  143. package/assets/assets/query-client-vB35tVTz.js +0 -1
  144. package/assets/assets/react-query-BI0567qs.js +0 -1
  145. package/assets/assets/service-c4YvpVKX.js +0 -1
  146. package/dist/chunk-OFL4PTYU.js +0 -644
  147. package/dist/intelligence-service-KCSU6ZUJ.js +0 -15
@@ -6,14 +6,14 @@ import {
6
6
  isSelfTraffic,
7
7
  normalizeCloudflareWorkerEvent,
8
8
  verifyRequestSignature
9
- } from "./chunk-Y4GK7GCV.js";
9
+ } from "./chunk-YOZ35ZTT.js";
10
10
  import {
11
11
  currentOutcomeAttribution,
12
12
  getRequestContext,
13
13
  registerRequestContext,
14
14
  requestAuditIdentity,
15
15
  sanitizeRequestContext
16
- } from "./chunk-QLPLENDT.js";
16
+ } from "./chunk-EIG2V6UI.js";
17
17
  import {
18
18
  SentimentIdempotencyConflict,
19
19
  SentimentRepository,
@@ -142,13 +142,14 @@ import {
142
142
  userSessions,
143
143
  users,
144
144
  writeNegativeReviewMaxStars
145
- } from "./chunk-MKAC7HKH.js";
145
+ } from "./chunk-GFRIXUDK.js";
146
146
  import {
147
147
  ADS_ACTIVATE_SCOPE,
148
148
  ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
149
149
  ADS_ACTIVATION_MAX_ENTITIES,
150
150
  ADS_APPROVE_SCOPE,
151
151
  ADS_WRITE_SCOPE,
152
+ AGENT_PROVIDER_IDS,
152
153
  AI_PROVIDER_INFRA_DOMAINS,
153
154
  AI_REFERRAL_ENGINE_DEFINITIONS,
154
155
  AUTO_ALIAS_SCAN_MAX_RUNS,
@@ -273,6 +274,7 @@ import {
273
274
  MeasurementPortfolioLists,
274
275
  MeasurementRunScopeError,
275
276
  MentionIdentities,
277
+ OPENROUTER_ROUTE_FAMILY,
276
278
  OPERATIONAL_LOG_FIELDS_HEADER,
277
279
  OPERATIONAL_LOG_OPT_IN_CONTEXT_FIELDS,
278
280
  OPERATION_ACCESS_HEADER,
@@ -288,6 +290,9 @@ import {
288
290
  PROVIDER_ACCOUNT_RETRY_HOURS,
289
291
  PROVIDER_NAMES,
290
292
  ProviderDispatchModes,
293
+ ProviderKinds,
294
+ ProviderNames,
295
+ ProviderWorkflows,
291
296
  READ_ONLY_SCOPE,
292
297
  RESEARCH_RUN_SCOPE,
293
298
  RUN_FILL_MAX_AGE_MS,
@@ -301,7 +306,6 @@ import {
301
306
  RunTriggers,
302
307
  SENTIMENT_ATTEMPT_PAGE_DEFAULT,
303
308
  SENTIMENT_INTERVAL_LIMITATION,
304
- SENTIMENT_MODEL,
305
309
  SENTIMENT_QUERY_PAGE_DEFAULT,
306
310
  SITE_AUDIT_ISSUES_DEFAULT_LIMIT,
307
311
  SITE_CRAWL_GRAPH_DEFAULT_MAX_EDGES,
@@ -668,16 +672,19 @@ import {
668
672
  internalError,
669
673
  intersectScopes,
670
674
  isBrowserProvider,
675
+ isEligibleFor,
671
676
  isFetchTransportError,
672
677
  isGa4AiAssistantChannel,
673
678
  isListingMarketplace,
674
679
  isLocationRedirectStatus,
675
680
  isNegativeReviewRating,
676
681
  isProviderAccountFailure,
682
+ isProviderAvailable,
677
683
  isReadOnlyKey,
678
684
  isRedactedNotificationUrl,
679
685
  isRetryableHttpError,
680
686
  isStrictSemver,
687
+ isSweepProvider,
681
688
  isVertexGroundingRedirect,
682
689
  isVisibilityCompareClassMetric,
683
690
  isoDateDaysBeforeInTimeZone,
@@ -689,6 +696,7 @@ import {
689
696
  locationContextSchema,
690
697
  logQuerySchema,
691
698
  loginRequestSchema,
699
+ makesInstallMeasurable,
692
700
  mapWithConcurrency,
693
701
  marketPinAliasClaims,
694
702
  matchOperationTemplate,
@@ -729,6 +737,7 @@ import {
729
737
  measurementDraftPreviewAssignmentsResponseSchema,
730
738
  measurementDraftPreviewGroupMembershipRequestSchema,
731
739
  measurementDraftPreviewGroupMembershipResponseSchema,
740
+ measurementDraftPreviewMarketRoutingResponseSchema,
732
741
  measurementDraftPublishRequestSchema,
733
742
  measurementDraftRebindTargetRequestSchema,
734
743
  measurementDraftRemoveAssignmentRequestSchema,
@@ -737,6 +746,7 @@ import {
737
746
  measurementDraftRenameTargetRequestSchema,
738
747
  measurementDraftReplaceAssignmentsRequestSchema,
739
748
  measurementDraftResponseSchema,
749
+ measurementDraftRouteMarketsRequestSchema,
740
750
  measurementDraftTargetPageSchema,
741
751
  measurementDraftUpsertCompetitorRequestSchema,
742
752
  measurementDraftUpsertGroupRequestSchema,
@@ -824,6 +834,7 @@ import {
824
834
  notificationDtoSchema,
825
835
  notificationEventSchema,
826
836
  onboardingTelemetryEventSchema,
837
+ openRouterRouteModel,
827
838
  operationAccess,
828
839
  operationInProgress,
829
840
  operationalLogListDtoSchema,
@@ -856,10 +867,12 @@ import {
856
867
  projectSearchResponseSchema,
857
868
  projectUpsertRequestSchema,
858
869
  providerAuthError,
870
+ providerConnectionName,
859
871
  providerDispatchModeSchema,
860
872
  providerError,
861
873
  providerReloadRequestSchema,
862
874
  providerReloadResponseDtoSchema,
875
+ providerRouteName,
863
876
  providerSummaryEntryDtoSchema,
864
877
  providersFailing,
865
878
  qualifiedNameIncludesName,
@@ -901,6 +914,7 @@ import {
901
914
  resolveNegativeReviewMaxStars,
902
915
  resolveProjectQualifiedAliases,
903
916
  resolveProviderModel,
917
+ resolveProviderRoute,
904
918
  resolveRunDispatchModes,
905
919
  resolveSnapshotRequestQueries,
906
920
  restrictedWriteScopes,
@@ -910,6 +924,7 @@ import {
910
924
  retrievedSourceSchema,
911
925
  retryAfterDelayMs,
912
926
  roundRatio,
927
+ routeFamiliesOf,
913
928
  runAdmissionDtoSchema,
914
929
  runCompletenessDtoSchema,
915
930
  runDetailDtoSchema,
@@ -939,6 +954,7 @@ import {
939
954
  sentimentBackfillSelectionSchema,
940
955
  sentimentCompareRequestSchema,
941
956
  sentimentComparisonSchema,
957
+ sentimentEvaluatorProvider,
942
958
  sentimentEvidencePageSchema,
943
959
  sentimentEvidenceRequestSchema,
944
960
  sentimentJobRequestSchema,
@@ -1058,7 +1074,7 @@ import {
1058
1074
  wordpressSchemaDeployResultDtoSchema,
1059
1075
  wordpressSchemaStatusResultDtoSchema,
1060
1076
  wordpressStatusDtoSchema
1061
- } from "./chunk-O4RMPA6H.js";
1077
+ } from "./chunk-OMXWBR2R.js";
1062
1078
 
1063
1079
  // ../api-routes/src/user-session.ts
1064
1080
  import crypto2 from "crypto";
@@ -6531,6 +6547,114 @@ function registerAgentConversationRoutes(app, opts) {
6531
6547
  });
6532
6548
  }
6533
6549
 
6550
+ // ../api-routes/src/egress-policy.ts
6551
+ import net from "net";
6552
+ function blockedAddressReason(value, options = {}) {
6553
+ const address = stripZoneId(stripIpv6Brackets(value));
6554
+ if (options.allowLoopback && isLoopbackAddress(address)) return null;
6555
+ const family = net.isIP(address);
6556
+ if (family === 4) return blockedIpv4Reason(ipv4Octets(address));
6557
+ if (family === 6) {
6558
+ const bytes = ipv6Bytes(address);
6559
+ return bytes ? blockedIpv6Reason(bytes) : "which could not be read as an address";
6560
+ }
6561
+ return "which is not an IP address";
6562
+ }
6563
+ function isLoopbackAddress(value) {
6564
+ const address = stripZoneId(stripIpv6Brackets(value));
6565
+ const family = net.isIP(address);
6566
+ if (family === 4) return ipv4Octets(address)[0] === 127;
6567
+ if (family !== 6) return false;
6568
+ const bytes = ipv6Bytes(address);
6569
+ if (!bytes) return false;
6570
+ const mapped = mappedIpv4(bytes);
6571
+ if (mapped) return mapped[0] === 127;
6572
+ return bytes.slice(0, 15).every((byte) => byte === 0) && bytes[15] === 1;
6573
+ }
6574
+ function stripIpv6Brackets(value) {
6575
+ return value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
6576
+ }
6577
+ function stripZoneId(address) {
6578
+ return address.split("%")[0];
6579
+ }
6580
+ function ipv4Octets(address) {
6581
+ return address.split(".").map((part) => Number.parseInt(part, 10));
6582
+ }
6583
+ function blockedIpv4Reason(octets) {
6584
+ const [first, second] = octets;
6585
+ if (first === 0) return "which is unspecified space";
6586
+ if (first === 127) return "which is loopback";
6587
+ if (first === 10 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168) {
6588
+ return "which is private space";
6589
+ }
6590
+ if (first === 100 && second >= 64 && second <= 127) return "which is carrier-grade NAT space";
6591
+ if (first === 169 && second === 254) return "which is link-local";
6592
+ if (first >= 224 && first <= 239) return "which is multicast";
6593
+ if (first === 192 && second === 0 && octets[2] === 0 || first === 198 && (second === 18 || second === 19) || first >= 240) {
6594
+ return "which is reserved";
6595
+ }
6596
+ return null;
6597
+ }
6598
+ function blockedIpv6Reason(bytes) {
6599
+ const first = bytes[0];
6600
+ if (first === 0) {
6601
+ const nat64 = nat64Ipv4(bytes);
6602
+ if (nat64) return blockedIpv4Reason(nat64) === null ? null : `which is the NAT64 form of ${nat64.join(".")}`;
6603
+ const mapped = mappedIpv4(bytes);
6604
+ return mapped ? `which is the IPv6 form of ${mapped.join(".")}` : "which is reserved IPv6 space";
6605
+ }
6606
+ if (first === 1 && bytes.slice(1, 8).every((byte) => byte === 0)) return "which is reserved IPv6 space";
6607
+ if (first === 255) return "which is multicast";
6608
+ if ((first & 254) === 252) return "which is unique-local";
6609
+ if (first === 254 && (bytes[1] & 192) === 128) return "which is link-local";
6610
+ if (first === 254 && (bytes[1] & 192) === 192) return "which is reserved site-local space";
6611
+ if (first === 32 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0) return "which is a Teredo tunnel";
6612
+ if (first === 32 && bytes[1] === 2) return "which is a 6to4 tunnel";
6613
+ if (first === 32 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 2 && bytes[4] === 0 && bytes[5] === 0) {
6614
+ return "which is reserved IPv6 space";
6615
+ }
6616
+ return null;
6617
+ }
6618
+ function mappedIpv4(bytes) {
6619
+ const isMapped = bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 255 && bytes[11] === 255;
6620
+ return isMapped ? [bytes[12], bytes[13], bytes[14], bytes[15]] : null;
6621
+ }
6622
+ var NAT64_WELL_KNOWN_PREFIX = [0, 100, 255, 155, 0, 0, 0, 0, 0, 0, 0, 0];
6623
+ function nat64Ipv4(bytes) {
6624
+ const isNat64 = NAT64_WELL_KNOWN_PREFIX.every((byte, index) => bytes[index] === byte);
6625
+ return isNat64 ? [bytes[12], bytes[13], bytes[14], bytes[15]] : null;
6626
+ }
6627
+ function ipv6Bytes(address) {
6628
+ if (!net.isIPv6(address)) return null;
6629
+ const halves = address.split("::");
6630
+ if (halves.length > 2) return null;
6631
+ const expand = (text) => {
6632
+ if (text === "") return [];
6633
+ const groups2 = [];
6634
+ const chunks = text.split(":");
6635
+ for (const [index, chunk] of chunks.entries()) {
6636
+ if (index === chunks.length - 1 && chunk.includes(".")) {
6637
+ const octets = ipv4Octets(chunk);
6638
+ groups2.push(octets[0] << 8 | octets[1], octets[2] << 8 | octets[3]);
6639
+ continue;
6640
+ }
6641
+ groups2.push(Number.parseInt(chunk, 16));
6642
+ }
6643
+ return groups2;
6644
+ };
6645
+ const head = expand(halves[0]);
6646
+ const tail = halves.length === 2 ? expand(halves[1]) : [];
6647
+ const missing = 8 - head.length - tail.length;
6648
+ if (halves.length === 1 ? missing !== 0 : missing < 0) return null;
6649
+ const groups = [...head, ...new Array(halves.length === 2 ? missing : 0).fill(0), ...tail];
6650
+ const bytes = new Uint8Array(16);
6651
+ for (const [index, group] of groups.entries()) {
6652
+ bytes[index * 2] = group >> 8;
6653
+ bytes[index * 2 + 1] = group & 255;
6654
+ }
6655
+ return bytes;
6656
+ }
6657
+
6534
6658
  // ../api-routes/src/index.ts
6535
6659
  import rateLimit from "@fastify/rate-limit";
6536
6660
  import fs8 from "fs";
@@ -6846,11 +6970,11 @@ function indexedPlan(db, projectId, versionId, cache2) {
6846
6970
  for (const query of plan.querySnapshots) keep(queryTexts, query.queryId, query.queryText);
6847
6971
  const groupKeys = /* @__PURE__ */ new Map(), marketKeys = /* @__PURE__ */ new Map();
6848
6972
  for (const group of plan.groups) for (const targetKey of new Set(group.targetKeys)) append(groupKeys, targetKey, group.stableKey);
6849
- for (const scope of plan.reportingScopes ?? []) for (const edgeKey2 of new Set(scope.usageEdges.map(measurementV2UsageEdgeKey))) append(marketKeys, edgeKey2, scope.stableKey);
6973
+ for (const scope of plan.reportingScopes ?? []) for (const edgeKey3 of new Set(scope.usageEdges.map(measurementV2UsageEdgeKey))) append(marketKeys, edgeKey3, scope.stableKey);
6850
6974
  const usages = [], usagesByNodeTarget = /* @__PURE__ */ new Map();
6851
6975
  for (const edge of plan.usageEdges) {
6852
- const edgeKey2 = measurementV2UsageEdgeKey(edge);
6853
- const usage = { edge, assignment: assignments.get(edgeKey2), queryText: queryTexts.get(edge.queryId), marketKeys: marketKeys.get(edgeKey2) ?? [] };
6976
+ const edgeKey3 = measurementV2UsageEdgeKey(edge);
6977
+ const usage = { edge, assignment: assignments.get(edgeKey3), queryText: queryTexts.get(edge.queryId), marketKeys: marketKeys.get(edgeKey3) ?? [] };
6854
6978
  usages.push(usage);
6855
6979
  append(usagesByNodeTarget, pairKey(edge.executionNodeKey, edge.targetKey), usage);
6856
6980
  }
@@ -6957,9 +7081,11 @@ var SentimentService = class {
6957
7081
  settings(projectId, administrator = false) {
6958
7082
  const install = this.options.install();
6959
7083
  const row = this.repository.getSettings(projectId);
6960
- const supportedDefinition = !row || hasCurrentSentimentTemplate(this.definition(row.evaluationDefinitionId));
7084
+ const definition2 = row ? this.definition(row.evaluationDefinitionId) : null;
7085
+ const supportedDefinition = !definition2 || hasCurrentSentimentTemplate(definition2) && sentimentEvaluatorProvider(definition2) === (install.provider ?? "typesafe") && definition2.requestedModel === install.model;
6961
7086
  const pause = this.repository.dispatchState();
6962
- const pauseReason = pause?.blockedReason === "provider-authorization" ? "provider-authorization: TypeSafe rejected the configured credentials. Dispatch is paused for every project until the key changes; one request retries each hour." : pause?.blockedReason === "provider-rate-limit" && pause.nextDispatchAt ? `provider-rate-limit: TypeSafe is rate limiting this install. Dispatch resumes after ${pause.nextDispatchAt}.` : null;
7087
+ const evaluatorLabel = install.provider === "openrouter" ? "OpenRouter" : "TypeSafe";
7088
+ const pauseReason = pause?.blockedReason === "provider-authorization" ? `provider-authorization: ${evaluatorLabel} rejected the configured credentials. Dispatch is paused for every project until the key changes; one request retries each hour.` : pause?.blockedReason === "provider-rate-limit" && pause.nextDispatchAt ? `provider-rate-limit: ${evaluatorLabel} is rate limiting this install. Dispatch resumes after ${pause.nextDispatchAt}.` : null;
6963
7089
  const ready = install.ready && supportedDefinition && pause?.blockedReason !== "provider-authorization";
6964
7090
  return {
6965
7091
  installEnabled: install.enabled,
@@ -6967,13 +7093,14 @@ var SentimentService = class {
6967
7093
  ready,
6968
7094
  readinessReasons: [...install.reason ? [install.reason] : [], ...!supportedDefinition ? ["unsupported-evaluator-definition: configure sentiment again to use the current evaluator."] : [], ...pauseReason ? [pauseReason] : []],
6969
7095
  model: install.model,
7096
+ provider: install.provider ?? "typesafe",
6970
7097
  enablementEpoch: row?.enablementEpoch ?? 0,
6971
7098
  completionBoundary: row?.completionBoundary ?? 0,
6972
7099
  evaluationDefinitionId: row?.evaluationDefinitionId ?? null,
6973
7100
  // A project that is still on can always be switched off, even while the install switch is off.
6974
7101
  actions: { configure: administrator && (install.enabled || Boolean(row?.enabled)), backfill: administrator && ready && Boolean(row?.enabled) },
6975
7102
  experimental: true,
6976
- disclosure: DISCLOSURE
7103
+ disclosure: install.provider === "openrouter" ? DISCLOSURE.replace("to TypeSafe", "to OpenRouter for the pinned TypeSafe Jev evaluator") : DISCLOSURE
6977
7104
  };
6978
7105
  }
6979
7106
  configure(projectId, value, actor = "system") {
@@ -6983,10 +7110,10 @@ var SentimentService = class {
6983
7110
  if (enabled && !previous.installEnabled) throw validationError("Sentiment is disabled in install configuration.");
6984
7111
  if (enabled && !this.options.install().ready) throw validationError("Sentiment provider is not ready.", { reasons: previous.readinessReasons });
6985
7112
  const configuration = { enabled };
6986
- const definition2 = createSentimentEvaluationDefinition();
7113
+ const definition2 = createSentimentEvaluationDefinition(this.options.install().provider);
6987
7114
  const definitionId = sentimentHash(definition2);
6988
- this.repository.putDefinition({ id: definitionId, contentHash: definitionId, requestedModel: SENTIMENT_MODEL, definition: definition2, createdAt: this.now() });
6989
- this.repository.configure({ projectId, enabled: configuration.enabled, evaluationDefinitionId: definitionId, configuration, actor, now: this.now(), forceNewEpoch: Boolean(previous.evaluationDefinitionId && !hasCurrentSentimentTemplate(this.definition(previous.evaluationDefinitionId))) });
7115
+ this.repository.putDefinition({ id: definitionId, contentHash: definitionId, requestedModel: definition2.requestedModel, definition: definition2, createdAt: this.now() });
7116
+ this.repository.configure({ projectId, enabled: configuration.enabled, evaluationDefinitionId: definitionId, configuration, actor, now: this.now(), forceNewEpoch: Boolean(previous.evaluationDefinitionId && previous.evaluationDefinitionId !== definitionId) });
6990
7117
  return this.settings(projectId, true);
6991
7118
  }
6992
7119
  disabled(projectId) {
@@ -7017,7 +7144,7 @@ var SentimentService = class {
7017
7144
  const source = selectSentimentSources(this.db, projectId, sourceFilter(selection));
7018
7145
  const frozenSelection = selection.runId ? { ...selection, runId: source.runIds[0] } : source.runIds.length ? { ...selection, runIds: source.runIds } : selection;
7019
7146
  const definitionId = settings.evaluationDefinitionId;
7020
- const definition2 = definitionId ? this.definition(definitionId) : createSentimentEvaluationDefinition();
7147
+ const definition2 = definitionId ? this.definition(definitionId) : createSentimentEvaluationDefinition(this.options.install().provider);
7021
7148
  const inputs = source.assessments.map((item2) => sentimentClassifierInput(item2, definition2));
7022
7149
  const existing = definitionId && source.runIds.length ? this.db.select({ snapshotId: sentimentWorkItems.snapshotId, sourceTextHash: sentimentWorkItems.sourceTextHash, subjectHash: sentimentWorkItems.subjectHash }).from(sentimentWorkItems).innerJoin(sentimentResults, eq15(sentimentResults.workItemId, sentimentWorkItems.id)).where(and9(eq15(sentimentWorkItems.projectId, projectId), eq15(sentimentWorkItems.evaluationDefinitionId, definitionId), inArray6(sentimentWorkItems.runId, source.runIds))).all() : [];
7023
7150
  const completed = new Set(existing.map((work) => `${work.snapshotId}:${work.sourceTextHash}:${work.subjectHash}`));
@@ -7723,6 +7850,7 @@ function registerOAuthRoutesIn(app, opts) {
7723
7850
  }
7724
7851
  );
7725
7852
  const { db, issuer } = opts;
7853
+ const authorizationPath = opts.authorizationPath ?? "/oauth/authorize";
7726
7854
  const resourcePaths = opts.resourcePaths;
7727
7855
  const canonicalPath = resourcePaths[0] ?? "/api/v1/mcp";
7728
7856
  const resourceUrl = `${issuer}${canonicalPath}`;
@@ -7732,7 +7860,7 @@ function registerOAuthRoutesIn(app, opts) {
7732
7860
  function authorizationServerMetadata() {
7733
7861
  return {
7734
7862
  issuer,
7735
- authorization_endpoint: `${issuer}/oauth/authorize`,
7863
+ authorization_endpoint: `${issuer}${authorizationPath}`,
7736
7864
  token_endpoint: `${issuer}/oauth/token`,
7737
7865
  revocation_endpoint: `${issuer}/oauth/revoke`,
7738
7866
  // RFC 7591. The current MCP revision calls DCR deprecated and prefers
@@ -7763,7 +7891,19 @@ function registerOAuthRoutesIn(app, opts) {
7763
7891
  }));
7764
7892
  }
7765
7893
  app.get("/.well-known/oauth-authorization-server", async () => authorizationServerMetadata());
7766
- app.get("/oauth/authorize", async (request, reply) => {
7894
+ if (authorizationPath !== "/oauth/authorize") {
7895
+ for (const suffix of ["", "/consent"]) {
7896
+ app.route({
7897
+ method: suffix ? ["POST"] : ["GET", "POST"],
7898
+ url: `/oauth/authorize${suffix}`,
7899
+ handler: async (request, reply) => {
7900
+ const query = request.url.includes("?") ? request.url.slice(request.url.indexOf("?")) : "";
7901
+ return reply.redirect(`${authorizationPath}${suffix}${query}`, 307);
7902
+ }
7903
+ });
7904
+ }
7905
+ }
7906
+ app.get(authorizationPath, async (request, reply) => {
7767
7907
  const q = request.query;
7768
7908
  const clientId = q.client_id;
7769
7909
  const redirectUri = q.redirect_uri;
@@ -7798,7 +7938,7 @@ function registerOAuthRoutesIn(app, opts) {
7798
7938
  csrf: consentToken(user.id, clientId, redirectUri, grantedScope)
7799
7939
  }));
7800
7940
  });
7801
- app.post("/oauth/authorize/consent", async (request, reply) => {
7941
+ app.post(`${authorizationPath}/consent`, async (request, reply) => {
7802
7942
  assertCookieWriteOrigin(request);
7803
7943
  const q = request.query;
7804
7944
  const body = request.body ?? {};
@@ -7908,7 +8048,7 @@ function registerOAuthRoutesIn(app, opts) {
7908
8048
  token_endpoint_auth_method: "none"
7909
8049
  });
7910
8050
  });
7911
- app.post("/oauth/authorize", async (request, reply) => {
8051
+ app.post(authorizationPath, async (request, reply) => {
7912
8052
  assertCookieWriteOrigin(request);
7913
8053
  const body = request.body ?? {};
7914
8054
  const name = body.name?.trim();
@@ -8614,30 +8754,214 @@ function connectionRoute(app, subjectOf, handler) {
8614
8754
  };
8615
8755
  }
8616
8756
 
8757
+ // ../api-routes/src/provider-models.ts
8758
+ function providerRouteFamilies(adapters) {
8759
+ return routeFamiliesOf(adapters);
8760
+ }
8761
+ function assertProviderRouteScope(request, selected, authorized, families) {
8762
+ const saved = new Set(authorized.map((name) => name.trim().toLowerCase()));
8763
+ if (selected.some((name) => resolveProviderRoute(name.trim().toLowerCase(), families) && !saved.has(name.trim().toLowerCase()))) {
8764
+ requireScope(request, SETTINGS_WRITE_SCOPE);
8765
+ }
8766
+ }
8767
+ var assertOpenRouterRouteScope = assertProviderRouteScope;
8768
+ function invalidProviderSelections(names, available, adapters, workflow) {
8769
+ const families = providerRouteFamilies(adapters);
8770
+ return names.filter((name) => {
8771
+ if (!isSweepProvider(name, families) || !isProviderAvailable(name, available, families)) return true;
8772
+ const adapter = adapters ? providerAdapterForName(name, adapters) : void 0;
8773
+ return adapter !== void 0 && !isEligibleFor(adapter, workflow, "explicit");
8774
+ });
8775
+ }
8776
+ function providerEligibleFor(name, adapters, workflow, selection) {
8777
+ const families = providerRouteFamilies(adapters);
8778
+ if (!isSweepProvider(name, families)) return false;
8779
+ const adapter = adapters ? providerAdapterForName(name, adapters) : void 0;
8780
+ return adapter === void 0 ? selection === "explicit" : isEligibleFor(adapter, workflow, selection);
8781
+ }
8782
+ function pinnedRouteSelection(name, families) {
8783
+ return resolveProviderRoute(name, families)?.selection;
8784
+ }
8785
+ function providerAdapterForName(name, adapters) {
8786
+ const direct = adapters.find((adapter) => adapter.name === name);
8787
+ if (direct) return direct;
8788
+ const route = resolveProviderRoute(name, providerRouteFamilies(adapters));
8789
+ const connection = route && adapters.find((adapter) => adapter.name === route.connection);
8790
+ if (!connection || !route) return void 0;
8791
+ if (route.family.selectionKind === "profile") {
8792
+ const profile = connection.profiles?.find((item2) => item2.id === route.selection);
8793
+ if (!profile) return void 0;
8794
+ return {
8795
+ ...connection,
8796
+ name,
8797
+ displayName: `${profile.displayName} \xB7 ${connection.displayName}`,
8798
+ modelConfigurable: false,
8799
+ defaultModel: profile.id,
8800
+ knownModels: [{ id: profile.id, displayName: profile.displayName, tier: "standard" }],
8801
+ modelValidationPattern: new RegExp(`^${escapeRegExp(profile.id)}$`),
8802
+ modelValidationHint: `The ${connection.displayName} route pins its profile; select another route to change it.`,
8803
+ capabilities: { textGeneration: false, groundedAnswer: true, workflows: [...profile.workflows] },
8804
+ profiles: [profile]
8805
+ };
8806
+ }
8807
+ const model = route.selection;
8808
+ connection.modelValidationPattern.lastIndex = 0;
8809
+ if (!connection.modelValidationPattern.test(model)) return void 0;
8810
+ const known = connection.knownModels.find((entry) => entry.id === model);
8811
+ return {
8812
+ ...connection,
8813
+ name,
8814
+ displayName: `${known?.displayName ?? model} via ${connection.displayName}`,
8815
+ modelConfigurable: false,
8816
+ defaultModel: model,
8817
+ knownModels: known ? [known] : [],
8818
+ modelValidationHint: `The ${connection.displayName} route pins its model; select another route to change it.`
8819
+ };
8820
+ }
8821
+ function validateProviderModels(models, adapters) {
8822
+ const entries = Object.entries(models);
8823
+ if (entries.length === 0) return {};
8824
+ if (!adapters || adapters.length === 0) {
8825
+ throw validationError("Project model overrides are unavailable because provider metadata is not configured.");
8826
+ }
8827
+ const normalized = {};
8828
+ for (const [provider, rawModel] of entries) {
8829
+ const adapter = providerAdapterForName(provider, adapters);
8830
+ if (!adapter) {
8831
+ throw validationError(`Invalid provider model override: unknown provider "${provider}".`, {
8832
+ provider,
8833
+ validProviders: adapters.map((item2) => item2.name)
8834
+ });
8835
+ }
8836
+ const route = resolveProviderRoute(provider, providerRouteFamilies(adapters));
8837
+ const pinned = route?.selection;
8838
+ if (pinned && rawModel.trim() !== pinned) {
8839
+ const connection = adapters.find((item2) => item2.name === route.connection)?.displayName ?? route.connection;
8840
+ throw validationError(`${connection} route "${provider}" pins ${route.family.selectionKind} "${pinned}". Select another route to change it.`, { provider, model: rawModel, pinnedModel: pinned });
8841
+ }
8842
+ if (!adapter.modelConfigurable && !pinned) {
8843
+ throw validationError(`Provider "${provider}" does not support project model overrides.`, {
8844
+ provider,
8845
+ modelConfigurable: false
8846
+ });
8847
+ }
8848
+ const model = rawModel.trim();
8849
+ if (!model) {
8850
+ throw validationError(`Model override for provider "${provider}" must not be blank.`);
8851
+ }
8852
+ adapter.modelValidationPattern.lastIndex = 0;
8853
+ if (!adapter.modelValidationPattern.test(model)) {
8854
+ throw validationError(
8855
+ `Invalid model "${model}" for provider "${provider}" \u2014 ${adapter.modelValidationHint}`,
8856
+ { provider, model, hint: adapter.modelValidationHint }
8857
+ );
8858
+ }
8859
+ normalized[provider] = resolveProviderModel(provider, model);
8860
+ }
8861
+ return normalized;
8862
+ }
8863
+ function validateProviderDispatchModes(modes, adapters) {
8864
+ const entries = Object.entries(modes);
8865
+ if (entries.length === 0) return {};
8866
+ if (!adapters || adapters.length === 0) {
8867
+ throw validationError("Project dispatch modes are unavailable because provider metadata is not configured.");
8868
+ }
8869
+ const normalized = {};
8870
+ for (const [provider, mode] of entries) {
8871
+ if (!providerAdapterForName(provider, adapters)) {
8872
+ throw validationError(`Invalid provider dispatch mode: unknown provider "${provider}".`, {
8873
+ provider,
8874
+ validProviders: adapters.map((item2) => item2.name)
8875
+ });
8876
+ }
8877
+ normalized[provider] = mode;
8878
+ }
8879
+ return normalized;
8880
+ }
8881
+ function pruneProviderModelsForProviders(models, providers) {
8882
+ if (providers.length === 0) return { ...models };
8883
+ const kept = {};
8884
+ for (const [provider, model] of Object.entries(models)) {
8885
+ if (providers.includes(provider)) kept[provider] = model;
8886
+ }
8887
+ return kept;
8888
+ }
8889
+ function pruneProviderDispatchModes(modes, providers, revisionProviders) {
8890
+ if (providers.length === 0) return { ...modes };
8891
+ return pruneProviderModelsForProviders(modes, [...providers, ...revisionProviders]);
8892
+ }
8893
+
8617
8894
  // ../api-routes/src/settings.ts
8618
8895
  var SETTINGS_WRITE_SCOPE = "settings.write";
8896
+ function descriptorFields(adapter) {
8897
+ if (!adapter.kind && !adapter.routes && !adapter.profiles) return {};
8898
+ return {
8899
+ ...adapter.kind ? { kind: adapter.kind } : {},
8900
+ connection: adapter.routes?.connection ?? adapter.name,
8901
+ selectionKind: adapter.routes?.selectionKind ?? null,
8902
+ ...adapter.profiles ? { profiles: adapter.profiles } : {},
8903
+ ...adapter.capabilities?.workflows ? { workflows: [...adapter.capabilities.workflows] } : {},
8904
+ ...adapter.capabilities ? { textGeneration: adapter.capabilities.textGeneration } : {},
8905
+ ...adapter.settingsFields ? { settingsFields: adapter.settingsFields } : {},
8906
+ ...adapter.keyCheck ? { keyCheck: adapter.keyCheck } : {},
8907
+ ...adapter.keyUrl ? { keyUrl: adapter.keyUrl } : {},
8908
+ ...adapter.vendorDocsUrl ? { vendorDocsUrl: adapter.vendorDocsUrl } : {}
8909
+ };
8910
+ }
8619
8911
  async function settingsRoutes(app, opts) {
8620
8912
  app.get("/settings", async (request) => {
8621
8913
  requireAdminSession(request);
8622
8914
  return {
8623
8915
  providers: opts.providerSummary ?? [],
8624
- providerCatalog: await Promise.all((opts.providerAdapters ?? []).map(async (adapter) => {
8916
+ providerCatalog: (await Promise.all((opts.providerAdapters ?? []).map(async (adapter) => {
8625
8917
  const configured = opts.providerSummary?.some((provider) => provider.name === adapter.name && provider.configured);
8626
8918
  const discovered = configured && opts.getProviderModels ? await opts.getProviderModels(adapter.name) : [];
8627
- return {
8919
+ const knownModels = discovered.length ? discovered : adapter.knownModels;
8920
+ const descriptor = {
8628
8921
  name: adapter.name,
8629
8922
  displayName: adapter.displayName,
8630
8923
  mode: adapter.mode,
8631
8924
  modelConfigurable: adapter.modelConfigurable,
8632
8925
  defaultModel: adapter.defaultModel,
8633
- knownModels: discovered.length ? discovered : adapter.knownModels,
8926
+ // Catalog entries can carry Aero's model metadata (limits, prices,
8927
+ // tool support); the documented choice shape is id, name and tier.
8928
+ knownModels: knownModels.map(({ id, displayName, tier }) => ({ id, displayName, tier })),
8634
8929
  modelValidationPattern: {
8635
8930
  source: adapter.modelValidationPattern.source,
8636
8931
  flags: adapter.modelValidationPattern.flags
8637
8932
  },
8638
- modelValidationHint: adapter.modelValidationHint
8933
+ modelValidationHint: adapter.modelValidationHint,
8934
+ ...descriptorFields(adapter)
8639
8935
  };
8640
- })),
8936
+ const family = routeFamiliesOf(opts.providerAdapters).find((item2) => item2.connection === adapter.name);
8937
+ if (!family) return [descriptor];
8938
+ const selections = family.selectionKind === "profile" ? (adapter.profiles ?? []).map((profile) => profile.id) : knownModels.map((model) => model.id);
8939
+ const routeAdapters = selections.flatMap((selection) => {
8940
+ let routeName;
8941
+ try {
8942
+ routeName = providerRouteName(family, selection);
8943
+ } catch {
8944
+ return [];
8945
+ }
8946
+ const route = providerAdapterForName(routeName, [{ ...adapter, knownModels }]);
8947
+ if (!route) return [];
8948
+ const fields = descriptorFields(route);
8949
+ return [{
8950
+ ...descriptor,
8951
+ ...fields,
8952
+ name: route.name,
8953
+ displayName: route.displayName,
8954
+ modelConfigurable: false,
8955
+ defaultModel: route.defaultModel,
8956
+ knownModels: route.knownModels,
8957
+ modelValidationPattern: { source: route.modelValidationPattern.source, flags: route.modelValidationPattern.flags },
8958
+ modelValidationHint: route.modelValidationHint,
8959
+ // A route is a target, not a connection: it selects nothing further and holds no key.
8960
+ ...Object.keys(fields).length > 0 ? { selectionKind: null, settingsFields: void 0, keyCheck: void 0 } : {}
8961
+ }];
8962
+ });
8963
+ return [descriptor, ...routeAdapters];
8964
+ }))).flat(),
8641
8965
  google: opts.google ?? { configured: false },
8642
8966
  bing: opts.bing ?? { configured: false }
8643
8967
  };
@@ -8692,6 +9016,10 @@ async function settingsRoutes(app, opts) {
8692
9016
  throw validationError("apiKey is required");
8693
9017
  }
8694
9018
  }
9019
+ if (adapterInfo.kind === ProviderKinds["answer-service"]) {
9020
+ if (baseUrl !== void 0) throw validationError(`${adapterInfo.displayName} uses a fixed endpoint; baseUrl is not accepted.`, { provider: name });
9021
+ if (model !== void 0) throw validationError(`${adapterInfo.displayName} has no connection model; choose profiles per project instead.`, { provider: name });
9022
+ }
8695
9023
  if (model !== void 0) {
8696
9024
  if (!adapterInfo.modelValidationPattern.test(model)) {
8697
9025
  throw validationError(
@@ -8780,79 +9108,9 @@ async function settingsRoutes(app, opts) {
8780
9108
  });
8781
9109
  }
8782
9110
 
8783
- // ../api-routes/src/provider-models.ts
8784
- function validateProviderModels(models, adapters) {
8785
- const entries = Object.entries(models);
8786
- if (entries.length === 0) return {};
8787
- if (!adapters || adapters.length === 0) {
8788
- throw validationError("Project model overrides are unavailable because provider metadata is not configured.");
8789
- }
8790
- const byName = new Map(adapters.map((adapter) => [adapter.name, adapter]));
8791
- const normalized = {};
8792
- for (const [provider, rawModel] of entries) {
8793
- const adapter = byName.get(provider);
8794
- if (!adapter) {
8795
- throw validationError(`Invalid provider model override: unknown provider "${provider}".`, {
8796
- provider,
8797
- validProviders: adapters.map((item2) => item2.name)
8798
- });
8799
- }
8800
- if (!adapter.modelConfigurable) {
8801
- throw validationError(`Provider "${provider}" does not support project model overrides.`, {
8802
- provider,
8803
- modelConfigurable: false
8804
- });
8805
- }
8806
- const model = rawModel.trim();
8807
- if (!model) {
8808
- throw validationError(`Model override for provider "${provider}" must not be blank.`);
8809
- }
8810
- adapter.modelValidationPattern.lastIndex = 0;
8811
- if (!adapter.modelValidationPattern.test(model)) {
8812
- throw validationError(
8813
- `Invalid model "${model}" for provider "${provider}" \u2014 ${adapter.modelValidationHint}`,
8814
- { provider, model, hint: adapter.modelValidationHint }
8815
- );
8816
- }
8817
- normalized[provider] = resolveProviderModel(provider, model);
8818
- }
8819
- return normalized;
8820
- }
8821
- function validateProviderDispatchModes(modes, adapters) {
8822
- const entries = Object.entries(modes);
8823
- if (entries.length === 0) return {};
8824
- if (!adapters || adapters.length === 0) {
8825
- throw validationError("Project dispatch modes are unavailable because provider metadata is not configured.");
8826
- }
8827
- const names = new Set(adapters.map((adapter) => adapter.name));
8828
- const normalized = {};
8829
- for (const [provider, mode] of entries) {
8830
- if (!names.has(provider)) {
8831
- throw validationError(`Invalid provider dispatch mode: unknown provider "${provider}".`, {
8832
- provider,
8833
- validProviders: adapters.map((item2) => item2.name)
8834
- });
8835
- }
8836
- normalized[provider] = mode;
8837
- }
8838
- return normalized;
8839
- }
8840
- function pruneProviderModelsForProviders(models, providers) {
8841
- if (providers.length === 0) return { ...models };
8842
- const kept = {};
8843
- for (const [provider, model] of Object.entries(models)) {
8844
- if (providers.includes(provider)) kept[provider] = model;
8845
- }
8846
- return kept;
8847
- }
8848
- function pruneProviderDispatchModes(modes, providers, revisionProviders) {
8849
- if (providers.length === 0) return { ...modes };
8850
- return pruneProviderModelsForProviders(modes, [...providers, ...revisionProviders]);
8851
- }
8852
-
8853
9111
  // ../api-routes/src/run-queue.ts
8854
9112
  import crypto12 from "crypto";
8855
- import { and as and13, desc as desc7, eq as eq19, gt as gt2, inArray as inArray8, or as or3 } from "drizzle-orm";
9113
+ import { and as and13, desc as desc7, eq as eq19, gt as gt2, inArray as inArray8, like as like2, or as or3 } from "drizzle-orm";
8856
9114
 
8857
9115
  // ../api-routes/src/measurement-report-adapter.ts
8858
9116
  import { and as and11, desc as desc5, eq as eq17, gte as gte2, inArray as inArray7, isNull as isNull3, lt as lt3, lte as lte4, ne as ne5 } from "drizzle-orm";
@@ -10204,7 +10462,7 @@ function ensureCurrentQueryBasketRevision(db, projectId, now = (/* @__PURE__ */
10204
10462
  function hasActiveMeasurementPlan(db, projectId) {
10205
10463
  return db.select({ projectId: measurementPlans.projectId }).from(measurementPlans).where(eq19(measurementPlans.projectId, projectId)).get() !== void 0;
10206
10464
  }
10207
- function activeRevisionProviders(db, projectId) {
10465
+ function activeRevisionProviders(db, projectId, selection = {}) {
10208
10466
  const version = db.select({ canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlans).innerJoin(measurementPlanVersions, and13(
10209
10467
  eq19(measurementPlanVersions.projectId, measurementPlans.projectId),
10210
10468
  eq19(measurementPlanVersions.id, measurementPlans.activeVersionId)
@@ -10212,7 +10470,9 @@ function activeRevisionProviders(db, projectId) {
10212
10470
  if (!version) return [];
10213
10471
  const stored = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
10214
10472
  if (stored.schemaVersion !== MEASUREMENT_PLAN_V2_SCHEMA_VERSION) return [];
10215
- return normalizeProviders(stored.executionNodes.flatMap((node) => node.context.providers));
10473
+ const resolution = sliceForV2(stored, { projectId, ...selection });
10474
+ const nodes = resolution?.executionNodes ?? stored.executionNodes;
10475
+ return normalizeProviders(nodes.flatMap((node) => node.context.providers));
10216
10476
  }
10217
10477
  function executionIdentityChecksum(input) {
10218
10478
  return crypto12.createHash("sha256").update(canonicalMeasurementExecutionIdentityJson(input)).digest("hex");
@@ -10224,15 +10484,15 @@ function resolveRunProviderSelection(input) {
10224
10484
  return resolveRunnableProviderSelection(input).selectedProviders;
10225
10485
  }
10226
10486
  function resolveRunnableProviderSelection(input) {
10487
+ const families = input.routeFamilies ?? void 0;
10227
10488
  const availableProviders = normalizeProviders(input.runnableProviders ?? []);
10228
10489
  const requested = normalizeProviders(input.requestedProviders ?? []);
10229
10490
  const project = normalizeProviders(input.projectProviders ?? []);
10230
- const selectedProviders = requested.length > 0 ? requested : project.length > 0 ? project : availableProviders;
10231
- const available = new Set(availableProviders);
10491
+ const selectedProviders = requested.length > 0 ? requested : project.length > 0 ? project : availableProviders.filter((provider) => isSweepProvider(provider, families));
10232
10492
  return {
10233
10493
  availableProviders,
10234
10494
  selectedProviders,
10235
- runnableProviders: selectedProviders.filter((provider) => available.has(provider)),
10495
+ runnableProviders: selectedProviders.filter((provider) => isSweepProvider(provider, families) && isProviderAvailable(provider, availableProviders, families)),
10236
10496
  selectionSource: requested.length > 0 ? "request" : project.length > 0 ? "project" : "instance"
10237
10497
  };
10238
10498
  }
@@ -10240,7 +10500,8 @@ function providerRoster(tx, params) {
10240
10500
  return resolveRunProviderSelection({
10241
10501
  requestedProviders: params.providers,
10242
10502
  projectProviders: tx.select({ providers: projects.providers }).from(projects).where(eq19(projects.id, params.projectId)).get()?.providers ?? [],
10243
- runnableProviders: params.runnableProviders
10503
+ runnableProviders: params.runnableProviders,
10504
+ routeFamilies: params.routeFamilies
10244
10505
  });
10245
10506
  }
10246
10507
  function effectiveModels(tx, params, providers) {
@@ -10248,7 +10509,7 @@ function effectiveModels(tx, params, providers) {
10248
10509
  const instance = params.providerModels ?? {};
10249
10510
  const resolved = {};
10250
10511
  for (const provider of providers) {
10251
- const model = overrides[provider] ?? instance[provider];
10512
+ const model = resolveProviderRoute(provider, params.routeFamilies ?? void 0)?.selection ?? overrides[provider] ?? instance[provider];
10252
10513
  if (model) resolved[provider] = resolveProviderModel(provider, model);
10253
10514
  }
10254
10515
  return resolved;
@@ -10284,7 +10545,7 @@ function executionSlotIdentity(node, providers, models) {
10284
10545
  providers.map((provider) => [provider, models.get(provider) ?? null])
10285
10546
  ])).digest("hex");
10286
10547
  }
10287
- function materializeV2ExecutionNodes(nodes, instanceModels) {
10548
+ function materializeV2ExecutionNodes(nodes, instanceModels, routeFamilies) {
10288
10549
  const expectedSlots = [];
10289
10550
  const providers = /* @__PURE__ */ new Set();
10290
10551
  const models = /* @__PURE__ */ new Map();
@@ -10296,7 +10557,12 @@ function materializeV2ExecutionNodes(nodes, instanceModels) {
10296
10557
  const declared = nodeProviderModels(node);
10297
10558
  const resolved = /* @__PURE__ */ new Map();
10298
10559
  for (const provider of nodeProviders) {
10299
- const model = declared.get(provider) ?? instanceModels[provider];
10560
+ const route = resolveProviderRoute(provider, routeFamilies);
10561
+ const pinned = route?.selection;
10562
+ if (pinned && declared.has(provider) && declared.get(provider) !== pinned) {
10563
+ throw validationError(`${route.connection === ProviderNames.openrouter ? "OpenRouter" : "The"} route "${provider}" cannot override its pinned ${route.family.selectionKind}.`);
10564
+ }
10565
+ const model = pinned ?? declared.get(provider) ?? instanceModels[provider];
10300
10566
  if (model) resolved.set(provider, model);
10301
10567
  }
10302
10568
  const identity = executionSlotIdentity(node, nodeProviders, resolved);
@@ -10401,7 +10667,7 @@ function measurementStampV2(plan, versionId, params) {
10401
10667
  "The published measurement plan has no execution nodes, so this run would measure nothing. Publish a revision with at least one property assigned to a question."
10402
10668
  );
10403
10669
  }
10404
- const materialized = materializeV2ExecutionNodes(nodes, params.providerModels ?? {});
10670
+ const materialized = materializeV2ExecutionNodes(nodes, params.providerModels ?? {}, params.routeFamilies ?? void 0);
10405
10671
  const requested = normalizeProviders(params.providers ?? []);
10406
10672
  if (requested.length && requested.join("\0") !== materialized.providers.join("\0")) {
10407
10673
  throw validationError(
@@ -10426,7 +10692,7 @@ function measurementStamp(tx, params) {
10426
10692
  if (!active) {
10427
10693
  if (!measurementRunScopeIsEmpty(params.measurementScope)) {
10428
10694
  throw validationError(
10429
- "This project has no published measurement plan, so there is nothing for a group or target scope to point at. Publish a plan first, or run a full sweep."
10695
+ "This project has no published measurement plan, so there is nothing for a group or target scope to point at. Publish a plan first, or run a full AI Visibility check."
10430
10696
  );
10431
10697
  }
10432
10698
  return null;
@@ -10549,15 +10815,18 @@ function queueProviderAdmission(db, params, stamp, now) {
10549
10815
  now,
10550
10816
  providers: () => providersARunWouldCall(
10551
10817
  stamp?.identity.providers ?? providerRoster(db, params),
10552
- params.runnableProviders
10553
- )
10818
+ params.runnableProviders,
10819
+ params.routeFamilies
10820
+ ),
10821
+ routeFamilies: params.routeFamilies
10554
10822
  }) : { skipped: {} };
10555
10823
  }
10556
- function providersARunWouldCall(roster, runnable) {
10824
+ function providersARunWouldCall(roster, runnable, routeFamilies) {
10557
10825
  const listed = normalizeProviders(roster);
10558
10826
  if (runnable == null) return listed;
10559
- const available = new Set(normalizeProviders(runnable));
10560
- return listed.filter((provider) => available.has(provider));
10827
+ const families = routeFamilies ?? void 0;
10828
+ const available = normalizeProviders(runnable);
10829
+ return listed.filter((provider) => isSweepProvider(provider, families) && isProviderAvailable(provider, available, families));
10561
10830
  }
10562
10831
  var PROVIDER_ACCOUNT_LOOKBACK = PROVIDER_ACCOUNT_FAILURE_STREAK * 5;
10563
10832
  function providerSettingsChangeCouldFix(action, diff) {
@@ -10574,6 +10843,8 @@ function providerSettingsChangeCouldFix(action, diff) {
10574
10843
  }
10575
10844
  }
10576
10845
  function heldProviderAccounts(db, params) {
10846
+ const families = params.routeFamilies ?? void 0;
10847
+ const connectionOf = (name) => providerConnectionName(name, families);
10577
10848
  const held = /* @__PURE__ */ new Map();
10578
10849
  const recent = db.select({
10579
10850
  id: runs.id,
@@ -10592,10 +10863,11 @@ function heldProviderAccounts(db, params) {
10592
10863
  if (withAccountFailure.length < PROVIDER_ACCOUNT_FAILURE_STREAK && !entries.some((entry) => entry.skipped)) return held;
10593
10864
  const calling = normalizeProviders(params.providers());
10594
10865
  if (calling.length === 0) return held;
10595
- const answered2 = (runId, provider) => db.select({ id: querySnapshots.id }).from(querySnapshots).where(and13(eq19(querySnapshots.runId, runId), eq19(querySnapshots.provider, provider))).limit(1).get() !== void 0;
10866
+ const answered2 = (runId, provider) => db.select({ id: querySnapshots.id }).from(querySnapshots).where(and13(eq19(querySnapshots.runId, runId), provider === ProviderNames.openrouter ? or3(eq19(querySnapshots.provider, provider), like2(querySnapshots.provider, "openrouter:%")) : eq19(querySnapshots.provider, provider))).limit(1).get() !== void 0;
10596
10867
  const finished = (run) => Date.parse(run.finishedAt ?? run.createdAt);
10597
10868
  const now = Date.parse(params.now);
10598
- for (const provider of calling) {
10869
+ const accounts = [...new Set(calling.map(connectionOf))];
10870
+ for (const provider of accounts) {
10599
10871
  let count9 = 0;
10600
10872
  let newest = null;
10601
10873
  let oldest = null;
@@ -10603,7 +10875,12 @@ function heldProviderAccounts(db, params) {
10603
10875
  let vouched = null;
10604
10876
  let ended = false;
10605
10877
  for (const run of recent) {
10606
- const entry = run.providers[provider];
10878
+ if (provider === ProviderNames.openrouter && answered2(run.id, provider)) {
10879
+ ended = true;
10880
+ break;
10881
+ }
10882
+ const accountEntries = Object.entries(run.providers).filter(([name]) => connectionOf(name) === provider).map(([, entry2]) => entry2);
10883
+ const entry = accountEntries.find((entry2) => !entry2.skipped && !isProviderAccountFailure(entry2.code)) ?? accountEntries.find((entry2) => !entry2.skipped) ?? accountEntries[0];
10607
10884
  if (!entry) {
10608
10885
  if (run.status !== RunStatuses.failed && answered2(run.id, provider)) {
10609
10886
  ended = true;
@@ -10612,7 +10889,7 @@ function heldProviderAccounts(db, params) {
10612
10889
  continue;
10613
10890
  }
10614
10891
  if (entry.skipped) {
10615
- vouched = run.skippedProviders?.[provider] ?? null;
10892
+ vouched = Object.entries(run.skippedProviders ?? {}).find(([name]) => connectionOf(name) === provider)?.[1] ?? null;
10616
10893
  if (vouched) break;
10617
10894
  continue;
10618
10895
  }
@@ -10648,7 +10925,10 @@ function heldProviderAccounts(db, params) {
10648
10925
  held.delete(change.entityId);
10649
10926
  }
10650
10927
  }
10651
- return held;
10928
+ return new Map(calling.flatMap((provider) => {
10929
+ const streak = held.get(connectionOf(provider));
10930
+ return streak ? [[provider, streak]] : [];
10931
+ }));
10652
10932
  }
10653
10933
  function providerAccountFailures(held) {
10654
10934
  const streaks = [...held.values()];
@@ -10666,26 +10946,27 @@ function providerAccountAdmission(db, params) {
10666
10946
  if (params.force || params.trigger === RunTriggers.probe) return { skipped: {} };
10667
10947
  let calling = null;
10668
10948
  const providers = () => calling ??= normalizeProviders(params.providers());
10669
- const held = heldProviderAccounts(db, { projectId: params.projectId, now: params.now, providers });
10949
+ const held = heldProviderAccounts(db, { projectId: params.projectId, now: params.now, providers, routeFamilies: params.routeFamilies });
10670
10950
  if (held.size === 0) return { skipped: {} };
10671
10951
  if (providers().every((provider) => held.has(provider))) return { refused: providerAccountFailures(held) };
10672
10952
  return { skipped: Object.fromEntries(held) };
10673
10953
  }
10674
- function sweepProviders(db, projectId, runnable, selection) {
10954
+ function sweepProviders(db, projectId, runnable, selection, routeFamilies) {
10675
10955
  const planProviders = activeRevisionProviders(db, projectId);
10676
- if (planProviders.length > 0) return providersARunWouldCall(planProviders, runnable);
10956
+ if (planProviders.length > 0) return providersARunWouldCall(planProviders, runnable, routeFamilies);
10677
10957
  const schedule = db.select({ providers: schedules.providers, enabled: schedules.enabled }).from(schedules).where(and13(eq19(schedules.projectId, projectId), eq19(schedules.kind, RunKinds["answer-visibility"]))).get();
10678
10958
  const project = db.select({ providers: projects.providers }).from(projects).where(eq19(projects.id, projectId)).get();
10679
10959
  return providersARunWouldCall(resolveRunProviderSelection({
10680
10960
  requestedProviders: selection === RunTriggers.scheduled && schedule?.enabled ? schedule.providers : null,
10681
10961
  projectProviders: project?.providers ?? [],
10682
- runnableProviders: runnable
10683
- }), runnable);
10962
+ runnableProviders: runnable,
10963
+ routeFamilies
10964
+ }), runnable, routeFamilies);
10684
10965
  }
10685
10966
  function runAdmissionState(db, params) {
10686
10967
  let calling = null;
10687
- const providers = () => calling ??= sweepProviders(db, params.projectId, params.runnableProviders, params.selection ?? RunTriggers.scheduled);
10688
- const held = heldProviderAccounts(db, { projectId: params.projectId, now: params.now, providers });
10968
+ const providers = () => calling ??= sweepProviders(db, params.projectId, params.runnableProviders, params.selection ?? RunTriggers.scheduled, params.routeFamilies);
10969
+ const held = heldProviderAccounts(db, { projectId: params.projectId, now: params.now, providers, routeFamilies: params.routeFamilies });
10689
10970
  const refused = held.size > 0 && providers().every((provider) => held.has(provider));
10690
10971
  return {
10691
10972
  refused,
@@ -10865,6 +11146,7 @@ function redactNotificationDiff(value) {
10865
11146
 
10866
11147
  // ../api-routes/src/projects.ts
10867
11148
  async function projectRoutes(app, opts) {
11149
+ const routeFamilies = providerRouteFamilies(opts.providerAdapters);
10868
11150
  const notifyProjectCreated = (projectId, projectName) => {
10869
11151
  try {
10870
11152
  opts.onProjectCreated?.(projectId, projectName);
@@ -10898,7 +11180,7 @@ async function projectRoutes(app, opts) {
10898
11180
  }
10899
11181
  const validNames = opts.providerAdapters?.map((adapter) => adapter.name) ?? [];
10900
11182
  if (validNames.length && body.providers?.length) {
10901
- const invalid = body.providers.filter((p) => !validNames.includes(p));
11183
+ const invalid = invalidProviderSelections(body.providers, validNames, opts.providerAdapters, ProviderWorkflows["visibility-sweep"]);
10902
11184
  if (invalid.length) {
10903
11185
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
10904
11186
  invalidProviders: invalid,
@@ -10907,6 +11189,7 @@ async function projectRoutes(app, opts) {
10907
11189
  }
10908
11190
  }
10909
11191
  const nextProviders = body.providers ?? [];
11192
+ assertProviderRouteScope(request, nextProviders, [], routeFamilies);
10910
11193
  const providerModels = pruneProviderModelsForProviders(
10911
11194
  validateProviderModels(body.providerModels ?? {}, opts.providerAdapters),
10912
11195
  nextProviders
@@ -10984,7 +11267,7 @@ async function projectRoutes(app, opts) {
10984
11267
  const prepareProjectUpdate = (request, body, existing) => {
10985
11268
  const validNames = opts.providerAdapters?.map((adapter) => adapter.name) ?? [];
10986
11269
  if (validNames.length && body.providers?.length) {
10987
- const invalid = body.providers.filter((p) => !validNames.includes(p));
11270
+ const invalid = invalidProviderSelections(body.providers, validNames, opts.providerAdapters, ProviderWorkflows["visibility-sweep"]);
10988
11271
  if (invalid.length) {
10989
11272
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
10990
11273
  invalidProviders: invalid,
@@ -10993,6 +11276,7 @@ async function projectRoutes(app, opts) {
10993
11276
  }
10994
11277
  }
10995
11278
  const nextProviders = body.providers ?? [];
11279
+ assertProviderRouteScope(request, nextProviders, existing?.providers ?? [], routeFamilies);
10996
11280
  const providerModels = pruneProviderModelsForProviders(
10997
11281
  validateProviderModels(body.providerModels ?? {}, opts.providerAdapters),
10998
11282
  nextProviders
@@ -11896,12 +12180,13 @@ async function queryRoutes(app, opts) {
11896
12180
  const body = parsed.data;
11897
12181
  const provider = body.provider.trim().toLowerCase();
11898
12182
  const validNames = opts.validProviderNames ?? [];
11899
- if (validNames.length && !validNames.includes(provider)) {
12183
+ if (validNames.length && (!isSweepProvider(provider) || !isProviderAvailable(provider, validNames))) {
11900
12184
  throw validationError(`Unknown provider "${body.provider}". Valid providers: ${validNames.join(", ")}`, {
11901
12185
  provider: body.provider,
11902
12186
  validProviders: validNames
11903
12187
  });
11904
12188
  }
12189
+ assertOpenRouterRouteScope(request, [provider], project.providers);
11905
12190
  const count9 = body.count ?? 5;
11906
12191
  if (!opts.onGenerateQueries) {
11907
12192
  throw notImplemented("Query generation is not supported in this deployment");
@@ -12029,12 +12314,13 @@ async function queryRoutes(app, opts) {
12029
12314
  const body = parsed.data;
12030
12315
  const provider = body.provider.trim().toLowerCase();
12031
12316
  const validNames = opts.validProviderNames ?? [];
12032
- if (validNames.length && !validNames.includes(provider)) {
12317
+ if (validNames.length && (!isSweepProvider(provider) || !isProviderAvailable(provider, validNames))) {
12033
12318
  throw validationError(`Unknown provider "${body.provider}". Valid providers: ${validNames.join(", ")}`, {
12034
12319
  provider: body.provider,
12035
12320
  validProviders: validNames
12036
12321
  });
12037
12322
  }
12323
+ assertOpenRouterRouteScope(request, [provider], project.providers);
12038
12324
  const count9 = body.count ?? 5;
12039
12325
  if (!opts.onGenerateQueries) {
12040
12326
  throw notImplemented("Keyword generation is not supported in this deployment");
@@ -12372,7 +12658,7 @@ import { and as and19, eq as eq26 } from "drizzle-orm";
12372
12658
  // ../api-routes/src/snapshot-evidence-fingerprint.ts
12373
12659
  import { createHash as createHash2 } from "crypto";
12374
12660
  function snapshotEvidenceFingerprint(snapshots) {
12375
- const canonical = [...snapshots].sort((left, right) => left.id.localeCompare(right.id)).map(({ dispatchMode: _dispatchMode, providerBatchId: _providerBatchId, stopReason: _stopReason, usage: _usage, mentionIdentity, wrongSubjectTargetKeys, ...evidence }) => JSON.stringify({
12661
+ const canonical = [...snapshots].sort((left, right) => left.id.localeCompare(right.id)).map(({ dispatchMode: _dispatchMode, providerBatchId: _providerBatchId, stopReason: _stopReason, usage: _usage, answerEvidence: _answerEvidence, mentionIdentity, wrongSubjectTargetKeys, ...evidence }) => JSON.stringify({
12376
12662
  ...evidence,
12377
12663
  ...mentionIdentity === null ? {} : { mentionIdentity },
12378
12664
  ...wrongSubjectTargetKeys === null ? {} : { wrongSubjectTargetKeys }
@@ -14431,7 +14717,7 @@ function evaluateRunFill(db, run, input = {}) {
14431
14717
  if (run.trigger === RunTriggers.probe || run.measurementScope !== null || run.queries !== null) {
14432
14718
  return refuse(
14433
14719
  RunFillRefusalCodes.scoped_or_probe,
14434
- "This run is a spot check that measured a slice on purpose. Only a full sweep can be filled."
14720
+ "This run is a spot check that measured a slice on purpose. Only a full AI Visibility check can be filled."
14435
14721
  );
14436
14722
  }
14437
14723
  if (!slots.readable || slots.hasUnboundSnapshot) {
@@ -14444,7 +14730,7 @@ function evaluateRunFill(db, run, input = {}) {
14444
14730
  if (run.status !== "partial") {
14445
14731
  return refuse(
14446
14732
  RunFillRefusalCodes.status_not_partial,
14447
- `Run ${run.id} is ${run.status}. Only a partial run can be filled; run a new sweep instead.`
14733
+ `Run ${run.id} is ${run.status}. Only a partial run can be filled; run a new AI Visibility check instead.`
14448
14734
  );
14449
14735
  }
14450
14736
  const active = activePlanVersionRow(db, run.projectId);
@@ -14460,14 +14746,14 @@ function evaluateRunFill(db, run, input = {}) {
14460
14746
  if (Number.isFinite(anchoredAt) && now - anchoredAt > RUN_FILL_MAX_AGE_MS) {
14461
14747
  return refuse(
14462
14748
  RunFillRefusalCodes.too_old,
14463
- `Run ${run.id} ${age.basis} more than 24 hours ago. Answers captured now would not describe the same moment; run a new sweep instead.`
14749
+ `Run ${run.id} ${age.basis} more than 24 hours ago. Answers captured now would not describe the same moment; run a new AI Visibility check instead.`
14464
14750
  );
14465
14751
  }
14466
14752
  const newer = newerFullSweep(db, run);
14467
14753
  if (newer) {
14468
14754
  return refuse(
14469
14755
  RunFillRefusalCodes.superseded,
14470
- `A newer sweep (${newer.id}) exists and is what every report reads; fill that one instead if it is partial.`
14756
+ `A newer AI Visibility check (${newer.id}) exists and is what every report reads; fill that one instead if it is partial.`
14471
14757
  );
14472
14758
  }
14473
14759
  const missingByProvider = /* @__PURE__ */ new Map();
@@ -14507,12 +14793,12 @@ function evaluateRunFill(db, run, input = {}) {
14507
14793
  if (retired.length) {
14508
14794
  return refuse(
14509
14795
  RunFillRefusalCodes.model_retired,
14510
- `This run measured ${retired.join(", ")} on a model the provider has since retired, and the replacement is a different engine. Filling it now would mix two engines in one run; run a new sweep instead.`
14796
+ `This run measured ${retired.join(", ")} on a model the provider has since retired, and the replacement is a different engine. Filling it now would mix two engines in one run; run a new AI Visibility check instead.`
14511
14797
  );
14512
14798
  }
14513
14799
  if (input.runnableProviders) {
14514
- const runnable = new Set(input.runnableProviders.map(normalizeProvider));
14515
- const absent = providers.filter((provider) => !runnable.has(provider));
14800
+ const runnable = input.runnableProviders.map(normalizeProvider);
14801
+ const absent = providers.filter((provider) => !isProviderAvailable(provider, runnable, input.routeFamilies ?? void 0));
14516
14802
  if (absent.length) {
14517
14803
  return refuse(
14518
14804
  RunFillRefusalCodes.provider_not_configured,
@@ -14522,10 +14808,14 @@ function evaluateRunFill(db, run, input = {}) {
14522
14808
  }
14523
14809
  if (input.dailyLimits) {
14524
14810
  const period2 = new Date(now).toISOString().slice(0, 10);
14811
+ const neededByConnection = /* @__PURE__ */ new Map();
14525
14812
  for (const provider of providers) {
14813
+ const connection = providerConnectionName(provider, input.routeFamilies ?? void 0);
14814
+ neededByConnection.set(connection, (neededByConnection.get(connection) ?? 0) + (missingByProvider.get(provider)?.length ?? 0));
14815
+ }
14816
+ for (const [provider, needed] of neededByConnection) {
14526
14817
  const limit = input.dailyLimits[provider];
14527
14818
  if (limit === void 0) continue;
14528
- const needed = missingByProvider.get(provider)?.length ?? 0;
14529
14819
  const used = db.select({ count: usageCounters.count }).from(usageCounters).where(and23(
14530
14820
  eq31(usageCounters.scope, `${run.projectId}:${provider}`),
14531
14821
  eq31(usageCounters.period, period2),
@@ -14615,6 +14905,7 @@ function queueRunFill(db, runId, input = {}) {
14615
14905
 
14616
14906
  // ../api-routes/src/runs.ts
14617
14907
  async function runRoutes(app, opts) {
14908
+ const routeFamilies = providerRouteFamilies(opts.providerAdapters);
14618
14909
  app.post("/projects/:name/runs", async (request, reply) => {
14619
14910
  const project = resolveProject(app.db, request.params.name);
14620
14911
  const body = parseRunTriggerRequest(request.body ?? {});
@@ -14626,7 +14917,7 @@ async function runRoutes(app, opts) {
14626
14917
  const normalized = rawProviders.map((p) => p.trim().toLowerCase()).filter(Boolean);
14627
14918
  const validNames = opts.validProviderNames ?? [];
14628
14919
  if (validNames.length) {
14629
- const invalid = normalized.filter((p) => !validNames.includes(p));
14920
+ const invalid = invalidProviderSelections(normalized, validNames, opts.providerAdapters, ProviderWorkflows["visibility-sweep"]);
14630
14921
  if (invalid.length) {
14631
14922
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
14632
14923
  invalidProviders: invalid,
@@ -14637,22 +14928,13 @@ async function runRoutes(app, opts) {
14637
14928
  rawProviders.splice(0, rawProviders.length, ...normalized);
14638
14929
  }
14639
14930
  const providers = rawProviders?.length ? rawProviders : void 0;
14931
+ const revisionProviders = activeRevisionProviders(app.db, project.id);
14932
+ assertProviderRouteScope(request, providers ?? [], [...project.providers, ...revisionProviders], routeFamilies);
14640
14933
  const shouldPreflight = trigger !== RunTriggers.probe && opts.getRunnableProviderNames !== void 0;
14641
14934
  const trackedRows2 = body.queries?.length || shouldPreflight ? app.db.select({ query: queries.query }).from(queries).where(eq32(queries.projectId, project.id)).all() : [];
14642
- if (shouldPreflight) {
14643
- const measuresAPlan = hasActiveMeasurementPlan(app.db, project.id);
14644
- const preflightError = answerVisibilityPreflightError({
14645
- projectName: project.name,
14646
- projectProviders: project.providers,
14647
- requestedProviders: providers,
14648
- runnableProviderNames: opts.getRunnableProviderNames(),
14649
- trackedQueryCount: measuresAPlan ? 1 : trackedRows2.length
14650
- });
14651
- if (preflightError) throw preflightError;
14652
- }
14653
14935
  if (body.measurementScope !== void 0 && measurementRunScopeIsEmpty(body.measurementScope)) {
14654
14936
  throw validationError(
14655
- "The measurement scope names nothing to measure. Name at least one group or target, or leave the scope out entirely to run a full sweep."
14937
+ "The measurement scope names nothing to measure. Name at least one group or target, or leave the scope out entirely to run a full AI Visibility check."
14656
14938
  );
14657
14939
  }
14658
14940
  if (hasActiveMeasurementPlan(app.db, project.id) && (body.location || body.allLocations || body.noLocation)) {
@@ -14678,6 +14960,22 @@ async function runRoutes(app, opts) {
14678
14960
  scopedQueries = body.queries;
14679
14961
  }
14680
14962
  const queriesColumn = scopedQueries ?? null;
14963
+ if (shouldPreflight) {
14964
+ const measuresAPlan = hasActiveMeasurementPlan(app.db, project.id);
14965
+ const scopedRevisionProviders = activeRevisionProviders(app.db, project.id, {
14966
+ measurementScope: body.measurementScope ?? null,
14967
+ queries: scopedQueries
14968
+ });
14969
+ const preflightError = answerVisibilityPreflightError({
14970
+ projectName: project.name,
14971
+ projectProviders: scopedRevisionProviders.length > 0 ? scopedRevisionProviders : project.providers,
14972
+ requestedProviders: providers,
14973
+ runnableProviderNames: opts.getRunnableProviderNames(),
14974
+ routeFamilies,
14975
+ trackedQueryCount: measuresAPlan ? 1 : trackedRows2.length
14976
+ });
14977
+ if (preflightError) throw preflightError;
14978
+ }
14681
14979
  let resolvedLocation;
14682
14980
  const projectLocations = project.locations;
14683
14981
  if (body.noLocation) {
@@ -14707,7 +15005,8 @@ async function runRoutes(app, opts) {
14707
15005
  providers: resolveRunnableProviderSelection({
14708
15006
  requestedProviders: providers,
14709
15007
  projectProviders: project.providers,
14710
- runnableProviders: opts.getRunnableProviderNames?.()
15008
+ runnableProviders: opts.getRunnableProviderNames?.(),
15009
+ routeFamilies
14711
15010
  }).selectedProviders,
14712
15011
  expectedSlots: null,
14713
15012
  scoped: queriesColumn !== null,
@@ -14734,9 +15033,10 @@ async function runRoutes(app, opts) {
14734
15033
  const roster = resolveRunnableProviderSelection({
14735
15034
  requestedProviders: providers,
14736
15035
  projectProviders: project.providers,
14737
- runnableProviders: runnable
15036
+ runnableProviders: runnable,
15037
+ routeFamilies
14738
15038
  }).selectedProviders;
14739
- return providersARunWouldCall(roster, runnable);
15039
+ return providersARunWouldCall(roster, runnable, routeFamilies);
14740
15040
  }
14741
15041
  });
14742
15042
  if (admission.refused) return { conflict: false, refused: admission.refused };
@@ -14790,6 +15090,7 @@ async function runRoutes(app, opts) {
14790
15090
  queries: queriesColumn,
14791
15091
  providers,
14792
15092
  runnableProviders: opts.getRunnableProviderNames?.(),
15093
+ routeFamilies,
14793
15094
  providerModels: opts.getEffectiveProviderModels?.(),
14794
15095
  measurementScope: body.measurementScope ?? null,
14795
15096
  dispatchMode: body.dispatchMode ?? null,
@@ -14836,7 +15137,8 @@ async function runRoutes(app, opts) {
14836
15137
  const admissionParams = {
14837
15138
  projectId: project.id,
14838
15139
  now: (/* @__PURE__ */ new Date()).toISOString(),
14839
- runnableProviders: opts.getRunnableProviderNames?.()
15140
+ runnableProviders: opts.getRunnableProviderNames?.(),
15141
+ routeFamilies
14840
15142
  };
14841
15143
  const admission = runAdmissionState(app.db, admissionParams);
14842
15144
  const manualAdmission = runAdmissionState(app.db, { ...admissionParams, selection: RunTriggers.manual });
@@ -14860,6 +15162,7 @@ async function runRoutes(app, opts) {
14860
15162
  projectId: project.id,
14861
15163
  now: (/* @__PURE__ */ new Date()).toISOString(),
14862
15164
  runnableProviders: opts.getRunnableProviderNames?.(),
15165
+ routeFamilies,
14863
15166
  selection
14864
15167
  }));
14865
15168
  });
@@ -14900,7 +15203,7 @@ async function runRoutes(app, opts) {
14900
15203
  const normalized = rawProviders.map((p) => p.trim().toLowerCase()).filter(Boolean);
14901
15204
  const validNames = opts.validProviderNames ?? [];
14902
15205
  if (validNames.length) {
14903
- const invalid = normalized.filter((p) => !validNames.includes(p));
15206
+ const invalid = invalidProviderSelections(normalized, validNames, opts.providerAdapters, ProviderWorkflows["visibility-sweep"]);
14904
15207
  if (invalid.length) {
14905
15208
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
14906
15209
  invalidProviders: invalid,
@@ -14916,11 +15219,12 @@ async function runRoutes(app, opts) {
14916
15219
  const runnableProviderNames = opts.getRunnableProviderNames?.();
14917
15220
  const eligible = [];
14918
15221
  for (const project of allProjects) {
15222
+ const revisionProviders = activeRevisionProviders(app.db, project.id);
14919
15223
  if (runnableProviderNames) {
14920
15224
  const trackedQuery = app.db.select({ id: queries.id }).from(queries).where(eq32(queries.projectId, project.id)).limit(1).get();
14921
15225
  const preflightError = answerVisibilityPreflightError({
14922
15226
  projectName: project.name,
14923
- projectProviders: project.providers,
15227
+ projectProviders: revisionProviders.length > 0 ? revisionProviders : project.providers,
14924
15228
  requestedProviders: providers,
14925
15229
  runnableProviderNames,
14926
15230
  // A project measuring a published plan runs the plan's frozen
@@ -14949,11 +15253,12 @@ async function runRoutes(app, opts) {
14949
15253
  }
14950
15254
  resolvedLocation = loc;
14951
15255
  }
14952
- eligible.push({ project, resolvedLocation });
15256
+ eligible.push({ project, revisionProviders, resolvedLocation });
14953
15257
  }
14954
15258
  const dispatchable = [];
14955
15259
  for (const entry of eligible) {
14956
15260
  try {
15261
+ assertProviderRouteScope(request, providers ?? [], [...entry.project.providers, ...entry.revisionProviders], routeFamilies);
14957
15262
  assertMeasurementRunStampable(app.db, {
14958
15263
  createdAt: now,
14959
15264
  projectId: entry.project.id,
@@ -14962,6 +15267,7 @@ async function runRoutes(app, opts) {
14962
15267
  location: entry.resolvedLocation?.label ?? null,
14963
15268
  providers,
14964
15269
  runnableProviders: runnableProviderNames,
15270
+ routeFamilies,
14965
15271
  providerModels: opts.getEffectiveProviderModels?.(),
14966
15272
  dispatchMode,
14967
15273
  batchEligibleProviders,
@@ -14990,6 +15296,7 @@ async function runRoutes(app, opts) {
14990
15296
  // against is what it was actually asked to do.
14991
15297
  providers,
14992
15298
  runnableProviders: runnableProviderNames,
15299
+ routeFamilies,
14993
15300
  providerModels: opts.getEffectiveProviderModels?.(),
14994
15301
  dispatchMode,
14995
15302
  batchEligibleProviders,
@@ -15053,6 +15360,7 @@ async function runRoutes(app, opts) {
15053
15360
  const input = {
15054
15361
  providers: parsed.data.providers,
15055
15362
  runnableProviders: opts.getRunnableProviderNames?.() ?? null,
15363
+ routeFamilies,
15056
15364
  dailyLimits: opts.getProviderDailyLimits?.() ?? null
15057
15365
  };
15058
15366
  if (parsed.data.dryRun) {
@@ -15083,6 +15391,7 @@ async function runRoutes(app, opts) {
15083
15391
  assertProjectScope(request, run.projectId);
15084
15392
  return reply.send(readRunCompleteness(app.db, run, {
15085
15393
  runnableProviders: opts.getRunnableProviderNames?.() ?? null,
15394
+ routeFamilies,
15086
15395
  dailyLimits: opts.getProviderDailyLimits?.() ?? null
15087
15396
  }));
15088
15397
  });
@@ -15100,7 +15409,8 @@ function answerVisibilityPreflightError(input) {
15100
15409
  const selection = resolveRunnableProviderSelection({
15101
15410
  requestedProviders: input.requestedProviders,
15102
15411
  projectProviders: input.projectProviders,
15103
- runnableProviders: input.runnableProviderNames
15412
+ runnableProviders: input.runnableProviderNames,
15413
+ routeFamilies: input.routeFamilies
15104
15414
  });
15105
15415
  if (selection.runnableProviders.length > 0) return null;
15106
15416
  return noProvider(input.projectName, {
@@ -15233,6 +15543,7 @@ function loadRunDetail(app, run) {
15233
15543
  dispatchMode: querySnapshots.dispatchMode,
15234
15544
  stopReason: querySnapshots.stopReason,
15235
15545
  usage: querySnapshots.usage,
15546
+ answerEvidence: querySnapshots.answerEvidence,
15236
15547
  rawResponse: querySnapshots.rawResponse,
15237
15548
  createdAt: querySnapshots.createdAt
15238
15549
  }).from(querySnapshots).leftJoin(queries, eq32(querySnapshots.queryId, queries.id)).where(eq32(querySnapshots.runId, run.id)).all();
@@ -15286,6 +15597,8 @@ function loadRunDetail(app, run) {
15286
15597
  groundingSources: rawParsed.groundingSources,
15287
15598
  searchQueries: rawParsed.searchQueries,
15288
15599
  retrievedSources: rawParsed.retrievedSources,
15600
+ // Only answer services record evidence; other rows keep their exact shape.
15601
+ ...s.answerEvidence ? { evidence: s.answerEvidence } : {},
15289
15602
  createdAt: s.createdAt
15290
15603
  };
15291
15604
  });
@@ -15388,7 +15701,7 @@ function compileContextForProject(app, project, opts) {
15388
15701
  const trackedQueries = app.db.select({ id: queries.id, query: queries.query }).from(queries).where(eq33(queries.projectId, project.id)).all();
15389
15702
  const defaultContext = project.defaultLocation ? project.locations.find((location) => location.label === project.defaultLocation) ?? null : null;
15390
15703
  const projectProviders = normalizedProviderNames(project.providers);
15391
- const selectedProviders = projectProviders.length > 0 ? projectProviders : normalizedProviderNames(opts.getRunnableProviderNames?.() ?? []);
15704
+ const selectedProviders = projectProviders.length > 0 ? projectProviders : normalizedProviderNames(opts.getRunnableProviderNames?.() ?? []).filter((name) => isSweepProvider(name, opts.providerRouteFamilies));
15392
15705
  return {
15393
15706
  canonicalDomain: project.canonicalDomain,
15394
15707
  ownedDomains: project.ownedDomains,
@@ -15494,9 +15807,9 @@ function executionDiff(before, after) {
15494
15807
  const afterCounts = planCounts(after);
15495
15808
  const nodes = diffKeys(before?.executionNodes ?? [], after.executionNodes);
15496
15809
  const beforeEdges = before?.usageEdges ?? [];
15497
- const edgeKey2 = (edge) => stableJson(edge);
15498
- const beforeEdgeKeys = new Set(beforeEdges.map(edgeKey2));
15499
- const afterEdgeKeys = new Set(after.usageEdges.map(edgeKey2));
15810
+ const edgeKey3 = (edge) => stableJson(edge);
15811
+ const beforeEdgeKeys = new Set(beforeEdges.map(edgeKey3));
15812
+ const afterEdgeKeys = new Set(after.usageEdges.map(edgeKey3));
15500
15813
  const counts2 = {
15501
15814
  before: beforeCounts,
15502
15815
  after: afterCounts,
@@ -15505,8 +15818,8 @@ function executionDiff(before, after) {
15505
15818
  return {
15506
15819
  addedNodeKeys: nodes.added,
15507
15820
  removedNodeKeys: nodes.removed,
15508
- addedUsageEdges: after.usageEdges.filter((edge) => !beforeEdgeKeys.has(edgeKey2(edge))),
15509
- removedUsageEdges: beforeEdges.filter((edge) => !afterEdgeKeys.has(edgeKey2(edge))),
15821
+ addedUsageEdges: after.usageEdges.filter((edge) => !beforeEdgeKeys.has(edgeKey3(edge))),
15822
+ removedUsageEdges: beforeEdges.filter((edge) => !afterEdgeKeys.has(edgeKey3(edge))),
15510
15823
  counts: counts2
15511
15824
  };
15512
15825
  }
@@ -15999,116 +16312,6 @@ import { promisify as promisify2 } from "util";
15999
16312
  import http from "http";
16000
16313
  import https from "https";
16001
16314
  import net2 from "net";
16002
-
16003
- // ../api-routes/src/egress-policy.ts
16004
- import net from "net";
16005
- function blockedAddressReason(value, options = {}) {
16006
- const address = stripZoneId(stripIpv6Brackets(value));
16007
- if (options.allowLoopback && isLoopbackAddress(address)) return null;
16008
- const family = net.isIP(address);
16009
- if (family === 4) return blockedIpv4Reason(ipv4Octets(address));
16010
- if (family === 6) {
16011
- const bytes = ipv6Bytes(address);
16012
- return bytes ? blockedIpv6Reason(bytes) : "which could not be read as an address";
16013
- }
16014
- return "which is not an IP address";
16015
- }
16016
- function isLoopbackAddress(value) {
16017
- const address = stripZoneId(stripIpv6Brackets(value));
16018
- const family = net.isIP(address);
16019
- if (family === 4) return ipv4Octets(address)[0] === 127;
16020
- if (family !== 6) return false;
16021
- const bytes = ipv6Bytes(address);
16022
- if (!bytes) return false;
16023
- const mapped = mappedIpv4(bytes);
16024
- if (mapped) return mapped[0] === 127;
16025
- return bytes.slice(0, 15).every((byte) => byte === 0) && bytes[15] === 1;
16026
- }
16027
- function stripIpv6Brackets(value) {
16028
- return value.startsWith("[") && value.endsWith("]") ? value.slice(1, -1) : value;
16029
- }
16030
- function stripZoneId(address) {
16031
- return address.split("%")[0];
16032
- }
16033
- function ipv4Octets(address) {
16034
- return address.split(".").map((part) => Number.parseInt(part, 10));
16035
- }
16036
- function blockedIpv4Reason(octets) {
16037
- const [first, second] = octets;
16038
- if (first === 0) return "which is unspecified space";
16039
- if (first === 127) return "which is loopback";
16040
- if (first === 10 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168) {
16041
- return "which is private space";
16042
- }
16043
- if (first === 100 && second >= 64 && second <= 127) return "which is carrier-grade NAT space";
16044
- if (first === 169 && second === 254) return "which is link-local";
16045
- if (first >= 224 && first <= 239) return "which is multicast";
16046
- if (first === 192 && second === 0 && octets[2] === 0 || first === 198 && (second === 18 || second === 19) || first >= 240) {
16047
- return "which is reserved";
16048
- }
16049
- return null;
16050
- }
16051
- function blockedIpv6Reason(bytes) {
16052
- const first = bytes[0];
16053
- if (first === 0) {
16054
- const nat64 = nat64Ipv4(bytes);
16055
- if (nat64) return blockedIpv4Reason(nat64) === null ? null : `which is the NAT64 form of ${nat64.join(".")}`;
16056
- const mapped = mappedIpv4(bytes);
16057
- return mapped ? `which is the IPv6 form of ${mapped.join(".")}` : "which is reserved IPv6 space";
16058
- }
16059
- if (first === 1 && bytes.slice(1, 8).every((byte) => byte === 0)) return "which is reserved IPv6 space";
16060
- if (first === 255) return "which is multicast";
16061
- if ((first & 254) === 252) return "which is unique-local";
16062
- if (first === 254 && (bytes[1] & 192) === 128) return "which is link-local";
16063
- if (first === 254 && (bytes[1] & 192) === 192) return "which is reserved site-local space";
16064
- if (first === 32 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 0) return "which is a Teredo tunnel";
16065
- if (first === 32 && bytes[1] === 2) return "which is a 6to4 tunnel";
16066
- if (first === 32 && bytes[1] === 1 && bytes[2] === 0 && bytes[3] === 2 && bytes[4] === 0 && bytes[5] === 0) {
16067
- return "which is reserved IPv6 space";
16068
- }
16069
- return null;
16070
- }
16071
- function mappedIpv4(bytes) {
16072
- const isMapped = bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 255 && bytes[11] === 255;
16073
- return isMapped ? [bytes[12], bytes[13], bytes[14], bytes[15]] : null;
16074
- }
16075
- var NAT64_WELL_KNOWN_PREFIX = [0, 100, 255, 155, 0, 0, 0, 0, 0, 0, 0, 0];
16076
- function nat64Ipv4(bytes) {
16077
- const isNat64 = NAT64_WELL_KNOWN_PREFIX.every((byte, index) => bytes[index] === byte);
16078
- return isNat64 ? [bytes[12], bytes[13], bytes[14], bytes[15]] : null;
16079
- }
16080
- function ipv6Bytes(address) {
16081
- if (!net.isIPv6(address)) return null;
16082
- const halves = address.split("::");
16083
- if (halves.length > 2) return null;
16084
- const expand = (text) => {
16085
- if (text === "") return [];
16086
- const groups2 = [];
16087
- const chunks = text.split(":");
16088
- for (const [index, chunk] of chunks.entries()) {
16089
- if (index === chunks.length - 1 && chunk.includes(".")) {
16090
- const octets = ipv4Octets(chunk);
16091
- groups2.push(octets[0] << 8 | octets[1], octets[2] << 8 | octets[3]);
16092
- continue;
16093
- }
16094
- groups2.push(Number.parseInt(chunk, 16));
16095
- }
16096
- return groups2;
16097
- };
16098
- const head = expand(halves[0]);
16099
- const tail = halves.length === 2 ? expand(halves[1]) : [];
16100
- const missing = 8 - head.length - tail.length;
16101
- if (halves.length === 1 ? missing !== 0 : missing < 0) return null;
16102
- const groups = [...head, ...new Array(halves.length === 2 ? missing : 0).fill(0), ...tail];
16103
- const bytes = new Uint8Array(16);
16104
- for (const [index, group] of groups.entries()) {
16105
- bytes[index * 2] = group >> 8;
16106
- bytes[index * 2 + 1] = group & 255;
16107
- }
16108
- return bytes;
16109
- }
16110
-
16111
- // ../api-routes/src/measurement-sitemap-fetch.ts
16112
16315
  var gunzipAsync = promisify2(gunzip);
16113
16316
  var DEFAULT_MEASUREMENT_SITEMAP_LIMITS = {
16114
16317
  timeoutMs: 1e4,
@@ -16591,6 +16794,33 @@ function createChecks() {
16591
16794
  function normalizeProviders2(values) {
16592
16795
  return sortedUnique(values.map((value) => value.trim().toLowerCase()).filter(Boolean));
16593
16796
  }
16797
+ function frozenMeasurementDraftExecutionKeys(authoring) {
16798
+ const keys = /* @__PURE__ */ new Map();
16799
+ for (const assignment of authoring.assignments) {
16800
+ for (const exact of assignment.executionContexts ?? []) {
16801
+ if (exact.executionNodeKey === void 0) continue;
16802
+ const signature = canonicalJson({
16803
+ queryId: assignment.queryId,
16804
+ location: exact.location,
16805
+ providers: normalizeProviders2(exact.providers),
16806
+ models: Object.fromEntries(Object.entries(exact.models).map(([provider, model]) => [provider.trim().toLowerCase(), model]))
16807
+ });
16808
+ keys.set(signature, exact.executionNodeKey);
16809
+ }
16810
+ }
16811
+ return keys;
16812
+ }
16813
+ function sweepIneligibleMessage(provider, adapters) {
16814
+ if (!adapters) return null;
16815
+ const adapter = providerAdapterForName(provider, adapters);
16816
+ if (!adapter || isEligibleFor(adapter, ProviderWorkflows["visibility-sweep"], "explicit")) return null;
16817
+ return `${adapter.displayName} (${provider}) does not run visibility sweeps; choose a profile that does.`;
16818
+ }
16819
+ function routedProviderMessage(provider, families) {
16820
+ const connection = (families ?? [OPENROUTER_ROUTE_FAMILY]).find((family) => provider === family.connection || provider.startsWith(`${family.connection}:`));
16821
+ if (!connection || connection.connection === "openrouter") return "OpenRouter measurement requires a fixed model route.";
16822
+ return `Measurement through ${connection.connection} requires one of its ${connection.selectionKind} routes.`;
16823
+ }
16594
16824
  function compileMeasurementDraft(authoring, context) {
16595
16825
  const { checks, sink, failed } = createChecks();
16596
16826
  let canonicalHost = "";
@@ -16744,6 +16974,16 @@ function compileMeasurementDraft(authoring, context) {
16744
16974
  }
16745
16975
  models[normalized] = model;
16746
16976
  }
16977
+ for (const provider of providers) {
16978
+ if (!isSweepProvider(provider, context.routeFamilies)) sink.fail("invalid-provider-model", routedProviderMessage(provider, context.routeFamilies), [...path8, "providers"]);
16979
+ const ineligible = sweepIneligibleMessage(provider, context.providerAdapters);
16980
+ if (ineligible) sink.fail("invalid-provider-model", ineligible, [...path8, "providers"]);
16981
+ const route = resolveProviderRoute(provider, context.routeFamilies);
16982
+ if (!route) continue;
16983
+ const pinned = route.selection;
16984
+ if (models[provider] && models[provider] !== pinned) sink.fail("invalid-provider-model", `${route.connection === "openrouter" ? "OpenRouter route" : "Route"} "${provider}" pins ${route.family.selectionKind} "${pinned}".`, [...path8, "models", provider]);
16985
+ models[provider] = pinned;
16986
+ }
16747
16987
  const labels = sortedUnique(override?.locations ?? authoring.defaultContext.locations);
16748
16988
  const locations = [];
16749
16989
  labels.forEach((label, labelIndex) => {
@@ -16771,6 +17011,16 @@ function compileMeasurementDraft(authoring, context) {
16771
17011
  }
16772
17012
  models[normalized] = model;
16773
17013
  }
17014
+ for (const provider of providers) {
17015
+ if (!isSweepProvider(provider, context.routeFamilies)) sink.fail("invalid-provider-model", routedProviderMessage(provider, context.routeFamilies), [...path8, "providers"]);
17016
+ const ineligible = sweepIneligibleMessage(provider, context.providerAdapters);
17017
+ if (ineligible) sink.fail("invalid-provider-model", ineligible, [...path8, "providers"]);
17018
+ const route = resolveProviderRoute(provider, context.routeFamilies);
17019
+ if (!route) continue;
17020
+ const pinned = route.selection;
17021
+ if (models[provider] && models[provider] !== pinned) sink.fail("invalid-provider-model", `${route.connection === "openrouter" ? "OpenRouter route" : "Route"} "${provider}" pins ${route.family.selectionKind} "${pinned}".`, [...path8, "models", provider]);
17022
+ models[provider] = pinned;
17023
+ }
16774
17024
  const identity = exact.executionNodeKey === void 0 ? {} : { executionNodeKey: exact.executionNodeKey };
16775
17025
  if (exact.location === null) return { ...identity, providers, models, location: null };
16776
17026
  const configured = locationsByLabel.get(exact.location.label);
@@ -16790,19 +17040,7 @@ function compileMeasurementDraft(authoring, context) {
16790
17040
  const usedQueryIds = /* @__PURE__ */ new Set();
16791
17041
  const claimedPairs = /* @__PURE__ */ new Set();
16792
17042
  const frozenProvenanceByQuery = /* @__PURE__ */ new Map();
16793
- const frozenKeysBySignature = /* @__PURE__ */ new Map();
16794
- for (const assignment of authoring.assignments) {
16795
- for (const exact of assignment.executionContexts ?? []) {
16796
- if (exact.executionNodeKey === void 0) continue;
16797
- const signature = canonicalJson({
16798
- queryId: assignment.queryId,
16799
- location: exact.location,
16800
- providers: normalizeProviders2(exact.providers),
16801
- models: Object.fromEntries(Object.entries(exact.models).map(([provider, model]) => [provider.trim().toLowerCase(), model]))
16802
- });
16803
- frozenKeysBySignature.set(signature, exact.executionNodeKey);
16804
- }
16805
- }
17043
+ const frozenKeysBySignature = frozenMeasurementDraftExecutionKeys(authoring);
16806
17044
  authoring.assignments.forEach((assignment, index) => {
16807
17045
  const path8 = ["assignments", index];
16808
17046
  const pair = `${assignment.targetKey} ${assignment.queryId}`;
@@ -17050,6 +17288,7 @@ var MEASUREMENT_DRAFT_ACTIONS = [
17050
17288
  "apply-assignments",
17051
17289
  "replace-assignments",
17052
17290
  "apply-paired-assignments",
17291
+ "route-markets",
17053
17292
  "remove-assignment",
17054
17293
  "clear-assignments",
17055
17294
  "classify-assignments",
@@ -17178,10 +17417,187 @@ function assertMeasurementDraftAuthoringLimits(before, candidate) {
17178
17417
  function warn(code, message, path8) {
17179
17418
  return { code, message, path: path8 };
17180
17419
  }
17181
- function withRequestedContext(assignment, contextOverride) {
17420
+ function normalizedProviders2(values) {
17421
+ return unique(values.map((value) => value.trim().toLowerCase()).filter(Boolean)).sort(compareText);
17422
+ }
17423
+ function normalizedModels(values) {
17424
+ return Object.fromEntries(Object.entries(values).map(([provider, model]) => [provider.trim().toLowerCase(), model]).sort(([left], [right]) => compareText(left, right)));
17425
+ }
17426
+ function normalizedExactContext(exact, queryId, override, frozenKeys) {
17427
+ const providers = normalizedProviders2(override.providers ?? exact.providers);
17428
+ const models = normalizedModels(override.models ?? (override.providers === void 0 ? exact.models : {}));
17429
+ for (const provider of providers) {
17430
+ const pinned = openRouterRouteModel(provider);
17431
+ if (pinned) models[provider] = pinned;
17432
+ }
17433
+ const next = { providers, models, location: exact.location };
17434
+ const current = {
17435
+ providers: normalizedProviders2(exact.providers),
17436
+ models: normalizedModels(exact.models),
17437
+ location: exact.location
17438
+ };
17439
+ if (canonicalJson(next) === canonicalJson(current)) return exact;
17440
+ const signature = canonicalJson({ queryId, ...next });
17441
+ return {
17442
+ ...next,
17443
+ executionNodeKey: frozenKeys.get(signature) ?? `execution-${sha256Hex(signature)}`
17444
+ };
17445
+ }
17446
+ function edgeKey(targetKey, queryId, executionNodeKey) {
17447
+ return measurementV2UsageEdgeKey({ targetKey, queryId, executionNodeKey });
17448
+ }
17449
+ function remapReportingScopeEdges(reportingScopes, remaps) {
17450
+ if (reportingScopes === void 0 || remaps.size === 0) return reportingScopes;
17451
+ return reportingScopes.map((scope) => {
17452
+ const seen2 = /* @__PURE__ */ new Set();
17453
+ const usageEdges = [];
17454
+ for (const edge of scope.usageEdges) {
17455
+ const next = remaps.get(measurementV2UsageEdgeKey(edge)) ?? edge;
17456
+ const key = measurementV2UsageEdgeKey(next);
17457
+ if (seen2.has(key)) continue;
17458
+ seen2.add(key);
17459
+ usageEdges.push(next);
17460
+ }
17461
+ return { ...scope, usageEdges };
17462
+ });
17463
+ }
17464
+ function pruneReportingScopeEdges(reportingScopes, assignments) {
17465
+ if (reportingScopes === void 0) return void 0;
17466
+ const validPairs = new Set(assignments.map((assignment) => `${assignment.targetKey}\0${assignment.queryId}`));
17467
+ return reportingScopes.map((scope) => ({
17468
+ ...scope,
17469
+ usageEdges: scope.usageEdges.filter((edge) => validPairs.has(`${edge.targetKey}\0${edge.queryId}`))
17470
+ }));
17471
+ }
17472
+ function authoringWithAssignments(authoring, assignments, reportingScopes = authoring.reportingScopes) {
17473
+ return {
17474
+ ...authoring,
17475
+ assignments,
17476
+ ...reportingScopes === void 0 ? {} : { reportingScopes: pruneReportingScopeEdges(reportingScopes, assignments) }
17477
+ };
17478
+ }
17479
+ function mutableAssignmentContext(authoring, assignment) {
17480
+ const override = assignment.contextOverride;
17481
+ const providers = normalizedProviders2(override?.providers ?? authoring.defaultContext.providers);
17482
+ const rawModels = normalizedModels(override?.models ?? authoring.defaultContext.models ?? {});
17483
+ const models = Object.fromEntries(Object.entries(rawModels).filter(([provider]) => providers.includes(provider)));
17484
+ for (const provider of providers) {
17485
+ const pinned = openRouterRouteModel(provider);
17486
+ if (pinned) models[provider] = pinned;
17487
+ }
17488
+ const locationLabels = unique(override?.locations ?? authoring.defaultContext.locations).sort(compareText);
17489
+ return { providers, models, locationLabels };
17490
+ }
17491
+ function mutableAssignmentExactContext(authoring, assignment, context, frozenKeys) {
17492
+ const { providers, models, locationLabels } = mutableAssignmentContext(authoring, assignment);
17493
+ if (locationLabels.length > 1) {
17494
+ throw validationError(
17495
+ `Market routing cannot safely choose among ${locationLabels.length} locations for ${assignment.targetKey}/${assignment.queryId}. Route the Property to one location first.`,
17496
+ { displayToOperator: true }
17497
+ );
17498
+ }
17499
+ const location = locationLabels.length === 0 ? null : context.locationsByLabel?.get(locationLabels[0]);
17500
+ if (locationLabels.length === 1 && !location) {
17501
+ throw validationError(`Location "${locationLabels[0]}" is unavailable for market routing. Reload the draft and try again.`, {
17502
+ displayToOperator: true
17503
+ });
17504
+ }
17505
+ const resolvedLocation = location ?? null;
17506
+ const locationIdentity = resolvedLocation ? [resolvedLocation.label, resolvedLocation.city, resolvedLocation.region, resolvedLocation.country].join("\0") : "";
17507
+ const executionNodeKey = frozenKeys.get(canonicalJson({
17508
+ queryId: assignment.queryId,
17509
+ location: resolvedLocation,
17510
+ providers,
17511
+ models
17512
+ })) ?? `execution-${sha256Hex(canonicalJson({
17513
+ queryId: assignment.queryId,
17514
+ location: locationIdentity,
17515
+ providers,
17516
+ models
17517
+ }))}`;
17518
+ return { providers, models, location: resolvedLocation, executionNodeKey };
17519
+ }
17520
+ function normalizeSelectedOneToOneMarketEdges(authoring, selectedMarkets, selectsEdge, context) {
17521
+ const assignmentsByPair = new Map(authoring.assignments.map((assignment, index) => [
17522
+ `${assignment.targetKey}\0${assignment.queryId}`,
17523
+ { assignment, index }
17524
+ ]));
17525
+ const successorByPair = /* @__PURE__ */ new Map();
17526
+ const mutableIndexes = /* @__PURE__ */ new Set();
17527
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17528
+ for (const scope of authoring.reportingScopes ?? []) {
17529
+ if (!selectedMarkets.has(scope.stableKey)) continue;
17530
+ for (const edge of scope.usageEdges) {
17531
+ if (!selectsEdge(edge)) continue;
17532
+ const pair = `${edge.targetKey}\0${edge.queryId}`;
17533
+ const found = assignmentsByPair.get(pair);
17534
+ if (!found) continue;
17535
+ if (found.assignment.executionContexts?.some((exact) => exact.executionNodeKey === edge.executionNodeKey)) continue;
17536
+ if (successorByPair.has(pair)) continue;
17537
+ if (found.assignment.executionContexts !== void 0) {
17538
+ if (found.assignment.executionContexts.length !== 1 || !found.assignment.executionContexts[0].executionNodeKey) {
17539
+ throw validationError(
17540
+ `Market routing cannot safely map stale membership for ${edge.targetKey}/${edge.queryId} across multiple contexts. Publish or restore one exact context first.`,
17541
+ { displayToOperator: true, marketEdge: edge }
17542
+ );
17543
+ }
17544
+ successorByPair.set(pair, found.assignment.executionContexts[0]);
17545
+ continue;
17546
+ }
17547
+ successorByPair.set(pair, mutableAssignmentExactContext(authoring, found.assignment, context, frozenKeys));
17548
+ mutableIndexes.add(found.index);
17549
+ }
17550
+ }
17551
+ if (successorByPair.size === 0) return authoring;
17552
+ const assignments = authoring.assignments.map((assignment, index) => {
17553
+ if (!mutableIndexes.has(index)) return assignment;
17554
+ const successor = successorByPair.get(`${assignment.targetKey}\0${assignment.queryId}`);
17555
+ const { contextOverride: _contextOverride, ...frozen } = assignment;
17556
+ return { ...frozen, executionContexts: [successor] };
17557
+ });
17558
+ const reportingScopes = authoring.reportingScopes?.map((scope) => {
17559
+ const seen2 = /* @__PURE__ */ new Set();
17560
+ const usageEdges = [];
17561
+ for (const edge of scope.usageEdges) {
17562
+ const successor = successorByPair.get(`${edge.targetKey}\0${edge.queryId}`);
17563
+ const next = successor?.executionNodeKey ? { ...edge, executionNodeKey: successor.executionNodeKey } : edge;
17564
+ const key = measurementV2UsageEdgeKey(next);
17565
+ if (seen2.has(key)) continue;
17566
+ seen2.add(key);
17567
+ usageEdges.push(next);
17568
+ }
17569
+ return { ...scope, usageEdges };
17570
+ });
17571
+ return authoringWithAssignments(authoring, assignments, reportingScopes);
17572
+ }
17573
+ function withRequestedContext(assignment, contextOverride, frozenKeys, edgeRemaps) {
17182
17574
  if (contextOverride === void 0) return assignment;
17575
+ if (assignment.executionContexts !== void 0 && contextOverride.locations === void 0) {
17576
+ const contextsByIdentity = /* @__PURE__ */ new Map();
17577
+ for (const exact of assignment.executionContexts) {
17578
+ const rewritten = normalizedExactContext(exact, assignment.queryId, contextOverride, frozenKeys);
17579
+ const identity = canonicalJson({
17580
+ providers: normalizedProviders2(rewritten.providers),
17581
+ models: normalizedModels(rewritten.models),
17582
+ location: rewritten.location
17583
+ });
17584
+ const kept = contextsByIdentity.get(identity) ?? rewritten;
17585
+ contextsByIdentity.set(identity, kept);
17586
+ if (edgeRemaps && exact.executionNodeKey && kept.executionNodeKey && exact.executionNodeKey !== kept.executionNodeKey) {
17587
+ edgeRemaps.set(
17588
+ edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey),
17589
+ { targetKey: assignment.targetKey, queryId: assignment.queryId, executionNodeKey: kept.executionNodeKey }
17590
+ );
17591
+ }
17592
+ }
17593
+ return { ...assignment, executionContexts: [...contextsByIdentity.values()] };
17594
+ }
17183
17595
  const { executionContexts: _frozenContexts, ...withoutFrozenContexts } = assignment;
17184
- return { ...withoutFrozenContexts, contextOverride };
17596
+ const locations = contextOverride.locations ?? assignment.contextOverride?.locations;
17597
+ return {
17598
+ ...withoutFrozenContexts,
17599
+ contextOverride: { ...contextOverride, ...locations === void 0 ? {} : { locations } }
17600
+ };
17185
17601
  }
17186
17602
  function upsertTarget(authoring, body, context) {
17187
17603
  const { target } = parseBody2(measurementDraftUpsertTargetRequestSchema, body, "upsert-target");
@@ -17226,24 +17642,68 @@ function mergeTargets(authoring, body) {
17226
17642
  urlMatchers: unique([...survivor.urlMatchers, ...authoring.targets.filter((target) => absorbedSet.has(target.stableKey)).flatMap((target) => target.urlMatchers)])
17227
17643
  };
17228
17644
  const assignments = [];
17229
- const seen2 = /* @__PURE__ */ new Set();
17645
+ const assignmentIndexes = /* @__PURE__ */ new Map();
17230
17646
  for (const assignment of authoring.assignments) {
17231
17647
  const owner = absorbedSet.has(assignment.targetKey) ? targetKey : assignment.targetKey;
17232
- const key = `${owner} ${assignment.queryId}`;
17233
- if (seen2.has(key)) continue;
17234
- seen2.add(key);
17235
- assignments.push({ ...assignment, targetKey: owner });
17648
+ const key = `${owner}\0${assignment.queryId}`;
17649
+ const mapped = { ...assignment, targetKey: owner };
17650
+ const index = assignmentIndexes.get(key);
17651
+ if (index === void 0) {
17652
+ assignmentIndexes.set(key, assignments.length);
17653
+ assignments.push(mapped);
17654
+ continue;
17655
+ }
17656
+ const existing = assignments[index];
17657
+ if (existing.executionContexts === void 0 !== (mapped.executionContexts === void 0)) {
17658
+ throw validationError(
17659
+ `Cannot merge duplicate assignment ${targetKey}/${assignment.queryId} because it combines exact and editable execution contexts. Publish the editable context first or remove one duplicate assignment, then merge.`,
17660
+ { displayToOperator: true }
17661
+ );
17662
+ }
17663
+ if (existing.executionContexts === void 0 && mapped.executionContexts === void 0 && canonicalJson(mutableAssignmentContext(authoring, existing)) !== canonicalJson(mutableAssignmentContext(authoring, mapped))) {
17664
+ throw validationError(
17665
+ `Cannot merge duplicate assignment ${targetKey}/${assignment.queryId} because its editable execution contexts differ. Align their providers, models, and locations or remove one duplicate assignment, then merge.`,
17666
+ { displayToOperator: true }
17667
+ );
17668
+ }
17669
+ const currentIsSurvivor = assignment.targetKey === targetKey;
17670
+ const winner = currentIsSurvivor ? mapped : existing;
17671
+ if (existing.executionContexts === void 0 || mapped.executionContexts === void 0) {
17672
+ assignments[index] = winner;
17673
+ continue;
17674
+ }
17675
+ const contexts = /* @__PURE__ */ new Map();
17676
+ for (const exact of [...existing.executionContexts, ...mapped.executionContexts]) {
17677
+ const identity = exact.executionNodeKey ?? canonicalJson({
17678
+ providers: normalizedProviders2(exact.providers),
17679
+ models: normalizedModels(exact.models),
17680
+ location: exact.location
17681
+ });
17682
+ if (!contexts.has(identity)) contexts.set(identity, exact);
17683
+ }
17684
+ assignments[index] = { ...winner, executionContexts: [...contexts.values()] };
17236
17685
  }
17686
+ const reportingScopes = authoring.reportingScopes?.map((scope) => {
17687
+ const seenEdges = /* @__PURE__ */ new Set();
17688
+ const usageEdges = [];
17689
+ for (const edge of scope.usageEdges) {
17690
+ const next = absorbedSet.has(edge.targetKey) ? { ...edge, targetKey } : edge;
17691
+ const key = measurementV2UsageEdgeKey(next);
17692
+ if (seenEdges.has(key)) continue;
17693
+ seenEdges.add(key);
17694
+ usageEdges.push(next);
17695
+ }
17696
+ return { ...scope, usageEdges };
17697
+ });
17237
17698
  return {
17238
- authoring: {
17699
+ authoring: authoringWithAssignments({
17239
17700
  ...authoring,
17240
17701
  targets: authoring.targets.filter((target) => !absorbedSet.has(target.stableKey)).map((target) => target.stableKey === targetKey ? merged : target),
17241
- assignments,
17242
17702
  groups: authoring.groups.map((group) => ({
17243
17703
  ...group,
17244
17704
  targetKeys: unique(group.targetKeys.map((key) => absorbedSet.has(key) ? targetKey : key))
17245
17705
  }))
17246
- },
17706
+ }, assignments, reportingScopes),
17247
17707
  warnings: []
17248
17708
  };
17249
17709
  }
@@ -17253,16 +17713,16 @@ function excludeTarget(authoring, body) {
17253
17713
  const targetIndex = authoring.targets.indexOf(target);
17254
17714
  const stranded = authoring.assignments.filter((assignment) => assignment.targetKey === targetKey).length;
17255
17715
  if (cleanup === "assignments-and-group-memberships") {
17716
+ const assignments = authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey);
17256
17717
  return {
17257
- authoring: {
17718
+ authoring: authoringWithAssignments({
17258
17719
  ...authoring,
17259
17720
  targets: authoring.targets.map((target2) => target2.stableKey === targetKey ? { ...target2, status: "excluded" } : target2),
17260
- assignments: authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey),
17261
17721
  groups: authoring.groups.map((group) => ({
17262
17722
  ...group,
17263
17723
  targetKeys: group.targetKeys.filter((key) => key !== targetKey)
17264
17724
  }))
17265
- },
17725
+ }, assignments),
17266
17726
  warnings: []
17267
17727
  };
17268
17728
  }
@@ -17297,6 +17757,8 @@ function applyAssignmentsToAuthoring(authoring, request, context) {
17297
17757
  assertAssignmentActionLimit(audience, queryIds);
17298
17758
  const targetByKey = new Map(authoring.targets.map((target) => [target.stableKey, target]));
17299
17759
  const assignments = [...authoring.assignments];
17760
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17761
+ const edgeRemaps = /* @__PURE__ */ new Map();
17300
17762
  const assignmentIndexes = new Map(assignments.map((assignment, index) => [
17301
17763
  `${assignment.targetKey}\0${assignment.queryId}`,
17302
17764
  index
@@ -17320,14 +17782,18 @@ function applyAssignmentsToAuthoring(authoring, request, context) {
17320
17782
  }
17321
17783
  const existing = assignments[index];
17322
17784
  assignments[index] = {
17323
- ...withRequestedContext(existing, request.contextOverride),
17785
+ ...withRequestedContext(existing, request.contextOverride, frozenKeys, edgeRemaps),
17324
17786
  ...existing.classificationSource === "operator" ? {} : { queryClass: proposeQueryClassForTarget(context.queriesById.get(queryId), context.brandNames, targetByKey.get(targetKey)) }
17325
17787
  };
17326
17788
  }
17327
17789
  }
17328
17790
  const requested = audience.targetKeys.length * queryIds.length;
17329
17791
  return {
17330
- authoring: { ...authoring, assignments },
17792
+ authoring: authoringWithAssignments(
17793
+ authoring,
17794
+ assignments,
17795
+ remapReportingScopeEdges(authoring.reportingScopes, edgeRemaps)
17796
+ ),
17331
17797
  warnings: [],
17332
17798
  audience,
17333
17799
  assignments: { requested, added, alreadyPresent: requested - added }
@@ -17370,6 +17836,8 @@ function applyPairedAssignments(authoring, body, context) {
17370
17836
  }
17371
17837
  const targetByKey = new Map(authoring.targets.map((target) => [target.stableKey, target]));
17372
17838
  const assignments = [...authoring.assignments];
17839
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17840
+ const edgeRemaps = /* @__PURE__ */ new Map();
17373
17841
  const assignmentIndexes = new Map(assignments.map((assignment, index) => [
17374
17842
  `${assignment.targetKey}\0${assignment.queryId}`,
17375
17843
  index
@@ -17390,31 +17858,197 @@ function applyPairedAssignments(authoring, body, context) {
17390
17858
  }
17391
17859
  const existing = assignments[index];
17392
17860
  assignments[index] = {
17393
- ...withRequestedContext(existing, contextOverride),
17861
+ ...withRequestedContext(existing, contextOverride, frozenKeys, edgeRemaps),
17394
17862
  ...existing.classificationSource === "operator" ? {} : { queryClass: proposeQueryClassForTarget(context.queriesById.get(queryId), context.brandNames, targetByKey.get(targetKey)) }
17395
17863
  };
17396
17864
  }
17397
- return { authoring: { ...authoring, assignments }, warnings: [] };
17865
+ return {
17866
+ authoring: authoringWithAssignments(
17867
+ authoring,
17868
+ assignments,
17869
+ remapReportingScopeEdges(authoring.reportingScopes, edgeRemaps)
17870
+ ),
17871
+ warnings: []
17872
+ };
17873
+ }
17874
+ function routeMarketsInAuthoring(authoring, request, context) {
17875
+ const assignmentPairs = new Set(authoring.assignments.map((assignment) => `${assignment.targetKey}\0${assignment.queryId}`));
17876
+ const originalScopesByKey = new Map((authoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17877
+ const pairPrunedAuthoring = authoringWithAssignments(authoring, authoring.assignments);
17878
+ const marketKeys = unique(request.marketKeys);
17879
+ const availableScopesByKey = new Map((pairPrunedAuthoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17880
+ for (const marketKey of marketKeys) {
17881
+ const scope = availableScopesByKey.get(marketKey);
17882
+ if (!scope) {
17883
+ throw validationError(`Selected market "${marketKey}" is no longer available. Reload the draft and try again.`, {
17884
+ displayToOperator: true
17885
+ });
17886
+ }
17887
+ }
17888
+ const targetFilter = request.targetKeys ? new Set(unique(request.targetKeys)) : null;
17889
+ if (targetFilter) {
17890
+ for (const targetKey of targetFilter) {
17891
+ const target = requireTarget(pairPrunedAuthoring, targetKey);
17892
+ if (target.status !== "included") {
17893
+ throw validationError(`Property "${target.label}" is ${target.status}, not included.`, { displayToOperator: true });
17894
+ }
17895
+ }
17896
+ }
17897
+ const queryFilter = request.queryIds ? new Set(knownQueryIds(request.queryIds, context)) : null;
17898
+ const selectedMarkets = new Set(marketKeys);
17899
+ const selectsEdge = (edge) => (targetFilter === null || targetFilter.has(edge.targetKey)) && (queryFilter === null || queryFilter.has(edge.queryId));
17900
+ const routableAuthoring = normalizeSelectedOneToOneMarketEdges(
17901
+ pairPrunedAuthoring,
17902
+ selectedMarkets,
17903
+ selectsEdge,
17904
+ context
17905
+ );
17906
+ const routableScopesByKey = new Map((routableAuthoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17907
+ const markets = marketKeys.map((marketKey) => routableScopesByKey.get(marketKey));
17908
+ const staleSelectedEdges = /* @__PURE__ */ new Map();
17909
+ for (const scope of authoring.reportingScopes ?? []) {
17910
+ if (!selectedMarkets.has(scope.stableKey)) continue;
17911
+ for (const edge of scope.usageEdges) {
17912
+ if (!selectsEdge(edge) || assignmentPairs.has(`${edge.targetKey}\0${edge.queryId}`)) continue;
17913
+ staleSelectedEdges.set(measurementV2UsageEdgeKey(edge), edge);
17914
+ }
17915
+ }
17916
+ const selectedEdges = /* @__PURE__ */ new Map();
17917
+ const unselectedUses = /* @__PURE__ */ new Set();
17918
+ for (const scope of routableAuthoring.reportingScopes ?? []) {
17919
+ for (const edge of scope.usageEdges) {
17920
+ const key = measurementV2UsageEdgeKey(edge);
17921
+ if (selectedMarkets.has(scope.stableKey) && selectsEdge(edge)) selectedEdges.set(key, edge);
17922
+ else unselectedUses.add(key);
17923
+ }
17924
+ }
17925
+ const assignmentsByPair = new Map(routableAuthoring.assignments.map((assignment, index) => [
17926
+ `${assignment.targetKey}\0${assignment.queryId}`,
17927
+ { assignment, index }
17928
+ ]));
17929
+ const selectedKeysByAssignment = /* @__PURE__ */ new Map();
17930
+ for (const edge of selectedEdges.values()) {
17931
+ const found = assignmentsByPair.get(`${edge.targetKey}\0${edge.queryId}`);
17932
+ const exact = found?.assignment.executionContexts?.find((item2) => item2.executionNodeKey === edge.executionNodeKey);
17933
+ if (!found || !exact) {
17934
+ throw validationError("A selected market contains a stale execution edge. Reload the draft and review its membership.", {
17935
+ displayToOperator: true,
17936
+ marketEdge: edge
17937
+ });
17938
+ }
17939
+ const keys = selectedKeysByAssignment.get(found.index) ?? /* @__PURE__ */ new Set();
17940
+ keys.add(edge.executionNodeKey);
17941
+ selectedKeysByAssignment.set(found.index, keys);
17942
+ }
17943
+ const selectedEdgeRemaps = /* @__PURE__ */ new Map();
17944
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(routableAuthoring);
17945
+ const assignments = routableAuthoring.assignments.map((assignment, assignmentIndex) => {
17946
+ const selectedKeys = selectedKeysByAssignment.get(assignmentIndex);
17947
+ if (!selectedKeys || assignment.executionContexts === void 0) return assignment;
17948
+ const rewrittenByKey = /* @__PURE__ */ new Map();
17949
+ for (const exact of assignment.executionContexts) {
17950
+ if (!exact.executionNodeKey || !selectedKeys.has(exact.executionNodeKey)) continue;
17951
+ rewrittenByKey.set(
17952
+ exact.executionNodeKey,
17953
+ normalizedExactContext(exact, assignment.queryId, request.contextOverride, frozenKeys)
17954
+ );
17955
+ }
17956
+ const contextsByIdentity = /* @__PURE__ */ new Map();
17957
+ const identityOf = (exact) => canonicalJson({
17958
+ providers: normalizedProviders2(exact.providers),
17959
+ models: normalizedModels(exact.models),
17960
+ location: exact.location
17961
+ });
17962
+ for (const exact of assignment.executionContexts) {
17963
+ const rewritten = exact.executionNodeKey ? rewrittenByKey.get(exact.executionNodeKey) : void 0;
17964
+ const changed = rewritten !== void 0 && identityOf(rewritten) !== identityOf(exact);
17965
+ const originalEdgeKey = exact.executionNodeKey ? edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey) : null;
17966
+ if (!changed || originalEdgeKey !== null && unselectedUses.has(originalEdgeKey)) {
17967
+ contextsByIdentity.set(identityOf(exact), exact);
17968
+ }
17969
+ }
17970
+ for (const exact of assignment.executionContexts) {
17971
+ if (!exact.executionNodeKey || !selectedKeys.has(exact.executionNodeKey)) continue;
17972
+ const rewritten = rewrittenByKey.get(exact.executionNodeKey);
17973
+ const identity = identityOf(rewritten);
17974
+ const kept = contextsByIdentity.get(identity) ?? rewritten;
17975
+ contextsByIdentity.set(identity, kept);
17976
+ if (!kept.executionNodeKey) continue;
17977
+ selectedEdgeRemaps.set(
17978
+ edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey),
17979
+ { targetKey: assignment.targetKey, queryId: assignment.queryId, executionNodeKey: kept.executionNodeKey }
17980
+ );
17981
+ }
17982
+ return { ...assignment, executionContexts: [...contextsByIdentity.values()] };
17983
+ });
17984
+ const marketStats = markets.map((scope) => {
17985
+ const matched = scope.usageEdges.filter(selectsEdge);
17986
+ const stale = (originalScopesByKey.get(scope.stableKey)?.usageEdges ?? []).filter((edge) => selectsEdge(edge) && !assignmentPairs.has(`${edge.targetKey}\0${edge.queryId}`));
17987
+ return {
17988
+ marketKey: scope.stableKey,
17989
+ label: scope.label,
17990
+ matchedEdges: matched.length + stale.length,
17991
+ changedEdges: stale.length + matched.filter((edge) => {
17992
+ const next = selectedEdgeRemaps.get(measurementV2UsageEdgeKey(edge));
17993
+ return next !== void 0 && next.executionNodeKey !== edge.executionNodeKey;
17994
+ }).length
17995
+ };
17996
+ });
17997
+ const reroutedEdges = [...selectedEdges.entries()].filter(([key, edge]) => {
17998
+ const next = selectedEdgeRemaps.get(key);
17999
+ return next !== void 0 && next.executionNodeKey !== edge.executionNodeKey;
18000
+ }).length;
18001
+ const matchedEdges = (/* @__PURE__ */ new Set([...selectedEdges.keys(), ...staleSelectedEdges.keys()])).size;
18002
+ const changedEdges = reroutedEdges + staleSelectedEdges.size;
18003
+ if (changedEdges === 0) {
18004
+ return {
18005
+ authoring: routableAuthoring,
18006
+ warnings: [],
18007
+ markets: marketStats,
18008
+ matchedEdges,
18009
+ changedEdges: 0
18010
+ };
18011
+ }
18012
+ const reportingScopes = (routableAuthoring.reportingScopes ?? []).map((scope) => {
18013
+ if (!selectedMarkets.has(scope.stableKey)) return scope;
18014
+ const seen2 = /* @__PURE__ */ new Set();
18015
+ const usageEdges = [];
18016
+ for (const edge of scope.usageEdges) {
18017
+ const next = selectsEdge(edge) ? selectedEdgeRemaps.get(measurementV2UsageEdgeKey(edge)) ?? edge : edge;
18018
+ const key = measurementV2UsageEdgeKey(next);
18019
+ if (seen2.has(key)) continue;
18020
+ seen2.add(key);
18021
+ usageEdges.push(next);
18022
+ }
18023
+ return { ...scope, usageEdges };
18024
+ });
18025
+ return {
18026
+ authoring: authoringWithAssignments(routableAuthoring, assignments, reportingScopes),
18027
+ warnings: [],
18028
+ markets: marketStats,
18029
+ matchedEdges,
18030
+ changedEdges
18031
+ };
18032
+ }
18033
+ function routeMarkets(authoring, body, context) {
18034
+ const request = parseBody2(measurementDraftRouteMarketsRequestSchema, body, "route-markets");
18035
+ return routeMarketsInAuthoring(authoring, request, context);
17398
18036
  }
17399
18037
  function removeAssignment(authoring, body) {
17400
18038
  const parsed = parseBody2(measurementDraftRemoveAssignmentRequestSchema, body, "remove-assignment");
17401
18039
  const { queryId } = parsed;
17402
18040
  const targetKeys = new Set("targetKeys" in parsed ? parsed.targetKeys : [parsed.targetKey]);
18041
+ const assignments = authoring.assignments.filter((assignment) => !(targetKeys.has(assignment.targetKey) && assignment.queryId === queryId));
17403
18042
  return {
17404
- authoring: {
17405
- ...authoring,
17406
- assignments: authoring.assignments.filter((assignment) => !(targetKeys.has(assignment.targetKey) && assignment.queryId === queryId))
17407
- },
18043
+ authoring: authoringWithAssignments(authoring, assignments),
17408
18044
  warnings: []
17409
18045
  };
17410
18046
  }
17411
18047
  function clearAssignments(authoring, body) {
17412
18048
  const { targetKey } = parseBody2(measurementDraftClearAssignmentsRequestSchema, body, "clear-assignments");
18049
+ const assignments = authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey);
17413
18050
  return {
17414
- authoring: {
17415
- ...authoring,
17416
- assignments: authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey)
17417
- },
18051
+ authoring: authoringWithAssignments(authoring, assignments),
17418
18052
  warnings: []
17419
18053
  };
17420
18054
  }
@@ -17532,6 +18166,8 @@ function applyDraftAction(action, authoring, body, context) {
17532
18166
  return replaceAssignments(authoring, body, context);
17533
18167
  case "apply-paired-assignments":
17534
18168
  return applyPairedAssignments(authoring, body, context);
18169
+ case "route-markets":
18170
+ return routeMarkets(authoring, body, context);
17535
18171
  case "remove-assignment":
17536
18172
  return removeAssignment(authoring, body);
17537
18173
  case "clear-assignments":
@@ -18271,22 +18907,37 @@ var MEASUREMENT_GROUP_MEMBERSHIP_BODY_LIMIT = MEASUREMENT_GROUP_MEMBERSHIP_CSV_M
18271
18907
  function authoringIdentity(authoring) {
18272
18908
  return canonicalJson(authoring);
18273
18909
  }
18910
+ function draftExecutionProviders(authoring) {
18911
+ return [
18912
+ ...authoring.defaultContext.providers,
18913
+ ...authoring.assignments.flatMap((assignment) => [
18914
+ ...assignment.contextOverride?.providers ?? [],
18915
+ ...assignment.executionContexts?.flatMap((context) => context.providers) ?? []
18916
+ ])
18917
+ ];
18918
+ }
18919
+ function storedPlanExecutionProviders(plan) {
18920
+ return plan.schemaVersion === 2 ? plan.executionNodes.flatMap((node) => node.context.providers) : [];
18921
+ }
18274
18922
  function trackedQueriesFor(db, projectId) {
18275
18923
  return db.select({ id: queries.id, query: queries.query }).from(queries).where(eq34(queries.projectId, projectId)).all();
18276
18924
  }
18277
- function compileContextFor(db, project) {
18925
+ function compileContextFor(db, project, opts) {
18278
18926
  return {
18279
18927
  canonicalDomain: project.canonicalDomain,
18280
18928
  ownedDomains: project.ownedDomains,
18281
18929
  brandNames: effectiveBrandNames(project),
18282
18930
  locations: project.locations,
18283
- trackedQueries: trackedQueriesFor(db, project.id)
18931
+ trackedQueries: trackedQueriesFor(db, project.id),
18932
+ ...opts.providerRouteFamilies ? { routeFamilies: opts.providerRouteFamilies } : {},
18933
+ ...opts.providerAdapters ? { providerAdapters: opts.providerAdapters } : {}
18284
18934
  };
18285
18935
  }
18286
18936
  function actionContextFor(db, project) {
18287
18937
  return {
18288
18938
  brandNames: effectiveBrandNames(project),
18289
- queriesById: new Map(trackedQueriesFor(db, project.id).map((query) => [query.id, query.query]))
18939
+ queriesById: new Map(trackedQueriesFor(db, project.id).map((query) => [query.id, query.query])),
18940
+ locationsByLabel: new Map(project.locations.map((location) => [location.label, location]))
18290
18941
  };
18291
18942
  }
18292
18943
  function segmentDescriptorsFor(db, projectId) {
@@ -18318,7 +18969,8 @@ function formatDraftMatcher(matcher) {
18318
18969
  function draftProviderNames(project, opts) {
18319
18970
  return resolveRunProviderSelection({
18320
18971
  projectProviders: project.providers,
18321
- runnableProviders: opts.getRunnableProviderNames?.()
18972
+ runnableProviders: opts.getRunnableProviderNames?.(),
18973
+ routeFamilies: opts.providerRouteFamilies
18322
18974
  });
18323
18975
  }
18324
18976
  function draftModels(project, providers) {
@@ -18629,7 +19281,8 @@ async function measurementDraftRoutes(app, opts = {}) {
18629
19281
  // the exact provider-selection decision enforced by run preflight.
18630
19282
  answerVisibilityProviderReady: resolveRunnableProviderSelection({
18631
19283
  projectProviders: project.providers,
18632
- runnableProviders: opts.getRunnableProviderNames?.()
19284
+ runnableProviders: opts.getRunnableProviderNames?.(),
19285
+ routeFamilies: opts.providerRouteFamilies
18633
19286
  }).runnableProviders.length > 0,
18634
19287
  activeRevision: active?.revision ?? null,
18635
19288
  activeSchemaVersion,
@@ -18826,6 +19479,7 @@ async function measurementDraftRoutes(app, opts = {}) {
18826
19479
  assertDraftEtag(row, ifMatch);
18827
19480
  const before = parseStoredAuthoring(row.authoringJson);
18828
19481
  const result = applyDraftAction(action, before, request.body, actionContextFor(app.db, gate.project));
19482
+ assertProviderRouteScope(request, draftExecutionProviders(result.authoring), [...gate.project.providers, ...draftExecutionProviders(before)], opts.providerRouteFamilies);
18829
19483
  const changed = authoringIdentity(result.authoring) !== authoringIdentity(before);
18830
19484
  const etagVersion = changed ? row.etagVersion + 1 : row.etagVersion;
18831
19485
  const response = mutationResponse(etagVersion, changed, result.warnings, result.authoring);
@@ -18882,7 +19536,7 @@ async function measurementDraftRoutes(app, opts = {}) {
18882
19536
  const before = parseStoredAuthoring(row.authoringJson);
18883
19537
  const result = applyAssignmentsToAuthoring(before, parsed.data, actionContextFor(app.db, project));
18884
19538
  assertMeasurementDraftAuthoringLimits(before, result.authoring);
18885
- const context = compileContextFor(app.db, project);
19539
+ const context = compileContextFor(app.db, project, opts);
18886
19540
  const current = compileMeasurementDraftAssignmentExecution(authoringForCompile(before, project, opts), context);
18887
19541
  const candidate = compileMeasurementDraftAssignmentExecution(authoringForCompile(result.authoring, project, opts), context);
18888
19542
  if (!current.ok || !candidate.ok) {
@@ -18903,6 +19557,40 @@ async function measurementDraftRoutes(app, opts = {}) {
18903
19557
  execution: assignmentExecutionImpact(current.plan, candidate.plan)
18904
19558
  };
18905
19559
  });
19560
+ app.post("/projects/:name/measurement-plan/draft/actions/preview-route-markets", {
19561
+ config: {
19562
+ readSemantic: true,
19563
+ rateLimit: { max: 30, timeWindow: "1 minute" }
19564
+ }
19565
+ }, async (request, reply) => {
19566
+ requireScope(request, MEASUREMENT_PLAN_WRITE_SCOPE);
19567
+ const project = resolveProject(app.db, request.params.name);
19568
+ const parsed = measurementDraftRouteMarketsRequestSchema.safeParse(request.body);
19569
+ if (!parsed.success) throw validationError('Invalid "preview-route-markets" payload', { issues: parsed.error.issues });
19570
+ const row = requireDraft(project);
19571
+ const before = parseStoredAuthoring(row.authoringJson);
19572
+ const result = routeMarketsInAuthoring(before, parsed.data, actionContextFor(app.db, project));
19573
+ assertMeasurementDraftAuthoringLimits(before, result.authoring);
19574
+ const context = compileContextFor(app.db, project, opts);
19575
+ const current = compileMeasurementDraftAssignmentExecution(authoringForCompile(before, project, opts), context);
19576
+ const candidate = compileMeasurementDraftAssignmentExecution(authoringForCompile(result.authoring, project, opts), context);
19577
+ if (!current.ok || !candidate.ok) {
19578
+ throw validationError("The selected market routing has invalid question or provider settings. Review it and try again.", {
19579
+ displayToOperator: true,
19580
+ currentChecks: current.checks,
19581
+ candidateChecks: candidate.checks
19582
+ });
19583
+ }
19584
+ const draftEtag = measurementDraftEtag(row.etagVersion);
19585
+ reply.header("etag", draftEtag);
19586
+ return {
19587
+ draftEtag,
19588
+ markets: result.markets,
19589
+ matchedEdges: result.matchedEdges,
19590
+ changedEdges: result.changedEdges,
19591
+ execution: assignmentExecutionImpact(current.plan, candidate.plan)
19592
+ };
19593
+ });
18906
19594
  app.post("/projects/:name/measurement-plan/draft/actions/preview-group-membership", {
18907
19595
  bodyLimit: MEASUREMENT_GROUP_MEMBERSHIP_BODY_LIMIT,
18908
19596
  config: {
@@ -19008,7 +19696,7 @@ async function measurementDraftRoutes(app, opts = {}) {
19008
19696
  requireScope(request, MEASUREMENT_PLAN_WRITE_SCOPE);
19009
19697
  const project = resolveProject(app.db, request.params.name);
19010
19698
  const authoring = authoringForCompile(parseStoredAuthoring(requireDraft(project).authoringJson), project, opts);
19011
- const compiled = compileMeasurementDraft(authoring, compileContextFor(app.db, project));
19699
+ const compiled = compileMeasurementDraft(authoring, compileContextFor(app.db, project, opts));
19012
19700
  if (!compiled.ok) return { ok: false, compiledChecksum: null, checks: compiled.checks };
19013
19701
  return {
19014
19702
  ok: true,
@@ -19024,7 +19712,7 @@ async function measurementDraftRoutes(app, opts = {}) {
19024
19712
  requireScope(request, MEASUREMENT_PLAN_WRITE_SCOPE);
19025
19713
  const project = resolveProject(app.db, request.params.name);
19026
19714
  const authoring = authoringForCompile(parseStoredAuthoring(requireDraft(project).authoringJson), project, opts);
19027
- const compiled = compileMeasurementDraft(authoring, compileContextFor(app.db, project));
19715
+ const compiled = compileMeasurementDraft(authoring, compileContextFor(app.db, project, opts));
19028
19716
  if (!compiled.ok) return { ok: false, compiledChecksum: null, checks: compiled.checks, diff: null };
19029
19717
  const active = activePlanVersionRow(app.db, project.id);
19030
19718
  const comparable = active && active.schemaVersion === 2 ? parseV2Plan(active) : null;
@@ -19052,7 +19740,7 @@ async function measurementDraftRoutes(app, opts = {}) {
19052
19740
  const parsed = measurementDraftPublishRequestSchema.safeParse(request.body);
19053
19741
  if (!parsed.success) throw validationError('Invalid "publish" payload', { issues: parsed.error.issues });
19054
19742
  const ifMatch = requireIfMatch(request);
19055
- const context = compileContextFor(app.db, gate.project);
19743
+ const context = compileContextFor(app.db, gate.project, opts);
19056
19744
  const now = /* @__PURE__ */ new Date();
19057
19745
  let pinEffect = null;
19058
19746
  const settled = app.db.transaction((tx) => {
@@ -19084,6 +19772,13 @@ async function measurementDraftRoutes(app, opts = {}) {
19084
19772
  if (!compiled.ok) {
19085
19773
  throw validationError("The measurement draft does not compile.", { checks: compiled.checks });
19086
19774
  }
19775
+ const activeProviders = active ? storedPlanExecutionProviders(parseStoredMeasurementPlanAnyVersion(active.canonicalJson)) : [];
19776
+ assertProviderRouteScope(
19777
+ request,
19778
+ compiled.plan.executionNodes.flatMap((node) => node.context.providers),
19779
+ [...gate.project.providers, ...activeProviders],
19780
+ opts.providerRouteFamilies
19781
+ );
19087
19782
  if (compiled.plan.compiledChecksum !== parsed.data.expectedCompiledChecksum) {
19088
19783
  throw measurementCompiledChecksumConflict(parsed.data.expectedCompiledChecksum, compiled.plan.compiledChecksum);
19089
19784
  }
@@ -23432,7 +24127,8 @@ function stableNewQueryId(projectId, normalizedText) {
23432
24127
  function providerNames(project, opts) {
23433
24128
  return resolveRunProviderSelection({
23434
24129
  projectProviders: project.providers,
23435
- runnableProviders: opts.getRunnableProviderNames?.()
24130
+ runnableProviders: opts.getRunnableProviderNames?.(),
24131
+ routeFamilies: opts.providerRouteFamilies
23436
24132
  });
23437
24133
  }
23438
24134
  function modelMap(project, providers) {
@@ -23447,20 +24143,21 @@ function simpleDispatchEngines(project, opts) {
23447
24143
  const runnable = opts.getRunnableProviderNames?.();
23448
24144
  const selected = resolveRunProviderSelection({
23449
24145
  projectProviders: project.providers,
23450
- runnableProviders: runnable
24146
+ runnableProviders: runnable,
24147
+ routeFamilies: opts.providerRouteFamilies
23451
24148
  });
23452
- const available = runnable === void 0 ? null : new Set(runnable.map((provider) => provider.trim().toLocaleLowerCase("en")).filter(Boolean));
24149
+ const available = runnable === void 0 ? null : runnable.map((provider) => provider.trim().toLocaleLowerCase("en")).filter(Boolean);
23453
24150
  const summaries = new Map((opts.providerSummary ?? []).map((summary3) => [
23454
24151
  summary3.name.trim().toLocaleLowerCase("en"),
23455
24152
  summary3
23456
24153
  ]));
23457
24154
  const overrides = project.providerModels;
23458
- return selected.filter((provider) => available === null || available.has(provider)).map((provider) => ({
24155
+ return selected.filter((provider) => available === null || isProviderAvailable(provider, available, opts.providerRouteFamilies)).map((provider) => ({
23459
24156
  provider,
23460
24157
  // `undefined` is materially different from an intentionally blank model
23461
24158
  // override/configuration, just as it is in JobRunner, which also resolves
23462
24159
  // a retired override to the id that answers now.
23463
- requestedModel: resolvedOverride(provider, overrides[provider]) ?? summaries.get(provider)?.model ?? null
24160
+ requestedModel: resolvedOverride(provider, overrides[provider]) ?? resolveProviderRoute(provider, opts.providerRouteFamilies)?.selection ?? summaries.get(provider)?.model ?? null
23464
24161
  })).sort((left, right) => compareText(left.provider, right.provider));
23465
24162
  }
23466
24163
  function resolvedOverride(provider, model) {
@@ -23873,7 +24570,7 @@ function trackedRows(db, state, queryRows2, plan, opts) {
23873
24570
  const node = nodes.get(assignment.executionNodeKey);
23874
24571
  if (!node) continue;
23875
24572
  const existing = assignments.get(assignment.targetKey);
23876
- const edgeKey2 = measurementV2UsageEdgeKey({
24573
+ const edgeKey3 = measurementV2UsageEdgeKey({
23877
24574
  executionNodeKey: assignment.executionNodeKey,
23878
24575
  targetKey: assignment.targetKey,
23879
24576
  queryId
@@ -23881,12 +24578,12 @@ function trackedRows(db, state, queryRows2, plan, opts) {
23881
24578
  const source = assignment.classificationSource ?? "frozen";
23882
24579
  if (existing) {
23883
24580
  existing.contexts.push(node.context);
23884
- existing.marketKeys.push(...marketsByEdge.get(edgeKey2) ?? []);
24581
+ existing.marketKeys.push(...marketsByEdge.get(edgeKey3) ?? []);
23885
24582
  } else {
23886
24583
  assignments.set(assignment.targetKey, {
23887
24584
  targetKey: assignment.targetKey,
23888
24585
  groupKeys: [...groupsByTarget.get(assignment.targetKey) ?? []].sort(compareText),
23889
- marketKeys: [...marketsByEdge.get(edgeKey2) ?? []],
24586
+ marketKeys: [...marketsByEdge.get(edgeKey3) ?? []],
23890
24587
  queryClass: assignment.queryClass,
23891
24588
  classificationSource: source,
23892
24589
  contexts: [node.context]
@@ -24212,8 +24909,8 @@ function addMarketEdge(plan, marketKey, edge) {
24212
24909
  const index = scopes.findIndex((scope) => scope.stableKey === marketKey);
24213
24910
  if (index === -1) throw validationError(`Selected market "${marketKey}" is not in the active plan.`);
24214
24911
  const existing = scopes[index];
24215
- const edgeKey2 = measurementV2UsageEdgeKey(edge);
24216
- if (existing.usageEdges.some((candidate) => measurementV2UsageEdgeKey(candidate) === edgeKey2)) return plan;
24912
+ const edgeKey3 = measurementV2UsageEdgeKey(edge);
24913
+ if (existing.usageEdges.some((candidate) => measurementV2UsageEdgeKey(candidate) === edgeKey3)) return plan;
24217
24914
  scopes[index] = { ...existing, usageEdges: [...existing.usageEdges, edge] };
24218
24915
  plan.reportingScopes = scopes;
24219
24916
  return plan;
@@ -24221,7 +24918,7 @@ function addMarketEdge(plan, marketKey, edge) {
24221
24918
  function assignmentKey(targetKey, queryId, executionNodeKey) {
24222
24919
  return `${targetKey}\0${queryId}\0${executionNodeKey}`;
24223
24920
  }
24224
- function edgeKey(edge) {
24921
+ function edgeKey2(edge) {
24225
24922
  return measurementV2UsageEdgeKey(edge);
24226
24923
  }
24227
24924
  function queryIdsByNormalized(state) {
@@ -24314,19 +25011,19 @@ function removeAdvancedAssignments(plan, queryId, targetKeys) {
24314
25011
  }
24315
25012
  function removeMarketMembership(plan, queryId, targetKeys, marketKeys) {
24316
25013
  if (marketKeys.size === 0 || plan.reportingScopes === void 0) return plan;
24317
- const selectedEdgeKeys = new Set(plan.reportingScopes.filter((scope) => marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).filter((edge) => edge.queryId === queryId && targetKeys.has(edge.targetKey)).map(edgeKey));
25014
+ const selectedEdgeKeys = new Set(plan.reportingScopes.filter((scope) => marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).filter((edge) => edge.queryId === queryId && targetKeys.has(edge.targetKey)).map(edgeKey2));
24318
25015
  if (selectedEdgeKeys.size === 0) return plan;
24319
- const retainedByAnotherMarket = new Set(plan.reportingScopes.filter((scope) => !marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey));
25016
+ const retainedByAnotherMarket = new Set(plan.reportingScopes.filter((scope) => !marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey2));
24320
25017
  const removableEdgeKeys = new Set([...selectedEdgeKeys].filter((key) => !retainedByAnotherMarket.has(key)));
24321
25018
  const reportingScopes = plan.reportingScopes.map((scope) => !marketKeys.has(scope.stableKey) ? scope : {
24322
25019
  ...scope,
24323
- usageEdges: scope.usageEdges.filter((edge) => !selectedEdgeKeys.has(edgeKey(edge)))
25020
+ usageEdges: scope.usageEdges.filter((edge) => !selectedEdgeKeys.has(edgeKey2(edge)))
24324
25021
  });
24325
25022
  if (removableEdgeKeys.size === 0) {
24326
25023
  return { ...plan, reportingScopes };
24327
25024
  }
24328
- const usageEdges = plan.usageEdges.filter((edge) => !removableEdgeKeys.has(edgeKey(edge)));
24329
- const assignments = plan.assignments.filter((assignment) => !removableEdgeKeys.has(edgeKey({
25025
+ const usageEdges = plan.usageEdges.filter((edge) => !removableEdgeKeys.has(edgeKey2(edge)));
25026
+ const assignments = plan.assignments.filter((assignment) => !removableEdgeKeys.has(edgeKey2({
24330
25027
  executionNodeKey: assignment.executionNodeKey,
24331
25028
  targetKey: assignment.targetKey,
24332
25029
  queryId: assignment.queryId
@@ -24361,7 +25058,7 @@ function ensureAdvancedEdge(plan, state, target, queryId, queryText, queryClass,
24361
25058
  executionNodeKey: compiled.edge.executionNodeKey
24362
25059
  });
24363
25060
  }
24364
- if (!plan.usageEdges.some((edge) => edgeKey(edge) === edgeKey(compiled.edge))) {
25061
+ if (!plan.usageEdges.some((edge) => edgeKey2(edge) === edgeKey2(compiled.edge))) {
24365
25062
  plan.usageEdges.push(compiled.edge);
24366
25063
  }
24367
25064
  return compiled.edge;
@@ -24372,7 +25069,7 @@ function applyOperatorClass(plan, queryId, targetKey, queryClass, executionNodeK
24372
25069
  if (assignment.queryId !== queryId || assignment.targetKey !== targetKey) continue;
24373
25070
  if (executionNodeKeys && !executionNodeKeys.has(assignment.executionNodeKey)) continue;
24374
25071
  if (assignment.queryClass !== queryClass || assignment.classificationSource !== "operator") {
24375
- if (marketKeys?.size && (plan.reportingScopes ?? []).some((scope) => !marketKeys.has(scope.stableKey) && scope.usageEdges.some((edge) => edgeKey(edge) === edgeKey(assignment)))) {
25072
+ if (marketKeys?.size && (plan.reportingScopes ?? []).some((scope) => !marketKeys.has(scope.stableKey) && scope.usageEdges.some((edge) => edgeKey2(edge) === edgeKey2(assignment)))) {
24376
25073
  throw validationError("This assignment is shared with another market. Change its classification from the Property or Whole site scope.");
24377
25074
  }
24378
25075
  assignment.queryClass = queryClass;
@@ -24423,21 +25120,21 @@ function candidateDiff(state, nextRows, plan, reusedQueryIds, mutatedQueryIds, s
24423
25120
  const unchangedIds = [...afterIds].filter((id) => !addedIds.includes(id) && !reusedIds.includes(id) && !removedIds.has(id));
24424
25121
  const removedAssignments = /* @__PURE__ */ new Map();
24425
25122
  if (state.active && plan && scopedRemovalQueryIds.size > 0) {
24426
- const remainingEdges = new Set(plan.usageEdges.map(edgeKey));
24427
- const remainingScopes = new Map((plan.reportingScopes ?? []).map((scope) => [scope.stableKey, new Set(scope.usageEdges.map(edgeKey))]));
25123
+ const remainingEdges = new Set(plan.usageEdges.map(edgeKey2));
25124
+ const remainingScopes = new Map((plan.reportingScopes ?? []).map((scope) => [scope.stableKey, new Set(scope.usageEdges.map(edgeKey2))]));
24428
25125
  const recordRemoved = (edge) => {
24429
25126
  if (!scopedRemovalQueryIds.has(edge.queryId)) return;
24430
25127
  const keys = removedAssignments.get(edge.queryId) ?? /* @__PURE__ */ new Set();
24431
- keys.add(edgeKey(edge));
25128
+ keys.add(edgeKey2(edge));
24432
25129
  removedAssignments.set(edge.queryId, keys);
24433
25130
  };
24434
25131
  for (const edge of state.active.plan.usageEdges) {
24435
- if (!remainingEdges.has(edgeKey(edge))) recordRemoved(edge);
25132
+ if (!remainingEdges.has(edgeKey2(edge))) recordRemoved(edge);
24436
25133
  }
24437
25134
  for (const scope of state.active.plan.reportingScopes ?? []) {
24438
25135
  const remaining = remainingScopes.get(scope.stableKey);
24439
25136
  for (const edge of scope.usageEdges) {
24440
- if (!remaining?.has(edgeKey(edge))) recordRemoved(edge);
25137
+ if (!remaining?.has(edgeKey2(edge))) recordRemoved(edge);
24441
25138
  }
24442
25139
  }
24443
25140
  }
@@ -24630,8 +25327,8 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24630
25327
  const audience = edit.audience === void 0 ? null : resolveAudience(requireAdvanced(state).plan, edit.audience);
24631
25328
  const targetKeys = audience ? new Set(audience.targetKeys) : null;
24632
25329
  const marketKeys = new Set(audience?.marketKeys ?? []);
24633
- const marketEdges = marketKeys.size === 0 ? null : new Set((plan.reportingScopes ?? []).filter((scope) => marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey));
24634
- const selectedEdges = plan.usageEdges.filter((edge) => edge.queryId === edit.queryId && (!targetKeys || targetKeys.has(edge.targetKey)) && (!marketEdges || marketEdges.has(edgeKey(edge))));
25330
+ const marketEdges = marketKeys.size === 0 ? null : new Set((plan.reportingScopes ?? []).filter((scope) => marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey2));
25331
+ const selectedEdges = plan.usageEdges.filter((edge) => edge.queryId === edit.queryId && (!targetKeys || targetKeys.has(edge.targetKey)) && (!marketEdges || marketEdges.has(edgeKey2(edge))));
24635
25332
  if (audience && selectedEdges.length === 0) throw validationError("This query has no assignments in the selected scope.");
24636
25333
  if (edit.queryClass !== void 0 && selectedEdges.length === 0) throw validationError("This query has no assignments to classify.");
24637
25334
  if (!textChanged && edit.queryClass === void 0) return plan;
@@ -24645,7 +25342,7 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24645
25342
  const proposed = edit.queryClass === null ? proposeQueryClassForTarget(textChanged ? text : oldText, effectiveBrandNames(state.project), target) : edit.queryClass ?? assignment.queryClass;
24646
25343
  if (proposed === "unclassified") throw validationError("The server could not classify this portfolio query.");
24647
25344
  const classificationSource = edit.queryClass === void 0 ? assignment.classificationSource : edit.queryClass === null ? "server" : "operator";
24648
- const scopes = (plan.reportingScopes ?? []).filter((scope) => scope.usageEdges.some((member) => edgeKey(member) === edgeKey(edge)));
25345
+ const scopes = (plan.reportingScopes ?? []).filter((scope) => scope.usageEdges.some((member) => edgeKey2(member) === edgeKey2(edge)));
24649
25346
  return { edge, assignment, node, target, queryClass: proposed, classificationSource, scopes };
24650
25347
  });
24651
25348
  if (!textChanged) {
@@ -24683,7 +25380,7 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24683
25380
  const createdAssignment = plan.assignments.find((candidate) => assignmentKey(candidate.targetKey, candidate.queryId, candidate.executionNodeKey) === assignmentKey(edge.targetKey, edge.queryId, edge.executionNodeKey));
24684
25381
  if (record2.classificationSource === void 0) delete createdAssignment.classificationSource;
24685
25382
  }
24686
- if (!plan.usageEdges.some((candidate) => edgeKey(candidate) === edgeKey(edge))) plan.usageEdges.push(edge);
25383
+ if (!plan.usageEdges.some((candidate) => edgeKey2(candidate) === edgeKey2(edge))) plan.usageEdges.push(edge);
24687
25384
  for (const scope of record2.scopes) {
24688
25385
  if (marketKeys.size === 0 || marketKeys.has(scope.stableKey)) addMarketEdge(plan, scope.stableKey, edge);
24689
25386
  }
@@ -25400,6 +26097,7 @@ var ApplyPreviewRollback = class extends Error {
25400
26097
  preview;
25401
26098
  };
25402
26099
  async function applyRoutes(app, opts) {
26100
+ const routeFamilies = providerRouteFamilies(opts?.providerAdapters);
25403
26101
  const allowLoopback = opts?.allowLoopbackWebhooks === true;
25404
26102
  const notifyProjectCreated = (projectId, projectName) => {
25405
26103
  try {
@@ -25423,7 +26121,7 @@ async function applyRoutes(app, opts) {
25423
26121
  ...config.spec.schedule?.providers ?? []
25424
26122
  ];
25425
26123
  if (allProviders.length) {
25426
- const invalid = allProviders.filter((p) => !validNames.includes(p));
26124
+ const invalid = invalidProviderSelections(allProviders, validNames, opts?.providerAdapters, ProviderWorkflows["visibility-sweep"]);
25427
26125
  if (invalid.length) {
25428
26126
  throw validationError(`Invalid provider(s): ${[...new Set(invalid)].join(", ")}. Must be one of: ${validNames.join(", ")}`, {
25429
26127
  invalidProviders: [...new Set(invalid)],
@@ -25483,7 +26181,7 @@ async function applyRoutes(app, opts) {
25483
26181
  const name = config.metadata.name;
25484
26182
  const managesQueries = "queries" in rawSpec || "keywords" in rawSpec;
25485
26183
  const configQueries = resolveConfigSpecQueries(config.spec);
25486
- const target = app.db.select({ id: projects.id, providerModels: projects.providerModels }).from(projects).where(eq43(projects.name, name)).get();
26184
+ const target = app.db.select({ id: projects.id, providerModels: projects.providerModels, providers: projects.providers }).from(projects).where(eq43(projects.name, name)).get();
25487
26185
  const scopedProjectId = request.apiKey?.projectId;
25488
26186
  if (scopedProjectId) {
25489
26187
  if (!target || target.id !== scopedProjectId) {
@@ -25496,6 +26194,7 @@ async function applyRoutes(app, opts) {
25496
26194
  notificationPlan = planNotificationSet(storedNotifications, config.spec.notifications);
25497
26195
  }
25498
26196
  assertProviderModelScope(request, target?.providerModels ?? {}, providerModels, specProviders);
26197
+ assertProviderRouteScope(request, [...specProviders, ...config.spec.schedule?.providers ?? []], target?.providers ?? [], routeFamilies);
25499
26198
  const competitorPreview = planCompetitorSet(
25500
26199
  target ? readStoredCompetitors(app.db, target.id) : [],
25501
26200
  competitorWrites,
@@ -25773,7 +26472,7 @@ async function applyRoutes(app, opts) {
25773
26472
  }
25774
26473
 
25775
26474
  // ../api-routes/src/history.ts
25776
- import { and as and35, asc as asc8, count as count2, getTableColumns as getTableColumns2, desc as desc17, eq as eq44, gte as gte6, inArray as inArray22, like as like2, lte as lte6, ne as ne9, notInArray as notInArray2, or as or9, sql as sql10 } from "drizzle-orm";
26475
+ import { and as and35, asc as asc8, count as count2, getTableColumns as getTableColumns2, desc as desc17, eq as eq44, gte as gte6, inArray as inArray22, like as like3, lte as lte6, ne as ne9, notInArray as notInArray2, or as or9, sql as sql10 } from "drizzle-orm";
25777
26476
  async function historyRoutes(app) {
25778
26477
  app.post("/projects/:name/results/clear", async (request) => {
25779
26478
  requireAdminSession(request);
@@ -26136,8 +26835,8 @@ function addAuditHistoryFilters(filters, query) {
26136
26835
  if (query.action) filters.push(eq44(auditLog.action, query.action));
26137
26836
  if (query.actor === "api") filters.push(or9(
26138
26837
  eq44(auditLog.actor, "api"),
26139
- like2(auditLog.actor, "api-key:%"),
26140
- like2(auditLog.actor, "user:%")
26838
+ like3(auditLog.actor, "api-key:%"),
26839
+ like3(auditLog.actor, "user:%")
26141
26840
  ));
26142
26841
  else if (query.actor) filters.push(eq44(auditLog.actor, query.actor));
26143
26842
  if (query.entityType) filters.push(eq44(auditLog.entityType, query.entityType));
@@ -26714,7 +27413,7 @@ async function analyticsRoutes(app) {
26714
27413
  const latestOutsideWindow = latestRuns?.find((run) => cutoff && run.createdAt < cutoff);
26715
27414
  if (latestOutsideWindow) {
26716
27415
  throw validationError(
26717
- `The latest sweep (run "${latestOutsideWindow.id}") is older than the ${window} window. Omit window, or widen it, to read it.`
27416
+ `The latest AI Visibility check (run "${latestOutsideWindow.id}") is older than the ${window} window. Omit window, or widen it, to read it.`
26718
27417
  );
26719
27418
  }
26720
27419
  const windowRuns = app.db.select().from(runs).where(and36(
@@ -27107,7 +27806,7 @@ function buildCategoryCounts(counts2) {
27107
27806
  }
27108
27807
 
27109
27808
  // ../api-routes/src/intelligence.ts
27110
- import { eq as eq46, desc as desc19, and as and37, inArray as inArray24, like as like3 } from "drizzle-orm";
27809
+ import { eq as eq46, desc as desc19, and as and37, inArray as inArray24, like as like4 } from "drizzle-orm";
27111
27810
  var SEVERITY_RANK = { low: 0, medium: 1, high: 2, critical: 3 };
27112
27811
  function severitiesAtOrAbove(min2) {
27113
27812
  const floor = SEVERITY_RANK[min2];
@@ -27232,7 +27931,7 @@ async function intelligenceRoutes(app) {
27232
27931
  const typeFilter = request.query.type?.trim();
27233
27932
  if (typeFilter) {
27234
27933
  conditions.push(
27235
- typeFilter.endsWith("*") ? like3(insights.type, `${typeFilter.slice(0, -1)}%`) : eq46(insights.type, typeFilter)
27934
+ typeFilter.endsWith("*") ? like4(insights.type, `${typeFilter.slice(0, -1)}%`) : eq46(insights.type, typeFilter)
27236
27935
  );
27237
27936
  }
27238
27937
  const severityFilter = request.query.severity?.trim();
@@ -29153,7 +29852,7 @@ function buildOrganicEvidence(db, projectName, periodDays) {
29153
29852
  if (visibility && visibility.ageDays > 30) {
29154
29853
  limitations.push({
29155
29854
  code: "stale-visibility-sweep",
29156
- detail: `The latest answer-visibility sweep is ${Math.floor(visibility.ageDays)} days old and may not represent current model behavior.`
29855
+ detail: `The latest AI Visibility check is ${Math.floor(visibility.ageDays)} days old and may not represent current model behavior.`
29157
29856
  });
29158
29857
  }
29159
29858
  return {
@@ -30118,7 +30817,9 @@ var CSV_COLUMNS = [
30118
30817
  "recommended_competitors_json",
30119
30818
  "answer_text",
30120
30819
  "grounding_sources_json",
30121
- "search_queries_json"
30820
+ "search_queries_json",
30821
+ // Vendor-neutral evidence (search answer services); empty for engines.
30822
+ "answer_evidence_json"
30122
30823
  ];
30123
30824
  function parseFormat(value) {
30124
30825
  if (value === void 0 || value === "" || value === "json") return "json";
@@ -30204,7 +30905,8 @@ function renderResultsExportCsv(report) {
30204
30905
  JSON.stringify(record2.recommendedCompetitors),
30205
30906
  record2.answerText,
30206
30907
  JSON.stringify(record2.groundingSources),
30207
- JSON.stringify(record2.searchQueries)
30908
+ JSON.stringify(record2.searchQueries),
30909
+ record2.answerEvidence ? JSON.stringify(record2.answerEvidence) : null
30208
30910
  ].map(csvCell).join(","));
30209
30911
  return [CSV_COLUMNS.join(","), ...rows].join("\r\n") + "\r\n";
30210
30912
  }
@@ -30252,7 +30954,8 @@ async function resultsExportRoutes(app) {
30252
30954
  competitorOverlap: querySnapshots.competitorOverlap,
30253
30955
  recommendedCompetitors: querySnapshots.recommendedCompetitors,
30254
30956
  answerText: querySnapshots.answerText,
30255
- rawResponse: querySnapshots.rawResponse
30957
+ rawResponse: querySnapshots.rawResponse,
30958
+ answerEvidence: querySnapshots.answerEvidence
30256
30959
  }).from(querySnapshots).innerJoin(runs, eq54(querySnapshots.runId, runs.id)).leftJoin(queries, eq54(querySnapshots.queryId, queries.id)).where(and46(...conditions)).orderBy(asc9(runs.createdAt), asc9(runs.id), asc9(querySnapshots.createdAt), asc9(querySnapshots.id)).all();
30257
30960
  const records = rows.map((row) => {
30258
30961
  const evidence = readEvidence(row.rawResponse);
@@ -30286,7 +30989,8 @@ async function resultsExportRoutes(app) {
30286
30989
  recommendedCompetitors: row.recommendedCompetitors,
30287
30990
  answerText: row.answerText,
30288
30991
  groundingSources: evidence.groundingSources,
30289
- searchQueries: evidence.searchQueries
30992
+ searchQueries: evidence.searchQueries,
30993
+ answerEvidence: row.answerEvidence ?? null
30290
30994
  };
30291
30995
  });
30292
30996
  const dto = {
@@ -30319,7 +31023,7 @@ async function resultsExportRoutes(app) {
30319
31023
  }
30320
31024
 
30321
31025
  // ../api-routes/src/composites.ts
30322
- import { eq as eq55, and as and47, desc as desc25, sql as sql18, like as like4, or as or13, inArray as inArray28 } from "drizzle-orm";
31026
+ import { eq as eq55, and as and47, desc as desc25, sql as sql18, like as like5, or as or13, inArray as inArray28 } from "drizzle-orm";
30323
31027
  var TOP_INSIGHT_LIMIT = 5;
30324
31028
  var SEARCH_HIT_HARD_LIMIT = 50;
30325
31029
  var SEARCH_SNIPPET_RADIUS = 80;
@@ -30355,7 +31059,8 @@ async function compositeRoutes(app, options) {
30355
31059
  const admissionParams = {
30356
31060
  projectId: project.id,
30357
31061
  now: (/* @__PURE__ */ new Date()).toISOString(),
30358
- runnableProviders: options.getRunnableProviderNames?.()
31062
+ runnableProviders: options.getRunnableProviderNames?.(),
31063
+ routeFamilies: options.providerRouteFamilies
30359
31064
  };
30360
31065
  const admission = runAdmissionState(app.db, admissionParams);
30361
31066
  const manualAdmission = runAdmissionState(app.db, { ...admissionParams, selection: RunTriggers.manual });
@@ -30531,7 +31236,7 @@ async function compositeRoutes(app, options) {
30531
31236
  sql18`${querySnapshots.citedDomains} LIKE ${pattern} ESCAPE '\\'`,
30532
31237
  sql18`${querySnapshots.citedUrls} LIKE ${pattern} ESCAPE '\\'`,
30533
31238
  sql18`${querySnapshots.rawResponse} LIKE ${pattern} ESCAPE '\\'`,
30534
- like4(queries.query, pattern)
31239
+ like5(queries.query, pattern)
30535
31240
  )
30536
31241
  )
30537
31242
  ).orderBy(desc25(querySnapshots.createdAt)).limit(limit + 1).all());
@@ -30539,8 +31244,8 @@ async function compositeRoutes(app, options) {
30539
31244
  and47(
30540
31245
  eq55(insights.projectId, project.id),
30541
31246
  or13(
30542
- like4(insights.title, pattern),
30543
- like4(insights.query, pattern),
31247
+ like5(insights.title, pattern),
31248
+ like5(insights.query, pattern),
30544
31249
  sql18`${insights.recommendation} LIKE ${pattern} ESCAPE '\\'`,
30545
31250
  sql18`${insights.cause} LIKE ${pattern} ESCAPE '\\'`
30546
31251
  )
@@ -30839,7 +31544,7 @@ function buildRunStatusScore(allRuns) {
30839
31544
  value: "None",
30840
31545
  delta: "No runs yet",
30841
31546
  tone: "neutral",
30842
- description: "Trigger a visibility sweep to start tracking.",
31547
+ description: "Run an AI Visibility check to start tracking.",
30843
31548
  tooltip,
30844
31549
  trend: []
30845
31550
  };
@@ -30888,7 +31593,7 @@ function buildAttentionItems(insightRows, allRuns) {
30888
31593
  id: "stale_visibility",
30889
31594
  tone: "caution",
30890
31595
  title: "Stale visibility data",
30891
- detail: `Last visibility sweep was ${latestVisRun.createdAt}; integration syncs have run since.`,
31596
+ detail: `Last AI Visibility check was ${latestVisRun.createdAt}; integration syncs have run since.`,
30892
31597
  actionLabel: "Stale",
30893
31598
  href: "#runs"
30894
31599
  });
@@ -32082,11 +32787,13 @@ var SCHEMA_TABLE = {
32082
32787
  MeasurementDraftPreviewAssignmentsResponse: measurementDraftPreviewAssignmentsResponseSchema,
32083
32788
  MeasurementDraftPreviewGroupMembershipRequest: measurementDraftPreviewGroupMembershipRequestSchema,
32084
32789
  MeasurementDraftPreviewGroupMembershipResponse: measurementDraftPreviewGroupMembershipResponseSchema,
32790
+ MeasurementDraftPreviewMarketRoutingResponse: measurementDraftPreviewMarketRoutingResponseSchema,
32085
32791
  MeasurementDraftRebindTargetRequest: measurementDraftRebindTargetRequestSchema,
32086
32792
  MeasurementDraftRemoveAssignmentRequest: measurementDraftRemoveAssignmentRequestSchema,
32087
32793
  MeasurementDraftRemoveCompetitorRequest: measurementDraftRemoveCompetitorRequestSchema,
32088
32794
  MeasurementDraftRemoveGroupRequest: measurementDraftRemoveGroupRequestSchema,
32089
32795
  MeasurementDraftReplaceAssignmentsRequest: measurementDraftReplaceAssignmentsRequestSchema,
32796
+ MeasurementDraftRouteMarketsRequest: measurementDraftRouteMarketsRequestSchema,
32090
32797
  MeasurementDraftRenameTargetRequest: measurementDraftRenameTargetRequestSchema,
32091
32798
  MeasurementChangesResponse: measurementChangesResponseSchema,
32092
32799
  MeasurementDataQualityResponse: measurementDataQualityResponseSchema,
@@ -32463,8 +33170,13 @@ var providerNameParameter = {
32463
33170
  name: "name",
32464
33171
  in: "path",
32465
33172
  required: true,
32466
- description: "Provider name.",
32467
- schema: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] }
33173
+ description: "Registered API provider connection name. OpenRouter settings use the bare `openrouter` connection id, never a model route.",
33174
+ schema: { type: "string", minLength: 1 }
33175
+ };
33176
+ var queryGenerationProviderSchema = {
33177
+ type: "string",
33178
+ minLength: 1,
33179
+ description: "Configured sweep provider. OpenRouter models use `openrouter:publisher/model`; the bare `openrouter` connection is not executable."
32468
33180
  };
32469
33181
  var locationLabelParameter = {
32470
33182
  name: "label",
@@ -33303,6 +34015,22 @@ var routeCatalog = [
33303
34015
  description: "Takes explicit (targetKey, queryId) pairs, so N pairs create at most N assignments. Use it when each question names its own Property; `apply-assignments` is a cross product and would multiply the two lists together.",
33304
34016
  request: "MeasurementDraftApplyPairedAssignmentsRequest"
33305
34017
  }),
34018
+ measurementDraftAction({
34019
+ action: "preview-route-markets",
34020
+ summary: "Preview exact market engine routing",
34021
+ description: "Previews provider and model changes for exact edges in the selected markets. Frozen locations and unrelated or shared market edges are preserved.",
34022
+ request: "MeasurementDraftRouteMarketsRequest",
34023
+ response: "MeasurementDraftPreviewMarketRoutingResponse",
34024
+ responseDescription: "Matched market edges and execution impact returned.",
34025
+ readOnly: true,
34026
+ rateLimited: true
34027
+ }),
34028
+ measurementDraftAction({
34029
+ action: "route-markets",
34030
+ summary: "Route selected market edges through an engine",
34031
+ description: "Changes provider and model identity only for exact edges in the selected markets. It preserves every frozen location and clones contexts shared with an unselected market.",
34032
+ request: "MeasurementDraftRouteMarketsRequest"
34033
+ }),
33306
34034
  measurementDraftAction({
33307
34035
  action: "remove-assignment",
33308
34036
  summary: "Remove one query assignment from draft Targets",
@@ -34243,7 +34971,7 @@ var routeCatalog = [
34243
34971
  type: "object",
34244
34972
  required: ["provider"],
34245
34973
  properties: {
34246
- provider: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] },
34974
+ provider: queryGenerationProviderSchema,
34247
34975
  count: integerSchema
34248
34976
  }
34249
34977
  }
@@ -34352,7 +35080,7 @@ var routeCatalog = [
34352
35080
  type: "object",
34353
35081
  required: ["provider"],
34354
35082
  properties: {
34355
- provider: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] },
35083
+ provider: queryGenerationProviderSchema,
34356
35084
  count: integerSchema
34357
35085
  }
34358
35086
  }
@@ -39983,7 +40711,7 @@ var canonryLocalRouteCatalog = [
39983
40711
  method: "get",
39984
40712
  path: "/api/v1/projects/{name}/agent/transcript",
39985
40713
  summary: "Get the rolling Aero transcript for this project",
39986
- description: "Returns the full message history of the project-scoped Aero session plus the persisted model provider/id and last-updated timestamp. Empty messages array when the project has no session yet. Administrator-only: a signed-in viewer, and any API key narrower than the install (read-only, or scoped to a single project), are refused with 403. There is one Aero session per project, so this is the operator conversation rather than metadata about it.",
40714
+ description: "Returns the full message history of the project-scoped Aero session plus the persisted model provider/id, `nextTurn` (the provider and model a turn that names neither would run on: the conversation's own model unless the `agent.provider` pin overrides it; null when no provider can run) and last-updated timestamp. Empty messages array when the project has no session yet. Administrator-only: a signed-in viewer, and any API key narrower than the install (read-only, or scoped to a single project), are refused with 403. There is one Aero session per project, so this is the operator conversation rather than metadata about it.",
39987
40715
  tags: ["agent"],
39988
40716
  parameters: [nameParameter],
39989
40717
  responses: {
@@ -40419,6 +41147,7 @@ async function userRoutes(app) {
40419
41147
 
40420
41148
  // ../api-routes/src/snapshot.ts
40421
41149
  async function snapshotRoutes(app, opts) {
41150
+ const routeFamilies = providerRouteFamilies(opts.providerAdapters);
40422
41151
  app.post("/snapshot", async (request) => {
40423
41152
  const parsed = snapshotRequestSchema.safeParse(request.body);
40424
41153
  if (!parsed.success) {
@@ -40437,6 +41166,7 @@ async function snapshotRoutes(app, opts) {
40437
41166
  queries: resolveSnapshotRequestQueries(parsed.data)
40438
41167
  };
40439
41168
  delete input.phrases;
41169
+ assertProviderRouteScope(request, input.providers ?? [], [], routeFamilies);
40440
41170
  try {
40441
41171
  return await opts.onSnapshotRequested(input);
40442
41172
  } catch (err) {
@@ -40596,6 +41326,7 @@ function parseExpectedUpdatedAtParam(raw) {
40596
41326
  return parsed.data;
40597
41327
  }
40598
41328
  async function scheduleRoutes(app, opts) {
41329
+ const routeFamilies = providerRouteFamilies(opts.providerAdapters);
40599
41330
  app.put("/projects/:name/schedule", async (request, reply) => {
40600
41331
  const project = resolveProject(app.db, request.params.name);
40601
41332
  const parsedBody = scheduleUpsertRequestSchema.safeParse(request.body);
@@ -40631,7 +41362,7 @@ async function scheduleRoutes(app, opts) {
40631
41362
  }
40632
41363
  const validNames = opts.validProviderNames ?? [];
40633
41364
  if (validNames.length && providers?.length) {
40634
- const invalid = providers.filter((p) => !validNames.includes(p));
41365
+ const invalid = invalidProviderSelections(providers, validNames, opts.providerAdapters, ProviderWorkflows["visibility-sweep"]);
40635
41366
  if (invalid.length) {
40636
41367
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
40637
41368
  invalidProviders: invalid,
@@ -40639,6 +41370,7 @@ async function scheduleRoutes(app, opts) {
40639
41370
  });
40640
41371
  }
40641
41372
  }
41373
+ assertProviderRouteScope(request, providers ?? [], project.providers, routeFamilies);
40642
41374
  if (!isValidTimezone(timezone)) {
40643
41375
  throw validationError(`Invalid timezone: ${timezone}`);
40644
41376
  }
@@ -64785,23 +65517,26 @@ var providersConfiguredCheck = {
64785
65517
  remediation: null
64786
65518
  };
64787
65519
  }
64788
- const configured = summary3.filter((entry) => entry.configured).map((entry) => entry.name);
64789
- const total = summary3.length;
65520
+ const engines = summary3.filter(makesInstallMeasurable);
65521
+ const configured = engines.filter((entry) => entry.configured).map((entry) => entry.name);
65522
+ const answerServices = summary3.filter((entry) => !makesInstallMeasurable(entry) && entry.configured).map((entry) => entry.name);
65523
+ const servicesNote = answerServices.length > 0 ? ` Search answer services configured (used only where a project picks one of their profiles): ${answerServices.join(", ")}.` : "";
65524
+ const total = engines.length;
64790
65525
  if (configured.length === 0) {
64791
65526
  return {
64792
65527
  status: CheckStatuses.warn,
64793
65528
  code: "providers.none-configured",
64794
- summary: "No answer-engine provider is configured. Page Health remains available; AI Visibility is disabled.",
65529
+ summary: `No answer-engine provider is configured. Page Health remains available; AI Visibility is disabled.${servicesNote}`,
64795
65530
  remediation: "To enable AI Visibility, run `canonry settings provider <name> --api-key <key>` while the server is running, or set a provider environment variable and rerun `canonry bootstrap`. Bootstrap reloads a matching running local server; if it is offline, start it to use the saved settings.",
64796
- details: { available: summary3.map((entry) => entry.name) }
65531
+ details: { available: engines.map((entry) => entry.name), ...answerServices.length > 0 ? { answerServices } : {} }
64797
65532
  };
64798
65533
  }
64799
65534
  return {
64800
65535
  status: CheckStatuses.ok,
64801
65536
  code: "providers.configured",
64802
- summary: `${configured.length} of ${total} providers configured: ${configured.join(", ")}.`,
65537
+ summary: `${configured.length} of ${total} providers configured: ${configured.join(", ")}.${servicesNote}`,
64803
65538
  remediation: null,
64804
- details: { configured, total }
65539
+ details: { configured, total, ...answerServices.length > 0 ? { answerServices } : {} }
64805
65540
  };
64806
65541
  }
64807
65542
  };
@@ -64810,7 +65545,7 @@ var agentProvidersConfiguredCheck = {
64810
65545
  category: CheckCategories.providers,
64811
65546
  scope: CheckScopes.global,
64812
65547
  title: "Agent provider keys",
64813
- run: (ctx) => {
65548
+ run: async (ctx) => {
64814
65549
  if (ctx.callerIsInstanceAdministrator === false) {
64815
65550
  return {
64816
65551
  status: CheckStatuses.skipped,
@@ -64838,7 +65573,7 @@ var agentProvidersConfiguredCheck = {
64838
65573
  keySource: entry.keySource
64839
65574
  }))
64840
65575
  };
64841
- const pin = ctx.getAgentPin?.() ?? null;
65576
+ const pin = await ctx.getAgentPin?.() ?? null;
64842
65577
  if (pin && !pin.configured) {
64843
65578
  return {
64844
65579
  status: CheckStatuses.warn,
@@ -64862,7 +65597,7 @@ var agentProvidersConfiguredCheck = {
64862
65597
  status: CheckStatuses.warn,
64863
65598
  code: "agent-providers.none-configured",
64864
65599
  summary: "No agent LLM provider has credentials configured \u2014 the built-in Aero agent cannot run.",
64865
- remediation: "Add a key for one of the agent providers (claude, openai, gemini, zai) under `providers.<name>.apiKey` in ~/.canonry/config.yaml, or export its env var (e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY).",
65600
+ remediation: `Add a key for one of the agent providers (${AGENT_PROVIDER_IDS.join(", ")}) under \`providers.<name>.apiKey\` in ~/.canonry/config.yaml, or export its env var (e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY).`,
64866
65601
  details
64867
65602
  };
64868
65603
  }
@@ -66326,14 +67061,14 @@ async function statusRoutes(app, opts) {
66326
67061
  if (requested) {
66327
67062
  const project = resolveProject(opts.db, requested);
66328
67063
  if (scopedId && project.id !== scopedId) throw forbidden("This project is outside the API key scope.");
66329
- const result = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), summary: { projects: 1, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: [projectStatus(opts, project)] };
67064
+ const result = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...opts.getMcpHealth ? { mcp: opts.getMcpHealth() } : {}, summary: { projects: 1, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: [projectStatus(opts, project)] };
66330
67065
  const status = result.projects[0].state;
66331
67066
  result.summary[status === "never-synced" ? "neverSynced" : status]++;
66332
67067
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
66333
67068
  return instanceStatusDtoSchema.parse(result);
66334
67069
  }
66335
67070
  const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq91(projects.id, scopedId)) : opts.db.select().from(projects)).all();
66336
- const output = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), summary: { projects: projectsRows.length, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: projectsRows.map((project) => projectStatus(opts, project)) };
67071
+ const output = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...opts.getMcpHealth ? { mcp: opts.getMcpHealth() } : {}, summary: { projects: projectsRows.length, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: projectsRows.map((project) => projectStatus(opts, project)) };
66337
67072
  for (const project of output.projects) {
66338
67073
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
66339
67074
  output.summary[key] = (output.summary[key] ?? 0) + 1;
@@ -66769,7 +67504,8 @@ function parseCompetitorMap(raw) {
66769
67504
  return raw.map((entry) => ({
66770
67505
  domain: entry.domain,
66771
67506
  hits: entry.hits,
66772
- competitorType: entry.competitorType ?? DiscoveryCompetitorTypes.unknown
67507
+ competitorType: entry.competitorType ?? DiscoveryCompetitorTypes.unknown,
67508
+ ...entry.evaluator ? { evaluator: entry.evaluator } : {}
66773
67509
  }));
66774
67510
  }
66775
67511
  function groupCompetitorMap(competitorMap, probes, preferred) {
@@ -66877,11 +67613,12 @@ function buildCompetitorMap(probes, project, classification = {}) {
66877
67613
  })).sort((a, b) => b.hits - a.hits || a.domain.localeCompare(b.domain));
66878
67614
  }
66879
67615
  async function classifyCompetitorDomains(deps, project, icpDescription, domains) {
66880
- if (domains.length === 0) return {};
67616
+ if (domains.length === 0) return { classifications: {} };
66881
67617
  try {
66882
- return await deps.classifyDomains({ project, icpDescription, domains });
67618
+ const result = await deps.classifyDomains({ project, icpDescription, domains });
67619
+ return typeof result.classifications === "object" ? result : { classifications: result };
66883
67620
  } catch {
66884
- return {};
67621
+ return { classifications: {} };
66885
67622
  }
66886
67623
  }
66887
67624
  async function pickCanonicalsWithStats(candidates, deps, dedupThreshold, primaryMask) {
@@ -67039,7 +67776,7 @@ async function executeDiscovery(opts) {
67039
67776
  opts.icpDescription,
67040
67777
  domains
67041
67778
  );
67042
- const competitorMap = buildCompetitorMap(probeRows, opts.project, classification);
67779
+ const competitorMap = buildCompetitorMap(probeRows, opts.project, classification.classifications).map((entry) => ({ ...entry, ...classification.evaluator ? { evaluator: classification.evaluator } : {} }));
67043
67780
  opts.db.update(discoverySessions).set({
67044
67781
  status: DiscoverySessionStatuses.completed,
67045
67782
  probeCount: probedCanonicals.length,
@@ -69641,6 +70378,7 @@ import { and as and80, count as count8, desc as desc44, eq as eq96, gte as gte25
69641
70378
  var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
69642
70379
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
69643
70380
  async function researchRoutes(app, opts) {
70381
+ const routeFamilies = providerRouteFamilies(opts.providerAdapters);
69644
70382
  const viewerDailyRunLimit = opts.viewerDailyRunLimit ?? DEFAULT_VIEWER_RESEARCH_DAILY_RUN_LIMIT;
69645
70383
  if (!Number.isInteger(viewerDailyRunLimit) || viewerDailyRunLimit <= 0) {
69646
70384
  throw new Error("viewerDailyRunLimit must be a positive integer");
@@ -69665,12 +70403,15 @@ async function researchRoutes(app, opts) {
69665
70403
  if (!opts.onResearchRunRequested) throw missingDependency("Research execution is not available on this deployment.", { reason: "no-research-handler" });
69666
70404
  const adapters = opts.providerAdapters ?? [];
69667
70405
  const configured = new Set(opts.getConfiguredProviderNames?.() ?? opts.configuredProviderNames ?? []);
69668
- const providerName = input.provider ?? project.providers.find((name) => configured.has(name) && adapters.some((adapter2) => adapter2.name === name && adapter2.mode === "api")) ?? adapters.find((adapter2) => adapter2.mode === "api" && configured.has(adapter2.name))?.name;
69669
- const adapter = adapters.find((candidate) => candidate.name === providerName);
69670
- if (!providerName || !adapter || adapter.mode !== "api" || isBrowserProvider(providerName) || !configured.has(providerName)) throw validationError("Research requires a configured API provider.", { provider: input.provider, validProviders: adapters.filter((a) => a.mode === "api" && configured.has(a.name)).map((a) => a.name) });
70406
+ const authorizedProviders = researchProjectProviders(app, project.id, project.providers);
70407
+ const implicitlyEligible = (name) => providerEligibleFor(name, adapters, ProviderWorkflows.research, "implicit");
70408
+ const providerName = input.provider ?? authorizedProviders.find((name) => implicitlyEligible(name) && isProviderAvailable(name, [...configured], routeFamilies) && providerAdapterForName(name, adapters)?.mode === "api") ?? adapters.find((adapter2) => adapter2.mode === "api" && implicitlyEligible(adapter2.name) && configured.has(adapter2.name))?.name;
70409
+ const adapter = providerName ? providerAdapterForName(providerName, adapters) : void 0;
70410
+ if (!providerName || !adapter || adapter.mode !== "api" || !isSweepProvider(providerName, routeFamilies) || isBrowserProvider(providerName) || !isProviderAvailable(providerName, [...configured], routeFamilies) || !providerEligibleFor(providerName, adapters, ProviderWorkflows.research, "explicit")) throw validationError("Research requires a configured API provider.", { provider: input.provider, validProviders: authorizedProviders.filter((name) => isProviderAvailable(name, [...configured], routeFamilies) && providerAdapterForName(name, adapters)?.mode === "api") });
70411
+ assertProviderRouteScope(request, [providerName], authorizedProviders, routeFamilies);
69671
70412
  if (input.model) {
69672
70413
  adapter.modelValidationPattern.lastIndex = 0;
69673
- if (!adapter.modelConfigurable || !adapter.modelValidationPattern.test(input.model)) throw validationError(`Invalid model "${input.model}" for provider "${providerName}".`, { provider: providerName, model: input.model, hint: adapter.modelValidationHint });
70414
+ if (!adapter.modelConfigurable && input.model !== adapter.defaultModel || !adapter.modelValidationPattern.test(input.model)) throw validationError(`Invalid model "${input.model}" for provider "${providerName}".`, { provider: providerName, model: input.model, hint: adapter.modelValidationHint });
69674
70415
  }
69675
70416
  const active = activeMeasurementPlan(app.db, project.id);
69676
70417
  const scope = input.scope ? resolveResearchScope(active, input.scope) : null;
@@ -69678,7 +70419,7 @@ async function researchRoutes(app, opts) {
69678
70419
  if (location && !project.locations.some((item2) => sameLocation(item2, location))) throw validationError("Research location must exactly match a configured project location.", { location });
69679
70420
  const template = input.template ? resolveResearchTemplate(app, project.id, input.template, scope, location) : null;
69680
70421
  const requestedModel2 = input.model ?? null;
69681
- const resolvedModel = resolveProviderModel(providerName, requestedModel2 ?? (project.providerModels[providerName] || opts.getEffectiveProviderModels?.()[providerName] || adapter.defaultModel));
70422
+ const resolvedModel = resolveProviderModel(providerName, pinnedRouteSelection(providerName, routeFamilies) ?? requestedModel2 ?? (project.providerModels[providerName] || opts.getEffectiveProviderModels?.()[providerName] || adapter.defaultModel));
69682
70423
  adapter.modelValidationPattern.lastIndex = 0;
69683
70424
  if (!adapter.modelValidationPattern.test(resolvedModel)) throw validationError('Invalid resolved model "' + resolvedModel + '" for provider "' + providerName + '".', { provider: providerName, model: resolvedModel, hint: adapter.modelValidationHint });
69684
70425
  if (deduplicateResearchQueries(input.queries).length !== input.queries.length) throw validationError("Research queries must be unique within a batch.");
@@ -69745,6 +70486,7 @@ async function researchRoutes(app, opts) {
69745
70486
  if (!opts.onResearchRunRequested) throw missingDependency("Research execution is not available on this deployment.", { reason: "no-research-handler" });
69746
70487
  const active = activeMeasurementPlan(app.db, project.id);
69747
70488
  const prepared = input.runs.map((run) => prepareBatchRun(app, opts, project, active, run));
70489
+ assertProviderRouteScope(request, prepared.map((run) => run.providerName), researchProjectProviders(app, project.id, project.providers), routeFamilies);
69748
70490
  const now = (/* @__PURE__ */ new Date()).toISOString();
69749
70491
  const initiatedBy = researchPrincipal(request);
69750
70492
  const decision = app.db.transaction((tx) => {
@@ -69814,16 +70556,35 @@ async function researchRoutes(app, opts) {
69814
70556
  const nextCursor = rows.length > limit && last ? Buffer.from(JSON.stringify({ projectId: project.id, createdAt: last.createdAt, id: last.id })).toString("base64url") : null;
69815
70557
  const configured = new Set(opts.getConfiguredProviderNames?.() ?? opts.configuredProviderNames ?? []);
69816
70558
  const effectiveModels2 = opts.getEffectiveProviderModels?.() ?? {};
69817
- const providers = (opts.providerAdapters ?? []).filter((adapter) => adapter.mode === "api" && !isBrowserProvider(adapter.name) && configured.has(adapter.name)).map((adapter) => {
70559
+ const adapters = opts.providerAdapters ?? [];
70560
+ const savedProviders = researchProjectProviders(app, project.id, project.providers);
70561
+ const profileRoutes = adapters.flatMap((adapter) => (adapter.profiles ?? []).filter((profile) => profile.workflows.includes(ProviderWorkflows.research)).map((profile) => profile.route));
70562
+ const catalog = [...new Map([
70563
+ ...adapters.filter((adapter) => isSweepProvider(adapter.name, routeFamilies)),
70564
+ ...[...savedProviders, ...profileRoutes].filter((name) => resolveProviderRoute(name, routeFamilies)).flatMap((name) => {
70565
+ const adapter = providerAdapterForName(name, adapters);
70566
+ return adapter && providerEligibleFor(name, adapters, ProviderWorkflows.research, "explicit") ? [adapter] : [];
70567
+ })
70568
+ ].map((adapter) => [adapter.name, adapter])).values()];
70569
+ const providers = catalog.filter((adapter) => adapter.mode === "api" && !isBrowserProvider(adapter.name) && isProviderAvailable(adapter.name, [...configured], routeFamilies)).map((adapter) => {
70570
+ const pinned = pinnedRouteSelection(adapter.name, routeFamilies);
69818
70571
  const defaultModel = resolveProviderModel(adapter.name, project.providerModels[adapter.name] || effectiveModels2[adapter.name] || adapter.defaultModel);
69819
- const cached = opts.getCachedProviderModels?.(adapter.name) ?? [];
69820
- const models = cached.length ? cached : adapter.knownModels;
70572
+ const cached = opts.getCachedProviderModels?.(providerConnectionName(adapter.name, routeFamilies)) ?? [];
70573
+ const candidates = cached.length ? cached : adapter.knownModels;
70574
+ const models = pinned ? candidates.filter((model) => model.id === defaultModel) : candidates;
69821
70575
  return {
69822
70576
  name: adapter.name,
69823
70577
  displayName: adapter.displayName,
69824
70578
  modelConfigurable: adapter.modelConfigurable,
69825
70579
  defaultModel,
69826
- knownModels: [...new Map([{ id: defaultModel, displayName: defaultModel }, ...models].map((model) => [model.id, { id: model.id, displayName: model.displayName }])).values()]
70580
+ knownModels: [...new Map([{ id: defaultModel, displayName: defaultModel }, ...models].map((model) => [model.id, { id: model.id, displayName: model.displayName }])).values()],
70581
+ // Only routed options carry identity fields; engine options keep their shape.
70582
+ ...adapter.kind ? {
70583
+ kind: adapter.kind,
70584
+ connection: providerConnectionName(adapter.name, routeFamilies),
70585
+ selectionKind: resolveProviderRoute(adapter.name, routeFamilies)?.family.selectionKind ?? null,
70586
+ ...adapter.profiles ? { profiles: adapter.profiles } : {}
70587
+ } : {}
69827
70588
  };
69828
70589
  });
69829
70590
  const canRun = canRunResearch(request, opts.allowViewers ?? false);
@@ -69835,6 +70596,9 @@ async function researchRoutes(app, opts) {
69835
70596
  return getDetail(app, project.id, request.params.runId);
69836
70597
  });
69837
70598
  }
70599
+ function researchProjectProviders(app, projectId, projectProviders) {
70600
+ return [.../* @__PURE__ */ new Set([...projectProviders, ...activeRevisionProviders(app.db, projectId)])];
70601
+ }
69838
70602
  var DIRECT_REQUEST_HASH_VERSION = "direct-v2:";
69839
70603
  function directResearchRequestHash(input) {
69840
70604
  const { idempotencyKey: _key, ...request } = input;
@@ -69886,8 +70650,9 @@ function prepareBatchRun(app, opts, project, active, input) {
69886
70650
  const adapters = opts.providerAdapters ?? [];
69887
70651
  const configured = new Set(opts.getConfiguredProviderNames?.() ?? opts.configuredProviderNames ?? []);
69888
70652
  const providerName = input.provider;
69889
- const adapter = adapters.find((candidate) => candidate.name === providerName);
69890
- if (!adapter || adapter.mode !== "api" || isBrowserProvider(providerName) || !configured.has(providerName)) {
70653
+ const adapter = providerName ? providerAdapterForName(providerName, adapters) : void 0;
70654
+ const routeFamilies = providerRouteFamilies(adapters);
70655
+ if (!adapter || adapter.mode !== "api" || !isSweepProvider(providerName, routeFamilies) || isBrowserProvider(providerName) || !isProviderAvailable(providerName, [...configured], routeFamilies) || !providerEligibleFor(providerName, adapters, ProviderWorkflows.research, "explicit")) {
69891
70656
  throw validationError("Research requires a configured API provider.", { provider: providerName, validProviders: adapters.filter((a) => a.mode === "api" && configured.has(a.name)).map((a) => a.name) });
69892
70657
  }
69893
70658
  adapter.modelValidationPattern.lastIndex = 0;
@@ -69967,7 +70732,32 @@ function serializeRun(row) {
69967
70732
  return { id: row.id, projectId: row.projectId, status: row.status, provider: row.provider, requestedModel: row.requestedModel, resolvedModel: row.resolvedModel, location: row.location ?? null, scope: row.scope ?? null, template: row.template ?? null, totalQueries: row.totalQueries, completedQueries: row.completedQueries, failedQueries: row.failedQueries, error: row.error, initiatedBy: row.initiatedBy ?? null, startedAt: row.startedAt, finishedAt: row.finishedAt, createdAt: row.createdAt };
69968
70733
  }
69969
70734
  function serializeQuery(row) {
69970
- return { id: row.id, position: row.position, query: row.queryText, queryClass: row.queryClass ?? null, status: row.status, requestedModel: row.requestedModel, resolvedModel: row.resolvedModel, servedModel: row.servedModel, answerText: row.answerText, groundingSources: row.groundingSources, citedDomains: row.citedDomains, searchQueries: row.searchQueries, retrievedSources: row.retrievedSources ?? null, namedCompetitors: row.namedCompetitors, citedCompetitorDomains: row.citedCompetitorDomains, answerMentioned: row.answerMentioned, citationState: row.citationState, error: row.error, startedAt: row.startedAt, finishedAt: row.finishedAt, createdAt: row.createdAt };
70735
+ return {
70736
+ id: row.id,
70737
+ position: row.position,
70738
+ query: row.queryText,
70739
+ queryClass: row.queryClass ?? null,
70740
+ status: row.status,
70741
+ requestedModel: row.requestedModel,
70742
+ resolvedModel: row.resolvedModel,
70743
+ servedModel: row.servedModel,
70744
+ answerText: row.answerText,
70745
+ groundingSources: row.groundingSources,
70746
+ citedDomains: row.citedDomains,
70747
+ searchQueries: row.searchQueries,
70748
+ retrievedSources: row.retrievedSources ?? null,
70749
+ namedCompetitors: row.namedCompetitors,
70750
+ citedCompetitorDomains: row.citedCompetitorDomains,
70751
+ answerMentioned: row.answerMentioned,
70752
+ citationState: row.citationState,
70753
+ error: row.error,
70754
+ startedAt: row.startedAt,
70755
+ finishedAt: row.finishedAt,
70756
+ createdAt: row.createdAt,
70757
+ // Only answer services record evidence; every other row keeps its exact shape.
70758
+ ...row.answerEvidence ? { evidence: row.answerEvidence, citationMeasured: row.status === ResearchQueryStatuses.completed && row.answerEvidence.citationMeasurable } : {},
70759
+ ...row.upstreamJobId ? { upstreamJobId: row.upstreamJobId } : {}
70760
+ };
69971
70761
  }
69972
70762
  function researchPrincipal(request) {
69973
70763
  const principal = request.principal;
@@ -70174,6 +70964,7 @@ async function apiRoutes(app, opts) {
70174
70964
  });
70175
70965
  await api.register(userRoutes);
70176
70966
  await api.register(openApiRoutes, { ...opts.openApiInfo, routePrefix: opts.routePrefix });
70967
+ const providerRouteFamilies2 = routeFamiliesOf(opts.providerAdapters);
70177
70968
  await api.register(projectRoutes, {
70178
70969
  onProjectDeleting: opts.onProjectDeleting,
70179
70970
  onProjectDeleted: opts.onProjectDeleted,
@@ -70205,10 +70996,12 @@ async function apiRoutes(app, opts) {
70205
70996
  validProviderNames: opts.providerAdapters?.map((a) => a.name),
70206
70997
  getRunnableProviderNames: opts.getRunnableProviderNames,
70207
70998
  getEffectiveProviderModels: opts.getEffectiveProviderModels,
70208
- getBatchEligibleProviderNames: opts.getBatchEligibleProviderNames
70999
+ getBatchEligibleProviderNames: opts.getBatchEligibleProviderNames,
71000
+ providerAdapters: opts.providerAdapters
70209
71001
  });
70210
71002
  await api.register(measurementPlanRoutes, {
70211
71003
  getRunnableProviderNames: opts.getRunnableProviderNames,
71004
+ providerRouteFamilies: providerRouteFamilies2,
70212
71005
  onCompetitorAliasesChanged: opts.onCompetitorAliasesChanged,
70213
71006
  onCompetitorAutoAliasRescan: opts.onCompetitorAutoAliasRescan
70214
71007
  });
@@ -70217,6 +71010,8 @@ async function apiRoutes(app, opts) {
70217
71010
  });
70218
71011
  await api.register(measurementDraftRoutes, {
70219
71012
  getRunnableProviderNames: opts.getRunnableProviderNames,
71013
+ providerRouteFamilies: providerRouteFamilies2,
71014
+ providerAdapters: opts.providerAdapters,
70220
71015
  onCompetitorAliasesChanged: opts.onCompetitorAliasesChanged,
70221
71016
  onCompetitorAutoAliasRescan: opts.onCompetitorAutoAliasRescan
70222
71017
  });
@@ -70228,6 +71023,7 @@ async function apiRoutes(app, opts) {
70228
71023
  await api.register(visibilityReportRoutes);
70229
71024
  await api.register(queryTrackingRoutes, {
70230
71025
  getRunnableProviderNames: opts.getRunnableProviderNames,
71026
+ providerRouteFamilies: providerRouteFamilies2,
70231
71027
  providerSummary: opts.providerSummary
70232
71028
  });
70233
71029
  await api.register(applyRoutes, {
@@ -70256,7 +71052,7 @@ async function apiRoutes(app, opts) {
70256
71052
  await api.register(citationRoutes);
70257
71053
  await api.register(visibilityStatsRoutes);
70258
71054
  await api.register(resultsExportRoutes);
70259
- await api.register(compositeRoutes, { sentiment: opts.sentiment, getRunnableProviderNames: opts.getRunnableProviderNames });
71055
+ await api.register(compositeRoutes, { sentiment: opts.sentiment, getRunnableProviderNames: opts.getRunnableProviderNames, providerRouteFamilies: providerRouteFamilies2 });
70260
71056
  await api.register(contentRoutes, {
70261
71057
  explainContentRecommendation: opts.explainContentRecommendation,
70262
71058
  briefContentRecommendation: opts.briefContentRecommendation,
@@ -70275,11 +71071,13 @@ async function apiRoutes(app, opts) {
70275
71071
  });
70276
71072
  await api.register(keysRoutes);
70277
71073
  await api.register(snapshotRoutes, {
70278
- onSnapshotRequested: opts.onSnapshotRequested
71074
+ onSnapshotRequested: opts.onSnapshotRequested,
71075
+ providerAdapters: opts.providerAdapters
70279
71076
  });
70280
71077
  await api.register(scheduleRoutes, {
70281
71078
  onScheduleUpdated: opts.onScheduleUpdated,
70282
- validProviderNames: opts.providerAdapters?.map((a) => a.name)
71079
+ validProviderNames: opts.providerAdapters?.map((a) => a.name),
71080
+ providerAdapters: opts.providerAdapters
70283
71081
  });
70284
71082
  await api.register(notificationRoutes, {
70285
71083
  allowLoopbackWebhooks: opts.allowLoopbackWebhooks
@@ -70441,6 +71239,7 @@ async function apiRoutes(app, opts) {
70441
71239
  });
70442
71240
  await api.register(statusRoutes, {
70443
71241
  db: opts.db,
71242
+ getMcpHealth: opts.getMcpHealth,
70444
71243
  googleConnectionStore: opts.googleConnectionStore,
70445
71244
  bingConnectionStore: opts.bingConnectionStore,
70446
71245
  ga4CredentialStore: opts.ga4CredentialStore,
@@ -70692,6 +71491,8 @@ export {
70692
71491
  writeAuditLog,
70693
71492
  auditFromRequest,
70694
71493
  registerAgentConversationRoutes,
71494
+ blockedAddressReason,
71495
+ stripIpv6Brackets,
70695
71496
  measurementSlotKey,
70696
71497
  measurementRunSlotState,
70697
71498
  measurementRunCompleteness,