@canonry/canonry 7.51.5 → 7.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +8 -0
  2. package/assets/assets/{AccessControls-B5TqDgeq.js → AccessControls-CteIuEGI.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-DgxiizOW.js → AuditHistoryPanel-DqJGiLsf.js} +1 -1
  4. package/assets/assets/{BacklinksPage-Ay6pdphx.js → BacklinksPage-DotWEPQt.js} +1 -1
  5. package/assets/assets/{HistoryPage-B11eFH21.js → HistoryPage-aOd198dT.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-CuaKVK8x.js +4 -0
  7. package/assets/assets/{ProjectPage-DoY0hftd.js → ProjectPage-O9oufMgi.js} +4 -4
  8. package/assets/assets/{RunsPage-BPBmuQAS.js → RunsPage-DIXMrc-N.js} +1 -1
  9. package/assets/assets/{SettingsPage-ClKnP8xy.js → SettingsPage-BuGb6AGa.js} +1 -1
  10. package/assets/assets/SiteHealthSection-CweaKjCo.js +2 -0
  11. package/assets/assets/TrafficPage-B7MaQalp.js +40 -0
  12. package/assets/assets/{TrafficSourceDetailPage-DQu0YNt2.js → TrafficSourceDetailPage-BPtjnF9s.js} +1 -1
  13. package/assets/assets/{card-DYMyvhB9.js → card-DoV-8Txo.js} +1 -1
  14. package/assets/assets/{extract-error-message-BRM1I_3L.js → extract-error-message-DKQJJlZ-.js} +1 -1
  15. package/assets/assets/{format-helpers-DrkFERj3.js → format-helpers-BWnMmkiO.js} +1 -1
  16. package/assets/assets/index-Z63c4PeO.js +39 -0
  17. package/assets/assets/{query-client-gRFnU4VF.js → query-client-vB35tVTz.js} +1 -1
  18. package/assets/assets/{react-query-lH82FULK.js → react-query-BI0567qs.js} +1 -1
  19. package/assets/assets/{react-sigma_core.esm.min-D09H4byP.js → react-sigma_core.esm.min-hGyOC4V_.js} +1 -1
  20. package/assets/assets/{service-Cx0HSnE9.js → service-c4YvpVKX.js} +1 -1
  21. package/assets/index.html +6 -6
  22. package/dist/ads-MREK2AGL.js +544 -0
  23. package/dist/agent-4RUZ3MC4.js +70 -0
  24. package/dist/agent-ask-YLTYBEYH.js +139 -0
  25. package/dist/agent-conversations-QA6IKDGR.js +52 -0
  26. package/dist/agent-memory-MEQAJOB3.js +92 -0
  27. package/dist/agent-providers-AXYPDJHL.js +55 -0
  28. package/dist/agent-transcript-SMNQNYCD.js +77 -0
  29. package/dist/analytics-4OR64IGV.js +240 -0
  30. package/dist/apply-CQXCFXAH.js +175 -0
  31. package/dist/backfill-TMXCNVOB.js +41 -0
  32. package/dist/backlinks-6KFAQGYV.js +303 -0
  33. package/dist/bing-HFCACTAC.js +418 -0
  34. package/dist/bootstrap-SQVQXOJC.js +326 -0
  35. package/dist/cdp-IACL7EXU.js +162 -0
  36. package/dist/chunk-4MJYGB56.js +124 -0
  37. package/dist/chunk-5N6245R7.js +1160 -0
  38. package/dist/chunk-6BPZHNDC.js +617 -0
  39. package/dist/chunk-6GO5VVAC.js +15 -0
  40. package/dist/chunk-7244X3K6.js +609 -0
  41. package/dist/chunk-7XE2IRBG.js +204 -0
  42. package/dist/chunk-AOJU5LKX.js +8 -0
  43. package/dist/chunk-AWCWIQAU.js +2686 -0
  44. package/dist/{chunk-JBZZEIM2.js → chunk-BBOHY2DQ.js} +2 -13
  45. package/dist/{chunk-AZFPA7JV.js → chunk-BU3VAG5J.js} +6 -4
  46. package/dist/{chunk-4YCGZGA3.js → chunk-BYOK6Z4F.js} +2 -2
  47. package/dist/chunk-DSNSD5J3.js +971 -0
  48. package/dist/chunk-EGIZNSDA.js +94 -0
  49. package/dist/chunk-ELCLGWUT.js +83 -0
  50. package/dist/chunk-FC4XND45.js +38 -0
  51. package/dist/chunk-GNKOBKPW.js +58 -0
  52. package/dist/chunk-HEGXGCGL.js +524 -0
  53. package/dist/chunk-I6KNMZ77.js +232 -0
  54. package/dist/{chunk-HLVEB5TB.js → chunk-IIOEAJTV.js} +7 -5
  55. package/dist/chunk-ILDT4LPB.js +1273 -0
  56. package/dist/chunk-JY3RLZGB.js +30 -0
  57. package/dist/{chunk-PLYJX67A.js → chunk-K5I45PZI.js} +8084 -13939
  58. package/dist/chunk-KXAOMTXN.js +1034 -0
  59. package/dist/chunk-LK2BG6EX.js +145 -0
  60. package/dist/chunk-MJNUSPO4.js +15 -0
  61. package/dist/chunk-MKAC7HKH.js +9178 -0
  62. package/dist/chunk-MLKGABMK.js +9 -0
  63. package/dist/{chunk-SFMWHPMX.js → chunk-O4RMPA6H.js} +13765 -13737
  64. package/dist/chunk-O77IBNVO.js +8264 -0
  65. package/dist/chunk-OFL4PTYU.js +644 -0
  66. package/dist/chunk-QLPLENDT.js +133 -0
  67. package/dist/chunk-R2J4SNKF.js +78 -0
  68. package/dist/{chunk-KEATAHXH.js → chunk-RVUCY4ZV.js} +358 -581
  69. package/dist/chunk-SNFBJKAW.js +530 -0
  70. package/dist/chunk-TALC5DX5.js +420 -0
  71. package/dist/chunk-TSENU4GG.js +18 -0
  72. package/dist/{chunk-HAHXPJQ5.js → chunk-V5D4XNWV.js} +16 -1684
  73. package/dist/chunk-VJWDBFSL.js +69 -0
  74. package/dist/chunk-XEBKF4N5.js +8 -0
  75. package/dist/chunk-Y4GK7GCV.js +15376 -0
  76. package/dist/{chunk-A3WSAAQS.js → chunk-YSEC6TIB.js} +7917 -33199
  77. package/dist/chunk-Z7IUAJOF.js +13 -0
  78. package/dist/citations-NSBBWRZ4.js +106 -0
  79. package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-OFWJMNMD.js} +5 -3
  80. package/dist/cli-commands-WVBL337U.js +19 -0
  81. package/dist/cli.js +35 -29
  82. package/dist/competitor-V4OHORBC.js +561 -0
  83. package/dist/content-RUXRI5IC.js +257 -0
  84. package/dist/dashboard-JXB2YAQJ.js +71 -0
  85. package/dist/demo-55ZNUOXU.js +75 -0
  86. package/dist/{demo-server-GIWDJGJX.js → demo-server-XO7PHM4I.js} +22 -9
  87. package/dist/discover-JJQ564HS.js +372 -0
  88. package/dist/discover-eval-KLEKZ6U4.js +282 -0
  89. package/dist/doctor-JAMQZCMZ.js +152 -0
  90. package/dist/evidence-YRSB7GFE.js +57 -0
  91. package/dist/export-cmd-MHML4OYU.js +49 -0
  92. package/dist/ga-LSXPE2MN.js +911 -0
  93. package/dist/gbp-RMKMLOC7.js +370 -0
  94. package/dist/google-JQ4T6JTQ.js +946 -0
  95. package/dist/google-marketing-J6SEODYC.js +403 -0
  96. package/dist/health-cmd-MV2JM2C3.js +64 -0
  97. package/dist/history-SRRH7A2E.js +90 -0
  98. package/dist/index.d.ts +43 -4
  99. package/dist/index.js +29 -6
  100. package/dist/init-ZJZFUERV.js +432 -0
  101. package/dist/insights-PMMGNWZH.js +63 -0
  102. package/dist/intelligence-service-KCSU6ZUJ.js +15 -0
  103. package/dist/keys-TS7NZANS.js +116 -0
  104. package/dist/keyword-VNCKDUGC.js +164 -0
  105. package/dist/logs-VH3WOTZJ.js +30 -0
  106. package/dist/mcp-DG2RROB3.js +14 -0
  107. package/dist/mcp.js +14 -5
  108. package/dist/measurement-plan-4T35TUGG.js +42 -0
  109. package/dist/notify-BWHUSKL7.js +125 -0
  110. package/dist/organic-evidence-QX4SXXJP.js +53 -0
  111. package/dist/overview-7IHUTKUV.js +213 -0
  112. package/dist/project-JXLSWDE2.js +460 -0
  113. package/dist/query-S75EL25H.js +211 -0
  114. package/dist/research-KFTV3IP4.js +200 -0
  115. package/dist/results-export-GTKVBU34.js +27 -0
  116. package/dist/run-26HDIRHF.js +31 -0
  117. package/dist/schedule-N6G4SVHQ.js +177 -0
  118. package/dist/search-MI32EPYM.js +42 -0
  119. package/dist/serve-XLGE42AG.js +598 -0
  120. package/dist/session-W5DXWIYM.js +47 -0
  121. package/dist/settings-T7WI2UVE.js +107 -0
  122. package/dist/skills-F3WPKPTK.js +33 -0
  123. package/dist/snapshot-PD3EAVEX.js +538 -0
  124. package/dist/src-XDUXMJC3.js +316 -0
  125. package/dist/status-PUH7JFZ4.js +126 -0
  126. package/dist/support-ARF4HER7.js +24 -0
  127. package/dist/technical-aeo-AUFWWJIP.js +625 -0
  128. package/dist/telemetry-XBYT7G2K.js +118 -0
  129. package/dist/tools-GVHIRWSN.js +41 -0
  130. package/dist/traffic-B3HW2ZWG.js +1295 -0
  131. package/dist/users-M5HNQZYI.js +170 -0
  132. package/dist/visibility-stats-Y7GJKMHN.js +241 -0
  133. package/dist/wordpress-GCIURYPN.js +600 -0
  134. package/package.json +1 -1
  135. package/assets/assets/MeasurementPropertyPage-1UYI7mzP.js +0 -4
  136. package/assets/assets/SiteHealthSection-PWjKMmEn.js +0 -2
  137. package/assets/assets/TrafficPage-DkfGiJXR.js +0 -40
  138. package/assets/assets/index-CG1Jox52.js +0 -39
  139. package/dist/chunk-4QQYYRHV.js +0 -23082
  140. package/dist/cli-commands-FOJR3HHU.js +0 -15
  141. package/dist/intelligence-service-XQCNWAPL.js +0 -9
@@ -0,0 +1,617 @@
1
+ import {
2
+ createApiClient
3
+ } from "./chunk-V5D4XNWV.js";
4
+ import {
5
+ emitJsonl
6
+ } from "./chunk-Z7IUAJOF.js";
7
+ import {
8
+ CliError,
9
+ EXIT_SYSTEM_ERROR,
10
+ isMachineFormat
11
+ } from "./chunk-HGMYEDAQ.js";
12
+ import {
13
+ CitationStates,
14
+ MentionIdentities,
15
+ OUTSTANDING_PROVIDER_BATCH_STATUSES,
16
+ ProviderBatchStatuses,
17
+ RunStatuses,
18
+ describeError,
19
+ formatMicros,
20
+ formatRunErrorOneLine,
21
+ resolveProviderInput
22
+ } from "./chunk-O4RMPA6H.js";
23
+
24
+ // src/commands/run.ts
25
+ function getClient() {
26
+ return createApiClient();
27
+ }
28
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["completed", "partial", "failed", "cancelled"]);
29
+ function shellArg(value) {
30
+ return /^[\w.-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
31
+ }
32
+ function providerAccountStreakLine(provider, streak) {
33
+ return `${provider} (${streak.code}): failed on its account in each of its last ${streak.consecutiveRuns} runs; called again after ${streak.retryAfter}`;
34
+ }
35
+ function providersThatKeepFailing(count) {
36
+ return count === 1 ? "a provider that keeps failing on its account" : `${count} providers that keep failing on their accounts`;
37
+ }
38
+ function providerAccountFixLine(project) {
39
+ return `Fix the key, access or billing in the provider's console. Saving a new key, model or endpoint (canonry settings provider <name>) retries at once; canonry run ${shellArg(project)} --force calls every provider now.`;
40
+ }
41
+ function admissionDecisionKey(admission) {
42
+ return JSON.stringify([
43
+ admission.refused,
44
+ admission.retryAfter,
45
+ Object.entries(admission.providers).sort(([left], [right]) => left.localeCompare(right)).map(([provider, streak]) => [provider, streak.code, streak.consecutiveRuns, streak.since, streak.latestRunId, streak.retryAfter])
46
+ ]);
47
+ }
48
+ function admissionScopeLines(admission, label, showAllowed) {
49
+ const held = Object.entries(admission.providers);
50
+ if (held.length === 0) return showAllowed ? [`${label}: no providers held back.`] : [];
51
+ const retry = label === "Manual sweep" ? `it can retry after ${admission.retryAfter}` : `scheduled sweeps skip their slots until ${admission.retryAfter}`;
52
+ return [
53
+ admission.refused ? `${label}: refused (PROVIDERS_FAILING). Every provider it would call keeps failing on its account; ${retry}.` : `${label}: skips ${providersThatKeepFailing(held.length)}; the rest run.`,
54
+ ...held.map(([provider, streak]) => ` ${providerAccountStreakLine(provider, streak)}`)
55
+ ];
56
+ }
57
+ function runAdmissionLines(project, admission, manualAdmission) {
58
+ if (!admission) return [];
59
+ const differs = manualAdmission !== void 0 && admissionDecisionKey(admission) !== admissionDecisionKey(manualAdmission);
60
+ const lines = differs ? [...admissionScopeLines(admission, "Scheduled sweep", true), ...admissionScopeLines(manualAdmission, "Manual sweep", true)] : admissionScopeLines(admission, "Next sweep", false);
61
+ return lines.length > 0 ? [...lines, providerAccountFixLine(project)] : [];
62
+ }
63
+ function printSkippedProviders(project, skipped) {
64
+ const held = Object.entries(skipped ?? {});
65
+ if (held.length === 0) return;
66
+ console.log(`
67
+ Not calling ${providersThatKeepFailing(held.length)}:`);
68
+ for (const [provider, streak] of held) console.log(` ${providerAccountStreakLine(provider, streak)}`);
69
+ console.log(providerAccountFixLine(project));
70
+ }
71
+ function throwIfWaitedRunFailed(waited) {
72
+ const failed = waited.filter((r) => r.status === RunStatuses.failed);
73
+ if (failed.length === 0) return;
74
+ const reason = (r) => r.error ? formatRunErrorOneLine(r.error) : null;
75
+ const label = (r) => [r.project, r.location ? `(${r.location})` : null, `run ${r.runId}`].filter(Boolean).join(" ");
76
+ const message = waited.length === 1 ? `Run ${failed[0].runId} failed${reason(failed[0]) ? `: ${reason(failed[0])}` : ""}` : `${failed.length} of ${waited.length} runs failed: ${failed.map((r) => `${label(r)}${reason(r) ? `: ${reason(r)}` : ""}`).join("; ")}`;
77
+ throw new CliError({
78
+ code: "RUN_FAILED",
79
+ message,
80
+ exitCode: EXIT_SYSTEM_ERROR,
81
+ details: {
82
+ waitedRunCount: waited.length,
83
+ failedRuns: failed.map((r) => ({
84
+ runId: r.runId,
85
+ ...r.project ? { project: r.project } : {},
86
+ ...r.location ? { location: r.location } : {},
87
+ error: reason(r)
88
+ }))
89
+ }
90
+ });
91
+ }
92
+ async function triggerRun(project, opts) {
93
+ const client = getClient();
94
+ const body = {};
95
+ if (opts?.provider) {
96
+ const providerInputs = opts.provider.split(",").map((s) => s.trim()).filter(Boolean);
97
+ const resolved = providerInputs.flatMap((p) => resolveProviderInput(p));
98
+ body.providers = resolved.length > 0 ? resolved : providerInputs;
99
+ }
100
+ if (opts?.queries?.length) {
101
+ body.queries = opts.queries;
102
+ }
103
+ if (opts?.groups?.length || opts?.targets?.length) {
104
+ body.measurementScope = {
105
+ ...opts.groups?.length ? { groups: opts.groups } : {},
106
+ ...opts.targets?.length ? { targets: opts.targets } : {}
107
+ };
108
+ }
109
+ if (opts?.location) {
110
+ body.location = opts.location;
111
+ }
112
+ if (opts?.allLocations) {
113
+ body.allLocations = true;
114
+ }
115
+ if (opts?.noLocation) {
116
+ body.noLocation = true;
117
+ }
118
+ if (opts?.probe) {
119
+ body.trigger = "probe";
120
+ }
121
+ if (opts?.dispatchMode) {
122
+ body.dispatchMode = opts.dispatchMode;
123
+ }
124
+ if (opts?.force) {
125
+ body.force = true;
126
+ }
127
+ const response = await client.triggerRun(project, body);
128
+ if (Array.isArray(response)) {
129
+ const locationRuns = response;
130
+ if (isMachineFormat(opts?.format)) {
131
+ if (opts?.wait) {
132
+ const finals = await Promise.all(
133
+ locationRuns.map(async (r) => !r.id || r.status === "conflict" ? null : pollRun(client, r.id, false))
134
+ );
135
+ console.log(JSON.stringify(locationRuns.map((r, i) => finals[i] ? { ...r, ...finals[i] } : r), null, 2));
136
+ throwIfWaitedRunFailed(locationRuns.flatMap((r, i) => {
137
+ const final = finals[i];
138
+ return final ? [{ runId: final.id, status: final.status, project, location: r.location ?? null, error: final.error }] : [];
139
+ }));
140
+ } else {
141
+ console.log(JSON.stringify(locationRuns, null, 2));
142
+ }
143
+ return;
144
+ }
145
+ console.log(`Triggered ${locationRuns.length} location sweep(s) \u2014 ${locationRuns.length}\xD7 API calls:
146
+ `);
147
+ console.log(" LOCATION RUN ID STATUS");
148
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
149
+ for (const r of locationRuns) {
150
+ const loc = (r.location ?? "(unknown)").padEnd(15);
151
+ const id = (r.id ?? "(conflict)").padEnd(36);
152
+ console.log(` ${loc} ${id} ${r.status}`);
153
+ }
154
+ printSkippedProviders(project, locationRuns.find((r) => r.skippedProviders)?.skippedProviders);
155
+ if (opts?.wait) {
156
+ const pending = locationRuns.filter((r) => r.id && r.status !== "conflict" && !TERMINAL_STATUSES.has(r.status));
157
+ const errors = /* @__PURE__ */ new Map();
158
+ if (pending.length > 0) {
159
+ process.stderr.write(`Waiting for ${pending.length} run(s)`);
160
+ const batchWaits = /* @__PURE__ */ new Map();
161
+ await Promise.all(
162
+ pending.map(async (r) => {
163
+ const final = await pollRun(client, r.id);
164
+ r.status = final.status;
165
+ errors.set(r.id, final.error);
166
+ const waiting = batchWaitLine(final);
167
+ if (waiting) batchWaits.set(r.id, waiting);
168
+ })
169
+ );
170
+ process.stderr.write("\n");
171
+ console.log("\nFinal statuses:");
172
+ for (const r of locationRuns) {
173
+ const loc = (r.location ?? "(unknown)").padEnd(15);
174
+ console.log(` ${loc} ${r.status}`);
175
+ }
176
+ if (batchWaits.size > 0) console.log("");
177
+ for (const r of locationRuns) {
178
+ const waiting = batchWaits.get(r.id);
179
+ if (waiting) console.log(` ${r.location ?? "(unknown)"}: ${waiting}`);
180
+ }
181
+ }
182
+ throwIfWaitedRunFailed(locationRuns.filter((r) => r.id && r.status !== "conflict").map((r) => ({ runId: r.id, status: r.status, project, location: r.location ?? null, error: errors.get(r.id) })));
183
+ }
184
+ return;
185
+ }
186
+ const run = response;
187
+ if (opts?.wait && run.id && !TERMINAL_STATUSES.has(run.status)) {
188
+ const showProgress = !isMachineFormat(opts?.format);
189
+ if (showProgress) process.stderr.write(`Run ${run.id} started`);
190
+ const result = await pollRun(client, run.id, showProgress);
191
+ if (isMachineFormat(opts?.format)) {
192
+ console.log(JSON.stringify(result, null, 2));
193
+ } else {
194
+ process.stderr.write("\n");
195
+ printRunDetail(result);
196
+ const waiting = batchWaitLine(result);
197
+ if (waiting) console.log(`
198
+ ${waiting}`);
199
+ }
200
+ throwIfWaitedRunFailed([{ runId: result.id, status: result.status, project, error: result.error }]);
201
+ return;
202
+ }
203
+ if (opts?.wait && (TERMINAL_STATUSES.has(run.status) || !run.id)) {
204
+ const result = run.id ? await client.getRun(run.id) : run;
205
+ if (isMachineFormat(opts?.format)) {
206
+ console.log(JSON.stringify(result, null, 2));
207
+ } else {
208
+ printRunDetail(result);
209
+ }
210
+ throwIfWaitedRunFailed([{ runId: result.id, status: result.status, project, error: result.error }]);
211
+ return;
212
+ }
213
+ if (isMachineFormat(opts?.format)) {
214
+ console.log(JSON.stringify(run, null, 2));
215
+ return;
216
+ }
217
+ console.log(`Run created: ${run.id}`);
218
+ console.log(` Kind: ${run.kind}`);
219
+ console.log(` Status: ${run.status}`);
220
+ if (opts?.provider) {
221
+ console.log(` Provider: ${opts.provider}`);
222
+ }
223
+ printSkippedProviders(project, run.skippedProviders);
224
+ }
225
+ async function triggerRunAll(opts) {
226
+ const client = getClient();
227
+ const projects = await client.listProjects();
228
+ if (projects.length === 0) {
229
+ if (isMachineFormat(opts?.format)) {
230
+ console.log("[]");
231
+ } else {
232
+ console.log("No projects found.");
233
+ }
234
+ return;
235
+ }
236
+ const baseBody = {};
237
+ if (opts?.provider) {
238
+ const providerInputs = opts.provider.split(",").map((s) => s.trim()).filter(Boolean);
239
+ const resolved = providerInputs.flatMap((p) => resolveProviderInput(p));
240
+ baseBody.providers = resolved.length > 0 ? resolved : providerInputs;
241
+ }
242
+ if (opts?.allLocations) {
243
+ baseBody.allLocations = true;
244
+ }
245
+ if (opts?.noLocation) {
246
+ baseBody.noLocation = true;
247
+ }
248
+ if (opts?.dispatchMode) {
249
+ baseBody.dispatchMode = opts.dispatchMode;
250
+ }
251
+ if (opts?.force) {
252
+ baseBody.force = true;
253
+ }
254
+ const results = [];
255
+ for (const p of projects) {
256
+ const body = { ...baseBody };
257
+ if (body.allLocations && p.locations.length === 0) {
258
+ delete body.allLocations;
259
+ }
260
+ try {
261
+ const response = await client.triggerRun(p.name, body);
262
+ const dispatched = Array.isArray(response) ? response : [response];
263
+ for (const r of dispatched) {
264
+ results.push({
265
+ project: p.name,
266
+ runId: r.id,
267
+ status: r.status,
268
+ location: r.location ?? null
269
+ });
270
+ }
271
+ } catch (err) {
272
+ const msg = describeError(err);
273
+ results.push({ project: p.name, runId: "", status: "error", location: null, error: msg });
274
+ }
275
+ }
276
+ const errors = /* @__PURE__ */ new Map();
277
+ const batchWaits = /* @__PURE__ */ new Map();
278
+ if (opts?.wait) {
279
+ const pending = results.filter((r) => r.runId && !TERMINAL_STATUSES.has(r.status));
280
+ if (pending.length > 0) {
281
+ const showProgress = !isMachineFormat(opts?.format);
282
+ if (showProgress) process.stderr.write(`Waiting for ${pending.length} run(s)`);
283
+ await Promise.all(pending.map(async (r) => {
284
+ const final = await pollRun(client, r.runId, showProgress);
285
+ r.status = final.status;
286
+ errors.set(r.runId, final.error);
287
+ const waiting = batchWaitLine(final);
288
+ if (waiting) batchWaits.set(r.runId, waiting);
289
+ }));
290
+ if (showProgress) process.stderr.write("\n");
291
+ }
292
+ }
293
+ const waited = results.filter((r) => r.runId).map((r) => ({ runId: r.runId, status: r.status, project: r.project, location: r.location, error: errors.get(r.runId) }));
294
+ if (isMachineFormat(opts?.format)) {
295
+ console.log(JSON.stringify(results, null, 2));
296
+ if (opts?.wait) throwIfWaitedRunFailed(waited);
297
+ return;
298
+ }
299
+ const showLocationColumn = results.some((r) => r.location !== null);
300
+ const projectCount = new Set(results.map((r) => r.project)).size;
301
+ console.log(`Triggered ${results.length} run(s) across ${projectCount} project(s):
302
+ `);
303
+ if (showLocationColumn) {
304
+ console.log(" PROJECT LOCATION RUN ID STATUS");
305
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
306
+ for (const r of results) {
307
+ const proj = r.project.padEnd(31);
308
+ const loc = (r.location ?? "\u2014").padEnd(15);
309
+ const id = (r.runId || "(failed)").padEnd(36);
310
+ console.log(` ${proj} ${loc} ${id} ${r.status}`);
311
+ }
312
+ } else {
313
+ console.log(" PROJECT RUN ID STATUS");
314
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
315
+ for (const r of results) {
316
+ const proj = r.project.padEnd(31);
317
+ const id = (r.runId || "(failed)").padEnd(36);
318
+ console.log(` ${proj} ${id} ${r.status}`);
319
+ }
320
+ }
321
+ if (batchWaits.size > 0) console.log("");
322
+ for (const r of results) {
323
+ const waiting = batchWaits.get(r.runId);
324
+ if (waiting) console.log(` ${r.location ? `${r.project} (${r.location})` : r.project}: ${waiting}`);
325
+ }
326
+ if (opts?.wait) throwIfWaitedRunFailed(waited);
327
+ }
328
+ async function cancelRun(project, runId, format) {
329
+ const client = getClient();
330
+ let targetId = runId;
331
+ if (!targetId) {
332
+ const runs = await client.listRuns(project);
333
+ const activeRuns = runs.filter((r) => r.status === "queued" || r.status === "running");
334
+ if (activeRuns.length > 1) {
335
+ const candidates = activeRuns.map(({ id, kind, status }) => ({ id, kind, status }));
336
+ throw new CliError({
337
+ code: "MULTIPLE_ACTIVE_RUNS",
338
+ message: `Multiple active runs found for project "${project}". Specify a run ID.`,
339
+ displayMessage: `Error: Multiple active runs found for project "${project}". Specify a run ID.
340
+ ` + candidates.map((r) => ` ${r.id} ${r.kind} ${r.status}`).join("\n") + `
341
+ To cancel by ID: canonry run cancel ${project} <run-id>`,
342
+ details: {
343
+ project,
344
+ activeRuns: candidates,
345
+ suggestedCommands: [`canonry run cancel ${project} <run-id>`]
346
+ }
347
+ });
348
+ }
349
+ const active = activeRuns[0];
350
+ if (!active) {
351
+ throw new CliError({
352
+ code: "NO_ACTIVE_RUN",
353
+ message: `No active run found for project "${project}"`,
354
+ displayMessage: `Error: canonry run cancel "${project}" \u2014 no active run found (status must be queued or running).
355
+ Check run status : canonry status ${project}
356
+ To cancel by ID : canonry run cancel ${project} <run-id>`,
357
+ details: {
358
+ project,
359
+ allowedStatuses: ["queued", "running"],
360
+ suggestedCommands: [
361
+ `canonry status ${project}`,
362
+ `canonry run cancel ${project} <run-id>`
363
+ ]
364
+ }
365
+ });
366
+ }
367
+ targetId = active.id;
368
+ }
369
+ const result = await client.cancelRun(targetId);
370
+ if (isMachineFormat(format)) {
371
+ console.log(JSON.stringify(result, null, 2));
372
+ return;
373
+ }
374
+ console.log(`Run ${result.id} cancelled.`);
375
+ }
376
+ async function showRun(id, format) {
377
+ const client = getClient();
378
+ const run = await client.getRun(id);
379
+ if (isMachineFormat(format)) {
380
+ console.log(JSON.stringify(run, null, 2));
381
+ return;
382
+ }
383
+ printRunDetail(run);
384
+ }
385
+ async function listRuns(project, opts) {
386
+ const client = getClient();
387
+ const runs = await client.listRuns(project, opts?.limit, opts?.kind, opts?.status, opts?.excludeKind, opts?.excludeKinds, opts?.since);
388
+ if (opts?.format === "json") {
389
+ console.log(JSON.stringify(runs, null, 2));
390
+ return;
391
+ } else if (opts?.format === "jsonl") {
392
+ emitJsonl(runs.map((run) => ({ project, ...run })));
393
+ return;
394
+ }
395
+ if (runs.length === 0) {
396
+ console.log(`No runs found for "${project}".`);
397
+ return;
398
+ }
399
+ console.log(`Runs for "${project}" (${runs.length}):
400
+ `);
401
+ console.log(" ID STATUS KIND TRIGGER CREATED");
402
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
403
+ for (const run of runs) {
404
+ console.log(
405
+ ` ${run.id} ${run.status.padEnd(10)} ${run.kind.padEnd(18)} ${run.trigger.padEnd(9)} ${run.createdAt}`
406
+ );
407
+ if ((run.status === RunStatuses.failed || run.status === RunStatuses.partial) && run.error) {
408
+ console.log(` error: ${formatRunErrorOneLine(run.error)}`);
409
+ }
410
+ }
411
+ }
412
+ var POLL_TIMEOUT_MS = 10 * 60 * 1e3;
413
+ async function pollRun(client, runId, showProgress = true) {
414
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
415
+ for (; ; ) {
416
+ await new Promise((r) => setTimeout(r, 2e3));
417
+ if (Date.now() > deadline) {
418
+ throw new Error(`Timed out waiting for run ${runId} after ${POLL_TIMEOUT_MS / 1e3}s`);
419
+ }
420
+ const run = await client.getRun(runId);
421
+ if (showProgress) process.stderr.write(".");
422
+ if (TERMINAL_STATUSES.has(run.status) || outstandingBatches(run).length > 0) {
423
+ return run;
424
+ }
425
+ }
426
+ }
427
+ function outstandingBatches(run) {
428
+ if (TERMINAL_STATUSES.has(run.status)) return [];
429
+ return (run.providerBatches ?? []).filter((batch) => OUTSTANDING_PROVIDER_BATCH_STATUSES.includes(batch.status));
430
+ }
431
+ function batchWaitLine(run) {
432
+ const outstanding = outstandingBatches(run);
433
+ if (outstanding.length === 0) return null;
434
+ const batches = outstanding.map((batch) => `${batch.provider} \u2014 ${batch.requestCount} requests, submitted ${batch.submittedAt ?? "unknown"}, deadline ${batch.deadlineAt}`);
435
+ return `Waiting on provider batch(es): ${batches.join("; ")}; check with canonry run show ${run.id}`;
436
+ }
437
+ function printRunDetail(run) {
438
+ console.log(`Run: ${run.id}`);
439
+ console.log(` Status: ${run.status}`);
440
+ console.log(` Kind: ${run.kind}`);
441
+ if (run.trigger) console.log(` Trigger: ${run.trigger}`);
442
+ if (run.startedAt) console.log(` Started: ${run.startedAt}`);
443
+ if (run.finishedAt) console.log(` Finished: ${run.finishedAt}`);
444
+ if (run.createdAt) console.log(` Created: ${run.createdAt}`);
445
+ const skipped = Object.entries(run.skippedProviders ?? {});
446
+ for (const [provider, streak] of skipped) console.log(` Skipped: ${providerAccountStreakLine(provider, streak)}`);
447
+ if (run.error) {
448
+ if (run.error.message) console.log(` Error: ${run.error.message}`);
449
+ if (run.error.providers) {
450
+ for (const [provider, detail] of Object.entries(run.error.providers)) {
451
+ if (detail.skipped && run.skippedProviders?.[provider]) continue;
452
+ console.log(` Error (${provider}): ${detail.message}`);
453
+ }
454
+ }
455
+ }
456
+ const batched = Object.keys(run.dispatchModes ?? {}).sort();
457
+ if (batched.length > 0) console.log(` Dispatch: ${batched.map((provider) => `${provider}=batch`).join(", ")} (other providers sync)`);
458
+ if (run.providerBatches && run.providerBatches.length > 0) {
459
+ console.log("\n Provider batches:");
460
+ for (const batch of run.providerBatches) console.log(` ${providerBatchLine(batch)}`);
461
+ }
462
+ if (run.usage && run.usage.length > 0) printUsageTable(run.usage);
463
+ if (run.snapshots && run.snapshots.length > 0) {
464
+ console.log(`
465
+ Snapshots: ${run.snapshots.length} (cell = [citation][mention]; C=cited c=not, M=mentioned m=not, \u2013=no data)`);
466
+ let differentSubject = 0;
467
+ for (const s of run.snapshots) {
468
+ const citationGlyph = s.citationState === CitationStates.cited ? "C" : "c";
469
+ const mentionGlyph = typeof s.answerMentioned === "boolean" ? s.answerMentioned ? "M" : "m" : "\u2013";
470
+ const modelLabel = s.model ? ` (${s.model})` : "";
471
+ const ruledOut = s.mentionIdentity === MentionIdentities["wrong-subject"];
472
+ if (ruledOut) differentSubject++;
473
+ console.log(` [${citationGlyph}${mentionGlyph}] ${s.provider}${modelLabel} ${s.query}${ruledOut ? " \xB7 different subject" : ""}`);
474
+ }
475
+ if (differentSubject > 0) {
476
+ console.log(" \xB7 different subject: the answer uses your name, but sentiment found it is about something else, so it is not counted as mentioned.");
477
+ }
478
+ }
479
+ }
480
+ function providerBatchLine(batch) {
481
+ const recorded = `${batch.recordedCount} of ${batch.requestCount} answers recorded`;
482
+ const withError = (text) => batch.error ? `${text} (${batch.error})` : text;
483
+ switch (batch.status) {
484
+ case ProviderBatchStatuses.submitting:
485
+ return `submitting provider batch: ${batch.provider} \u2014 ${batch.requestCount} requests`;
486
+ // The two outstanding statuses: the run stays `running` until they clear.
487
+ case ProviderBatchStatuses.submitted:
488
+ case ProviderBatchStatuses.ended:
489
+ return `waiting on provider batch: ${batch.provider} \u2014 ${batch.requestCount} requests, submitted ${batch.submittedAt ?? "unknown"}, deadline ${batch.deadlineAt}`;
490
+ case ProviderBatchStatuses.ingested:
491
+ return withError(`provider batch ${batch.provider}: ingested \u2014 ${recorded}`);
492
+ case ProviderBatchStatuses.cancelled:
493
+ return withError(`provider batch ${batch.provider}: cancelled \u2014 ${recorded}; the rest are missing and can be filled`);
494
+ case ProviderBatchStatuses.failed:
495
+ return withError(`provider batch ${batch.provider}: rejected by the provider \u2014 its ${batch.requestCount} answers ran sync instead`);
496
+ case ProviderBatchStatuses.unknown:
497
+ return withError(`provider batch ${batch.provider}: submit outcome unknown \u2014 never resubmitted; its ${batch.requestCount} answers stay missing`);
498
+ }
499
+ }
500
+ function printUsageTable(rows) {
501
+ const cost = (row) => row.estimatedCostMicros === null ? "unpriced" : `${formatMicros(row.estimatedCostMicros, "USD", { fractionDigits: 4, showTinyAsLessThan: true })}${row.unpricedAnswers > 0 ? ` (+${row.unpricedAnswers} unpriced)` : ""}`;
502
+ const table = rows.map((row) => [
503
+ row.provider,
504
+ row.pricingTier,
505
+ row.answers.toLocaleString("en-US"),
506
+ row.inputTokens.toLocaleString("en-US"),
507
+ row.cachedInputTokens.toLocaleString("en-US"),
508
+ row.cacheWriteTokens.toLocaleString("en-US"),
509
+ row.outputTokens.toLocaleString("en-US"),
510
+ row.searchCount.toLocaleString("en-US"),
511
+ cost(row)
512
+ ]);
513
+ const header = ["PROVIDER", "TIER", "ANSWERS", "INPUT", "CACHED", "CACHE WRITE", "OUTPUT", "SEARCHES", "EST. COST"];
514
+ const widths = header.map((title, index) => Math.max(title.length, ...table.map((cells) => cells[index].length)));
515
+ const line = (cells) => ` ${cells.map((cell, index) => cell.padEnd(widths[index])).join(" ").trimEnd()}`;
516
+ console.log("\n Usage (answers with recorded usage; cost is an estimate):");
517
+ console.log(line(header));
518
+ for (const cells of table) console.log(line(cells));
519
+ }
520
+ var FILL_POLL_INTERVAL_MS = 3e3;
521
+ var FILL_POLL_TIMEOUT_MS = 6 * 60 * 60 * 1e3;
522
+ function missingSummary(completeness) {
523
+ const parts = Object.entries(completeness.missingByProvider).sort(([left], [right]) => left.localeCompare(right)).map(([provider, count]) => `${provider} ${count}`);
524
+ return parts.length ? parts.join(", ") : "none";
525
+ }
526
+ function printCompleteness(completeness) {
527
+ console.log(`Run: ${completeness.runId}`);
528
+ console.log(` Status: ${completeness.status}`);
529
+ if (!completeness.planned) {
530
+ console.log(" Not a measurement-plan run: there are no expected answers to count.");
531
+ return;
532
+ }
533
+ if (!completeness.readable) {
534
+ console.log(" Answers: unknown (the run's manifest cannot be read)");
535
+ } else {
536
+ console.log(` Answers: ${completeness.executed}/${completeness.expected}`);
537
+ console.log(` Missing: ${completeness.missing} (${missingSummary(completeness)})`);
538
+ }
539
+ if (completeness.refusal) console.log(` Fillable: no. ${completeness.refusal.message}`);
540
+ else console.log(` Fillable: ${completeness.fillable ? "yes" : "not right now (a sweep or another fill is running)"}`);
541
+ const fill = completeness.latestFill;
542
+ if (fill) {
543
+ console.log(` Last fill: ${fill.id} ${fill.status}, ${fill.filled}/${fill.expected} recorded${fill.error ? `. ${fill.error}` : ""}`);
544
+ }
545
+ }
546
+ async function showRunCompleteness(runId, format) {
547
+ const completeness = await getClient().getRunCompleteness(runId);
548
+ if (isMachineFormat(format)) {
549
+ console.log(JSON.stringify(completeness, null, 2));
550
+ return;
551
+ }
552
+ printCompleteness(completeness);
553
+ }
554
+ async function fillRun(runId, opts = {}) {
555
+ const client = getClient();
556
+ const response = await client.fillRun(runId, {
557
+ ...opts.providers?.length ? { providers: opts.providers } : {},
558
+ ...opts.dryRun ? { dryRun: true } : {}
559
+ });
560
+ if (!opts.wait || response.outcome !== "queued" || !response.fill) {
561
+ if (isMachineFormat(opts.format)) {
562
+ console.log(JSON.stringify(response, null, 2));
563
+ return;
564
+ }
565
+ if (response.outcome === "already-complete") console.log(`Run ${runId} is already complete: nothing to fill.`);
566
+ else if (response.outcome === "dry-run") console.log("Dry run: nothing was queued.");
567
+ else if (response.fill) console.log(`Fill ${response.fill.id} queued: ${response.fill.expected} missing answer(s) (${missingSummary(response.completeness)}).`);
568
+ printCompleteness(response.completeness);
569
+ return;
570
+ }
571
+ const fillId = response.fill.id;
572
+ const deadline = Date.now() + FILL_POLL_TIMEOUT_MS;
573
+ let completeness = response.completeness;
574
+ if (!isMachineFormat(opts.format)) {
575
+ process.stderr.write(`Filling ${response.fill.expected} missing answer(s) in run ${runId}`);
576
+ }
577
+ for (; ; ) {
578
+ await new Promise((resolve) => setTimeout(resolve, FILL_POLL_INTERVAL_MS));
579
+ if (Date.now() > deadline) {
580
+ throw new CliError({
581
+ code: "RUN_FILL_INCOMPLETE",
582
+ message: `Timed out waiting for fill ${fillId}; it may still be running. Check with: canonry run completeness ${runId}`,
583
+ exitCode: EXIT_SYSTEM_ERROR,
584
+ details: { runId, fillId }
585
+ });
586
+ }
587
+ completeness = await client.getRunCompleteness(runId);
588
+ if (!isMachineFormat(opts.format)) process.stderr.write(".");
589
+ const latest = completeness.latestFill;
590
+ const working = latest !== null && (latest.status === "queued" || latest.status === "running");
591
+ if (completeness.status === "completed" || !working) break;
592
+ }
593
+ if (!isMachineFormat(opts.format)) process.stderr.write("\n");
594
+ if (isMachineFormat(opts.format)) console.log(JSON.stringify(completeness, null, 2));
595
+ else printCompleteness(completeness);
596
+ if (completeness.status !== "completed") {
597
+ throw new CliError({
598
+ code: "RUN_FILL_INCOMPLETE",
599
+ message: `Run ${runId} is still ${completeness.status}: ${completeness.missing} answer(s) missing (${missingSummary(completeness)}).`,
600
+ exitCode: EXIT_SYSTEM_ERROR,
601
+ details: { runId, fillId, missing: completeness.missing, missingByProvider: completeness.missingByProvider }
602
+ });
603
+ }
604
+ }
605
+
606
+ export {
607
+ providerAccountStreakLine,
608
+ runAdmissionLines,
609
+ triggerRun,
610
+ triggerRunAll,
611
+ cancelRun,
612
+ showRun,
613
+ listRuns,
614
+ printRunDetail,
615
+ showRunCompleteness,
616
+ fillRun
617
+ };
@@ -0,0 +1,15 @@
1
+ // src/operator-url.ts
2
+ function operatorHost(bindHost) {
3
+ if (bindHost === "0.0.0.0") return "127.0.0.1";
4
+ if (bindHost === "::" || bindHost === "[::]") return "::1";
5
+ return bindHost;
6
+ }
7
+ function operatorHttpUrl(bindHost, port) {
8
+ const host = operatorHost(bindHost);
9
+ const bare = host.replace(/^\[|\]$/g, "");
10
+ return `http://${bare.includes(":") ? `[${bare}]` : bare}:${port}`;
11
+ }
12
+
13
+ export {
14
+ operatorHttpUrl
15
+ };