@canonry/canonry 7.52.0 → 7.53.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 (138) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +11 -1
  2. package/assets/assets/{AccessControls-CteIuEGI.js → AccessControls-B-5YUuLE.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-DqJGiLsf.js → AuditHistoryPanel-BkCUPvPv.js} +1 -1
  4. package/assets/assets/{BacklinksPage-DotWEPQt.js → BacklinksPage-BMgHZKuw.js} +1 -1
  5. package/assets/assets/{HistoryPage-aOd198dT.js → HistoryPage-D2DOk7ms.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-Bwv8nKS7.js +4 -0
  7. package/assets/assets/ProjectPage-CsJfGPx3.js +7 -0
  8. package/assets/assets/RunsPage-DSHDuj9b.js +1 -0
  9. package/assets/assets/SettingsPage-BDRdWk5X.js +1 -0
  10. package/assets/assets/SiteHealthSection-DV06NTxC.js +2 -0
  11. package/assets/assets/TrafficPage-CBMMwRfw.js +40 -0
  12. package/assets/assets/{TrafficSourceDetailPage-BPtjnF9s.js → TrafficSourceDetailPage-Czpt0S7j.js} +1 -1
  13. package/assets/assets/card-CVejjbhs.js +60 -0
  14. package/assets/assets/{extract-error-message-DKQJJlZ-.js → extract-error-message-Co6zPipR.js} +1 -1
  15. package/assets/assets/{format-helpers-BWnMmkiO.js → format-helpers-B_2jkVGI.js} +1 -1
  16. package/assets/assets/index-BnS2Vuv0.js +40 -0
  17. package/assets/assets/index-DgS5TTSb.css +1 -0
  18. package/assets/assets/{query-client-vB35tVTz.js → query-client-BKJLgjJd.js} +1 -1
  19. package/assets/assets/react-query-ltP1RErY.js +1 -0
  20. package/assets/assets/{react-sigma_core.esm.min-hGyOC4V_.js → react-sigma_core.esm.min-Bjux3j_1.js} +1 -1
  21. package/assets/assets/service-CDsqgNrS.js +1 -0
  22. package/assets/index.html +8 -7
  23. package/dist/{ads-MREK2AGL.js → ads-S4S74OXM.js} +3 -3
  24. package/dist/{agent-4RUZ3MC4.js → agent-JZWKCI5V.js} +7 -7
  25. package/dist/{agent-ask-YLTYBEYH.js → agent-ask-N2DG5ZLZ.js} +3 -3
  26. package/dist/{agent-conversations-QA6IKDGR.js → agent-conversations-7UDNE7YI.js} +3 -3
  27. package/dist/{agent-memory-MEQAJOB3.js → agent-memory-I74OWTU7.js} +3 -3
  28. package/dist/{agent-providers-AXYPDJHL.js → agent-providers-MEMCZPGE.js} +3 -3
  29. package/dist/{agent-transcript-SMNQNYCD.js → agent-transcript-Z7VTL7PY.js} +3 -3
  30. package/dist/{analytics-4OR64IGV.js → analytics-4NUSNTKT.js} +3 -3
  31. package/dist/{apply-CQXCFXAH.js → apply-OZKQK3YF.js} +3 -3
  32. package/dist/{backfill-TMXCNVOB.js → backfill-PLY2NOOY.js} +9 -9
  33. package/dist/{backlinks-6KFAQGYV.js → backlinks-2CMRJFWO.js} +3 -3
  34. package/dist/{bing-HFCACTAC.js → bing-RD3DDESD.js} +3 -3
  35. package/dist/{bootstrap-SQVQXOJC.js → bootstrap-JOYV4SWM.js} +9 -9
  36. package/dist/{cdp-IACL7EXU.js → cdp-LUGL3CT6.js} +7 -7
  37. package/dist/{chunk-EGIZNSDA.js → chunk-23UZNTF4.js} +1 -1
  38. package/dist/{chunk-BYOK6Z4F.js → chunk-2EYBZYDG.js} +2 -2
  39. package/dist/{chunk-O4RMPA6H.js → chunk-2GAXZAQJ.js} +107 -11
  40. package/dist/{chunk-BU3VAG5J.js → chunk-2HWY4NRQ.js} +3 -3
  41. package/dist/{chunk-RVUCY4ZV.js → chunk-2XDGFHPM.js} +6 -4
  42. package/dist/{chunk-GNKOBKPW.js → chunk-3DO3CS7Y.js} +4 -4
  43. package/dist/{chunk-SNFBJKAW.js → chunk-6VSKBVB3.js} +3 -3
  44. package/dist/{chunk-7244X3K6.js → chunk-6ZCZRZ66.js} +2 -2
  45. package/dist/{chunk-FC4XND45.js → chunk-BGZL5RCP.js} +1 -1
  46. package/dist/{chunk-MKAC7HKH.js → chunk-BH274VEO.js} +3 -3
  47. package/dist/{chunk-LK2BG6EX.js → chunk-BQT7VLGM.js} +11 -1
  48. package/dist/{chunk-6BPZHNDC.js → chunk-C5GCRQ66.js} +2 -2
  49. package/dist/{chunk-QLPLENDT.js → chunk-DFQHGWPB.js} +1 -1
  50. package/dist/{chunk-IIOEAJTV.js → chunk-F55ER5RQ.js} +3 -3
  51. package/dist/{chunk-DSNSD5J3.js → chunk-IWQGZQHE.js} +19 -9
  52. package/dist/{chunk-YSEC6TIB.js → chunk-JZARXJV6.js} +821 -227
  53. package/dist/{chunk-MJNUSPO4.js → chunk-LGU3O5YP.js} +2 -2
  54. package/dist/{chunk-BBOHY2DQ.js → chunk-LYCYSM6O.js} +1 -1
  55. package/dist/chunk-N3WQHLDI.js +1199 -0
  56. package/dist/{chunk-AWCWIQAU.js → chunk-N6MS4VG2.js} +226 -5
  57. package/dist/{chunk-TALC5DX5.js → chunk-NKSASP4U.js} +1 -1
  58. package/dist/{chunk-V5D4XNWV.js → chunk-O3OTW7F4.js} +39 -2
  59. package/dist/{chunk-K5I45PZI.js → chunk-P4SXRRB4.js} +307 -194
  60. package/dist/{chunk-ILDT4LPB.js → chunk-QARV5HVI.js} +26 -240
  61. package/dist/{chunk-O77IBNVO.js → chunk-QNU7IIO7.js} +326 -324
  62. package/dist/{chunk-I6KNMZ77.js → chunk-QXJ356KK.js} +4 -4
  63. package/dist/{chunk-JY3RLZGB.js → chunk-RVBGFWJ3.js} +1 -1
  64. package/dist/{chunk-7XE2IRBG.js → chunk-SZG7S7TE.js} +1 -1
  65. package/dist/{chunk-KXAOMTXN.js → chunk-U7JJKXLA.js} +5 -5
  66. package/dist/{chunk-Y4GK7GCV.js → chunk-VEH4YLWR.js} +1 -1
  67. package/dist/{chunk-R2J4SNKF.js → chunk-WNXKW3NS.js} +1 -1
  68. package/dist/{chunk-HEGXGCGL.js → chunk-XTIP5WSA.js} +3 -3
  69. package/dist/{chunk-5N6245R7.js → chunk-ZXH5IFIA.js} +4 -4
  70. package/dist/{citations-NSBBWRZ4.js → citations-GMLBTNLW.js} +3 -3
  71. package/dist/{cli-catalog-OFWJMNMD.js → cli-catalog-WKUCQEWA.js} +3 -3
  72. package/dist/{cli-commands-WVBL337U.js → cli-commands-YCHQWUNK.js} +7 -7
  73. package/dist/cli.js +13 -13
  74. package/dist/{competitor-V4OHORBC.js → competitor-QNPVJFEI.js} +3 -3
  75. package/dist/{content-RUXRI5IC.js → content-NFTC74HD.js} +3 -3
  76. package/dist/{dashboard-JXB2YAQJ.js → dashboard-TMUQT5H5.js} +6 -6
  77. package/dist/{demo-55ZNUOXU.js → demo-O5SPVLZZ.js} +1 -1
  78. package/dist/{demo-server-XO7PHM4I.js → demo-server-WKZ53RGK.js} +11 -11
  79. package/dist/{discover-JJQ564HS.js → discover-LTTO7KHN.js} +3 -3
  80. package/dist/{discover-eval-KLEKZ6U4.js → discover-eval-QRDNMDUE.js} +3 -3
  81. package/dist/{doctor-JAMQZCMZ.js → doctor-SFL5FOW4.js} +3 -3
  82. package/dist/{evidence-YRSB7GFE.js → evidence-J6WZ767P.js} +3 -3
  83. package/dist/{export-cmd-MHML4OYU.js → export-cmd-D3JDTBDV.js} +3 -3
  84. package/dist/{ga-LSXPE2MN.js → ga-N56LXQUN.js} +3 -3
  85. package/dist/{gbp-RMKMLOC7.js → gbp-7WVJYWDR.js} +3 -3
  86. package/dist/{google-JQ4T6JTQ.js → google-YLRVXYVJ.js} +4 -4
  87. package/dist/{google-marketing-J6SEODYC.js → google-marketing-4DGX3RBB.js} +1 -1
  88. package/dist/{health-cmd-MV2JM2C3.js → health-cmd-PK3BASF6.js} +3 -3
  89. package/dist/{history-SRRH7A2E.js → history-UWTEZ626.js} +3 -3
  90. package/dist/index.d.ts +40 -7
  91. package/dist/index.js +23 -23
  92. package/dist/{init-ZJZFUERV.js → init-RBI2IOBY.js} +11 -11
  93. package/dist/{insights-PMMGNWZH.js → insights-ZUC5XHFD.js} +3 -3
  94. package/dist/intelligence-service-JXXB43RB.js +15 -0
  95. package/dist/{keys-TS7NZANS.js → keys-NOG3M76V.js} +3 -3
  96. package/dist/{keyword-VNCKDUGC.js → keyword-HD57L76I.js} +3 -3
  97. package/dist/{logs-VH3WOTZJ.js → logs-VAB7ITBS.js} +3 -3
  98. package/dist/{mcp-DG2RROB3.js → mcp-HYHIL5FB.js} +2 -2
  99. package/dist/mcp.js +9 -9
  100. package/dist/{measurement-plan-4T35TUGG.js → measurement-plan-GEHOHCH3.js} +5 -5
  101. package/dist/{notify-BWHUSKL7.js → notify-VQ2ZDGN4.js} +3 -3
  102. package/dist/{organic-evidence-QX4SXXJP.js → organic-evidence-6TX627YW.js} +3 -3
  103. package/dist/{overview-7IHUTKUV.js → overview-XBO7WYAV.js} +4 -4
  104. package/dist/{project-JXLSWDE2.js → project-DR6744WZ.js} +3 -3
  105. package/dist/{query-S75EL25H.js → query-OGVTCPG5.js} +3 -3
  106. package/dist/{research-KFTV3IP4.js → research-B2TGKSMC.js} +3 -3
  107. package/dist/{results-export-GTKVBU34.js → results-export-K7PAYPWQ.js} +3 -3
  108. package/dist/{run-26HDIRHF.js → run-Y6LUMCVL.js} +4 -4
  109. package/dist/{schedule-N6G4SVHQ.js → schedule-PNAUJ5FX.js} +3 -3
  110. package/dist/{search-MI32EPYM.js → search-PMVOGL4U.js} +3 -3
  111. package/dist/{serve-XLGE42AG.js → serve-PQHXSS5T.js} +24 -24
  112. package/dist/{session-W5DXWIYM.js → session-S5NDMMKF.js} +16 -15
  113. package/dist/{settings-T7WI2UVE.js → settings-AL7E7QUK.js} +3 -3
  114. package/dist/{skills-F3WPKPTK.js → skills-GQOOTDR7.js} +2 -2
  115. package/dist/{snapshot-PD3EAVEX.js → snapshot-W3FXRTZM.js} +3 -3
  116. package/dist/{src-XDUXMJC3.js → src-WZLTQFCH.js} +2 -2
  117. package/dist/{status-PUH7JFZ4.js → status-MBJVN4W5.js} +4 -4
  118. package/dist/{technical-aeo-AUFWWJIP.js → technical-aeo-Y4RFST72.js} +3 -3
  119. package/dist/{telemetry-XBYT7G2K.js → telemetry-VK6F5QSZ.js} +4 -4
  120. package/dist/{tools-GVHIRWSN.js → tools-W3AQY5TY.js} +11 -11
  121. package/dist/{traffic-B3HW2ZWG.js → traffic-ER4I6V3B.js} +5 -5
  122. package/dist/{users-M5HNQZYI.js → users-KZK2OF4L.js} +3 -3
  123. package/dist/{visibility-stats-Y7GJKMHN.js → visibility-stats-CR7BUG5G.js} +3 -3
  124. package/dist/{wordpress-GCIURYPN.js → wordpress-DG5JUCAC.js} +3 -3
  125. package/package.json +2 -1
  126. package/assets/assets/MeasurementPropertyPage-CuaKVK8x.js +0 -4
  127. package/assets/assets/ProjectPage-O9oufMgi.js +0 -8
  128. package/assets/assets/RunsPage-DIXMrc-N.js +0 -1
  129. package/assets/assets/SettingsPage-BuGb6AGa.js +0 -1
  130. package/assets/assets/SiteHealthSection-CweaKjCo.js +0 -2
  131. package/assets/assets/TrafficPage-B7MaQalp.js +0 -40
  132. package/assets/assets/card-DoV-8Txo.js +0 -60
  133. package/assets/assets/index-CsPsaUr7.css +0 -1
  134. package/assets/assets/index-Z63c4PeO.js +0 -39
  135. package/assets/assets/react-query-BI0567qs.js +0 -1
  136. package/assets/assets/service-c4YvpVKX.js +0 -1
  137. package/dist/chunk-OFL4PTYU.js +0 -644
  138. 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-VEH4YLWR.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-DFQHGWPB.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-BH274VEO.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,
@@ -288,6 +289,7 @@ import {
288
289
  PROVIDER_ACCOUNT_RETRY_HOURS,
289
290
  PROVIDER_NAMES,
290
291
  ProviderDispatchModes,
292
+ ProviderNames,
291
293
  READ_ONLY_SCOPE,
292
294
  RESEARCH_RUN_SCOPE,
293
295
  RUN_FILL_MAX_AGE_MS,
@@ -301,7 +303,6 @@ import {
301
303
  RunTriggers,
302
304
  SENTIMENT_ATTEMPT_PAGE_DEFAULT,
303
305
  SENTIMENT_INTERVAL_LIMITATION,
304
- SENTIMENT_MODEL,
305
306
  SENTIMENT_QUERY_PAGE_DEFAULT,
306
307
  SITE_AUDIT_ISSUES_DEFAULT_LIMIT,
307
308
  SITE_CRAWL_GRAPH_DEFAULT_MAX_EDGES,
@@ -673,11 +674,14 @@ import {
673
674
  isListingMarketplace,
674
675
  isLocationRedirectStatus,
675
676
  isNegativeReviewRating,
677
+ isOpenRouterRoute,
676
678
  isProviderAccountFailure,
679
+ isProviderAvailable,
677
680
  isReadOnlyKey,
678
681
  isRedactedNotificationUrl,
679
682
  isRetryableHttpError,
680
683
  isStrictSemver,
684
+ isSweepProvider,
681
685
  isVertexGroundingRedirect,
682
686
  isVisibilityCompareClassMetric,
683
687
  isoDateDaysBeforeInTimeZone,
@@ -729,6 +733,7 @@ import {
729
733
  measurementDraftPreviewAssignmentsResponseSchema,
730
734
  measurementDraftPreviewGroupMembershipRequestSchema,
731
735
  measurementDraftPreviewGroupMembershipResponseSchema,
736
+ measurementDraftPreviewMarketRoutingResponseSchema,
732
737
  measurementDraftPublishRequestSchema,
733
738
  measurementDraftRebindTargetRequestSchema,
734
739
  measurementDraftRemoveAssignmentRequestSchema,
@@ -737,6 +742,7 @@ import {
737
742
  measurementDraftRenameTargetRequestSchema,
738
743
  measurementDraftReplaceAssignmentsRequestSchema,
739
744
  measurementDraftResponseSchema,
745
+ measurementDraftRouteMarketsRequestSchema,
740
746
  measurementDraftTargetPageSchema,
741
747
  measurementDraftUpsertCompetitorRequestSchema,
742
748
  measurementDraftUpsertGroupRequestSchema,
@@ -824,6 +830,8 @@ import {
824
830
  notificationDtoSchema,
825
831
  notificationEventSchema,
826
832
  onboardingTelemetryEventSchema,
833
+ openRouterRouteModel,
834
+ openRouterRouteName,
827
835
  operationAccess,
828
836
  operationInProgress,
829
837
  operationalLogListDtoSchema,
@@ -856,6 +864,7 @@ import {
856
864
  projectSearchResponseSchema,
857
865
  projectUpsertRequestSchema,
858
866
  providerAuthError,
867
+ providerConnectionName,
859
868
  providerDispatchModeSchema,
860
869
  providerError,
861
870
  providerReloadRequestSchema,
@@ -939,6 +948,7 @@ import {
939
948
  sentimentBackfillSelectionSchema,
940
949
  sentimentCompareRequestSchema,
941
950
  sentimentComparisonSchema,
951
+ sentimentEvaluatorProvider,
942
952
  sentimentEvidencePageSchema,
943
953
  sentimentEvidenceRequestSchema,
944
954
  sentimentJobRequestSchema,
@@ -1058,7 +1068,7 @@ import {
1058
1068
  wordpressSchemaDeployResultDtoSchema,
1059
1069
  wordpressSchemaStatusResultDtoSchema,
1060
1070
  wordpressStatusDtoSchema
1061
- } from "./chunk-O4RMPA6H.js";
1071
+ } from "./chunk-2GAXZAQJ.js";
1062
1072
 
1063
1073
  // ../api-routes/src/user-session.ts
1064
1074
  import crypto2 from "crypto";
@@ -6846,11 +6856,11 @@ function indexedPlan(db, projectId, versionId, cache2) {
6846
6856
  for (const query of plan.querySnapshots) keep(queryTexts, query.queryId, query.queryText);
6847
6857
  const groupKeys = /* @__PURE__ */ new Map(), marketKeys = /* @__PURE__ */ new Map();
6848
6858
  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);
6859
+ for (const scope of plan.reportingScopes ?? []) for (const edgeKey3 of new Set(scope.usageEdges.map(measurementV2UsageEdgeKey))) append(marketKeys, edgeKey3, scope.stableKey);
6850
6860
  const usages = [], usagesByNodeTarget = /* @__PURE__ */ new Map();
6851
6861
  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) ?? [] };
6862
+ const edgeKey3 = measurementV2UsageEdgeKey(edge);
6863
+ const usage = { edge, assignment: assignments.get(edgeKey3), queryText: queryTexts.get(edge.queryId), marketKeys: marketKeys.get(edgeKey3) ?? [] };
6854
6864
  usages.push(usage);
6855
6865
  append(usagesByNodeTarget, pairKey(edge.executionNodeKey, edge.targetKey), usage);
6856
6866
  }
@@ -6957,9 +6967,11 @@ var SentimentService = class {
6957
6967
  settings(projectId, administrator = false) {
6958
6968
  const install = this.options.install();
6959
6969
  const row = this.repository.getSettings(projectId);
6960
- const supportedDefinition = !row || hasCurrentSentimentTemplate(this.definition(row.evaluationDefinitionId));
6970
+ const definition2 = row ? this.definition(row.evaluationDefinitionId) : null;
6971
+ const supportedDefinition = !definition2 || hasCurrentSentimentTemplate(definition2) && sentimentEvaluatorProvider(definition2) === (install.provider ?? "typesafe") && definition2.requestedModel === install.model;
6961
6972
  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;
6973
+ const evaluatorLabel = install.provider === "openrouter" ? "OpenRouter" : "TypeSafe";
6974
+ 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
6975
  const ready = install.ready && supportedDefinition && pause?.blockedReason !== "provider-authorization";
6964
6976
  return {
6965
6977
  installEnabled: install.enabled,
@@ -6967,13 +6979,14 @@ var SentimentService = class {
6967
6979
  ready,
6968
6980
  readinessReasons: [...install.reason ? [install.reason] : [], ...!supportedDefinition ? ["unsupported-evaluator-definition: configure sentiment again to use the current evaluator."] : [], ...pauseReason ? [pauseReason] : []],
6969
6981
  model: install.model,
6982
+ provider: install.provider ?? "typesafe",
6970
6983
  enablementEpoch: row?.enablementEpoch ?? 0,
6971
6984
  completionBoundary: row?.completionBoundary ?? 0,
6972
6985
  evaluationDefinitionId: row?.evaluationDefinitionId ?? null,
6973
6986
  // A project that is still on can always be switched off, even while the install switch is off.
6974
6987
  actions: { configure: administrator && (install.enabled || Boolean(row?.enabled)), backfill: administrator && ready && Boolean(row?.enabled) },
6975
6988
  experimental: true,
6976
- disclosure: DISCLOSURE
6989
+ disclosure: install.provider === "openrouter" ? DISCLOSURE.replace("to TypeSafe", "to OpenRouter for the pinned TypeSafe Jev evaluator") : DISCLOSURE
6977
6990
  };
6978
6991
  }
6979
6992
  configure(projectId, value, actor = "system") {
@@ -6983,10 +6996,10 @@ var SentimentService = class {
6983
6996
  if (enabled && !previous.installEnabled) throw validationError("Sentiment is disabled in install configuration.");
6984
6997
  if (enabled && !this.options.install().ready) throw validationError("Sentiment provider is not ready.", { reasons: previous.readinessReasons });
6985
6998
  const configuration = { enabled };
6986
- const definition2 = createSentimentEvaluationDefinition();
6999
+ const definition2 = createSentimentEvaluationDefinition(this.options.install().provider);
6987
7000
  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))) });
7001
+ this.repository.putDefinition({ id: definitionId, contentHash: definitionId, requestedModel: definition2.requestedModel, definition: definition2, createdAt: this.now() });
7002
+ this.repository.configure({ projectId, enabled: configuration.enabled, evaluationDefinitionId: definitionId, configuration, actor, now: this.now(), forceNewEpoch: Boolean(previous.evaluationDefinitionId && previous.evaluationDefinitionId !== definitionId) });
6990
7003
  return this.settings(projectId, true);
6991
7004
  }
6992
7005
  disabled(projectId) {
@@ -7017,7 +7030,7 @@ var SentimentService = class {
7017
7030
  const source = selectSentimentSources(this.db, projectId, sourceFilter(selection));
7018
7031
  const frozenSelection = selection.runId ? { ...selection, runId: source.runIds[0] } : source.runIds.length ? { ...selection, runIds: source.runIds } : selection;
7019
7032
  const definitionId = settings.evaluationDefinitionId;
7020
- const definition2 = definitionId ? this.definition(definitionId) : createSentimentEvaluationDefinition();
7033
+ const definition2 = definitionId ? this.definition(definitionId) : createSentimentEvaluationDefinition(this.options.install().provider);
7021
7034
  const inputs = source.assessments.map((item2) => sentimentClassifierInput(item2, definition2));
7022
7035
  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
7036
  const completed = new Set(existing.map((work) => `${work.snapshotId}:${work.sourceTextHash}:${work.subjectHash}`));
@@ -8614,6 +8627,103 @@ function connectionRoute(app, subjectOf, handler) {
8614
8627
  };
8615
8628
  }
8616
8629
 
8630
+ // ../api-routes/src/provider-models.ts
8631
+ function assertOpenRouterRouteScope(request, selected, authorized) {
8632
+ const saved = new Set(authorized.map((name) => name.trim().toLowerCase()));
8633
+ if (selected.some((name) => openRouterRouteModel(name.trim().toLowerCase()) && !saved.has(name.trim().toLowerCase()))) {
8634
+ requireScope(request, SETTINGS_WRITE_SCOPE);
8635
+ }
8636
+ }
8637
+ function providerAdapterForName(name, adapters) {
8638
+ const direct = adapters.find((adapter) => adapter.name === name);
8639
+ if (direct) return direct;
8640
+ const model = openRouterRouteModel(name);
8641
+ const connection = model && adapters.find((adapter) => adapter.name === ProviderNames.openrouter);
8642
+ if (!connection || !model) return void 0;
8643
+ connection.modelValidationPattern.lastIndex = 0;
8644
+ if (!connection.modelValidationPattern.test(model)) return void 0;
8645
+ const known = connection.knownModels.find((entry) => entry.id === model);
8646
+ return {
8647
+ ...connection,
8648
+ name,
8649
+ displayName: `${known?.displayName ?? model} via OpenRouter`,
8650
+ modelConfigurable: false,
8651
+ defaultModel: model,
8652
+ knownModels: known ? [known] : [],
8653
+ modelValidationHint: "The OpenRouter route pins its model; select another route to change it."
8654
+ };
8655
+ }
8656
+ function validateProviderModels(models, adapters) {
8657
+ const entries = Object.entries(models);
8658
+ if (entries.length === 0) return {};
8659
+ if (!adapters || adapters.length === 0) {
8660
+ throw validationError("Project model overrides are unavailable because provider metadata is not configured.");
8661
+ }
8662
+ const normalized = {};
8663
+ for (const [provider, rawModel] of entries) {
8664
+ const adapter = providerAdapterForName(provider, adapters);
8665
+ if (!adapter) {
8666
+ throw validationError(`Invalid provider model override: unknown provider "${provider}".`, {
8667
+ provider,
8668
+ validProviders: adapters.map((item2) => item2.name)
8669
+ });
8670
+ }
8671
+ const pinned = openRouterRouteModel(provider);
8672
+ if (pinned && rawModel.trim() !== pinned) {
8673
+ throw validationError(`OpenRouter route "${provider}" pins model "${pinned}". Select another route to change it.`, { provider, model: rawModel, pinnedModel: pinned });
8674
+ }
8675
+ if (!adapter.modelConfigurable && !pinned) {
8676
+ throw validationError(`Provider "${provider}" does not support project model overrides.`, {
8677
+ provider,
8678
+ modelConfigurable: false
8679
+ });
8680
+ }
8681
+ const model = rawModel.trim();
8682
+ if (!model) {
8683
+ throw validationError(`Model override for provider "${provider}" must not be blank.`);
8684
+ }
8685
+ adapter.modelValidationPattern.lastIndex = 0;
8686
+ if (!adapter.modelValidationPattern.test(model)) {
8687
+ throw validationError(
8688
+ `Invalid model "${model}" for provider "${provider}" \u2014 ${adapter.modelValidationHint}`,
8689
+ { provider, model, hint: adapter.modelValidationHint }
8690
+ );
8691
+ }
8692
+ normalized[provider] = resolveProviderModel(provider, model);
8693
+ }
8694
+ return normalized;
8695
+ }
8696
+ function validateProviderDispatchModes(modes, adapters) {
8697
+ const entries = Object.entries(modes);
8698
+ if (entries.length === 0) return {};
8699
+ if (!adapters || adapters.length === 0) {
8700
+ throw validationError("Project dispatch modes are unavailable because provider metadata is not configured.");
8701
+ }
8702
+ const normalized = {};
8703
+ for (const [provider, mode] of entries) {
8704
+ if (!providerAdapterForName(provider, adapters)) {
8705
+ throw validationError(`Invalid provider dispatch mode: unknown provider "${provider}".`, {
8706
+ provider,
8707
+ validProviders: adapters.map((item2) => item2.name)
8708
+ });
8709
+ }
8710
+ normalized[provider] = mode;
8711
+ }
8712
+ return normalized;
8713
+ }
8714
+ function pruneProviderModelsForProviders(models, providers) {
8715
+ if (providers.length === 0) return { ...models };
8716
+ const kept = {};
8717
+ for (const [provider, model] of Object.entries(models)) {
8718
+ if (providers.includes(provider)) kept[provider] = model;
8719
+ }
8720
+ return kept;
8721
+ }
8722
+ function pruneProviderDispatchModes(modes, providers, revisionProviders) {
8723
+ if (providers.length === 0) return { ...modes };
8724
+ return pruneProviderModelsForProviders(modes, [...providers, ...revisionProviders]);
8725
+ }
8726
+
8617
8727
  // ../api-routes/src/settings.ts
8618
8728
  var SETTINGS_WRITE_SCOPE = "settings.write";
8619
8729
  async function settingsRoutes(app, opts) {
@@ -8621,23 +8731,33 @@ async function settingsRoutes(app, opts) {
8621
8731
  requireAdminSession(request);
8622
8732
  return {
8623
8733
  providers: opts.providerSummary ?? [],
8624
- providerCatalog: await Promise.all((opts.providerAdapters ?? []).map(async (adapter) => {
8734
+ providerCatalog: (await Promise.all((opts.providerAdapters ?? []).map(async (adapter) => {
8625
8735
  const configured = opts.providerSummary?.some((provider) => provider.name === adapter.name && provider.configured);
8626
8736
  const discovered = configured && opts.getProviderModels ? await opts.getProviderModels(adapter.name) : [];
8627
- return {
8737
+ const descriptor = {
8628
8738
  name: adapter.name,
8629
8739
  displayName: adapter.displayName,
8630
8740
  mode: adapter.mode,
8631
8741
  modelConfigurable: adapter.modelConfigurable,
8632
8742
  defaultModel: adapter.defaultModel,
8633
- knownModels: discovered.length ? discovered : adapter.knownModels,
8743
+ // Catalog entries can carry Aero's model metadata (limits, prices,
8744
+ // tool support); the documented choice shape is id, name and tier.
8745
+ knownModels: (discovered.length ? discovered : adapter.knownModels).map(({ id, displayName, tier }) => ({ id, displayName, tier })),
8634
8746
  modelValidationPattern: {
8635
8747
  source: adapter.modelValidationPattern.source,
8636
8748
  flags: adapter.modelValidationPattern.flags
8637
8749
  },
8638
8750
  modelValidationHint: adapter.modelValidationHint
8639
8751
  };
8640
- })),
8752
+ if (adapter.name !== ProviderNames.openrouter) return [descriptor];
8753
+ const routeAdapters = descriptor.knownModels.flatMap((model) => {
8754
+ const routeName = `openrouter:${model.id}`;
8755
+ if (!isOpenRouterRoute(routeName)) return [];
8756
+ const route = providerAdapterForName(openRouterRouteName(model.id), [{ ...adapter, knownModels: descriptor.knownModels }]);
8757
+ return route ? [{ ...descriptor, name: route.name, displayName: route.displayName, modelConfigurable: false, defaultModel: model.id, knownModels: [model], modelValidationHint: route.modelValidationHint }] : [];
8758
+ });
8759
+ return [descriptor, ...routeAdapters];
8760
+ }))).flat(),
8641
8761
  google: opts.google ?? { configured: false },
8642
8762
  bing: opts.bing ?? { configured: false }
8643
8763
  };
@@ -8780,79 +8900,9 @@ async function settingsRoutes(app, opts) {
8780
8900
  });
8781
8901
  }
8782
8902
 
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
8903
  // ../api-routes/src/run-queue.ts
8854
8904
  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";
8905
+ 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
8906
 
8857
8907
  // ../api-routes/src/measurement-report-adapter.ts
8858
8908
  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 +10254,7 @@ function ensureCurrentQueryBasketRevision(db, projectId, now = (/* @__PURE__ */
10204
10254
  function hasActiveMeasurementPlan(db, projectId) {
10205
10255
  return db.select({ projectId: measurementPlans.projectId }).from(measurementPlans).where(eq19(measurementPlans.projectId, projectId)).get() !== void 0;
10206
10256
  }
10207
- function activeRevisionProviders(db, projectId) {
10257
+ function activeRevisionProviders(db, projectId, selection = {}) {
10208
10258
  const version = db.select({ canonicalJson: measurementPlanVersions.canonicalJson }).from(measurementPlans).innerJoin(measurementPlanVersions, and13(
10209
10259
  eq19(measurementPlanVersions.projectId, measurementPlans.projectId),
10210
10260
  eq19(measurementPlanVersions.id, measurementPlans.activeVersionId)
@@ -10212,7 +10262,9 @@ function activeRevisionProviders(db, projectId) {
10212
10262
  if (!version) return [];
10213
10263
  const stored = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
10214
10264
  if (stored.schemaVersion !== MEASUREMENT_PLAN_V2_SCHEMA_VERSION) return [];
10215
- return normalizeProviders(stored.executionNodes.flatMap((node) => node.context.providers));
10265
+ const resolution = sliceForV2(stored, { projectId, ...selection });
10266
+ const nodes = resolution?.executionNodes ?? stored.executionNodes;
10267
+ return normalizeProviders(nodes.flatMap((node) => node.context.providers));
10216
10268
  }
10217
10269
  function executionIdentityChecksum(input) {
10218
10270
  return crypto12.createHash("sha256").update(canonicalMeasurementExecutionIdentityJson(input)).digest("hex");
@@ -10227,12 +10279,11 @@ function resolveRunnableProviderSelection(input) {
10227
10279
  const availableProviders = normalizeProviders(input.runnableProviders ?? []);
10228
10280
  const requested = normalizeProviders(input.requestedProviders ?? []);
10229
10281
  const project = normalizeProviders(input.projectProviders ?? []);
10230
- const selectedProviders = requested.length > 0 ? requested : project.length > 0 ? project : availableProviders;
10231
- const available = new Set(availableProviders);
10282
+ const selectedProviders = requested.length > 0 ? requested : project.length > 0 ? project : availableProviders.filter(isSweepProvider);
10232
10283
  return {
10233
10284
  availableProviders,
10234
10285
  selectedProviders,
10235
- runnableProviders: selectedProviders.filter((provider) => available.has(provider)),
10286
+ runnableProviders: selectedProviders.filter((provider) => isSweepProvider(provider) && isProviderAvailable(provider, availableProviders)),
10236
10287
  selectionSource: requested.length > 0 ? "request" : project.length > 0 ? "project" : "instance"
10237
10288
  };
10238
10289
  }
@@ -10248,7 +10299,7 @@ function effectiveModels(tx, params, providers) {
10248
10299
  const instance = params.providerModels ?? {};
10249
10300
  const resolved = {};
10250
10301
  for (const provider of providers) {
10251
- const model = overrides[provider] ?? instance[provider];
10302
+ const model = openRouterRouteModel(provider) ?? overrides[provider] ?? instance[provider];
10252
10303
  if (model) resolved[provider] = resolveProviderModel(provider, model);
10253
10304
  }
10254
10305
  return resolved;
@@ -10296,7 +10347,11 @@ function materializeV2ExecutionNodes(nodes, instanceModels) {
10296
10347
  const declared = nodeProviderModels(node);
10297
10348
  const resolved = /* @__PURE__ */ new Map();
10298
10349
  for (const provider of nodeProviders) {
10299
- const model = declared.get(provider) ?? instanceModels[provider];
10350
+ const pinned = openRouterRouteModel(provider);
10351
+ if (pinned && declared.has(provider) && declared.get(provider) !== pinned) {
10352
+ throw validationError(`OpenRouter route "${provider}" cannot override its pinned model.`);
10353
+ }
10354
+ const model = pinned ?? declared.get(provider) ?? instanceModels[provider];
10300
10355
  if (model) resolved.set(provider, model);
10301
10356
  }
10302
10357
  const identity = executionSlotIdentity(node, nodeProviders, resolved);
@@ -10556,8 +10611,8 @@ function queueProviderAdmission(db, params, stamp, now) {
10556
10611
  function providersARunWouldCall(roster, runnable) {
10557
10612
  const listed = normalizeProviders(roster);
10558
10613
  if (runnable == null) return listed;
10559
- const available = new Set(normalizeProviders(runnable));
10560
- return listed.filter((provider) => available.has(provider));
10614
+ const available = normalizeProviders(runnable);
10615
+ return listed.filter((provider) => isSweepProvider(provider) && isProviderAvailable(provider, available));
10561
10616
  }
10562
10617
  var PROVIDER_ACCOUNT_LOOKBACK = PROVIDER_ACCOUNT_FAILURE_STREAK * 5;
10563
10618
  function providerSettingsChangeCouldFix(action, diff) {
@@ -10592,10 +10647,11 @@ function heldProviderAccounts(db, params) {
10592
10647
  if (withAccountFailure.length < PROVIDER_ACCOUNT_FAILURE_STREAK && !entries.some((entry) => entry.skipped)) return held;
10593
10648
  const calling = normalizeProviders(params.providers());
10594
10649
  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;
10650
+ 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
10651
  const finished = (run) => Date.parse(run.finishedAt ?? run.createdAt);
10597
10652
  const now = Date.parse(params.now);
10598
- for (const provider of calling) {
10653
+ const accounts = [...new Set(calling.map(providerConnectionName))];
10654
+ for (const provider of accounts) {
10599
10655
  let count9 = 0;
10600
10656
  let newest = null;
10601
10657
  let oldest = null;
@@ -10603,7 +10659,12 @@ function heldProviderAccounts(db, params) {
10603
10659
  let vouched = null;
10604
10660
  let ended = false;
10605
10661
  for (const run of recent) {
10606
- const entry = run.providers[provider];
10662
+ if (provider === ProviderNames.openrouter && answered2(run.id, provider)) {
10663
+ ended = true;
10664
+ break;
10665
+ }
10666
+ const accountEntries = Object.entries(run.providers).filter(([name]) => providerConnectionName(name) === provider).map(([, entry2]) => entry2);
10667
+ const entry = accountEntries.find((entry2) => !entry2.skipped && !isProviderAccountFailure(entry2.code)) ?? accountEntries.find((entry2) => !entry2.skipped) ?? accountEntries[0];
10607
10668
  if (!entry) {
10608
10669
  if (run.status !== RunStatuses.failed && answered2(run.id, provider)) {
10609
10670
  ended = true;
@@ -10612,7 +10673,7 @@ function heldProviderAccounts(db, params) {
10612
10673
  continue;
10613
10674
  }
10614
10675
  if (entry.skipped) {
10615
- vouched = run.skippedProviders?.[provider] ?? null;
10676
+ vouched = Object.entries(run.skippedProviders ?? {}).find(([name]) => providerConnectionName(name) === provider)?.[1] ?? null;
10616
10677
  if (vouched) break;
10617
10678
  continue;
10618
10679
  }
@@ -10648,7 +10709,10 @@ function heldProviderAccounts(db, params) {
10648
10709
  held.delete(change.entityId);
10649
10710
  }
10650
10711
  }
10651
- return held;
10712
+ return new Map(calling.flatMap((provider) => {
10713
+ const streak = held.get(providerConnectionName(provider));
10714
+ return streak ? [[provider, streak]] : [];
10715
+ }));
10652
10716
  }
10653
10717
  function providerAccountFailures(held) {
10654
10718
  const streaks = [...held.values()];
@@ -10898,7 +10962,7 @@ async function projectRoutes(app, opts) {
10898
10962
  }
10899
10963
  const validNames = opts.providerAdapters?.map((adapter) => adapter.name) ?? [];
10900
10964
  if (validNames.length && body.providers?.length) {
10901
- const invalid = body.providers.filter((p) => !validNames.includes(p));
10965
+ const invalid = body.providers.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
10902
10966
  if (invalid.length) {
10903
10967
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
10904
10968
  invalidProviders: invalid,
@@ -10907,6 +10971,7 @@ async function projectRoutes(app, opts) {
10907
10971
  }
10908
10972
  }
10909
10973
  const nextProviders = body.providers ?? [];
10974
+ assertOpenRouterRouteScope(request, nextProviders, []);
10910
10975
  const providerModels = pruneProviderModelsForProviders(
10911
10976
  validateProviderModels(body.providerModels ?? {}, opts.providerAdapters),
10912
10977
  nextProviders
@@ -10984,7 +11049,7 @@ async function projectRoutes(app, opts) {
10984
11049
  const prepareProjectUpdate = (request, body, existing) => {
10985
11050
  const validNames = opts.providerAdapters?.map((adapter) => adapter.name) ?? [];
10986
11051
  if (validNames.length && body.providers?.length) {
10987
- const invalid = body.providers.filter((p) => !validNames.includes(p));
11052
+ const invalid = body.providers.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
10988
11053
  if (invalid.length) {
10989
11054
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
10990
11055
  invalidProviders: invalid,
@@ -10993,6 +11058,7 @@ async function projectRoutes(app, opts) {
10993
11058
  }
10994
11059
  }
10995
11060
  const nextProviders = body.providers ?? [];
11061
+ assertOpenRouterRouteScope(request, nextProviders, existing?.providers ?? []);
10996
11062
  const providerModels = pruneProviderModelsForProviders(
10997
11063
  validateProviderModels(body.providerModels ?? {}, opts.providerAdapters),
10998
11064
  nextProviders
@@ -11896,12 +11962,13 @@ async function queryRoutes(app, opts) {
11896
11962
  const body = parsed.data;
11897
11963
  const provider = body.provider.trim().toLowerCase();
11898
11964
  const validNames = opts.validProviderNames ?? [];
11899
- if (validNames.length && !validNames.includes(provider)) {
11965
+ if (validNames.length && (!isSweepProvider(provider) || !isProviderAvailable(provider, validNames))) {
11900
11966
  throw validationError(`Unknown provider "${body.provider}". Valid providers: ${validNames.join(", ")}`, {
11901
11967
  provider: body.provider,
11902
11968
  validProviders: validNames
11903
11969
  });
11904
11970
  }
11971
+ assertOpenRouterRouteScope(request, [provider], project.providers);
11905
11972
  const count9 = body.count ?? 5;
11906
11973
  if (!opts.onGenerateQueries) {
11907
11974
  throw notImplemented("Query generation is not supported in this deployment");
@@ -12029,12 +12096,13 @@ async function queryRoutes(app, opts) {
12029
12096
  const body = parsed.data;
12030
12097
  const provider = body.provider.trim().toLowerCase();
12031
12098
  const validNames = opts.validProviderNames ?? [];
12032
- if (validNames.length && !validNames.includes(provider)) {
12099
+ if (validNames.length && (!isSweepProvider(provider) || !isProviderAvailable(provider, validNames))) {
12033
12100
  throw validationError(`Unknown provider "${body.provider}". Valid providers: ${validNames.join(", ")}`, {
12034
12101
  provider: body.provider,
12035
12102
  validProviders: validNames
12036
12103
  });
12037
12104
  }
12105
+ assertOpenRouterRouteScope(request, [provider], project.providers);
12038
12106
  const count9 = body.count ?? 5;
12039
12107
  if (!opts.onGenerateQueries) {
12040
12108
  throw notImplemented("Keyword generation is not supported in this deployment");
@@ -14511,8 +14579,8 @@ function evaluateRunFill(db, run, input = {}) {
14511
14579
  );
14512
14580
  }
14513
14581
  if (input.runnableProviders) {
14514
- const runnable = new Set(input.runnableProviders.map(normalizeProvider));
14515
- const absent = providers.filter((provider) => !runnable.has(provider));
14582
+ const runnable = input.runnableProviders.map(normalizeProvider);
14583
+ const absent = providers.filter((provider) => !isProviderAvailable(provider, runnable));
14516
14584
  if (absent.length) {
14517
14585
  return refuse(
14518
14586
  RunFillRefusalCodes.provider_not_configured,
@@ -14522,10 +14590,14 @@ function evaluateRunFill(db, run, input = {}) {
14522
14590
  }
14523
14591
  if (input.dailyLimits) {
14524
14592
  const period2 = new Date(now).toISOString().slice(0, 10);
14593
+ const neededByConnection = /* @__PURE__ */ new Map();
14525
14594
  for (const provider of providers) {
14595
+ const connection = providerConnectionName(provider);
14596
+ neededByConnection.set(connection, (neededByConnection.get(connection) ?? 0) + (missingByProvider.get(provider)?.length ?? 0));
14597
+ }
14598
+ for (const [provider, needed] of neededByConnection) {
14526
14599
  const limit = input.dailyLimits[provider];
14527
14600
  if (limit === void 0) continue;
14528
- const needed = missingByProvider.get(provider)?.length ?? 0;
14529
14601
  const used = db.select({ count: usageCounters.count }).from(usageCounters).where(and23(
14530
14602
  eq31(usageCounters.scope, `${run.projectId}:${provider}`),
14531
14603
  eq31(usageCounters.period, period2),
@@ -14626,7 +14698,7 @@ async function runRoutes(app, opts) {
14626
14698
  const normalized = rawProviders.map((p) => p.trim().toLowerCase()).filter(Boolean);
14627
14699
  const validNames = opts.validProviderNames ?? [];
14628
14700
  if (validNames.length) {
14629
- const invalid = normalized.filter((p) => !validNames.includes(p));
14701
+ const invalid = normalized.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
14630
14702
  if (invalid.length) {
14631
14703
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
14632
14704
  invalidProviders: invalid,
@@ -14637,19 +14709,10 @@ async function runRoutes(app, opts) {
14637
14709
  rawProviders.splice(0, rawProviders.length, ...normalized);
14638
14710
  }
14639
14711
  const providers = rawProviders?.length ? rawProviders : void 0;
14712
+ const revisionProviders = activeRevisionProviders(app.db, project.id);
14713
+ assertOpenRouterRouteScope(request, providers ?? [], [...project.providers, ...revisionProviders]);
14640
14714
  const shouldPreflight = trigger !== RunTriggers.probe && opts.getRunnableProviderNames !== void 0;
14641
14715
  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
14716
  if (body.measurementScope !== void 0 && measurementRunScopeIsEmpty(body.measurementScope)) {
14654
14717
  throw validationError(
14655
14718
  "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."
@@ -14678,6 +14741,21 @@ async function runRoutes(app, opts) {
14678
14741
  scopedQueries = body.queries;
14679
14742
  }
14680
14743
  const queriesColumn = scopedQueries ?? null;
14744
+ if (shouldPreflight) {
14745
+ const measuresAPlan = hasActiveMeasurementPlan(app.db, project.id);
14746
+ const scopedRevisionProviders = activeRevisionProviders(app.db, project.id, {
14747
+ measurementScope: body.measurementScope ?? null,
14748
+ queries: scopedQueries
14749
+ });
14750
+ const preflightError = answerVisibilityPreflightError({
14751
+ projectName: project.name,
14752
+ projectProviders: scopedRevisionProviders.length > 0 ? scopedRevisionProviders : project.providers,
14753
+ requestedProviders: providers,
14754
+ runnableProviderNames: opts.getRunnableProviderNames(),
14755
+ trackedQueryCount: measuresAPlan ? 1 : trackedRows2.length
14756
+ });
14757
+ if (preflightError) throw preflightError;
14758
+ }
14681
14759
  let resolvedLocation;
14682
14760
  const projectLocations = project.locations;
14683
14761
  if (body.noLocation) {
@@ -14900,7 +14978,7 @@ async function runRoutes(app, opts) {
14900
14978
  const normalized = rawProviders.map((p) => p.trim().toLowerCase()).filter(Boolean);
14901
14979
  const validNames = opts.validProviderNames ?? [];
14902
14980
  if (validNames.length) {
14903
- const invalid = normalized.filter((p) => !validNames.includes(p));
14981
+ const invalid = normalized.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
14904
14982
  if (invalid.length) {
14905
14983
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
14906
14984
  invalidProviders: invalid,
@@ -14916,11 +14994,12 @@ async function runRoutes(app, opts) {
14916
14994
  const runnableProviderNames = opts.getRunnableProviderNames?.();
14917
14995
  const eligible = [];
14918
14996
  for (const project of allProjects) {
14997
+ const revisionProviders = activeRevisionProviders(app.db, project.id);
14919
14998
  if (runnableProviderNames) {
14920
14999
  const trackedQuery = app.db.select({ id: queries.id }).from(queries).where(eq32(queries.projectId, project.id)).limit(1).get();
14921
15000
  const preflightError = answerVisibilityPreflightError({
14922
15001
  projectName: project.name,
14923
- projectProviders: project.providers,
15002
+ projectProviders: revisionProviders.length > 0 ? revisionProviders : project.providers,
14924
15003
  requestedProviders: providers,
14925
15004
  runnableProviderNames,
14926
15005
  // A project measuring a published plan runs the plan's frozen
@@ -14949,11 +15028,12 @@ async function runRoutes(app, opts) {
14949
15028
  }
14950
15029
  resolvedLocation = loc;
14951
15030
  }
14952
- eligible.push({ project, resolvedLocation });
15031
+ eligible.push({ project, revisionProviders, resolvedLocation });
14953
15032
  }
14954
15033
  const dispatchable = [];
14955
15034
  for (const entry of eligible) {
14956
15035
  try {
15036
+ assertOpenRouterRouteScope(request, providers ?? [], [...entry.project.providers, ...entry.revisionProviders]);
14957
15037
  assertMeasurementRunStampable(app.db, {
14958
15038
  createdAt: now,
14959
15039
  projectId: entry.project.id,
@@ -15494,9 +15574,9 @@ function executionDiff(before, after) {
15494
15574
  const afterCounts = planCounts(after);
15495
15575
  const nodes = diffKeys(before?.executionNodes ?? [], after.executionNodes);
15496
15576
  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));
15577
+ const edgeKey3 = (edge) => stableJson(edge);
15578
+ const beforeEdgeKeys = new Set(beforeEdges.map(edgeKey3));
15579
+ const afterEdgeKeys = new Set(after.usageEdges.map(edgeKey3));
15500
15580
  const counts2 = {
15501
15581
  before: beforeCounts,
15502
15582
  after: afterCounts,
@@ -15505,8 +15585,8 @@ function executionDiff(before, after) {
15505
15585
  return {
15506
15586
  addedNodeKeys: nodes.added,
15507
15587
  removedNodeKeys: nodes.removed,
15508
- addedUsageEdges: after.usageEdges.filter((edge) => !beforeEdgeKeys.has(edgeKey2(edge))),
15509
- removedUsageEdges: beforeEdges.filter((edge) => !afterEdgeKeys.has(edgeKey2(edge))),
15588
+ addedUsageEdges: after.usageEdges.filter((edge) => !beforeEdgeKeys.has(edgeKey3(edge))),
15589
+ removedUsageEdges: beforeEdges.filter((edge) => !afterEdgeKeys.has(edgeKey3(edge))),
15510
15590
  counts: counts2
15511
15591
  };
15512
15592
  }
@@ -16591,6 +16671,22 @@ function createChecks() {
16591
16671
  function normalizeProviders2(values) {
16592
16672
  return sortedUnique(values.map((value) => value.trim().toLowerCase()).filter(Boolean));
16593
16673
  }
16674
+ function frozenMeasurementDraftExecutionKeys(authoring) {
16675
+ const keys = /* @__PURE__ */ new Map();
16676
+ for (const assignment of authoring.assignments) {
16677
+ for (const exact of assignment.executionContexts ?? []) {
16678
+ if (exact.executionNodeKey === void 0) continue;
16679
+ const signature = canonicalJson({
16680
+ queryId: assignment.queryId,
16681
+ location: exact.location,
16682
+ providers: normalizeProviders2(exact.providers),
16683
+ models: Object.fromEntries(Object.entries(exact.models).map(([provider, model]) => [provider.trim().toLowerCase(), model]))
16684
+ });
16685
+ keys.set(signature, exact.executionNodeKey);
16686
+ }
16687
+ }
16688
+ return keys;
16689
+ }
16594
16690
  function compileMeasurementDraft(authoring, context) {
16595
16691
  const { checks, sink, failed } = createChecks();
16596
16692
  let canonicalHost = "";
@@ -16744,6 +16840,13 @@ function compileMeasurementDraft(authoring, context) {
16744
16840
  }
16745
16841
  models[normalized] = model;
16746
16842
  }
16843
+ for (const provider of providers) {
16844
+ if (!isSweepProvider(provider)) sink.fail("invalid-provider-model", "OpenRouter measurement requires a fixed model route.", [...path8, "providers"]);
16845
+ const pinned = openRouterRouteModel(provider);
16846
+ if (!pinned) continue;
16847
+ if (models[provider] && models[provider] !== pinned) sink.fail("invalid-provider-model", `OpenRouter route "${provider}" pins model "${pinned}".`, [...path8, "models", provider]);
16848
+ models[provider] = pinned;
16849
+ }
16747
16850
  const labels = sortedUnique(override?.locations ?? authoring.defaultContext.locations);
16748
16851
  const locations = [];
16749
16852
  labels.forEach((label, labelIndex) => {
@@ -16771,6 +16874,13 @@ function compileMeasurementDraft(authoring, context) {
16771
16874
  }
16772
16875
  models[normalized] = model;
16773
16876
  }
16877
+ for (const provider of providers) {
16878
+ if (!isSweepProvider(provider)) sink.fail("invalid-provider-model", "OpenRouter measurement requires a fixed model route.", [...path8, "providers"]);
16879
+ const pinned = openRouterRouteModel(provider);
16880
+ if (!pinned) continue;
16881
+ if (models[provider] && models[provider] !== pinned) sink.fail("invalid-provider-model", `OpenRouter route "${provider}" pins model "${pinned}".`, [...path8, "models", provider]);
16882
+ models[provider] = pinned;
16883
+ }
16774
16884
  const identity = exact.executionNodeKey === void 0 ? {} : { executionNodeKey: exact.executionNodeKey };
16775
16885
  if (exact.location === null) return { ...identity, providers, models, location: null };
16776
16886
  const configured = locationsByLabel.get(exact.location.label);
@@ -16790,19 +16900,7 @@ function compileMeasurementDraft(authoring, context) {
16790
16900
  const usedQueryIds = /* @__PURE__ */ new Set();
16791
16901
  const claimedPairs = /* @__PURE__ */ new Set();
16792
16902
  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
- }
16903
+ const frozenKeysBySignature = frozenMeasurementDraftExecutionKeys(authoring);
16806
16904
  authoring.assignments.forEach((assignment, index) => {
16807
16905
  const path8 = ["assignments", index];
16808
16906
  const pair = `${assignment.targetKey} ${assignment.queryId}`;
@@ -17050,6 +17148,7 @@ var MEASUREMENT_DRAFT_ACTIONS = [
17050
17148
  "apply-assignments",
17051
17149
  "replace-assignments",
17052
17150
  "apply-paired-assignments",
17151
+ "route-markets",
17053
17152
  "remove-assignment",
17054
17153
  "clear-assignments",
17055
17154
  "classify-assignments",
@@ -17178,10 +17277,187 @@ function assertMeasurementDraftAuthoringLimits(before, candidate) {
17178
17277
  function warn(code, message, path8) {
17179
17278
  return { code, message, path: path8 };
17180
17279
  }
17181
- function withRequestedContext(assignment, contextOverride) {
17280
+ function normalizedProviders2(values) {
17281
+ return unique(values.map((value) => value.trim().toLowerCase()).filter(Boolean)).sort(compareText);
17282
+ }
17283
+ function normalizedModels(values) {
17284
+ return Object.fromEntries(Object.entries(values).map(([provider, model]) => [provider.trim().toLowerCase(), model]).sort(([left], [right]) => compareText(left, right)));
17285
+ }
17286
+ function normalizedExactContext(exact, queryId, override, frozenKeys) {
17287
+ const providers = normalizedProviders2(override.providers ?? exact.providers);
17288
+ const models = normalizedModels(override.models ?? (override.providers === void 0 ? exact.models : {}));
17289
+ for (const provider of providers) {
17290
+ const pinned = openRouterRouteModel(provider);
17291
+ if (pinned) models[provider] = pinned;
17292
+ }
17293
+ const next = { providers, models, location: exact.location };
17294
+ const current = {
17295
+ providers: normalizedProviders2(exact.providers),
17296
+ models: normalizedModels(exact.models),
17297
+ location: exact.location
17298
+ };
17299
+ if (canonicalJson(next) === canonicalJson(current)) return exact;
17300
+ const signature = canonicalJson({ queryId, ...next });
17301
+ return {
17302
+ ...next,
17303
+ executionNodeKey: frozenKeys.get(signature) ?? `execution-${sha256Hex(signature)}`
17304
+ };
17305
+ }
17306
+ function edgeKey(targetKey, queryId, executionNodeKey) {
17307
+ return measurementV2UsageEdgeKey({ targetKey, queryId, executionNodeKey });
17308
+ }
17309
+ function remapReportingScopeEdges(reportingScopes, remaps) {
17310
+ if (reportingScopes === void 0 || remaps.size === 0) return reportingScopes;
17311
+ return reportingScopes.map((scope) => {
17312
+ const seen2 = /* @__PURE__ */ new Set();
17313
+ const usageEdges = [];
17314
+ for (const edge of scope.usageEdges) {
17315
+ const next = remaps.get(measurementV2UsageEdgeKey(edge)) ?? edge;
17316
+ const key = measurementV2UsageEdgeKey(next);
17317
+ if (seen2.has(key)) continue;
17318
+ seen2.add(key);
17319
+ usageEdges.push(next);
17320
+ }
17321
+ return { ...scope, usageEdges };
17322
+ });
17323
+ }
17324
+ function pruneReportingScopeEdges(reportingScopes, assignments) {
17325
+ if (reportingScopes === void 0) return void 0;
17326
+ const validPairs = new Set(assignments.map((assignment) => `${assignment.targetKey}\0${assignment.queryId}`));
17327
+ return reportingScopes.map((scope) => ({
17328
+ ...scope,
17329
+ usageEdges: scope.usageEdges.filter((edge) => validPairs.has(`${edge.targetKey}\0${edge.queryId}`))
17330
+ }));
17331
+ }
17332
+ function authoringWithAssignments(authoring, assignments, reportingScopes = authoring.reportingScopes) {
17333
+ return {
17334
+ ...authoring,
17335
+ assignments,
17336
+ ...reportingScopes === void 0 ? {} : { reportingScopes: pruneReportingScopeEdges(reportingScopes, assignments) }
17337
+ };
17338
+ }
17339
+ function mutableAssignmentContext(authoring, assignment) {
17340
+ const override = assignment.contextOverride;
17341
+ const providers = normalizedProviders2(override?.providers ?? authoring.defaultContext.providers);
17342
+ const rawModels = normalizedModels(override?.models ?? authoring.defaultContext.models ?? {});
17343
+ const models = Object.fromEntries(Object.entries(rawModels).filter(([provider]) => providers.includes(provider)));
17344
+ for (const provider of providers) {
17345
+ const pinned = openRouterRouteModel(provider);
17346
+ if (pinned) models[provider] = pinned;
17347
+ }
17348
+ const locationLabels = unique(override?.locations ?? authoring.defaultContext.locations).sort(compareText);
17349
+ return { providers, models, locationLabels };
17350
+ }
17351
+ function mutableAssignmentExactContext(authoring, assignment, context, frozenKeys) {
17352
+ const { providers, models, locationLabels } = mutableAssignmentContext(authoring, assignment);
17353
+ if (locationLabels.length > 1) {
17354
+ throw validationError(
17355
+ `Market routing cannot safely choose among ${locationLabels.length} locations for ${assignment.targetKey}/${assignment.queryId}. Route the Property to one location first.`,
17356
+ { displayToOperator: true }
17357
+ );
17358
+ }
17359
+ const location = locationLabels.length === 0 ? null : context.locationsByLabel?.get(locationLabels[0]);
17360
+ if (locationLabels.length === 1 && !location) {
17361
+ throw validationError(`Location "${locationLabels[0]}" is unavailable for market routing. Reload the draft and try again.`, {
17362
+ displayToOperator: true
17363
+ });
17364
+ }
17365
+ const resolvedLocation = location ?? null;
17366
+ const locationIdentity = resolvedLocation ? [resolvedLocation.label, resolvedLocation.city, resolvedLocation.region, resolvedLocation.country].join("\0") : "";
17367
+ const executionNodeKey = frozenKeys.get(canonicalJson({
17368
+ queryId: assignment.queryId,
17369
+ location: resolvedLocation,
17370
+ providers,
17371
+ models
17372
+ })) ?? `execution-${sha256Hex(canonicalJson({
17373
+ queryId: assignment.queryId,
17374
+ location: locationIdentity,
17375
+ providers,
17376
+ models
17377
+ }))}`;
17378
+ return { providers, models, location: resolvedLocation, executionNodeKey };
17379
+ }
17380
+ function normalizeSelectedOneToOneMarketEdges(authoring, selectedMarkets, selectsEdge, context) {
17381
+ const assignmentsByPair = new Map(authoring.assignments.map((assignment, index) => [
17382
+ `${assignment.targetKey}\0${assignment.queryId}`,
17383
+ { assignment, index }
17384
+ ]));
17385
+ const successorByPair = /* @__PURE__ */ new Map();
17386
+ const mutableIndexes = /* @__PURE__ */ new Set();
17387
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17388
+ for (const scope of authoring.reportingScopes ?? []) {
17389
+ if (!selectedMarkets.has(scope.stableKey)) continue;
17390
+ for (const edge of scope.usageEdges) {
17391
+ if (!selectsEdge(edge)) continue;
17392
+ const pair = `${edge.targetKey}\0${edge.queryId}`;
17393
+ const found = assignmentsByPair.get(pair);
17394
+ if (!found) continue;
17395
+ if (found.assignment.executionContexts?.some((exact) => exact.executionNodeKey === edge.executionNodeKey)) continue;
17396
+ if (successorByPair.has(pair)) continue;
17397
+ if (found.assignment.executionContexts !== void 0) {
17398
+ if (found.assignment.executionContexts.length !== 1 || !found.assignment.executionContexts[0].executionNodeKey) {
17399
+ throw validationError(
17400
+ `Market routing cannot safely map stale membership for ${edge.targetKey}/${edge.queryId} across multiple contexts. Publish or restore one exact context first.`,
17401
+ { displayToOperator: true, marketEdge: edge }
17402
+ );
17403
+ }
17404
+ successorByPair.set(pair, found.assignment.executionContexts[0]);
17405
+ continue;
17406
+ }
17407
+ successorByPair.set(pair, mutableAssignmentExactContext(authoring, found.assignment, context, frozenKeys));
17408
+ mutableIndexes.add(found.index);
17409
+ }
17410
+ }
17411
+ if (successorByPair.size === 0) return authoring;
17412
+ const assignments = authoring.assignments.map((assignment, index) => {
17413
+ if (!mutableIndexes.has(index)) return assignment;
17414
+ const successor = successorByPair.get(`${assignment.targetKey}\0${assignment.queryId}`);
17415
+ const { contextOverride: _contextOverride, ...frozen } = assignment;
17416
+ return { ...frozen, executionContexts: [successor] };
17417
+ });
17418
+ const reportingScopes = authoring.reportingScopes?.map((scope) => {
17419
+ const seen2 = /* @__PURE__ */ new Set();
17420
+ const usageEdges = [];
17421
+ for (const edge of scope.usageEdges) {
17422
+ const successor = successorByPair.get(`${edge.targetKey}\0${edge.queryId}`);
17423
+ const next = successor?.executionNodeKey ? { ...edge, executionNodeKey: successor.executionNodeKey } : edge;
17424
+ const key = measurementV2UsageEdgeKey(next);
17425
+ if (seen2.has(key)) continue;
17426
+ seen2.add(key);
17427
+ usageEdges.push(next);
17428
+ }
17429
+ return { ...scope, usageEdges };
17430
+ });
17431
+ return authoringWithAssignments(authoring, assignments, reportingScopes);
17432
+ }
17433
+ function withRequestedContext(assignment, contextOverride, frozenKeys, edgeRemaps) {
17182
17434
  if (contextOverride === void 0) return assignment;
17435
+ if (assignment.executionContexts !== void 0 && contextOverride.locations === void 0) {
17436
+ const contextsByIdentity = /* @__PURE__ */ new Map();
17437
+ for (const exact of assignment.executionContexts) {
17438
+ const rewritten = normalizedExactContext(exact, assignment.queryId, contextOverride, frozenKeys);
17439
+ const identity = canonicalJson({
17440
+ providers: normalizedProviders2(rewritten.providers),
17441
+ models: normalizedModels(rewritten.models),
17442
+ location: rewritten.location
17443
+ });
17444
+ const kept = contextsByIdentity.get(identity) ?? rewritten;
17445
+ contextsByIdentity.set(identity, kept);
17446
+ if (edgeRemaps && exact.executionNodeKey && kept.executionNodeKey && exact.executionNodeKey !== kept.executionNodeKey) {
17447
+ edgeRemaps.set(
17448
+ edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey),
17449
+ { targetKey: assignment.targetKey, queryId: assignment.queryId, executionNodeKey: kept.executionNodeKey }
17450
+ );
17451
+ }
17452
+ }
17453
+ return { ...assignment, executionContexts: [...contextsByIdentity.values()] };
17454
+ }
17183
17455
  const { executionContexts: _frozenContexts, ...withoutFrozenContexts } = assignment;
17184
- return { ...withoutFrozenContexts, contextOverride };
17456
+ const locations = contextOverride.locations ?? assignment.contextOverride?.locations;
17457
+ return {
17458
+ ...withoutFrozenContexts,
17459
+ contextOverride: { ...contextOverride, ...locations === void 0 ? {} : { locations } }
17460
+ };
17185
17461
  }
17186
17462
  function upsertTarget(authoring, body, context) {
17187
17463
  const { target } = parseBody2(measurementDraftUpsertTargetRequestSchema, body, "upsert-target");
@@ -17226,24 +17502,68 @@ function mergeTargets(authoring, body) {
17226
17502
  urlMatchers: unique([...survivor.urlMatchers, ...authoring.targets.filter((target) => absorbedSet.has(target.stableKey)).flatMap((target) => target.urlMatchers)])
17227
17503
  };
17228
17504
  const assignments = [];
17229
- const seen2 = /* @__PURE__ */ new Set();
17505
+ const assignmentIndexes = /* @__PURE__ */ new Map();
17230
17506
  for (const assignment of authoring.assignments) {
17231
17507
  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 });
17508
+ const key = `${owner}\0${assignment.queryId}`;
17509
+ const mapped = { ...assignment, targetKey: owner };
17510
+ const index = assignmentIndexes.get(key);
17511
+ if (index === void 0) {
17512
+ assignmentIndexes.set(key, assignments.length);
17513
+ assignments.push(mapped);
17514
+ continue;
17515
+ }
17516
+ const existing = assignments[index];
17517
+ if (existing.executionContexts === void 0 !== (mapped.executionContexts === void 0)) {
17518
+ throw validationError(
17519
+ `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.`,
17520
+ { displayToOperator: true }
17521
+ );
17522
+ }
17523
+ if (existing.executionContexts === void 0 && mapped.executionContexts === void 0 && canonicalJson(mutableAssignmentContext(authoring, existing)) !== canonicalJson(mutableAssignmentContext(authoring, mapped))) {
17524
+ throw validationError(
17525
+ `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.`,
17526
+ { displayToOperator: true }
17527
+ );
17528
+ }
17529
+ const currentIsSurvivor = assignment.targetKey === targetKey;
17530
+ const winner = currentIsSurvivor ? mapped : existing;
17531
+ if (existing.executionContexts === void 0 || mapped.executionContexts === void 0) {
17532
+ assignments[index] = winner;
17533
+ continue;
17534
+ }
17535
+ const contexts = /* @__PURE__ */ new Map();
17536
+ for (const exact of [...existing.executionContexts, ...mapped.executionContexts]) {
17537
+ const identity = exact.executionNodeKey ?? canonicalJson({
17538
+ providers: normalizedProviders2(exact.providers),
17539
+ models: normalizedModels(exact.models),
17540
+ location: exact.location
17541
+ });
17542
+ if (!contexts.has(identity)) contexts.set(identity, exact);
17543
+ }
17544
+ assignments[index] = { ...winner, executionContexts: [...contexts.values()] };
17236
17545
  }
17546
+ const reportingScopes = authoring.reportingScopes?.map((scope) => {
17547
+ const seenEdges = /* @__PURE__ */ new Set();
17548
+ const usageEdges = [];
17549
+ for (const edge of scope.usageEdges) {
17550
+ const next = absorbedSet.has(edge.targetKey) ? { ...edge, targetKey } : edge;
17551
+ const key = measurementV2UsageEdgeKey(next);
17552
+ if (seenEdges.has(key)) continue;
17553
+ seenEdges.add(key);
17554
+ usageEdges.push(next);
17555
+ }
17556
+ return { ...scope, usageEdges };
17557
+ });
17237
17558
  return {
17238
- authoring: {
17559
+ authoring: authoringWithAssignments({
17239
17560
  ...authoring,
17240
17561
  targets: authoring.targets.filter((target) => !absorbedSet.has(target.stableKey)).map((target) => target.stableKey === targetKey ? merged : target),
17241
- assignments,
17242
17562
  groups: authoring.groups.map((group) => ({
17243
17563
  ...group,
17244
17564
  targetKeys: unique(group.targetKeys.map((key) => absorbedSet.has(key) ? targetKey : key))
17245
17565
  }))
17246
- },
17566
+ }, assignments, reportingScopes),
17247
17567
  warnings: []
17248
17568
  };
17249
17569
  }
@@ -17253,16 +17573,16 @@ function excludeTarget(authoring, body) {
17253
17573
  const targetIndex = authoring.targets.indexOf(target);
17254
17574
  const stranded = authoring.assignments.filter((assignment) => assignment.targetKey === targetKey).length;
17255
17575
  if (cleanup === "assignments-and-group-memberships") {
17576
+ const assignments = authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey);
17256
17577
  return {
17257
- authoring: {
17578
+ authoring: authoringWithAssignments({
17258
17579
  ...authoring,
17259
17580
  targets: authoring.targets.map((target2) => target2.stableKey === targetKey ? { ...target2, status: "excluded" } : target2),
17260
- assignments: authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey),
17261
17581
  groups: authoring.groups.map((group) => ({
17262
17582
  ...group,
17263
17583
  targetKeys: group.targetKeys.filter((key) => key !== targetKey)
17264
17584
  }))
17265
- },
17585
+ }, assignments),
17266
17586
  warnings: []
17267
17587
  };
17268
17588
  }
@@ -17297,6 +17617,8 @@ function applyAssignmentsToAuthoring(authoring, request, context) {
17297
17617
  assertAssignmentActionLimit(audience, queryIds);
17298
17618
  const targetByKey = new Map(authoring.targets.map((target) => [target.stableKey, target]));
17299
17619
  const assignments = [...authoring.assignments];
17620
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17621
+ const edgeRemaps = /* @__PURE__ */ new Map();
17300
17622
  const assignmentIndexes = new Map(assignments.map((assignment, index) => [
17301
17623
  `${assignment.targetKey}\0${assignment.queryId}`,
17302
17624
  index
@@ -17320,14 +17642,18 @@ function applyAssignmentsToAuthoring(authoring, request, context) {
17320
17642
  }
17321
17643
  const existing = assignments[index];
17322
17644
  assignments[index] = {
17323
- ...withRequestedContext(existing, request.contextOverride),
17645
+ ...withRequestedContext(existing, request.contextOverride, frozenKeys, edgeRemaps),
17324
17646
  ...existing.classificationSource === "operator" ? {} : { queryClass: proposeQueryClassForTarget(context.queriesById.get(queryId), context.brandNames, targetByKey.get(targetKey)) }
17325
17647
  };
17326
17648
  }
17327
17649
  }
17328
17650
  const requested = audience.targetKeys.length * queryIds.length;
17329
17651
  return {
17330
- authoring: { ...authoring, assignments },
17652
+ authoring: authoringWithAssignments(
17653
+ authoring,
17654
+ assignments,
17655
+ remapReportingScopeEdges(authoring.reportingScopes, edgeRemaps)
17656
+ ),
17331
17657
  warnings: [],
17332
17658
  audience,
17333
17659
  assignments: { requested, added, alreadyPresent: requested - added }
@@ -17370,6 +17696,8 @@ function applyPairedAssignments(authoring, body, context) {
17370
17696
  }
17371
17697
  const targetByKey = new Map(authoring.targets.map((target) => [target.stableKey, target]));
17372
17698
  const assignments = [...authoring.assignments];
17699
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(authoring);
17700
+ const edgeRemaps = /* @__PURE__ */ new Map();
17373
17701
  const assignmentIndexes = new Map(assignments.map((assignment, index) => [
17374
17702
  `${assignment.targetKey}\0${assignment.queryId}`,
17375
17703
  index
@@ -17390,31 +17718,197 @@ function applyPairedAssignments(authoring, body, context) {
17390
17718
  }
17391
17719
  const existing = assignments[index];
17392
17720
  assignments[index] = {
17393
- ...withRequestedContext(existing, contextOverride),
17721
+ ...withRequestedContext(existing, contextOverride, frozenKeys, edgeRemaps),
17394
17722
  ...existing.classificationSource === "operator" ? {} : { queryClass: proposeQueryClassForTarget(context.queriesById.get(queryId), context.brandNames, targetByKey.get(targetKey)) }
17395
17723
  };
17396
17724
  }
17397
- return { authoring: { ...authoring, assignments }, warnings: [] };
17725
+ return {
17726
+ authoring: authoringWithAssignments(
17727
+ authoring,
17728
+ assignments,
17729
+ remapReportingScopeEdges(authoring.reportingScopes, edgeRemaps)
17730
+ ),
17731
+ warnings: []
17732
+ };
17733
+ }
17734
+ function routeMarketsInAuthoring(authoring, request, context) {
17735
+ const assignmentPairs = new Set(authoring.assignments.map((assignment) => `${assignment.targetKey}\0${assignment.queryId}`));
17736
+ const originalScopesByKey = new Map((authoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17737
+ const pairPrunedAuthoring = authoringWithAssignments(authoring, authoring.assignments);
17738
+ const marketKeys = unique(request.marketKeys);
17739
+ const availableScopesByKey = new Map((pairPrunedAuthoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17740
+ for (const marketKey of marketKeys) {
17741
+ const scope = availableScopesByKey.get(marketKey);
17742
+ if (!scope) {
17743
+ throw validationError(`Selected market "${marketKey}" is no longer available. Reload the draft and try again.`, {
17744
+ displayToOperator: true
17745
+ });
17746
+ }
17747
+ }
17748
+ const targetFilter = request.targetKeys ? new Set(unique(request.targetKeys)) : null;
17749
+ if (targetFilter) {
17750
+ for (const targetKey of targetFilter) {
17751
+ const target = requireTarget(pairPrunedAuthoring, targetKey);
17752
+ if (target.status !== "included") {
17753
+ throw validationError(`Property "${target.label}" is ${target.status}, not included.`, { displayToOperator: true });
17754
+ }
17755
+ }
17756
+ }
17757
+ const queryFilter = request.queryIds ? new Set(knownQueryIds(request.queryIds, context)) : null;
17758
+ const selectedMarkets = new Set(marketKeys);
17759
+ const selectsEdge = (edge) => (targetFilter === null || targetFilter.has(edge.targetKey)) && (queryFilter === null || queryFilter.has(edge.queryId));
17760
+ const routableAuthoring = normalizeSelectedOneToOneMarketEdges(
17761
+ pairPrunedAuthoring,
17762
+ selectedMarkets,
17763
+ selectsEdge,
17764
+ context
17765
+ );
17766
+ const routableScopesByKey = new Map((routableAuthoring.reportingScopes ?? []).map((scope) => [scope.stableKey, scope]));
17767
+ const markets = marketKeys.map((marketKey) => routableScopesByKey.get(marketKey));
17768
+ const staleSelectedEdges = /* @__PURE__ */ new Map();
17769
+ for (const scope of authoring.reportingScopes ?? []) {
17770
+ if (!selectedMarkets.has(scope.stableKey)) continue;
17771
+ for (const edge of scope.usageEdges) {
17772
+ if (!selectsEdge(edge) || assignmentPairs.has(`${edge.targetKey}\0${edge.queryId}`)) continue;
17773
+ staleSelectedEdges.set(measurementV2UsageEdgeKey(edge), edge);
17774
+ }
17775
+ }
17776
+ const selectedEdges = /* @__PURE__ */ new Map();
17777
+ const unselectedUses = /* @__PURE__ */ new Set();
17778
+ for (const scope of routableAuthoring.reportingScopes ?? []) {
17779
+ for (const edge of scope.usageEdges) {
17780
+ const key = measurementV2UsageEdgeKey(edge);
17781
+ if (selectedMarkets.has(scope.stableKey) && selectsEdge(edge)) selectedEdges.set(key, edge);
17782
+ else unselectedUses.add(key);
17783
+ }
17784
+ }
17785
+ const assignmentsByPair = new Map(routableAuthoring.assignments.map((assignment, index) => [
17786
+ `${assignment.targetKey}\0${assignment.queryId}`,
17787
+ { assignment, index }
17788
+ ]));
17789
+ const selectedKeysByAssignment = /* @__PURE__ */ new Map();
17790
+ for (const edge of selectedEdges.values()) {
17791
+ const found = assignmentsByPair.get(`${edge.targetKey}\0${edge.queryId}`);
17792
+ const exact = found?.assignment.executionContexts?.find((item2) => item2.executionNodeKey === edge.executionNodeKey);
17793
+ if (!found || !exact) {
17794
+ throw validationError("A selected market contains a stale execution edge. Reload the draft and review its membership.", {
17795
+ displayToOperator: true,
17796
+ marketEdge: edge
17797
+ });
17798
+ }
17799
+ const keys = selectedKeysByAssignment.get(found.index) ?? /* @__PURE__ */ new Set();
17800
+ keys.add(edge.executionNodeKey);
17801
+ selectedKeysByAssignment.set(found.index, keys);
17802
+ }
17803
+ const selectedEdgeRemaps = /* @__PURE__ */ new Map();
17804
+ const frozenKeys = frozenMeasurementDraftExecutionKeys(routableAuthoring);
17805
+ const assignments = routableAuthoring.assignments.map((assignment, assignmentIndex) => {
17806
+ const selectedKeys = selectedKeysByAssignment.get(assignmentIndex);
17807
+ if (!selectedKeys || assignment.executionContexts === void 0) return assignment;
17808
+ const rewrittenByKey = /* @__PURE__ */ new Map();
17809
+ for (const exact of assignment.executionContexts) {
17810
+ if (!exact.executionNodeKey || !selectedKeys.has(exact.executionNodeKey)) continue;
17811
+ rewrittenByKey.set(
17812
+ exact.executionNodeKey,
17813
+ normalizedExactContext(exact, assignment.queryId, request.contextOverride, frozenKeys)
17814
+ );
17815
+ }
17816
+ const contextsByIdentity = /* @__PURE__ */ new Map();
17817
+ const identityOf = (exact) => canonicalJson({
17818
+ providers: normalizedProviders2(exact.providers),
17819
+ models: normalizedModels(exact.models),
17820
+ location: exact.location
17821
+ });
17822
+ for (const exact of assignment.executionContexts) {
17823
+ const rewritten = exact.executionNodeKey ? rewrittenByKey.get(exact.executionNodeKey) : void 0;
17824
+ const changed = rewritten !== void 0 && identityOf(rewritten) !== identityOf(exact);
17825
+ const originalEdgeKey = exact.executionNodeKey ? edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey) : null;
17826
+ if (!changed || originalEdgeKey !== null && unselectedUses.has(originalEdgeKey)) {
17827
+ contextsByIdentity.set(identityOf(exact), exact);
17828
+ }
17829
+ }
17830
+ for (const exact of assignment.executionContexts) {
17831
+ if (!exact.executionNodeKey || !selectedKeys.has(exact.executionNodeKey)) continue;
17832
+ const rewritten = rewrittenByKey.get(exact.executionNodeKey);
17833
+ const identity = identityOf(rewritten);
17834
+ const kept = contextsByIdentity.get(identity) ?? rewritten;
17835
+ contextsByIdentity.set(identity, kept);
17836
+ if (!kept.executionNodeKey) continue;
17837
+ selectedEdgeRemaps.set(
17838
+ edgeKey(assignment.targetKey, assignment.queryId, exact.executionNodeKey),
17839
+ { targetKey: assignment.targetKey, queryId: assignment.queryId, executionNodeKey: kept.executionNodeKey }
17840
+ );
17841
+ }
17842
+ return { ...assignment, executionContexts: [...contextsByIdentity.values()] };
17843
+ });
17844
+ const marketStats = markets.map((scope) => {
17845
+ const matched = scope.usageEdges.filter(selectsEdge);
17846
+ const stale = (originalScopesByKey.get(scope.stableKey)?.usageEdges ?? []).filter((edge) => selectsEdge(edge) && !assignmentPairs.has(`${edge.targetKey}\0${edge.queryId}`));
17847
+ return {
17848
+ marketKey: scope.stableKey,
17849
+ label: scope.label,
17850
+ matchedEdges: matched.length + stale.length,
17851
+ changedEdges: stale.length + matched.filter((edge) => {
17852
+ const next = selectedEdgeRemaps.get(measurementV2UsageEdgeKey(edge));
17853
+ return next !== void 0 && next.executionNodeKey !== edge.executionNodeKey;
17854
+ }).length
17855
+ };
17856
+ });
17857
+ const reroutedEdges = [...selectedEdges.entries()].filter(([key, edge]) => {
17858
+ const next = selectedEdgeRemaps.get(key);
17859
+ return next !== void 0 && next.executionNodeKey !== edge.executionNodeKey;
17860
+ }).length;
17861
+ const matchedEdges = (/* @__PURE__ */ new Set([...selectedEdges.keys(), ...staleSelectedEdges.keys()])).size;
17862
+ const changedEdges = reroutedEdges + staleSelectedEdges.size;
17863
+ if (changedEdges === 0) {
17864
+ return {
17865
+ authoring: routableAuthoring,
17866
+ warnings: [],
17867
+ markets: marketStats,
17868
+ matchedEdges,
17869
+ changedEdges: 0
17870
+ };
17871
+ }
17872
+ const reportingScopes = (routableAuthoring.reportingScopes ?? []).map((scope) => {
17873
+ if (!selectedMarkets.has(scope.stableKey)) return scope;
17874
+ const seen2 = /* @__PURE__ */ new Set();
17875
+ const usageEdges = [];
17876
+ for (const edge of scope.usageEdges) {
17877
+ const next = selectsEdge(edge) ? selectedEdgeRemaps.get(measurementV2UsageEdgeKey(edge)) ?? edge : edge;
17878
+ const key = measurementV2UsageEdgeKey(next);
17879
+ if (seen2.has(key)) continue;
17880
+ seen2.add(key);
17881
+ usageEdges.push(next);
17882
+ }
17883
+ return { ...scope, usageEdges };
17884
+ });
17885
+ return {
17886
+ authoring: authoringWithAssignments(routableAuthoring, assignments, reportingScopes),
17887
+ warnings: [],
17888
+ markets: marketStats,
17889
+ matchedEdges,
17890
+ changedEdges
17891
+ };
17892
+ }
17893
+ function routeMarkets(authoring, body, context) {
17894
+ const request = parseBody2(measurementDraftRouteMarketsRequestSchema, body, "route-markets");
17895
+ return routeMarketsInAuthoring(authoring, request, context);
17398
17896
  }
17399
17897
  function removeAssignment(authoring, body) {
17400
17898
  const parsed = parseBody2(measurementDraftRemoveAssignmentRequestSchema, body, "remove-assignment");
17401
17899
  const { queryId } = parsed;
17402
17900
  const targetKeys = new Set("targetKeys" in parsed ? parsed.targetKeys : [parsed.targetKey]);
17901
+ const assignments = authoring.assignments.filter((assignment) => !(targetKeys.has(assignment.targetKey) && assignment.queryId === queryId));
17403
17902
  return {
17404
- authoring: {
17405
- ...authoring,
17406
- assignments: authoring.assignments.filter((assignment) => !(targetKeys.has(assignment.targetKey) && assignment.queryId === queryId))
17407
- },
17903
+ authoring: authoringWithAssignments(authoring, assignments),
17408
17904
  warnings: []
17409
17905
  };
17410
17906
  }
17411
17907
  function clearAssignments(authoring, body) {
17412
17908
  const { targetKey } = parseBody2(measurementDraftClearAssignmentsRequestSchema, body, "clear-assignments");
17909
+ const assignments = authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey);
17413
17910
  return {
17414
- authoring: {
17415
- ...authoring,
17416
- assignments: authoring.assignments.filter((assignment) => assignment.targetKey !== targetKey)
17417
- },
17911
+ authoring: authoringWithAssignments(authoring, assignments),
17418
17912
  warnings: []
17419
17913
  };
17420
17914
  }
@@ -17532,6 +18026,8 @@ function applyDraftAction(action, authoring, body, context) {
17532
18026
  return replaceAssignments(authoring, body, context);
17533
18027
  case "apply-paired-assignments":
17534
18028
  return applyPairedAssignments(authoring, body, context);
18029
+ case "route-markets":
18030
+ return routeMarkets(authoring, body, context);
17535
18031
  case "remove-assignment":
17536
18032
  return removeAssignment(authoring, body);
17537
18033
  case "clear-assignments":
@@ -18271,6 +18767,18 @@ var MEASUREMENT_GROUP_MEMBERSHIP_BODY_LIMIT = MEASUREMENT_GROUP_MEMBERSHIP_CSV_M
18271
18767
  function authoringIdentity(authoring) {
18272
18768
  return canonicalJson(authoring);
18273
18769
  }
18770
+ function draftExecutionProviders(authoring) {
18771
+ return [
18772
+ ...authoring.defaultContext.providers,
18773
+ ...authoring.assignments.flatMap((assignment) => [
18774
+ ...assignment.contextOverride?.providers ?? [],
18775
+ ...assignment.executionContexts?.flatMap((context) => context.providers) ?? []
18776
+ ])
18777
+ ];
18778
+ }
18779
+ function storedPlanExecutionProviders(plan) {
18780
+ return plan.schemaVersion === 2 ? plan.executionNodes.flatMap((node) => node.context.providers) : [];
18781
+ }
18274
18782
  function trackedQueriesFor(db, projectId) {
18275
18783
  return db.select({ id: queries.id, query: queries.query }).from(queries).where(eq34(queries.projectId, projectId)).all();
18276
18784
  }
@@ -18286,7 +18794,8 @@ function compileContextFor(db, project) {
18286
18794
  function actionContextFor(db, project) {
18287
18795
  return {
18288
18796
  brandNames: effectiveBrandNames(project),
18289
- queriesById: new Map(trackedQueriesFor(db, project.id).map((query) => [query.id, query.query]))
18797
+ queriesById: new Map(trackedQueriesFor(db, project.id).map((query) => [query.id, query.query])),
18798
+ locationsByLabel: new Map(project.locations.map((location) => [location.label, location]))
18290
18799
  };
18291
18800
  }
18292
18801
  function segmentDescriptorsFor(db, projectId) {
@@ -18826,6 +19335,7 @@ async function measurementDraftRoutes(app, opts = {}) {
18826
19335
  assertDraftEtag(row, ifMatch);
18827
19336
  const before = parseStoredAuthoring(row.authoringJson);
18828
19337
  const result = applyDraftAction(action, before, request.body, actionContextFor(app.db, gate.project));
19338
+ assertOpenRouterRouteScope(request, draftExecutionProviders(result.authoring), [...gate.project.providers, ...draftExecutionProviders(before)]);
18829
19339
  const changed = authoringIdentity(result.authoring) !== authoringIdentity(before);
18830
19340
  const etagVersion = changed ? row.etagVersion + 1 : row.etagVersion;
18831
19341
  const response = mutationResponse(etagVersion, changed, result.warnings, result.authoring);
@@ -18903,6 +19413,40 @@ async function measurementDraftRoutes(app, opts = {}) {
18903
19413
  execution: assignmentExecutionImpact(current.plan, candidate.plan)
18904
19414
  };
18905
19415
  });
19416
+ app.post("/projects/:name/measurement-plan/draft/actions/preview-route-markets", {
19417
+ config: {
19418
+ readSemantic: true,
19419
+ rateLimit: { max: 30, timeWindow: "1 minute" }
19420
+ }
19421
+ }, async (request, reply) => {
19422
+ requireScope(request, MEASUREMENT_PLAN_WRITE_SCOPE);
19423
+ const project = resolveProject(app.db, request.params.name);
19424
+ const parsed = measurementDraftRouteMarketsRequestSchema.safeParse(request.body);
19425
+ if (!parsed.success) throw validationError('Invalid "preview-route-markets" payload', { issues: parsed.error.issues });
19426
+ const row = requireDraft(project);
19427
+ const before = parseStoredAuthoring(row.authoringJson);
19428
+ const result = routeMarketsInAuthoring(before, parsed.data, actionContextFor(app.db, project));
19429
+ assertMeasurementDraftAuthoringLimits(before, result.authoring);
19430
+ const context = compileContextFor(app.db, project);
19431
+ const current = compileMeasurementDraftAssignmentExecution(authoringForCompile(before, project, opts), context);
19432
+ const candidate = compileMeasurementDraftAssignmentExecution(authoringForCompile(result.authoring, project, opts), context);
19433
+ if (!current.ok || !candidate.ok) {
19434
+ throw validationError("The selected market routing has invalid question or provider settings. Review it and try again.", {
19435
+ displayToOperator: true,
19436
+ currentChecks: current.checks,
19437
+ candidateChecks: candidate.checks
19438
+ });
19439
+ }
19440
+ const draftEtag = measurementDraftEtag(row.etagVersion);
19441
+ reply.header("etag", draftEtag);
19442
+ return {
19443
+ draftEtag,
19444
+ markets: result.markets,
19445
+ matchedEdges: result.matchedEdges,
19446
+ changedEdges: result.changedEdges,
19447
+ execution: assignmentExecutionImpact(current.plan, candidate.plan)
19448
+ };
19449
+ });
18906
19450
  app.post("/projects/:name/measurement-plan/draft/actions/preview-group-membership", {
18907
19451
  bodyLimit: MEASUREMENT_GROUP_MEMBERSHIP_BODY_LIMIT,
18908
19452
  config: {
@@ -19084,6 +19628,12 @@ async function measurementDraftRoutes(app, opts = {}) {
19084
19628
  if (!compiled.ok) {
19085
19629
  throw validationError("The measurement draft does not compile.", { checks: compiled.checks });
19086
19630
  }
19631
+ const activeProviders = active ? storedPlanExecutionProviders(parseStoredMeasurementPlanAnyVersion(active.canonicalJson)) : [];
19632
+ assertOpenRouterRouteScope(
19633
+ request,
19634
+ compiled.plan.executionNodes.flatMap((node) => node.context.providers),
19635
+ [...gate.project.providers, ...activeProviders]
19636
+ );
19087
19637
  if (compiled.plan.compiledChecksum !== parsed.data.expectedCompiledChecksum) {
19088
19638
  throw measurementCompiledChecksumConflict(parsed.data.expectedCompiledChecksum, compiled.plan.compiledChecksum);
19089
19639
  }
@@ -23873,7 +24423,7 @@ function trackedRows(db, state, queryRows2, plan, opts) {
23873
24423
  const node = nodes.get(assignment.executionNodeKey);
23874
24424
  if (!node) continue;
23875
24425
  const existing = assignments.get(assignment.targetKey);
23876
- const edgeKey2 = measurementV2UsageEdgeKey({
24426
+ const edgeKey3 = measurementV2UsageEdgeKey({
23877
24427
  executionNodeKey: assignment.executionNodeKey,
23878
24428
  targetKey: assignment.targetKey,
23879
24429
  queryId
@@ -23881,12 +24431,12 @@ function trackedRows(db, state, queryRows2, plan, opts) {
23881
24431
  const source = assignment.classificationSource ?? "frozen";
23882
24432
  if (existing) {
23883
24433
  existing.contexts.push(node.context);
23884
- existing.marketKeys.push(...marketsByEdge.get(edgeKey2) ?? []);
24434
+ existing.marketKeys.push(...marketsByEdge.get(edgeKey3) ?? []);
23885
24435
  } else {
23886
24436
  assignments.set(assignment.targetKey, {
23887
24437
  targetKey: assignment.targetKey,
23888
24438
  groupKeys: [...groupsByTarget.get(assignment.targetKey) ?? []].sort(compareText),
23889
- marketKeys: [...marketsByEdge.get(edgeKey2) ?? []],
24439
+ marketKeys: [...marketsByEdge.get(edgeKey3) ?? []],
23890
24440
  queryClass: assignment.queryClass,
23891
24441
  classificationSource: source,
23892
24442
  contexts: [node.context]
@@ -24212,8 +24762,8 @@ function addMarketEdge(plan, marketKey, edge) {
24212
24762
  const index = scopes.findIndex((scope) => scope.stableKey === marketKey);
24213
24763
  if (index === -1) throw validationError(`Selected market "${marketKey}" is not in the active plan.`);
24214
24764
  const existing = scopes[index];
24215
- const edgeKey2 = measurementV2UsageEdgeKey(edge);
24216
- if (existing.usageEdges.some((candidate) => measurementV2UsageEdgeKey(candidate) === edgeKey2)) return plan;
24765
+ const edgeKey3 = measurementV2UsageEdgeKey(edge);
24766
+ if (existing.usageEdges.some((candidate) => measurementV2UsageEdgeKey(candidate) === edgeKey3)) return plan;
24217
24767
  scopes[index] = { ...existing, usageEdges: [...existing.usageEdges, edge] };
24218
24768
  plan.reportingScopes = scopes;
24219
24769
  return plan;
@@ -24221,7 +24771,7 @@ function addMarketEdge(plan, marketKey, edge) {
24221
24771
  function assignmentKey(targetKey, queryId, executionNodeKey) {
24222
24772
  return `${targetKey}\0${queryId}\0${executionNodeKey}`;
24223
24773
  }
24224
- function edgeKey(edge) {
24774
+ function edgeKey2(edge) {
24225
24775
  return measurementV2UsageEdgeKey(edge);
24226
24776
  }
24227
24777
  function queryIdsByNormalized(state) {
@@ -24314,19 +24864,19 @@ function removeAdvancedAssignments(plan, queryId, targetKeys) {
24314
24864
  }
24315
24865
  function removeMarketMembership(plan, queryId, targetKeys, marketKeys) {
24316
24866
  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));
24867
+ 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
24868
  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));
24869
+ const retainedByAnotherMarket = new Set(plan.reportingScopes.filter((scope) => !marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey2));
24320
24870
  const removableEdgeKeys = new Set([...selectedEdgeKeys].filter((key) => !retainedByAnotherMarket.has(key)));
24321
24871
  const reportingScopes = plan.reportingScopes.map((scope) => !marketKeys.has(scope.stableKey) ? scope : {
24322
24872
  ...scope,
24323
- usageEdges: scope.usageEdges.filter((edge) => !selectedEdgeKeys.has(edgeKey(edge)))
24873
+ usageEdges: scope.usageEdges.filter((edge) => !selectedEdgeKeys.has(edgeKey2(edge)))
24324
24874
  });
24325
24875
  if (removableEdgeKeys.size === 0) {
24326
24876
  return { ...plan, reportingScopes };
24327
24877
  }
24328
- const usageEdges = plan.usageEdges.filter((edge) => !removableEdgeKeys.has(edgeKey(edge)));
24329
- const assignments = plan.assignments.filter((assignment) => !removableEdgeKeys.has(edgeKey({
24878
+ const usageEdges = plan.usageEdges.filter((edge) => !removableEdgeKeys.has(edgeKey2(edge)));
24879
+ const assignments = plan.assignments.filter((assignment) => !removableEdgeKeys.has(edgeKey2({
24330
24880
  executionNodeKey: assignment.executionNodeKey,
24331
24881
  targetKey: assignment.targetKey,
24332
24882
  queryId: assignment.queryId
@@ -24361,7 +24911,7 @@ function ensureAdvancedEdge(plan, state, target, queryId, queryText, queryClass,
24361
24911
  executionNodeKey: compiled.edge.executionNodeKey
24362
24912
  });
24363
24913
  }
24364
- if (!plan.usageEdges.some((edge) => edgeKey(edge) === edgeKey(compiled.edge))) {
24914
+ if (!plan.usageEdges.some((edge) => edgeKey2(edge) === edgeKey2(compiled.edge))) {
24365
24915
  plan.usageEdges.push(compiled.edge);
24366
24916
  }
24367
24917
  return compiled.edge;
@@ -24372,7 +24922,7 @@ function applyOperatorClass(plan, queryId, targetKey, queryClass, executionNodeK
24372
24922
  if (assignment.queryId !== queryId || assignment.targetKey !== targetKey) continue;
24373
24923
  if (executionNodeKeys && !executionNodeKeys.has(assignment.executionNodeKey)) continue;
24374
24924
  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)))) {
24925
+ if (marketKeys?.size && (plan.reportingScopes ?? []).some((scope) => !marketKeys.has(scope.stableKey) && scope.usageEdges.some((edge) => edgeKey2(edge) === edgeKey2(assignment)))) {
24376
24926
  throw validationError("This assignment is shared with another market. Change its classification from the Property or Whole site scope.");
24377
24927
  }
24378
24928
  assignment.queryClass = queryClass;
@@ -24423,21 +24973,21 @@ function candidateDiff(state, nextRows, plan, reusedQueryIds, mutatedQueryIds, s
24423
24973
  const unchangedIds = [...afterIds].filter((id) => !addedIds.includes(id) && !reusedIds.includes(id) && !removedIds.has(id));
24424
24974
  const removedAssignments = /* @__PURE__ */ new Map();
24425
24975
  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))]));
24976
+ const remainingEdges = new Set(plan.usageEdges.map(edgeKey2));
24977
+ const remainingScopes = new Map((plan.reportingScopes ?? []).map((scope) => [scope.stableKey, new Set(scope.usageEdges.map(edgeKey2))]));
24428
24978
  const recordRemoved = (edge) => {
24429
24979
  if (!scopedRemovalQueryIds.has(edge.queryId)) return;
24430
24980
  const keys = removedAssignments.get(edge.queryId) ?? /* @__PURE__ */ new Set();
24431
- keys.add(edgeKey(edge));
24981
+ keys.add(edgeKey2(edge));
24432
24982
  removedAssignments.set(edge.queryId, keys);
24433
24983
  };
24434
24984
  for (const edge of state.active.plan.usageEdges) {
24435
- if (!remainingEdges.has(edgeKey(edge))) recordRemoved(edge);
24985
+ if (!remainingEdges.has(edgeKey2(edge))) recordRemoved(edge);
24436
24986
  }
24437
24987
  for (const scope of state.active.plan.reportingScopes ?? []) {
24438
24988
  const remaining = remainingScopes.get(scope.stableKey);
24439
24989
  for (const edge of scope.usageEdges) {
24440
- if (!remaining?.has(edgeKey(edge))) recordRemoved(edge);
24990
+ if (!remaining?.has(edgeKey2(edge))) recordRemoved(edge);
24441
24991
  }
24442
24992
  }
24443
24993
  }
@@ -24630,8 +25180,8 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24630
25180
  const audience = edit.audience === void 0 ? null : resolveAudience(requireAdvanced(state).plan, edit.audience);
24631
25181
  const targetKeys = audience ? new Set(audience.targetKeys) : null;
24632
25182
  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))));
25183
+ const marketEdges = marketKeys.size === 0 ? null : new Set((plan.reportingScopes ?? []).filter((scope) => marketKeys.has(scope.stableKey)).flatMap((scope) => scope.usageEdges).map(edgeKey2));
25184
+ const selectedEdges = plan.usageEdges.filter((edge) => edge.queryId === edit.queryId && (!targetKeys || targetKeys.has(edge.targetKey)) && (!marketEdges || marketEdges.has(edgeKey2(edge))));
24635
25185
  if (audience && selectedEdges.length === 0) throw validationError("This query has no assignments in the selected scope.");
24636
25186
  if (edit.queryClass !== void 0 && selectedEdges.length === 0) throw validationError("This query has no assignments to classify.");
24637
25187
  if (!textChanged && edit.queryClass === void 0) return plan;
@@ -24645,7 +25195,7 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24645
25195
  const proposed = edit.queryClass === null ? proposeQueryClassForTarget(textChanged ? text : oldText, effectiveBrandNames(state.project), target) : edit.queryClass ?? assignment.queryClass;
24646
25196
  if (proposed === "unclassified") throw validationError("The server could not classify this portfolio query.");
24647
25197
  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)));
25198
+ const scopes = (plan.reportingScopes ?? []).filter((scope) => scope.usageEdges.some((member) => edgeKey2(member) === edgeKey2(edge)));
24649
25199
  return { edge, assignment, node, target, queryClass: proposed, classificationSource, scopes };
24650
25200
  });
24651
25201
  if (!textChanged) {
@@ -24683,7 +25233,7 @@ function applyAdvancedEdit(state, plan, rows, edit, capturedAt, reusedQueryIds,
24683
25233
  const createdAssignment = plan.assignments.find((candidate) => assignmentKey(candidate.targetKey, candidate.queryId, candidate.executionNodeKey) === assignmentKey(edge.targetKey, edge.queryId, edge.executionNodeKey));
24684
25234
  if (record2.classificationSource === void 0) delete createdAssignment.classificationSource;
24685
25235
  }
24686
- if (!plan.usageEdges.some((candidate) => edgeKey(candidate) === edgeKey(edge))) plan.usageEdges.push(edge);
25236
+ if (!plan.usageEdges.some((candidate) => edgeKey2(candidate) === edgeKey2(edge))) plan.usageEdges.push(edge);
24687
25237
  for (const scope of record2.scopes) {
24688
25238
  if (marketKeys.size === 0 || marketKeys.has(scope.stableKey)) addMarketEdge(plan, scope.stableKey, edge);
24689
25239
  }
@@ -25423,7 +25973,7 @@ async function applyRoutes(app, opts) {
25423
25973
  ...config.spec.schedule?.providers ?? []
25424
25974
  ];
25425
25975
  if (allProviders.length) {
25426
- const invalid = allProviders.filter((p) => !validNames.includes(p));
25976
+ const invalid = allProviders.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
25427
25977
  if (invalid.length) {
25428
25978
  throw validationError(`Invalid provider(s): ${[...new Set(invalid)].join(", ")}. Must be one of: ${validNames.join(", ")}`, {
25429
25979
  invalidProviders: [...new Set(invalid)],
@@ -25483,7 +26033,7 @@ async function applyRoutes(app, opts) {
25483
26033
  const name = config.metadata.name;
25484
26034
  const managesQueries = "queries" in rawSpec || "keywords" in rawSpec;
25485
26035
  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();
26036
+ const target = app.db.select({ id: projects.id, providerModels: projects.providerModels, providers: projects.providers }).from(projects).where(eq43(projects.name, name)).get();
25487
26037
  const scopedProjectId = request.apiKey?.projectId;
25488
26038
  if (scopedProjectId) {
25489
26039
  if (!target || target.id !== scopedProjectId) {
@@ -25496,6 +26046,7 @@ async function applyRoutes(app, opts) {
25496
26046
  notificationPlan = planNotificationSet(storedNotifications, config.spec.notifications);
25497
26047
  }
25498
26048
  assertProviderModelScope(request, target?.providerModels ?? {}, providerModels, specProviders);
26049
+ assertOpenRouterRouteScope(request, [...specProviders, ...config.spec.schedule?.providers ?? []], target?.providers ?? []);
25499
26050
  const competitorPreview = planCompetitorSet(
25500
26051
  target ? readStoredCompetitors(app.db, target.id) : [],
25501
26052
  competitorWrites,
@@ -25773,7 +26324,7 @@ async function applyRoutes(app, opts) {
25773
26324
  }
25774
26325
 
25775
26326
  // ../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";
26327
+ 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
26328
  async function historyRoutes(app) {
25778
26329
  app.post("/projects/:name/results/clear", async (request) => {
25779
26330
  requireAdminSession(request);
@@ -26136,8 +26687,8 @@ function addAuditHistoryFilters(filters, query) {
26136
26687
  if (query.action) filters.push(eq44(auditLog.action, query.action));
26137
26688
  if (query.actor === "api") filters.push(or9(
26138
26689
  eq44(auditLog.actor, "api"),
26139
- like2(auditLog.actor, "api-key:%"),
26140
- like2(auditLog.actor, "user:%")
26690
+ like3(auditLog.actor, "api-key:%"),
26691
+ like3(auditLog.actor, "user:%")
26141
26692
  ));
26142
26693
  else if (query.actor) filters.push(eq44(auditLog.actor, query.actor));
26143
26694
  if (query.entityType) filters.push(eq44(auditLog.entityType, query.entityType));
@@ -27107,7 +27658,7 @@ function buildCategoryCounts(counts2) {
27107
27658
  }
27108
27659
 
27109
27660
  // ../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";
27661
+ import { eq as eq46, desc as desc19, and as and37, inArray as inArray24, like as like4 } from "drizzle-orm";
27111
27662
  var SEVERITY_RANK = { low: 0, medium: 1, high: 2, critical: 3 };
27112
27663
  function severitiesAtOrAbove(min2) {
27113
27664
  const floor = SEVERITY_RANK[min2];
@@ -27232,7 +27783,7 @@ async function intelligenceRoutes(app) {
27232
27783
  const typeFilter = request.query.type?.trim();
27233
27784
  if (typeFilter) {
27234
27785
  conditions.push(
27235
- typeFilter.endsWith("*") ? like3(insights.type, `${typeFilter.slice(0, -1)}%`) : eq46(insights.type, typeFilter)
27786
+ typeFilter.endsWith("*") ? like4(insights.type, `${typeFilter.slice(0, -1)}%`) : eq46(insights.type, typeFilter)
27236
27787
  );
27237
27788
  }
27238
27789
  const severityFilter = request.query.severity?.trim();
@@ -30319,7 +30870,7 @@ async function resultsExportRoutes(app) {
30319
30870
  }
30320
30871
 
30321
30872
  // ../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";
30873
+ 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
30874
  var TOP_INSIGHT_LIMIT = 5;
30324
30875
  var SEARCH_HIT_HARD_LIMIT = 50;
30325
30876
  var SEARCH_SNIPPET_RADIUS = 80;
@@ -30531,7 +31082,7 @@ async function compositeRoutes(app, options) {
30531
31082
  sql18`${querySnapshots.citedDomains} LIKE ${pattern} ESCAPE '\\'`,
30532
31083
  sql18`${querySnapshots.citedUrls} LIKE ${pattern} ESCAPE '\\'`,
30533
31084
  sql18`${querySnapshots.rawResponse} LIKE ${pattern} ESCAPE '\\'`,
30534
- like4(queries.query, pattern)
31085
+ like5(queries.query, pattern)
30535
31086
  )
30536
31087
  )
30537
31088
  ).orderBy(desc25(querySnapshots.createdAt)).limit(limit + 1).all());
@@ -30539,8 +31090,8 @@ async function compositeRoutes(app, options) {
30539
31090
  and47(
30540
31091
  eq55(insights.projectId, project.id),
30541
31092
  or13(
30542
- like4(insights.title, pattern),
30543
- like4(insights.query, pattern),
31093
+ like5(insights.title, pattern),
31094
+ like5(insights.query, pattern),
30544
31095
  sql18`${insights.recommendation} LIKE ${pattern} ESCAPE '\\'`,
30545
31096
  sql18`${insights.cause} LIKE ${pattern} ESCAPE '\\'`
30546
31097
  )
@@ -32082,11 +32633,13 @@ var SCHEMA_TABLE = {
32082
32633
  MeasurementDraftPreviewAssignmentsResponse: measurementDraftPreviewAssignmentsResponseSchema,
32083
32634
  MeasurementDraftPreviewGroupMembershipRequest: measurementDraftPreviewGroupMembershipRequestSchema,
32084
32635
  MeasurementDraftPreviewGroupMembershipResponse: measurementDraftPreviewGroupMembershipResponseSchema,
32636
+ MeasurementDraftPreviewMarketRoutingResponse: measurementDraftPreviewMarketRoutingResponseSchema,
32085
32637
  MeasurementDraftRebindTargetRequest: measurementDraftRebindTargetRequestSchema,
32086
32638
  MeasurementDraftRemoveAssignmentRequest: measurementDraftRemoveAssignmentRequestSchema,
32087
32639
  MeasurementDraftRemoveCompetitorRequest: measurementDraftRemoveCompetitorRequestSchema,
32088
32640
  MeasurementDraftRemoveGroupRequest: measurementDraftRemoveGroupRequestSchema,
32089
32641
  MeasurementDraftReplaceAssignmentsRequest: measurementDraftReplaceAssignmentsRequestSchema,
32642
+ MeasurementDraftRouteMarketsRequest: measurementDraftRouteMarketsRequestSchema,
32090
32643
  MeasurementDraftRenameTargetRequest: measurementDraftRenameTargetRequestSchema,
32091
32644
  MeasurementChangesResponse: measurementChangesResponseSchema,
32092
32645
  MeasurementDataQualityResponse: measurementDataQualityResponseSchema,
@@ -32463,8 +33016,13 @@ var providerNameParameter = {
32463
33016
  name: "name",
32464
33017
  in: "path",
32465
33018
  required: true,
32466
- description: "Provider name.",
32467
- schema: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] }
33019
+ description: "Registered API provider connection name. OpenRouter settings use the bare `openrouter` connection id, never a model route.",
33020
+ schema: { type: "string", minLength: 1 }
33021
+ };
33022
+ var queryGenerationProviderSchema = {
33023
+ type: "string",
33024
+ minLength: 1,
33025
+ description: "Configured sweep provider. OpenRouter models use `openrouter:publisher/model`; the bare `openrouter` connection is not executable."
32468
33026
  };
32469
33027
  var locationLabelParameter = {
32470
33028
  name: "label",
@@ -33303,6 +33861,22 @@ var routeCatalog = [
33303
33861
  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
33862
  request: "MeasurementDraftApplyPairedAssignmentsRequest"
33305
33863
  }),
33864
+ measurementDraftAction({
33865
+ action: "preview-route-markets",
33866
+ summary: "Preview exact market engine routing",
33867
+ description: "Previews provider and model changes for exact edges in the selected markets. Frozen locations and unrelated or shared market edges are preserved.",
33868
+ request: "MeasurementDraftRouteMarketsRequest",
33869
+ response: "MeasurementDraftPreviewMarketRoutingResponse",
33870
+ responseDescription: "Matched market edges and execution impact returned.",
33871
+ readOnly: true,
33872
+ rateLimited: true
33873
+ }),
33874
+ measurementDraftAction({
33875
+ action: "route-markets",
33876
+ summary: "Route selected market edges through an engine",
33877
+ 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.",
33878
+ request: "MeasurementDraftRouteMarketsRequest"
33879
+ }),
33306
33880
  measurementDraftAction({
33307
33881
  action: "remove-assignment",
33308
33882
  summary: "Remove one query assignment from draft Targets",
@@ -34243,7 +34817,7 @@ var routeCatalog = [
34243
34817
  type: "object",
34244
34818
  required: ["provider"],
34245
34819
  properties: {
34246
- provider: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] },
34820
+ provider: queryGenerationProviderSchema,
34247
34821
  count: integerSchema
34248
34822
  }
34249
34823
  }
@@ -34352,7 +34926,7 @@ var routeCatalog = [
34352
34926
  type: "object",
34353
34927
  required: ["provider"],
34354
34928
  properties: {
34355
- provider: { type: "string", enum: ["gemini", "openai", "claude", "perplexity", "muse", "local"] },
34929
+ provider: queryGenerationProviderSchema,
34356
34930
  count: integerSchema
34357
34931
  }
34358
34932
  }
@@ -39983,7 +40557,7 @@ var canonryLocalRouteCatalog = [
39983
40557
  method: "get",
39984
40558
  path: "/api/v1/projects/{name}/agent/transcript",
39985
40559
  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.",
40560
+ 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
40561
  tags: ["agent"],
39988
40562
  parameters: [nameParameter],
39989
40563
  responses: {
@@ -40437,6 +41011,7 @@ async function snapshotRoutes(app, opts) {
40437
41011
  queries: resolveSnapshotRequestQueries(parsed.data)
40438
41012
  };
40439
41013
  delete input.phrases;
41014
+ assertOpenRouterRouteScope(request, input.providers ?? [], []);
40440
41015
  try {
40441
41016
  return await opts.onSnapshotRequested(input);
40442
41017
  } catch (err) {
@@ -40631,7 +41206,7 @@ async function scheduleRoutes(app, opts) {
40631
41206
  }
40632
41207
  const validNames = opts.validProviderNames ?? [];
40633
41208
  if (validNames.length && providers?.length) {
40634
- const invalid = providers.filter((p) => !validNames.includes(p));
41209
+ const invalid = providers.filter((p) => !isSweepProvider(p) || !isProviderAvailable(p, validNames));
40635
41210
  if (invalid.length) {
40636
41211
  throw validationError(`Invalid provider(s): ${invalid.join(", ")}. Must be one of: ${validNames.join(", ")}`, {
40637
41212
  invalidProviders: invalid,
@@ -40639,6 +41214,7 @@ async function scheduleRoutes(app, opts) {
40639
41214
  });
40640
41215
  }
40641
41216
  }
41217
+ assertOpenRouterRouteScope(request, providers ?? [], project.providers);
40642
41218
  if (!isValidTimezone(timezone)) {
40643
41219
  throw validationError(`Invalid timezone: ${timezone}`);
40644
41220
  }
@@ -64810,7 +65386,7 @@ var agentProvidersConfiguredCheck = {
64810
65386
  category: CheckCategories.providers,
64811
65387
  scope: CheckScopes.global,
64812
65388
  title: "Agent provider keys",
64813
- run: (ctx) => {
65389
+ run: async (ctx) => {
64814
65390
  if (ctx.callerIsInstanceAdministrator === false) {
64815
65391
  return {
64816
65392
  status: CheckStatuses.skipped,
@@ -64838,7 +65414,7 @@ var agentProvidersConfiguredCheck = {
64838
65414
  keySource: entry.keySource
64839
65415
  }))
64840
65416
  };
64841
- const pin = ctx.getAgentPin?.() ?? null;
65417
+ const pin = await ctx.getAgentPin?.() ?? null;
64842
65418
  if (pin && !pin.configured) {
64843
65419
  return {
64844
65420
  status: CheckStatuses.warn,
@@ -64862,7 +65438,7 @@ var agentProvidersConfiguredCheck = {
64862
65438
  status: CheckStatuses.warn,
64863
65439
  code: "agent-providers.none-configured",
64864
65440
  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).",
65441
+ 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
65442
  details
64867
65443
  };
64868
65444
  }
@@ -66769,7 +67345,8 @@ function parseCompetitorMap(raw) {
66769
67345
  return raw.map((entry) => ({
66770
67346
  domain: entry.domain,
66771
67347
  hits: entry.hits,
66772
- competitorType: entry.competitorType ?? DiscoveryCompetitorTypes.unknown
67348
+ competitorType: entry.competitorType ?? DiscoveryCompetitorTypes.unknown,
67349
+ ...entry.evaluator ? { evaluator: entry.evaluator } : {}
66773
67350
  }));
66774
67351
  }
66775
67352
  function groupCompetitorMap(competitorMap, probes, preferred) {
@@ -66877,11 +67454,12 @@ function buildCompetitorMap(probes, project, classification = {}) {
66877
67454
  })).sort((a, b) => b.hits - a.hits || a.domain.localeCompare(b.domain));
66878
67455
  }
66879
67456
  async function classifyCompetitorDomains(deps, project, icpDescription, domains) {
66880
- if (domains.length === 0) return {};
67457
+ if (domains.length === 0) return { classifications: {} };
66881
67458
  try {
66882
- return await deps.classifyDomains({ project, icpDescription, domains });
67459
+ const result = await deps.classifyDomains({ project, icpDescription, domains });
67460
+ return typeof result.classifications === "object" ? result : { classifications: result };
66883
67461
  } catch {
66884
- return {};
67462
+ return { classifications: {} };
66885
67463
  }
66886
67464
  }
66887
67465
  async function pickCanonicalsWithStats(candidates, deps, dedupThreshold, primaryMask) {
@@ -67039,7 +67617,7 @@ async function executeDiscovery(opts) {
67039
67617
  opts.icpDescription,
67040
67618
  domains
67041
67619
  );
67042
- const competitorMap = buildCompetitorMap(probeRows, opts.project, classification);
67620
+ const competitorMap = buildCompetitorMap(probeRows, opts.project, classification.classifications).map((entry) => ({ ...entry, ...classification.evaluator ? { evaluator: classification.evaluator } : {} }));
67043
67621
  opts.db.update(discoverySessions).set({
67044
67622
  status: DiscoverySessionStatuses.completed,
67045
67623
  probeCount: probedCanonicals.length,
@@ -69665,12 +70243,14 @@ async function researchRoutes(app, opts) {
69665
70243
  if (!opts.onResearchRunRequested) throw missingDependency("Research execution is not available on this deployment.", { reason: "no-research-handler" });
69666
70244
  const adapters = opts.providerAdapters ?? [];
69667
70245
  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) });
70246
+ const authorizedProviders = researchProjectProviders(app, project.id, project.providers);
70247
+ const providerName = input.provider ?? authorizedProviders.find((name) => isSweepProvider(name) && isProviderAvailable(name, [...configured]) && providerAdapterForName(name, adapters)?.mode === "api") ?? adapters.find((adapter2) => adapter2.mode === "api" && isSweepProvider(adapter2.name) && configured.has(adapter2.name))?.name;
70248
+ const adapter = providerName ? providerAdapterForName(providerName, adapters) : void 0;
70249
+ if (!providerName || !adapter || adapter.mode !== "api" || !isSweepProvider(providerName) || isBrowserProvider(providerName) || !isProviderAvailable(providerName, [...configured])) throw validationError("Research requires a configured API provider.", { provider: input.provider, validProviders: authorizedProviders.filter((name) => isProviderAvailable(name, [...configured]) && providerAdapterForName(name, adapters)?.mode === "api") });
70250
+ assertOpenRouterRouteScope(request, [providerName], authorizedProviders);
69671
70251
  if (input.model) {
69672
70252
  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 });
70253
+ 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
70254
  }
69675
70255
  const active = activeMeasurementPlan(app.db, project.id);
69676
70256
  const scope = input.scope ? resolveResearchScope(active, input.scope) : null;
@@ -69678,7 +70258,7 @@ async function researchRoutes(app, opts) {
69678
70258
  if (location && !project.locations.some((item2) => sameLocation(item2, location))) throw validationError("Research location must exactly match a configured project location.", { location });
69679
70259
  const template = input.template ? resolveResearchTemplate(app, project.id, input.template, scope, location) : null;
69680
70260
  const requestedModel2 = input.model ?? null;
69681
- const resolvedModel = resolveProviderModel(providerName, requestedModel2 ?? (project.providerModels[providerName] || opts.getEffectiveProviderModels?.()[providerName] || adapter.defaultModel));
70261
+ const resolvedModel = resolveProviderModel(providerName, openRouterRouteModel(providerName) ?? requestedModel2 ?? (project.providerModels[providerName] || opts.getEffectiveProviderModels?.()[providerName] || adapter.defaultModel));
69682
70262
  adapter.modelValidationPattern.lastIndex = 0;
69683
70263
  if (!adapter.modelValidationPattern.test(resolvedModel)) throw validationError('Invalid resolved model "' + resolvedModel + '" for provider "' + providerName + '".', { provider: providerName, model: resolvedModel, hint: adapter.modelValidationHint });
69684
70264
  if (deduplicateResearchQueries(input.queries).length !== input.queries.length) throw validationError("Research queries must be unique within a batch.");
@@ -69745,6 +70325,7 @@ async function researchRoutes(app, opts) {
69745
70325
  if (!opts.onResearchRunRequested) throw missingDependency("Research execution is not available on this deployment.", { reason: "no-research-handler" });
69746
70326
  const active = activeMeasurementPlan(app.db, project.id);
69747
70327
  const prepared = input.runs.map((run) => prepareBatchRun(app, opts, project, active, run));
70328
+ assertOpenRouterRouteScope(request, prepared.map((run) => run.providerName), researchProjectProviders(app, project.id, project.providers));
69748
70329
  const now = (/* @__PURE__ */ new Date()).toISOString();
69749
70330
  const initiatedBy = researchPrincipal(request);
69750
70331
  const decision = app.db.transaction((tx) => {
@@ -69814,10 +70395,20 @@ async function researchRoutes(app, opts) {
69814
70395
  const nextCursor = rows.length > limit && last ? Buffer.from(JSON.stringify({ projectId: project.id, createdAt: last.createdAt, id: last.id })).toString("base64url") : null;
69815
70396
  const configured = new Set(opts.getConfiguredProviderNames?.() ?? opts.configuredProviderNames ?? []);
69816
70397
  const effectiveModels2 = opts.getEffectiveProviderModels?.() ?? {};
69817
- const providers = (opts.providerAdapters ?? []).filter((adapter) => adapter.mode === "api" && !isBrowserProvider(adapter.name) && configured.has(adapter.name)).map((adapter) => {
70398
+ const adapters = opts.providerAdapters ?? [];
70399
+ const savedProviders = researchProjectProviders(app, project.id, project.providers);
70400
+ const catalog = [...new Map([
70401
+ ...adapters.filter((adapter) => isSweepProvider(adapter.name)),
70402
+ ...savedProviders.filter((name) => openRouterRouteModel(name)).flatMap((name) => {
70403
+ const adapter = providerAdapterForName(name, adapters);
70404
+ return adapter ? [adapter] : [];
70405
+ })
70406
+ ].map((adapter) => [adapter.name, adapter])).values()];
70407
+ const providers = catalog.filter((adapter) => adapter.mode === "api" && !isBrowserProvider(adapter.name) && isProviderAvailable(adapter.name, [...configured])).map((adapter) => {
69818
70408
  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;
70409
+ const cached = opts.getCachedProviderModels?.(providerConnectionName(adapter.name)) ?? [];
70410
+ const candidates = cached.length ? cached : adapter.knownModels;
70411
+ const models = openRouterRouteModel(adapter.name) ? candidates.filter((model) => model.id === defaultModel) : candidates;
69821
70412
  return {
69822
70413
  name: adapter.name,
69823
70414
  displayName: adapter.displayName,
@@ -69835,6 +70426,9 @@ async function researchRoutes(app, opts) {
69835
70426
  return getDetail(app, project.id, request.params.runId);
69836
70427
  });
69837
70428
  }
70429
+ function researchProjectProviders(app, projectId, projectProviders) {
70430
+ return [.../* @__PURE__ */ new Set([...projectProviders, ...activeRevisionProviders(app.db, projectId)])];
70431
+ }
69838
70432
  var DIRECT_REQUEST_HASH_VERSION = "direct-v2:";
69839
70433
  function directResearchRequestHash(input) {
69840
70434
  const { idempotencyKey: _key, ...request } = input;
@@ -69886,8 +70480,8 @@ function prepareBatchRun(app, opts, project, active, input) {
69886
70480
  const adapters = opts.providerAdapters ?? [];
69887
70481
  const configured = new Set(opts.getConfiguredProviderNames?.() ?? opts.configuredProviderNames ?? []);
69888
70482
  const providerName = input.provider;
69889
- const adapter = adapters.find((candidate) => candidate.name === providerName);
69890
- if (!adapter || adapter.mode !== "api" || isBrowserProvider(providerName) || !configured.has(providerName)) {
70483
+ const adapter = providerName ? providerAdapterForName(providerName, adapters) : void 0;
70484
+ if (!adapter || adapter.mode !== "api" || !isSweepProvider(providerName) || isBrowserProvider(providerName) || !isProviderAvailable(providerName, [...configured])) {
69891
70485
  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
70486
  }
69893
70487
  adapter.modelValidationPattern.lastIndex = 0;