@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.
- package/dist/ads-ABAT3K4K.js +544 -0
- package/dist/agent-5G4DRLYX.js +70 -0
- package/dist/agent-ask-UDVCZRO7.js +139 -0
- package/dist/agent-conversations-5E4JP2QZ.js +52 -0
- package/dist/agent-memory-7IIJ4HGZ.js +92 -0
- package/dist/agent-providers-BOXPUXZ4.js +55 -0
- package/dist/agent-transcript-4O56G6PQ.js +77 -0
- package/dist/analytics-PKMWX5XL.js +240 -0
- package/dist/apply-OK4XEBDA.js +175 -0
- package/dist/backfill-2OT56CX2.js +41 -0
- package/dist/backlinks-547WCHND.js +303 -0
- package/dist/bing-ZVBV4ZD5.js +418 -0
- package/dist/bootstrap-HUB7XQ73.js +326 -0
- package/dist/cdp-KQKQ4PWJ.js +162 -0
- package/dist/chunk-2G6IP3MO.js +517 -0
- package/dist/chunk-42D2LE2B.js +1273 -0
- package/dist/chunk-4MJYGB56.js +124 -0
- package/dist/chunk-63ISSSGX.js +9150 -0
- package/dist/{chunk-PLYJX67A.js → chunk-6G6FTDWC.js} +8080 -13939
- package/dist/chunk-6GO5VVAC.js +15 -0
- package/dist/{chunk-4YCGZGA3.js → chunk-73P65KPW.js} +2 -2
- package/dist/chunk-7B2Q4NJE.js +133 -0
- package/dist/{chunk-JBZZEIM2.js → chunk-7WZ2FPB4.js} +2 -13
- package/dist/chunk-AOJU5LKX.js +8 -0
- package/dist/chunk-B2FR2ZQ4.js +420 -0
- package/dist/{chunk-HAHXPJQ5.js → chunk-B5J675KK.js} +16 -1684
- package/dist/{chunk-SFMWHPMX.js → chunk-D6COIM3U.js} +17128 -17143
- package/dist/{chunk-A3WSAAQS.js → chunk-DGVUTH7W.js} +9086 -34522
- package/dist/chunk-ELCLGWUT.js +83 -0
- package/dist/chunk-GO2J7SYT.js +1034 -0
- package/dist/chunk-HACZUMGM.js +145 -0
- package/dist/chunk-HM4NNKLG.js +94 -0
- package/dist/chunk-I3A56PFP.js +58 -0
- package/dist/chunk-I77PLCWG.js +961 -0
- package/dist/chunk-ISOQPVPY.js +232 -0
- package/dist/chunk-KFT5LOP2.js +610 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-MMEO22MF.js +38 -0
- package/dist/chunk-NHQ2U5I4.js +78 -0
- package/dist/chunk-PCXRFT3N.js +530 -0
- package/dist/chunk-PITHTCAX.js +15376 -0
- package/dist/chunk-QWKPSFGL.js +30 -0
- package/dist/chunk-RKIXES2B.js +609 -0
- package/dist/chunk-TSENU4GG.js +18 -0
- package/dist/{chunk-HLVEB5TB.js → chunk-TUTKNUMV.js} +7 -5
- package/dist/chunk-U3AHE2RT.js +1160 -0
- package/dist/chunk-UQ3MOZGC.js +644 -0
- package/dist/{chunk-AZFPA7JV.js → chunk-VBCE4CLX.js} +6 -4
- package/dist/chunk-VJWDBFSL.js +69 -0
- package/dist/chunk-VYMZ3QXG.js +8264 -0
- package/dist/chunk-WAULJDKO.js +2686 -0
- package/dist/chunk-WDFI5YMD.js +204 -0
- package/dist/chunk-XEBKF4N5.js +8 -0
- package/dist/chunk-Z7IUAJOF.js +13 -0
- package/dist/{chunk-KEATAHXH.js → chunk-ZWJRY5UI.js} +358 -581
- package/dist/chunk-ZXUAWVWM.js +15 -0
- package/dist/citations-UYB2RU5U.js +106 -0
- package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-F6FI7NB2.js} +5 -3
- package/dist/cli-commands-ZG5ILKDA.js +19 -0
- package/dist/cli.js +35 -29
- package/dist/competitor-EKP4R7YY.js +561 -0
- package/dist/content-DREE6JF3.js +257 -0
- package/dist/dashboard-ZALEOLLU.js +71 -0
- package/dist/demo-JG4Y22O4.js +75 -0
- package/dist/{demo-server-GIWDJGJX.js → demo-server-3A4J2C65.js} +22 -9
- package/dist/discover-W6GMD2HS.js +372 -0
- package/dist/discover-eval-CKFZHRBW.js +282 -0
- package/dist/doctor-TNGBSUMA.js +152 -0
- package/dist/evidence-3H2GFQBZ.js +57 -0
- package/dist/export-cmd-WUIKU5GK.js +49 -0
- package/dist/ga-JI6REFO4.js +911 -0
- package/dist/gbp-4ENDM5NS.js +370 -0
- package/dist/google-HKQSCLOC.js +946 -0
- package/dist/google-marketing-KQR5J2S4.js +403 -0
- package/dist/health-cmd-TS7EMMCS.js +64 -0
- package/dist/history-MSD5DK6K.js +90 -0
- package/dist/index.d.ts +47 -47
- package/dist/index.js +29 -6
- package/dist/init-L6WAEOWX.js +432 -0
- package/dist/insights-RTZ3IZTD.js +63 -0
- package/dist/intelligence-service-TH52PCNJ.js +15 -0
- package/dist/keys-625DZBRM.js +116 -0
- package/dist/keyword-CW46RNRR.js +164 -0
- package/dist/logs-V33SHBIW.js +30 -0
- package/dist/mcp-DFEDPSEG.js +14 -0
- package/dist/mcp.js +14 -5
- package/dist/measurement-plan-6W37RUOP.js +42 -0
- package/dist/notify-DSUOT7WO.js +125 -0
- package/dist/organic-evidence-BMN6L4OB.js +53 -0
- package/dist/overview-WRRMBZ6S.js +213 -0
- package/dist/project-2GJIU3FE.js +460 -0
- package/dist/query-3XPMGJUA.js +211 -0
- package/dist/research-V433CKJ4.js +200 -0
- package/dist/results-export-RGBU7QQQ.js +27 -0
- package/dist/run-NIAC6OJN.js +31 -0
- package/dist/schedule-KDWXRIE7.js +177 -0
- package/dist/search-626MPUJN.js +42 -0
- package/dist/serve-73SMMASI.js +557 -0
- package/dist/session-7WWOETZB.js +47 -0
- package/dist/settings-VKFQO6F2.js +107 -0
- package/dist/skills-5HC5H7TE.js +33 -0
- package/dist/snapshot-BSJUHFBC.js +538 -0
- package/dist/src-F6HM73TN.js +316 -0
- package/dist/status-V4OWP7LZ.js +126 -0
- package/dist/support-ARF4HER7.js +24 -0
- package/dist/technical-aeo-TG7CGU3F.js +625 -0
- package/dist/telemetry-O2IUNUBW.js +118 -0
- package/dist/tools-2GJIDKND.js +41 -0
- package/dist/traffic-XV4I3UPH.js +1295 -0
- package/dist/users-VGBLDL5K.js +170 -0
- package/dist/visibility-stats-UKJYJ6PP.js +241 -0
- package/dist/wordpress-JZA7CGC6.js +600 -0
- package/package.json +1 -1
- package/dist/chunk-4QQYYRHV.js +0 -23082
- package/dist/cli-commands-FOJR3HHU.js +0 -15
- package/dist/intelligence-service-XQCNWAPL.js +0 -9
|
@@ -1,40 +1,26 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
loadConfig
|
|
3
|
+
} from "./chunk-UQ3MOZGC.js";
|
|
4
|
+
import {
|
|
5
|
+
PACKAGE_VERSION
|
|
6
|
+
} from "./chunk-AOJU5LKX.js";
|
|
6
7
|
import {
|
|
7
8
|
CliError,
|
|
8
9
|
EXIT_SYSTEM_ERROR,
|
|
9
|
-
EXIT_USER_ERROR
|
|
10
|
-
isMachineFormat
|
|
10
|
+
EXIT_USER_ERROR
|
|
11
11
|
} from "./chunk-HGMYEDAQ.js";
|
|
12
12
|
import {
|
|
13
|
-
AGENT_PROVIDER_IDS,
|
|
14
13
|
CANONRY_NPM_PACKAGE_URL,
|
|
15
|
-
CodingAgents,
|
|
16
|
-
DEFAULT_VIEWER_RESEARCH_DAILY_RUN_LIMIT,
|
|
17
14
|
OPERATIONAL_LOG_FIELDS_HEADER,
|
|
18
15
|
OPERATIONAL_LOG_OPT_IN_CONTEXT_FIELDS,
|
|
19
16
|
OPERATION_ACCESS_HEADER,
|
|
20
17
|
OperationAccesses,
|
|
21
|
-
RESEARCH_RUN_SCOPE,
|
|
22
|
-
SKILL_MANIFEST_FILENAME,
|
|
23
18
|
STORED_ONLY_HEADER,
|
|
24
|
-
SkillsClients,
|
|
25
19
|
USAGE_TELEMETRY_HEADERS,
|
|
26
|
-
agentPluginClientLabel,
|
|
27
|
-
agentProviderIdSchema,
|
|
28
|
-
classifySkillFile,
|
|
29
|
-
coerceSkillManifest,
|
|
30
20
|
compareSemver,
|
|
31
21
|
describeError,
|
|
32
22
|
detectAgentRuntime,
|
|
33
|
-
formatCanonryPluginUpdateHint,
|
|
34
|
-
formatCanonryPluginVersionMismatch,
|
|
35
23
|
isInstallMethod,
|
|
36
|
-
isReadOnlyKey,
|
|
37
|
-
isRetiredAgentProviderId,
|
|
38
24
|
isSensitiveDiagnosticQueryKey,
|
|
39
25
|
isStrictSemver,
|
|
40
26
|
matchOperationTemplate,
|
|
@@ -42,11 +28,6 @@ import {
|
|
|
42
28
|
normalizeTelemetryStatus,
|
|
43
29
|
operationAccess,
|
|
44
30
|
operationalLogListReadSchema,
|
|
45
|
-
providerBatchConfigSchema,
|
|
46
|
-
providerPricingSchema,
|
|
47
|
-
resolveProviderModel,
|
|
48
|
-
restrictedWriteScopes,
|
|
49
|
-
schedulableRunKindSchema,
|
|
50
31
|
sentimentBackfillPreviewReadSchema,
|
|
51
32
|
sentimentComparisonReadSchema,
|
|
52
33
|
sentimentEvidencePageReadSchema,
|
|
@@ -54,619 +35,8 @@ import {
|
|
|
54
35
|
sentimentJobsReadSchema,
|
|
55
36
|
sentimentSettingsReadSchema,
|
|
56
37
|
sentimentSummaryReadSchema,
|
|
57
|
-
skillsClientSchema,
|
|
58
|
-
upgradeCaveatFor,
|
|
59
38
|
upgradeCommandFor
|
|
60
|
-
} from "./chunk-
|
|
61
|
-
|
|
62
|
-
// src/config.ts
|
|
63
|
-
import fs from "fs";
|
|
64
|
-
import path from "path";
|
|
65
|
-
import os from "os";
|
|
66
|
-
import crypto from "crypto";
|
|
67
|
-
import { parse, stringify } from "yaml";
|
|
68
|
-
|
|
69
|
-
// ../config/src/index.ts
|
|
70
|
-
import { z as z2 } from "zod";
|
|
71
|
-
|
|
72
|
-
// ../config/src/sentiment.ts
|
|
73
|
-
import { z } from "zod";
|
|
74
|
-
var sentimentInstallConfigSchema = z.object({
|
|
75
|
-
enabled: z.boolean().default(false),
|
|
76
|
-
apiKey: z.string().trim().min(1).optional(),
|
|
77
|
-
model: z.string().trim().min(1).default("jev-1.13.0"),
|
|
78
|
-
maxConcurrency: z.number().int().min(1).max(8).default(2),
|
|
79
|
-
maxRequestsPerMinute: z.number().int().min(1).max(1e4).default(60),
|
|
80
|
-
maxInputTokensPerMinute: z.number().int().min(1).max(1e7).default(1e5),
|
|
81
|
-
maxAttempts: z.number().int().min(1).max(5).default(3)
|
|
82
|
-
}).strict();
|
|
83
|
-
function resolveSentimentInstallConfig(env, value) {
|
|
84
|
-
const enabled = env.CANONRY_SENTIMENT_ENABLED?.trim().toLowerCase();
|
|
85
|
-
return sentimentInstallConfigSchema.parse({
|
|
86
|
-
...value,
|
|
87
|
-
...enabled ? { enabled: enabled === "1" || enabled === "true" } : {},
|
|
88
|
-
...env.TYPESAFE_API_KEY !== void 0 ? { apiKey: env.TYPESAFE_API_KEY.trim() || void 0 } : {},
|
|
89
|
-
...env.TYPESAFE_MODEL !== void 0 ? { model: env.TYPESAFE_MODEL } : {}
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
function sentimentInstallReadiness(config) {
|
|
93
|
-
const reason = config.invalid ? "invalid-config" : !config.enabled ? "install-disabled" : config.model !== "jev-1.13.0" ? "unsupported-model" : !config.apiKey ? "missing-credentials" : null;
|
|
94
|
-
return { enabled: config.enabled, ready: reason === null, reason };
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// ../config/src/index.ts
|
|
98
|
-
var dashboardManagedSweepsSchema = z2.boolean().nullish();
|
|
99
|
-
var researchAllowViewersSchema = z2.boolean().nullish();
|
|
100
|
-
var agentAllowViewersSchema = z2.boolean().nullish();
|
|
101
|
-
var AGENT_REASONING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
102
|
-
var agentReasoningSchema = z2.enum(AGENT_REASONING_LEVELS).nullish();
|
|
103
|
-
var researchViewerDailyRunLimitSchema = z2.number().int().positive().nullish();
|
|
104
|
-
var dashboardManagedRunKindsSchema = z2.array(schedulableRunKindSchema).nullish();
|
|
105
|
-
var agentProviderSchema = agentProviderIdSchema.nullish();
|
|
106
|
-
var agentModelSchema = z2.string().trim().min(1).nullish();
|
|
107
|
-
function resolveOperatorApiKeyIds(source) {
|
|
108
|
-
const raw = source.CANONRY_OPERATOR_KEY_IDS?.trim();
|
|
109
|
-
if (!raw) return [];
|
|
110
|
-
const parsed = z2.array(z2.string().regex(/^[\w-]{1,256}$/)).max(100).safeParse(raw.split(",").map((id) => id.trim()));
|
|
111
|
-
if (!parsed.success) throw new Error("CANONRY_OPERATOR_KEY_IDS must contain at most 100 comma-separated API key IDs (letters, digits, underscores, hyphens; no wildcards).");
|
|
112
|
-
return [...new Set(parsed.data)];
|
|
113
|
-
}
|
|
114
|
-
var envSchema = z2.object({
|
|
115
|
-
DATABASE_URL: z2.string().default("postgresql://aeo:aeo@postgres:5432/aeo_platform"),
|
|
116
|
-
API_PORT: z2.coerce.number().int().positive().default(3e3),
|
|
117
|
-
WORKER_PORT: z2.coerce.number().int().positive().default(3001),
|
|
118
|
-
WEB_PORT: z2.coerce.number().int().positive().default(4173),
|
|
119
|
-
BOOTSTRAP_SECRET: z2.string().default("change-me"),
|
|
120
|
-
CANONRY_BASE_PATH: z2.string().default("/"),
|
|
121
|
-
// Gemini
|
|
122
|
-
GEMINI_API_KEY: z2.string().optional(),
|
|
123
|
-
GEMINI_MODEL: z2.string().optional(),
|
|
124
|
-
GEMINI_BASE_URL: z2.string().optional(),
|
|
125
|
-
GEMINI_MAX_CONCURRENCY: z2.coerce.number().int().positive().default(2),
|
|
126
|
-
GEMINI_MAX_REQUESTS_PER_MINUTE: z2.coerce.number().int().positive().default(10),
|
|
127
|
-
GEMINI_MAX_REQUESTS_PER_DAY: z2.coerce.number().int().positive().default(1e3),
|
|
128
|
-
// Gemini Vertex AI (alternative to API key auth)
|
|
129
|
-
GEMINI_VERTEX_PROJECT: z2.string().optional(),
|
|
130
|
-
GEMINI_VERTEX_REGION: z2.string().optional(),
|
|
131
|
-
GEMINI_VERTEX_CREDENTIALS: z2.string().optional(),
|
|
132
|
-
// OpenAI
|
|
133
|
-
OPENAI_API_KEY: z2.string().optional(),
|
|
134
|
-
OPENAI_MODEL: z2.string().optional(),
|
|
135
|
-
OPENAI_BASE_URL: z2.string().optional(),
|
|
136
|
-
OPENAI_MAX_CONCURRENCY: z2.coerce.number().int().positive().default(2),
|
|
137
|
-
OPENAI_MAX_REQUESTS_PER_MINUTE: z2.coerce.number().int().positive().default(10),
|
|
138
|
-
OPENAI_MAX_REQUESTS_PER_DAY: z2.coerce.number().int().positive().default(1e3),
|
|
139
|
-
// Anthropic / Claude
|
|
140
|
-
ANTHROPIC_API_KEY: z2.string().optional(),
|
|
141
|
-
ANTHROPIC_MODEL: z2.string().optional(),
|
|
142
|
-
ANTHROPIC_MAX_CONCURRENCY: z2.coerce.number().int().positive().default(2),
|
|
143
|
-
ANTHROPIC_MAX_REQUESTS_PER_MINUTE: z2.coerce.number().int().positive().default(10),
|
|
144
|
-
ANTHROPIC_MAX_REQUESTS_PER_DAY: z2.coerce.number().int().positive().default(1e3),
|
|
145
|
-
// Perplexity
|
|
146
|
-
PERPLEXITY_API_KEY: z2.string().optional(),
|
|
147
|
-
PERPLEXITY_MODEL: z2.string().optional(),
|
|
148
|
-
PERPLEXITY_MAX_CONCURRENCY: z2.coerce.number().int().positive().default(2),
|
|
149
|
-
PERPLEXITY_MAX_REQUESTS_PER_MINUTE: z2.coerce.number().int().positive().default(10),
|
|
150
|
-
PERPLEXITY_MAX_REQUESTS_PER_DAY: z2.coerce.number().int().positive().default(1e3),
|
|
151
|
-
// Meta Muse
|
|
152
|
-
MUSE_API_KEY: z2.string().optional(),
|
|
153
|
-
MUSE_MODEL: z2.string().optional(),
|
|
154
|
-
MUSE_BASE_URL: z2.string().optional(),
|
|
155
|
-
MUSE_MAX_CONCURRENCY: z2.coerce.number().int().positive().default(2),
|
|
156
|
-
MUSE_MAX_REQUESTS_PER_MINUTE: z2.coerce.number().int().positive().default(10),
|
|
157
|
-
MUSE_MAX_REQUESTS_PER_DAY: z2.coerce.number().int().positive().default(1e3),
|
|
158
|
-
// Secret for HMAC-signing Google OAuth state parameters. Required for
|
|
159
|
-
// cloud deployments that mount googleRoutes; the plugin refuses to register
|
|
160
|
-
// without it (see packages/api-routes/src/google.ts).
|
|
161
|
-
GOOGLE_STATE_SECRET: z2.string().optional(),
|
|
162
|
-
CANONRY_RESEARCH_ALLOW_VIEWERS: z2.string().optional(),
|
|
163
|
-
CANONRY_RESEARCH_VIEWER_DAILY_RUN_LIMIT: z2.coerce.number().int().positive().default(DEFAULT_VIEWER_RESEARCH_DAILY_RUN_LIMIT)
|
|
164
|
-
});
|
|
165
|
-
var BOOTSTRAP_PROVIDER_DEFAULT_MODELS = {
|
|
166
|
-
gemini: "gemini-flash-latest",
|
|
167
|
-
openai: "gpt-5.4",
|
|
168
|
-
claude: "claude-sonnet-4-6",
|
|
169
|
-
perplexity: resolveProviderModel("perplexity", "fast"),
|
|
170
|
-
muse: "muse-spark-1.3",
|
|
171
|
-
local: "llama3"
|
|
172
|
-
};
|
|
173
|
-
var BOOTSTRAP_PROVIDER_DEFAULT_QUOTA = {
|
|
174
|
-
maxConcurrency: 2,
|
|
175
|
-
maxRequestsPerMinute: 10,
|
|
176
|
-
maxRequestsPerDay: 500
|
|
177
|
-
};
|
|
178
|
-
function withBootstrapProviderDefaults(name, entry) {
|
|
179
|
-
return {
|
|
180
|
-
...entry,
|
|
181
|
-
model: entry.model ?? BOOTSTRAP_PROVIDER_DEFAULT_MODELS[name],
|
|
182
|
-
quota: entry.quota ?? { ...BOOTSTRAP_PROVIDER_DEFAULT_QUOTA }
|
|
183
|
-
};
|
|
184
|
-
}
|
|
185
|
-
var bootstrapEnvSchema = z2.object({
|
|
186
|
-
CANONRY_API_KEY: z2.string().optional(),
|
|
187
|
-
CANONRY_API_URL: z2.string().optional(),
|
|
188
|
-
CANONRY_DATABASE_PATH: z2.string().optional(),
|
|
189
|
-
GEMINI_API_KEY: z2.string().optional(),
|
|
190
|
-
GEMINI_MODEL: z2.string().optional(),
|
|
191
|
-
GEMINI_BASE_URL: z2.string().optional(),
|
|
192
|
-
GEMINI_VERTEX_PROJECT: z2.string().optional(),
|
|
193
|
-
GEMINI_VERTEX_REGION: z2.string().optional(),
|
|
194
|
-
GEMINI_VERTEX_CREDENTIALS: z2.string().optional(),
|
|
195
|
-
OPENAI_API_KEY: z2.string().optional(),
|
|
196
|
-
OPENAI_MODEL: z2.string().optional(),
|
|
197
|
-
OPENAI_BASE_URL: z2.string().optional(),
|
|
198
|
-
ANTHROPIC_API_KEY: z2.string().optional(),
|
|
199
|
-
ANTHROPIC_MODEL: z2.string().optional(),
|
|
200
|
-
PERPLEXITY_API_KEY: z2.string().optional(),
|
|
201
|
-
PERPLEXITY_MODEL: z2.string().optional(),
|
|
202
|
-
MUSE_API_KEY: z2.string().optional(),
|
|
203
|
-
MUSE_MODEL: z2.string().optional(),
|
|
204
|
-
MUSE_BASE_URL: z2.string().optional(),
|
|
205
|
-
LOCAL_BASE_URL: z2.string().optional(),
|
|
206
|
-
LOCAL_API_KEY: z2.string().optional(),
|
|
207
|
-
LOCAL_MODEL: z2.string().optional(),
|
|
208
|
-
GOOGLE_CLIENT_ID: z2.string().optional(),
|
|
209
|
-
GOOGLE_CLIENT_SECRET: z2.string().optional()
|
|
210
|
-
});
|
|
211
|
-
function getBootstrapEnv(source, overrides) {
|
|
212
|
-
const filtered = overrides ? Object.fromEntries(Object.entries(overrides).filter(([, v]) => v != null)) : {};
|
|
213
|
-
const parsed = bootstrapEnvSchema.parse({ ...source, ...filtered });
|
|
214
|
-
const providers = {};
|
|
215
|
-
if (parsed.GEMINI_API_KEY || parsed.GEMINI_VERTEX_PROJECT) {
|
|
216
|
-
providers.gemini = {
|
|
217
|
-
apiKey: parsed.GEMINI_API_KEY ?? "",
|
|
218
|
-
model: parsed.GEMINI_MODEL || void 0,
|
|
219
|
-
baseUrl: parsed.GEMINI_BASE_URL,
|
|
220
|
-
quota: void 0,
|
|
221
|
-
vertexProject: parsed.GEMINI_VERTEX_PROJECT,
|
|
222
|
-
vertexRegion: parsed.GEMINI_VERTEX_REGION,
|
|
223
|
-
vertexCredentials: parsed.GEMINI_VERTEX_CREDENTIALS
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
if (parsed.OPENAI_API_KEY) {
|
|
227
|
-
providers.openai = {
|
|
228
|
-
apiKey: parsed.OPENAI_API_KEY,
|
|
229
|
-
model: parsed.OPENAI_MODEL || void 0,
|
|
230
|
-
baseUrl: parsed.OPENAI_BASE_URL,
|
|
231
|
-
quota: void 0
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
if (parsed.ANTHROPIC_API_KEY) {
|
|
235
|
-
providers.claude = {
|
|
236
|
-
apiKey: parsed.ANTHROPIC_API_KEY,
|
|
237
|
-
model: parsed.ANTHROPIC_MODEL || void 0,
|
|
238
|
-
quota: void 0
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
if (parsed.PERPLEXITY_API_KEY) {
|
|
242
|
-
providers.perplexity = {
|
|
243
|
-
apiKey: parsed.PERPLEXITY_API_KEY,
|
|
244
|
-
// A retired Sonar name resolves to the Agent API preset that now answers.
|
|
245
|
-
model: parsed.PERPLEXITY_MODEL ? resolveProviderModel("perplexity", parsed.PERPLEXITY_MODEL) : void 0,
|
|
246
|
-
quota: void 0
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
const museKey = parsed.MUSE_API_KEY?.trim();
|
|
250
|
-
if (museKey) {
|
|
251
|
-
providers.muse = {
|
|
252
|
-
apiKey: museKey,
|
|
253
|
-
model: parsed.MUSE_MODEL?.trim() || void 0,
|
|
254
|
-
baseUrl: parsed.MUSE_BASE_URL?.trim() || void 0,
|
|
255
|
-
quota: void 0
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
if (parsed.LOCAL_BASE_URL) {
|
|
259
|
-
providers.local = {
|
|
260
|
-
baseUrl: parsed.LOCAL_BASE_URL,
|
|
261
|
-
apiKey: parsed.LOCAL_API_KEY,
|
|
262
|
-
model: parsed.LOCAL_MODEL || void 0,
|
|
263
|
-
quota: void 0
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
return {
|
|
267
|
-
apiKey: parsed.CANONRY_API_KEY,
|
|
268
|
-
apiUrl: parsed.CANONRY_API_URL,
|
|
269
|
-
databasePath: parsed.CANONRY_DATABASE_PATH,
|
|
270
|
-
googleClientId: parsed.GOOGLE_CLIENT_ID,
|
|
271
|
-
googleClientSecret: parsed.GOOGLE_CLIENT_SECRET,
|
|
272
|
-
providers
|
|
273
|
-
};
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// src/provider-batch-config.ts
|
|
277
|
-
function issuesText(issues) {
|
|
278
|
-
return issues.map((issue) => issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message).join("; ");
|
|
279
|
-
}
|
|
280
|
-
function normalizeProviderBatchSettings(providers, configPath) {
|
|
281
|
-
for (const [name, entry] of Object.entries(providers ?? {})) {
|
|
282
|
-
if (!entry) continue;
|
|
283
|
-
if (entry.batch !== void 0) {
|
|
284
|
-
const parsed = providerBatchConfigSchema.safeParse(entry.batch);
|
|
285
|
-
if (!parsed.success) {
|
|
286
|
-
throw new CliError({
|
|
287
|
-
code: "CONFIG_INVALID",
|
|
288
|
-
message: `Invalid config at ${configPath}: providers.${name}.batch is invalid (${issuesText(parsed.error.issues)}). Allowed keys: enabled (true/false), maxRequestsPerBatch (positive integer), deadlineHours (positive number).`
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
entry.batch = parsed.data;
|
|
292
|
-
}
|
|
293
|
-
if (entry.pricing !== void 0) {
|
|
294
|
-
const parsed = providerPricingSchema.safeParse(entry.pricing);
|
|
295
|
-
if (!parsed.success) {
|
|
296
|
-
throw new CliError({
|
|
297
|
-
code: "CONFIG_INVALID",
|
|
298
|
-
message: `Invalid config at ${configPath}: providers.${name}.pricing is invalid (${issuesText(parsed.error.issues)}). Prices are USD: inputPerMTok / cachedInputPerMTok / cacheWritePerMTok / outputPerMTok per million tokens, searchPer1k per 1,000 searches.`
|
|
299
|
-
});
|
|
300
|
-
}
|
|
301
|
-
entry.pricing = parsed.data;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
function providerConfigFromEntry(name, entry, quotaPolicy) {
|
|
306
|
-
return {
|
|
307
|
-
provider: name,
|
|
308
|
-
apiKey: entry.apiKey,
|
|
309
|
-
baseUrl: entry.baseUrl,
|
|
310
|
-
model: entry.model,
|
|
311
|
-
quotaPolicy,
|
|
312
|
-
vertexProject: entry.vertexProject,
|
|
313
|
-
vertexRegion: entry.vertexRegion,
|
|
314
|
-
vertexCredentials: entry.vertexCredentials,
|
|
315
|
-
...entry.batch ? { batch: entry.batch } : {},
|
|
316
|
-
...entry.pricing ? { pricing: entry.pricing } : {}
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
function adapterSupportsBatch(adapter) {
|
|
320
|
-
return adapter.batch !== void 0 && adapter.buildTrackedQueryRequest !== void 0 && adapter.parseTrackedQueryResponse !== void 0;
|
|
321
|
-
}
|
|
322
|
-
function batchEligibleProviderNames(registry) {
|
|
323
|
-
return registry.getAll().filter((provider) => provider.config.batch?.enabled === true && adapterSupportsBatch(provider.adapter)).map((provider) => provider.adapter.name).sort();
|
|
324
|
-
}
|
|
325
|
-
function providersWithUnsupportedBatch(providers, adapterFor) {
|
|
326
|
-
return Object.entries(providers ?? {}).filter(([name, entry]) => {
|
|
327
|
-
if (entry?.batch?.enabled !== true) return false;
|
|
328
|
-
const adapter = adapterFor(name);
|
|
329
|
-
return adapter !== void 0 && !adapterSupportsBatch(adapter);
|
|
330
|
-
}).map(([name]) => name).sort();
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// src/config.ts
|
|
334
|
-
function normalizeGoogleConfig(config) {
|
|
335
|
-
if (!config.google) return;
|
|
336
|
-
config.google.connections = (config.google.connections ?? []).map((connection) => ({
|
|
337
|
-
...connection,
|
|
338
|
-
propertyId: connection.propertyId ?? null,
|
|
339
|
-
refreshToken: connection.refreshToken ?? null,
|
|
340
|
-
tokenExpiresAt: connection.tokenExpiresAt ?? null,
|
|
341
|
-
scopes: connection.scopes ?? []
|
|
342
|
-
}));
|
|
343
|
-
}
|
|
344
|
-
function normalizeGoogleMarketingConfig(config) {
|
|
345
|
-
if (config.googleAds) {
|
|
346
|
-
config.googleAds.connections = (config.googleAds.connections ?? []).map((connection) => ({
|
|
347
|
-
...connection,
|
|
348
|
-
refreshToken: connection.refreshToken ?? null,
|
|
349
|
-
tokenExpiresAt: connection.tokenExpiresAt ?? null,
|
|
350
|
-
scopes: connection.scopes ?? []
|
|
351
|
-
}));
|
|
352
|
-
}
|
|
353
|
-
if (config.gtm) {
|
|
354
|
-
config.gtm.connections = (config.gtm.connections ?? []).map((connection) => ({
|
|
355
|
-
...connection,
|
|
356
|
-
refreshToken: connection.refreshToken ?? null,
|
|
357
|
-
tokenExpiresAt: connection.tokenExpiresAt ?? null,
|
|
358
|
-
scopes: connection.scopes ?? []
|
|
359
|
-
}));
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
function normalizeWordpressConfig(config) {
|
|
363
|
-
if (!config.wordpress) return;
|
|
364
|
-
config.wordpress.connections = (config.wordpress.connections ?? []).map((connection) => ({
|
|
365
|
-
...connection,
|
|
366
|
-
url: connection.url.replace(/\/$/, ""),
|
|
367
|
-
stagingUrl: connection.stagingUrl?.replace(/\/$/, ""),
|
|
368
|
-
defaultEnv: connection.defaultEnv ?? "live"
|
|
369
|
-
}));
|
|
370
|
-
}
|
|
371
|
-
function normalizeCloudflareTrafficConfig(config) {
|
|
372
|
-
for (const connection of config.cloudflareTraffic?.connections ?? []) {
|
|
373
|
-
const legacy = connection;
|
|
374
|
-
if (legacy.deliveryMode === void 0) {
|
|
375
|
-
legacy.deliveryMode = "direct-push";
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
function getConfigDir() {
|
|
380
|
-
const override = process.env.CANONRY_CONFIG_DIR?.trim();
|
|
381
|
-
if (override) {
|
|
382
|
-
return override;
|
|
383
|
-
}
|
|
384
|
-
return path.join(os.homedir(), ".canonry");
|
|
385
|
-
}
|
|
386
|
-
function getConfigPath() {
|
|
387
|
-
return path.join(getConfigDir(), "config.yaml");
|
|
388
|
-
}
|
|
389
|
-
function loadConfig(configPath = getConfigPath()) {
|
|
390
|
-
if (!fs.existsSync(configPath)) {
|
|
391
|
-
throw new Error(
|
|
392
|
-
`Config not found at ${configPath}.
|
|
393
|
-
Run "canonry bootstrap" to create the local Page Health runtime; provider credentials are optional.
|
|
394
|
-
Use "canonry init" instead only when you want interactive provider/OAuth provisioning.`
|
|
395
|
-
);
|
|
396
|
-
}
|
|
397
|
-
const raw = fs.readFileSync(configPath, "utf-8");
|
|
398
|
-
const parsed = parse(raw);
|
|
399
|
-
if (!parsed.apiUrl || !parsed.database || !parsed.apiKey) {
|
|
400
|
-
const missing = [
|
|
401
|
-
!parsed.apiUrl && "apiUrl",
|
|
402
|
-
!parsed.database && "database",
|
|
403
|
-
!parsed.apiKey && "apiKey"
|
|
404
|
-
].filter(Boolean).join(", ");
|
|
405
|
-
throw new Error(
|
|
406
|
-
`Invalid config at ${configPath} \u2014 missing: ${missing}.
|
|
407
|
-
Back up this config privately before you repair it.
|
|
408
|
-
Restore the missing values from a known-good backup. If none exists, recover the original values before you retry.
|
|
409
|
-
Keep the original API key and database path. Do not share secrets.
|
|
410
|
-
Do not use "canonry init --force" for recovery. It replaces credentials without a backup.`
|
|
411
|
-
);
|
|
412
|
-
}
|
|
413
|
-
if (!dashboardManagedSweepsSchema.safeParse(parsed.dashboard?.managedSweeps).success) {
|
|
414
|
-
throw new CliError({
|
|
415
|
-
code: "CONFIG_INVALID",
|
|
416
|
-
message: `Invalid config at ${configPath}: dashboard.managedSweeps must be true, false, or left blank.`
|
|
417
|
-
});
|
|
418
|
-
}
|
|
419
|
-
if (!researchAllowViewersSchema.safeParse(parsed.research?.allowViewers).success) {
|
|
420
|
-
throw new CliError({
|
|
421
|
-
code: "CONFIG_INVALID",
|
|
422
|
-
message: `Invalid config at ${configPath}: research.allowViewers must be true, false, or left blank.`
|
|
423
|
-
});
|
|
424
|
-
}
|
|
425
|
-
if (!dashboardManagedRunKindsSchema.safeParse(parsed.dashboard?.managedRunKinds).success) {
|
|
426
|
-
throw new CliError({
|
|
427
|
-
code: "CONFIG_INVALID",
|
|
428
|
-
message: `Invalid config at ${configPath}: dashboard.managedRunKinds must be a list of schedulable run kinds.`
|
|
429
|
-
});
|
|
430
|
-
}
|
|
431
|
-
if (!researchViewerDailyRunLimitSchema.safeParse(parsed.research?.viewerDailyRunLimit).success) {
|
|
432
|
-
throw new CliError({
|
|
433
|
-
code: "CONFIG_INVALID",
|
|
434
|
-
message: `Invalid config at ${configPath}: research.viewerDailyRunLimit must be a positive integer or left blank.`
|
|
435
|
-
});
|
|
436
|
-
}
|
|
437
|
-
if (!agentProviderSchema.safeParse(parsed.agent?.provider).success) {
|
|
438
|
-
const pinned = parsed.agent?.provider;
|
|
439
|
-
const retired = typeof pinned === "string" && isRetiredAgentProviderId(pinned);
|
|
440
|
-
throw new CliError({
|
|
441
|
-
code: "CONFIG_INVALID",
|
|
442
|
-
message: retired ? `Invalid config at ${configPath}: agent.provider ${pinned} was removed. Pin one of ${AGENT_PROVIDER_IDS.join(", ")} (with a key under providers.<name>.apiKey), or leave it blank.` : `Invalid config at ${configPath}: agent.provider must be one of ${AGENT_PROVIDER_IDS.join(", ")}, or left blank.`
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
if (!agentModelSchema.safeParse(parsed.agent?.model).success) {
|
|
446
|
-
throw new CliError({
|
|
447
|
-
code: "CONFIG_INVALID",
|
|
448
|
-
message: `Invalid config at ${configPath}: agent.model must be a non-empty string or left blank.`
|
|
449
|
-
});
|
|
450
|
-
}
|
|
451
|
-
if (!agentAllowViewersSchema.safeParse(parsed.agent?.allowViewers).success) {
|
|
452
|
-
throw new CliError({
|
|
453
|
-
code: "CONFIG_INVALID",
|
|
454
|
-
message: `Invalid config at ${configPath}: agent.allowViewers must be true, false, or left blank.`
|
|
455
|
-
});
|
|
456
|
-
}
|
|
457
|
-
if (!agentReasoningSchema.safeParse(parsed.agent?.reasoning).success) {
|
|
458
|
-
throw new CliError({
|
|
459
|
-
code: "CONFIG_INVALID",
|
|
460
|
-
message: `Invalid config at ${configPath}: agent.reasoning must be one of ${AGENT_REASONING_LEVELS.join(", ")}, or left blank.`
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
if (parsed.agent?.model && !parsed.agent?.provider) {
|
|
464
|
-
throw new CliError({
|
|
465
|
-
code: "CONFIG_INVALID",
|
|
466
|
-
message: `Invalid config at ${configPath}: agent.model requires agent.provider \u2014 a model id is only meaningful against the provider that serves it.`
|
|
467
|
-
});
|
|
468
|
-
}
|
|
469
|
-
if (parsed.geminiApiKey && !parsed.providers?.gemini) {
|
|
470
|
-
parsed.providers = {
|
|
471
|
-
...parsed.providers,
|
|
472
|
-
gemini: {
|
|
473
|
-
apiKey: parsed.geminiApiKey,
|
|
474
|
-
model: parsed.geminiModel,
|
|
475
|
-
quota: parsed.geminiQuota
|
|
476
|
-
}
|
|
477
|
-
};
|
|
478
|
-
}
|
|
479
|
-
normalizeProviderBatchSettings(parsed.providers, configPath);
|
|
480
|
-
normalizeGoogleConfig(parsed);
|
|
481
|
-
normalizeGoogleMarketingConfig(parsed);
|
|
482
|
-
normalizeWordpressConfig(parsed);
|
|
483
|
-
normalizeCloudflareTrafficConfig(parsed);
|
|
484
|
-
const portOverride = process.env.CANONRY_PORT?.trim();
|
|
485
|
-
if (portOverride) {
|
|
486
|
-
try {
|
|
487
|
-
const url = new URL(parsed.apiUrl);
|
|
488
|
-
url.port = portOverride;
|
|
489
|
-
parsed.apiUrl = url.origin;
|
|
490
|
-
} catch {
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
if ("CANONRY_BASE_PATH" in process.env) {
|
|
494
|
-
const val = process.env.CANONRY_BASE_PATH.trim();
|
|
495
|
-
parsed.basePath = val || void 0;
|
|
496
|
-
}
|
|
497
|
-
if (parsed.basePath) {
|
|
498
|
-
const normalizedBase = "/" + parsed.basePath.replace(/^\/|\/$/g, "");
|
|
499
|
-
try {
|
|
500
|
-
const url = new URL(parsed.apiUrl);
|
|
501
|
-
if (normalizedBase !== "/" && !url.pathname.startsWith(normalizedBase)) {
|
|
502
|
-
parsed.apiUrl = url.origin + normalizedBase;
|
|
503
|
-
}
|
|
504
|
-
} catch {
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
const parsedExternalMcp = parseExternalMcpEnv(process.env.CANONRY_EXTERNAL_MCP);
|
|
508
|
-
if (parsedExternalMcp) {
|
|
509
|
-
parsed.externalMcpServers = parsedExternalMcp;
|
|
510
|
-
}
|
|
511
|
-
return parsed;
|
|
512
|
-
}
|
|
513
|
-
function parseExternalMcpEnv(raw) {
|
|
514
|
-
const trimmed = raw?.trim();
|
|
515
|
-
if (!trimmed) return void 0;
|
|
516
|
-
let value;
|
|
517
|
-
try {
|
|
518
|
-
value = JSON.parse(trimmed);
|
|
519
|
-
} catch {
|
|
520
|
-
return void 0;
|
|
521
|
-
}
|
|
522
|
-
if (!Array.isArray(value)) return void 0;
|
|
523
|
-
const servers = [];
|
|
524
|
-
for (const entry of value) {
|
|
525
|
-
if (!entry || typeof entry !== "object") continue;
|
|
526
|
-
const candidate = entry;
|
|
527
|
-
const url = typeof candidate.url === "string" ? candidate.url.trim() : "";
|
|
528
|
-
const token = typeof candidate.token === "string" ? candidate.token : "";
|
|
529
|
-
if (!url || !token) continue;
|
|
530
|
-
const label = typeof candidate.label === "string" ? candidate.label : void 0;
|
|
531
|
-
servers.push({ url, token, ...label ? { label } : {} });
|
|
532
|
-
}
|
|
533
|
-
return servers.length > 0 ? servers : void 0;
|
|
534
|
-
}
|
|
535
|
-
function loadConfigRaw() {
|
|
536
|
-
const configPath = getConfigPath();
|
|
537
|
-
if (!fs.existsSync(configPath)) return null;
|
|
538
|
-
try {
|
|
539
|
-
return parse(fs.readFileSync(configPath, "utf-8")) ?? null;
|
|
540
|
-
} catch {
|
|
541
|
-
return null;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
function writeConfigAtomically(configPath, contents) {
|
|
545
|
-
const directory = path.dirname(configPath);
|
|
546
|
-
const temporaryPath = path.join(
|
|
547
|
-
directory,
|
|
548
|
-
`.${path.basename(configPath)}.${process.pid}.${crypto.randomUUID()}.tmp`
|
|
549
|
-
);
|
|
550
|
-
let descriptor;
|
|
551
|
-
try {
|
|
552
|
-
descriptor = fs.openSync(temporaryPath, "wx", 384);
|
|
553
|
-
fs.fchmodSync(descriptor, 384);
|
|
554
|
-
fs.writeFileSync(descriptor, contents, { encoding: "utf-8" });
|
|
555
|
-
fs.fsyncSync(descriptor);
|
|
556
|
-
fs.closeSync(descriptor);
|
|
557
|
-
descriptor = void 0;
|
|
558
|
-
fs.renameSync(temporaryPath, configPath);
|
|
559
|
-
} catch (error) {
|
|
560
|
-
if (descriptor !== void 0) {
|
|
561
|
-
try {
|
|
562
|
-
fs.closeSync(descriptor);
|
|
563
|
-
} catch {
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
try {
|
|
567
|
-
fs.unlinkSync(temporaryPath);
|
|
568
|
-
} catch {
|
|
569
|
-
}
|
|
570
|
-
throw error;
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
function saveConfig(config) {
|
|
574
|
-
const configDir = getConfigDir();
|
|
575
|
-
if (!fs.existsSync(configDir)) {
|
|
576
|
-
fs.mkdirSync(configDir, { recursive: true });
|
|
577
|
-
}
|
|
578
|
-
const configPath = getConfigPath();
|
|
579
|
-
const onDisk = loadConfigRaw();
|
|
580
|
-
const merged = onDisk ? { ...onDisk } : {};
|
|
581
|
-
for (const [key, value] of Object.entries(config)) {
|
|
582
|
-
if (value !== void 0) {
|
|
583
|
-
merged[key] = value;
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
if (onDisk) {
|
|
587
|
-
if (process.env.CANONRY_PORT?.trim() || onDisk.basePath) {
|
|
588
|
-
merged.apiUrl = onDisk.apiUrl;
|
|
589
|
-
}
|
|
590
|
-
if ("CANONRY_BASE_PATH" in process.env) {
|
|
591
|
-
if (onDisk.basePath !== void 0) {
|
|
592
|
-
merged.basePath = onDisk.basePath;
|
|
593
|
-
} else {
|
|
594
|
-
delete merged.basePath;
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
const yaml = stringify(merged);
|
|
599
|
-
writeConfigAtomically(configPath, yaml);
|
|
600
|
-
}
|
|
601
|
-
function saveConfigPatch(patch, options = {}) {
|
|
602
|
-
const configDir = getConfigDir();
|
|
603
|
-
if (!fs.existsSync(configDir)) {
|
|
604
|
-
fs.mkdirSync(configDir, { recursive: true });
|
|
605
|
-
}
|
|
606
|
-
const configPath = getConfigPath();
|
|
607
|
-
let base = {};
|
|
608
|
-
let baseRead = false;
|
|
609
|
-
if (fs.existsSync(configPath)) {
|
|
610
|
-
try {
|
|
611
|
-
const raw = fs.readFileSync(configPath, "utf-8");
|
|
612
|
-
const parsed = parse(raw);
|
|
613
|
-
base = parsed ?? {};
|
|
614
|
-
baseRead = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed);
|
|
615
|
-
} catch {
|
|
616
|
-
base = {};
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
const merged = { ...base, ...patch };
|
|
620
|
-
if (base.database) merged.database = base.database;
|
|
621
|
-
if (base.apiKey) merged.apiKey = base.apiKey;
|
|
622
|
-
if (base.anonymousId) merged.anonymousId = base.anonymousId;
|
|
623
|
-
if (base.dashboardPasswordHash) merged.dashboardPasswordHash = base.dashboardPasswordHash;
|
|
624
|
-
else if (options.setDashboardPasswordHash) merged.dashboardPasswordHash = options.setDashboardPasswordHash;
|
|
625
|
-
else if (baseRead) delete merged.dashboardPasswordHash;
|
|
626
|
-
if (base.sentiment === void 0) delete merged.sentiment;
|
|
627
|
-
else merged.sentiment = base.sentiment;
|
|
628
|
-
if (base.providers && patch.providers) {
|
|
629
|
-
merged.providers = { ...base.providers };
|
|
630
|
-
for (const [key, patchEntry] of Object.entries(patch.providers)) {
|
|
631
|
-
const baseEntry = base.providers[key] ?? {};
|
|
632
|
-
merged.providers[key] = { ...baseEntry, ...patchEntry };
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
const yaml = stringify(merged);
|
|
636
|
-
writeConfigAtomically(configPath, yaml);
|
|
637
|
-
}
|
|
638
|
-
function clearDashboardPassword() {
|
|
639
|
-
const configPath = getConfigPath();
|
|
640
|
-
if (!fs.existsSync(configPath)) {
|
|
641
|
-
throw new CliError({
|
|
642
|
-
code: "CONFIG_REQUIRED",
|
|
643
|
-
message: `No config found at ${configPath}. If the server uses another config directory, set CANONRY_CONFIG_DIR to it and retry.`
|
|
644
|
-
});
|
|
645
|
-
}
|
|
646
|
-
const raw = fs.readFileSync(configPath, "utf-8");
|
|
647
|
-
let parsed;
|
|
648
|
-
try {
|
|
649
|
-
parsed = parse(raw) ?? {};
|
|
650
|
-
} catch {
|
|
651
|
-
parsed = void 0;
|
|
652
|
-
}
|
|
653
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
654
|
-
throw new CliError({
|
|
655
|
-
code: "CONFIG_INVALID",
|
|
656
|
-
message: `Invalid config at ${configPath}: it could not be read as YAML settings. Repair the file and retry.`
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
const config = parsed;
|
|
660
|
-
if (!config.dashboardPasswordHash) {
|
|
661
|
-
return { cleared: false, configPath };
|
|
662
|
-
}
|
|
663
|
-
delete config.dashboardPasswordHash;
|
|
664
|
-
writeConfigAtomically(configPath, stringify(config));
|
|
665
|
-
return { cleared: true, configPath };
|
|
666
|
-
}
|
|
667
|
-
function configExists() {
|
|
668
|
-
return fs.existsSync(getConfigPath());
|
|
669
|
-
}
|
|
39
|
+
} from "./chunk-D6COIM3U.js";
|
|
670
40
|
|
|
671
41
|
// ../api-client-generated/src/generated/core/bodySerializer.gen.ts
|
|
672
42
|
var jsonBodySerializer = {
|
|
@@ -935,7 +305,7 @@ var serializeObjectParam = ({
|
|
|
935
305
|
|
|
936
306
|
// ../api-client-generated/src/generated/core/utils.gen.ts
|
|
937
307
|
var PATH_PARAM_RE = /\{[^{}]+\}/g;
|
|
938
|
-
var defaultPathSerializer = ({ path
|
|
308
|
+
var defaultPathSerializer = ({ path, url: _url }) => {
|
|
939
309
|
let url = _url;
|
|
940
310
|
const matches = _url.match(PATH_PARAM_RE);
|
|
941
311
|
if (matches) {
|
|
@@ -954,7 +324,7 @@ var defaultPathSerializer = ({ path: path3, url: _url }) => {
|
|
|
954
324
|
name = name.substring(1);
|
|
955
325
|
style = "matrix";
|
|
956
326
|
}
|
|
957
|
-
const value =
|
|
327
|
+
const value = path[name];
|
|
958
328
|
if (value === void 0 || value === null) {
|
|
959
329
|
continue;
|
|
960
330
|
}
|
|
@@ -995,15 +365,15 @@ var defaultPathSerializer = ({ path: path3, url: _url }) => {
|
|
|
995
365
|
};
|
|
996
366
|
var getUrl = ({
|
|
997
367
|
baseUrl,
|
|
998
|
-
path
|
|
368
|
+
path,
|
|
999
369
|
query,
|
|
1000
370
|
querySerializer,
|
|
1001
371
|
url: _url
|
|
1002
372
|
}) => {
|
|
1003
373
|
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
|
|
1004
374
|
let url = (baseUrl ?? "") + pathUrl;
|
|
1005
|
-
if (
|
|
1006
|
-
url = defaultPathSerializer({ path
|
|
375
|
+
if (path) {
|
|
376
|
+
url = defaultPathSerializer({ path, url });
|
|
1007
377
|
}
|
|
1008
378
|
let search = query ? querySerializer(query) : "";
|
|
1009
379
|
if (search.startsWith("?")) {
|
|
@@ -4243,11 +3613,11 @@ var ApiClient = class {
|
|
|
4243
3613
|
* structured-error behavior of `request()`; the caller reads `res.body`
|
|
4244
3614
|
* and releases the response when done.
|
|
4245
3615
|
*/
|
|
4246
|
-
async streamPost(
|
|
4247
|
-
const candidateUrl = `${this.originUrl}/api/v1${
|
|
3616
|
+
async streamPost(path, body, signal) {
|
|
3617
|
+
const candidateUrl = `${this.originUrl}/api/v1${path}`;
|
|
4248
3618
|
const storedOnlyHeaders = storedOnlyRequestHeaders("POST", candidateUrl);
|
|
4249
3619
|
await this.probeBasePath();
|
|
4250
|
-
const url = `${this.originUrl}/api/v1${
|
|
3620
|
+
const url = `${this.originUrl}/api/v1${path}`;
|
|
4251
3621
|
const headers = {
|
|
4252
3622
|
...this.requestHeaders,
|
|
4253
3623
|
...storedOnlyHeaders,
|
|
@@ -7180,1046 +6550,8 @@ var ApiClient = class {
|
|
|
7180
6550
|
}
|
|
7181
6551
|
};
|
|
7182
6552
|
|
|
7183
|
-
// src/mcp/server.ts
|
|
7184
|
-
import { randomUUID } from "crypto";
|
|
7185
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7186
|
-
import { z as z3 } from "zod";
|
|
7187
|
-
|
|
7188
|
-
// src/mcp/results.ts
|
|
7189
|
-
import { ZodError } from "zod";
|
|
7190
|
-
function jsonToolResult(value) {
|
|
7191
|
-
const result = value === void 0 ? { ok: true } : value;
|
|
7192
|
-
return {
|
|
7193
|
-
structuredContent: toStructuredContent(result),
|
|
7194
|
-
content: [
|
|
7195
|
-
{
|
|
7196
|
-
type: "text",
|
|
7197
|
-
text: JSON.stringify(result, null, 2)
|
|
7198
|
-
}
|
|
7199
|
-
]
|
|
7200
|
-
};
|
|
7201
|
-
}
|
|
7202
|
-
function errorToolResult(error) {
|
|
7203
|
-
const envelope = toCanonryErrorEnvelope(error);
|
|
7204
|
-
return {
|
|
7205
|
-
isError: true,
|
|
7206
|
-
structuredContent: envelope,
|
|
7207
|
-
content: [
|
|
7208
|
-
{
|
|
7209
|
-
type: "text",
|
|
7210
|
-
text: JSON.stringify(envelope, null, 2)
|
|
7211
|
-
}
|
|
7212
|
-
]
|
|
7213
|
-
};
|
|
7214
|
-
}
|
|
7215
|
-
function toStructuredContent(value) {
|
|
7216
|
-
if (Array.isArray(value)) return { items: value };
|
|
7217
|
-
if (value !== null && typeof value === "object") return value;
|
|
7218
|
-
return { value };
|
|
7219
|
-
}
|
|
7220
|
-
async function withToolErrors(handler) {
|
|
7221
|
-
try {
|
|
7222
|
-
return jsonToolResult(await handler());
|
|
7223
|
-
} catch (error) {
|
|
7224
|
-
return errorToolResult(error);
|
|
7225
|
-
}
|
|
7226
|
-
}
|
|
7227
|
-
function toCanonryErrorEnvelope(error) {
|
|
7228
|
-
if (error instanceof ZodError) {
|
|
7229
|
-
return {
|
|
7230
|
-
error: {
|
|
7231
|
-
code: "VALIDATION_ERROR",
|
|
7232
|
-
message: zodErrorMessage(error),
|
|
7233
|
-
details: { issues: error.issues.map(formatZodIssue) }
|
|
7234
|
-
}
|
|
7235
|
-
};
|
|
7236
|
-
}
|
|
7237
|
-
if (error instanceof CliError) {
|
|
7238
|
-
return {
|
|
7239
|
-
error: {
|
|
7240
|
-
code: error.code,
|
|
7241
|
-
message: error.message,
|
|
7242
|
-
...error.details ? { details: error.details } : {}
|
|
7243
|
-
}
|
|
7244
|
-
};
|
|
7245
|
-
}
|
|
7246
|
-
if (hasErrorEnvelope(error)) {
|
|
7247
|
-
const { code, message, details } = error.error;
|
|
7248
|
-
return {
|
|
7249
|
-
error: {
|
|
7250
|
-
code: typeof code === "string" ? code : "API_ERROR",
|
|
7251
|
-
message: typeof message === "string" ? message : "Canonry API error",
|
|
7252
|
-
...details !== void 0 ? { details } : {}
|
|
7253
|
-
}
|
|
7254
|
-
};
|
|
7255
|
-
}
|
|
7256
|
-
if (error instanceof Error) {
|
|
7257
|
-
return {
|
|
7258
|
-
error: {
|
|
7259
|
-
code: "MCP_TOOL_ERROR",
|
|
7260
|
-
message: error.message
|
|
7261
|
-
}
|
|
7262
|
-
};
|
|
7263
|
-
}
|
|
7264
|
-
return {
|
|
7265
|
-
error: {
|
|
7266
|
-
code: "MCP_TOOL_ERROR",
|
|
7267
|
-
message: "Unknown MCP tool error"
|
|
7268
|
-
}
|
|
7269
|
-
};
|
|
7270
|
-
}
|
|
7271
|
-
function hasErrorEnvelope(value) {
|
|
7272
|
-
if (!value || typeof value !== "object" || !("error" in value)) return false;
|
|
7273
|
-
const error = value.error;
|
|
7274
|
-
return Boolean(error && typeof error === "object");
|
|
7275
|
-
}
|
|
7276
|
-
function formatZodIssue(issue) {
|
|
7277
|
-
return { path: issue.path.map(String).join("."), message: issue.message };
|
|
7278
|
-
}
|
|
7279
|
-
function zodErrorMessage(error) {
|
|
7280
|
-
const first = error.issues[0];
|
|
7281
|
-
if (!first) return "Input validation failed";
|
|
7282
|
-
const path3 = first.path.map(String).join(".");
|
|
7283
|
-
return path3 ? `${path3}: ${first.message}` : first.message;
|
|
7284
|
-
}
|
|
7285
|
-
|
|
7286
|
-
// src/mcp/toolkits.ts
|
|
7287
|
-
var CANONRY_MCP_TIERS = [
|
|
7288
|
-
"core",
|
|
7289
|
-
"monitoring",
|
|
7290
|
-
"setup",
|
|
7291
|
-
"gsc",
|
|
7292
|
-
"bing",
|
|
7293
|
-
"ga",
|
|
7294
|
-
"gbp",
|
|
7295
|
-
// `ads` is deliberately OpenAI / ChatGPT Ads. Google Ads has its own
|
|
7296
|
-
// toolkit so an agent never mistakes the two provider surfaces.
|
|
7297
|
-
"ads",
|
|
7298
|
-
"google-ads",
|
|
7299
|
-
"gtm",
|
|
7300
|
-
"conversion-tracking",
|
|
7301
|
-
"traffic",
|
|
7302
|
-
"agent",
|
|
7303
|
-
"discovery"
|
|
7304
|
-
];
|
|
7305
|
-
var CANONRY_MCP_TOOLKIT_NAMES = [
|
|
7306
|
-
"monitoring",
|
|
7307
|
-
"setup",
|
|
7308
|
-
"gsc",
|
|
7309
|
-
"bing",
|
|
7310
|
-
"ga",
|
|
7311
|
-
"gbp",
|
|
7312
|
-
"ads",
|
|
7313
|
-
"google-ads",
|
|
7314
|
-
"gtm",
|
|
7315
|
-
"conversion-tracking",
|
|
7316
|
-
"traffic",
|
|
7317
|
-
"agent",
|
|
7318
|
-
"discovery"
|
|
7319
|
-
];
|
|
7320
|
-
var CANONRY_MCP_TOOLKITS = [
|
|
7321
|
-
{
|
|
7322
|
-
name: "monitoring",
|
|
7323
|
-
title: "Measurement, runs, insights, health",
|
|
7324
|
-
description: "Inspect portfolio and Property measurement, question results, experimental branded and non-brand sentiment and evidence, content opportunities and addressed-target records, run history, intelligence insights, health timelines, and bounded Site Health reads (overview, page audit evidence, focused subgraphs, paths, and scan changes).",
|
|
7325
|
-
whenToLoad: "Load when finding weak Properties, reviewing answers, sentiment and competitors, marking or restoring addressed content targets, checking data quality, tying a Site Health page score to concrete findings, investigating site architecture, comparing scans, or diagnosing regressions."
|
|
7326
|
-
},
|
|
7327
|
-
{
|
|
7328
|
-
name: "setup",
|
|
7329
|
-
title: "Project setup and measurement",
|
|
7330
|
-
description: "Manage project configuration, Advanced Measurement drafts, query assets, competitors, and schedules.",
|
|
7331
|
-
whenToLoad: "Load when onboarding a project, editing its measurement plan, or managing tracked queries, competitors, or schedules."
|
|
7332
|
-
},
|
|
7333
|
-
{
|
|
7334
|
-
name: "gsc",
|
|
7335
|
-
title: "Google Search Console",
|
|
7336
|
-
description: "Read GSC performance, per-query totals, inspections, coverage, sitemaps, and deindexed URLs.",
|
|
7337
|
-
whenToLoad: "Load when you need indexing, coverage, or sitemap data from Google Search Console."
|
|
7338
|
-
},
|
|
7339
|
-
{
|
|
7340
|
-
name: "bing",
|
|
7341
|
-
title: "Bing Webmaster Tools",
|
|
7342
|
-
description: "Read stored project index coverage and URL inspection evidence without calling Bing.",
|
|
7343
|
-
whenToLoad: "Load when reviewing indexed, not indexed or unknown URLs from a connected Bing site."
|
|
7344
|
-
},
|
|
7345
|
-
{
|
|
7346
|
-
name: "ga",
|
|
7347
|
-
title: "Google Analytics 4",
|
|
7348
|
-
description: "Read GA traffic, AI/social referral history, attribution trend, session history, and GA4's Search Console landing-page report (Google organic clicks, impressions, CTR, position and active users per landing page).",
|
|
7349
|
-
whenToLoad: "Load when you need traffic, referral, or attribution data from Google Analytics 4."
|
|
7350
|
-
},
|
|
7351
|
-
{
|
|
7352
|
-
name: "gbp",
|
|
7353
|
-
title: "Google Business Profile",
|
|
7354
|
-
description: "Local AEO signals: discover GBP locations under a connected account and toggle which ones sync, then read daily performance metrics, search keywords, booking links, hotel and owner-set attributes, the public Places listing, and reviews with their alert state.",
|
|
7355
|
-
whenToLoad: "Load when the project tracks local search visibility or has connected Google Business Profile."
|
|
7356
|
-
},
|
|
7357
|
-
{
|
|
7358
|
-
name: "ads",
|
|
7359
|
-
title: "OpenAI ads (ChatGPT ads)",
|
|
7360
|
-
description: "Live OpenAI ad-account review state, targetable geo IDs, conversion pixels/event settings, synced campaign structure, paid-performance rollups, and guarded lifecycle operations.",
|
|
7361
|
-
whenToLoad: "Load when planning, creating, reviewing, or measuring ChatGPT ads, including geo and conversion-readiness checks before launch."
|
|
7362
|
-
},
|
|
7363
|
-
{
|
|
7364
|
-
name: "google-ads",
|
|
7365
|
-
title: "Google Ads conversion evidence",
|
|
7366
|
-
description: "Read a connected Google Ads account, its conversion actions, effective campaign goals, and bounded stored snapshots. v1 only reads provider state; it never edits campaigns, conversion actions, or bidding goals.",
|
|
7367
|
-
whenToLoad: "Load when selecting a Google Ads customer, reviewing conversion-action and effective-goal evidence, or starting a bounded read-only sync."
|
|
7368
|
-
},
|
|
7369
|
-
{
|
|
7370
|
-
name: "gtm",
|
|
7371
|
-
title: "Google Tag Manager conversion evidence",
|
|
7372
|
-
description: "Read GTM accounts, containers, workspaces, and sanitized live/draft tag graphs used to verify a conversion contract. v1 never edits a workspace or publishes a container version.",
|
|
7373
|
-
whenToLoad: "Load when selecting a GTM container, reviewing a live or draft conversion-tag graph, or starting a bounded read-only sync."
|
|
7374
|
-
},
|
|
7375
|
-
{
|
|
7376
|
-
name: "conversion-tracking",
|
|
7377
|
-
title: "Cross-provider conversion integrity",
|
|
7378
|
-
description: "Read declared conversion contracts and assess them against stored Google Ads and GTM evidence without calling or mutating either provider.",
|
|
7379
|
-
whenToLoad: "Load when listing or inspecting declared conversion contracts, or when checking whether stored Google Ads and GTM evidence is consistent with one contract."
|
|
7380
|
-
},
|
|
7381
|
-
{
|
|
7382
|
-
name: "traffic",
|
|
7383
|
-
title: "Server-side traffic ingestion",
|
|
7384
|
-
description: "Read complete 7/14/30/90-day traffic analytics and crawler / AI-referral hourly rollups straight from server logs (no GA dependency), assess AI-referral bursts from stored evidence (raw counts, candidate bursts, a separate adjusted estimate, coverage limits), connect Cloud Run / WordPress / Vercel sources, trigger syncs, and backfill Cloud Run / Vercel windows.",
|
|
7385
|
-
whenToLoad: "Load when you need server-log evidence of crawler hits or AI-referral sessions (e.g. confirming GPTBot or ChatGPT-User on a page), when reviewing candidate AI-referral bursts before quoting server-side AI referral totals, or when wiring up / syncing a traffic source."
|
|
7386
|
-
},
|
|
7387
|
-
{
|
|
7388
|
-
name: "agent",
|
|
7389
|
-
title: "Aero agent lifecycle and memory",
|
|
7390
|
-
description: "Manage the built-in Aero agent: durable project-scoped memory (list/set/forget), clear the rolling transcript, and detach the external-agent webhook.",
|
|
7391
|
-
whenToLoad: "Load when reading or writing project-scoped Aero notes, clearing a stuck conversation, or removing an external agent webhook."
|
|
7392
|
-
},
|
|
7393
|
-
{
|
|
7394
|
-
name: "discovery",
|
|
7395
|
-
title: "Query discovery and research",
|
|
7396
|
-
description: "Find queries expands an ICP into a promotable tracked-query basket; research queries runs saved free-form experiments against one API model. Research never adds queries to tracking. Prospect snapshots generate a company report without creating a project.",
|
|
7397
|
-
whenToLoad: "Load for prospect snapshots, ICP-led candidates for a tracked basket, or research into free-form queries, model answers, sources, and location effects without changing tracking."
|
|
7398
|
-
}
|
|
7399
|
-
];
|
|
7400
|
-
function isCanonryMcpToolkitName(value) {
|
|
7401
|
-
return CANONRY_MCP_TOOLKIT_NAMES.includes(value);
|
|
7402
|
-
}
|
|
7403
|
-
|
|
7404
|
-
// src/mcp/dynamic-catalog.ts
|
|
7405
|
-
var DynamicToolCatalog = class {
|
|
7406
|
-
entries;
|
|
7407
|
-
loaded = /* @__PURE__ */ new Set();
|
|
7408
|
-
eager;
|
|
7409
|
-
scope;
|
|
7410
|
-
server;
|
|
7411
|
-
constructor(server, entries, scope, options = {}) {
|
|
7412
|
-
this.server = server;
|
|
7413
|
-
this.entries = entries;
|
|
7414
|
-
this.scope = scope;
|
|
7415
|
-
this.eager = Boolean(options.eager);
|
|
7416
|
-
if (this.eager) {
|
|
7417
|
-
for (const toolkit of CANONRY_MCP_TOOLKITS) {
|
|
7418
|
-
if (this.toolsForToolkit(toolkit.name).length > 0) {
|
|
7419
|
-
this.loaded.add(toolkit.name);
|
|
7420
|
-
}
|
|
7421
|
-
}
|
|
7422
|
-
}
|
|
7423
|
-
}
|
|
7424
|
-
applyInitialEnablement() {
|
|
7425
|
-
if (this.eager) return;
|
|
7426
|
-
this.batchListChanged(() => {
|
|
7427
|
-
for (const entry of this.entries) {
|
|
7428
|
-
if (entry.tool.tier !== "core") entry.registered.disable();
|
|
7429
|
-
}
|
|
7430
|
-
});
|
|
7431
|
-
}
|
|
7432
|
-
loadToolkit(rawName) {
|
|
7433
|
-
if (!isCanonryMcpToolkitName(rawName)) {
|
|
7434
|
-
const valid = CANONRY_MCP_TOOLKITS.map((t) => t.name).join(", ");
|
|
7435
|
-
throw new Error(`Unknown toolkit "${rawName}". Available: ${valid}.`);
|
|
7436
|
-
}
|
|
7437
|
-
const name = rawName;
|
|
7438
|
-
const matches = this.entries.filter((entry) => entry.tool.tier === name);
|
|
7439
|
-
if (matches.length === 0) {
|
|
7440
|
-
return { status: "empty", name, tools: [] };
|
|
7441
|
-
}
|
|
7442
|
-
if (this.loaded.has(name)) {
|
|
7443
|
-
return { status: "already-loaded", name, tools: matches.map((entry) => entry.tool.name) };
|
|
7444
|
-
}
|
|
7445
|
-
this.batchListChanged(() => {
|
|
7446
|
-
for (const entry of matches) {
|
|
7447
|
-
entry.registered.enable();
|
|
7448
|
-
}
|
|
7449
|
-
});
|
|
7450
|
-
this.loaded.add(name);
|
|
7451
|
-
return { status: "loaded", name, tools: matches.map((entry) => entry.tool.name) };
|
|
7452
|
-
}
|
|
7453
|
-
helpResult() {
|
|
7454
|
-
return {
|
|
7455
|
-
scope: this.scope,
|
|
7456
|
-
eager: this.eager,
|
|
7457
|
-
loadedToolkits: [...this.loaded].sort(),
|
|
7458
|
-
coreTools: this.entries.filter((entry) => entry.tool.tier === "core").map((entry) => entry.tool.name),
|
|
7459
|
-
liveTools: this.entries.filter((entry) => entry.tool.tier === "core" && toolOperationAccess(entry.tool) === OperationAccesses.live).map((entry) => entry.tool.name),
|
|
7460
|
-
toolkits: CANONRY_MCP_TOOLKITS.map((toolkit) => this.toolkitEntry(toolkit)).filter((entry) => entry.toolCount > 0),
|
|
7461
|
-
usage: this.eager ? "All tools available on this connection are already loaded. Use their listed schemas; tool visibility does not grant server permissions." : "Call canonry_load_toolkit with one of the toolkit names listed in `toolkits[].name` to register its tools for the rest of this session. Wait for its response before calling any newly enabled tool."
|
|
7462
|
-
};
|
|
7463
|
-
}
|
|
7464
|
-
toolkitEntry(toolkit) {
|
|
7465
|
-
const tools = this.toolsForToolkit(toolkit.name);
|
|
7466
|
-
return {
|
|
7467
|
-
name: toolkit.name,
|
|
7468
|
-
title: toolkit.title,
|
|
7469
|
-
description: toolkit.description,
|
|
7470
|
-
whenToLoad: toolkit.whenToLoad,
|
|
7471
|
-
toolCount: tools.length,
|
|
7472
|
-
tools,
|
|
7473
|
-
liveTools: this.entries.filter((entry) => entry.tool.tier === toolkit.name && toolOperationAccess(entry.tool) === OperationAccesses.live).map((entry) => entry.tool.name),
|
|
7474
|
-
loaded: this.loaded.has(toolkit.name)
|
|
7475
|
-
};
|
|
7476
|
-
}
|
|
7477
|
-
toolsForToolkit(name) {
|
|
7478
|
-
return this.entries.filter((entry) => entry.tool.tier === name).map((entry) => entry.tool.name);
|
|
7479
|
-
}
|
|
7480
|
-
// RegisteredTool.enable/disable each call sendToolListChanged on the McpServer
|
|
7481
|
-
// we registered with. Loading an 11-tool toolkit emits 11 notifications under
|
|
7482
|
-
// that contract, which a spec-compliant client will treat as 11 catalog
|
|
7483
|
-
// refetches. Coalesce them into one notification per batch by intercepting
|
|
7484
|
-
// the SDK's sender for the duration of the batch.
|
|
7485
|
-
batchListChanged(fn) {
|
|
7486
|
-
const host = this.server;
|
|
7487
|
-
const original = host.sendToolListChanged.bind(host);
|
|
7488
|
-
let suppressed = false;
|
|
7489
|
-
host.sendToolListChanged = () => {
|
|
7490
|
-
suppressed = true;
|
|
7491
|
-
};
|
|
7492
|
-
try {
|
|
7493
|
-
fn();
|
|
7494
|
-
} finally {
|
|
7495
|
-
host.sendToolListChanged = original;
|
|
7496
|
-
}
|
|
7497
|
-
if (suppressed) original();
|
|
7498
|
-
}
|
|
7499
|
-
};
|
|
7500
|
-
|
|
7501
|
-
// src/mcp/operations-guide.generated.ts
|
|
7502
|
-
var OPERATIONS_GUIDE = {
|
|
7503
|
-
"guideVersion": "v1",
|
|
7504
|
-
"operationsGuideUrl": "https://github.com/Canonry/canonry/blob/main/docs/agent-operations/v1.md",
|
|
7505
|
-
"resourceUri": "canonry://agent-operations/v1",
|
|
7506
|
-
"initialize": 'Canonry tracks how AI answer engines mention brands and cite domains. Start with canonry_help({intent:"status"}) or a workflow; follow its stored reads and approval boundaries. Connected MCP clients need no skill, resource, plugin, or local CLI. The Canonry skill offers optional additional guidance.\nmentioned = brand in answer TEXT; cited = domain in SOURCE links. Never compute one from the other. A null answerMentioned means not checked, not false. No recorded sweep means no measured figure.\nGet approval for live provider reads, sweeps, probes, research, syncs and writes, scoped to the exact target, action and work. A GET or readOnlyHint does not mean free. canonry_help returns all liveTools for this connection; each needs approval, including read-only tools.\nREST exposes x-canonry-access; CLI help/catalog expose access; MCP help lists liveTools.\nStored-only: CLI --stored-only or CANONRY_STORED_ONLY=1; MCP --stored-only, --scope=stored-only or CANONRY_MCP_SCOPE=stored-only. It refuses live/write work (including doctor) before execution and suppresses housekeeping. CLI refusal is STORED_ONLY_REFUSED. Explicit exports may write files; server accounting remains separate from business mutations.\nHelp and skills grant no permissions; the server enforces authority. Report missing tools or 403; never bypass them with other credentials or endpoints. Hosted catalogs are fixed; use canonry_load_toolkit only when help offers it.\nReport concrete Canonry failures, confusing output, workarounds or improvements to the user and once via canonry_feedback. Exclude secrets and customer data.\n',
|
|
7507
|
-
"approvalBoundary": [
|
|
7508
|
-
"provider reads",
|
|
7509
|
-
"sweeps",
|
|
7510
|
-
"writes"
|
|
7511
|
-
],
|
|
7512
|
-
"approvalRule": "Get explicit approval for the exact target, action, and bounded provider work before crossing a boundary. Existing approval covers only its stated scope; stop on refusal or ambiguous results.",
|
|
7513
|
-
"authority": "Guidance and tool visibility are not permission grants. Server-side roles, scopes, project boundaries, quotas, and approval receipts remain authoritative. Never bypass a refusal with different credentials or endpoints.",
|
|
7514
|
-
"workflows": {
|
|
7515
|
-
"operations": {
|
|
7516
|
-
"keywords": [
|
|
7517
|
-
"operations",
|
|
7518
|
-
"permissions",
|
|
7519
|
-
"settings",
|
|
7520
|
-
"telemetry",
|
|
7521
|
-
"logs",
|
|
7522
|
-
"configuration"
|
|
7523
|
-
],
|
|
7524
|
-
"next": [
|
|
7525
|
-
"canonry_key_self",
|
|
7526
|
-
"canonry_settings_get",
|
|
7527
|
-
"canonry_telemetry_get",
|
|
7528
|
-
"canonry_logs_list"
|
|
7529
|
-
],
|
|
7530
|
-
"guidance": "Inspect current credential and server state before proposing changes. Runtime logs require instance-wide logs.read; inspect retention, dropped, and captureErrors before drawing conclusions. File-backed hosts retain bounded redacted logs across restarts. Logs are separate from audit history. Respect a 403; never substitute credentials to bypass it. Settings writes require settings.write and explicit approval."
|
|
7531
|
-
},
|
|
7532
|
-
"status": {
|
|
7533
|
-
"keywords": [
|
|
7534
|
-
"status",
|
|
7535
|
-
"overview",
|
|
7536
|
-
"health"
|
|
7537
|
-
],
|
|
7538
|
-
"next": [
|
|
7539
|
-
"canonry_status",
|
|
7540
|
-
"canonry_projects_list",
|
|
7541
|
-
"canonry_project_overview"
|
|
7542
|
-
],
|
|
7543
|
-
"guidance": "Read canonry_status first for stored integration health, freshness, and repeated failures across accessible projects, then inspect a project overview for detail. Report missing evidence; do not start a sweep or sync to fill a gap."
|
|
7544
|
-
},
|
|
7545
|
-
"diagnose": {
|
|
7546
|
-
"keywords": [
|
|
7547
|
-
"diagnose",
|
|
7548
|
-
"diagnosis",
|
|
7549
|
-
"regression",
|
|
7550
|
-
"changed",
|
|
7551
|
-
"change",
|
|
7552
|
-
"troubleshoot"
|
|
7553
|
-
],
|
|
7554
|
-
"next": [
|
|
7555
|
-
"canonry_projects_list",
|
|
7556
|
-
"canonry_project_overview",
|
|
7557
|
-
"canonry_project_history"
|
|
7558
|
-
],
|
|
7559
|
-
"guidance": "Compare stored history in the same project, period, provider/model, location, and query-class scope. Separate observed changes from possible causes; propose any live verification for approval."
|
|
7560
|
-
},
|
|
7561
|
-
"prospecting": {
|
|
7562
|
-
"keywords": [
|
|
7563
|
-
"prospect",
|
|
7564
|
-
"prospects",
|
|
7565
|
-
"prospecting",
|
|
7566
|
-
"snapshot"
|
|
7567
|
-
],
|
|
7568
|
-
"next": [
|
|
7569
|
-
"canonry_settings_get"
|
|
7570
|
-
],
|
|
7571
|
-
"actions": [
|
|
7572
|
-
"canonry_snapshot"
|
|
7573
|
-
],
|
|
7574
|
-
"guidance": "Inspect stored provider settings, then agree on the company, domain, providers, and queries. Snapshot generation spends quota and fetches the site; approval must cover that work. No project is required. Use the snapshot action only when offered by this connection; its absence does not grant permission to bypass access restrictions."
|
|
7575
|
-
},
|
|
7576
|
-
"measurement": {
|
|
7577
|
-
"keywords": [
|
|
7578
|
-
"measurement",
|
|
7579
|
-
"measure",
|
|
7580
|
-
"portfolio",
|
|
7581
|
-
"property",
|
|
7582
|
-
"target",
|
|
7583
|
-
"query",
|
|
7584
|
-
"queries",
|
|
7585
|
-
"research"
|
|
7586
|
-
],
|
|
7587
|
-
"next": [
|
|
7588
|
-
"canonry_projects_list",
|
|
7589
|
-
"canonry_measurement_overview",
|
|
7590
|
-
"canonry_measurement_setup",
|
|
7591
|
-
"canonry_research_runs_list"
|
|
7592
|
-
],
|
|
7593
|
-
"guidance": "Inspect existing measurement before editing it. Preserve Simple versus Advanced scope, Property/Target identity, market, provider/model, and query class. Direct research submits final queries in one context; reviewed batches submit explicit destinations under one retry key. Expand patterns client-side: scope records a destination and never rewrites queries or fans out a group. Research is separate from tracking; publication does not authorize a sweep."
|
|
7594
|
-
},
|
|
7595
|
-
"integrations": {
|
|
7596
|
-
"keywords": [
|
|
7597
|
-
"integrations",
|
|
7598
|
-
"integration",
|
|
7599
|
-
"connect",
|
|
7600
|
-
"connection",
|
|
7601
|
-
"traffic",
|
|
7602
|
-
"gsc",
|
|
7603
|
-
"ga4",
|
|
7604
|
-
"ads",
|
|
7605
|
-
"gtm"
|
|
7606
|
-
],
|
|
7607
|
-
"next": [
|
|
7608
|
-
"canonry_status",
|
|
7609
|
-
"canonry_projects_list",
|
|
7610
|
-
"canonry_project_get",
|
|
7611
|
-
"canonry_ga_status",
|
|
7612
|
-
"canonry_google_ads_status"
|
|
7613
|
-
],
|
|
7614
|
-
"guidance": "Read canonry_status first for the stored instance or project health view, then use specialist tools for detail. Connecting, selecting resources, syncing, and live provider reads require scoped approval; never request credentials in chat."
|
|
7615
|
-
},
|
|
7616
|
-
"reports": {
|
|
7617
|
-
"keywords": [
|
|
7618
|
-
"reports",
|
|
7619
|
-
"report",
|
|
7620
|
-
"reporting",
|
|
7621
|
-
"summary"
|
|
7622
|
-
],
|
|
7623
|
-
"next": [
|
|
7624
|
-
"canonry_projects_list",
|
|
7625
|
-
"canonry_project_overview",
|
|
7626
|
-
"canonry_organic_evidence"
|
|
7627
|
-
],
|
|
7628
|
-
"guidance": "Build the requested summary from stored project overview, organic evidence, and the relevant visibility, measurement, integration, or traffic reads. Retain evidence dates, scope, sample sizes, missing data, and separate mention/citation signals; do not generate fresh runs implicitly."
|
|
7629
|
-
}
|
|
7630
|
-
},
|
|
7631
|
-
"markdown": "# Canonry Operations Guide v1\n\nCanonry is an agent-first AI visibility platform. MCP is the universal entry\npoint for connected agents. Host-native skills are optional upgrades, not a\nprerequisite or a permission mechanism.\n\n## Connect and choose a route\n\nRead the initialization guidance, then call `canonry_help` with an `intent`:\n`status`, `diagnose`, `operations`, `prospecting`, `measurement`, `integrations`,\n`reports`, or a short task\ndescription. Select an accessible project with `canonry_projects_list` before\nusing its exact name in project tools. Inspect each listed tool's input schema;\nhelp suggests tool names, not invented arguments or authorization.\n\nHelp returns a versioned, compact route: connection `mode`, available `next`\ntools, workflow guidance, approval boundaries, and this guide's URL. It performs\nno provider calls, reads no project data, and changes no permissions.\n`next` lists stored reads. Optional `actions` lists loaded tools for work that\nrequires approval; listing an action does not authorize or execute it.\n`includeCatalog: true` additionally returns toolkit details when needed.\n\nHosted connections use a fixed catalog. Help only suggests tools offered by that\nconnection; it never tells a hosted agent to dynamically load a toolkit. A\nprogressive local stdio connection may return `loadToolkits`: call\n`canonry_load_toolkit` with one returned name, await it, then call help again.\nLoading only changes local tool discovery, never server authority.\n\nThe optional `canonry://agent-operations/v1` MCP resource contains this same\nguide. If the host cannot read resources or open links, continue through help.\nDo not install a plugin, local runtime, or skill merely to use connected MCP.\nAn installed Codex or Claude Canonry skill contains a generated copy of this\nguide plus links to host-native references. It does not replace runtime help.\n\n## Vocabulary and evidence\n\n- **Mentioned** means the brand appears in answer text. **Cited** means its\n domain appears in source links. Either, both, or neither can occur; never\n compute one signal from the other.\n- `answerMentioned: null` means not checked, not false. Missing runs and empty\n populations mean no measurement, not zero visibility.\n- Preserve project, time window, provider, requested/served model, location,\n sample size, and query class when comparing evidence. Use server-returned\n metrics; do not invent a score from incompatible populations.\n- Simple projects and Advanced portfolios share the workflow. For Advanced\n results, preserve Property, Target, market, plan revision, and class scope.\n Groups organize navigation; do not infer an unrequested fan-out.\n- Research is isolated evidence, not tracked measurement. A probe still spends\n quota and persists evidence but is excluded from normal tracking metrics.\n\n## Workflows\n\n**Status:** read the stored overview and freshness first. Say when evidence is\nmissing instead of silently creating it.\n\n**Setup:** Page Health needs no answer-engine provider; AI Visibility does.\nAfter a Page Health result on an install with no provider (a `NO_PROVIDER`\nnotice, or doctor's `providers.none-configured`), propose AI Visibility setup\nas the next step. The operator adds the provider key in the dashboard or in\ntheir own terminal; never ask for it in chat.\nRerunning `canonry bootstrap` after a provider change reloads saved provider\nsettings on a matching running local server and reports whether they became\nactive. If the server is offline, start it to apply the saved settings. For an\nexplicit reload of the connected server's own config, use\n`canonry settings reload-providers` or `canonry_providers_reload` with install\nadministrator authority. Remote servers are never reloaded automatically by\nbootstrap, and a local server that belongs to another install is left alone.\nPorts and database settings still need a restart.\n\n**Diagnose:** inspect stored history and comparable evidence. Explain what\nchanged separately from why it might have changed. A hypothesis is not a\nmeasured cause. Propose bounded verification if stored evidence is insufficient.\n\n**Site Health:** read `canonry_site_health_issues` for stored technical findings,\naffected-page counts and example URLs, then `canonry_site_health_issue_pages`\nfor a selected issue's remaining pages. Pin subsequent reads to the returned\nrun. Inspect coverage and omissions: a passing score can still have findings,\nan older scan may lack cross-page evidence, and a partial scan cannot establish\nsite-wide absence. Advisory findings require judgment before proposing a repair.\nAudit evidence informs technical repairs and existing-page recommendations;\nit does not itself establish a new-blog opportunity or authorize any edit.\n\n**Prospecting:** generate a one-shot company snapshot without creating a project.\nInspect stored provider settings first. Agree on the company, domain, selected\nproviders, and queries before starting the quota-spending snapshot action.\nBrowser-only selection requires manual queries. Progressive stdio help offers\nthe discovery toolkit when this connection permits snapshots; load it, then\ncall help again. Fixed catalogs offer only already available actions. Read-only\nand restricted connections must not bypass missing snapshot access.\n\n**Measurement:** inspect the existing setup and results before proposing edits.\nKeep research, query tracking, plan publication, and sweep execution separate.\nFor direct research, submit the final editable query text in one context. For a\nreviewed batch, submit each explicit destination with its final text and one\nidempotency key. Pattern substitution happens in the client before either\nrequest; choosing a market or Property records a destination only and never\nrewrites a query or creates an automatic fan-out. `research.run` does not\nauthorize saving patterns, changing tracking, publishing plans, or settings.\nUse a supported preview where available, inspect its exact destination and\nrevision, then seek approval for the actual change. A preview may itself require\nwrite permission; never treat a dry-run flag as a universal safety guarantee.\n\n**Integrations:** inspect stored connection state and snapshot freshness first.\nProvider configuration evidence does not prove a browser event fired or a\nconversion was recorded. Connection, resource selection, refresh/sync, and live\nreads are separate actions. Credentials belong in the operator's secure setup\nflow, never in chat, tool arguments, reports, or public guidance.\n\n**Reports:** use saved evidence for the requested period and scope. Keep mention\nand citation signals separate, include dates and sample sizes, and state missing\nor stale inputs. For Advanced Property mention rankings, use\n`canonry_measurement_portfolio_summary` and its `mentionRanking.strongest`,\n`.weakest`, and `.excluded` lists. It defaults to non-brand questions; state the\nreturned class and report branded results separately. An unavailable portfolio\naggregate does not invalidate available Property mention rates. Flag excluded\nProperties individually; do not silently replace mention ranking with citation\nranking. Compact `nextCursor` completes only `pageList`; use `list` to enumerate\none ranking, markets, observed names or cited domains, preserving filters.\nFirst-page sibling lists are bounded summaries. Keep sample sizes and ties\nvisible. Preparing a report does not\nauthorize new measurement.\n\n## Authority and approval\n\n### Agent operations\n\nUse `canonry_key_self` (CLI `canonry key whoami --format json`) to inspect the\ncurrent credential's scopes, project boundary, and host-derived `operator`\nauthority without exposing its token. Missing `operator` means unapproved.\n`canonry_settings_get` and\n`canonry_telemetry_get` describe the connected server, not the agent's local\nmachine. Telemetry reports configured preference, effective state, and any\nenvironment override; inspecting status never creates an anonymous identifier.\nAfter approval, `canonry_telemetry_update` changes that preference and\n`canonry_provider_settings_update` changes an already-configured provider's\nmodel/quota. Both require `settings.write`; neither accepts credentials.\nServer telemetry reads and updates additionally require operator authority.\nOrdinary audit-history reads omit internal telemetry events and their state.\n\nOperator authority is deny-by-default and separate from customer admin roles.\nThe deployment owner must approve a dedicated, instance-wide API key's ID in\nthe server environment variable `CANONRY_OPERATOR_KEY_IDS` (comma-separated IDs),\nthen restart the server. Empty/unset approves nobody; wildcards are invalid.\nKeep the bearer private to internal operators; never approve a customer-held or\nshared proxy/bootstrap key. Use `logs.read` for read-only diagnostics, adding\n`settings.write` only when telemetry control is required. Ordinary key creation,\naccount roles, OAuth consent, and caller headers cannot grant operator status.\nRevoking an approved key invalidates it immediately. Host enrollment is a trust\nbootstrap step, intentionally unavailable through customer-facing APIs.\nAPI, CLI, and MCP enforce the same boundary; MCP hides internal tools unless\nthe server confirms operator authority, including in explicit read-only mode.\nProject analytics, research, and normal project permissions are unchanged.\n\n`canonry_logs_list` reads bounded, redacted runtime events from both the\napplication logger and Fastify request/error logging. It requires an\ninstance-wide `logs.read` grant (or wildcard) and a host-approved direct bearer.\nBrowser sessions, OAuth/delegated credentials, customer admins, and project-scoped\nkeys cannot use it, even with a project filter or a matching allowlist ID.\nA `logs.read`-only key is read-only automatically, without a\nsecond `read` marker. Named `*.read` scopes cannot grant mutations; an explicit\nwrite grant is needed and remains subject to its route gates. Returned messages\nare sanitized and bounded; raw request or response bodies, headers, cookies,\nprovider payloads, and stacks are not\npart of the queryable surface. The same secret-redaction policy runs before\nconsole output and storage. Do not deliberately log secrets: redaction is a\ndefense in depth, not permission to put credentials into diagnostic strings.\nOpaque escaped payloads containing secret assignments are omitted when safe\npartial masking cannot be guaranteed; correlate their retained error codes and IDs.\n\nFile-backed hosts retain runtime logs in SQLite across restarts, bounded to\n10,000 events and seven days. In-memory hosts report `retention: \"process\"`.\nFilter by `actor`, `requestId`, `runId`, `projectId`, `module`, `level`, or an\ninclusive `since`/`until` interval. Keep filters unchanged when resuming an\nopaque cursor; retention eviction can invalidate it. Inspect `retentionPolicy`,\n`captureErrors`, `dropped`, `truncated`, and `retention` before drawing\nconclusions. Missing logs are not proof that an action did not happen. Use\n`canonry_project_history` or `canonry_history_global` for persistent audit events;\noffset pages have deterministic ordering but are not snapshots of concurrent writes.\n\nAudit `actor` comes from authenticated identity (`user:<id>` or `api-key:<id>`),\nnot a caller-supplied header. A delegated MCP credential records its originating\nuser as actor and the actual credential in `credentialId`. `requestId` correlates\nHTTP events; `userAgent` and `actorSession` are bounded, untrusted client hints,\nnever identity or permission grants. Older audit rows are not backfilled with\nidentities the server cannot prove.\n\nBoth shipped HTTP hosts issue restart-safe UUID request IDs and return them in\n`x-request-id`. Use that value to correlate a CLI/API failure with log entries;\nHTTP diagnostics retain the method and route template, not raw URL parameters.\nRequest-bound loggers retain completion attribution, while generic background\ncontinuations stop inheriting caller identity after the response completes.\nCapture covers the owning server process after initialization, not arbitrary\nconsole output, other worker processes, or host/container logs. Run one server\ninstance per process and database, as required by the single-tenant deployment\nmodel; this is not a cross-tenant or distributed log collector.\n\nFor CLI use, settings reads are remote. Google setup and telemetry retain their\nlocal defaults: pass `--target server` explicitly to configure the connected\nserver. `schedule list <project>` lists all schedule kinds, and\n`notify events --target server` discovers the server's event catalog.\n\nMCP returns legacy text JSON plus structured results. Objects keep their shape;\narrays use `{items: [...]}` in `structuredContent`, and scalars use `{value: ...}`.\nErrors preserve the existing envelope and CLI exit codes: HTTP 4xx (including\n429 policy limits) use exit 1; HTTP 5xx use exit 2. Server-provided `Retry-After`\nand request IDs are exposed as `retryAfterMs` and `requestId` when available;\nclients do not infer retryability from HTTP 429 or retry automatically.\nFor a write with an ambiguous outcome, inspect saved state or its receipt before\nretrying; a retry hint is not proof that repeating a write is safe.\n\n### Action boundaries\n\nStart with stored evidence. Before a live provider read, sweep, probe, research\nrun, sync, write, or externally visible action, obtain approval covering its\nexact target, action, and bounded work. Approval already given for that exact\noperation need not be asked for again, but does not extend to more projects,\nlarger batches, retries with new identities, or recurring work.\n\nHTTP GET and MCP `readOnlyHint` describe aspects of an operation, not its cost\nor permission. Provider discovery, account reads, and live diagnostics may\nconsume quota even when labeled read-only. If the tool's effect is unclear,\ninspect its description and request direction before calling it.\n\nAuthentication, role/scope checks, project restrictions, quotas, and guarded\napproval receipts are enforced by the server. Help, skills, resources, and tool\nvisibility cannot grant authority. Never change credentials, endpoints, or\nproject identifiers to work around a missing tool or a `403` response.\n\nFor guarded ads writes, inspect unresolved operation receipts before retrying.\nUse the receipt's supported recovery action; do not replay a mutation under a\nnew identity. An executor cannot create or widen its own human approval grant.\nOn ambiguous results, exhausted bounds, or refusal, stop and report what is\nknown and what permission or operator action is needed.\n\n## Version and source\n\nThis public, versioned document is the source for initialization guidance,\nintent routes, the optional resource, and generated Canonry `SKILL.md` files.\nGuide v1 may receive compatible clarifications; incompatible routing contracts\nrequire a new guide version. The running server's help describes its actual\ncatalog and remains usable without fetching this document.\n"
|
|
7632
|
-
};
|
|
7633
|
-
|
|
7634
|
-
// src/mcp/operations-guide.ts
|
|
7635
|
-
function operationsHelp(catalog, mode, intent = "", includeCatalog = false) {
|
|
7636
|
-
const workflows = Object.keys(OPERATIONS_GUIDE.workflows);
|
|
7637
|
-
const words = new Set(intent.toLowerCase().split(/[^a-z0-9-]+/));
|
|
7638
|
-
const workflow = workflows.find((name) => OPERATIONS_GUIDE.workflows[name].keywords.some((word) => words.has(word))) ?? "status";
|
|
7639
|
-
const route = OPERATIONS_GUIDE.workflows[workflow];
|
|
7640
|
-
const available = /* @__PURE__ */ new Set([...catalog.coreTools, ...catalog.toolkits.filter((t) => t.loaded).flatMap((t) => t.tools)]);
|
|
7641
|
-
const reads = route.next;
|
|
7642
|
-
const requestedActions = "actions" in route ? route.actions : [];
|
|
7643
|
-
const next = reads.filter((name) => available.has(name)).slice(0, 4);
|
|
7644
|
-
const actions = requestedActions.filter((name) => available.has(name));
|
|
7645
|
-
if (reads.includes("canonry_projects_list") && next.length < 2 && available.has("canonry_project_overview") && !next.includes("canonry_project_overview")) {
|
|
7646
|
-
next.push("canonry_project_overview");
|
|
7647
|
-
}
|
|
7648
|
-
const wanted = [...reads, ...requestedActions];
|
|
7649
|
-
const loadToolkits = mode === "stdio-progressive" ? catalog.toolkits.filter((t) => !t.loaded && t.tools.some((name) => wanted.includes(name))).map((t) => t.name) : [];
|
|
7650
|
-
const liveTools = [...catalog.liveTools];
|
|
7651
|
-
for (const toolkit of catalog.toolkits) liveTools.push(...toolkit.liveTools);
|
|
7652
|
-
return {
|
|
7653
|
-
guideVersion: OPERATIONS_GUIDE.guideVersion,
|
|
7654
|
-
mode,
|
|
7655
|
-
scope: catalog.scope,
|
|
7656
|
-
workflow,
|
|
7657
|
-
next,
|
|
7658
|
-
...actions.length ? { actions } : {},
|
|
7659
|
-
workflows,
|
|
7660
|
-
guidance: route.guidance,
|
|
7661
|
-
approvalBoundary: OPERATIONS_GUIDE.approvalBoundary,
|
|
7662
|
-
approvalRule: OPERATIONS_GUIDE.approvalRule,
|
|
7663
|
-
authority: OPERATIONS_GUIDE.authority,
|
|
7664
|
-
operationsGuideUrl: OPERATIONS_GUIDE.operationsGuideUrl,
|
|
7665
|
-
...loadToolkits.length ? { loadToolkits } : {},
|
|
7666
|
-
...includeCatalog ? catalog : {},
|
|
7667
|
-
liveTools: [...new Set(liveTools)].sort()
|
|
7668
|
-
};
|
|
7669
|
-
}
|
|
7670
|
-
|
|
7671
|
-
// src/mcp/server.ts
|
|
7672
|
-
function createCanonryMcpServer(options = {}) {
|
|
7673
|
-
return createCanonryMcpServerWithCatalog(options).server;
|
|
7674
|
-
}
|
|
7675
|
-
var SERVER_INSTRUCTIONS = OPERATIONS_GUIDE.initialize;
|
|
7676
|
-
function updateNoticeInstructions(update) {
|
|
7677
|
-
const upgrade = update.installMethod === "docker" ? update.upgradeCommand : `${update.upgradeCommand}, then restart the Canonry server`;
|
|
7678
|
-
const caveat = upgradeCaveatFor(update.installMethod);
|
|
7679
|
-
return `Update available (UPDATE_AVAILABLE): canonry ${update.latest} is published; the connected Canonry server runs ${update.current}. Tell the operator. Upgrade: ${upgrade}. ${caveat ? `${caveat} ` : ""}Only upgrade with the operator's approval.`;
|
|
7680
|
-
}
|
|
7681
|
-
function updateNoticePayload(update) {
|
|
7682
|
-
const caveat = upgradeCaveatFor(update.installMethod);
|
|
7683
|
-
return { code: "UPDATE_AVAILABLE", ...update, ...caveat ? { note: caveat } : {} };
|
|
7684
|
-
}
|
|
7685
|
-
function readUpdateAvailable(getter) {
|
|
7686
|
-
try {
|
|
7687
|
-
return getter?.() ?? null;
|
|
7688
|
-
} catch {
|
|
7689
|
-
return null;
|
|
7690
|
-
}
|
|
7691
|
-
}
|
|
7692
|
-
function createCanonryMcpServerWithCatalog(options = {}) {
|
|
7693
|
-
const clientFactory = options.clientFactory ?? (() => createApiClient({ clientName: "canonry-mcp", surface: "mcp-stdio", actorSession: randomUUID() }));
|
|
7694
|
-
const client2 = clientFactory();
|
|
7695
|
-
const scope = options.scope ?? "all";
|
|
7696
|
-
const update = readUpdateAvailable(options.updateAvailable);
|
|
7697
|
-
const server = new McpServer({
|
|
7698
|
-
name: "canonry",
|
|
7699
|
-
version: PACKAGE_VERSION
|
|
7700
|
-
}, {
|
|
7701
|
-
instructions: update ? `${SERVER_INSTRUCTIONS.trimEnd()}
|
|
7702
|
-
|
|
7703
|
-
${updateNoticeInstructions(update)}` : SERVER_INSTRUCTIONS
|
|
7704
|
-
});
|
|
7705
|
-
server.validateToolInput = async (_tool, args) => args;
|
|
7706
|
-
const entries = [];
|
|
7707
|
-
for (const registryTool of getCanonryMcpTools(scope, options.tiers, options.credentialScopes, options.operator)) {
|
|
7708
|
-
const tool = registryTool;
|
|
7709
|
-
const handler = tool.handler;
|
|
7710
|
-
const registered = server.registerTool(
|
|
7711
|
-
tool.name,
|
|
7712
|
-
{
|
|
7713
|
-
title: tool.title,
|
|
7714
|
-
description: tool.description,
|
|
7715
|
-
inputSchema: tool.inputSchema,
|
|
7716
|
-
outputSchema: tool.outputSchema,
|
|
7717
|
-
annotations: tool.annotations
|
|
7718
|
-
},
|
|
7719
|
-
async (input) => withToolErrors(async () => {
|
|
7720
|
-
const parsed = tool.inputSchema.parse(input ?? {});
|
|
7721
|
-
return runWithUsageTags(client2, {
|
|
7722
|
-
mcpTool: tool.name,
|
|
7723
|
-
mcpCall: randomUUID(),
|
|
7724
|
-
mcpClient: server.server.getClientVersion()?.name
|
|
7725
|
-
}, () => handler(client2, parsed));
|
|
7726
|
-
})
|
|
7727
|
-
);
|
|
7728
|
-
entries.push({ tool, registered });
|
|
7729
|
-
}
|
|
7730
|
-
const eager = options.eager === true || options.tiers !== void 0;
|
|
7731
|
-
const catalog = new DynamicToolCatalog(server, entries, scope, { eager });
|
|
7732
|
-
catalog.applyInitialEnablement();
|
|
7733
|
-
const mode = options.tiers !== void 0 ? "hosted-fixed-catalog" : eager ? "stdio-fixed-catalog" : "stdio-progressive";
|
|
7734
|
-
registerMetaTools(server, catalog, { includeToolkitLoader: options.tiers === void 0, mode, updateAvailable: options.updateAvailable });
|
|
7735
|
-
server.registerResource("canonry-agent-operations-v1", OPERATIONS_GUIDE.resourceUri, {
|
|
7736
|
-
title: "Canonry Operations Guide v1",
|
|
7737
|
-
description: "Optional public operations guidance. Use canonry_help when resources are unavailable.",
|
|
7738
|
-
mimeType: "text/markdown"
|
|
7739
|
-
}, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: OPERATIONS_GUIDE.markdown }] }));
|
|
7740
|
-
return { server, catalog };
|
|
7741
|
-
}
|
|
7742
|
-
var loadToolkitInputSchema = z3.object({
|
|
7743
|
-
name: z3.enum(CANONRY_MCP_TOOLKIT_NAMES).describe("Toolkit name. List options with canonry_help.")
|
|
7744
|
-
});
|
|
7745
|
-
var helpInputSchema = z3.object({
|
|
7746
|
-
intent: z3.string().max(200).optional().describe("Workflow (status, diagnose, prospecting, measurement, integrations, reports) or a short task description."),
|
|
7747
|
-
includeCatalog: z3.boolean().optional().describe("Include full toolkit details. Omit for a compact, actionable route.")
|
|
7748
|
-
});
|
|
7749
|
-
function registerMetaTools(server, catalog, opts) {
|
|
7750
|
-
server.registerTool(
|
|
7751
|
-
"canonry_help",
|
|
7752
|
-
{
|
|
7753
|
-
title: "Guide a Canonry workflow",
|
|
7754
|
-
description: "Start here: route an intent to available stored-evidence tools, separately listed actions requiring approval, and workflow guidance. No provider calls or installation required. Optionally include full toolkit details.",
|
|
7755
|
-
inputSchema: helpInputSchema.shape,
|
|
7756
|
-
annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
|
|
7757
|
-
},
|
|
7758
|
-
async (input) => {
|
|
7759
|
-
try {
|
|
7760
|
-
const parsed = helpInputSchema.parse(input ?? {});
|
|
7761
|
-
const update = readUpdateAvailable(opts.updateAvailable);
|
|
7762
|
-
const result = {
|
|
7763
|
-
...operationsHelp(catalog.helpResult(), opts.mode, parsed.intent, parsed.includeCatalog),
|
|
7764
|
-
...update ? { updateAvailable: updateNoticePayload(update) } : {}
|
|
7765
|
-
};
|
|
7766
|
-
return { ...jsonToolResult(result), structuredContent: result };
|
|
7767
|
-
} catch (error) {
|
|
7768
|
-
return errorToolResult(error);
|
|
7769
|
-
}
|
|
7770
|
-
}
|
|
7771
|
-
);
|
|
7772
|
-
if (!opts.includeToolkitLoader) return;
|
|
7773
|
-
server.registerTool(
|
|
7774
|
-
"canonry_load_toolkit",
|
|
7775
|
-
{
|
|
7776
|
-
title: "Load a Canonry MCP toolkit",
|
|
7777
|
-
description: `Register a toolkit's tools for this session and emit one notifications/tools/list_changed. Idempotent. Loaded toolkits remain loaded for the rest of the session. Wait for this call to return before calling any newly enabled tool \u2014 pipelining the call with a tools/call on the same connection can race the registration and fail with "MCP error -32602: Tool ... disabled".`,
|
|
7778
|
-
inputSchema: loadToolkitInputSchema.shape,
|
|
7779
|
-
annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: false }
|
|
7780
|
-
},
|
|
7781
|
-
async (input) => withToolErrors(async () => {
|
|
7782
|
-
const parsed = loadToolkitInputSchema.parse(input ?? {});
|
|
7783
|
-
return catalog.loadToolkit(parsed.name);
|
|
7784
|
-
})
|
|
7785
|
-
);
|
|
7786
|
-
}
|
|
7787
|
-
function getCanonryMcpTools(scope = "all", tiers, credentialScopes, operator = false) {
|
|
7788
|
-
const readOnly = scope === "read-only" || credentialScopes !== void 0 && isReadOnlyKey(credentialScopes);
|
|
7789
|
-
const restricted = credentialScopes && restrictedWriteScopes(credentialScopes);
|
|
7790
|
-
const authorized = canonryMcpTools.filter((tool) => !tool.requiresOperator || operator);
|
|
7791
|
-
const byScope = scope === "stored-only" ? authorized.filter((tool) => toolOperationAccess(tool) === OperationAccesses.stored) : readOnly ? authorized.filter((tool) => tool.access === "read") : authorized.filter((tool) => {
|
|
7792
|
-
if (!restricted || tool.access === "read") return true;
|
|
7793
|
-
if (tool.requiredScope && restricted.includes(tool.requiredScope)) return true;
|
|
7794
|
-
return restricted.some((grant) => grant !== RESEARCH_RUN_SCOPE) && tool.tier === "ads";
|
|
7795
|
-
});
|
|
7796
|
-
if (!tiers) return byScope;
|
|
7797
|
-
const wanted = new Set(tiers);
|
|
7798
|
-
return byScope.filter((tool) => wanted.has(tool.tier));
|
|
7799
|
-
}
|
|
7800
|
-
|
|
7801
|
-
// src/commands/skills.ts
|
|
7802
|
-
import crypto2 from "crypto";
|
|
7803
|
-
import fs2 from "fs";
|
|
7804
|
-
import os2 from "os";
|
|
7805
|
-
import path2 from "path";
|
|
7806
|
-
import { fileURLToPath } from "url";
|
|
7807
|
-
var BUNDLED_SKILL_NAMES = ["canonry", "aero"];
|
|
7808
|
-
function resolveBundledSkillsRoot(pkgDir) {
|
|
7809
|
-
const here = pkgDir ?? path2.dirname(fileURLToPath(import.meta.url));
|
|
7810
|
-
const candidates = [
|
|
7811
|
-
path2.join(here, "../assets/agent-workspace/skills"),
|
|
7812
|
-
path2.join(here, "../../assets/agent-workspace/skills"),
|
|
7813
|
-
path2.join(here, "../../../../skills")
|
|
7814
|
-
];
|
|
7815
|
-
for (const candidate of candidates) {
|
|
7816
|
-
if (BUNDLED_SKILL_NAMES.every((name) => fs2.existsSync(path2.join(candidate, name, "SKILL.md")))) {
|
|
7817
|
-
return candidate;
|
|
7818
|
-
}
|
|
7819
|
-
}
|
|
7820
|
-
throw new CliError({
|
|
7821
|
-
code: "INTERNAL_ERROR",
|
|
7822
|
-
message: `Bundled skills not found. Searched:
|
|
7823
|
-
${candidates.join("\n ")}`,
|
|
7824
|
-
exitCode: 2
|
|
7825
|
-
});
|
|
7826
|
-
}
|
|
7827
|
-
function parseDescription(content) {
|
|
7828
|
-
const fmMatch = /^---\n([\s\S]*?)\n---/.exec(content);
|
|
7829
|
-
if (!fmMatch) return "";
|
|
7830
|
-
const descMatch = /^description:\s*(\S.*)$/m.exec(fmMatch[1]);
|
|
7831
|
-
if (!descMatch) return "";
|
|
7832
|
-
return descMatch[1].replace(/^["']|["']$/g, "").trim();
|
|
7833
|
-
}
|
|
7834
|
-
function getBundledSkills(pkgDir) {
|
|
7835
|
-
const root = resolveBundledSkillsRoot(pkgDir);
|
|
7836
|
-
return BUNDLED_SKILL_NAMES.map((name) => {
|
|
7837
|
-
const skillDir = path2.join(root, name);
|
|
7838
|
-
const skillFile = path2.join(skillDir, "SKILL.md");
|
|
7839
|
-
const content = fs2.readFileSync(skillFile, "utf-8");
|
|
7840
|
-
return { name, description: parseDescription(content), bundledPath: skillDir };
|
|
7841
|
-
});
|
|
7842
|
-
}
|
|
7843
|
-
function walkRelative(dir, prefix = "") {
|
|
7844
|
-
const out = [];
|
|
7845
|
-
for (const entry of fs2.readdirSync(dir, { withFileTypes: true })) {
|
|
7846
|
-
const rel = prefix ? path2.join(prefix, entry.name) : entry.name;
|
|
7847
|
-
const full = path2.join(dir, entry.name);
|
|
7848
|
-
if (entry.isDirectory()) {
|
|
7849
|
-
out.push(...walkRelative(full, rel));
|
|
7850
|
-
} else if (entry.isFile()) {
|
|
7851
|
-
out.push(rel);
|
|
7852
|
-
}
|
|
7853
|
-
}
|
|
7854
|
-
return out.sort();
|
|
7855
|
-
}
|
|
7856
|
-
function sha256File(filePath) {
|
|
7857
|
-
return crypto2.createHash("sha256").update(fs2.readFileSync(filePath)).digest("hex");
|
|
7858
|
-
}
|
|
7859
|
-
function readSkillManifest(skillDir) {
|
|
7860
|
-
try {
|
|
7861
|
-
return coerceSkillManifest(JSON.parse(fs2.readFileSync(path2.join(skillDir, SKILL_MANIFEST_FILENAME), "utf-8")));
|
|
7862
|
-
} catch {
|
|
7863
|
-
return null;
|
|
7864
|
-
}
|
|
7865
|
-
}
|
|
7866
|
-
function writeSkillManifest(skillDir, manifest) {
|
|
7867
|
-
fs2.writeFileSync(path2.join(skillDir, SKILL_MANIFEST_FILENAME), `${JSON.stringify(manifest, null, 2)}
|
|
7868
|
-
`, "utf-8");
|
|
7869
|
-
}
|
|
7870
|
-
function reconcileSkillTree(srcDir, destDir, manifest, force) {
|
|
7871
|
-
const result = { added: [], updated: [], unchanged: [], conflicts: [], bundledHashes: /* @__PURE__ */ new Map() };
|
|
7872
|
-
for (const rel of walkRelative(srcDir)) {
|
|
7873
|
-
const srcPath = path2.join(srcDir, rel);
|
|
7874
|
-
const destPath = path2.join(destDir, rel);
|
|
7875
|
-
const bundledHash = sha256File(srcPath);
|
|
7876
|
-
result.bundledHashes.set(rel, bundledHash);
|
|
7877
|
-
const installedHash = fs2.existsSync(destPath) ? sha256File(destPath) : void 0;
|
|
7878
|
-
const state = classifySkillFile({ bundledHash, installedHash, manifestHash: manifest?.files[rel] });
|
|
7879
|
-
switch (state) {
|
|
7880
|
-
case "missing":
|
|
7881
|
-
fs2.mkdirSync(path2.dirname(destPath), { recursive: true });
|
|
7882
|
-
fs2.copyFileSync(srcPath, destPath);
|
|
7883
|
-
result.added.push(rel);
|
|
7884
|
-
break;
|
|
7885
|
-
case "unchanged":
|
|
7886
|
-
result.unchanged.push(rel);
|
|
7887
|
-
break;
|
|
7888
|
-
case "stale":
|
|
7889
|
-
fs2.copyFileSync(srcPath, destPath);
|
|
7890
|
-
result.updated.push(rel);
|
|
7891
|
-
break;
|
|
7892
|
-
case "edited":
|
|
7893
|
-
if (force) {
|
|
7894
|
-
fs2.copyFileSync(srcPath, destPath);
|
|
7895
|
-
result.updated.push(rel);
|
|
7896
|
-
} else {
|
|
7897
|
-
result.conflicts.push(rel);
|
|
7898
|
-
}
|
|
7899
|
-
break;
|
|
7900
|
-
}
|
|
7901
|
-
}
|
|
7902
|
-
return result;
|
|
7903
|
-
}
|
|
7904
|
-
function buildManifest(skillName, recon, prior) {
|
|
7905
|
-
const conflicts = new Set(recon.conflicts);
|
|
7906
|
-
const files = {};
|
|
7907
|
-
for (const [rel, bundledHash] of recon.bundledHashes) {
|
|
7908
|
-
files[rel] = conflicts.has(rel) ? prior?.files[rel] ?? bundledHash : bundledHash;
|
|
7909
|
-
}
|
|
7910
|
-
return { skill: skillName, version: PACKAGE_VERSION, files };
|
|
7911
|
-
}
|
|
7912
|
-
function describeChanges(recon) {
|
|
7913
|
-
const parts = [];
|
|
7914
|
-
if (recon.added.length > 0) parts.push(`${recon.added.length} added`);
|
|
7915
|
-
if (recon.updated.length > 0) parts.push(`${recon.updated.length} refreshed`);
|
|
7916
|
-
return parts.length > 0 ? parts.join(", ") : "no changes";
|
|
7917
|
-
}
|
|
7918
|
-
function buildClaudeMessage(name, status, recon) {
|
|
7919
|
-
const rel = `.claude/skills/${name}`;
|
|
7920
|
-
let message = status === "installed" ? `Installed ${rel}` : status === "updated" ? `Updated ${rel} (${describeChanges(recon)})` : `Already installed: ${rel}`;
|
|
7921
|
-
if (recon.conflicts.length > 0) {
|
|
7922
|
-
message += ` \u2014 ${recon.conflicts.length} file(s) differ from the bundle (local edits kept; pass --force to overwrite)`;
|
|
7923
|
-
}
|
|
7924
|
-
return message;
|
|
7925
|
-
}
|
|
7926
|
-
function installClaudeSkill(skill, targetDir, force) {
|
|
7927
|
-
const targetPath = path2.join(targetDir, ".claude", "skills", skill.name);
|
|
7928
|
-
const existedBefore = fs2.existsSync(path2.join(targetPath, "SKILL.md"));
|
|
7929
|
-
const priorManifest = readSkillManifest(targetPath);
|
|
7930
|
-
fs2.mkdirSync(targetPath, { recursive: true });
|
|
7931
|
-
const recon = reconcileSkillTree(skill.bundledPath, targetPath, priorManifest, force);
|
|
7932
|
-
writeSkillManifest(targetPath, buildManifest(skill.name, recon, priorManifest));
|
|
7933
|
-
const changed = recon.added.length + recon.updated.length;
|
|
7934
|
-
const status = !existedBefore ? "installed" : changed > 0 ? "updated" : "already-installed";
|
|
7935
|
-
return {
|
|
7936
|
-
skill: skill.name,
|
|
7937
|
-
client: CodingAgents.claude,
|
|
7938
|
-
targetPath,
|
|
7939
|
-
status,
|
|
7940
|
-
message: buildClaudeMessage(skill.name, status, recon),
|
|
7941
|
-
added: recon.added,
|
|
7942
|
-
updated: recon.updated,
|
|
7943
|
-
unchanged: recon.unchanged,
|
|
7944
|
-
conflicts: recon.conflicts
|
|
7945
|
-
};
|
|
7946
|
-
}
|
|
7947
|
-
function installCodexSymlink(skill, targetDir, force) {
|
|
7948
|
-
const codexPath = path2.join(targetDir, ".codex", "skills", skill.name);
|
|
7949
|
-
const claudePath = path2.join(targetDir, ".claude", "skills", skill.name);
|
|
7950
|
-
const linkTarget = path2.relative(path2.dirname(codexPath), claudePath);
|
|
7951
|
-
fs2.mkdirSync(path2.dirname(codexPath), { recursive: true });
|
|
7952
|
-
let stat;
|
|
7953
|
-
try {
|
|
7954
|
-
stat = fs2.lstatSync(codexPath);
|
|
7955
|
-
} catch {
|
|
7956
|
-
stat = void 0;
|
|
7957
|
-
}
|
|
7958
|
-
if (stat?.isSymbolicLink()) {
|
|
7959
|
-
const existing = fs2.readlinkSync(codexPath);
|
|
7960
|
-
if (existing === linkTarget) {
|
|
7961
|
-
return {
|
|
7962
|
-
skill: skill.name,
|
|
7963
|
-
client: CodingAgents.codex,
|
|
7964
|
-
targetPath: codexPath,
|
|
7965
|
-
status: "already-linked",
|
|
7966
|
-
message: `Already linked: .codex/skills/${skill.name}`
|
|
7967
|
-
};
|
|
7968
|
-
}
|
|
7969
|
-
if (!force) {
|
|
7970
|
-
throw new CliError({
|
|
7971
|
-
code: "VALIDATION_ERROR",
|
|
7972
|
-
message: `.codex/skills/${skill.name} is a symlink pointing elsewhere (${existing}). Pass --force to relink.`,
|
|
7973
|
-
details: { skill: skill.name, targetPath: codexPath, existingTarget: existing },
|
|
7974
|
-
exitCode: 1
|
|
7975
|
-
});
|
|
7976
|
-
}
|
|
7977
|
-
fs2.unlinkSync(codexPath);
|
|
7978
|
-
fs2.symlinkSync(linkTarget, codexPath);
|
|
7979
|
-
return {
|
|
7980
|
-
skill: skill.name,
|
|
7981
|
-
client: CodingAgents.codex,
|
|
7982
|
-
targetPath: codexPath,
|
|
7983
|
-
status: "relinked",
|
|
7984
|
-
message: `Relinked .codex/skills/${skill.name} \u2192 ${linkTarget}`
|
|
7985
|
-
};
|
|
7986
|
-
}
|
|
7987
|
-
if (stat) {
|
|
7988
|
-
if (!force) {
|
|
7989
|
-
throw new CliError({
|
|
7990
|
-
code: "VALIDATION_ERROR",
|
|
7991
|
-
message: `.codex/skills/${skill.name} exists but is not a symlink. Pass --force to replace.`,
|
|
7992
|
-
details: { skill: skill.name, targetPath: codexPath },
|
|
7993
|
-
exitCode: 1
|
|
7994
|
-
});
|
|
7995
|
-
}
|
|
7996
|
-
fs2.rmSync(codexPath, { recursive: true, force: true });
|
|
7997
|
-
}
|
|
7998
|
-
fs2.symlinkSync(linkTarget, codexPath);
|
|
7999
|
-
return {
|
|
8000
|
-
skill: skill.name,
|
|
8001
|
-
client: CodingAgents.codex,
|
|
8002
|
-
targetPath: codexPath,
|
|
8003
|
-
status: stat ? "relinked" : "linked",
|
|
8004
|
-
message: stat ? `Replaced and linked .codex/skills/${skill.name} \u2192 ${linkTarget}` : `Linked .codex/skills/${skill.name} \u2192 ${linkTarget}`
|
|
8005
|
-
};
|
|
8006
|
-
}
|
|
8007
|
-
function buildSummaryMessage(results) {
|
|
8008
|
-
const counts = {};
|
|
8009
|
-
for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1;
|
|
8010
|
-
const parts = Object.entries(counts).map(([status, n]) => `${n} ${status}`);
|
|
8011
|
-
let message = `Skills install summary: ${parts.join(", ")}.`;
|
|
8012
|
-
const totalConflicts = results.reduce((sum, r) => sum + (r.conflicts?.length ?? 0), 0);
|
|
8013
|
-
if (totalConflicts > 0) {
|
|
8014
|
-
message += ` ${totalConflicts} file(s) differ from the bundle and were kept \u2014 pass --force to overwrite local edits.`;
|
|
8015
|
-
}
|
|
8016
|
-
return message;
|
|
8017
|
-
}
|
|
8018
|
-
function getBundledSkillSnapshots(pkgDir) {
|
|
8019
|
-
return getBundledSkills(pkgDir).map((skill) => {
|
|
8020
|
-
const files = {};
|
|
8021
|
-
for (const rel of walkRelative(skill.bundledPath)) {
|
|
8022
|
-
files[rel] = sha256File(path2.join(skill.bundledPath, rel));
|
|
8023
|
-
}
|
|
8024
|
-
return {
|
|
8025
|
-
name: skill.name,
|
|
8026
|
-
version: PACKAGE_VERSION,
|
|
8027
|
-
files,
|
|
8028
|
-
description: readBundledSkillDescription(skill.bundledPath)
|
|
8029
|
-
};
|
|
8030
|
-
});
|
|
8031
|
-
}
|
|
8032
|
-
function readBundledSkillDescription(skillDir) {
|
|
8033
|
-
let raw;
|
|
8034
|
-
try {
|
|
8035
|
-
raw = fs2.readFileSync(path2.join(skillDir, "SKILL.md"), "utf-8");
|
|
8036
|
-
} catch {
|
|
8037
|
-
return void 0;
|
|
8038
|
-
}
|
|
8039
|
-
const parts = raw.split("---");
|
|
8040
|
-
if (parts.length < 3) return void 0;
|
|
8041
|
-
const lines = (parts[1] ?? "").split("\n");
|
|
8042
|
-
const collected = [];
|
|
8043
|
-
let inside = false;
|
|
8044
|
-
for (const line of lines) {
|
|
8045
|
-
const isTopLevelKey = /^[a-z][\w-]*:/i.test(line);
|
|
8046
|
-
if (inside && isTopLevelKey) break;
|
|
8047
|
-
if (isTopLevelKey && line.startsWith("description:")) {
|
|
8048
|
-
inside = true;
|
|
8049
|
-
collected.push(line.slice("description:".length).trim());
|
|
8050
|
-
continue;
|
|
8051
|
-
}
|
|
8052
|
-
if (inside) collected.push(line.trim());
|
|
8053
|
-
}
|
|
8054
|
-
if (!inside) return void 0;
|
|
8055
|
-
const value = collected.join(" ").trim();
|
|
8056
|
-
const unquoted = value.length >= 2 && value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1) : value;
|
|
8057
|
-
return unquoted.length > 0 ? unquoted : void 0;
|
|
8058
|
-
}
|
|
8059
|
-
async function installSkills(opts = {}) {
|
|
8060
|
-
const targetDir = opts.user ? os2.homedir() : path2.resolve(opts.dir ?? process.cwd());
|
|
8061
|
-
const client2 = opts.client ?? SkillsClients.all;
|
|
8062
|
-
const force = opts.force ?? false;
|
|
8063
|
-
const allSkills = getBundledSkills();
|
|
8064
|
-
const requestedNames = opts.skills && opts.skills.length > 0 ? opts.skills : allSkills.map((s) => s.name);
|
|
8065
|
-
const knownNames = new Set(allSkills.map((s) => s.name));
|
|
8066
|
-
const unknown = requestedNames.filter((n) => !knownNames.has(n));
|
|
8067
|
-
if (unknown.length > 0) {
|
|
8068
|
-
throw new CliError({
|
|
8069
|
-
code: "VALIDATION_ERROR",
|
|
8070
|
-
message: `Unknown skill(s): ${unknown.join(", ")}. Available: ${[...knownNames].join(", ")}`,
|
|
8071
|
-
details: { unknownSkills: unknown, availableSkills: [...knownNames] },
|
|
8072
|
-
exitCode: 1
|
|
8073
|
-
});
|
|
8074
|
-
}
|
|
8075
|
-
const skillsToInstall = allSkills.filter((s) => requestedNames.includes(s.name));
|
|
8076
|
-
fs2.mkdirSync(targetDir, { recursive: true });
|
|
8077
|
-
const results = [];
|
|
8078
|
-
for (const skill of skillsToInstall) {
|
|
8079
|
-
results.push(installClaudeSkill(skill, targetDir, force));
|
|
8080
|
-
if (client2 !== SkillsClients.claude) {
|
|
8081
|
-
results.push(installCodexSymlink(skill, targetDir, force));
|
|
8082
|
-
}
|
|
8083
|
-
}
|
|
8084
|
-
return {
|
|
8085
|
-
targetDir,
|
|
8086
|
-
results,
|
|
8087
|
-
message: buildSummaryMessage(results)
|
|
8088
|
-
};
|
|
8089
|
-
}
|
|
8090
|
-
async function listSkills(opts = {}) {
|
|
8091
|
-
const skills = getBundledSkills();
|
|
8092
|
-
if (isMachineFormat(opts.format)) {
|
|
8093
|
-
console.log(JSON.stringify({
|
|
8094
|
-
skills: skills.map((s) => ({
|
|
8095
|
-
name: s.name,
|
|
8096
|
-
description: s.description,
|
|
8097
|
-
claudePath: `.claude/skills/${s.name}`,
|
|
8098
|
-
codexPath: `.codex/skills/${s.name}`
|
|
8099
|
-
}))
|
|
8100
|
-
}, null, 2));
|
|
8101
|
-
return;
|
|
8102
|
-
}
|
|
8103
|
-
console.log("Bundled canonry skills:\n");
|
|
8104
|
-
for (const skill of skills) {
|
|
8105
|
-
console.log(` ${skill.name}`);
|
|
8106
|
-
if (skill.description) console.log(` ${skill.description}`);
|
|
8107
|
-
console.log(` Claude: .claude/skills/${skill.name}/`);
|
|
8108
|
-
console.log(` Codex: .codex/skills/${skill.name} (symlink \u2192 ../../.claude/skills/${skill.name})`);
|
|
8109
|
-
console.log();
|
|
8110
|
-
}
|
|
8111
|
-
}
|
|
8112
|
-
function emitInstallSummary(summary, format) {
|
|
8113
|
-
if (isMachineFormat(format)) {
|
|
8114
|
-
console.log(JSON.stringify(summary, null, 2));
|
|
8115
|
-
return;
|
|
8116
|
-
}
|
|
8117
|
-
for (const r of summary.results) console.log(r.message);
|
|
8118
|
-
console.log(`
|
|
8119
|
-
Target: ${summary.targetDir}`);
|
|
8120
|
-
console.log(summary.message);
|
|
8121
|
-
}
|
|
8122
|
-
function shouldPrintServeSkillsNudge(nudge, updateAvailable) {
|
|
8123
|
-
if (!nudge) return false;
|
|
8124
|
-
if (nudge.source === "plugin" && updateAvailable) return false;
|
|
8125
|
-
return true;
|
|
8126
|
-
}
|
|
8127
|
-
function getMissingUserSkillsNudge(home, agentPlugin) {
|
|
8128
|
-
if (!home) return null;
|
|
8129
|
-
const skillsBase = path2.join(home, ".claude", "skills");
|
|
8130
|
-
const installed = [];
|
|
8131
|
-
const missing = [];
|
|
8132
|
-
for (const name of BUNDLED_SKILL_NAMES) {
|
|
8133
|
-
const skillFile = path2.join(skillsBase, name, "SKILL.md");
|
|
8134
|
-
if (existsSafe(skillFile)) installed.push(name);
|
|
8135
|
-
else missing.push(name);
|
|
8136
|
-
}
|
|
8137
|
-
if (agentPlugin && agentPlugin.configuredClients.length > 0) {
|
|
8138
|
-
const unverifiedClients = agentPlugin.configuredClients.filter((client2) => !agentPlugin.verifiedClients.includes(client2));
|
|
8139
|
-
const mismatchedClients = agentPlugin.verifiedClients.filter((client2) => agentPlugin.verifiedClientVersions?.[client2] !== PACKAGE_VERSION);
|
|
8140
|
-
if (unverifiedClients.length === 0 && mismatchedClients.length === 0) return null;
|
|
8141
|
-
const displayClients = (clients) => clients.map((client2) => agentPluginClientLabel(client2)).join(" + ");
|
|
8142
|
-
const problems = [];
|
|
8143
|
-
if (unverifiedClients.length > 0) {
|
|
8144
|
-
problems.push(`The Canonry plugin is enabled for ${displayClients(unverifiedClients)}, but its cached manifest and skill assets could not be verified.`);
|
|
8145
|
-
}
|
|
8146
|
-
if (mismatchedClients.length > 0) {
|
|
8147
|
-
problems.push(`${formatCanonryPluginVersionMismatch({
|
|
8148
|
-
mismatchedClients,
|
|
8149
|
-
verifiedClientVersions: agentPlugin.verifiedClientVersions,
|
|
8150
|
-
runningVersion: PACKAGE_VERSION
|
|
8151
|
-
})}.`);
|
|
8152
|
-
}
|
|
8153
|
-
const hintClients = [.../* @__PURE__ */ new Set([...unverifiedClients, ...mismatchedClients])];
|
|
8154
|
-
return {
|
|
8155
|
-
message: `Tip: ${problems.join(" ")} ${formatCanonryPluginUpdateHint(hintClients)}`,
|
|
8156
|
-
source: "plugin",
|
|
8157
|
-
missing,
|
|
8158
|
-
installed
|
|
8159
|
-
};
|
|
8160
|
-
}
|
|
8161
|
-
if (missing.length === 0) return null;
|
|
8162
|
-
const fix = missing.length === BUNDLED_SKILL_NAMES.length ? "canonry skills install --user" : `canonry skills install ${missing.join(" ")} --user`;
|
|
8163
|
-
return {
|
|
8164
|
-
message: `Tip: ${missing.join(" + ")} skill${missing.length === 1 ? "" : "s"} not installed in ~/.claude/skills/. Run \`${fix}\` so Claude/Codex sessions on this host auto-load the canonry reference docs.`,
|
|
8165
|
-
source: "legacy-skills",
|
|
8166
|
-
missing,
|
|
8167
|
-
installed
|
|
8168
|
-
};
|
|
8169
|
-
}
|
|
8170
|
-
function existsSafe(p) {
|
|
8171
|
-
try {
|
|
8172
|
-
return fs2.existsSync(p);
|
|
8173
|
-
} catch {
|
|
8174
|
-
return false;
|
|
8175
|
-
}
|
|
8176
|
-
}
|
|
8177
|
-
function parseSkillsClient(value) {
|
|
8178
|
-
if (!value) return SkillsClients.all;
|
|
8179
|
-
const parsed = skillsClientSchema.safeParse(value);
|
|
8180
|
-
if (parsed.success) return parsed.data;
|
|
8181
|
-
const allowed = skillsClientSchema.options;
|
|
8182
|
-
throw new CliError({
|
|
8183
|
-
code: "VALIDATION_ERROR",
|
|
8184
|
-
message: `Invalid --client value "${value}". Must be one of: ${allowed.join(", ")}`,
|
|
8185
|
-
details: { flag: "client", value, allowed },
|
|
8186
|
-
exitCode: 1
|
|
8187
|
-
});
|
|
8188
|
-
}
|
|
8189
|
-
|
|
8190
6553
|
export {
|
|
8191
|
-
resolveSentimentInstallConfig,
|
|
8192
|
-
sentimentInstallReadiness,
|
|
8193
|
-
AGENT_REASONING_LEVELS,
|
|
8194
|
-
dashboardManagedRunKindsSchema,
|
|
8195
|
-
resolveOperatorApiKeyIds,
|
|
8196
|
-
withBootstrapProviderDefaults,
|
|
8197
|
-
getBootstrapEnv,
|
|
8198
|
-
providerConfigFromEntry,
|
|
8199
|
-
adapterSupportsBatch,
|
|
8200
|
-
batchEligibleProviderNames,
|
|
8201
|
-
providersWithUnsupportedBatch,
|
|
8202
|
-
getConfigDir,
|
|
8203
|
-
getConfigPath,
|
|
8204
|
-
loadConfig,
|
|
8205
|
-
loadConfigRaw,
|
|
8206
|
-
saveConfig,
|
|
8207
|
-
saveConfigPatch,
|
|
8208
|
-
clearDashboardPassword,
|
|
8209
|
-
configExists,
|
|
8210
|
-
BUNDLED_SKILL_NAMES,
|
|
8211
|
-
getBundledSkillSnapshots,
|
|
8212
|
-
installSkills,
|
|
8213
|
-
listSkills,
|
|
8214
|
-
emitInstallSummary,
|
|
8215
|
-
shouldPrintServeSkillsNudge,
|
|
8216
|
-
getMissingUserSkillsNudge,
|
|
8217
|
-
parseSkillsClient,
|
|
8218
6554
|
runWithUsageTags,
|
|
8219
6555
|
createApiClient,
|
|
8220
|
-
ApiClient
|
|
8221
|
-
CANONRY_MCP_TIERS,
|
|
8222
|
-
CANONRY_MCP_TOOLKIT_NAMES,
|
|
8223
|
-
CANONRY_MCP_TOOLKITS,
|
|
8224
|
-
createCanonryMcpServer
|
|
6556
|
+
ApiClient
|
|
8225
6557
|
};
|