@canonry/canonry 7.51.5 → 7.51.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/ads-ABAT3K4K.js +544 -0
  2. package/dist/agent-5G4DRLYX.js +70 -0
  3. package/dist/agent-ask-UDVCZRO7.js +139 -0
  4. package/dist/agent-conversations-5E4JP2QZ.js +52 -0
  5. package/dist/agent-memory-7IIJ4HGZ.js +92 -0
  6. package/dist/agent-providers-BOXPUXZ4.js +55 -0
  7. package/dist/agent-transcript-4O56G6PQ.js +77 -0
  8. package/dist/analytics-PKMWX5XL.js +240 -0
  9. package/dist/apply-OK4XEBDA.js +175 -0
  10. package/dist/backfill-2OT56CX2.js +41 -0
  11. package/dist/backlinks-547WCHND.js +303 -0
  12. package/dist/bing-ZVBV4ZD5.js +418 -0
  13. package/dist/bootstrap-HUB7XQ73.js +326 -0
  14. package/dist/cdp-KQKQ4PWJ.js +162 -0
  15. package/dist/chunk-2G6IP3MO.js +517 -0
  16. package/dist/chunk-42D2LE2B.js +1273 -0
  17. package/dist/chunk-4MJYGB56.js +124 -0
  18. package/dist/chunk-63ISSSGX.js +9150 -0
  19. package/dist/{chunk-PLYJX67A.js → chunk-6G6FTDWC.js} +8080 -13939
  20. package/dist/chunk-6GO5VVAC.js +15 -0
  21. package/dist/{chunk-4YCGZGA3.js → chunk-73P65KPW.js} +2 -2
  22. package/dist/chunk-7B2Q4NJE.js +133 -0
  23. package/dist/{chunk-JBZZEIM2.js → chunk-7WZ2FPB4.js} +2 -13
  24. package/dist/chunk-AOJU5LKX.js +8 -0
  25. package/dist/chunk-B2FR2ZQ4.js +420 -0
  26. package/dist/{chunk-HAHXPJQ5.js → chunk-B5J675KK.js} +16 -1684
  27. package/dist/{chunk-SFMWHPMX.js → chunk-D6COIM3U.js} +17128 -17143
  28. package/dist/{chunk-A3WSAAQS.js → chunk-DGVUTH7W.js} +9086 -34522
  29. package/dist/chunk-ELCLGWUT.js +83 -0
  30. package/dist/chunk-GO2J7SYT.js +1034 -0
  31. package/dist/chunk-HACZUMGM.js +145 -0
  32. package/dist/chunk-HM4NNKLG.js +94 -0
  33. package/dist/chunk-I3A56PFP.js +58 -0
  34. package/dist/chunk-I77PLCWG.js +961 -0
  35. package/dist/chunk-ISOQPVPY.js +232 -0
  36. package/dist/chunk-KFT5LOP2.js +610 -0
  37. package/dist/chunk-MLKGABMK.js +9 -0
  38. package/dist/chunk-MMEO22MF.js +38 -0
  39. package/dist/chunk-NHQ2U5I4.js +78 -0
  40. package/dist/chunk-PCXRFT3N.js +530 -0
  41. package/dist/chunk-PITHTCAX.js +15376 -0
  42. package/dist/chunk-QWKPSFGL.js +30 -0
  43. package/dist/chunk-RKIXES2B.js +609 -0
  44. package/dist/chunk-TSENU4GG.js +18 -0
  45. package/dist/{chunk-HLVEB5TB.js → chunk-TUTKNUMV.js} +7 -5
  46. package/dist/chunk-U3AHE2RT.js +1160 -0
  47. package/dist/chunk-UQ3MOZGC.js +644 -0
  48. package/dist/{chunk-AZFPA7JV.js → chunk-VBCE4CLX.js} +6 -4
  49. package/dist/chunk-VJWDBFSL.js +69 -0
  50. package/dist/chunk-VYMZ3QXG.js +8264 -0
  51. package/dist/chunk-WAULJDKO.js +2686 -0
  52. package/dist/chunk-WDFI5YMD.js +204 -0
  53. package/dist/chunk-XEBKF4N5.js +8 -0
  54. package/dist/chunk-Z7IUAJOF.js +13 -0
  55. package/dist/{chunk-KEATAHXH.js → chunk-ZWJRY5UI.js} +358 -581
  56. package/dist/chunk-ZXUAWVWM.js +15 -0
  57. package/dist/citations-UYB2RU5U.js +106 -0
  58. package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-F6FI7NB2.js} +5 -3
  59. package/dist/cli-commands-ZG5ILKDA.js +19 -0
  60. package/dist/cli.js +35 -29
  61. package/dist/competitor-EKP4R7YY.js +561 -0
  62. package/dist/content-DREE6JF3.js +257 -0
  63. package/dist/dashboard-ZALEOLLU.js +71 -0
  64. package/dist/demo-JG4Y22O4.js +75 -0
  65. package/dist/{demo-server-GIWDJGJX.js → demo-server-3A4J2C65.js} +22 -9
  66. package/dist/discover-W6GMD2HS.js +372 -0
  67. package/dist/discover-eval-CKFZHRBW.js +282 -0
  68. package/dist/doctor-TNGBSUMA.js +152 -0
  69. package/dist/evidence-3H2GFQBZ.js +57 -0
  70. package/dist/export-cmd-WUIKU5GK.js +49 -0
  71. package/dist/ga-JI6REFO4.js +911 -0
  72. package/dist/gbp-4ENDM5NS.js +370 -0
  73. package/dist/google-HKQSCLOC.js +946 -0
  74. package/dist/google-marketing-KQR5J2S4.js +403 -0
  75. package/dist/health-cmd-TS7EMMCS.js +64 -0
  76. package/dist/history-MSD5DK6K.js +90 -0
  77. package/dist/index.d.ts +47 -47
  78. package/dist/index.js +29 -6
  79. package/dist/init-L6WAEOWX.js +432 -0
  80. package/dist/insights-RTZ3IZTD.js +63 -0
  81. package/dist/intelligence-service-TH52PCNJ.js +15 -0
  82. package/dist/keys-625DZBRM.js +116 -0
  83. package/dist/keyword-CW46RNRR.js +164 -0
  84. package/dist/logs-V33SHBIW.js +30 -0
  85. package/dist/mcp-DFEDPSEG.js +14 -0
  86. package/dist/mcp.js +14 -5
  87. package/dist/measurement-plan-6W37RUOP.js +42 -0
  88. package/dist/notify-DSUOT7WO.js +125 -0
  89. package/dist/organic-evidence-BMN6L4OB.js +53 -0
  90. package/dist/overview-WRRMBZ6S.js +213 -0
  91. package/dist/project-2GJIU3FE.js +460 -0
  92. package/dist/query-3XPMGJUA.js +211 -0
  93. package/dist/research-V433CKJ4.js +200 -0
  94. package/dist/results-export-RGBU7QQQ.js +27 -0
  95. package/dist/run-NIAC6OJN.js +31 -0
  96. package/dist/schedule-KDWXRIE7.js +177 -0
  97. package/dist/search-626MPUJN.js +42 -0
  98. package/dist/serve-73SMMASI.js +557 -0
  99. package/dist/session-7WWOETZB.js +47 -0
  100. package/dist/settings-VKFQO6F2.js +107 -0
  101. package/dist/skills-5HC5H7TE.js +33 -0
  102. package/dist/snapshot-BSJUHFBC.js +538 -0
  103. package/dist/src-F6HM73TN.js +316 -0
  104. package/dist/status-V4OWP7LZ.js +126 -0
  105. package/dist/support-ARF4HER7.js +24 -0
  106. package/dist/technical-aeo-TG7CGU3F.js +625 -0
  107. package/dist/telemetry-O2IUNUBW.js +118 -0
  108. package/dist/tools-2GJIDKND.js +41 -0
  109. package/dist/traffic-XV4I3UPH.js +1295 -0
  110. package/dist/users-VGBLDL5K.js +170 -0
  111. package/dist/visibility-stats-UKJYJ6PP.js +241 -0
  112. package/dist/wordpress-JZA7CGC6.js +600 -0
  113. package/package.json +1 -1
  114. package/dist/chunk-4QQYYRHV.js +0 -23082
  115. package/dist/cli-commands-FOJR3HHU.js +0 -15
  116. package/dist/intelligence-service-XQCNWAPL.js +0 -9
@@ -0,0 +1,557 @@
1
+ import {
2
+ backfillAiReferralPaths,
3
+ backfillNormalizedPaths
4
+ } from "./chunk-I77PLCWG.js";
5
+ import {
6
+ operatorHttpUrl
7
+ } from "./chunk-6GO5VVAC.js";
8
+ import {
9
+ allowsKeylessFirstRunSetup,
10
+ createServer,
11
+ waitForServerRuntimeStartup
12
+ } from "./chunk-6G6FTDWC.js";
13
+ import "./chunk-42D2LE2B.js";
14
+ import "./chunk-U3AHE2RT.js";
15
+ import "./chunk-ELCLGWUT.js";
16
+ import "./chunk-XEBKF4N5.js";
17
+ import "./chunk-NHQ2U5I4.js";
18
+ import "./chunk-WAULJDKO.js";
19
+ import {
20
+ trackFeatureCompleted
21
+ } from "./chunk-ISOQPVPY.js";
22
+ import {
23
+ isLoopbackBindHost,
24
+ resolveServePort
25
+ } from "./chunk-TSENU4GG.js";
26
+ import {
27
+ registeredProviderNames
28
+ } from "./chunk-QWKPSFGL.js";
29
+ import {
30
+ cliRuntimeContext,
31
+ getPrintedUpdateAvailable,
32
+ installAttribution,
33
+ isTelemetryEnabled,
34
+ setTelemetrySource,
35
+ trackEvent
36
+ } from "./chunk-RKIXES2B.js";
37
+ import "./chunk-PCXRFT3N.js";
38
+ import "./chunk-4MJYGB56.js";
39
+ import "./chunk-B5J675KK.js";
40
+ import {
41
+ getConfigDir,
42
+ loadConfig
43
+ } from "./chunk-UQ3MOZGC.js";
44
+ import {
45
+ getMissingUserSkillsNudge,
46
+ shouldPrintServeSkillsNudge
47
+ } from "./chunk-B2FR2ZQ4.js";
48
+ import "./chunk-73P65KPW.js";
49
+ import "./chunk-ZWJRY5UI.js";
50
+ import "./chunk-HM4NNKLG.js";
51
+ import "./chunk-HACZUMGM.js";
52
+ import "./chunk-AOJU5LKX.js";
53
+ import {
54
+ CliError,
55
+ isMachineFormat
56
+ } from "./chunk-HGMYEDAQ.js";
57
+ import "./chunk-GO2J7SYT.js";
58
+ import "./chunk-MMEO22MF.js";
59
+ import "./chunk-DGVUTH7W.js";
60
+ import "./chunk-PITHTCAX.js";
61
+ import "./chunk-7B2Q4NJE.js";
62
+ import {
63
+ createClient,
64
+ dataRepairCompletions,
65
+ migrate,
66
+ projects,
67
+ runs
68
+ } from "./chunk-63ISSSGX.js";
69
+ import {
70
+ OutcomeReasonCodes,
71
+ OutcomeTriggers,
72
+ RunKinds,
73
+ RunStatuses,
74
+ RunTriggers,
75
+ URL_PATH_NORMALIZATION_VERSION,
76
+ classifyOutcomeError,
77
+ describeError
78
+ } from "./chunk-D6COIM3U.js";
79
+ import "./chunk-MLKGABMK.js";
80
+
81
+ // src/commands/serve.ts
82
+ import { and, asc, eq as eq2, ne } from "drizzle-orm";
83
+
84
+ // src/server-shutdown.ts
85
+ async function closeWithIdleSweep(app, intervalMs = 250) {
86
+ const sweep = setInterval(() => app.server.closeIdleConnections(), intervalMs);
87
+ sweep.unref();
88
+ try {
89
+ await app.close();
90
+ } finally {
91
+ clearInterval(sweep);
92
+ }
93
+ }
94
+
95
+ // src/startup-path-repairs.ts
96
+ import { eq, lt } from "drizzle-orm";
97
+ var STARTUP_REPAIR_PAGE_SIZE = 4096;
98
+ function repairNormalizedPathsOnStartup(db) {
99
+ return repairPathsOnce(db, "ga-traffic-paths", backfillNormalizedPaths);
100
+ }
101
+ function repairAiReferralPathsOnStartup(db) {
102
+ return repairPathsOnce(db, "ga-ai-referral-paths", backfillAiReferralPaths);
103
+ }
104
+ async function repairPathsOnce(db, name, repair) {
105
+ const completed = db.select({ version: dataRepairCompletions.version }).from(dataRepairCompletions).where(eq(dataRepairCompletions.name, name)).get();
106
+ if (completed && completed.version >= URL_PATH_NORMALIZATION_VERSION) return null;
107
+ let conflicted = false;
108
+ const result = await repair(db, { pageSize: STARTUP_REPAIR_PAGE_SIZE, onConflict: () => {
109
+ conflicted = true;
110
+ } });
111
+ if (!conflicted) {
112
+ const completion = { version: URL_PATH_NORMALIZATION_VERSION, completedAt: (/* @__PURE__ */ new Date()).toISOString() };
113
+ db.insert(dataRepairCompletions).values({ name, ...completion }).onConflictDoUpdate({
114
+ target: dataRepairCompletions.name,
115
+ set: completion,
116
+ setWhere: lt(dataRepairCompletions.version, URL_PATH_NORMALIZATION_VERSION)
117
+ }).run();
118
+ }
119
+ return result;
120
+ }
121
+
122
+ // src/agent-plugin.ts
123
+ import fs from "fs";
124
+ import path from "path";
125
+ var CANONRY_PLUGIN_ID = "canonry@canonry";
126
+ var REQUIRED_SKILLS = ["canonry", "aero"];
127
+ var AGENT_PLUGINS_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
128
+ var AGENT_PLUGINS_MCP_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";
129
+ function parseSemver(version) {
130
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-z.-]+))?(?:\+[0-9a-z.-]+)?$/i.exec(version);
131
+ if (!match) return null;
132
+ return {
133
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
134
+ prerelease: match.at(4)?.split(".")
135
+ };
136
+ }
137
+ function compareSemver(left, right) {
138
+ const leftVersion = parseSemver(left);
139
+ const rightVersion = parseSemver(right);
140
+ for (let index = 0; index < leftVersion.core.length; index += 1) {
141
+ if (leftVersion.core[index] !== rightVersion.core[index]) {
142
+ return leftVersion.core[index] > rightVersion.core[index] ? 1 : -1;
143
+ }
144
+ }
145
+ if (!leftVersion.prerelease && !rightVersion.prerelease) return 0;
146
+ if (!leftVersion.prerelease) return 1;
147
+ if (!rightVersion.prerelease) return -1;
148
+ const length = Math.max(leftVersion.prerelease.length, rightVersion.prerelease.length);
149
+ for (let index = 0; index < length; index += 1) {
150
+ const leftIdentifier = leftVersion.prerelease.at(index);
151
+ const rightIdentifier = rightVersion.prerelease.at(index);
152
+ if (leftIdentifier === void 0) return -1;
153
+ if (rightIdentifier === void 0) return 1;
154
+ if (leftIdentifier === rightIdentifier) continue;
155
+ const leftNumeric = /^\d+$/.test(leftIdentifier);
156
+ const rightNumeric = /^\d+$/.test(rightIdentifier);
157
+ if (leftNumeric && rightNumeric) return Number(leftIdentifier) > Number(rightIdentifier) ? 1 : -1;
158
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
159
+ return leftIdentifier > rightIdentifier ? 1 : -1;
160
+ }
161
+ return 0;
162
+ }
163
+ function isCanonryPluginId(value) {
164
+ return value.trim() === CANONRY_PLUGIN_ID;
165
+ }
166
+ function readJson(filePath) {
167
+ try {
168
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+ function readClaudePluginConfigured(filePath) {
174
+ const parsed = readJson(filePath);
175
+ if (!parsed || typeof parsed !== "object") return false;
176
+ const enabledPlugins = parsed.enabledPlugins;
177
+ if (!enabledPlugins || typeof enabledPlugins !== "object") return false;
178
+ for (const [id, enabled] of Object.entries(enabledPlugins)) {
179
+ if (isCanonryPluginId(id)) return enabled === true;
180
+ }
181
+ return false;
182
+ }
183
+ function readCodexPluginConfigured(filePath) {
184
+ try {
185
+ let currentPlugin = null;
186
+ let inPluginsTable = false;
187
+ for (const line of fs.readFileSync(filePath, "utf8").split(/\r?\n/)) {
188
+ const section = /^\s*\[plugins\.(?:"([^"]+)"|'([^']+)'|(\S+))\]\s*(?:#.*)?$/.exec(line);
189
+ if (section) {
190
+ const captures = section.slice(1, 4);
191
+ currentPlugin = captures.find((value) => value != null && value.length > 0) ?? null;
192
+ inPluginsTable = false;
193
+ continue;
194
+ }
195
+ if (/^\s*\[plugins\]\s*(?:#.*)?$/.test(line)) {
196
+ currentPlugin = null;
197
+ inPluginsTable = true;
198
+ continue;
199
+ }
200
+ if (/^\s*\[/.test(line)) {
201
+ currentPlugin = null;
202
+ inPluginsTable = false;
203
+ continue;
204
+ }
205
+ if (currentPlugin && isCanonryPluginId(currentPlugin)) {
206
+ const enabled = /^\s*enabled\s*=\s*(true|false)\s*(?:#.*)?$/.exec(line);
207
+ if (enabled) return enabled[1] === "true";
208
+ } else if (inPluginsTable) {
209
+ const inline = /^\s*(?:"([^"]+)"|'([^']+)'|([^=\s]+))\s*=\s*\{[^}]*\benabled\s*=\s*(true|false)\b[^}]*\}\s*(?:#.*)?$/.exec(line);
210
+ const id = inline?.[1] ?? inline?.[2] ?? inline?.[3];
211
+ if (inline && id && isCanonryPluginId(id)) return inline[4] === "true";
212
+ }
213
+ }
214
+ return false;
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+ function verifiedPluginVersion(root, client) {
220
+ if (client === "codex" && fs.existsSync(path.join(root, "plugin.json"))) {
221
+ const manifest2 = readJson(path.join(root, "plugin.json"));
222
+ if (manifest2 && typeof manifest2 === "object") {
223
+ const plugin2 = manifest2;
224
+ if (plugin2.$schema === AGENT_PLUGINS_SCHEMA) {
225
+ if (plugin2.name !== "canonry" || typeof plugin2.version !== "string" || !parseSemver(plugin2.version)) {
226
+ return null;
227
+ }
228
+ const mcp2 = readJson(path.join(root, "mcp.json"));
229
+ if (!mcp2 || typeof mcp2 !== "object") return null;
230
+ const portableMcp = mcp2;
231
+ if (portableMcp.$schema !== AGENT_PLUGINS_MCP_SCHEMA || portableMcp.mcpServers?.canonry?.type !== "stdio" || portableMcp.mcpServers.canonry.command !== "canonry-mcp") {
232
+ return null;
233
+ }
234
+ return REQUIRED_SKILLS.every((name) => fs.existsSync(path.join(root, "skills", name, "SKILL.md"))) ? plugin2.version : null;
235
+ }
236
+ if (typeof plugin2.$schema === "string" && plugin2.$schema.startsWith("https://agent-plugins.org/schemas/")) {
237
+ return null;
238
+ }
239
+ }
240
+ }
241
+ const manifestDir = client === "claude-code" ? ".claude-plugin" : ".codex-plugin";
242
+ const manifest = readJson(path.join(root, manifestDir, "plugin.json"));
243
+ if (!manifest || typeof manifest !== "object") return null;
244
+ const plugin = manifest;
245
+ if (plugin.name !== "canonry" || typeof plugin.version !== "string" || !parseSemver(plugin.version) || plugin.skills !== "./skills/" || plugin.mcpServers !== "./.mcp.json") {
246
+ return null;
247
+ }
248
+ const mcp = readJson(path.join(root, ".mcp.json"));
249
+ if (!mcp || typeof mcp !== "object") return null;
250
+ const canonryServer = mcp.mcpServers?.canonry;
251
+ if (canonryServer?.command !== "canonry-mcp") return null;
252
+ return REQUIRED_SKILLS.every((name) => fs.existsSync(path.join(root, "skills", name, "SKILL.md"))) ? plugin.version : null;
253
+ }
254
+ function readClaudeUserInstallPaths(claudeConfigDir) {
255
+ const parsed = readJson(path.join(claudeConfigDir, "plugins", "installed_plugins.json"));
256
+ if (!parsed || typeof parsed !== "object") return [];
257
+ const plugins = parsed.plugins;
258
+ if (!plugins || typeof plugins !== "object") return [];
259
+ const installs = plugins[CANONRY_PLUGIN_ID];
260
+ if (!Array.isArray(installs)) return [];
261
+ return installs.flatMap((install) => {
262
+ if (!install || typeof install !== "object") return [];
263
+ const record = install;
264
+ return record.scope === "user" && typeof record.installPath === "string" ? [record.installPath] : [];
265
+ });
266
+ }
267
+ function listDirectories(dir) {
268
+ try {
269
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path.join(dir, entry.name));
270
+ } catch {
271
+ return [];
272
+ }
273
+ }
274
+ function newestVersion(versions) {
275
+ return versions.sort(compareSemver).at(-1) ?? null;
276
+ }
277
+ function verifiedClaudeVersion(claudeConfigDir) {
278
+ return newestVersion(readClaudeUserInstallPaths(claudeConfigDir).map((installPath) => verifiedPluginVersion(installPath, "claude-code")).filter((version) => version !== null));
279
+ }
280
+ function verifiedCodexVersion(codexHome) {
281
+ const pluginCache = path.join(codexHome, "plugins", "cache", "canonry", "canonry");
282
+ const versionedRoots = listDirectories(pluginCache).map((installPath) => ({ installPath, version: path.basename(installPath) })).filter((candidate) => parseSemver(candidate.version) !== null).sort((left, right) => compareSemver(left.version, right.version));
283
+ const active = versionedRoots.at(-1);
284
+ if (!active) return verifiedPluginVersion(pluginCache, "codex");
285
+ const manifestVersion = verifiedPluginVersion(active.installPath, "codex");
286
+ return manifestVersion === active.version ? manifestVersion : null;
287
+ }
288
+ function detectCanonryAgentPlugin(opts = {}) {
289
+ const home = opts.home?.trim() || null;
290
+ const claudeConfigDir = opts.claudeConfigDir?.trim() || (home ? path.join(home, ".claude") : null);
291
+ const codexHome = opts.codexHome?.trim() || (home ? path.join(home, ".codex") : null);
292
+ const configuredClients = [];
293
+ const verifiedClients = [];
294
+ const verifiedClientVersions = {};
295
+ const claudeConfigured = claudeConfigDir ? readClaudePluginConfigured(path.join(claudeConfigDir, "settings.json")) : false;
296
+ if (claudeConfigured) {
297
+ configuredClients.push("claude-code");
298
+ const version = claudeConfigDir ? verifiedClaudeVersion(claudeConfigDir) : null;
299
+ if (version) {
300
+ verifiedClients.push("claude-code");
301
+ verifiedClientVersions["claude-code"] = version;
302
+ }
303
+ }
304
+ const codexConfigured = codexHome ? readCodexPluginConfigured(path.join(codexHome, "config.toml")) : false;
305
+ if (codexConfigured) {
306
+ configuredClients.push("codex");
307
+ const version = codexHome ? verifiedCodexVersion(codexHome) : null;
308
+ if (version) {
309
+ verifiedClients.push("codex");
310
+ verifiedClientVersions.codex = version;
311
+ }
312
+ }
313
+ return { configuredClients, verifiedClients, verifiedClientVersions };
314
+ }
315
+
316
+ // src/server-crash-telemetry.ts
317
+ import fs2 from "fs";
318
+ import path2 from "path";
319
+ var CRASH_MARKER = "crash-telemetry.json";
320
+ var MAX_MARKER_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
321
+ function telemetryAllowed() {
322
+ try {
323
+ return isTelemetryEnabled();
324
+ } catch {
325
+ return false;
326
+ }
327
+ }
328
+ function markerPath(configDir) {
329
+ return path2.join(configDir, CRASH_MARKER);
330
+ }
331
+ function trackServerStartFailure(err, reasonCode) {
332
+ try {
333
+ const classified = classifyOutcomeError(err);
334
+ const code = err?.code;
335
+ const reason = reasonCode ?? (code === "EADDRINUSE" ? OutcomeReasonCodes.PORT_IN_USE : classified.reasonCode);
336
+ trackFeatureCompleted({
337
+ feature: "server",
338
+ operation: "start",
339
+ status: "failed",
340
+ trigger: OutcomeTriggers.startup,
341
+ reasonCode: reason,
342
+ ...classified.errorName ? { errorName: classified.errorName } : {}
343
+ });
344
+ } catch {
345
+ }
346
+ }
347
+ var watched = /* @__PURE__ */ new WeakSet();
348
+ function watchServerCrashes(configDir = getConfigDir(), proc = process, now = Date.now) {
349
+ if (watched.has(proc)) return;
350
+ watched.add(proc);
351
+ proc.on("uncaughtExceptionMonitor", (err, origin) => {
352
+ if (!telemetryAllowed()) return;
353
+ try {
354
+ const { errorName } = classifyOutcomeError(err);
355
+ fs2.writeFileSync(markerPath(configDir), JSON.stringify({
356
+ origin: origin === "unhandledRejection" ? "unhandledRejection" : "uncaughtException",
357
+ at: now(),
358
+ ...errorName ? { errorName } : {}
359
+ }));
360
+ } catch {
361
+ }
362
+ });
363
+ }
364
+ function reportPreviousServerCrash(configDir = getConfigDir(), now = Date.now) {
365
+ if (!telemetryAllowed()) return;
366
+ const file = markerPath(configDir);
367
+ let marker;
368
+ try {
369
+ marker = JSON.parse(fs2.readFileSync(file, "utf8"));
370
+ } catch {
371
+ return;
372
+ }
373
+ try {
374
+ fs2.rmSync(file, { force: true });
375
+ } catch {
376
+ return;
377
+ }
378
+ if (typeof marker.at !== "number" || now() - marker.at > MAX_MARKER_AGE_MS) return;
379
+ const errorName = typeof marker.errorName === "string" && /^[A-Z_$][\w$]{0,39}$/i.test(marker.errorName) ? marker.errorName : void 0;
380
+ trackFeatureCompleted({
381
+ feature: "server",
382
+ operation: "crash",
383
+ status: "failed",
384
+ trigger: OutcomeTriggers.startup,
385
+ reasonCode: marker.origin === "unhandledRejection" ? OutcomeReasonCodes.UNHANDLED_REJECTION : OutcomeReasonCodes.UNCAUGHT_EXCEPTION,
386
+ ...errorName ? { errorName } : {}
387
+ });
388
+ }
389
+
390
+ // src/commands/serve.ts
391
+ function readServeOpenState(db) {
392
+ try {
393
+ const rows = db.select({
394
+ id: projects.id,
395
+ name: projects.name,
396
+ createdAt: projects.createdAt
397
+ }).from(projects).orderBy(asc(projects.createdAt), asc(projects.name)).all();
398
+ if (rows.length === 0) return { projectCount: 0, hasSiteAudit: false };
399
+ let scanned;
400
+ try {
401
+ const audits = db.select({
402
+ projectId: runs.projectId,
403
+ status: runs.status
404
+ }).from(runs).where(and(
405
+ eq2(runs.kind, RunKinds["site-audit"]),
406
+ ne(runs.trigger, RunTriggers.probe)
407
+ )).all();
408
+ scanned = new Set(
409
+ audits.filter((run) => run.status === RunStatuses.completed || run.status === RunStatuses.partial).map((run) => run.projectId)
410
+ );
411
+ } catch {
412
+ return { projectCount: rows.length, firstProjectName: rows[0]?.name, hasSiteAudit: true };
413
+ }
414
+ const firstUnscanned = rows.find((row) => !scanned.has(row.id));
415
+ if (firstUnscanned) {
416
+ return { projectCount: rows.length, firstProjectName: firstUnscanned.name, hasSiteAudit: false };
417
+ }
418
+ return { projectCount: rows.length, firstProjectName: rows[0]?.name, hasSiteAudit: true };
419
+ } catch {
420
+ return { projectCount: 0, hasSiteAudit: false };
421
+ }
422
+ }
423
+ function buildServeOpenLine(input) {
424
+ if (input.projectCount === 0) {
425
+ return `Open ${input.url}/setup to map your site and run your first Page Health scan.`;
426
+ }
427
+ if (!input.hasSiteAudit && input.firstProjectName) {
428
+ return `Open ${input.url}/setup?onboarding=site-health&setupProject=${encodeURIComponent(input.firstProjectName)} to run your first Page Health scan.`;
429
+ }
430
+ return `Open ${input.url}`;
431
+ }
432
+ async function serveCommand(format = "text") {
433
+ const config = loadConfig();
434
+ const port = resolveServePort(process.env.CANONRY_PORT, config.port);
435
+ const host = process.env.CANONRY_HOST ?? "127.0.0.1";
436
+ config.port = port;
437
+ const db = createClient(config.database);
438
+ try {
439
+ migrate(db);
440
+ } catch (err) {
441
+ trackServerStartFailure(err, "MIGRATION_FAILED");
442
+ throw err;
443
+ }
444
+ try {
445
+ const result = await repairNormalizedPathsOnStartup(db);
446
+ if (result && result.updated > 0 && format === "text") {
447
+ console.log(
448
+ `Migrated ${result.updated} GA landing-page row${result.updated === 1 ? "" : "s"} to canonical form.`
449
+ );
450
+ }
451
+ } catch (err) {
452
+ const msg = describeError(err);
453
+ process.stderr.write(`warning: normalized-path backfill skipped: ${msg}
454
+ `);
455
+ }
456
+ try {
457
+ const result = await repairAiReferralPathsOnStartup(db);
458
+ if (result && result.updated > 0 && format === "text") {
459
+ console.log(
460
+ `Migrated ${result.updated} GA AI referral row${result.updated === 1 ? "" : "s"} to canonical form.`
461
+ );
462
+ }
463
+ } catch (err) {
464
+ const msg = describeError(err);
465
+ process.stderr.write(`warning: ai-referral-paths backfill skipped: ${msg}
466
+ `);
467
+ }
468
+ const getAgentPluginState = () => detectCanonryAgentPlugin({
469
+ home: process.env.HOME,
470
+ claudeConfigDir: process.env.CLAUDE_CONFIG_DIR,
471
+ codexHome: process.env.CODEX_HOME
472
+ });
473
+ const app = await createServer({ config, db, host, getAgentPluginState });
474
+ let listening = false;
475
+ try {
476
+ await app.listen({ host, port });
477
+ let shuttingDown = false;
478
+ const shutdown = (signal) => {
479
+ if (shuttingDown) return;
480
+ shuttingDown = true;
481
+ if (format === "text") {
482
+ console.log(`
483
+ Received ${signal}, stopping server...`);
484
+ }
485
+ closeWithIdleSweep(app).then(() => {
486
+ process.exit(0);
487
+ }).catch((err) => {
488
+ console.error("Error during shutdown:", err);
489
+ process.exit(1);
490
+ });
491
+ };
492
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
493
+ process.on("SIGINT", () => shutdown("SIGINT"));
494
+ const url = operatorHttpUrl(host, port);
495
+ if (!isMachineFormat(format)) {
496
+ console.log(`
497
+ Canonry server running at ${url}`);
498
+ console.log(buildServeOpenLine({ url, ...readServeOpenState(db) }));
499
+ if (!allowsKeylessFirstRunSetup(app)) {
500
+ console.log(isLoopbackBindHost(host) ? "This server is configured to be reached through a proxy or external URL (publicUrl, apiUrl, basePath, or CANONRY_TRUST_PROXY), so first-run dashboard password setup requires the root API key (apiKey in config.yaml)." : "This server is not bound to loopback, so first-run dashboard password setup requires the root API key (apiKey in config.yaml).");
501
+ }
502
+ console.log("Press Ctrl+C to stop.\n");
503
+ const nudge = getMissingUserSkillsNudge(process.env.HOME, getAgentPluginState());
504
+ if (shouldPrintServeSkillsNudge(nudge, getPrintedUpdateAvailable())) {
505
+ process.stderr.write(`${nudge.message}
506
+ `);
507
+ }
508
+ }
509
+ await waitForServerRuntimeStartup(app);
510
+ listening = true;
511
+ if (isMachineFormat(format)) {
512
+ console.log(JSON.stringify({
513
+ started: true,
514
+ host,
515
+ port,
516
+ url
517
+ }, null, 2));
518
+ }
519
+ setTelemetrySource("cli-server");
520
+ watchServerCrashes();
521
+ reportPreviousServerCrash();
522
+ const providerNames = registeredProviderNames(config);
523
+ trackEvent("serve.started", {
524
+ providerCount: providerNames.length,
525
+ providers: providerNames,
526
+ ...installAttribution(),
527
+ // Who launched the server: an agent-started install is its own funnel.
528
+ ...cliRuntimeContext()
529
+ });
530
+ } catch (err) {
531
+ const message = describeError(err);
532
+ if (listening) {
533
+ process.stderr.write(`warning: server started but post-startup reporting failed: ${message}
534
+ `);
535
+ return;
536
+ }
537
+ trackServerStartFailure(err);
538
+ try {
539
+ await closeWithIdleSweep(app);
540
+ } catch (closeErr) {
541
+ process.stderr.write(`warning: failed to close server after startup error: ${describeError(closeErr)}
542
+ `);
543
+ }
544
+ throw new CliError({
545
+ code: "SERVE_START_FAILED",
546
+ message: `Failed to start server: ${message}`,
547
+ displayMessage: `Failed to start server: ${message}`,
548
+ details: {
549
+ host,
550
+ port
551
+ }
552
+ });
553
+ }
554
+ }
555
+ export {
556
+ serveCommand
557
+ };
@@ -0,0 +1,47 @@
1
+ import {
2
+ AgentProviders,
3
+ appendSystemPromptExtras,
4
+ buildApiKeyResolver,
5
+ coerceAgentProvider,
6
+ createAeroSession,
7
+ describeAgentPin,
8
+ detectAgentProvider,
9
+ listAgentProviders,
10
+ loadAeroSystemPrompt,
11
+ missingProviderMessage,
12
+ resolveAeroModel,
13
+ resolveAeroSkillDir,
14
+ resolveConfiguredAgentProvider,
15
+ resolveSessionProviderAndModel
16
+ } from "./chunk-42D2LE2B.js";
17
+ import "./chunk-U3AHE2RT.js";
18
+ import "./chunk-4MJYGB56.js";
19
+ import "./chunk-B5J675KK.js";
20
+ import "./chunk-UQ3MOZGC.js";
21
+ import "./chunk-ZWJRY5UI.js";
22
+ import "./chunk-HM4NNKLG.js";
23
+ import "./chunk-HACZUMGM.js";
24
+ import "./chunk-AOJU5LKX.js";
25
+ import "./chunk-HGMYEDAQ.js";
26
+ import "./chunk-DGVUTH7W.js";
27
+ import "./chunk-PITHTCAX.js";
28
+ import "./chunk-7B2Q4NJE.js";
29
+ import "./chunk-63ISSSGX.js";
30
+ import "./chunk-D6COIM3U.js";
31
+ import "./chunk-MLKGABMK.js";
32
+ export {
33
+ AgentProviders,
34
+ appendSystemPromptExtras,
35
+ buildApiKeyResolver,
36
+ coerceAgentProvider,
37
+ createAeroSession,
38
+ describeAgentPin,
39
+ detectAgentProvider,
40
+ listAgentProviders,
41
+ loadAeroSystemPrompt,
42
+ missingProviderMessage,
43
+ resolveAeroModel,
44
+ resolveAeroSkillDir,
45
+ resolveConfiguredAgentProvider,
46
+ resolveSessionProviderAndModel
47
+ };