@canonry/canonry 7.108.2 → 7.110.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.
- package/assets/agent-workspace/skills/aero/SKILL.md +16 -7
- package/assets/agent-workspace/skills/aero/references/aeo-discovery.md +40 -30
- package/assets/agent-workspace/skills/aero/references/agent-operations.md +14 -7
- package/assets/agent-workspace/skills/aero/references/ai-traffic-tracking.md +12 -20
- package/assets/agent-workspace/skills/aero/references/memory-patterns.md +3 -3
- package/assets/agent-workspace/skills/aero/references/orchestration.md +22 -9
- package/assets/agent-workspace/skills/aero/references/portfolio-analysis.md +10 -8
- package/assets/agent-workspace/skills/aero/references/regression-playbook.md +11 -7
- package/assets/agent-workspace/skills/aero/references/seo-analysis.md +4 -3
- package/assets/agent-workspace/skills/aero/references/site-health.md +3 -2
- package/assets/agent-workspace/skills/aero/references/wordpress-elementor-mcp.md +48 -219
- package/assets/agent-workspace/skills/aero/soul.md +1 -1
- package/assets/agent-workspace/skills/canonry/SKILL.md +14 -7
- package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +18 -25
- package/assets/agent-workspace/skills/canonry/references/ai-traffic-tracking.md +12 -20
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +70 -27
- package/assets/agent-workspace/skills/canonry/references/google-business-profile.md +18 -24
- package/assets/agent-workspace/skills/canonry/references/google-marketing.md +10 -10
- package/assets/agent-workspace/skills/canonry/references/indexing.md +25 -27
- package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +8 -15
- package/assets/agent-workspace/skills/canonry/references/wordpress-integration.md +6 -2
- package/assets/assets/{AccessControls-B6bkOAge.js → AccessControls-DmKPF5t5.js} +2 -2
- package/assets/assets/{AgentSetupPage-H8VoauIK.js → AgentSetupPage-BvoJ7cu0.js} +1 -1
- package/assets/assets/{AuditHistoryPanel-Cmm537Mw.js → AuditHistoryPanel-GHjaPPXk.js} +1 -1
- package/assets/assets/{BacklinksPage-Dg6IJr83.js → BacklinksPage-Ca3l7bel.js} +1 -1
- package/assets/assets/{ChartPrimitives-C1meaNiX.js → ChartPrimitives-CJLgYfSw.js} +1 -1
- package/assets/assets/{HistoryPage-DMmZ0fSd.js → HistoryPage-HqdlYIsd.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-x4S_SV30.js → MeasurementPropertyPage-D71Ki-q4.js} +1 -1
- package/assets/assets/ProjectPage-wGYGNnLC.js +15 -0
- package/assets/assets/{RunsPage-DG43ZJib.js → RunsPage-CeXFTDg4.js} +1 -1
- package/assets/assets/{ServerTrafficSection-B-QGjFGD.js → ServerTrafficSection-BZVlcCO2.js} +1 -1
- package/assets/assets/{SettingsPage-CJlAiPn3.js → SettingsPage-MiW1TGtF.js} +1 -1
- package/assets/assets/ToneBadge-BXxSLZUc.js +60 -0
- package/assets/assets/{TrafficPage-Dlp26Fvy.js → TrafficPage-1ZXZ2BLa.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-D-x32dzk.js → TrafficSourceDetailPage-BJPiUWus.js} +1 -1
- package/assets/assets/{account-context-C66suepK.js → account-context-DHUo7ntg.js} +1 -1
- package/assets/assets/{agent-trust-copy-BKQRIoVJ.js → agent-trust-copy-x8ECjEJu.js} +1 -1
- package/assets/assets/{card-iPmHn3JZ.js → card-bE38V9NH.js} +1 -1
- package/assets/assets/{index-C05Wdzzv.js → index-Ce3zYiH3.js} +15 -15
- package/assets/assets/{query-client-D_jULVYr.js → query-client-CBtgvGgy.js} +1 -1
- package/assets/assets/{react-query-ih29UP0I.js → react-query-CsgUn_pT.js} +1 -1
- package/assets/assets/{react-sigma_core.esm.min-sHrGO6oc.js → react-sigma_core.esm.min-DeLn6mIk.js} +1 -1
- package/assets/assets/{server-traffic-BScF0-_t.js → server-traffic-Dwwd7cw6.js} +1 -1
- package/assets/assets/{service-DYJdF5mP.js → service-Bq_5mBI4.js} +1 -1
- package/assets/index.html +8 -8
- package/dist/{ads-IJHKPMDL.js → ads-VITOHLIW.js} +3 -3
- package/dist/{agent-X5SDBTII.js → agent-N57IKFTH.js} +10 -10
- package/dist/{agent-ask-UPROPFVK.js → agent-ask-VPK4ED7D.js} +3 -3
- package/dist/{agent-conversations-A7W74X6Q.js → agent-conversations-DPEGQ5NJ.js} +3 -3
- package/dist/{agent-journeys-WOLFWP3G.js → agent-journeys-7AS543HY.js} +3 -3
- package/dist/{agent-memory-TH6ORG63.js → agent-memory-OKKNU2MA.js} +3 -3
- package/dist/{agent-providers-FKVRHV4J.js → agent-providers-JZGGMH5H.js} +3 -3
- package/dist/{agent-transcript-UFEBYD4L.js → agent-transcript-AICHEB4B.js} +3 -3
- package/dist/{analytics-XNFXAKRP.js → analytics-FXNYSIAY.js} +3 -3
- package/dist/{apply-O46BRKQG.js → apply-DYYB2I2S.js} +3 -3
- package/dist/{backfill-IUCWBDEI.js → backfill-CXKKDOST.js} +10 -10
- package/dist/{backlinks-PB2Y3APJ.js → backlinks-442C4H4M.js} +3 -3
- package/dist/{bing-YOUZDEA2.js → bing-HRSXPL7O.js} +3 -3
- package/dist/{bootstrap-E4EI2W54.js → bootstrap-U5UVQDHJ.js} +10 -10
- package/dist/{cdp-72553DTZ.js → cdp-JSOEQZJJ.js} +7 -7
- package/dist/{chunk-46QQ3MQC.js → chunk-35H5E662.js} +1 -2
- package/dist/{chunk-7K3EFBNK.js → chunk-3AVO5OWE.js} +26 -1
- package/dist/{chunk-WTNB7B2K.js → chunk-3WAGCCAO.js} +1 -1
- package/dist/{chunk-WJUF7P7N.js → chunk-4CTVYOBQ.js} +1 -1
- package/dist/{chunk-K6HCS36A.js → chunk-5RMDU4MM.js} +6 -6
- package/dist/{chunk-PYLSLW6L.js → chunk-5SN2O7QH.js} +1 -1
- package/dist/{chunk-VGJCR6MC.js → chunk-66OTF2QQ.js} +587 -354
- package/dist/{chunk-JH6E6IV4.js → chunk-7GU4F2QO.js} +2 -2
- package/dist/{chunk-IZMQNTWQ.js → chunk-A334LHJ7.js} +3 -3
- package/dist/{chunk-V342HTLC.js → chunk-DMCJJ5FT.js} +3 -3
- package/dist/{chunk-QJGQOAUK.js → chunk-ES7XSOBY.js} +1 -1
- package/dist/{chunk-5KH7Y233.js → chunk-EU6JYD3C.js} +5 -5
- package/dist/{chunk-OEV6HQ3X.js → chunk-FEIDW5BU.js} +70 -2
- package/dist/{chunk-4FEKXZYP.js → chunk-FRKHFU6D.js} +5 -5
- package/dist/{chunk-J7RHAKTA.js → chunk-HGKB6J7I.js} +4 -4
- package/dist/{chunk-7XDDCPZV.js → chunk-HH4XK3FX.js} +1 -1
- package/dist/{chunk-LU3TWJX7.js → chunk-HX4KJWQO.js} +3 -3
- package/dist/{chunk-FU324DV3.js → chunk-JJ7RXQ2W.js} +2 -2
- package/dist/{chunk-AVBTCCAY.js → chunk-JXFFKZOI.js} +2 -2
- package/dist/{chunk-QNSTLSVL.js → chunk-M7R7GSO5.js} +2 -2
- package/dist/{chunk-6OBPZ6WK.js → chunk-ME74SV2T.js} +1 -1
- package/dist/{chunk-MA5VHGWC.js → chunk-OJYY6W5S.js} +1438 -1206
- package/dist/{chunk-CLWAZBJY.js → chunk-Q3IXAH34.js} +1 -1
- package/dist/{chunk-CORHE557.js → chunk-QIGC5JGR.js} +4 -4
- package/dist/{chunk-HAOLFBSD.js → chunk-QXBHZSOW.js} +3 -3
- package/dist/{chunk-6Y3I2QFU.js → chunk-RHY7GL5R.js} +2 -2
- package/dist/{chunk-2S25YWMO.js → chunk-S2I5FPQC.js} +1 -1
- package/dist/{chunk-EFY5C7ZJ.js → chunk-TV6BFBRI.js} +4 -4
- package/dist/{chunk-PKD22D4H.js → chunk-UC2LPOW4.js} +1 -1
- package/dist/chunk-UX3HJV2V.js +12 -0
- package/dist/{chunk-SHCFV7PL.js → chunk-VDAC54IW.js} +7 -7
- package/dist/{chunk-HOKR2Q26.js → chunk-VYPDVWRG.js} +1 -1
- package/dist/{chunk-BPKV6YLN.js → chunk-XS3S3UQE.js} +7 -7
- package/dist/{chunk-HABH5YAF.js → chunk-YKEXZBB4.js} +1 -1
- package/dist/{chunk-3XYCTAL7.js → chunk-ZABO7FFF.js} +13 -15
- package/dist/{chunk-E2ACURKW.js → chunk-ZVKWDSKW.js} +2 -2
- package/dist/{chunk-L6G22DGG.js → chunk-ZVLZ7YFW.js} +366 -366
- package/dist/{citations-A3N7E44V.js → citations-A6QP2QOT.js} +4 -4
- package/dist/{cli-catalog-2IKVWAJ7.js → cli-catalog-OJT3WVRE.js} +3 -3
- package/dist/{cli-commands-SEYCDGTO.js → cli-commands-KQQPOXIP.js} +7 -7
- package/dist/cli.js +13 -13
- package/dist/{competitor-CZV7O3YY.js → competitor-AY5SURO6.js} +3 -3
- package/dist/{content-7Y6QZH2G.js → content-UZJF7XQV.js} +3 -3
- package/dist/{dashboard-OOCOW7VZ.js → dashboard-IXNMMT5P.js} +6 -6
- package/dist/{demo-72QLTRMQ.js → demo-Y7DDERG7.js} +1 -1
- package/dist/{demo-server-NFJOZ6ZF.js → demo-server-PNPTTPGQ.js} +13 -12
- package/dist/{discover-LUCA6O5X.js → discover-45FOFNGO.js} +4 -4
- package/dist/{discover-eval-U2XY45WE.js → discover-eval-CJ5G32A6.js} +3 -3
- package/dist/{doctor-4O3ZZJAG.js → doctor-2R4J6QC7.js} +3 -3
- package/dist/{evidence-COM64MWY.js → evidence-HDUJMIIR.js} +3 -3
- package/dist/{export-cmd-HEQ5TZER.js → export-cmd-3AXP4C3S.js} +3 -3
- package/dist/{ga-F5KCSFBL.js → ga-RYK2FEEH.js} +3 -3
- package/dist/{gbp-GNHJKLUF.js → gbp-TAA3TNDA.js} +16 -5
- package/dist/{google-SAW6YWIC.js → google-62PQ4SMC.js} +4 -4
- package/dist/{google-marketing-SIZWYSL2.js → google-marketing-UWGFDUUZ.js} +1 -1
- package/dist/{health-cmd-5IZFIQK2.js → health-cmd-ZDHMZLYQ.js} +4 -4
- package/dist/{history-O3VAYWT6.js → history-RVBQUMCX.js} +3 -3
- package/dist/index.d.ts +87 -3
- package/dist/index.js +26 -25
- package/dist/{init-KAEFZHQB.js → init-XP3J3HPB.js} +12 -12
- package/dist/{insights-UFSQCY2N.js → insights-I2YS7U6L.js} +3 -3
- package/dist/intelligence-service-OHEFN77N.js +16 -0
- package/dist/{journeys-XUPV4POH.js → journeys-BELWHYCZ.js} +3 -3
- package/dist/{keys-MWIC2RAM.js → keys-XDILBZFM.js} +3 -3
- package/dist/{keyword-BI6JIKFU.js → keyword-BQ4ECK2Z.js} +3 -3
- package/dist/{logs-DJAPNQRC.js → logs-UAZUYRCJ.js} +3 -3
- package/dist/{mcp-K7KJOU2D.js → mcp-4262JRAS.js} +4 -4
- package/dist/mcp.js +10 -9
- package/dist/{measurement-plan-IZ3ONXKO.js → measurement-plan-D4DFV7XU.js} +5 -5
- package/dist/{notify-23XROT44.js → notify-TIAGVEYL.js} +12 -22
- package/dist/{organic-evidence-MY3YS2FV.js → organic-evidence-2TUODD26.js} +3 -3
- package/dist/{overview-XF3HRTRP.js → overview-WP2DO3GW.js} +5 -5
- package/dist/{project-BTX7G7RS.js → project-OOUUH5QM.js} +3 -3
- package/dist/{project-setup-OEF4VHVO.js → project-setup-HBKPIBNL.js} +3 -3
- package/dist/{query-67PA6WZ2.js → query-M7XT5UL3.js} +3 -3
- package/dist/{research-AFDDYAZS.js → research-O36LMQ6N.js} +3 -3
- package/dist/{results-export-6BI6P2MI.js → results-export-EQWWL2FH.js} +3 -3
- package/dist/{run-24TJZZXB.js → run-2I7SGZWI.js} +5 -5
- package/dist/{schedule-J2LIJ52P.js → schedule-UIPFPM64.js} +3 -3
- package/dist/{search-6RAWS2IO.js → search-L3BSPUWL.js} +3 -3
- package/dist/{serve-IURZ4D4U.js → serve-CKQIXMZH.js} +27 -26
- package/dist/{session-ZZG6G4D7.js → session-JMUEO4JX.js} +14 -13
- package/dist/{settings-UV6TFSYN.js → settings-CCYLUD6M.js} +3 -3
- package/dist/{sitemaps-YVX6NKUG.js → sitemaps-QKEA3DLO.js} +3 -3
- package/dist/{skills-6GYQKVDM.js → skills-6QCTDYJX.js} +2 -2
- package/dist/{snapshot-N6RFEDB5.js → snapshot-SPVUDPYM.js} +3 -3
- package/dist/{src-U2E6JQJF.js → src-TV6FYYJC.js} +4 -2
- package/dist/{status-HZHN6UNX.js → status-FU5K5ZIP.js} +5 -5
- package/dist/{technical-aeo-ZQD4Q7DP.js → technical-aeo-A2UNMVHB.js} +3 -3
- package/dist/{telemetry-GQA2LXOM.js → telemetry-4UAREPKB.js} +4 -4
- package/dist/{tools-XH6DGBGV.js → tools-OLOHKI7B.js} +12 -11
- package/dist/{traffic-Y6T2OKJF.js → traffic-3TQUDBQB.js} +5 -5
- package/dist/{trends-DTHOUJUU.js → trends-IHC2MH5V.js} +3 -3
- package/dist/{users-JSG4WKPW.js → users-TYU5PIYM.js} +3 -3
- package/dist/{visibility-stats-4FW4DZSK.js → visibility-stats-BWJF57ON.js} +4 -4
- package/dist/{wordpress-AHTU5C7M.js → wordpress-T4CVB32J.js} +3 -3
- package/package.json +1 -1
- package/assets/assets/ProjectPage-DnDw0Cvk.js +0 -15
- package/assets/assets/ToneBadge-BkNG9buI.js +0 -60
- package/dist/intelligence-service-OZIEPTCK.js +0 -16
|
@@ -24,18 +24,18 @@ import {
|
|
|
24
24
|
resolveConfiguredAgentProvider,
|
|
25
25
|
resolveSessionProviderAndModel,
|
|
26
26
|
setAeroSystemPrompt
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-5RMDU4MM.js";
|
|
28
28
|
import {
|
|
29
29
|
answerServiceAdapters,
|
|
30
30
|
answerServiceDescriptors
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-5SN2O7QH.js";
|
|
32
32
|
import {
|
|
33
33
|
AeroToolProfiles,
|
|
34
34
|
AeroToolScopes,
|
|
35
35
|
buildAeroStateTools,
|
|
36
36
|
isAeroToolProfile,
|
|
37
37
|
truncateToolResult
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-QIGC5JGR.js";
|
|
39
39
|
import {
|
|
40
40
|
getGoogleAuthConfig,
|
|
41
41
|
getGoogleConnection,
|
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
removeCloudflareTrafficConnection,
|
|
55
55
|
removeCloudflareTrafficConnectionBySourceId,
|
|
56
56
|
upsertCloudflareTrafficConnection
|
|
57
|
-
} from "./chunk-
|
|
57
|
+
} from "./chunk-ES7XSOBY.js";
|
|
58
58
|
import {
|
|
59
59
|
claudeAdapter,
|
|
60
60
|
embedQueries,
|
|
@@ -66,7 +66,7 @@ import {
|
|
|
66
66
|
openrouterAdapter,
|
|
67
67
|
perplexityAdapter,
|
|
68
68
|
startTrafficReclassification
|
|
69
|
-
} from "./chunk-
|
|
69
|
+
} from "./chunk-FRKHFU6D.js";
|
|
70
70
|
import {
|
|
71
71
|
classifyUsageSurface,
|
|
72
72
|
createApiUsageTelemetry,
|
|
@@ -78,7 +78,7 @@ import {
|
|
|
78
78
|
startOutcomeTimer,
|
|
79
79
|
trackFeatureCompleted,
|
|
80
80
|
trackInstallState
|
|
81
|
-
} from "./chunk-
|
|
81
|
+
} from "./chunk-TV6BFBRI.js";
|
|
82
82
|
import {
|
|
83
83
|
isLoopbackBindHost
|
|
84
84
|
} from "./chunk-TSENU4GG.js";
|
|
@@ -86,7 +86,7 @@ import {
|
|
|
86
86
|
isApiProviderRegistrable,
|
|
87
87
|
isCdpProviderRegistrable,
|
|
88
88
|
registeredProviderNames
|
|
89
|
-
} from "./chunk-
|
|
89
|
+
} from "./chunk-4CTVYOBQ.js";
|
|
90
90
|
import {
|
|
91
91
|
checkLatestVersionForServer,
|
|
92
92
|
getOrCreateAnonymousId,
|
|
@@ -98,17 +98,17 @@ import {
|
|
|
98
98
|
recordDashboardEvent,
|
|
99
99
|
setTelemetryPreference,
|
|
100
100
|
trackEvent
|
|
101
|
-
} from "./chunk-
|
|
101
|
+
} from "./chunk-ZVKWDSKW.js";
|
|
102
102
|
import {
|
|
103
103
|
createCanonryMcpServer
|
|
104
|
-
} from "./chunk-
|
|
104
|
+
} from "./chunk-VDAC54IW.js";
|
|
105
105
|
import {
|
|
106
106
|
CANONRY_MCP_TIERS,
|
|
107
107
|
CANONRY_MCP_TOOLKIT_NAMES
|
|
108
108
|
} from "./chunk-YW6J3STO.js";
|
|
109
109
|
import {
|
|
110
110
|
ApiClient
|
|
111
|
-
} from "./chunk-
|
|
111
|
+
} from "./chunk-JJ7RXQ2W.js";
|
|
112
112
|
import {
|
|
113
113
|
AGENT_PROVIDERS,
|
|
114
114
|
PROVIDER_MODELS,
|
|
@@ -143,21 +143,21 @@ import {
|
|
|
143
143
|
saveConfigPatch,
|
|
144
144
|
sentimentInstallReadiness,
|
|
145
145
|
updateSharedProviderExecutionGate
|
|
146
|
-
} from "./chunk-
|
|
146
|
+
} from "./chunk-35H5E662.js";
|
|
147
147
|
import {
|
|
148
148
|
getBundledSkillSnapshots
|
|
149
|
-
} from "./chunk-
|
|
149
|
+
} from "./chunk-3WAGCCAO.js";
|
|
150
150
|
import {
|
|
151
151
|
computeFactorAverages,
|
|
152
152
|
deleteSiteCrawlGraphLayout,
|
|
153
153
|
persistSiteCrawlGraphLayout,
|
|
154
154
|
prepareSiteCrawlGraphLayout,
|
|
155
155
|
recordedSharePct
|
|
156
|
-
} from "./chunk-
|
|
156
|
+
} from "./chunk-JXFFKZOI.js";
|
|
157
157
|
import {
|
|
158
158
|
CanonryMcpToolNames,
|
|
159
159
|
canonryMcpTools
|
|
160
|
-
} from "./chunk-
|
|
160
|
+
} from "./chunk-ZABO7FFF.js";
|
|
161
161
|
import {
|
|
162
162
|
PACKAGE_VERSION
|
|
163
163
|
} from "./chunk-AOJU5LKX.js";
|
|
@@ -166,16 +166,16 @@ import {
|
|
|
166
166
|
} from "./chunk-HGMYEDAQ.js";
|
|
167
167
|
import {
|
|
168
168
|
IntelligenceService
|
|
169
|
-
} from "./chunk-
|
|
169
|
+
} from "./chunk-EU6JYD3C.js";
|
|
170
170
|
import {
|
|
171
171
|
computeCitedCompetitorDomains,
|
|
172
172
|
determineCitationState
|
|
173
|
-
} from "./chunk-
|
|
173
|
+
} from "./chunk-UC2LPOW4.js";
|
|
174
174
|
import {
|
|
175
175
|
addLogListener,
|
|
176
176
|
createFastifyLogger,
|
|
177
177
|
createLogger
|
|
178
|
-
} from "./chunk-
|
|
178
|
+
} from "./chunk-M7R7GSO5.js";
|
|
179
179
|
import {
|
|
180
180
|
BingApiError,
|
|
181
181
|
CC_CACHE_DIR,
|
|
@@ -292,9 +292,11 @@ import {
|
|
|
292
292
|
pruneCachedRelease,
|
|
293
293
|
queryBacklinks,
|
|
294
294
|
queueRunIfProjectIdle,
|
|
295
|
+
readAdvancedSignalTransitions,
|
|
295
296
|
readAnswerIdentity,
|
|
296
297
|
readInstalledVersion,
|
|
297
298
|
readMarketCompetitorNames,
|
|
299
|
+
readQueryClasses,
|
|
298
300
|
redactNotificationUrl,
|
|
299
301
|
refreshAccessToken,
|
|
300
302
|
refreshSnapshotMentionIdentity,
|
|
@@ -315,6 +317,7 @@ import {
|
|
|
315
317
|
sentimentClassifierInput,
|
|
316
318
|
sentimentHash,
|
|
317
319
|
serializeUserSessionCookie,
|
|
320
|
+
snapshotMentionObserver,
|
|
318
321
|
startScheduledSeoRefreshes,
|
|
319
322
|
stripIpv6Brackets,
|
|
320
323
|
syncRunClaimKey,
|
|
@@ -323,7 +326,7 @@ import {
|
|
|
323
326
|
webhookResponseReason,
|
|
324
327
|
webhookTargetRefusalReason,
|
|
325
328
|
writeAuditLog
|
|
326
|
-
} from "./chunk-
|
|
329
|
+
} from "./chunk-OJYY6W5S.js";
|
|
327
330
|
import {
|
|
328
331
|
OperationalLogStore,
|
|
329
332
|
SentimentIdempotencyConflict,
|
|
@@ -403,7 +406,9 @@ import {
|
|
|
403
406
|
runFills,
|
|
404
407
|
runs,
|
|
405
408
|
schedules,
|
|
409
|
+
sentimentAlertRuns,
|
|
406
410
|
sentimentCompletionReceipts,
|
|
411
|
+
sentimentJobs,
|
|
407
412
|
sentimentSettings,
|
|
408
413
|
seoJobs,
|
|
409
414
|
seoTasks,
|
|
@@ -423,7 +428,7 @@ import {
|
|
|
423
428
|
unrecognizedAgentEventsHourly,
|
|
424
429
|
unrecognizedAgentNotifyState,
|
|
425
430
|
usageCounters
|
|
426
|
-
} from "./chunk-
|
|
431
|
+
} from "./chunk-3AVO5OWE.js";
|
|
427
432
|
import {
|
|
428
433
|
AGENT_MEMORY_VALUE_MAX_BYTES,
|
|
429
434
|
AI_ENGINE_DOMAINS,
|
|
@@ -471,6 +476,7 @@ import {
|
|
|
471
476
|
MEASUREMENT_PLAN_V2_SCHEMA_VERSION,
|
|
472
477
|
McpTransportStatuses,
|
|
473
478
|
MemorySources,
|
|
479
|
+
MentionStates,
|
|
474
480
|
ONBOARDING_FLOW_VERSION,
|
|
475
481
|
OPERATION_ACCESS_HEADER,
|
|
476
482
|
OUTSTANDING_PROVIDER_BATCH_STATUSES,
|
|
@@ -704,7 +710,7 @@ import {
|
|
|
704
710
|
winnabilityClassLabel,
|
|
705
711
|
withRetry,
|
|
706
712
|
withSkippedProviders
|
|
707
|
-
} from "./chunk-
|
|
713
|
+
} from "./chunk-FEIDW5BU.js";
|
|
708
714
|
|
|
709
715
|
// src/google-marketing-runtime.ts
|
|
710
716
|
import crypto2 from "crypto";
|
|
@@ -3394,7 +3400,7 @@ import path6 from "path";
|
|
|
3394
3400
|
import { isIP as isIP2 } from "net";
|
|
3395
3401
|
import { fileURLToPath } from "url";
|
|
3396
3402
|
import { setImmediate as yieldToEventLoop4 } from "timers/promises";
|
|
3397
|
-
import { and as
|
|
3403
|
+
import { and as and33, eq as eq39, isNotNull as isNotNull5, isNull as isNull8, lte as lte4, max, ne as ne4, or as or4, sql as sql16 } from "drizzle-orm";
|
|
3398
3404
|
|
|
3399
3405
|
// src/seo-runtime.ts
|
|
3400
3406
|
import { eq, inArray } from "drizzle-orm";
|
|
@@ -5048,7 +5054,7 @@ var localAdapter = {
|
|
|
5048
5054
|
name: "local",
|
|
5049
5055
|
displayName: "Local",
|
|
5050
5056
|
mode: "api",
|
|
5051
|
-
// normalize.ts folds the location into the
|
|
5057
|
+
// normalize.ts folds the location into the user message.
|
|
5052
5058
|
supportsLocationContext: true,
|
|
5053
5059
|
modelRegistry: {
|
|
5054
5060
|
defaultModel: "llama3",
|
|
@@ -6458,7 +6464,7 @@ function nonBlank(value) {
|
|
|
6458
6464
|
return trimmed ? trimmed : void 0;
|
|
6459
6465
|
}
|
|
6460
6466
|
function resolveBuildCommit(env = process.env) {
|
|
6461
|
-
const embedded = true ? "
|
|
6467
|
+
const embedded = true ? "a8dddc9bf914b0c2450542fdbc6fc93dab196d80" : void 0;
|
|
6462
6468
|
return nonBlank(embedded) ?? nonBlank(env.CANONRY_COMMIT);
|
|
6463
6469
|
}
|
|
6464
6470
|
function resolveInstanceIdentity(env = process.env) {
|
|
@@ -9798,7 +9804,9 @@ async function executeGbpSync(db, runId, projectId, opts) {
|
|
|
9798
9804
|
}
|
|
9799
9805
|
const reviewNow = /* @__PURE__ */ new Date();
|
|
9800
9806
|
const insertNow = reviewNow.toISOString();
|
|
9801
|
-
db.transaction((tx) => {
|
|
9807
|
+
const written = db.transaction((tx) => {
|
|
9808
|
+
const stillSelected = tx.select({ id: gbpLocations.id }).from(gbpLocations).where(and8(eq10(gbpLocations.id, loc.id), eq10(gbpLocations.selected, true))).get();
|
|
9809
|
+
if (!stillSelected) return false;
|
|
9802
9810
|
tx.delete(gbpDailyMetrics).where(and8(eq10(gbpDailyMetrics.projectId, projectId), eq10(gbpDailyMetrics.locationName, loc.locationName))).run();
|
|
9803
9811
|
for (const row of metricRows) {
|
|
9804
9812
|
tx.insert(gbpDailyMetrics).values({
|
|
@@ -9929,7 +9937,12 @@ async function executeGbpSync(db, runId, projectId, opts) {
|
|
|
9929
9937
|
reviewsAccessReason: reviewFetch.access.reason,
|
|
9930
9938
|
reviewsCheckedAt: insertNow
|
|
9931
9939
|
}).where(eq10(gbpLocations.id, loc.id)).run();
|
|
9940
|
+
return true;
|
|
9932
9941
|
});
|
|
9942
|
+
if (!written) {
|
|
9943
|
+
log6.info("location.deselected-during-sync", { runId, location: loc.locationName });
|
|
9944
|
+
return;
|
|
9945
|
+
}
|
|
9933
9946
|
okCount++;
|
|
9934
9947
|
rowsWritten += metricRows.length + keywordRows.length + placeActionRows.length + monthlyKeywordResults.reduce((total, month) => total + month.rows.length, 0);
|
|
9935
9948
|
const access = reviewFetch.access;
|
|
@@ -15422,6 +15435,22 @@ async function deliverReviewEvent(options) {
|
|
|
15422
15435
|
|
|
15423
15436
|
// src/unrecognized-agent-alerts.ts
|
|
15424
15437
|
import { and as and21, desc as desc8, eq as eq25, gte as gte3, sql as sql10 } from "drizzle-orm";
|
|
15438
|
+
|
|
15439
|
+
// src/alert-loop.ts
|
|
15440
|
+
function startAlertLoop(dispatch, intervalMs, onError) {
|
|
15441
|
+
let running = false;
|
|
15442
|
+
const timer = setInterval(() => {
|
|
15443
|
+
if (running) return;
|
|
15444
|
+
running = true;
|
|
15445
|
+
void dispatch().catch(onError).finally(() => {
|
|
15446
|
+
running = false;
|
|
15447
|
+
});
|
|
15448
|
+
}, intervalMs);
|
|
15449
|
+
timer.unref();
|
|
15450
|
+
return () => clearInterval(timer);
|
|
15451
|
+
}
|
|
15452
|
+
|
|
15453
|
+
// src/unrecognized-agent-alerts.ts
|
|
15425
15454
|
var log22 = createLogger("UnrecognizedAgentAlerts");
|
|
15426
15455
|
var UNRECOGNIZED_AGENT_ALERT_WINDOW_MS = 7 * 864e5;
|
|
15427
15456
|
var UNRECOGNIZED_AGENT_ALERT_MIN_HITS = 3;
|
|
@@ -15481,23 +15510,71 @@ function recordUnrecognizedAgentDecisions(db, projectId, names, state, now) {
|
|
|
15481
15510
|
}
|
|
15482
15511
|
}
|
|
15483
15512
|
function startUnrecognizedAgentAlertLoop(dispatch, intervalMs = UNRECOGNIZED_AGENT_ALERT_INTERVAL_MS) {
|
|
15484
|
-
|
|
15485
|
-
|
|
15486
|
-
|
|
15487
|
-
|
|
15488
|
-
|
|
15489
|
-
|
|
15490
|
-
|
|
15491
|
-
|
|
15492
|
-
|
|
15493
|
-
|
|
15494
|
-
|
|
15495
|
-
|
|
15513
|
+
return startAlertLoop(dispatch, intervalMs, (err) => {
|
|
15514
|
+
log22.warn("unrecognized-agent-alerts.dispatch-failed", { error: describeError(err) });
|
|
15515
|
+
});
|
|
15516
|
+
}
|
|
15517
|
+
|
|
15518
|
+
// src/sentiment-alerts.ts
|
|
15519
|
+
import { and as and22, asc as asc5, eq as eq26, gte as gte4, inArray as inArray11, sql as sql11 } from "drizzle-orm";
|
|
15520
|
+
var log23 = createLogger("SentimentAlerts");
|
|
15521
|
+
var SENTIMENT_ALERT_WINDOW_MS = 7 * 864e5;
|
|
15522
|
+
var SENTIMENT_ALERT_INTERVAL_MS = 5 * 6e4;
|
|
15523
|
+
var SentimentAlertStates = {
|
|
15524
|
+
sent: "sent",
|
|
15525
|
+
skipped: "skipped",
|
|
15526
|
+
quiet: "quiet",
|
|
15527
|
+
baseline: "baseline"
|
|
15528
|
+
};
|
|
15529
|
+
var AUTOMATIC = "automatic";
|
|
15530
|
+
function settledSentimentRuns(db, now) {
|
|
15531
|
+
const since = new Date(now - SENTIMENT_ALERT_WINDOW_MS).toISOString();
|
|
15532
|
+
const jobRunId = sql11`json_extract(${sentimentJobs.selection}, '$.runId')`;
|
|
15533
|
+
const lastReceipt = sql11`(SELECT MAX(${sentimentCompletionReceipts.sequence}) FROM ${sentimentCompletionReceipts}
|
|
15534
|
+
WHERE ${sentimentCompletionReceipts.projectId} = ${runs.projectId} AND ${sentimentCompletionReceipts.runId} = ${runs.id})`;
|
|
15535
|
+
const rows = db.select({
|
|
15536
|
+
projectId: sentimentJobs.projectId,
|
|
15537
|
+
runId: runs.id,
|
|
15538
|
+
open: sql11`SUM(${sentimentJobs.pendingItems} + ${sentimentJobs.runningItems})`,
|
|
15539
|
+
lastReceipt,
|
|
15540
|
+
reconciled: sentimentSettings.reconciledSequence
|
|
15541
|
+
}).from(sentimentJobs).innerJoin(runs, and22(eq26(runs.projectId, sentimentJobs.projectId), sql11`${runs.id} = ${jobRunId}`)).leftJoin(sentimentSettings, eq26(sentimentSettings.projectId, sentimentJobs.projectId)).where(and22(eq26(sentimentJobs.action, AUTOMATIC), gte4(sentimentJobs.createdAt, since), notProbeRun())).groupBy(sentimentJobs.projectId, runs.id).orderBy(asc5(runs.createdAt), asc5(runs.id)).all();
|
|
15542
|
+
const settled = /* @__PURE__ */ new Map();
|
|
15543
|
+
const waiting = /* @__PURE__ */ new Set();
|
|
15544
|
+
for (const row of rows) {
|
|
15545
|
+
if (waiting.has(row.projectId)) continue;
|
|
15546
|
+
const admitted = row.lastReceipt === null || row.lastReceipt <= (row.reconciled ?? 0);
|
|
15547
|
+
if (Number(row.open) > 0 || !admitted) {
|
|
15548
|
+
waiting.add(row.projectId);
|
|
15549
|
+
continue;
|
|
15550
|
+
}
|
|
15551
|
+
const list = settled.get(row.projectId);
|
|
15552
|
+
if (list) list.push(row.runId);
|
|
15553
|
+
else settled.set(row.projectId, [row.runId]);
|
|
15554
|
+
}
|
|
15555
|
+
return settled;
|
|
15556
|
+
}
|
|
15557
|
+
function undecidedSentimentRuns(db, projectId, runIds) {
|
|
15558
|
+
if (runIds.length === 0) return { undecided: [], firstPass: false };
|
|
15559
|
+
const decided = new Set(db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(and22(eq26(sentimentAlertRuns.projectId, projectId), inArray11(sentimentAlertRuns.runId, [...runIds]))).all().map((row) => row.runId));
|
|
15560
|
+
const firstPass = db.select({ runId: sentimentAlertRuns.runId }).from(sentimentAlertRuns).where(eq26(sentimentAlertRuns.projectId, projectId)).limit(1).get() === void 0;
|
|
15561
|
+
return { undecided: runIds.filter((runId) => !decided.has(runId)), firstPass };
|
|
15562
|
+
}
|
|
15563
|
+
function recordSentimentAlertRuns(db, projectId, runIds, state, now) {
|
|
15564
|
+
const recordedAt = new Date(now).toISOString();
|
|
15565
|
+
for (const runId of runIds) {
|
|
15566
|
+
db.insert(sentimentAlertRuns).values({ projectId, runId, state, recordedAt }).onConflictDoNothing().run();
|
|
15567
|
+
}
|
|
15568
|
+
}
|
|
15569
|
+
function startSentimentAlertLoop(dispatch, intervalMs = SENTIMENT_ALERT_INTERVAL_MS) {
|
|
15570
|
+
return startAlertLoop(dispatch, intervalMs, (err) => {
|
|
15571
|
+
log23.warn("sentiment-alerts.dispatch-failed", { error: describeError(err) });
|
|
15572
|
+
});
|
|
15496
15573
|
}
|
|
15497
15574
|
|
|
15498
15575
|
// src/provider-batch-poller.ts
|
|
15499
|
-
import { and as
|
|
15500
|
-
var
|
|
15576
|
+
import { and as and23, eq as eq27, inArray as inArray12, isNotNull as isNotNull3, isNull as isNull4, notExists as notExists2, sql as sql12 } from "drizzle-orm";
|
|
15577
|
+
var log24 = createLogger("ProviderBatchPoller");
|
|
15501
15578
|
var PROVIDER_BATCH_POLL_INITIAL_MS = 3e4;
|
|
15502
15579
|
var PROVIDER_BATCH_POLL_MAX_MS = 10 * 6e4;
|
|
15503
15580
|
var PROVIDER_BATCH_CANCEL_GRACE_MS = 60 * 6e4;
|
|
@@ -15513,7 +15590,7 @@ var ProviderBatchPoller = class {
|
|
|
15513
15590
|
/** One pass: advance every outstanding batch that is due, then finalize what that settled. */
|
|
15514
15591
|
async tick() {
|
|
15515
15592
|
const { db } = this.deps;
|
|
15516
|
-
const rows = db.select().from(providerBatches).where(
|
|
15593
|
+
const rows = db.select().from(providerBatches).where(inArray12(providerBatches.status, [...OUTSTANDING_PROVIDER_BATCH_STATUSES])).all();
|
|
15517
15594
|
const live = new Set(rows.map((row) => row.id));
|
|
15518
15595
|
for (const id of this.schedule.keys()) if (!live.has(id)) this.schedule.delete(id);
|
|
15519
15596
|
const settledRuns = /* @__PURE__ */ new Map();
|
|
@@ -15521,7 +15598,7 @@ var ProviderBatchPoller = class {
|
|
|
15521
15598
|
try {
|
|
15522
15599
|
if (await this.advance(row)) settledRuns.set(row.runId, row.projectId);
|
|
15523
15600
|
} catch (err) {
|
|
15524
|
-
|
|
15601
|
+
log24.warn("batch.advance-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
|
|
15525
15602
|
this.reschedule(row.id, null);
|
|
15526
15603
|
}
|
|
15527
15604
|
}
|
|
@@ -15530,7 +15607,7 @@ var ProviderBatchPoller = class {
|
|
|
15530
15607
|
try {
|
|
15531
15608
|
this.deps.runner.finalizeBatchRun(runId, projectId);
|
|
15532
15609
|
} catch (err) {
|
|
15533
|
-
|
|
15610
|
+
log24.warn("batch.finalize-failed", { runId, error: describeError(err) });
|
|
15534
15611
|
}
|
|
15535
15612
|
}
|
|
15536
15613
|
}
|
|
@@ -15539,7 +15616,7 @@ var ProviderBatchPoller = class {
|
|
|
15539
15616
|
* outstanding (ingested or cancelled), so its run may now finalize.
|
|
15540
15617
|
*/
|
|
15541
15618
|
async advance(row) {
|
|
15542
|
-
const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(
|
|
15619
|
+
const runStatus = this.deps.db.select({ status: runs.status }).from(runs).where(eq27(runs.id, row.runId)).get()?.status;
|
|
15543
15620
|
if (runStatus !== RunStatuses.running) {
|
|
15544
15621
|
await this.deps.runner.abandonProviderBatches([row.id], "Cancelled because its run is no longer running.");
|
|
15545
15622
|
this.schedule.delete(row.id);
|
|
@@ -15556,15 +15633,15 @@ var ProviderBatchPoller = class {
|
|
|
15556
15633
|
status = poll.status;
|
|
15557
15634
|
if (poll.status === "ended") {
|
|
15558
15635
|
const endedAt = poll.endedAt ?? new Date(this.now()).toISOString();
|
|
15559
|
-
const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(
|
|
15636
|
+
const ended = this.deps.db.update(providerBatches).set({ status: ProviderBatchStatuses.ended, endedAt, resultsExpireAt: poll.resultsExpireAt ?? null, updatedAt: endedAt }).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
|
|
15560
15637
|
this.schedule.delete(row.id);
|
|
15561
15638
|
return ended ? this.ingest({ ...row, status: ProviderBatchStatuses.ended, resultsExpireAt: poll.resultsExpireAt ?? null }) : false;
|
|
15562
15639
|
}
|
|
15563
15640
|
} catch (err) {
|
|
15564
|
-
|
|
15641
|
+
log24.warn("batch.poll-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error: describeError(err) });
|
|
15565
15642
|
}
|
|
15566
15643
|
} else {
|
|
15567
|
-
|
|
15644
|
+
log24.warn("batch.poll-unavailable", { batchId: row.id, runId: row.runId, provider: row.provider });
|
|
15568
15645
|
}
|
|
15569
15646
|
this.reschedule(row.id, status);
|
|
15570
15647
|
return this.enforceDeadline(row, registered);
|
|
@@ -15580,18 +15657,18 @@ var ProviderBatchPoller = class {
|
|
|
15580
15657
|
const at = new Date(now).toISOString();
|
|
15581
15658
|
if (row.cancelRequestedAt === null) {
|
|
15582
15659
|
if (now < Date.parse(row.deadlineAt)) return false;
|
|
15583
|
-
const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(
|
|
15584
|
-
|
|
15585
|
-
|
|
15660
|
+
const claimed = this.deps.db.update(providerBatches).set({ cancelRequestedAt: at, updatedAt: at }).where(and23(
|
|
15661
|
+
eq27(providerBatches.id, row.id),
|
|
15662
|
+
eq27(providerBatches.status, ProviderBatchStatuses.submitted),
|
|
15586
15663
|
isNull4(providerBatches.cancelRequestedAt)
|
|
15587
15664
|
)).run().changes === 1;
|
|
15588
15665
|
if (!claimed) return false;
|
|
15589
|
-
|
|
15666
|
+
log24.warn("batch.deadline-passed", { batchId: row.id, runId: row.runId, provider: row.provider, deadlineAt: row.deadlineAt });
|
|
15590
15667
|
if (registered?.adapter.batch && row.providerBatchId) {
|
|
15591
15668
|
try {
|
|
15592
15669
|
await registered.adapter.batch.cancel(row.providerBatchId, registered.config);
|
|
15593
15670
|
} catch (err) {
|
|
15594
|
-
|
|
15671
|
+
log24.warn("batch.cancel-failed", { batchId: row.id, provider: row.provider, error: describeError(err) });
|
|
15595
15672
|
}
|
|
15596
15673
|
}
|
|
15597
15674
|
return false;
|
|
@@ -15601,9 +15678,9 @@ var ProviderBatchPoller = class {
|
|
|
15601
15678
|
status: ProviderBatchStatuses.cancelled,
|
|
15602
15679
|
error: `The provider batch did not end within an hour of being cancelled at its deadline; its ${row.requestCount} answer(s) were not recorded.`,
|
|
15603
15680
|
updatedAt: at
|
|
15604
|
-
}).where(
|
|
15681
|
+
}).where(and23(eq27(providerBatches.id, row.id), eq27(providerBatches.status, ProviderBatchStatuses.submitted))).run().changes === 1;
|
|
15605
15682
|
this.schedule.delete(row.id);
|
|
15606
|
-
if (gaveUp)
|
|
15683
|
+
if (gaveUp) log24.warn("batch.abandoned-after-deadline", { batchId: row.id, runId: row.runId, provider: row.provider });
|
|
15607
15684
|
return gaveUp;
|
|
15608
15685
|
}
|
|
15609
15686
|
async ingest(row) {
|
|
@@ -15612,7 +15689,7 @@ var ProviderBatchPoller = class {
|
|
|
15612
15689
|
return result.kind !== "skipped";
|
|
15613
15690
|
} catch (err) {
|
|
15614
15691
|
const error = describeError(err);
|
|
15615
|
-
|
|
15692
|
+
log24.warn("batch.ingest-failed", { batchId: row.id, runId: row.runId, provider: row.provider, error });
|
|
15616
15693
|
const now = this.now();
|
|
15617
15694
|
const unreadable = row.resultsExpireAt !== null && now >= Date.parse(row.resultsExpireAt);
|
|
15618
15695
|
if (unreadable || now >= Date.parse(row.deadlineAt) + PROVIDER_BATCH_CANCEL_GRACE_MS) {
|
|
@@ -15641,10 +15718,10 @@ var ProviderBatchPoller = class {
|
|
|
15641
15718
|
/** Runs the sweep handed off whose batches have all settled. */
|
|
15642
15719
|
finalizableRuns() {
|
|
15643
15720
|
const holding = [ProviderBatchStatuses.submitting, ...OUTSTANDING_PROVIDER_BATCH_STATUSES];
|
|
15644
|
-
return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(
|
|
15645
|
-
|
|
15721
|
+
return this.deps.db.select({ id: runs.id, projectId: runs.projectId }).from(runs).where(and23(
|
|
15722
|
+
eq27(runs.status, RunStatuses.running),
|
|
15646
15723
|
isNotNull3(runs.pendingProviderErrors),
|
|
15647
|
-
notExists2(this.deps.db.select({ one:
|
|
15724
|
+
notExists2(this.deps.db.select({ one: sql12`1` }).from(providerBatches).where(and23(eq27(providerBatches.runId, runs.id), inArray12(providerBatches.status, holding))))
|
|
15648
15725
|
)).all();
|
|
15649
15726
|
}
|
|
15650
15727
|
};
|
|
@@ -15654,7 +15731,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
|
|
|
15654
15731
|
const timer = setInterval(() => {
|
|
15655
15732
|
if (running) return;
|
|
15656
15733
|
running = true;
|
|
15657
|
-
void poller.tick().catch((err) =>
|
|
15734
|
+
void poller.tick().catch((err) => log24.warn("batch.pass-failed", { error: describeError(err) })).finally(() => {
|
|
15658
15735
|
running = false;
|
|
15659
15736
|
});
|
|
15660
15737
|
}, intervalMs);
|
|
@@ -15663,7 +15740,7 @@ function startProviderBatchPoller(deps, intervalMs = PROVIDER_BATCH_TICK_MS) {
|
|
|
15663
15740
|
}
|
|
15664
15741
|
|
|
15665
15742
|
// src/data-refresh.ts
|
|
15666
|
-
var
|
|
15743
|
+
var log25 = createLogger("DataRefresh");
|
|
15667
15744
|
function gaRefreshDays(now = /* @__PURE__ */ new Date()) {
|
|
15668
15745
|
const [reportMonth] = reportMonthsForDoctor(void 0, now);
|
|
15669
15746
|
const reach = inclusiveDayCount(`${reportMonth}-01`, now.toISOString().slice(0, 10)) ?? 0;
|
|
@@ -15705,15 +15782,15 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
|
|
|
15705
15782
|
if (result.status === "rejected") {
|
|
15706
15783
|
const reason = result.reason;
|
|
15707
15784
|
const message = describeError(reason);
|
|
15708
|
-
|
|
15785
|
+
log25.warn("integration.refresh-failed", { projectName, integration, error: message });
|
|
15709
15786
|
return;
|
|
15710
15787
|
}
|
|
15711
15788
|
switch (completion) {
|
|
15712
15789
|
case "synchronous":
|
|
15713
|
-
|
|
15790
|
+
log25.info("integration.refreshed", { projectName, integration });
|
|
15714
15791
|
return;
|
|
15715
15792
|
case "queued":
|
|
15716
|
-
|
|
15793
|
+
log25.info("integration.queued", { projectName, integration, ...queuedRun(result.value) });
|
|
15717
15794
|
return;
|
|
15718
15795
|
default: {
|
|
15719
15796
|
const _exhaustive = completion;
|
|
@@ -15724,12 +15801,12 @@ async function refreshAllIntegrations(client, projectName, now = /* @__PURE__ */
|
|
|
15724
15801
|
}
|
|
15725
15802
|
|
|
15726
15803
|
// src/notifier.ts
|
|
15727
|
-
import { eq as
|
|
15804
|
+
import { eq as eq29, desc as desc10, and as and25, inArray as inArray13, or as or2, isNull as isNull5 } from "drizzle-orm";
|
|
15728
15805
|
import crypto25 from "crypto";
|
|
15729
15806
|
|
|
15730
15807
|
// src/site-health-alerts.ts
|
|
15731
15808
|
import crypto24 from "crypto";
|
|
15732
|
-
import { and as
|
|
15809
|
+
import { and as and24, asc as asc6, desc as desc9, eq as eq28, gt as gt3 } from "drizzle-orm";
|
|
15733
15810
|
var ISSUE_TITLES = {
|
|
15734
15811
|
"missing-h1": "Missing H1",
|
|
15735
15812
|
"multiple-h1": "Multiple H1 tags",
|
|
@@ -15742,18 +15819,18 @@ function siteHealthProblemKey(code, url) {
|
|
|
15742
15819
|
return `${code}|${crypto24.createHash("sha256").update(url).digest("hex").slice(0, 16)}`;
|
|
15743
15820
|
}
|
|
15744
15821
|
function readSiteHealthScan(db, projectId, runId) {
|
|
15745
|
-
const snapshot = db.select().from(siteCrawlSnapshots).where(
|
|
15822
|
+
const snapshot = db.select().from(siteCrawlSnapshots).where(and24(eq28(siteCrawlSnapshots.projectId, projectId), eq28(siteCrawlSnapshots.runId, runId))).orderBy(desc9(siteCrawlSnapshots.updatedAt)).limit(1).get();
|
|
15746
15823
|
if (!snapshot?.detailsAvailable || !snapshot.attemptId) return null;
|
|
15747
|
-
const scope =
|
|
15748
|
-
|
|
15749
|
-
|
|
15750
|
-
|
|
15824
|
+
const scope = and24(
|
|
15825
|
+
eq28(siteCrawlPages.projectId, projectId),
|
|
15826
|
+
eq28(siteCrawlPages.runId, runId),
|
|
15827
|
+
eq28(siteCrawlPages.attemptId, snapshot.attemptId)
|
|
15751
15828
|
);
|
|
15752
15829
|
const pagesByCode = /* @__PURE__ */ new Map();
|
|
15753
15830
|
const keys = /* @__PURE__ */ new Set();
|
|
15754
15831
|
let after;
|
|
15755
15832
|
for (; ; ) {
|
|
15756
|
-
const pages = db.select({ nodeKey: siteCrawlPages.nodeKey, url: siteCrawlPages.url, auditFields: siteCrawlPages.auditFields }).from(siteCrawlPages).where(after === void 0 ? scope :
|
|
15833
|
+
const pages = db.select({ nodeKey: siteCrawlPages.nodeKey, url: siteCrawlPages.url, auditFields: siteCrawlPages.auditFields }).from(siteCrawlPages).where(after === void 0 ? scope : and24(scope, gt3(siteCrawlPages.nodeKey, after))).orderBy(asc6(siteCrawlPages.nodeKey)).limit(PAGE_BATCH).all();
|
|
15757
15834
|
for (const page of pages) {
|
|
15758
15835
|
const defects = page.auditFields.criticalDefects;
|
|
15759
15836
|
for (const defect of Array.isArray(defects) ? defects : []) {
|
|
@@ -15795,7 +15872,7 @@ function settledSiteHealthKeys(scan, reported) {
|
|
|
15795
15872
|
return [...scan.complete ? scan.keys : /* @__PURE__ */ new Set([...reported, ...scan.keys])].sort(compareText);
|
|
15796
15873
|
}
|
|
15797
15874
|
function readSiteHealthNotifyState(db, projectId) {
|
|
15798
|
-
return db.select().from(siteHealthNotifyState).where(
|
|
15875
|
+
return db.select().from(siteHealthNotifyState).where(eq28(siteHealthNotifyState.projectId, projectId)).get() ?? null;
|
|
15799
15876
|
}
|
|
15800
15877
|
function writeSiteHealthNotifyState(db, input) {
|
|
15801
15878
|
const values = { reportedKeys: input.reportedKeys, runId: input.runId, updatedAt: input.updatedAt, notifiedAt: input.notifiedAt };
|
|
@@ -15803,7 +15880,7 @@ function writeSiteHealthNotifyState(db, input) {
|
|
|
15803
15880
|
}
|
|
15804
15881
|
|
|
15805
15882
|
// src/notifier.ts
|
|
15806
|
-
var
|
|
15883
|
+
var log26 = createLogger("Notifier");
|
|
15807
15884
|
var sampleDelivery = createOutcomeSampler({ burst: 20, refillMs: 6e4, now: () => Date.now() });
|
|
15808
15885
|
function trackWebhookDelivery(input) {
|
|
15809
15886
|
const sample = sampleDelivery(input.failure ? "failed" : "succeeded");
|
|
@@ -15916,52 +15993,67 @@ var Notifier = class {
|
|
|
15916
15993
|
reviewDispatchInFlight = /* @__PURE__ */ new Set();
|
|
15917
15994
|
/** Set while a {@link dispatchUnrecognizedAgentAlerts} pass runs, so passes never overlap. */
|
|
15918
15995
|
unrecognizedAgentDispatchInFlight = false;
|
|
15996
|
+
/** The sentiment install's readiness; without it no sentiment alert is read. */
|
|
15997
|
+
sentimentInstall;
|
|
15998
|
+
/** Set while a {@link dispatchSentimentAlerts} pass runs, so passes never overlap. */
|
|
15999
|
+
sentimentDispatchInFlight = false;
|
|
16000
|
+
/**
|
|
16001
|
+
* Answers of sweeps no webhook accepted yet, by run id, so a refused alert
|
|
16002
|
+
* is retried without reading every assessment of two sweeps again. Kept
|
|
16003
|
+
* only while the sweep is undecided and still in the alert window.
|
|
16004
|
+
*/
|
|
16005
|
+
undeliveredSentimentAlerts = /* @__PURE__ */ new Map();
|
|
15919
16006
|
constructor(db, serverUrl, opts = {}) {
|
|
15920
16007
|
this.db = db;
|
|
15921
16008
|
this.serverUrl = serverUrl;
|
|
15922
16009
|
this.allowLoopbackWebhooks = opts.allowLoopbackWebhooks === true;
|
|
16010
|
+
this.sentimentInstall = opts.sentimentInstall ?? null;
|
|
15923
16011
|
}
|
|
15924
16012
|
/** Called after a run completes (success, partial, or failed). */
|
|
15925
16013
|
async onRunCompleted(runId, projectId, opts) {
|
|
15926
|
-
|
|
15927
|
-
const notifs = this.db.select().from(notifications).where(
|
|
16014
|
+
log26.info("run.completed", { runId, projectId, origin: opts?.origin ?? "sweep" });
|
|
16015
|
+
const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
|
|
15928
16016
|
if (notifs.length === 0) {
|
|
15929
|
-
|
|
16017
|
+
log26.info("notifications.none-enabled", { projectId });
|
|
15930
16018
|
return;
|
|
15931
16019
|
}
|
|
15932
|
-
|
|
15933
|
-
const run = this.db.select().from(runs).where(
|
|
16020
|
+
log26.info("notifications.found", { projectId, count: notifs.length });
|
|
16021
|
+
const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
|
|
15934
16022
|
if (!run) {
|
|
15935
|
-
|
|
16023
|
+
log26.error("run.not-found", { runId, msg: "skipping notification dispatch" });
|
|
15936
16024
|
return;
|
|
15937
16025
|
}
|
|
15938
|
-
const project = this.db.select().from(projects).where(
|
|
16026
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
15939
16027
|
if (!project) {
|
|
15940
|
-
|
|
16028
|
+
log26.error("project.not-found", { projectId, msg: "skipping notification dispatch" });
|
|
15941
16029
|
return;
|
|
15942
16030
|
}
|
|
15943
|
-
const transitions = this.computeTransitions(runId,
|
|
16031
|
+
const transitions = this.computeTransitions(runId, project);
|
|
15944
16032
|
const events = [];
|
|
15945
|
-
|
|
16033
|
+
log26.info("run.status", { runId: run.id, status: run.status, projectId });
|
|
15946
16034
|
if ((run.status === "completed" || run.status === "partial") && opts?.origin !== "fill") {
|
|
15947
16035
|
events.push("run.completed");
|
|
15948
16036
|
}
|
|
15949
16037
|
if (run.status === "failed") {
|
|
15950
16038
|
events.push("run.failed");
|
|
15951
16039
|
}
|
|
15952
|
-
const lostTransitions = transitions.filter((t) => t.to === CitationStates["not-cited"] && t.from === CitationStates.cited);
|
|
15953
|
-
const gainedTransitions = transitions.filter((t) => t.to === CitationStates.cited && t.from === CitationStates["not-cited"]);
|
|
16040
|
+
const lostTransitions = transitions.citation.filter((t) => t.to === CitationStates["not-cited"] && t.from === CitationStates.cited);
|
|
16041
|
+
const gainedTransitions = transitions.citation.filter((t) => t.to === CitationStates.cited && t.from === CitationStates["not-cited"]);
|
|
16042
|
+
const lostMentions = transitions.mention.filter((t) => t.to === MentionStates["not-mentioned"]);
|
|
16043
|
+
const gainedMentions = transitions.mention.filter((t) => t.to === MentionStates.mentioned);
|
|
15954
16044
|
if (lostTransitions.length > 0) events.push("citation.lost");
|
|
15955
16045
|
if (gainedTransitions.length > 0) events.push("citation.gained");
|
|
16046
|
+
if (lostMentions.length > 0) events.push("mention.lost");
|
|
16047
|
+
if (gainedMentions.length > 0) events.push("mention.gained");
|
|
15956
16048
|
for (const notif of notifs) {
|
|
15957
16049
|
const config = notif.config;
|
|
15958
16050
|
if (!config.url) continue;
|
|
15959
16051
|
const subscribedEvents = config.events;
|
|
15960
16052
|
const matchingEvents = events.filter((e) => subscribedEvents.includes(e));
|
|
15961
|
-
|
|
16053
|
+
log26.info("notification.match", { notificationId: notif.id, subscribedEvents, matchedEvents: matchingEvents });
|
|
15962
16054
|
if (matchingEvents.length === 0) continue;
|
|
15963
16055
|
for (const event of matchingEvents) {
|
|
15964
|
-
const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : transitions;
|
|
16056
|
+
const relevantTransitions = event === "citation.lost" ? lostTransitions : event === "citation.gained" ? gainedTransitions : event === "mention.lost" ? lostMentions : event === "mention.gained" ? gainedMentions : transitions.citation;
|
|
15965
16057
|
const payload = {
|
|
15966
16058
|
source: "canonry",
|
|
15967
16059
|
event,
|
|
@@ -16014,9 +16106,9 @@ var Notifier = class {
|
|
|
16014
16106
|
* than inferred from the absence of a webhook.
|
|
16015
16107
|
*/
|
|
16016
16108
|
async onHealthChecked(projectId, report) {
|
|
16017
|
-
const project = this.db.select().from(projects).where(
|
|
16109
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16018
16110
|
if (!project) {
|
|
16019
|
-
|
|
16111
|
+
log26.error("project.not-found", { projectId, msg: "skipping health notification" });
|
|
16020
16112
|
return null;
|
|
16021
16113
|
}
|
|
16022
16114
|
const rank = healthRank;
|
|
@@ -16047,7 +16139,7 @@ var Notifier = class {
|
|
|
16047
16139
|
const status = noSignal ? "warn" : worst ? worst.status : "ok";
|
|
16048
16140
|
const code = noSignal ? HEALTH_NO_SIGNAL_CODE : worst?.code ?? "health.ok";
|
|
16049
16141
|
const summary = noSignal ? `No health check produced a result (${healthChecks.length} skipped) \u2014 health is unknown, not confirmed.` : worst?.summary ?? `All ${graded.length} health check(s) passing.`;
|
|
16050
|
-
const previous = this.db.select().from(doctorHealthState).where(
|
|
16142
|
+
const previous = this.db.select().from(doctorHealthState).where(eq29(doctorHealthState.projectId, projectId)).get();
|
|
16051
16143
|
const previousStatus = previous?.status ?? null;
|
|
16052
16144
|
const failingSignature = failing.map((c) => `${c.status}:${c.code}`).join(",");
|
|
16053
16145
|
const failingNow = failing.map((c) => ({ id: c.id, code: c.code, rank: rank(c.status) }));
|
|
@@ -16117,7 +16209,7 @@ var Notifier = class {
|
|
|
16117
16209
|
const urgentById = new Map(urgentItems.map((item) => [item.id, item]));
|
|
16118
16210
|
const generalEvent = event;
|
|
16119
16211
|
const urgentRecord = previous?.urgentNotified ?? null;
|
|
16120
|
-
const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(
|
|
16212
|
+
const enabled = generalEvent || urgentItems.length > 0 || urgentRecord ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
|
|
16121
16213
|
const listedEvents = (notif) => notif.config.events;
|
|
16122
16214
|
const hasUrl = (notif) => Boolean(notif.config.url);
|
|
16123
16215
|
const urgentSubscribers = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
|
|
@@ -16165,7 +16257,7 @@ var Notifier = class {
|
|
|
16165
16257
|
if (previous === void 0) {
|
|
16166
16258
|
this.db.insert(doctorHealthState).values({ ...observation, notifiedAt: null }).run();
|
|
16167
16259
|
} else {
|
|
16168
|
-
this.db.update(doctorHealthState).set(observation).where(
|
|
16260
|
+
this.db.update(doctorHealthState).set(observation).where(eq29(doctorHealthState.projectId, projectId)).run();
|
|
16169
16261
|
}
|
|
16170
16262
|
for (const group of urgentGroups) {
|
|
16171
16263
|
const { urgentEvent, urgentTold, urgentNew, urgentCleared, urgentNotifs, urgentSettled } = group;
|
|
@@ -16209,10 +16301,10 @@ var Notifier = class {
|
|
|
16209
16301
|
}
|
|
16210
16302
|
if (accepted > 0) {
|
|
16211
16303
|
recordUrgentReceipts(urgentReceipts, group.subscribers, formatUrgentBreaches(urgentSettled) || null);
|
|
16212
|
-
this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(
|
|
16304
|
+
this.db.update(doctorHealthState).set({ urgentNotified: doctorUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(doctorHealthState.projectId, projectId)).run();
|
|
16213
16305
|
}
|
|
16214
16306
|
if (urgentNotifs.length > 0) {
|
|
16215
|
-
|
|
16307
|
+
log26.info("health.urgent-notified", {
|
|
16216
16308
|
projectId,
|
|
16217
16309
|
event: urgentEvent,
|
|
16218
16310
|
codes: urgentEvent === "health.urgent" ? breachCodes(urgentNew) : breachCodes(urgentCleared),
|
|
@@ -16223,9 +16315,9 @@ var Notifier = class {
|
|
|
16223
16315
|
}
|
|
16224
16316
|
if (!event) {
|
|
16225
16317
|
if (clearedThisPass.length > 0 || easedThisPass.length > 0) {
|
|
16226
|
-
|
|
16318
|
+
log26.info("health.improved", { projectId, status, code, cleared: clearedThisPass, eased: easedThisPass });
|
|
16227
16319
|
} else {
|
|
16228
|
-
|
|
16320
|
+
log26.info("health.unchanged", { projectId, status, code });
|
|
16229
16321
|
}
|
|
16230
16322
|
return null;
|
|
16231
16323
|
}
|
|
@@ -16253,9 +16345,9 @@ var Notifier = class {
|
|
|
16253
16345
|
if (await this.sendWebhook(config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) delivered += 1;
|
|
16254
16346
|
}
|
|
16255
16347
|
if (delivered > 0) {
|
|
16256
|
-
this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(
|
|
16348
|
+
this.db.update(doctorHealthState).set({ notifiedAt: now, notifiedSignature: formatBreaches(failingNow), pendingSignature: null }).where(eq29(doctorHealthState.projectId, projectId)).run();
|
|
16257
16349
|
}
|
|
16258
|
-
|
|
16350
|
+
log26.info("health.notified", {
|
|
16259
16351
|
projectId,
|
|
16260
16352
|
event,
|
|
16261
16353
|
status,
|
|
@@ -16283,12 +16375,12 @@ var Notifier = class {
|
|
|
16283
16375
|
async onSiteLivenessChecked(projectId, result) {
|
|
16284
16376
|
const { check, checkedAt } = result;
|
|
16285
16377
|
if (check.status !== "ok" && check.status !== "fail") return null;
|
|
16286
|
-
const project = this.db.select().from(projects).where(
|
|
16378
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16287
16379
|
if (!project) {
|
|
16288
|
-
|
|
16380
|
+
log26.error("project.not-found", { projectId, msg: "skipping site liveness notification" });
|
|
16289
16381
|
return null;
|
|
16290
16382
|
}
|
|
16291
|
-
const previous = this.db.select().from(siteLivenessState).where(
|
|
16383
|
+
const previous = this.db.select().from(siteLivenessState).where(eq29(siteLivenessState.projectId, projectId)).get();
|
|
16292
16384
|
const sincePrevious = previous ? Date.parse(checkedAt) - Date.parse(previous.checkedAt) : Number.NaN;
|
|
16293
16385
|
const countsAsRepeat = Number.isFinite(sincePrevious) && sincePrevious >= SITE_LIVENESS_MIN_PASS_GAP_MS && sincePrevious <= SITE_LIVENESS_MAX_PASS_GAP_MS;
|
|
16294
16386
|
const failures = check.status === "fail" ? countsAsRepeat ? (previous?.consecutiveFailures ?? 0) + 1 : 1 : 0;
|
|
@@ -16298,7 +16390,7 @@ var Notifier = class {
|
|
|
16298
16390
|
if (check.status === "ok" && outagePaged) event = "health.recovered";
|
|
16299
16391
|
const confirmed = check.status === "fail" && failures >= SITE_LIVENESS_FAILURES_TO_PAGE;
|
|
16300
16392
|
const urgentRecord = previous?.urgentNotifiedAt ?? null;
|
|
16301
|
-
const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(
|
|
16393
|
+
const enabled = event !== null || confirmed || urgentRecord !== null ? this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled) : [];
|
|
16302
16394
|
const listedEvents = (notif) => notif.config.events;
|
|
16303
16395
|
const hasUrl = (notif) => Boolean(notif.config.url);
|
|
16304
16396
|
const scoped = enabled.filter((n) => hasUrl(n) && (listedEvents(n) ?? []).some((e) => URGENT_HEALTH_EVENTS.has(e)));
|
|
@@ -16331,7 +16423,7 @@ var Notifier = class {
|
|
|
16331
16423
|
if (previous === void 0) {
|
|
16332
16424
|
this.db.insert(siteLivenessState).values(observation).run();
|
|
16333
16425
|
} else {
|
|
16334
|
-
this.db.update(siteLivenessState).set(observation).where(
|
|
16426
|
+
this.db.update(siteLivenessState).set(observation).where(eq29(siteLivenessState.projectId, projectId)).run();
|
|
16335
16427
|
}
|
|
16336
16428
|
if (!event && urgentGroups.every((group) => group.urgentEvent === null)) return null;
|
|
16337
16429
|
const payloadFor = (name) => {
|
|
@@ -16367,9 +16459,9 @@ var Notifier = class {
|
|
|
16367
16459
|
}
|
|
16368
16460
|
}
|
|
16369
16461
|
if (event === "health.degraded" && delivered > 0) {
|
|
16370
|
-
this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(
|
|
16462
|
+
this.db.update(siteLivenessState).set({ notifiedAt: checkedAt }).where(eq29(siteLivenessState.projectId, projectId)).run();
|
|
16371
16463
|
}
|
|
16372
|
-
|
|
16464
|
+
log26.info("site-liveness.notified", { projectId, event, code: check.code, subscribers: notifs.length, delivered });
|
|
16373
16465
|
}
|
|
16374
16466
|
for (const group of urgentGroups) {
|
|
16375
16467
|
const { urgentEvent, urgentNotifs, generalIds } = group;
|
|
@@ -16381,10 +16473,10 @@ var Notifier = class {
|
|
|
16381
16473
|
}
|
|
16382
16474
|
if (accepted > 0) {
|
|
16383
16475
|
recordUrgentReceipts(urgentReceipts, group.subscribers, group.settled);
|
|
16384
|
-
this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(
|
|
16476
|
+
this.db.update(siteLivenessState).set({ urgentNotifiedAt: siteUrgentSummary(urgentReceipts), urgentReceipts }).where(eq29(siteLivenessState.projectId, projectId)).run();
|
|
16385
16477
|
}
|
|
16386
16478
|
if (urgentNotifs.length > 0 || generalIds.size > 0) {
|
|
16387
|
-
|
|
16479
|
+
log26.info("site-liveness.urgent-notified", { projectId, event: urgentEvent, code: check.code, subscribers: urgentNotifs.length + generalIds.size, delivered: accepted });
|
|
16388
16480
|
}
|
|
16389
16481
|
}
|
|
16390
16482
|
return event;
|
|
@@ -16407,7 +16499,7 @@ var Notifier = class {
|
|
|
16407
16499
|
*/
|
|
16408
16500
|
isNewInsightNews(projectId, insight) {
|
|
16409
16501
|
const key = insightNotifyKey(projectId, insight);
|
|
16410
|
-
const previous = this.db.select().from(insightNotifyState).where(
|
|
16502
|
+
const previous = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
|
|
16411
16503
|
if (!previous) return true;
|
|
16412
16504
|
if (severityRank(insight.severity) > severityRank(previous.severity)) return true;
|
|
16413
16505
|
const magnitude = insightMagnitude(insight);
|
|
@@ -16429,9 +16521,9 @@ var Notifier = class {
|
|
|
16429
16521
|
magnitude: insightMagnitude(insight),
|
|
16430
16522
|
notifiedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
16431
16523
|
};
|
|
16432
|
-
const existing = this.db.select().from(insightNotifyState).where(
|
|
16524
|
+
const existing = this.db.select().from(insightNotifyState).where(eq29(insightNotifyState.key, key)).get();
|
|
16433
16525
|
if (existing) {
|
|
16434
|
-
this.db.update(insightNotifyState).set(row).where(
|
|
16526
|
+
this.db.update(insightNotifyState).set(row).where(eq29(insightNotifyState.key, key)).run();
|
|
16435
16527
|
} else {
|
|
16436
16528
|
this.db.insert(insightNotifyState).values(row).run();
|
|
16437
16529
|
}
|
|
@@ -16445,11 +16537,11 @@ var Notifier = class {
|
|
|
16445
16537
|
if (criticalInsights.length > 0) insightEvents.push("insight.critical");
|
|
16446
16538
|
if (highInsights.length > 0) insightEvents.push("insight.high");
|
|
16447
16539
|
if (insightEvents.length === 0) return;
|
|
16448
|
-
const notifs = this.db.select().from(notifications).where(
|
|
16540
|
+
const notifs = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled);
|
|
16449
16541
|
if (notifs.length === 0) return;
|
|
16450
|
-
const run = this.db.select().from(runs).where(
|
|
16542
|
+
const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
|
|
16451
16543
|
if (!run) return;
|
|
16452
|
-
const project = this.db.select().from(projects).where(
|
|
16544
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16453
16545
|
if (!project) return;
|
|
16454
16546
|
for (const notif of notifs) {
|
|
16455
16547
|
const config = notif.config;
|
|
@@ -16530,9 +16622,9 @@ var Notifier = class {
|
|
|
16530
16622
|
return delivered;
|
|
16531
16623
|
}
|
|
16532
16624
|
async dispatchQueuedReviewAlerts(projectId) {
|
|
16533
|
-
const pendingReviews = this.db.select().from(gbpReviews).where(
|
|
16534
|
-
const pendingRatings = this.db.select().from(gbpReviewRatings).where(
|
|
16535
|
-
const project = this.db.select().from(projects).where(
|
|
16625
|
+
const pendingReviews = this.db.select().from(gbpReviews).where(and25(eq29(gbpReviews.projectId, projectId), eq29(gbpReviews.alertState, "pending"))).all();
|
|
16626
|
+
const pendingRatings = this.db.select().from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.alertState, "pending"))).all();
|
|
16627
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16536
16628
|
if (!project) return { reviews: 0, ratingDrops: 0, delivered: 0 };
|
|
16537
16629
|
const chatSendsLeft = /* @__PURE__ */ new Map();
|
|
16538
16630
|
const now = /* @__PURE__ */ new Date();
|
|
@@ -16544,10 +16636,10 @@ var Notifier = class {
|
|
|
16544
16636
|
displayName: gbpLocations.displayName,
|
|
16545
16637
|
mapsUri: gbpLocations.mapsUri,
|
|
16546
16638
|
reviewsAccess: gbpLocations.reviewsAccess
|
|
16547
|
-
}).from(gbpLocations).where(
|
|
16639
|
+
}).from(gbpLocations).where(eq29(gbpLocations.projectId, projectId)).all().map((loc) => [loc.locationName, loc])
|
|
16548
16640
|
);
|
|
16549
16641
|
const v4HasWorked = new Set(
|
|
16550
|
-
this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(
|
|
16642
|
+
this.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and25(eq29(gbpReviewRatings.projectId, projectId), eq29(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
|
|
16551
16643
|
);
|
|
16552
16644
|
const coveredByBusinessProfile = (locationName) => businessProfileReviewsCover(locations.get(locationName)?.reviewsAccess ?? null, v4HasWorked.has(locationName));
|
|
16553
16645
|
const locationRef = (locationName) => {
|
|
@@ -16556,11 +16648,11 @@ var Notifier = class {
|
|
|
16556
16648
|
};
|
|
16557
16649
|
const setReviewState = (ids, alertState) => {
|
|
16558
16650
|
if (ids.length === 0) return;
|
|
16559
|
-
this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(
|
|
16651
|
+
this.db.update(gbpReviews).set({ alertState, alertStateAt: nowIso }).where(inArray13(gbpReviews.id, ids)).run();
|
|
16560
16652
|
};
|
|
16561
16653
|
const setRatingState = (ids, alertState) => {
|
|
16562
16654
|
if (ids.length === 0) return;
|
|
16563
|
-
this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(
|
|
16655
|
+
this.db.update(gbpReviewRatings).set({ alertState, alertStateAt: nowIso }).where(inArray13(gbpReviewRatings.id, ids)).run();
|
|
16564
16656
|
};
|
|
16565
16657
|
const reviewsToSend = [];
|
|
16566
16658
|
for (const row of pendingReviews) {
|
|
@@ -16576,7 +16668,7 @@ var Notifier = class {
|
|
|
16576
16668
|
else if (row.rating === null || row.previousRating === null) setRatingState([row.id], "none");
|
|
16577
16669
|
else ratingsToSend.push(row);
|
|
16578
16670
|
}
|
|
16579
|
-
const enabled = this.db.select().from(notifications).where(
|
|
16671
|
+
const enabled = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url);
|
|
16580
16672
|
const subscribedTo = (event) => enabled.filter((n) => (n.config.events ?? []).includes(event));
|
|
16581
16673
|
const projectRef = { name: project.name, canonicalDomain: project.canonicalDomain };
|
|
16582
16674
|
const dashboardUrl = `${this.serverUrl}/projects/${project.name}`;
|
|
@@ -16630,13 +16722,13 @@ var Notifier = class {
|
|
|
16630
16722
|
if (!sent) all = false;
|
|
16631
16723
|
}
|
|
16632
16724
|
if (all) {
|
|
16633
|
-
this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(
|
|
16634
|
-
|
|
16635
|
-
|
|
16636
|
-
|
|
16637
|
-
review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) :
|
|
16638
|
-
review.comment === null ? isNull5(gbpReviews.comment) :
|
|
16639
|
-
review.starRating === null ? isNull5(gbpReviews.starRating) :
|
|
16725
|
+
this.db.update(gbpReviews).set({ alertState: "sent", alertStateAt: nowIso }).where(and25(
|
|
16726
|
+
eq29(gbpReviews.id, review.id),
|
|
16727
|
+
eq29(gbpReviews.alertState, "pending"),
|
|
16728
|
+
eq29(gbpReviews.updateTime, review.updateTime),
|
|
16729
|
+
review.alertStateAt === null ? isNull5(gbpReviews.alertStateAt) : eq29(gbpReviews.alertStateAt, review.alertStateAt),
|
|
16730
|
+
review.comment === null ? isNull5(gbpReviews.comment) : eq29(gbpReviews.comment, review.comment),
|
|
16731
|
+
review.starRating === null ? isNull5(gbpReviews.starRating) : eq29(gbpReviews.starRating, review.starRating)
|
|
16640
16732
|
)).run();
|
|
16641
16733
|
}
|
|
16642
16734
|
}
|
|
@@ -16668,7 +16760,7 @@ var Notifier = class {
|
|
|
16668
16760
|
delivered += accepted;
|
|
16669
16761
|
}
|
|
16670
16762
|
}
|
|
16671
|
-
|
|
16763
|
+
log26.info("reviews.dispatched", {
|
|
16672
16764
|
projectId,
|
|
16673
16765
|
reviews: reviewsToSend.length,
|
|
16674
16766
|
ratingDrops: ratingsToSend.length,
|
|
@@ -16676,30 +16768,32 @@ var Notifier = class {
|
|
|
16676
16768
|
});
|
|
16677
16769
|
return { reviews: reviewsToSend.length, ratingDrops: ratingsToSend.length, delivered };
|
|
16678
16770
|
}
|
|
16679
|
-
computeTransitions(runId,
|
|
16680
|
-
const
|
|
16681
|
-
|
|
16771
|
+
computeTransitions(runId, project) {
|
|
16772
|
+
const none = { citation: [], mention: [] };
|
|
16773
|
+
const projectId = project.id;
|
|
16774
|
+
const thisRun = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
|
|
16775
|
+
if (!thisRun) return none;
|
|
16682
16776
|
const completeness = measurementRunCompleteness(this.db, runId);
|
|
16683
16777
|
if (completeness.planned && !completeness.complete) {
|
|
16684
|
-
|
|
16778
|
+
log26.info("transitions.skipped-incomplete", {
|
|
16685
16779
|
runId,
|
|
16686
16780
|
executed: completeness.executed,
|
|
16687
16781
|
expected: completeness.expected
|
|
16688
16782
|
});
|
|
16689
|
-
return
|
|
16783
|
+
return none;
|
|
16690
16784
|
}
|
|
16691
|
-
const groupSiblings = this.db.select().from(runs).where(
|
|
16692
|
-
|
|
16693
|
-
|
|
16694
|
-
|
|
16785
|
+
const groupSiblings = this.db.select().from(runs).where(and25(
|
|
16786
|
+
eq29(runs.projectId, projectId),
|
|
16787
|
+
eq29(runs.kind, thisRun.kind),
|
|
16788
|
+
eq29(runs.createdAt, thisRun.createdAt),
|
|
16695
16789
|
notProbeRun()
|
|
16696
16790
|
)).all();
|
|
16697
16791
|
const stillPending = groupSiblings.some((r) => r.status === "queued" || r.status === "running");
|
|
16698
|
-
if (stillPending) return
|
|
16792
|
+
if (stillPending) return none;
|
|
16699
16793
|
const completedPartialSiblings = groupSiblings.filter(
|
|
16700
16794
|
(r) => r.status === "completed" || r.status === "partial"
|
|
16701
16795
|
);
|
|
16702
|
-
if (completedPartialSiblings.length === 0) return
|
|
16796
|
+
if (completedPartialSiblings.length === 0) return none;
|
|
16703
16797
|
const winner = completedPartialSiblings.reduce((best, candidate) => {
|
|
16704
16798
|
const candFinish = candidate.finishedAt ?? "";
|
|
16705
16799
|
const bestFinish = best.finishedAt ?? "";
|
|
@@ -16707,27 +16801,27 @@ var Notifier = class {
|
|
|
16707
16801
|
if (candFinish < bestFinish) return best;
|
|
16708
16802
|
return candidate.id > best.id ? candidate : best;
|
|
16709
16803
|
});
|
|
16710
|
-
if (winner.id !== runId) return
|
|
16711
|
-
|
|
16712
|
-
|
|
16713
|
-
|
|
16714
|
-
|
|
16715
|
-
);
|
|
16804
|
+
if (winner.id !== runId) return none;
|
|
16805
|
+
if (thisRun.measurementPlanVersionId !== null) {
|
|
16806
|
+
const advanced = this.advancedTransitions(runId, projectId);
|
|
16807
|
+
if (advanced !== null) return advanced;
|
|
16808
|
+
}
|
|
16809
|
+
const locationCount = Math.max(1, project.locations.length);
|
|
16716
16810
|
const RECENT_FETCH_LIMIT = Math.max(8, locationCount * 4);
|
|
16717
16811
|
const recentRuns = this.db.select().from(runs).where(
|
|
16718
|
-
|
|
16719
|
-
|
|
16720
|
-
|
|
16721
|
-
or2(
|
|
16812
|
+
and25(
|
|
16813
|
+
eq29(runs.projectId, projectId),
|
|
16814
|
+
eq29(runs.kind, thisRun.kind),
|
|
16815
|
+
or2(eq29(runs.status, "completed"), eq29(runs.status, "partial")),
|
|
16722
16816
|
notProbeRun()
|
|
16723
16817
|
)
|
|
16724
16818
|
).orderBy(desc10(runs.createdAt), desc10(runs.id)).limit(RECENT_FETCH_LIMIT).all();
|
|
16725
16819
|
const groups = groupRunsByCreatedAt(recentRuns);
|
|
16726
16820
|
const currentGroupIdx = groups.findIndex((g) => g[0]?.createdAt === thisRun.createdAt);
|
|
16727
|
-
if (currentGroupIdx < 0) return
|
|
16821
|
+
if (currentGroupIdx < 0) return none;
|
|
16728
16822
|
const currentGroup = groups[currentGroupIdx] ?? [];
|
|
16729
16823
|
const previousGroup = groups[currentGroupIdx + 1] ?? [];
|
|
16730
|
-
if (currentGroup.length === 0 || previousGroup.length === 0) return
|
|
16824
|
+
if (currentGroup.length === 0 || previousGroup.length === 0) return none;
|
|
16731
16825
|
const currentRunIds = currentGroup.map((r) => r.id);
|
|
16732
16826
|
const previousRunIds = previousGroup.map((r) => r.id);
|
|
16733
16827
|
const currentSnapshots = this.db.select({
|
|
@@ -16736,40 +16830,96 @@ var Notifier = class {
|
|
|
16736
16830
|
provider: querySnapshots.provider,
|
|
16737
16831
|
location: querySnapshots.location,
|
|
16738
16832
|
citationState: querySnapshots.citationState,
|
|
16739
|
-
retrievalStatus: querySnapshots.retrievalStatus
|
|
16740
|
-
|
|
16833
|
+
retrievalStatus: querySnapshots.retrievalStatus,
|
|
16834
|
+
answerText: querySnapshots.answerText,
|
|
16835
|
+
answerMentioned: querySnapshots.answerMentioned,
|
|
16836
|
+
mentionIdentity: querySnapshots.mentionIdentity
|
|
16837
|
+
}).from(querySnapshots).leftJoin(queries, eq29(querySnapshots.queryId, queries.id)).where(inArray13(querySnapshots.runId, currentRunIds)).all();
|
|
16741
16838
|
const previousSnapshots = this.db.select({
|
|
16742
16839
|
queryId: querySnapshots.queryId,
|
|
16743
16840
|
provider: querySnapshots.provider,
|
|
16744
16841
|
location: querySnapshots.location,
|
|
16745
16842
|
citationState: querySnapshots.citationState,
|
|
16746
|
-
retrievalStatus: querySnapshots.retrievalStatus
|
|
16747
|
-
|
|
16748
|
-
|
|
16843
|
+
retrievalStatus: querySnapshots.retrievalStatus,
|
|
16844
|
+
answerText: querySnapshots.answerText,
|
|
16845
|
+
answerMentioned: querySnapshots.answerMentioned,
|
|
16846
|
+
mentionIdentity: querySnapshots.mentionIdentity
|
|
16847
|
+
}).from(querySnapshots).where(inArray13(querySnapshots.runId, previousRunIds)).all();
|
|
16848
|
+
const citationState = (s) => {
|
|
16849
|
+
const state = readCitationState(s);
|
|
16850
|
+
return isCitationStateMeasured(state) ? state : null;
|
|
16851
|
+
};
|
|
16852
|
+
const observeMention = snapshotMentionObserver(project);
|
|
16853
|
+
const mentionState = (s) => {
|
|
16854
|
+
const mentioned = observeMention(s);
|
|
16855
|
+
return mentioned === null ? null : mentioned ? MentionStates.mentioned : MentionStates["not-mentioned"];
|
|
16856
|
+
};
|
|
16857
|
+
const prevCitation = /* @__PURE__ */ new Map();
|
|
16858
|
+
const prevMention = /* @__PURE__ */ new Map();
|
|
16749
16859
|
for (const s of previousSnapshots) {
|
|
16750
16860
|
if (s.queryId == null) continue;
|
|
16751
|
-
const
|
|
16752
|
-
|
|
16753
|
-
|
|
16754
|
-
|
|
16755
|
-
|
|
16861
|
+
const key = `${s.queryId}:${s.provider}:${s.location ?? ""}`;
|
|
16862
|
+
const cited = citationState(s);
|
|
16863
|
+
if (cited !== null) prevCitation.set(key, cited);
|
|
16864
|
+
const mentioned = mentionState(s);
|
|
16865
|
+
if (mentioned !== null) prevMention.set(key, mentioned);
|
|
16866
|
+
}
|
|
16867
|
+
const citation = [];
|
|
16868
|
+
const mention = [];
|
|
16869
|
+
const changedQueries = /* @__PURE__ */ new Map();
|
|
16756
16870
|
for (const s of currentSnapshots) {
|
|
16757
16871
|
if (s.queryId == null) continue;
|
|
16758
|
-
const state = readCitationState(s);
|
|
16759
|
-
if (!isCitationStateMeasured(state)) continue;
|
|
16760
16872
|
const key = `${s.queryId}:${s.provider}:${s.location ?? ""}`;
|
|
16761
|
-
const
|
|
16762
|
-
|
|
16763
|
-
|
|
16764
|
-
|
|
16765
|
-
|
|
16766
|
-
|
|
16767
|
-
|
|
16768
|
-
|
|
16769
|
-
|
|
16770
|
-
|
|
16873
|
+
const query = s.query ?? s.queryId;
|
|
16874
|
+
const tracked = { id: s.queryId, query };
|
|
16875
|
+
const change = (from, to) => {
|
|
16876
|
+
if (from === void 0 || from === to) return null;
|
|
16877
|
+
const transition = { query, from, to, provider: s.provider, location: s.location, queryClass: null };
|
|
16878
|
+
changedQueries.set(transition, tracked);
|
|
16879
|
+
return transition;
|
|
16880
|
+
};
|
|
16881
|
+
const cited = citationState(s);
|
|
16882
|
+
const citationChange = cited === null ? null : change(prevCitation.get(key), cited);
|
|
16883
|
+
if (citationChange) citation.push(citationChange);
|
|
16884
|
+
const mentioned = mentionState(s);
|
|
16885
|
+
const mentionChange = mentioned === null ? null : change(prevMention.get(key), mentioned);
|
|
16886
|
+
if (mentionChange) mention.push(mentionChange);
|
|
16771
16887
|
}
|
|
16772
|
-
|
|
16888
|
+
if (changedQueries.size > 0) {
|
|
16889
|
+
const classes = readQueryClasses(this.db, project, [...changedQueries.values()]);
|
|
16890
|
+
for (const [transition, tracked] of changedQueries) transition.queryClass = classes.get(tracked.id) ?? null;
|
|
16891
|
+
}
|
|
16892
|
+
return { citation, mention };
|
|
16893
|
+
}
|
|
16894
|
+
/**
|
|
16895
|
+
* The per-Property changes of a custom-portfolio sweep, or null when the
|
|
16896
|
+
* project has no schema v2 plan to read them from, in which case its
|
|
16897
|
+
* changes are the project-level ones.
|
|
16898
|
+
*/
|
|
16899
|
+
advancedTransitions(runId, projectId) {
|
|
16900
|
+
let read;
|
|
16901
|
+
try {
|
|
16902
|
+
read = readAdvancedSignalTransitions(this.db, projectId, runId);
|
|
16903
|
+
} catch (error) {
|
|
16904
|
+
log26.error("transitions.advanced-unreadable", { runId, error: describeError(error) });
|
|
16905
|
+
return { citation: [], mention: [] };
|
|
16906
|
+
}
|
|
16907
|
+
if (read === null) return null;
|
|
16908
|
+
if (read.state === "unavailable") {
|
|
16909
|
+
log26.info("transitions.advanced-not-comparable", { runId, reason: read.reason });
|
|
16910
|
+
return { citation: [], mention: [] };
|
|
16911
|
+
}
|
|
16912
|
+
const wire = (t) => ({
|
|
16913
|
+
query: t.query,
|
|
16914
|
+
from: t.from,
|
|
16915
|
+
to: t.to,
|
|
16916
|
+
provider: t.provider,
|
|
16917
|
+
location: t.location,
|
|
16918
|
+
queryClass: t.queryClass,
|
|
16919
|
+
property: t.property,
|
|
16920
|
+
markets: t.markets
|
|
16921
|
+
});
|
|
16922
|
+
return { citation: read.citation.map(wire), mention: read.mention.map(wire) };
|
|
16773
16923
|
}
|
|
16774
16924
|
/** True only when the destination accepted the payload. Callers that record "already said" must not count an attempt. */
|
|
16775
16925
|
/**
|
|
@@ -16793,12 +16943,12 @@ var Notifier = class {
|
|
|
16793
16943
|
recordUnrecognizedAgentDecisions(this.db, projectId, baseline, UnrecognizedAgentNotifyStates.baseline, now);
|
|
16794
16944
|
if (due.length === 0) continue;
|
|
16795
16945
|
const names = due.map((agent) => agent.name);
|
|
16796
|
-
const subscribed = this.db.select().from(notifications).where(
|
|
16946
|
+
const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("traffic.agent.discovered"));
|
|
16797
16947
|
if (subscribed.length === 0) {
|
|
16798
16948
|
recordUnrecognizedAgentDecisions(this.db, projectId, names, UnrecognizedAgentNotifyStates.skipped, now);
|
|
16799
16949
|
continue;
|
|
16800
16950
|
}
|
|
16801
|
-
const project = this.db.select().from(projects).where(
|
|
16951
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16802
16952
|
if (!project) continue;
|
|
16803
16953
|
const payload = {
|
|
16804
16954
|
source: "canonry",
|
|
@@ -16821,6 +16971,84 @@ var Notifier = class {
|
|
|
16821
16971
|
}
|
|
16822
16972
|
return sentNames;
|
|
16823
16973
|
}
|
|
16974
|
+
/**
|
|
16975
|
+
* Send `sentiment.unfavorable` for sweeps whose automatic sentiment work has
|
|
16976
|
+
* settled: one message per sweep listing the answers sentiment newly rates
|
|
16977
|
+
* unfavorable (`SentimentService.newlyUnfavorable`). A sweep is decided
|
|
16978
|
+
* once: `sent` when a webhook accepted it, `skipped` when nothing
|
|
16979
|
+
* subscribed, so subscribing later starts from new sweeps, `quiet` when no
|
|
16980
|
+
* answer turned, and `baseline` for what had settled before the project's
|
|
16981
|
+
* first pass. When every delivery fails the sweep stays undecided and the
|
|
16982
|
+
* next pass retries it while its sentiment jobs are inside the window; so
|
|
16983
|
+
* does a sweep read while sentiment is off, which says nothing about it.
|
|
16984
|
+
* Returns how many sweeps were sent.
|
|
16985
|
+
*/
|
|
16986
|
+
async dispatchSentimentAlerts(now = Date.now()) {
|
|
16987
|
+
if (this.sentimentInstall === null || this.sentimentDispatchInFlight) return 0;
|
|
16988
|
+
this.sentimentDispatchInFlight = true;
|
|
16989
|
+
let sentRuns = 0;
|
|
16990
|
+
try {
|
|
16991
|
+
const service = new SentimentService(this.db, { install: this.sentimentInstall, previewSecret: crypto25.randomUUID() });
|
|
16992
|
+
const settledRuns = settledSentimentRuns(this.db, now);
|
|
16993
|
+
const inWindow = new Set([...settledRuns.values()].flat());
|
|
16994
|
+
for (const runId of this.undeliveredSentimentAlerts.keys()) if (!inWindow.has(runId)) this.undeliveredSentimentAlerts.delete(runId);
|
|
16995
|
+
for (const [projectId, settled] of settledRuns) {
|
|
16996
|
+
const { undecided, firstPass } = undecidedSentimentRuns(this.db, projectId, settled);
|
|
16997
|
+
if (undecided.length === 0) continue;
|
|
16998
|
+
if (firstPass) {
|
|
16999
|
+
recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.baseline, now);
|
|
17000
|
+
continue;
|
|
17001
|
+
}
|
|
17002
|
+
const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("sentiment.unfavorable"));
|
|
17003
|
+
if (subscribed.length === 0) {
|
|
17004
|
+
recordSentimentAlertRuns(this.db, projectId, undecided, SentimentAlertStates.skipped, now);
|
|
17005
|
+
continue;
|
|
17006
|
+
}
|
|
17007
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
17008
|
+
if (!project) continue;
|
|
17009
|
+
for (const runId of undecided) {
|
|
17010
|
+
let answers = this.undeliveredSentimentAlerts.get(runId) ?? null;
|
|
17011
|
+
if (answers === null) {
|
|
17012
|
+
try {
|
|
17013
|
+
answers = service.newlyUnfavorable(projectId, runId);
|
|
17014
|
+
} catch (error) {
|
|
17015
|
+
log26.error("sentiment-alerts.unreadable", { projectId, runId, error: describeError(error) });
|
|
17016
|
+
continue;
|
|
17017
|
+
}
|
|
17018
|
+
}
|
|
17019
|
+
if (answers === null) continue;
|
|
17020
|
+
if (answers.length === 0) {
|
|
17021
|
+
recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.quiet, now);
|
|
17022
|
+
continue;
|
|
17023
|
+
}
|
|
17024
|
+
const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
|
|
17025
|
+
if (!run) continue;
|
|
17026
|
+
const payload = {
|
|
17027
|
+
source: "canonry",
|
|
17028
|
+
event: "sentiment.unfavorable",
|
|
17029
|
+
project: { name: project.name, canonicalDomain: project.canonicalDomain },
|
|
17030
|
+
run: { id: run.id, status: run.status, finishedAt: run.finishedAt },
|
|
17031
|
+
answers,
|
|
17032
|
+
dashboardUrl: `${this.serverUrl}/projects/${project.name}`
|
|
17033
|
+
};
|
|
17034
|
+
let accepted = false;
|
|
17035
|
+
for (const notif of subscribed) {
|
|
17036
|
+
if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
|
|
17037
|
+
}
|
|
17038
|
+
if (accepted) {
|
|
17039
|
+
recordSentimentAlertRuns(this.db, projectId, [runId], SentimentAlertStates.sent, now);
|
|
17040
|
+
this.undeliveredSentimentAlerts.delete(runId);
|
|
17041
|
+
sentRuns++;
|
|
17042
|
+
} else {
|
|
17043
|
+
this.undeliveredSentimentAlerts.set(runId, answers);
|
|
17044
|
+
}
|
|
17045
|
+
}
|
|
17046
|
+
}
|
|
17047
|
+
} finally {
|
|
17048
|
+
this.sentimentDispatchInFlight = false;
|
|
17049
|
+
}
|
|
17050
|
+
return sentRuns;
|
|
17051
|
+
}
|
|
16824
17052
|
/**
|
|
16825
17053
|
* After a site audit, send `site-health.issue.new` to the webhooks that list
|
|
16826
17054
|
* it when the scan found a critical page problem on a page where it was not
|
|
@@ -16837,12 +17065,12 @@ var Notifier = class {
|
|
|
16837
17065
|
* observable in tests.
|
|
16838
17066
|
*/
|
|
16839
17067
|
async onSiteAuditCompleted(runId, projectId) {
|
|
16840
|
-
const run = this.db.select().from(runs).where(
|
|
17068
|
+
const run = this.db.select().from(runs).where(eq29(runs.id, runId)).get();
|
|
16841
17069
|
if (!run || run.kind !== RunKinds["site-audit"]) return null;
|
|
16842
17070
|
if (run.status !== RunStatuses.completed && run.status !== RunStatuses.partial) return null;
|
|
16843
|
-
const subscribed = this.db.select().from(notifications).where(
|
|
17071
|
+
const subscribed = this.db.select().from(notifications).where(eq29(notifications.projectId, projectId)).all().filter((n) => n.enabled && n.config.url && n.config.events.includes("site-health.issue.new"));
|
|
16844
17072
|
if (subscribed.length === 0) return null;
|
|
16845
|
-
const project = this.db.select().from(projects).where(
|
|
17073
|
+
const project = this.db.select().from(projects).where(eq29(projects.id, projectId)).get();
|
|
16846
17074
|
if (!project) return null;
|
|
16847
17075
|
const scan = readSiteHealthScan(this.db, projectId, runId);
|
|
16848
17076
|
if (!scan) return null;
|
|
@@ -16876,7 +17104,7 @@ var Notifier = class {
|
|
|
16876
17104
|
if (await this.sendWebhook(notif.config.url, payload, notif.id, projectId, notif.webhookSecret ?? null)) accepted = true;
|
|
16877
17105
|
}
|
|
16878
17106
|
if (!accepted) {
|
|
16879
|
-
|
|
17107
|
+
log26.info("site-health.alert-owed", { runId, projectId, issues: issues.length });
|
|
16880
17108
|
return null;
|
|
16881
17109
|
}
|
|
16882
17110
|
writeSiteHealthNotifyState(this.db, {
|
|
@@ -16896,7 +17124,7 @@ var Notifier = class {
|
|
|
16896
17124
|
const targetLabel = redactNotificationUrl(url).urlDisplay;
|
|
16897
17125
|
const targetCheck = await resolveWebhookTarget(url, { allowLoopback: this.allowLoopbackWebhooks });
|
|
16898
17126
|
if (!targetCheck.ok) {
|
|
16899
|
-
|
|
17127
|
+
log26.error("webhook.ssrf-blocked", { url: targetLabel, reason: targetCheck.message });
|
|
16900
17128
|
this.logDelivery(projectId, notificationId, payload.event, "failed", `SSRF: ${targetCheck.message}`);
|
|
16901
17129
|
const reasonCode = webhookTargetRefusalReason(targetCheck);
|
|
16902
17130
|
trackWebhookDelivery({
|
|
@@ -16909,7 +17137,7 @@ var Notifier = class {
|
|
|
16909
17137
|
});
|
|
16910
17138
|
return false;
|
|
16911
17139
|
}
|
|
16912
|
-
|
|
17140
|
+
log26.info("webhook.send", { event: payload.event, url: targetLabel });
|
|
16913
17141
|
const maxRetries = 3;
|
|
16914
17142
|
const delays = [1e3, 4e3, 16e3];
|
|
16915
17143
|
let lastStatusClass = "network";
|
|
@@ -16918,13 +17146,13 @@ var Notifier = class {
|
|
|
16918
17146
|
try {
|
|
16919
17147
|
const response = await deliverWebhook(targetCheck.target, body, signingSecret);
|
|
16920
17148
|
if (response.status >= 200 && response.status < 300) {
|
|
16921
|
-
|
|
17149
|
+
log26.info("webhook.delivered", { event: payload.event, url: targetLabel, httpStatus: response.status });
|
|
16922
17150
|
this.logDelivery(projectId, notificationId, payload.event, "sent", null);
|
|
16923
17151
|
trackWebhookDelivery({ url, event: payload.event, attempts: attempt + 1, durationBucket: elapsed(), statusClass: "2xx" });
|
|
16924
17152
|
return true;
|
|
16925
17153
|
}
|
|
16926
17154
|
const errorDetail = response.error ?? `HTTP ${response.status}`;
|
|
16927
|
-
|
|
17155
|
+
log26.warn("webhook.attempt-failed", { event: payload.event, url: targetLabel, attempt: attempt + 1, maxRetries, httpStatus: response.status, error: errorDetail });
|
|
16928
17156
|
lastStatusClass = response.status === 0 && response.timedOut ? "timeout" : statusClassOf(response.status);
|
|
16929
17157
|
lastFailure = { reasonCode: webhookResponseReason(response) ?? "UNKNOWN" };
|
|
16930
17158
|
if (attempt === maxRetries - 1) {
|
|
@@ -16936,7 +17164,7 @@ var Notifier = class {
|
|
|
16936
17164
|
lastFailure = outcomeFailure(err);
|
|
16937
17165
|
if (attempt === maxRetries - 1) {
|
|
16938
17166
|
this.logDelivery(projectId, notificationId, payload.event, "failed", errorDetail);
|
|
16939
|
-
|
|
17167
|
+
log26.error("webhook.exhausted", { event: payload.event, url: targetLabel, maxRetries, error: errorDetail });
|
|
16940
17168
|
}
|
|
16941
17169
|
}
|
|
16942
17170
|
if (attempt < maxRetries - 1) {
|
|
@@ -16968,8 +17196,8 @@ var Notifier = class {
|
|
|
16968
17196
|
};
|
|
16969
17197
|
|
|
16970
17198
|
// src/run-coordinator.ts
|
|
16971
|
-
import { eq as
|
|
16972
|
-
var
|
|
17199
|
+
import { eq as eq30 } from "drizzle-orm";
|
|
17200
|
+
var log27 = createLogger("RunCoordinator");
|
|
16973
17201
|
function reportInsightsGenerated(runTrigger, outcome) {
|
|
16974
17202
|
trackFeatureCompleted({
|
|
16975
17203
|
feature: "insights",
|
|
@@ -17002,22 +17230,22 @@ var RunCoordinator = class {
|
|
|
17002
17230
|
*/
|
|
17003
17231
|
onAnswersRecorded;
|
|
17004
17232
|
async onRunCompleted(runId, projectId, opts) {
|
|
17005
|
-
const runRow = this.db.select().from(runs).where(
|
|
17233
|
+
const runRow = this.db.select().from(runs).where(eq30(runs.id, runId)).get();
|
|
17006
17234
|
const kind = runRow?.kind ?? RunKinds["answer-visibility"];
|
|
17007
17235
|
if (runRow?.trigger === RunTriggers.probe) {
|
|
17008
|
-
|
|
17236
|
+
log27.info("probe.skip-side-effects", { runId, projectId, kind });
|
|
17009
17237
|
return;
|
|
17010
17238
|
}
|
|
17011
17239
|
if (kind === RunKinds["answer-visibility"] && (runRow?.status === RunStatuses.completed || runRow?.status === RunStatuses.partial) && this.onAnswersRecorded) {
|
|
17012
17240
|
try {
|
|
17013
17241
|
await this.onAnswersRecorded(runId, projectId);
|
|
17014
17242
|
} catch (err) {
|
|
17015
|
-
|
|
17243
|
+
log27.error("answers-recorded.failed", { runId, projectId, error: describeError(err) });
|
|
17016
17244
|
}
|
|
17017
17245
|
}
|
|
17018
17246
|
const completeness = measurementRunCompleteness(this.db, runId);
|
|
17019
17247
|
if (completeness.planned && !completeness.complete) {
|
|
17020
|
-
|
|
17248
|
+
log27.info("measurement.incomplete-skip-derived", {
|
|
17021
17249
|
runId,
|
|
17022
17250
|
projectId,
|
|
17023
17251
|
executed: completeness.executed,
|
|
@@ -17026,7 +17254,7 @@ var RunCoordinator = class {
|
|
|
17026
17254
|
try {
|
|
17027
17255
|
await this.notifier.onRunCompleted(runId, projectId);
|
|
17028
17256
|
} catch (err) {
|
|
17029
|
-
|
|
17257
|
+
log27.error("notifier.failed", { runId, error: describeError(err) });
|
|
17030
17258
|
}
|
|
17031
17259
|
return;
|
|
17032
17260
|
}
|
|
@@ -17034,7 +17262,7 @@ var RunCoordinator = class {
|
|
|
17034
17262
|
try {
|
|
17035
17263
|
await this.onSentimentCompleted(runId, projectId);
|
|
17036
17264
|
} catch {
|
|
17037
|
-
|
|
17265
|
+
log27.error("sentiment.wakeup-failed", { runId, projectId });
|
|
17038
17266
|
}
|
|
17039
17267
|
}
|
|
17040
17268
|
let insightCount = 0;
|
|
@@ -17054,12 +17282,12 @@ var RunCoordinator = class {
|
|
|
17054
17282
|
try {
|
|
17055
17283
|
await this.onInsightsGenerated(runId, projectId, result);
|
|
17056
17284
|
} catch (err) {
|
|
17057
|
-
|
|
17285
|
+
log27.error("insight-webhook.failed", { runId, error: describeError(err) });
|
|
17058
17286
|
}
|
|
17059
17287
|
}
|
|
17060
17288
|
}
|
|
17061
17289
|
} catch (err) {
|
|
17062
|
-
|
|
17290
|
+
log27.error("intelligence.failed", { runId, error: describeError(err) });
|
|
17063
17291
|
insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
|
|
17064
17292
|
}
|
|
17065
17293
|
reportInsightsGenerated(runRow?.trigger, insightsOutcome);
|
|
@@ -17077,30 +17305,30 @@ var RunCoordinator = class {
|
|
|
17077
17305
|
try {
|
|
17078
17306
|
await this.onInsightsGenerated(runId, projectId, analysisResultFromInsights(gbpInsights));
|
|
17079
17307
|
} catch (err) {
|
|
17080
|
-
|
|
17308
|
+
log27.error("gbp-insight-webhook.failed", { runId, error: describeError(err) });
|
|
17081
17309
|
}
|
|
17082
17310
|
}
|
|
17083
17311
|
} catch (err) {
|
|
17084
|
-
|
|
17312
|
+
log27.error("gbp-intelligence.failed", { runId, error: describeError(err) });
|
|
17085
17313
|
insightsOutcome = { status: OutcomeStatuses.failed, ...outcomeFailure(err), durationBucket: elapsed() };
|
|
17086
17314
|
}
|
|
17087
17315
|
reportInsightsGenerated(runRow?.trigger, insightsOutcome);
|
|
17088
17316
|
try {
|
|
17089
17317
|
await this.notifier.dispatchReviewAlerts(projectId);
|
|
17090
17318
|
} catch (err) {
|
|
17091
|
-
|
|
17319
|
+
log27.error("review-webhook.failed", { runId, error: describeError(err) });
|
|
17092
17320
|
}
|
|
17093
17321
|
}
|
|
17094
17322
|
try {
|
|
17095
17323
|
await (opts ? this.notifier.onRunCompleted(runId, projectId, opts) : this.notifier.onRunCompleted(runId, projectId));
|
|
17096
17324
|
} catch (err) {
|
|
17097
|
-
|
|
17325
|
+
log27.error("notifier.failed", { runId, error: describeError(err) });
|
|
17098
17326
|
}
|
|
17099
17327
|
if (kind === RunKinds["site-audit"]) {
|
|
17100
17328
|
try {
|
|
17101
17329
|
await this.notifier.onSiteAuditCompleted(runId, projectId);
|
|
17102
17330
|
} catch (err) {
|
|
17103
|
-
|
|
17331
|
+
log27.error("site-health-webhook.failed", { runId, error: describeError(err) });
|
|
17104
17332
|
}
|
|
17105
17333
|
}
|
|
17106
17334
|
if (this.onAeroEvent) {
|
|
@@ -17114,7 +17342,7 @@ var RunCoordinator = class {
|
|
|
17114
17342
|
};
|
|
17115
17343
|
await this.onAeroEvent(ctx);
|
|
17116
17344
|
} catch (err) {
|
|
17117
|
-
|
|
17345
|
+
log27.error("aero.failed", { runId, error: describeError(err) });
|
|
17118
17346
|
}
|
|
17119
17347
|
}
|
|
17120
17348
|
}
|
|
@@ -17129,7 +17357,7 @@ var RunCoordinator = class {
|
|
|
17129
17357
|
* so the Aero queue is never starved of a follow-up.
|
|
17130
17358
|
*/
|
|
17131
17359
|
buildDiscoveryAeroContext(runId, projectId, status, error) {
|
|
17132
|
-
const session = this.db.select().from(discoverySessions).where(
|
|
17360
|
+
const session = this.db.select().from(discoverySessions).where(eq30(discoverySessions.runId, runId)).get();
|
|
17133
17361
|
const competitorMap = session ? session.competitorMap : [];
|
|
17134
17362
|
return {
|
|
17135
17363
|
kind: RunKinds["aeo-discover-probe"],
|
|
@@ -17173,12 +17401,12 @@ function analysisResultFromInsights(insights2) {
|
|
|
17173
17401
|
|
|
17174
17402
|
// src/agent/session-registry.ts
|
|
17175
17403
|
import crypto27 from "crypto";
|
|
17176
|
-
import { and as
|
|
17404
|
+
import { and as and28, eq as eq33, gt as gt4, lte as lte3 } from "drizzle-orm";
|
|
17177
17405
|
|
|
17178
17406
|
// src/agent/remote-mcp.ts
|
|
17179
17407
|
import { Type } from "@earendil-works/pi-ai";
|
|
17180
17408
|
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
17181
|
-
var
|
|
17409
|
+
var log28 = createLogger("RemoteMcp");
|
|
17182
17410
|
var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([]);
|
|
17183
17411
|
async function connectStreamableHttp(server) {
|
|
17184
17412
|
const transport = new StreamableHTTPClientTransport(new URL(server.url), {
|
|
@@ -17246,7 +17474,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17246
17474
|
try {
|
|
17247
17475
|
client = await connect(server);
|
|
17248
17476
|
} catch (err) {
|
|
17249
|
-
|
|
17477
|
+
log28.error("external-mcp.connect-failed", {
|
|
17250
17478
|
label,
|
|
17251
17479
|
error: describeError(err)
|
|
17252
17480
|
});
|
|
@@ -17256,7 +17484,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17256
17484
|
try {
|
|
17257
17485
|
listed = await client.listTools();
|
|
17258
17486
|
} catch (err) {
|
|
17259
|
-
|
|
17487
|
+
log28.error("external-mcp.list-failed", {
|
|
17260
17488
|
label,
|
|
17261
17489
|
error: describeError(err)
|
|
17262
17490
|
});
|
|
@@ -17267,7 +17495,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17267
17495
|
if (!isReadOnly(tool)) continue;
|
|
17268
17496
|
tools.push(adaptRemoteTool(client, tool));
|
|
17269
17497
|
}
|
|
17270
|
-
|
|
17498
|
+
log28.info("external-mcp.loaded", {
|
|
17271
17499
|
label,
|
|
17272
17500
|
discovered: listed.tools.length,
|
|
17273
17501
|
adopted: tools.length
|
|
@@ -17278,7 +17506,7 @@ async function loadExternalMcpTools(servers, opts = {}) {
|
|
|
17278
17506
|
|
|
17279
17507
|
// src/agent/memory-store.ts
|
|
17280
17508
|
import crypto26 from "crypto";
|
|
17281
|
-
import { and as
|
|
17509
|
+
import { and as and26, desc as desc11, eq as eq31, like, sql as sql13, or as or3 } from "drizzle-orm";
|
|
17282
17510
|
var COMPACTION_KEY_PREFIX = "compaction:";
|
|
17283
17511
|
var COMPACTION_NOTES_PER_SESSION = 3;
|
|
17284
17512
|
function rowToDto(row) {
|
|
@@ -17292,7 +17520,7 @@ function rowToDto(row) {
|
|
|
17292
17520
|
};
|
|
17293
17521
|
}
|
|
17294
17522
|
function listMemoryEntries(db, projectId, opts = {}) {
|
|
17295
|
-
const query = db.select().from(agentMemory).where(
|
|
17523
|
+
const query = db.select().from(agentMemory).where(eq31(agentMemory.projectId, projectId)).orderBy(desc11(agentMemory.updatedAt));
|
|
17296
17524
|
const rows = opts.limit === void 0 ? query.all() : query.limit(opts.limit).all();
|
|
17297
17525
|
return rows.map(rowToDto);
|
|
17298
17526
|
}
|
|
@@ -17323,21 +17551,21 @@ function upsertMemoryEntry(db, args) {
|
|
|
17323
17551
|
updatedAt: now
|
|
17324
17552
|
}
|
|
17325
17553
|
}).run();
|
|
17326
|
-
const row = db.select().from(agentMemory).where(
|
|
17554
|
+
const row = db.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, args.key))).get();
|
|
17327
17555
|
if (!row) throw new Error("memory upsert produced no row");
|
|
17328
17556
|
return rowToDto(row);
|
|
17329
17557
|
}
|
|
17330
17558
|
function deleteMemoryEntry(db, projectId, key) {
|
|
17331
|
-
const result = db.delete(agentMemory).where(
|
|
17559
|
+
const result = db.delete(agentMemory).where(and26(eq31(agentMemory.projectId, projectId), eq31(agentMemory.key, key))).run();
|
|
17332
17560
|
const changes = result.changes ?? 0;
|
|
17333
17561
|
return changes > 0;
|
|
17334
17562
|
}
|
|
17335
17563
|
function loadRecentForHydrate(db, projectId, limit, sessionId) {
|
|
17336
17564
|
if (sessionId === void 0) return listMemoryEntries(db, projectId, { limit });
|
|
17337
17565
|
const sessionPrefix = `compaction:${sessionId ?? ""}:`;
|
|
17338
|
-
return db.select().from(agentMemory).where(
|
|
17339
|
-
|
|
17340
|
-
or3(
|
|
17566
|
+
return db.select().from(agentMemory).where(and26(
|
|
17567
|
+
eq31(agentMemory.projectId, projectId),
|
|
17568
|
+
or3(sql13`substr(${agentMemory.key}, 1, ${COMPACTION_KEY_PREFIX.length}) <> ${COMPACTION_KEY_PREFIX}`, sessionId ? sql13`substr(${agentMemory.key}, 1, ${sessionPrefix.length}) = ${sessionPrefix}` : void 0)
|
|
17341
17569
|
)).orderBy(desc11(agentMemory.updatedAt)).limit(limit).all().map(rowToDto);
|
|
17342
17570
|
}
|
|
17343
17571
|
function writeCompactionNote(db, args) {
|
|
@@ -17362,16 +17590,16 @@ function writeCompactionNote(db, args) {
|
|
|
17362
17590
|
}).run();
|
|
17363
17591
|
const sessionPrefix = `${COMPACTION_KEY_PREFIX}${args.sessionId}:`;
|
|
17364
17592
|
const existing = tx.select({ id: agentMemory.id, updatedAt: agentMemory.updatedAt }).from(agentMemory).where(
|
|
17365
|
-
|
|
17366
|
-
|
|
17593
|
+
and26(
|
|
17594
|
+
eq31(agentMemory.projectId, args.projectId),
|
|
17367
17595
|
like(agentMemory.key, `${sessionPrefix}%`)
|
|
17368
17596
|
)
|
|
17369
17597
|
).orderBy(desc11(agentMemory.updatedAt)).all();
|
|
17370
17598
|
const stale = existing.slice(COMPACTION_NOTES_PER_SESSION).map((r) => r.id);
|
|
17371
17599
|
if (stale.length > 0) {
|
|
17372
|
-
tx.delete(agentMemory).where(
|
|
17600
|
+
tx.delete(agentMemory).where(sql13`${agentMemory.id} IN (${sql13.join(stale.map((s) => sql13`${s}`), sql13`, `)})`).run();
|
|
17373
17601
|
}
|
|
17374
|
-
const row = tx.select().from(agentMemory).where(
|
|
17602
|
+
const row = tx.select().from(agentMemory).where(and26(eq31(agentMemory.projectId, args.projectId), eq31(agentMemory.key, key))).get();
|
|
17375
17603
|
if (row) inserted = rowToDto(row);
|
|
17376
17604
|
});
|
|
17377
17605
|
if (!inserted) throw new Error("compaction note write produced no row");
|
|
@@ -17379,7 +17607,7 @@ function writeCompactionNote(db, args) {
|
|
|
17379
17607
|
}
|
|
17380
17608
|
|
|
17381
17609
|
// src/agent/turn-telemetry.ts
|
|
17382
|
-
var
|
|
17610
|
+
var log29 = createLogger("AeroTurn");
|
|
17383
17611
|
var PROVIDER_ERROR_REASONS = {
|
|
17384
17612
|
PROVIDER_AUTH: "INVALID_CREDENTIALS",
|
|
17385
17613
|
PROVIDER_BILLING: "BILLING",
|
|
@@ -17435,7 +17663,7 @@ function trackAeroTurn(agent, turn) {
|
|
|
17435
17663
|
phase: turn.phase ?? (turn.error === void 0 && agent.state.errorMessage ? OutcomePhases["provider-request"] : OutcomePhases.unknown)
|
|
17436
17664
|
});
|
|
17437
17665
|
const outcome = turnOutcome(turn.error === void 0 ? status.reason : "error", turn.error, agent.state.errorMessage);
|
|
17438
|
-
|
|
17666
|
+
log29.info("completed", {
|
|
17439
17667
|
operationId,
|
|
17440
17668
|
projectId: turn.projectId,
|
|
17441
17669
|
provider: modelProvider,
|
|
@@ -17463,7 +17691,7 @@ function trackAeroTurn(agent, turn) {
|
|
|
17463
17691
|
}
|
|
17464
17692
|
|
|
17465
17693
|
// src/agent/project-shape.ts
|
|
17466
|
-
import { and as
|
|
17694
|
+
import { and as and27, count as count5, eq as eq32 } from "drizzle-orm";
|
|
17467
17695
|
var ADVANCED_TOOLS = [
|
|
17468
17696
|
"canonry_measurement_portfolio_summary",
|
|
17469
17697
|
"canonry_measurement_overview",
|
|
@@ -17490,10 +17718,10 @@ var ADVANCED_ROUTES = [
|
|
|
17490
17718
|
];
|
|
17491
17719
|
function aeroProjectShape(db, projectId) {
|
|
17492
17720
|
try {
|
|
17493
|
-
const pointer = db.select().from(measurementPlans).where(
|
|
17494
|
-
const version = pointer ? db.select().from(measurementPlanVersions).where(
|
|
17495
|
-
|
|
17496
|
-
|
|
17721
|
+
const pointer = db.select().from(measurementPlans).where(eq32(measurementPlans.projectId, projectId)).get();
|
|
17722
|
+
const version = pointer ? db.select().from(measurementPlanVersions).where(and27(
|
|
17723
|
+
eq32(measurementPlanVersions.projectId, projectId),
|
|
17724
|
+
eq32(measurementPlanVersions.id, pointer.activeVersionId)
|
|
17497
17725
|
)).get() : void 0;
|
|
17498
17726
|
if (version) {
|
|
17499
17727
|
const plan = JSON.parse(version.canonicalJson);
|
|
@@ -17520,7 +17748,7 @@ canonry_visibility_report describes the whole project, not one Property. canonry
|
|
|
17520
17748
|
pinned: ADVANCED_TOOLS
|
|
17521
17749
|
};
|
|
17522
17750
|
}
|
|
17523
|
-
const tracked = db.select({ total: count5() }).from(queries).where(
|
|
17751
|
+
const tracked = db.select({ total: count5() }).from(queries).where(eq32(queries.projectId, projectId)).get()?.total ?? 0;
|
|
17524
17752
|
return {
|
|
17525
17753
|
prompt: `
|
|
17526
17754
|
|
|
@@ -17660,7 +17888,7 @@ async function compactMessages(args) {
|
|
|
17660
17888
|
}
|
|
17661
17889
|
|
|
17662
17890
|
// src/agent/session-registry.ts
|
|
17663
|
-
var
|
|
17891
|
+
var log30 = createLogger("SessionRegistry");
|
|
17664
17892
|
var MAX_HYDRATE_NOTES = 20;
|
|
17665
17893
|
var PROVIDER_ACCOUNT_COOLDOWN_MS = 24 * 60 * 60 * 1e3;
|
|
17666
17894
|
var MAX_HYDRATE_BYTES = 32 * 1024;
|
|
@@ -17722,7 +17950,7 @@ var SessionRegistry = class {
|
|
|
17722
17950
|
if (!this.externalToolsPromise) {
|
|
17723
17951
|
this.externalToolsPromise = loadExternalMcpTools(this.opts.config.externalMcpServers).catch(
|
|
17724
17952
|
(err) => {
|
|
17725
|
-
|
|
17953
|
+
log30.error("external-mcp.load-failed", {
|
|
17726
17954
|
error: describeError(err)
|
|
17727
17955
|
});
|
|
17728
17956
|
return [];
|
|
@@ -17798,7 +18026,7 @@ var SessionRegistry = class {
|
|
|
17798
18026
|
modelProvider: effectiveProvider,
|
|
17799
18027
|
modelId: effectiveModelId,
|
|
17800
18028
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
17801
|
-
}).where(
|
|
18029
|
+
}).where(eq33(agentSessions.projectId, projectId)).run();
|
|
17802
18030
|
}
|
|
17803
18031
|
const agent2 = createAeroSession({
|
|
17804
18032
|
projectName,
|
|
@@ -18017,13 +18245,13 @@ ${lines.join("\n")}
|
|
|
18017
18245
|
agent.state.messages = result.messages;
|
|
18018
18246
|
setAeroSystemPrompt(agent, this.buildHydratedSystemPrompt(projectId, row.systemPrompt));
|
|
18019
18247
|
this.save(projectName);
|
|
18020
|
-
|
|
18248
|
+
log30.info("compaction.completed", {
|
|
18021
18249
|
projectName,
|
|
18022
18250
|
removedCount: result.removedCount,
|
|
18023
18251
|
summaryBytes: Buffer.byteLength(result.summary, "utf8")
|
|
18024
18252
|
});
|
|
18025
18253
|
} catch (err) {
|
|
18026
|
-
|
|
18254
|
+
log30.error("compaction.failed", {
|
|
18027
18255
|
projectName,
|
|
18028
18256
|
error: describeError(err)
|
|
18029
18257
|
});
|
|
@@ -18117,7 +18345,7 @@ ${lines.join("\n")}
|
|
|
18117
18345
|
modelProvider: nextProvider,
|
|
18118
18346
|
modelId: nextModelId,
|
|
18119
18347
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
18120
|
-
}).where(
|
|
18348
|
+
}).where(eq33(agentSessions.projectId, projectId)).run();
|
|
18121
18349
|
}
|
|
18122
18350
|
/** Snapshot pending work without consuming it before an atomic conversation switch. */
|
|
18123
18351
|
prepareConversationChange(projectName) {
|
|
@@ -18205,7 +18433,7 @@ ${lines.join("\n")}
|
|
|
18205
18433
|
}
|
|
18206
18434
|
trackAeroTurn(agent, { trigger: OutcomeTriggers.agent, projectId });
|
|
18207
18435
|
} catch (err) {
|
|
18208
|
-
|
|
18436
|
+
log30.error("drain.failed", {
|
|
18209
18437
|
projectName,
|
|
18210
18438
|
error: describeError(err)
|
|
18211
18439
|
});
|
|
@@ -18327,9 +18555,9 @@ ${lines.join("\n")}
|
|
|
18327
18555
|
persisted = true;
|
|
18328
18556
|
} catch (error) {
|
|
18329
18557
|
this.providerCooldownFallbacks.set(accountKey, cooldown);
|
|
18330
|
-
|
|
18558
|
+
log30.warn("provider.background-pause.persist-failed", { projectName, error: describeError(error) });
|
|
18331
18559
|
}
|
|
18332
|
-
|
|
18560
|
+
log30.warn("provider.background-paused", {
|
|
18333
18561
|
projectName,
|
|
18334
18562
|
provider: agent.state.model.provider,
|
|
18335
18563
|
reason,
|
|
@@ -18340,14 +18568,14 @@ ${lines.join("\n")}
|
|
|
18340
18568
|
} else if (aeroTurnStatus(agent)?.reason === "completed" && durableKnown && (fallbackFailureId || durableFailureId) && this.providerCooldownFallbacks.get(accountKey)?.failureId === fallbackFailureId) {
|
|
18341
18569
|
try {
|
|
18342
18570
|
if (durableFailureId) {
|
|
18343
|
-
this.opts.db.delete(agentProviderCooldowns).where(
|
|
18344
|
-
|
|
18345
|
-
|
|
18571
|
+
this.opts.db.delete(agentProviderCooldowns).where(and28(
|
|
18572
|
+
eq33(agentProviderCooldowns.accountKey, accountKey),
|
|
18573
|
+
eq33(agentProviderCooldowns.failureId, durableFailureId)
|
|
18346
18574
|
)).run();
|
|
18347
18575
|
}
|
|
18348
18576
|
this.providerCooldownFallbacks.delete(accountKey);
|
|
18349
18577
|
} catch (error) {
|
|
18350
|
-
|
|
18578
|
+
log30.warn("provider.background-pause.clear-failed", { projectName, error: describeError(error) });
|
|
18351
18579
|
}
|
|
18352
18580
|
}
|
|
18353
18581
|
}
|
|
@@ -18376,13 +18604,13 @@ ${lines.join("\n")}
|
|
|
18376
18604
|
}
|
|
18377
18605
|
const fallback = this.providerCooldownFallbacks.get(accountKey);
|
|
18378
18606
|
try {
|
|
18379
|
-
const durable = this.opts.db.select().from(agentProviderCooldowns).where(
|
|
18380
|
-
|
|
18607
|
+
const durable = this.opts.db.select().from(agentProviderCooldowns).where(and28(
|
|
18608
|
+
eq33(agentProviderCooldowns.accountKey, accountKey),
|
|
18381
18609
|
gt4(agentProviderCooldowns.retryAt, Date.now())
|
|
18382
18610
|
)).get();
|
|
18383
18611
|
return { fallback, durable };
|
|
18384
18612
|
} catch (error) {
|
|
18385
|
-
|
|
18613
|
+
log30.warn("provider.background-pause.read-failed", { error: describeError(error) });
|
|
18386
18614
|
return { fallback, durable: null };
|
|
18387
18615
|
}
|
|
18388
18616
|
}
|
|
@@ -18396,11 +18624,11 @@ ${lines.join("\n")}
|
|
|
18396
18624
|
return id;
|
|
18397
18625
|
}
|
|
18398
18626
|
tryResolveProjectId(projectName) {
|
|
18399
|
-
const row = this.opts.db.select({ id: projects.id }).from(projects).where(
|
|
18627
|
+
const row = this.opts.db.select({ id: projects.id }).from(projects).where(eq33(projects.name, projectName)).get();
|
|
18400
18628
|
return row?.id;
|
|
18401
18629
|
}
|
|
18402
18630
|
loadRow(projectId) {
|
|
18403
|
-
const row = this.opts.db.select().from(agentSessions).where(
|
|
18631
|
+
const row = this.opts.db.select().from(agentSessions).where(eq33(agentSessions.projectId, projectId)).get();
|
|
18404
18632
|
return row ?? null;
|
|
18405
18633
|
}
|
|
18406
18634
|
insertRow(params) {
|
|
@@ -18420,7 +18648,7 @@ ${lines.join("\n")}
|
|
|
18420
18648
|
}
|
|
18421
18649
|
updateRow(projectId, patch) {
|
|
18422
18650
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
18423
|
-
this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(
|
|
18651
|
+
this.opts.db.update(agentSessions).set({ ...patch, updatedAt: now }).where(eq33(agentSessions.projectId, projectId)).run();
|
|
18424
18652
|
}
|
|
18425
18653
|
/**
|
|
18426
18654
|
* Store a refreshed prompt snapshot without touching `updatedAt`, which the
|
|
@@ -18429,13 +18657,13 @@ ${lines.join("\n")}
|
|
|
18429
18657
|
* recently used right after an upgrade.
|
|
18430
18658
|
*/
|
|
18431
18659
|
persistPromptSnapshot(projectId, systemPrompt) {
|
|
18432
|
-
this.opts.db.update(agentSessions).set({ systemPrompt }).where(
|
|
18660
|
+
this.opts.db.update(agentSessions).set({ systemPrompt }).where(eq33(agentSessions.projectId, projectId)).run();
|
|
18433
18661
|
}
|
|
18434
18662
|
};
|
|
18435
18663
|
|
|
18436
18664
|
// src/agent/viewer-sessions.ts
|
|
18437
18665
|
import crypto28 from "crypto";
|
|
18438
|
-
import { and as
|
|
18666
|
+
import { and as and29, eq as eq34, isNotNull as isNotNull4, like as like2 } from "drizzle-orm";
|
|
18439
18667
|
|
|
18440
18668
|
// src/agent/chatgpt-plan.ts
|
|
18441
18669
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
@@ -18806,12 +19034,12 @@ var ViewerAeroSessions = class {
|
|
|
18806
19034
|
*/
|
|
18807
19035
|
removeKey(id) {
|
|
18808
19036
|
try {
|
|
18809
|
-
this.opts.db.delete(apiKeys).where(
|
|
19037
|
+
this.opts.db.delete(apiKeys).where(eq34(apiKeys.id, id)).run();
|
|
18810
19038
|
} catch {
|
|
18811
19039
|
try {
|
|
18812
19040
|
this.opts.db.transaction((tx) => {
|
|
18813
|
-
tx.delete(dashboardSessions).where(
|
|
18814
|
-
tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(
|
|
19041
|
+
tx.delete(dashboardSessions).where(eq34(dashboardSessions.apiKeyId, id)).run();
|
|
19042
|
+
tx.update(apiKeys).set({ revokedAt: new Date(this.now()).toISOString() }).where(eq34(apiKeys.id, id)).run();
|
|
18815
19043
|
});
|
|
18816
19044
|
} catch {
|
|
18817
19045
|
}
|
|
@@ -18824,7 +19052,7 @@ var ViewerAeroSessions = class {
|
|
|
18824
19052
|
*/
|
|
18825
19053
|
revokeOrphanedKeys() {
|
|
18826
19054
|
try {
|
|
18827
|
-
this.opts.db.delete(apiKeys).where(
|
|
19055
|
+
this.opts.db.delete(apiKeys).where(and29(like2(apiKeys.name, `${VIEWER_AERO_KEY_PREFIX}%`), isNotNull4(apiKeys.delegatedUserId))).run();
|
|
18828
19056
|
} catch {
|
|
18829
19057
|
}
|
|
18830
19058
|
}
|
|
@@ -18841,7 +19069,7 @@ var ViewerAeroSessions = class {
|
|
|
18841
19069
|
// src/mcp-http.ts
|
|
18842
19070
|
import crypto29 from "crypto";
|
|
18843
19071
|
import { isIP } from "net";
|
|
18844
|
-
import { and as
|
|
19072
|
+
import { and as and30, eq as eq35, isNull as isNull6 } from "drizzle-orm";
|
|
18845
19073
|
import { NodeStreamableHTTPServerTransport, toNodeHandler, toWebRequest } from "@modelcontextprotocol/node";
|
|
18846
19074
|
import { McpServer, createMcpHandler, isInitializeRequest, isLegacyRequest } from "@modelcontextprotocol/server";
|
|
18847
19075
|
var SESSION_IDLE_MS = 10 * 60 * 1e3;
|
|
@@ -18947,12 +19175,12 @@ function registerMcpHttpRoutes(scope, opts) {
|
|
|
18947
19175
|
try {
|
|
18948
19176
|
withoutLockWait(() => {
|
|
18949
19177
|
opts.db.transaction((tx) => {
|
|
18950
|
-
tx.delete(dashboardSessions).where(
|
|
18951
|
-
tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(
|
|
19178
|
+
tx.delete(dashboardSessions).where(eq35(dashboardSessions.apiKeyId, id)).run();
|
|
19179
|
+
tx.update(apiKeys).set({ revokedAt: new Date(now()).toISOString() }).where(and30(eq35(apiKeys.id, id), isNull6(apiKeys.revokedAt))).run();
|
|
18952
19180
|
});
|
|
18953
19181
|
if (remove) {
|
|
18954
19182
|
try {
|
|
18955
|
-
opts.db.delete(apiKeys).where(
|
|
19183
|
+
opts.db.delete(apiKeys).where(eq35(apiKeys.id, id)).run();
|
|
18956
19184
|
} catch (error) {
|
|
18957
19185
|
scope.log.warn({ err: error, keyId: id }, "Retained revoked MCP request key after deletion failed");
|
|
18958
19186
|
}
|
|
@@ -19003,14 +19231,14 @@ function registerMcpHttpRoutes(scope, opts) {
|
|
|
19003
19231
|
withoutLockWait(() => {
|
|
19004
19232
|
const cutoff = now() - SESSION_IDLE_MS;
|
|
19005
19233
|
for (const session of legacyServers) {
|
|
19006
|
-
const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(
|
|
19234
|
+
const key = session.sessionKeyId ? opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, session.sessionKeyId)).get() : void 0;
|
|
19007
19235
|
if (session.lastSeenAt < cutoff || session.expiresAt !== void 0 && session.expiresAt <= now() || session.sessionKeyId && (!key || key.revokedAt)) {
|
|
19008
19236
|
void session.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP session"));
|
|
19009
19237
|
}
|
|
19010
19238
|
}
|
|
19011
19239
|
for (const exchange of modernExchanges) {
|
|
19012
19240
|
if (!exchange.sessionKey) continue;
|
|
19013
|
-
const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(
|
|
19241
|
+
const key = opts.db.select({ revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq35(apiKeys.id, exchange.sessionKey.id)).get();
|
|
19014
19242
|
if (!key || key.revokedAt || exchange.sessionKey.expiresAt <= now()) {
|
|
19015
19243
|
void exchange.close().catch((error) => scope.log.error({ err: error }, "Failed to close expired MCP request"));
|
|
19016
19244
|
}
|
|
@@ -19296,7 +19524,7 @@ function resolveChatGptSettings(config, env = process.env) {
|
|
|
19296
19524
|
}
|
|
19297
19525
|
|
|
19298
19526
|
// src/agent/agent-routes.ts
|
|
19299
|
-
import { eq as
|
|
19527
|
+
import { eq as eq36 } from "drizzle-orm";
|
|
19300
19528
|
function viewerAeroCaller(request, opts) {
|
|
19301
19529
|
if (!opts.viewerSessions) return null;
|
|
19302
19530
|
const principal = request.principal;
|
|
@@ -19339,7 +19567,7 @@ function turnAttribution(request) {
|
|
|
19339
19567
|
};
|
|
19340
19568
|
}
|
|
19341
19569
|
function resolveProject(db, name) {
|
|
19342
|
-
const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(
|
|
19570
|
+
const row = db.select({ id: projects.id, name: projects.name }).from(projects).where(eq36(projects.name, name)).get();
|
|
19343
19571
|
if (!row) throw notFound("project", name);
|
|
19344
19572
|
return row;
|
|
19345
19573
|
}
|
|
@@ -19462,7 +19690,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19462
19690
|
}
|
|
19463
19691
|
requireInstanceAdministrator(request);
|
|
19464
19692
|
const project = resolveProject(opts.db, request.params.name);
|
|
19465
|
-
const row = opts.db.select().from(agentSessions).where(
|
|
19693
|
+
const row = opts.db.select().from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
|
|
19466
19694
|
const nextTurn = opts.sessionRegistry.nextTurnModel(project.name);
|
|
19467
19695
|
if (!row) {
|
|
19468
19696
|
return { conversationId: null, messages: [], modelProvider: null, modelId: null, nextTurn, updatedAt: null };
|
|
@@ -19504,7 +19732,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19504
19732
|
const project = resolveProject(opts.db, request.params.name);
|
|
19505
19733
|
if (opts.sessionRegistry.isBusy(project.name)) throw agentBusy(project.name);
|
|
19506
19734
|
opts.sessionRegistry.reset(project.name);
|
|
19507
|
-
opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
19735
|
+
opts.db.update(agentSessions).set({ messages: "[]", followUpQueue: "[]", updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq36(agentSessions.projectId, project.id)).run();
|
|
19508
19736
|
return { status: "reset" };
|
|
19509
19737
|
}
|
|
19510
19738
|
);
|
|
@@ -19528,7 +19756,7 @@ function registerAgentRoutes(app, opts) {
|
|
|
19528
19756
|
return streamViewerTurn(opts, project, viewerId, body, reply, turnAttribution(request));
|
|
19529
19757
|
}
|
|
19530
19758
|
if (body.conversationId !== void 0) {
|
|
19531
|
-
const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(
|
|
19759
|
+
const current = opts.db.select({ id: agentSessions.id }).from(agentSessions).where(eq36(agentSessions.projectId, project.id)).get();
|
|
19532
19760
|
if ((current?.id ?? null) !== body.conversationId) throw validationError("The active conversation changed. Reload the conversation before sending.");
|
|
19533
19761
|
}
|
|
19534
19762
|
const promptText = body.prompt;
|
|
@@ -19940,7 +20168,7 @@ function stripHtml(html) {
|
|
|
19940
20168
|
}
|
|
19941
20169
|
|
|
19942
20170
|
// src/snapshot-service.ts
|
|
19943
|
-
var
|
|
20171
|
+
var log31 = createLogger("Snapshot");
|
|
19944
20172
|
var ANALYSIS_PROVIDER_PRIORITY = ["openai", "claude", "gemini", "perplexity", "muse", "local"];
|
|
19945
20173
|
var SNAPSHOT_QUERY_COUNT = 6;
|
|
19946
20174
|
var SnapshotService = class {
|
|
@@ -20042,7 +20270,7 @@ var SnapshotService = class {
|
|
|
20042
20270
|
return mapAuditReport(report);
|
|
20043
20271
|
} catch (err) {
|
|
20044
20272
|
const message = describeError(err);
|
|
20045
|
-
|
|
20273
|
+
log31.warn("audit.failed", { homepageUrl, error: message });
|
|
20046
20274
|
return {
|
|
20047
20275
|
url: homepageUrl,
|
|
20048
20276
|
finalUrl: homepageUrl,
|
|
@@ -20071,7 +20299,7 @@ var SnapshotService = class {
|
|
|
20071
20299
|
queries: parsedQueries
|
|
20072
20300
|
};
|
|
20073
20301
|
} catch (err) {
|
|
20074
|
-
|
|
20302
|
+
log31.warn("profile.generation-failed", {
|
|
20075
20303
|
domain: ctx.domain,
|
|
20076
20304
|
provider: ctx.analysisProvider.adapter.name,
|
|
20077
20305
|
error: describeError(err)
|
|
@@ -20221,7 +20449,7 @@ var SnapshotService = class {
|
|
|
20221
20449
|
recommendedActions: uniqueStrings2(parsed.recommendedActions ?? []).slice(0, 4)
|
|
20222
20450
|
};
|
|
20223
20451
|
} catch (err) {
|
|
20224
|
-
|
|
20452
|
+
log31.warn("response.analysis-failed", {
|
|
20225
20453
|
provider: ctx.analysisProvider.adapter.name,
|
|
20226
20454
|
error: describeError(err)
|
|
20227
20455
|
});
|
|
@@ -20491,7 +20719,7 @@ function clipText(value, length) {
|
|
|
20491
20719
|
}
|
|
20492
20720
|
|
|
20493
20721
|
// src/research-runner.ts
|
|
20494
|
-
import { and as
|
|
20722
|
+
import { and as and31, eq as eq37, inArray as inArray14, sql as sql14 } from "drizzle-orm";
|
|
20495
20723
|
var unfinishedResearchQueryStatuses = [ResearchQueryStatuses.queued, ResearchQueryStatuses.running];
|
|
20496
20724
|
function finalResearchRunStatus(completed, failed, waiting) {
|
|
20497
20725
|
if (waiting > 0) return ResearchRunStatuses["waiting-upstream"];
|
|
@@ -20499,13 +20727,13 @@ function finalResearchRunStatus(completed, failed, waiting) {
|
|
|
20499
20727
|
return completed > 0 ? ResearchRunStatuses.partial : ResearchRunStatuses.failed;
|
|
20500
20728
|
}
|
|
20501
20729
|
async function executeResearchRun(db, registry, runId, projectId, options = {}) {
|
|
20502
|
-
const run = db.select().from(researchRuns).where(
|
|
20730
|
+
const run = db.select().from(researchRuns).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.projectId, projectId))).get();
|
|
20503
20731
|
if (!run || run.status !== ResearchRunStatuses.queued) return;
|
|
20504
|
-
const project = db.select().from(projects).where(
|
|
20732
|
+
const project = db.select().from(projects).where(eq37(projects.id, projectId)).get();
|
|
20505
20733
|
if (!project) return;
|
|
20506
20734
|
const provider = registry.get(run.provider);
|
|
20507
20735
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
20508
|
-
const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(
|
|
20736
|
+
const claim = db.update(researchRuns).set({ status: ResearchRunStatuses.running, startedAt: now }).where(and31(eq37(researchRuns.id, runId), eq37(researchRuns.status, ResearchRunStatuses.queued))).run();
|
|
20509
20737
|
if (claim.changes !== 1) return;
|
|
20510
20738
|
const elapsed = startOutcomeTimer();
|
|
20511
20739
|
const requested = currentOutcomeOrigin();
|
|
@@ -20539,8 +20767,8 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20539
20767
|
}
|
|
20540
20768
|
reserved = run.totalQueries;
|
|
20541
20769
|
reservation = { scope, period };
|
|
20542
|
-
const rows = db.select().from(researchRunQueries).where(
|
|
20543
|
-
const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(
|
|
20770
|
+
const rows = db.select().from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).orderBy(researchRunQueries.position).all();
|
|
20771
|
+
const competitorRows = db.select(competitorIdentityColumns).from(competitors).where(eq37(competitors.projectId, projectId)).orderBy(competitors.domain).all();
|
|
20544
20772
|
const competitorDomains = competitorRows.map((row) => row.domain);
|
|
20545
20773
|
const competitorAliases = new Map(competitorRows.map((row) => [row.domain, competitorIdentityAliases(row)]).filter(([, aliases]) => aliases.length > 0));
|
|
20546
20774
|
const domains = effectiveDomains(project);
|
|
@@ -20550,7 +20778,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20550
20778
|
await mapWithConcurrency(rows, Math.max(1, provider.config.quotaPolicy.maxConcurrency), async (row) => {
|
|
20551
20779
|
try {
|
|
20552
20780
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
20553
|
-
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(
|
|
20781
|
+
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.running, startedAt }).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.queued))).run();
|
|
20554
20782
|
const raw = await gate.run(async () => {
|
|
20555
20783
|
dispatched++;
|
|
20556
20784
|
return provider.adapter.executeTrackedQuery({ query: row.queryText, canonicalDomains: domains, competitorDomains, ...run.location ? { location: run.location } : {} }, config);
|
|
@@ -20581,7 +20809,7 @@ async function executeResearchRun(db, registry, runId, projectId, options = {})
|
|
|
20581
20809
|
rawResponse: raw.rawResponse,
|
|
20582
20810
|
answerEvidence: raw.evidence ?? null,
|
|
20583
20811
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20584
|
-
}).where(
|
|
20812
|
+
}).where(and31(eq37(researchRunQueries.id, row.id), eq37(researchRunQueries.status, ResearchQueryStatuses.running))).run();
|
|
20585
20813
|
if (completed.changes === 1) incrementResearchProgress(db, runId, "completedQueries");
|
|
20586
20814
|
} catch (error) {
|
|
20587
20815
|
if (!(error instanceof IncompleteAnswerError && error.resumable)) queryFailure ??= error;
|
|
@@ -20632,11 +20860,11 @@ function researchOutcomeStatus(status) {
|
|
|
20632
20860
|
}
|
|
20633
20861
|
}
|
|
20634
20862
|
function incrementResearchProgress(db, runId, column) {
|
|
20635
|
-
db.update(researchRuns).set({ [column]:
|
|
20863
|
+
db.update(researchRuns).set({ [column]: sql14`${researchRuns[column]} + 1` }).where(eq37(researchRuns.id, runId)).run();
|
|
20636
20864
|
}
|
|
20637
20865
|
function markResearchQueryFailed(db, runId, queryId, error) {
|
|
20638
20866
|
const message = describeError(error);
|
|
20639
|
-
const unfinished =
|
|
20867
|
+
const unfinished = and31(eq37(researchRunQueries.id, queryId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses));
|
|
20640
20868
|
if (error instanceof IncompleteAnswerError && error.resumable) {
|
|
20641
20869
|
db.update(researchRunQueries).set({
|
|
20642
20870
|
status: ResearchQueryStatuses["waiting-upstream"],
|
|
@@ -20652,10 +20880,10 @@ function markResearchQueryFailed(db, runId, queryId, error) {
|
|
|
20652
20880
|
if (failed.changes === 1) incrementResearchProgress(db, runId, "failedQueries");
|
|
20653
20881
|
}
|
|
20654
20882
|
function markUnfinishedResearchQueriesFailed(db, runId, error) {
|
|
20655
|
-
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
20883
|
+
db.update(researchRunQueries).set({ status: ResearchQueryStatuses.failed, error, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and31(eq37(researchRunQueries.researchRunId, runId), inArray14(researchRunQueries.status, unfinishedResearchQueryStatuses))).run();
|
|
20656
20884
|
}
|
|
20657
20885
|
function finalizeResearchRun(db, runId, fatalError) {
|
|
20658
|
-
const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(
|
|
20886
|
+
const rows = db.select({ status: researchRunQueries.status }).from(researchRunQueries).where(eq37(researchRunQueries.researchRunId, runId)).all();
|
|
20659
20887
|
const completed = rows.filter((row) => row.status === ResearchQueryStatuses.completed).length;
|
|
20660
20888
|
const failed = rows.filter((row) => row.status === ResearchQueryStatuses.failed).length;
|
|
20661
20889
|
const waiting = rows.filter((row) => row.status === ResearchQueryStatuses["waiting-upstream"]).length;
|
|
@@ -20667,12 +20895,12 @@ function finalizeResearchRun(db, runId, fatalError) {
|
|
|
20667
20895
|
error: fatalError ?? (failed === rows.length ? "Every research query failed." : null),
|
|
20668
20896
|
// A run waiting on upstream jobs has not finished.
|
|
20669
20897
|
finishedAt: waiting > 0 ? null : (/* @__PURE__ */ new Date()).toISOString()
|
|
20670
|
-
}).where(
|
|
20898
|
+
}).where(eq37(researchRuns.id, runId)).run();
|
|
20671
20899
|
return { status, total: rows.length, completed, failed };
|
|
20672
20900
|
}
|
|
20673
20901
|
|
|
20674
20902
|
// src/google-marketing-sync.ts
|
|
20675
|
-
import { and as
|
|
20903
|
+
import { and as and32, eq as eq38, isNull as isNull7, sql as sql15 } from "drizzle-orm";
|
|
20676
20904
|
var RUNTIME_FAILURE_REASONS = {
|
|
20677
20905
|
INVALID_INPUT: OutcomeReasonCodes.VALIDATION,
|
|
20678
20906
|
NOT_CONFIGURED: OutcomeReasonCodes.NOT_CONNECTED,
|
|
@@ -20709,10 +20937,10 @@ function assertSnapshotContext(metadata, expected) {
|
|
|
20709
20937
|
}
|
|
20710
20938
|
}
|
|
20711
20939
|
function requireSyncRun(db, runId, projectId, kind) {
|
|
20712
|
-
const run = db.select().from(runs).where(
|
|
20713
|
-
|
|
20714
|
-
|
|
20715
|
-
|
|
20940
|
+
const run = db.select().from(runs).where(and32(
|
|
20941
|
+
eq38(runs.id, runId),
|
|
20942
|
+
eq38(runs.projectId, projectId),
|
|
20943
|
+
eq38(runs.kind, kind)
|
|
20716
20944
|
)).get();
|
|
20717
20945
|
if (!run) throw withOutcomeReason(new Error(`Run ${runId} is not a ${kind} run for this project.`), OutcomeReasonCodes.NOT_FOUND);
|
|
20718
20946
|
if (run.status !== RunStatuses.queued) {
|
|
@@ -20728,19 +20956,19 @@ function markFailed(db, runId, projectId, kind, expectedStatus, error) {
|
|
|
20728
20956
|
status: RunStatuses.failed,
|
|
20729
20957
|
error: serializeRunError({ message: safeErrorMessage(error) }),
|
|
20730
20958
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
20731
|
-
}).where(
|
|
20732
|
-
|
|
20733
|
-
|
|
20734
|
-
|
|
20735
|
-
|
|
20959
|
+
}).where(and32(
|
|
20960
|
+
eq38(runs.id, runId),
|
|
20961
|
+
eq38(runs.projectId, projectId),
|
|
20962
|
+
eq38(runs.kind, kind),
|
|
20963
|
+
eq38(runs.status, expectedStatus)
|
|
20736
20964
|
)).run();
|
|
20737
20965
|
}
|
|
20738
20966
|
function claimSyncRun(db, runId, projectId, kind, startedAt) {
|
|
20739
|
-
const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(
|
|
20740
|
-
|
|
20741
|
-
|
|
20742
|
-
|
|
20743
|
-
|
|
20967
|
+
const claim = db.update(runs).set({ status: RunStatuses.running, startedAt, error: null }).where(and32(
|
|
20968
|
+
eq38(runs.id, runId),
|
|
20969
|
+
eq38(runs.projectId, projectId),
|
|
20970
|
+
eq38(runs.kind, kind),
|
|
20971
|
+
eq38(runs.status, RunStatuses.queued)
|
|
20744
20972
|
)).run();
|
|
20745
20973
|
return claim.changes === 1;
|
|
20746
20974
|
}
|
|
@@ -20750,9 +20978,9 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
20750
20978
|
let evidenceCollected = false;
|
|
20751
20979
|
try {
|
|
20752
20980
|
requireSyncRun(db, runId, projectId, RunKinds["google-ads-sync"]);
|
|
20753
|
-
const project = db.select().from(projects).where(
|
|
20981
|
+
const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
|
|
20754
20982
|
if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
|
|
20755
|
-
const connection = db.select().from(googleAdsConnections).where(
|
|
20983
|
+
const connection = db.select().from(googleAdsConnections).where(eq38(googleAdsConnections.projectId, projectId)).get();
|
|
20756
20984
|
if (!connection?.selectedCustomerId) {
|
|
20757
20985
|
throw withOutcomeReason(new Error("Google Ads needs a selected customer before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
|
|
20758
20986
|
}
|
|
@@ -20804,11 +21032,11 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
20804
21032
|
status: RunStatuses.completed,
|
|
20805
21033
|
finishedAt,
|
|
20806
21034
|
error: null
|
|
20807
|
-
}).where(
|
|
20808
|
-
|
|
20809
|
-
|
|
20810
|
-
|
|
20811
|
-
|
|
21035
|
+
}).where(and32(
|
|
21036
|
+
eq38(runs.id, runId),
|
|
21037
|
+
eq38(runs.projectId, projectId),
|
|
21038
|
+
eq38(runs.kind, RunKinds["google-ads-sync"]),
|
|
21039
|
+
eq38(runs.status, RunStatuses.running)
|
|
20812
21040
|
)).run();
|
|
20813
21041
|
if (terminalClaim.changes !== 1) {
|
|
20814
21042
|
throw withOutcomeReason(
|
|
@@ -20828,12 +21056,12 @@ async function executeGoogleAdsMarketingSync(db, runtime, runId, projectId) {
|
|
|
20828
21056
|
lastMetricsSnapshotAt: result.metrics?.metadata.capturedAt ?? connection.lastMetricsSnapshotAt,
|
|
20829
21057
|
lastMetricsSnapshotId: result.metrics?.metadata.id ?? connection.lastMetricsSnapshotId,
|
|
20830
21058
|
updatedAt: finishedAt
|
|
20831
|
-
}).where(
|
|
20832
|
-
|
|
20833
|
-
|
|
20834
|
-
|
|
20835
|
-
connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) :
|
|
20836
|
-
|
|
21059
|
+
}).where(and32(
|
|
21060
|
+
eq38(googleAdsConnections.id, connection.id),
|
|
21061
|
+
eq38(googleAdsConnections.projectId, projectId),
|
|
21062
|
+
eq38(googleAdsConnections.selectedCustomerId, connection.selectedCustomerId),
|
|
21063
|
+
connection.selectedLoginCustomerId === null ? isNull7(googleAdsConnections.selectedLoginCustomerId) : eq38(googleAdsConnections.selectedLoginCustomerId, connection.selectedLoginCustomerId),
|
|
21064
|
+
eq38(googleAdsConnections.selectionGeneration, connection.selectionGeneration)
|
|
20837
21065
|
)).run();
|
|
20838
21066
|
if (connectionClaim.changes !== 1) {
|
|
20839
21067
|
throw withOutcomeReason(
|
|
@@ -20873,9 +21101,9 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
20873
21101
|
let evidenceCollected = false;
|
|
20874
21102
|
try {
|
|
20875
21103
|
requireSyncRun(db, runId, projectId, RunKinds["gtm-sync"]);
|
|
20876
|
-
const project = db.select().from(projects).where(
|
|
21104
|
+
const project = db.select().from(projects).where(eq38(projects.id, projectId)).get();
|
|
20877
21105
|
if (!project) throw withOutcomeReason(new Error(`Project ${projectId} was not found.`), OutcomeReasonCodes.NOT_FOUND);
|
|
20878
|
-
const connection = db.select().from(gtmConnections).where(
|
|
21106
|
+
const connection = db.select().from(gtmConnections).where(eq38(gtmConnections.projectId, projectId)).get();
|
|
20879
21107
|
if (!connection?.selectedAccountId || !connection.selectedContainerId) {
|
|
20880
21108
|
throw withOutcomeReason(new Error("GTM needs a selected account and container before it can sync."), OutcomeReasonCodes.ACCOUNT_NOT_FOUND);
|
|
20881
21109
|
}
|
|
@@ -20913,11 +21141,11 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
20913
21141
|
status: RunStatuses.completed,
|
|
20914
21142
|
finishedAt,
|
|
20915
21143
|
error: null
|
|
20916
|
-
}).where(
|
|
20917
|
-
|
|
20918
|
-
|
|
20919
|
-
|
|
20920
|
-
|
|
21144
|
+
}).where(and32(
|
|
21145
|
+
eq38(runs.id, runId),
|
|
21146
|
+
eq38(runs.projectId, projectId),
|
|
21147
|
+
eq38(runs.kind, RunKinds["gtm-sync"]),
|
|
21148
|
+
eq38(runs.status, RunStatuses.running)
|
|
20921
21149
|
)).run();
|
|
20922
21150
|
if (terminalClaim.changes !== 1) {
|
|
20923
21151
|
throw withOutcomeReason(
|
|
@@ -20932,19 +21160,19 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
20932
21160
|
selectedWorkspaceName: selectedWorkspace?.name ?? null,
|
|
20933
21161
|
...workspaceReplaced ? {
|
|
20934
21162
|
selectedWorkspaceId: workspaceId,
|
|
20935
|
-
selectionGeneration:
|
|
21163
|
+
selectionGeneration: sql15`${gtmConnections.selectionGeneration} + 1`
|
|
20936
21164
|
} : {},
|
|
20937
21165
|
lastValidatedAt: snapshot.metadata.capturedAt,
|
|
20938
21166
|
lastSnapshotAt: snapshot.metadata.capturedAt,
|
|
20939
21167
|
lastSnapshotId: snapshot.metadata.id,
|
|
20940
21168
|
updatedAt: finishedAt
|
|
20941
|
-
}).where(
|
|
20942
|
-
|
|
20943
|
-
|
|
20944
|
-
|
|
20945
|
-
|
|
20946
|
-
connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) :
|
|
20947
|
-
|
|
21169
|
+
}).where(and32(
|
|
21170
|
+
eq38(gtmConnections.id, connection.id),
|
|
21171
|
+
eq38(gtmConnections.projectId, projectId),
|
|
21172
|
+
eq38(gtmConnections.selectedAccountId, connection.selectedAccountId),
|
|
21173
|
+
eq38(gtmConnections.selectedContainerId, connection.selectedContainerId),
|
|
21174
|
+
connection.selectedWorkspaceId === null ? isNull7(gtmConnections.selectedWorkspaceId) : eq38(gtmConnections.selectedWorkspaceId, connection.selectedWorkspaceId),
|
|
21175
|
+
eq38(gtmConnections.selectionGeneration, connection.selectionGeneration)
|
|
20948
21176
|
)).run();
|
|
20949
21177
|
if (connectionClaim.changes !== 1) {
|
|
20950
21178
|
throw withOutcomeReason(
|
|
@@ -20982,7 +21210,7 @@ async function executeGtmMarketingSync(db, runtime, runId, projectId) {
|
|
|
20982
21210
|
// src/server.ts
|
|
20983
21211
|
var _require = createRequire(import.meta.url);
|
|
20984
21212
|
var { version: PKG_VERSION } = _require("../package.json");
|
|
20985
|
-
var
|
|
21213
|
+
var log32 = createLogger("Server");
|
|
20986
21214
|
var runtimeStartupByServer = /* @__PURE__ */ new WeakMap();
|
|
20987
21215
|
function waitForServerRuntimeStartup(app) {
|
|
20988
21216
|
const startup = runtimeStartupByServer.get(app);
|
|
@@ -21234,7 +21462,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
|
|
|
21234
21462
|
}
|
|
21235
21463
|
if (migratedGoogle > 0) {
|
|
21236
21464
|
persistConfigPatch({ google: config.google });
|
|
21237
|
-
|
|
21465
|
+
log32.info("credentials.migrated", { type: "google", count: migratedGoogle });
|
|
21238
21466
|
}
|
|
21239
21467
|
let migratedGa4 = 0;
|
|
21240
21468
|
for (const row of rows.ga4) {
|
|
@@ -21252,7 +21480,7 @@ function applyLegacyCredentials(rows, config, persistConfigPatch = saveConfigPat
|
|
|
21252
21480
|
}
|
|
21253
21481
|
if (migratedGa4 > 0) {
|
|
21254
21482
|
persistConfigPatch({ ga4: config.ga4 });
|
|
21255
|
-
|
|
21483
|
+
log32.info("credentials.migrated", { type: "ga4", count: migratedGa4 });
|
|
21256
21484
|
}
|
|
21257
21485
|
}
|
|
21258
21486
|
function isLoopbackPeerAddress(address) {
|
|
@@ -21535,17 +21763,17 @@ async function createServer(opts) {
|
|
|
21535
21763
|
applyLegacyCredentials(legacyRows, opts.config, persistConfigPatch);
|
|
21536
21764
|
dropLegacyCredentialColumns(opts.db);
|
|
21537
21765
|
} catch (err) {
|
|
21538
|
-
|
|
21766
|
+
log32.warn("credentials.migration.failed", {
|
|
21539
21767
|
error: describeError(err)
|
|
21540
21768
|
});
|
|
21541
21769
|
}
|
|
21542
21770
|
}
|
|
21543
|
-
|
|
21771
|
+
log32.info("providers.configured", {
|
|
21544
21772
|
providers: registeredProviderNames({ providers, cdp: opts.config.cdp })
|
|
21545
21773
|
});
|
|
21546
21774
|
registry.replace(configuredProviderEntries(opts.config, API_ADAPTERS, cdpChatgptAdapter));
|
|
21547
21775
|
for (const name of providersWithUnsupportedBatch(providers, (provider) => adapterMap[provider])) {
|
|
21548
|
-
|
|
21776
|
+
log32.warn("provider.batch.unsupported", {
|
|
21549
21777
|
provider: name,
|
|
21550
21778
|
message: `providers.${name}.batch.enabled is true, but the ${name} adapter has no batch API; its sweeps run sync.`
|
|
21551
21779
|
});
|
|
@@ -21565,7 +21793,11 @@ async function createServer(opts) {
|
|
|
21565
21793
|
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
21566
21794
|
});
|
|
21567
21795
|
const allowLoopbackWebhooks = process.env.CANONRY_ALLOW_LOOPBACK_WEBHOOKS !== "0";
|
|
21568
|
-
const
|
|
21796
|
+
const sentimentInstall = () => {
|
|
21797
|
+
const configuration = loadSentimentInstallConfig();
|
|
21798
|
+
return { ...sentimentInstallReadiness(configuration), model: configuration.model, provider: configuration.provider };
|
|
21799
|
+
};
|
|
21800
|
+
const notifier = new Notifier(opts.db, serverUrl, { allowLoopbackWebhooks, sentimentInstall });
|
|
21569
21801
|
const intelligenceService = new IntelligenceService(opts.db);
|
|
21570
21802
|
const aeroClient = new ApiClient(opts.config.apiUrl, opts.config.apiKey, {
|
|
21571
21803
|
skipProbe: true,
|
|
@@ -21592,7 +21824,7 @@ async function createServer(opts) {
|
|
|
21592
21824
|
settings: () => resolveChatGptSettings(opts.config)
|
|
21593
21825
|
});
|
|
21594
21826
|
if (opts.config.chatgpt && (opts.config.chatgpt.signIn || opts.config.chatgpt.planUsage) && !resolveChatGptSettings(opts.config)) {
|
|
21595
|
-
|
|
21827
|
+
log32.warn("chatgpt.disabled", {
|
|
21596
21828
|
reason: "Sign in with ChatGPT needs chatgpt.clientId and an HTTPS publicUrl; it stays off until both are set."
|
|
21597
21829
|
});
|
|
21598
21830
|
}
|
|
@@ -21612,7 +21844,7 @@ async function createServer(opts) {
|
|
|
21612
21844
|
async (ctx) => {
|
|
21613
21845
|
if (!sessionRegistry) return;
|
|
21614
21846
|
if (!agentProactive) return;
|
|
21615
|
-
const project = opts.db.select({ name: projects.name }).from(projects).where(
|
|
21847
|
+
const project = opts.db.select({ name: projects.name }).from(projects).where(eq39(projects.id, ctx.projectId)).get();
|
|
21616
21848
|
if (!project) return;
|
|
21617
21849
|
let content;
|
|
21618
21850
|
if (ctx.kind === RunKinds["aeo-discover-probe"]) {
|
|
@@ -22042,6 +22274,7 @@ async function createServer(opts) {
|
|
|
22042
22274
|
let stopSiteLiveness = null;
|
|
22043
22275
|
let stopReviewDeliveries = null;
|
|
22044
22276
|
let stopUnrecognizedAgentAlerts = null;
|
|
22277
|
+
let stopSentimentAlerts = null;
|
|
22045
22278
|
let stopTrafficReclassification = null;
|
|
22046
22279
|
let stopProviderBatchPoller = null;
|
|
22047
22280
|
let stopInstallState = null;
|
|
@@ -22086,7 +22319,7 @@ async function createServer(opts) {
|
|
|
22086
22319
|
void (async () => {
|
|
22087
22320
|
try {
|
|
22088
22321
|
const report = await schedulerClient.runDoctor({ project: projectName, checkIds: scheduledHealthCheckIds() });
|
|
22089
|
-
const project = opts.db.select().from(projects).where(
|
|
22322
|
+
const project = opts.db.select().from(projects).where(eq39(projects.name, projectName)).get();
|
|
22090
22323
|
if (!project) {
|
|
22091
22324
|
app.log.warn({ projectName }, "doctor schedule fired for an unknown project");
|
|
22092
22325
|
return;
|
|
@@ -22378,7 +22611,7 @@ async function createServer(opts) {
|
|
|
22378
22611
|
})();
|
|
22379
22612
|
if (opts.config.apiKey) {
|
|
22380
22613
|
const keyHash = hashApiKey(opts.config.apiKey);
|
|
22381
|
-
const existing = opts.db.select().from(apiKeys).where(
|
|
22614
|
+
const existing = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, keyHash)).get();
|
|
22382
22615
|
if (!existing) {
|
|
22383
22616
|
const prefix = opts.config.apiKey.slice(0, 12);
|
|
22384
22617
|
opts.db.insert(apiKeys).values({
|
|
@@ -22397,14 +22630,14 @@ async function createServer(opts) {
|
|
|
22397
22630
|
);
|
|
22398
22631
|
const currentPasswordFingerprint = () => hashSessionToken(opts.config.dashboardPasswordHash ?? "");
|
|
22399
22632
|
opts.db.delete(dashboardSessions).where(or4(
|
|
22400
|
-
|
|
22401
|
-
|
|
22633
|
+
eq39(dashboardSessions.apiKeyHash, ""),
|
|
22634
|
+
and33(
|
|
22402
22635
|
isNotNull5(dashboardSessions.passwordFingerprint),
|
|
22403
22636
|
ne4(dashboardSessions.passwordFingerprint, currentPasswordFingerprint())
|
|
22404
22637
|
)
|
|
22405
22638
|
)).run();
|
|
22406
22639
|
if (!opts.config.dashboardPasswordHash) {
|
|
22407
|
-
const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(
|
|
22640
|
+
const lastPasswordEventAt = (action) => opts.db.select({ at: max(auditLog.createdAt) }).from(auditLog).where(and33(eq39(auditLog.entityType, "dashboard-password"), eq39(auditLog.action, action))).get()?.at ?? null;
|
|
22408
22641
|
const createdAt = lastPasswordEventAt("dashboard-password.created");
|
|
22409
22642
|
const clearedAt = lastPasswordEventAt("dashboard-password.cleared");
|
|
22410
22643
|
if (createdAt !== null && (clearedAt === null || clearedAt < createdAt)) {
|
|
@@ -22438,23 +22671,23 @@ async function createServer(opts) {
|
|
|
22438
22671
|
currentApiKeyHash: apiKeys.keyHash,
|
|
22439
22672
|
passwordFingerprint: dashboardSessions.passwordFingerprint,
|
|
22440
22673
|
expiresAt: dashboardSessions.expiresAt
|
|
22441
|
-
}).from(dashboardSessions).innerJoin(apiKeys,
|
|
22674
|
+
}).from(dashboardSessions).innerJoin(apiKeys, eq39(apiKeys.id, dashboardSessions.apiKeyId)).where(and33(eq39(dashboardSessions.tokenHash, tokenHash), isNull8(apiKeys.revokedAt))).get();
|
|
22442
22675
|
if (!session) return null;
|
|
22443
22676
|
const expiresAt = Date.parse(session.expiresAt);
|
|
22444
22677
|
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || session.apiKeyHash !== session.currentApiKeyHash || session.passwordFingerprint !== null && session.passwordFingerprint !== currentPasswordFingerprint()) {
|
|
22445
|
-
opts.db.delete(dashboardSessions).where(
|
|
22678
|
+
opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, tokenHash)).run();
|
|
22446
22679
|
return null;
|
|
22447
22680
|
}
|
|
22448
22681
|
return session.apiKeyId;
|
|
22449
22682
|
};
|
|
22450
22683
|
const clearSession = (sessionId) => {
|
|
22451
22684
|
if (sessionId) {
|
|
22452
|
-
opts.db.delete(dashboardSessions).where(
|
|
22685
|
+
opts.db.delete(dashboardSessions).where(eq39(dashboardSessions.tokenHash, hashSessionToken(sessionId))).run();
|
|
22453
22686
|
}
|
|
22454
22687
|
};
|
|
22455
22688
|
const getDefaultApiKey = () => {
|
|
22456
22689
|
if (!opts.config.apiKey) return void 0;
|
|
22457
|
-
return opts.db.select().from(apiKeys).where(
|
|
22690
|
+
return opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(opts.config.apiKey))).get();
|
|
22458
22691
|
};
|
|
22459
22692
|
const setSessionCookie = (reply, sessionId) => {
|
|
22460
22693
|
reply.header(
|
|
@@ -22615,12 +22848,12 @@ async function createServer(opts) {
|
|
|
22615
22848
|
return reply.send({ authenticated: true });
|
|
22616
22849
|
}
|
|
22617
22850
|
if (apiKey) {
|
|
22618
|
-
const key = opts.db.select().from(apiKeys).where(
|
|
22851
|
+
const key = opts.db.select().from(apiKeys).where(eq39(apiKeys.keyHash, hashApiKey(apiKey))).get();
|
|
22619
22852
|
if (!key || key.revokedAt) {
|
|
22620
22853
|
const err2 = authInvalid();
|
|
22621
22854
|
return reply.status(err2.statusCode).send(err2.toJSON());
|
|
22622
22855
|
}
|
|
22623
|
-
opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(
|
|
22856
|
+
opts.db.update(apiKeys).set({ lastUsedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq39(apiKeys.id, key.id)).run();
|
|
22624
22857
|
setSessionCookie(reply, createSession(key));
|
|
22625
22858
|
return reply.send({ authenticated: true });
|
|
22626
22859
|
}
|
|
@@ -22686,7 +22919,7 @@ async function createServer(opts) {
|
|
|
22686
22919
|
const sentimentPoller = createSentimentPoller(
|
|
22687
22920
|
() => sentimentWorker.tick(),
|
|
22688
22921
|
() => {
|
|
22689
|
-
|
|
22922
|
+
log32.error("sentiment.worker-failed", { reason: "Stored sentiment worker could not finish its tick." });
|
|
22690
22923
|
}
|
|
22691
22924
|
);
|
|
22692
22925
|
const pollSentiment = sentimentPoller.poll;
|
|
@@ -22698,7 +22931,7 @@ async function createServer(opts) {
|
|
|
22698
22931
|
const recomputeDebts = /* @__PURE__ */ new Map();
|
|
22699
22932
|
let recomputeSequence = 0;
|
|
22700
22933
|
const markAnswerFieldRecompute = (projectId, full) => {
|
|
22701
|
-
opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" :
|
|
22934
|
+
opts.db.update(projects).set({ answerFieldsRecompute: full ? "full" : sql16`CASE WHEN ${projects.answerFieldsRecompute} = 'full' THEN 'full' ELSE 'competitors' END` }).where(eq39(projects.id, projectId)).run();
|
|
22702
22935
|
};
|
|
22703
22936
|
const requestAnswerFieldRecompute = (projectId, projectName, scope, reason) => {
|
|
22704
22937
|
const sequence = ++recomputeSequence;
|
|
@@ -22716,10 +22949,10 @@ async function createServer(opts) {
|
|
|
22716
22949
|
if (pass.full && debt.latestFull <= sequence) debt.latestFull = 0;
|
|
22717
22950
|
try {
|
|
22718
22951
|
if (debt.latest === sequence && debt.latestFull === 0) {
|
|
22719
|
-
opts.db.update(projects).set({ answerFieldsRecompute: null }).where(
|
|
22952
|
+
opts.db.update(projects).set({ answerFieldsRecompute: null }).where(eq39(projects.id, projectId)).run();
|
|
22720
22953
|
if (recomputeDebts.get(projectId) === debt) recomputeDebts.delete(projectId);
|
|
22721
22954
|
} else if (debt.latestFull === 0) {
|
|
22722
|
-
opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(
|
|
22955
|
+
opts.db.update(projects).set({ answerFieldsRecompute: "competitors" }).where(and33(eq39(projects.id, projectId), eq39(projects.answerFieldsRecompute, "full"))).run();
|
|
22723
22956
|
}
|
|
22724
22957
|
} catch (err) {
|
|
22725
22958
|
app.log.error({ err, projectId }, "could not clear the owed answer field recompute");
|
|
@@ -22756,7 +22989,7 @@ async function createServer(opts) {
|
|
|
22756
22989
|
await yieldToEventLoop4();
|
|
22757
22990
|
const reason = (competitorAutoAliasReasons.get(projectId) ?? []).join(",");
|
|
22758
22991
|
competitorAutoAliasReasons.delete(projectId);
|
|
22759
|
-
const project = opts.db.select().from(projects).where(
|
|
22992
|
+
const project = opts.db.select().from(projects).where(eq39(projects.id, projectId)).get();
|
|
22760
22993
|
if (!project || project.competitorAutoAliases === "off") return;
|
|
22761
22994
|
if (project.competitorAutoAliases === "apply") {
|
|
22762
22995
|
await competitorAutoAliases.request(projectId, reason).catch(() => void 0);
|
|
@@ -22881,10 +23114,7 @@ async function createServer(opts) {
|
|
|
22881
23114
|
db: opts.db,
|
|
22882
23115
|
claimScheduledSync,
|
|
22883
23116
|
sentiment: {
|
|
22884
|
-
install:
|
|
22885
|
-
const configuration = loadSentimentInstallConfig();
|
|
22886
|
-
return { ...sentimentInstallReadiness(configuration), model: configuration.model, provider: configuration.provider };
|
|
22887
|
-
},
|
|
23117
|
+
install: sentimentInstall,
|
|
22888
23118
|
previewSecret: opts.config.apiKey,
|
|
22889
23119
|
estimate: (input) => {
|
|
22890
23120
|
const built = buildJevSentimentRequest(input);
|
|
@@ -22983,8 +23213,8 @@ async function createServer(opts) {
|
|
|
22983
23213
|
getAgentPin: () => describeAgentPin(opts.config),
|
|
22984
23214
|
getGoogleMarketingDoctorInput: (ctx) => {
|
|
22985
23215
|
if (!ctx.project) return null;
|
|
22986
|
-
const googleAds = opts.db.select().from(googleAdsConnections).where(
|
|
22987
|
-
const gtm = opts.db.select().from(gtmConnections).where(
|
|
23216
|
+
const googleAds = opts.db.select().from(googleAdsConnections).where(eq39(googleAdsConnections.projectId, ctx.project.id)).get();
|
|
23217
|
+
const gtm = opts.db.select().from(gtmConnections).where(eq39(gtmConnections.projectId, ctx.project.id)).get();
|
|
22988
23218
|
const googleAdsCredential = getGoogleAdsConnection(opts.config, ctx.project.id);
|
|
22989
23219
|
const gtmCredential = getGtmConnection(opts.config, ctx.project.id);
|
|
22990
23220
|
const googleAdsConnected = Boolean(googleAdsCredential?.accessToken);
|
|
@@ -23234,7 +23464,7 @@ async function createServer(opts) {
|
|
|
23234
23464
|
...inspectOpts,
|
|
23235
23465
|
config: opts.config
|
|
23236
23466
|
}).then(() => {
|
|
23237
|
-
const finished = opts.db.select({ status: runs.status }).from(runs).where(
|
|
23467
|
+
const finished = opts.db.select({ status: runs.status }).from(runs).where(eq39(runs.id, runId)).get();
|
|
23238
23468
|
if (finished?.status === RunStatuses.completed || finished?.status === RunStatuses.partial) {
|
|
23239
23469
|
return maybeRefreshGscCoverage(
|
|
23240
23470
|
opts.db,
|
|
@@ -23712,6 +23942,7 @@ async function createServer(opts) {
|
|
|
23712
23942
|
});
|
|
23713
23943
|
stopReviewDeliveries = startReviewDeliveryLoop(() => notifier.drainDueReviewDeliveries());
|
|
23714
23944
|
stopUnrecognizedAgentAlerts = startUnrecognizedAgentAlertLoop(() => notifier.dispatchUnrecognizedAgentAlerts());
|
|
23945
|
+
stopSentimentAlerts = startSentimentAlertLoop(() => notifier.dispatchSentimentAlerts());
|
|
23715
23946
|
stopTrafficReclassification = startTrafficReclassification({ db: opts.db });
|
|
23716
23947
|
stopProviderBatchPoller = startProviderBatchPoller({ db: opts.db, registry, runner: jobRunner });
|
|
23717
23948
|
if (!embed.enabled) {
|
|
@@ -23722,7 +23953,7 @@ async function createServer(opts) {
|
|
|
23722
23953
|
isBacklinksInstalled: () => isDuckdbInstalled()
|
|
23723
23954
|
});
|
|
23724
23955
|
}
|
|
23725
|
-
for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(
|
|
23956
|
+
for (const run of opts.db.select({ id: researchRuns.id, projectId: researchRuns.projectId }).from(researchRuns).where(eq39(researchRuns.status, ResearchRunStatuses.queued)).all()) {
|
|
23726
23957
|
dispatchResearchRun(run.id, run.projectId, OutcomeTriggers.startup);
|
|
23727
23958
|
}
|
|
23728
23959
|
runtimeStartupSettled = true;
|
|
@@ -23741,6 +23972,8 @@ async function createServer(opts) {
|
|
|
23741
23972
|
stopReviewDeliveries = null;
|
|
23742
23973
|
stopUnrecognizedAgentAlerts?.();
|
|
23743
23974
|
stopUnrecognizedAgentAlerts = null;
|
|
23975
|
+
stopSentimentAlerts?.();
|
|
23976
|
+
stopSentimentAlerts = null;
|
|
23744
23977
|
stopTrafficReclassification?.();
|
|
23745
23978
|
stopTrafficReclassification = null;
|
|
23746
23979
|
stopProviderBatchPoller?.();
|