@canonry/canonry 7.51.4 → 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/assets/assets/AccessControls-B5TqDgeq.js +1 -0
- package/assets/assets/AuditHistoryPanel-DgxiizOW.js +1 -0
- package/assets/assets/BacklinksPage-Ay6pdphx.js +1 -0
- package/assets/assets/ChartPrimitives-DIEeZdrs.js +1 -0
- package/assets/assets/Hint-Cn4lh0Do.js +1 -0
- package/assets/assets/HistoryPage-B11eFH21.js +1 -0
- package/assets/assets/InfoTooltip-TIx9qM5h.js +1 -0
- package/assets/assets/MeasurementPropertyPage-1UYI7mzP.js +4 -0
- package/assets/assets/ProjectPage-DoY0hftd.js +8 -0
- package/assets/assets/RunsPage-BPBmuQAS.js +1 -0
- package/assets/assets/SettingsPage-ClKnP8xy.js +1 -0
- package/assets/assets/SiteHealthSection-PWjKMmEn.js +2 -0
- package/assets/assets/TrafficPage-DkfGiJXR.js +40 -0
- package/assets/assets/TrafficSourceDetailPage-DQu0YNt2.js +1 -0
- package/assets/assets/async-handler-Bj3TnIRw.js +1 -0
- package/assets/assets/card-DYMyvhB9.js +60 -0
- package/assets/assets/extract-error-message-BRM1I_3L.js +1 -0
- package/assets/assets/format-helpers-DrkFERj3.js +3 -0
- package/assets/assets/index-CG1Jox52.js +39 -0
- package/assets/assets/index-CsPsaUr7.css +1 -0
- package/assets/assets/query-client-gRFnU4VF.js +1 -0
- package/assets/assets/react-query-lH82FULK.js +1 -0
- package/assets/assets/react-sigma_core.esm.min-D09H4byP.js +3225 -0
- package/assets/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/assets/assets/service-Cx0HSnE9.js +1 -0
- package/assets/assets/vendor-lucide-BjvO55Hk.js +1 -0
- package/assets/assets/vendor-markdown-DWjffpgb.js +29 -0
- package/assets/assets/vendor-radix-BU76HM0G.js +41 -0
- package/assets/assets/vendor-recharts-CsHBXoK8.js +59 -0
- package/assets/assets/vendor-tanstack-QhOrDhIL.js +2 -0
- package/assets/assets/vendor-yaml-Y43rmNgW.js +105 -0
- package/assets/index.html +16 -8
- 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-HHRM3H3L.js → chunk-6G6FTDWC.js} +8082 -13941
- package/dist/chunk-6GO5VVAC.js +15 -0
- package/dist/{chunk-6GNV6VF4.js → chunk-73P65KPW.js} +2 -2
- package/dist/chunk-7B2Q4NJE.js +133 -0
- package/dist/{chunk-KU4TPVZV.js → chunk-7WZ2FPB4.js} +2 -13
- package/dist/chunk-AOJU5LKX.js +8 -0
- package/dist/chunk-B2FR2ZQ4.js +420 -0
- package/dist/chunk-B5J675KK.js +6557 -0
- package/dist/{chunk-YOGHHIGE.js → chunk-D6COIM3U.js} +17155 -17164
- package/dist/{chunk-KUS7M65J.js → chunk-DGVUTH7W.js} +6809 -32243
- 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-P6D6P337.js → chunk-TUTKNUMV.js} +7 -5
- package/dist/chunk-U3AHE2RT.js +1160 -0
- package/dist/chunk-UQ3MOZGC.js +644 -0
- package/dist/{chunk-35QQMVO6.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-RUWELF3K.js → chunk-ZWJRY5UI.js} +358 -581
- package/dist/chunk-ZXUAWVWM.js +15 -0
- package/dist/citations-UYB2RU5U.js +106 -0
- package/dist/{cli-catalog-KTQ6BHEU.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-26UUDUM7.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 +194 -60
- 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 +30 -30
- package/assets/assets/AuditHistoryPanel-CtWNkC6F.js +0 -1
- package/assets/assets/BacklinksPage-Cs3_j55C.js +0 -1
- package/assets/assets/ChartPrimitives-B6ryduMN.js +0 -1
- package/assets/assets/Hint-DICI5Jq9.js +0 -1
- package/assets/assets/HistoryPage-_5Vwj01m.js +0 -1
- package/assets/assets/MeasurementPropertyPage-B2yBTUZd.js +0 -4
- package/assets/assets/ProjectPage-hs-9PcoS.js +0 -8
- package/assets/assets/RunsPage-B_mhz9vj.js +0 -1
- package/assets/assets/SettingsPage-D1Lzcw03.js +0 -1
- package/assets/assets/SiteHealthSection-CGlrPdrk.js +0 -4
- package/assets/assets/TrafficPage-C27a0rQp.js +0 -40
- package/assets/assets/TrafficSourceDetailPage-DOSoQySv.js +0 -1
- package/assets/assets/extract-error-message-itBoiivg.js +0 -1
- package/assets/assets/index-Br2WtEIO.css +0 -1
- package/assets/assets/index-CdAuyP-X.js +0 -86
- package/assets/assets/react-sigma_core.esm.min-CPYhSQFc.js +0 -312
- package/assets/assets/v2-overview-adapter-DQXWmK0B.js +0 -1
- package/assets/assets/vendor-lucide-Y6jANGfG.js +0 -1
- package/assets/assets/vendor-markdown-B4giJcws.js +0 -29
- package/assets/assets/vendor-radix-twS1M3FF.js +0 -45
- package/assets/assets/vendor-recharts-D_R6YxjS.js +0 -36
- package/assets/assets/vendor-tanstack-ZXXkndVj.js +0 -1
- package/assets/assets/vendor-yaml-GWJz5H2G.js +0 -131
- package/dist/chunk-EQTVQIM2.js +0 -23082
- package/dist/chunk-GZPJ7TSE.js +0 -10872
- package/dist/cli-commands-5ZODWR4I.js +0 -15
- package/dist/intelligence-service-ZGDBVFDE.js +0 -9
|
@@ -0,0 +1,1160 @@
|
|
|
1
|
+
import {
|
|
2
|
+
runWithUsageTags
|
|
3
|
+
} from "./chunk-B5J675KK.js";
|
|
4
|
+
import {
|
|
5
|
+
CanonryMcpToolNames,
|
|
6
|
+
canonryMcpTools
|
|
7
|
+
} from "./chunk-ZWJRY5UI.js";
|
|
8
|
+
import {
|
|
9
|
+
CliError
|
|
10
|
+
} from "./chunk-HGMYEDAQ.js";
|
|
11
|
+
import {
|
|
12
|
+
buildOpenApiDocument
|
|
13
|
+
} from "./chunk-DGVUTH7W.js";
|
|
14
|
+
import {
|
|
15
|
+
DEFAULT_COMPETITOR_AUTO_ALIAS_MODE,
|
|
16
|
+
MeasurementPortfolioLists,
|
|
17
|
+
RATIO_UNIT_META_KEY,
|
|
18
|
+
RunKinds,
|
|
19
|
+
describeError,
|
|
20
|
+
formatPercent,
|
|
21
|
+
ratioUnitSchema,
|
|
22
|
+
truncateUtf16
|
|
23
|
+
} from "./chunk-D6COIM3U.js";
|
|
24
|
+
|
|
25
|
+
// src/agent/tools.ts
|
|
26
|
+
import { Type as Type2 } from "@earendil-works/pi-ai";
|
|
27
|
+
|
|
28
|
+
// src/agent/mcp-to-agent-tool.ts
|
|
29
|
+
import { Type } from "@earendil-works/pi-ai";
|
|
30
|
+
import { createHash, randomUUID } from "crypto";
|
|
31
|
+
|
|
32
|
+
// src/agent/tool-result-units.ts
|
|
33
|
+
var SUCCESS_STATUSES = ["200", "201", "202"];
|
|
34
|
+
var MAX_DEPTH = 40;
|
|
35
|
+
var MAX_REF_HOPS = 8;
|
|
36
|
+
var cachedDocument;
|
|
37
|
+
function openApiDocument() {
|
|
38
|
+
cachedDocument ??= buildOpenApiDocument();
|
|
39
|
+
return cachedDocument;
|
|
40
|
+
}
|
|
41
|
+
function responseComponents() {
|
|
42
|
+
return openApiDocument().components?.schemas ?? {};
|
|
43
|
+
}
|
|
44
|
+
function responseSchemasFor(operations) {
|
|
45
|
+
const paths = openApiDocument().paths;
|
|
46
|
+
return operations.flatMap((operation) => {
|
|
47
|
+
const space = operation.indexOf(" ");
|
|
48
|
+
if (space < 0) return [];
|
|
49
|
+
const responses = paths[operation.slice(space + 1)]?.[operation.slice(0, space).toLowerCase()]?.responses;
|
|
50
|
+
const schema = SUCCESS_STATUSES.map((status) => responses?.[status]?.content?.["application/json"]?.schema).find(Boolean);
|
|
51
|
+
return schema ? [schema] : [];
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function isRecord(value) {
|
|
55
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
56
|
+
}
|
|
57
|
+
function resolve(schema, components) {
|
|
58
|
+
let current = schema;
|
|
59
|
+
for (let hop = 0; hop < MAX_REF_HOPS && typeof current.$ref === "string"; hop++) {
|
|
60
|
+
const next = components[current.$ref.replace("#/components/schemas/", "")];
|
|
61
|
+
if (!next) break;
|
|
62
|
+
current = next;
|
|
63
|
+
}
|
|
64
|
+
return current;
|
|
65
|
+
}
|
|
66
|
+
function members(schema) {
|
|
67
|
+
return ["allOf", "anyOf", "oneOf"].flatMap((key) => Array.isArray(schema[key]) ? schema[key] : []);
|
|
68
|
+
}
|
|
69
|
+
function unitOf(schema, components) {
|
|
70
|
+
const own = ratioUnitSchema.safeParse(schema[RATIO_UNIT_META_KEY]);
|
|
71
|
+
if (own.success) return own.data;
|
|
72
|
+
for (const member of members(schema)) {
|
|
73
|
+
const unit = unitOf(resolve(member, components), components);
|
|
74
|
+
if (unit) return unit;
|
|
75
|
+
}
|
|
76
|
+
return void 0;
|
|
77
|
+
}
|
|
78
|
+
function render(schema, value, components, depth) {
|
|
79
|
+
if (depth > MAX_DEPTH) return value;
|
|
80
|
+
const node = resolve(schema, components);
|
|
81
|
+
if (typeof value === "number") {
|
|
82
|
+
const unit = unitOf(node, components);
|
|
83
|
+
return unit ? formatPercent(value, unit) : value;
|
|
84
|
+
}
|
|
85
|
+
let current = value;
|
|
86
|
+
for (const member of members(node)) current = render(member, current, components, depth + 1);
|
|
87
|
+
if (Array.isArray(current) && isRecord(node.items)) {
|
|
88
|
+
const items = node.items;
|
|
89
|
+
let changed = false;
|
|
90
|
+
const out = current.map((item) => {
|
|
91
|
+
const rendered = render(items, item, components, depth + 1);
|
|
92
|
+
if (rendered !== item) changed = true;
|
|
93
|
+
return rendered;
|
|
94
|
+
});
|
|
95
|
+
return changed ? out : current;
|
|
96
|
+
}
|
|
97
|
+
if (isRecord(current)) {
|
|
98
|
+
const properties = isRecord(node.properties) ? node.properties : {};
|
|
99
|
+
const extra = isRecord(node.additionalProperties) ? node.additionalProperties : void 0;
|
|
100
|
+
let changed = false;
|
|
101
|
+
const out = {};
|
|
102
|
+
for (const [key, child] of Object.entries(current)) {
|
|
103
|
+
const childSchema = properties[key] ?? extra;
|
|
104
|
+
const rendered = childSchema ? render(childSchema, child, components, depth + 1) : child;
|
|
105
|
+
if (rendered !== child) changed = true;
|
|
106
|
+
out[key] = rendered;
|
|
107
|
+
}
|
|
108
|
+
if (typeof current.value === "number" && typeof out.value === "string" && Number.isInteger(current.numerator) && Number.isInteger(current.denominator)) {
|
|
109
|
+
out.value = `${out.value} (${current.numerator}/${current.denominator})`;
|
|
110
|
+
}
|
|
111
|
+
return changed ? out : current;
|
|
112
|
+
}
|
|
113
|
+
return current;
|
|
114
|
+
}
|
|
115
|
+
function renderRatioUnits(schema, value, components = {}) {
|
|
116
|
+
return schema ? render(schema, value, components, 0) : value;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/agent/mcp-to-agent-tool.ts
|
|
120
|
+
var MAX_TOOL_RESULT_CHARS = 2e4;
|
|
121
|
+
var TRUNCATION_SUMMARY_KEY = "__truncation";
|
|
122
|
+
var PARTIAL_LISTS_KEY = "__partialLists";
|
|
123
|
+
var CURSOR_KEYS = ["nextCursor", "nextOffset", "nextPageToken", "next_cursor"];
|
|
124
|
+
var PORTFOLIO_PAGE_LISTS = /* @__PURE__ */ new Map([
|
|
125
|
+
[MeasurementPortfolioLists["weakest-properties"], { path: "weakestProperties", totalKey: "totalProperties" }],
|
|
126
|
+
[MeasurementPortfolioLists["strongest-mentions"], { path: "mentionRanking.strongest", totalKey: "eligiblePropertyCount" }],
|
|
127
|
+
[MeasurementPortfolioLists["weakest-mentions"], { path: "mentionRanking.weakest", totalKey: "eligiblePropertyCount" }],
|
|
128
|
+
[MeasurementPortfolioLists["excluded-mentions"], { path: "mentionRanking.excluded", totalKey: "excludedTotal" }],
|
|
129
|
+
[MeasurementPortfolioLists.markets, { path: "markets", totalKey: "totalMarkets" }],
|
|
130
|
+
[MeasurementPortfolioLists["observed-names"], { path: "answerEvidence.observedNames", totalKey: "observedNamesTotal" }],
|
|
131
|
+
[MeasurementPortfolioLists["cited-domains"], { path: "answerEvidence.citedDomains", totalKey: "citedDomainsTotal" }]
|
|
132
|
+
]);
|
|
133
|
+
var MAX_STRUCTURED_TRUNCATION_CHARS = 2e6;
|
|
134
|
+
var TRUNCATION_SERIALIZE_BUDGET_CHARS = 64e6;
|
|
135
|
+
var SMALL_LIST_ROWS = 25;
|
|
136
|
+
var MAX_SUMMARY_KEYS = 30;
|
|
137
|
+
var MAX_SUMMARY_PATH_CHARS = 96;
|
|
138
|
+
var PROJECTION_SUMMARY_CHARS = 5e3;
|
|
139
|
+
var PROJECTION_METADATA_CHARS = PROJECTION_SUMMARY_CHARS - 500;
|
|
140
|
+
var MAX_PARTIAL_DEPTH = 4;
|
|
141
|
+
var MAX_PARTIAL_NOTES = 12;
|
|
142
|
+
function serializeResult(value) {
|
|
143
|
+
return JSON.stringify(value);
|
|
144
|
+
}
|
|
145
|
+
function isRecord2(value) {
|
|
146
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
147
|
+
}
|
|
148
|
+
function keptSummary(counts, cursors = {}) {
|
|
149
|
+
const summary = { droppedKeys: [], keptItems: {} };
|
|
150
|
+
for (const [path, { kept, total }] of counts) {
|
|
151
|
+
if (kept >= total) continue;
|
|
152
|
+
if (kept === 0) summary.droppedKeys.push(path);
|
|
153
|
+
summary.keptItems[path] = `${kept} of ${total}`;
|
|
154
|
+
}
|
|
155
|
+
if (Object.keys(cursors).length > 0) summary.cursors = cursors;
|
|
156
|
+
return summary;
|
|
157
|
+
}
|
|
158
|
+
function noteCursor(owner, ownerPath, listPath, kept, total, notes, root = owner) {
|
|
159
|
+
const cursor = cursorForList(owner, ownerPath, listPath.slice(listPath.lastIndexOf(".") + 1), root);
|
|
160
|
+
if (!cursor || kept >= total) return;
|
|
161
|
+
notes[cursor.path] = `incomplete page: skips the ${total - kept} rows cut from ${listPath}; re-request the original cursor with ${kept > 0 ? `${cursor.limit} <= ${kept}` : `a lower ${cursor.limit}`}`;
|
|
162
|
+
}
|
|
163
|
+
function cursorForList(owner, ownerPath, listKey, root = owner) {
|
|
164
|
+
const prefix = ownerPath ? `${ownerPath}.` : "";
|
|
165
|
+
if (listKey === "queries" && isRecord2(owner.queryPage) && owner.queryPage.nextCursor !== void 0 && owner.queryPage.nextCursor !== null) {
|
|
166
|
+
const page = owner.queryPage;
|
|
167
|
+
return {
|
|
168
|
+
path: `${prefix}queryPage.nextCursor`,
|
|
169
|
+
value: page.nextCursor,
|
|
170
|
+
parameter: "queryCursor",
|
|
171
|
+
limit: "queryLimit",
|
|
172
|
+
...typeof page.total === "number" ? { total: { count: page.total, text: String(page.total) } } : {}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
if (listKey === "attempts" && owner.nextAttemptCursor !== void 0 && owner.nextAttemptCursor !== null) {
|
|
176
|
+
return {
|
|
177
|
+
path: `${prefix}nextAttemptCursor`,
|
|
178
|
+
value: owner.nextAttemptCursor,
|
|
179
|
+
parameter: "attemptCursor",
|
|
180
|
+
limit: "attemptLimit",
|
|
181
|
+
...typeof owner.attemptCount === "number" ? { total: { count: owner.attemptCount, text: String(owner.attemptCount) } } : {}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
const selected = typeof root.pageList === "string" ? PORTFOLIO_PAGE_LISTS.get(root.pageList) : void 0;
|
|
185
|
+
const selectedList = selected?.path === `${prefix}${listKey}`;
|
|
186
|
+
if (selected && owner === root && !selectedList) return void 0;
|
|
187
|
+
const cursorOwner = selectedList ? root : owner;
|
|
188
|
+
const cursorPrefix = selectedList ? "" : prefix;
|
|
189
|
+
const key = CURSOR_KEYS.find((candidate) => cursorOwner[candidate] !== void 0 && cursorOwner[candidate] !== null);
|
|
190
|
+
if (!key) return void 0;
|
|
191
|
+
const total = selectedList ? owner[selected.totalKey] : void 0;
|
|
192
|
+
return {
|
|
193
|
+
path: `${cursorPrefix}${key}`,
|
|
194
|
+
value: cursorOwner[key],
|
|
195
|
+
parameter: "cursor",
|
|
196
|
+
limit: "limit",
|
|
197
|
+
...typeof total === "number" ? { total: { count: total, text: String(total) } } : {}
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function ownListTotal(numbers, key) {
|
|
201
|
+
const lower = key.toLowerCase();
|
|
202
|
+
for (const [field, value] of numbers) {
|
|
203
|
+
if (field === "total" || field === "totalEstimate") continue;
|
|
204
|
+
if (field === `${key}Total` || field === `${key.replace(/s$/, "")}Total` || /^total[A-Z]/.test(field) && lower.endsWith(field.slice(5).toLowerCase())) return { count: value, text: String(value) };
|
|
205
|
+
}
|
|
206
|
+
return void 0;
|
|
207
|
+
}
|
|
208
|
+
function bareTotal(numbers) {
|
|
209
|
+
const total = numbers.find(([field]) => field === "total");
|
|
210
|
+
if (total) return { count: total[1], text: String(total[1]) };
|
|
211
|
+
const estimate = numbers.find(([field]) => field === "totalEstimate");
|
|
212
|
+
return estimate ? { count: estimate[1], text: `about ${estimate[1]}` } : void 0;
|
|
213
|
+
}
|
|
214
|
+
function partialLists(root) {
|
|
215
|
+
const notes = [];
|
|
216
|
+
const visit = (object, path, depth) => {
|
|
217
|
+
const lists = [];
|
|
218
|
+
const numbers = [];
|
|
219
|
+
for (const [key, value] of Object.entries(object)) {
|
|
220
|
+
if (key.startsWith("__")) continue;
|
|
221
|
+
if (Array.isArray(value)) lists.push([key, value]);
|
|
222
|
+
else if (typeof value === "number") numbers.push([key, value]);
|
|
223
|
+
}
|
|
224
|
+
let noted = false;
|
|
225
|
+
if (lists.length <= MAX_SUMMARY_KEYS) {
|
|
226
|
+
const counts = lists.map(([key]) => ownListTotal(numbers, key) ?? cursorForList(object, path, key, root)?.total);
|
|
227
|
+
const uncounted = counts.flatMap((count, index) => count ? [] : [index]);
|
|
228
|
+
if (uncounted.length === 1) {
|
|
229
|
+
const index = uncounted[0];
|
|
230
|
+
const key = lists[index][0];
|
|
231
|
+
const paged = object === root || cursorForList(object, path, key, root) || typeof object.truncated === "boolean" || typeof object[`${key}Truncated`] === "boolean" || ["items", "rows", "results"].includes(key);
|
|
232
|
+
if (paged) counts[index] = bareTotal(numbers);
|
|
233
|
+
}
|
|
234
|
+
for (const [index, [key, rows]] of lists.entries()) {
|
|
235
|
+
const label = path ? `${path}.${key}` : key;
|
|
236
|
+
const count = counts[index];
|
|
237
|
+
const ownFlag = object[`${key}Truncated`];
|
|
238
|
+
if (count) {
|
|
239
|
+
if (count.count <= rows.length) continue;
|
|
240
|
+
notes.push([label, `${rows.length} of ${count.text}`]);
|
|
241
|
+
noted = true;
|
|
242
|
+
} else if (ownFlag === true || object.truncated === true && typeof ownFlag !== "boolean" && (lists.length === 1 || rows.some(isRecord2))) {
|
|
243
|
+
notes.push([label, `${rows.length} shown; the tool cut this list`]);
|
|
244
|
+
noted = true;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (object.truncated === true && !noted) notes.push([path || "(root)", "the tool cut the lists here"]);
|
|
249
|
+
if (depth >= MAX_PARTIAL_DEPTH || notes.length >= MAX_PARTIAL_NOTES) return;
|
|
250
|
+
for (const [key, value] of Object.entries(object)) {
|
|
251
|
+
if (!key.startsWith("__") && isRecord2(value)) visit(value, path ? `${path}.${key}` : key, depth + 1);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
visit(root, "", 1);
|
|
255
|
+
return notes.length > 0 ? Object.fromEntries(notes.slice(0, MAX_PARTIAL_NOTES)) : void 0;
|
|
256
|
+
}
|
|
257
|
+
function withPartialLists(value) {
|
|
258
|
+
if (!isRecord2(value) || typeof value.toJSON === "function") return value;
|
|
259
|
+
const hadNote = Object.hasOwn(value, PARTIAL_LISTS_KEY);
|
|
260
|
+
const notes = partialLists(value);
|
|
261
|
+
if (!notes && !hadNote && value.nextAttemptCursor == null && !CURSOR_KEYS.some((key) => value[key] !== void 0 && value[key] !== null) && !Object.values(value).some((child) => isRecord2(child) && CURSOR_KEYS.some((key) => child[key] !== void 0 && child[key] !== null))) return value;
|
|
262
|
+
const pagination = {};
|
|
263
|
+
const visit = (owner, path, depth) => {
|
|
264
|
+
const lists = Object.entries(owner).filter((entry) => Array.isArray(entry[1]));
|
|
265
|
+
const numbers = Object.entries(owner).filter((entry) => typeof entry[1] === "number");
|
|
266
|
+
for (const [key, rows] of lists) {
|
|
267
|
+
const cursor = cursorForList(owner, path, key, value);
|
|
268
|
+
if (!cursor || key.startsWith("__") || Object.keys(pagination).length >= MAX_PARTIAL_NOTES) continue;
|
|
269
|
+
const label = path ? `${path}.${key}` : key;
|
|
270
|
+
const total = cursor.total ?? ownListTotal(numbers, key) ?? (lists.length === 1 ? bareTotal(numbers) : void 0);
|
|
271
|
+
const incomplete = owner.__truncated === true || isRecord2(owner.__omittedRowsByField) && typeof owner.__omittedRowsByField[key] === "number";
|
|
272
|
+
pagination[label] = `showing ${rows.length}${total ? ` of ${total.text}` : " rows"}; ${incomplete ? `incomplete page: re-request the original cursor with a smaller ${cursor.limit}; the next cursor skips omitted rows` : `pass ${cursor.parameter} ${JSON.stringify(cursor.value)}`}`;
|
|
273
|
+
}
|
|
274
|
+
if (depth >= MAX_PARTIAL_DEPTH) return;
|
|
275
|
+
for (const [key, child] of Object.entries(owner)) if (!key.startsWith("__") && isRecord2(child)) visit(child, path ? `${path}.${key}` : key, depth + 1);
|
|
276
|
+
};
|
|
277
|
+
visit(value, "", 1);
|
|
278
|
+
const { [PARTIAL_LISTS_KEY]: _previous, __pagination: _pagination, ...rest } = value;
|
|
279
|
+
return { ...notes ? { [PARTIAL_LISTS_KEY]: notes } : {}, ...Object.keys(pagination).length > 0 ? { __pagination: pagination } : {}, ...rest };
|
|
280
|
+
}
|
|
281
|
+
function largestArrayKey(obj) {
|
|
282
|
+
let best;
|
|
283
|
+
let bestLen = -1;
|
|
284
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
285
|
+
if (!Array.isArray(v)) continue;
|
|
286
|
+
const len = serializeResult(v).length;
|
|
287
|
+
if (len > bestLen) {
|
|
288
|
+
bestLen = len;
|
|
289
|
+
best = k;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return best;
|
|
293
|
+
}
|
|
294
|
+
function fitsCap(text) {
|
|
295
|
+
return text.length <= MAX_TOOL_RESULT_CHARS;
|
|
296
|
+
}
|
|
297
|
+
function largestFitting(max, fits) {
|
|
298
|
+
let low = 0;
|
|
299
|
+
let high = max;
|
|
300
|
+
while (low < high) {
|
|
301
|
+
const middle = Math.ceil((low + high) / 2);
|
|
302
|
+
if (fits(middle)) low = middle;
|
|
303
|
+
else high = middle - 1;
|
|
304
|
+
}
|
|
305
|
+
return low;
|
|
306
|
+
}
|
|
307
|
+
function trimRowsToFit(rows, render2) {
|
|
308
|
+
if (rows.length === 0) return [];
|
|
309
|
+
const all = rows.slice();
|
|
310
|
+
if (fitsCap(render2(all))) return all;
|
|
311
|
+
return rows.slice(0, largestFitting(rows.length - 1, (count) => fitsCap(render2(rows.slice(0, count)))));
|
|
312
|
+
}
|
|
313
|
+
function listTrimmer(lists) {
|
|
314
|
+
const owners = /* @__PURE__ */ new Map();
|
|
315
|
+
lists.forEach((list, index) => {
|
|
316
|
+
const indexes = owners.get(list.owner);
|
|
317
|
+
if (indexes) indexes.push(index);
|
|
318
|
+
else owners.set(list.owner, [index]);
|
|
319
|
+
});
|
|
320
|
+
const markers = [...owners].map(([owner, indexes]) => {
|
|
321
|
+
const previous = owner.__omittedRowsByField;
|
|
322
|
+
return {
|
|
323
|
+
owner,
|
|
324
|
+
indexes,
|
|
325
|
+
hadTruncated: Object.hasOwn(owner, "__truncated"),
|
|
326
|
+
priorTruncated: owner.__truncated,
|
|
327
|
+
previous,
|
|
328
|
+
priorOmitted: isRecord2(previous) ? previous : void 0
|
|
329
|
+
};
|
|
330
|
+
});
|
|
331
|
+
return (counts) => {
|
|
332
|
+
lists.forEach((list, index) => {
|
|
333
|
+
list.owner[list.key] = list.rows.slice(0, counts[index]);
|
|
334
|
+
});
|
|
335
|
+
for (const { owner, indexes, hadTruncated, priorTruncated, previous, priorOmitted } of markers) {
|
|
336
|
+
const omitted = {};
|
|
337
|
+
for (const index of indexes) {
|
|
338
|
+
const { key, rows } = lists[index];
|
|
339
|
+
const prior = typeof priorOmitted?.[key] === "number" ? priorOmitted[key] : 0;
|
|
340
|
+
const count = prior + rows.length - Math.min(counts[index], rows.length);
|
|
341
|
+
if (count > 0) omitted[key] = count;
|
|
342
|
+
}
|
|
343
|
+
if (Object.keys(omitted).length > 0) {
|
|
344
|
+
owner.__truncated = true;
|
|
345
|
+
owner.__omittedRowsByField = { ...priorOmitted, ...omitted };
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
if (hadTruncated) owner.__truncated = priorTruncated;
|
|
349
|
+
else delete owner.__truncated;
|
|
350
|
+
if (previous === void 0) delete owner.__omittedRowsByField;
|
|
351
|
+
else owner.__omittedRowsByField = previous;
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function collectCollections(root) {
|
|
356
|
+
const found = [];
|
|
357
|
+
const visit = (object, path, nested) => {
|
|
358
|
+
for (const [key, value] of Object.entries(object)) {
|
|
359
|
+
if (object === root && (key === TRUNCATION_SUMMARY_KEY || key === PARTIAL_LISTS_KEY)) continue;
|
|
360
|
+
const valuePath = path ? `${path}.${key}` : key;
|
|
361
|
+
if (Array.isArray(value)) {
|
|
362
|
+
let records = false;
|
|
363
|
+
for (const row of value) {
|
|
364
|
+
if (!isRecord2(row)) continue;
|
|
365
|
+
records = true;
|
|
366
|
+
visit(row, `${valuePath}[]`, true);
|
|
367
|
+
}
|
|
368
|
+
if (value.length > 0) found.push({ path: valuePath, nested, records, owner: object, key, rows: value });
|
|
369
|
+
} else if (isRecord2(value)) {
|
|
370
|
+
visit(value, valuePath, nested);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
visit(root, "", false);
|
|
375
|
+
return found;
|
|
376
|
+
}
|
|
377
|
+
var TRIM_STAGES = [
|
|
378
|
+
// Lists longer than a rollup, wherever they sit, down to rollup size.
|
|
379
|
+
{ applies: (list) => list.records && list.rows.length > SMALL_LIST_ROWS, floor: SMALL_LIST_ROWS },
|
|
380
|
+
// Per-row detail (the names under each Property row), down to one entry a row.
|
|
381
|
+
{ applies: (list) => list.records && list.nested, floor: 1 },
|
|
382
|
+
// Every other list, rollups included, down to one row.
|
|
383
|
+
{ applies: (list) => list.records && !list.nested, floor: 1 },
|
|
384
|
+
{ applies: (list) => list.records && list.nested, floor: 0 },
|
|
385
|
+
{ applies: (list) => list.records && !list.nested, floor: 0 },
|
|
386
|
+
// Scalar lists can carry identity (served model IDs), so they go last.
|
|
387
|
+
{ applies: (list) => !list.records, floor: 0 }
|
|
388
|
+
];
|
|
389
|
+
function currentSummary(root, owned) {
|
|
390
|
+
const counts = /* @__PURE__ */ new Map();
|
|
391
|
+
const cursors = {};
|
|
392
|
+
const visit = (object, path) => {
|
|
393
|
+
const lists = owned.get(object);
|
|
394
|
+
for (const [key, value] of Object.entries(object)) {
|
|
395
|
+
if (object === root && (key === TRUNCATION_SUMMARY_KEY || key === PARTIAL_LISTS_KEY)) continue;
|
|
396
|
+
const valuePath = path ? `${path}.${key}` : key;
|
|
397
|
+
if (Array.isArray(value)) {
|
|
398
|
+
const list = lists?.get(key);
|
|
399
|
+
if (list) {
|
|
400
|
+
const count = counts.get(list.path) ?? { kept: 0, total: 0 };
|
|
401
|
+
count.kept += value.length;
|
|
402
|
+
count.total += list.rows.length;
|
|
403
|
+
counts.set(list.path, count);
|
|
404
|
+
noteCursor(object, path, list.path, value.length, list.rows.length, cursors, root);
|
|
405
|
+
}
|
|
406
|
+
for (const row of value) if (isRecord2(row)) visit(row, `${valuePath}[]`);
|
|
407
|
+
} else if (isRecord2(value)) {
|
|
408
|
+
visit(value, valuePath);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
visit(root, "");
|
|
413
|
+
return keptSummary(counts, cursors);
|
|
414
|
+
}
|
|
415
|
+
function emptiedFloorChars(root) {
|
|
416
|
+
return JSON.stringify(root, (_key, value) => Array.isArray(value) ? [] : value).length;
|
|
417
|
+
}
|
|
418
|
+
function trimNestedArrays(full) {
|
|
419
|
+
const copy = JSON.parse(full);
|
|
420
|
+
if (!isRecord2(copy)) return void 0;
|
|
421
|
+
copy.__truncated = true;
|
|
422
|
+
copy[TRUNCATION_SUMMARY_KEY] = keptSummary(/* @__PURE__ */ new Map());
|
|
423
|
+
if (emptiedFloorChars(copy) > MAX_TOOL_RESULT_CHARS) return void 0;
|
|
424
|
+
const lists = collectCollections(copy);
|
|
425
|
+
const owned = /* @__PURE__ */ new Map();
|
|
426
|
+
for (const list of lists) {
|
|
427
|
+
const byKey = owned.get(list.owner) ?? /* @__PURE__ */ new Map();
|
|
428
|
+
byKey.set(list.key, list);
|
|
429
|
+
owned.set(list.owner, byKey);
|
|
430
|
+
}
|
|
431
|
+
const stagesOf = lists.map((list) => TRIM_STAGES.flatMap((stage, index) => stage.applies(list) ? [index] : []));
|
|
432
|
+
const levels = TRIM_STAGES.map(() => Infinity);
|
|
433
|
+
let boosted;
|
|
434
|
+
const capOf = (index) => stagesOf[index].reduce((cap, stage) => Math.min(
|
|
435
|
+
cap,
|
|
436
|
+
levels[stage] + (boosted?.stage === stage && boosted.lists.has(index) ? 1 : 0)
|
|
437
|
+
), Infinity);
|
|
438
|
+
const trim = listTrimmer(lists);
|
|
439
|
+
let spent = 0;
|
|
440
|
+
const render2 = () => {
|
|
441
|
+
trim(lists.map((_, index) => capOf(index)));
|
|
442
|
+
copy[TRUNCATION_SUMMARY_KEY] = currentSummary(copy, owned);
|
|
443
|
+
const text = serializeResult(withPartialLists(copy));
|
|
444
|
+
spent += text.length;
|
|
445
|
+
return text;
|
|
446
|
+
};
|
|
447
|
+
const fits = () => spent <= TRUNCATION_SERIALIZE_BUDGET_CHARS && fitsCap(render2());
|
|
448
|
+
const members2 = (stage) => lists.flatMap((_, index) => stagesOf[index].includes(stage) ? [index] : []);
|
|
449
|
+
const longest = (indexes) => indexes.reduce((max, index) => Math.max(max, lists[index].rows.length), 0);
|
|
450
|
+
let out = render2();
|
|
451
|
+
let fittedAt = -1;
|
|
452
|
+
for (let stage = 0; stage < TRIM_STAGES.length && !fitsCap(out); stage++) {
|
|
453
|
+
if (spent > TRUNCATION_SERIALIZE_BUDGET_CHARS) return void 0;
|
|
454
|
+
const { floor } = TRIM_STAGES[stage];
|
|
455
|
+
const indexes = members2(stage);
|
|
456
|
+
const top = longest(indexes);
|
|
457
|
+
if (top <= floor) continue;
|
|
458
|
+
levels[stage] = floor;
|
|
459
|
+
out = render2();
|
|
460
|
+
if (!fitsCap(out)) continue;
|
|
461
|
+
fittedAt = stage;
|
|
462
|
+
const level = floor + largestFitting(top - floor - 1, (n) => {
|
|
463
|
+
levels[stage] = floor + n;
|
|
464
|
+
return fits();
|
|
465
|
+
});
|
|
466
|
+
levels[stage] = level;
|
|
467
|
+
const cut = indexes.filter((index) => lists[index].rows.length > level && capOf(index) === level);
|
|
468
|
+
const extra = largestFitting(cut.length, (n) => {
|
|
469
|
+
boosted = { stage, lists: new Set(cut.slice(0, n)) };
|
|
470
|
+
return fits();
|
|
471
|
+
});
|
|
472
|
+
boosted = { stage, lists: new Set(cut.slice(0, extra)) };
|
|
473
|
+
out = render2();
|
|
474
|
+
}
|
|
475
|
+
if (!fitsCap(out)) return void 0;
|
|
476
|
+
for (let stage = fittedAt - 1; stage >= 0; stage--) {
|
|
477
|
+
const floor = levels[stage];
|
|
478
|
+
const top = longest(members2(stage));
|
|
479
|
+
if (floor === Infinity || top <= floor) continue;
|
|
480
|
+
levels[stage] = floor + largestFitting(top - floor, (n) => {
|
|
481
|
+
levels[stage] = floor + n;
|
|
482
|
+
return fits();
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
out = render2();
|
|
486
|
+
return fitsCap(out) ? out : void 0;
|
|
487
|
+
}
|
|
488
|
+
function keptRowTotal(serialized) {
|
|
489
|
+
const count = (value) => {
|
|
490
|
+
if (Array.isArray(value)) return value.length;
|
|
491
|
+
if (!isRecord2(value)) return 0;
|
|
492
|
+
return Object.entries(value).reduce((sum, [key, child]) => key.startsWith("__") ? sum : sum + count(child), 0);
|
|
493
|
+
};
|
|
494
|
+
try {
|
|
495
|
+
return count(JSON.parse(serialized));
|
|
496
|
+
} catch {
|
|
497
|
+
return 0;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
function hasOtherLists(value, primary) {
|
|
501
|
+
if (Array.isArray(value)) {
|
|
502
|
+
if (value !== primary && value.length > 0) return true;
|
|
503
|
+
return value.some((row) => (isRecord2(row) || Array.isArray(row)) && hasOtherLists(row, primary));
|
|
504
|
+
}
|
|
505
|
+
return isRecord2(value) && Object.values(value).some((child) => hasOtherLists(child, primary));
|
|
506
|
+
}
|
|
507
|
+
function projectionPath(path) {
|
|
508
|
+
if (path.length <= MAX_SUMMARY_PATH_CHARS) return path;
|
|
509
|
+
const digest = createHash("sha256").update(path).digest("hex").slice(0, 12);
|
|
510
|
+
return `${truncateUtf16(path, 48)}...#${digest}${path.slice(-24)}`;
|
|
511
|
+
}
|
|
512
|
+
function boundedProjection(full, partialRows, reserve = 0) {
|
|
513
|
+
const value = JSON.parse(full);
|
|
514
|
+
let summary = {
|
|
515
|
+
droppedKeys: [],
|
|
516
|
+
keptItems: {},
|
|
517
|
+
projection: partialRows ? "Array rows are complete unless slicedKeys or droppedKeys name a field inside one; sliced strings are partial prefixes and omitted fields are not evidence. Never follow a cursor from a cut page; re-request the original cursor with a smaller limit." : "Only complete array rows and marked partial string prefixes are shown; omitted fields are not evidence. Never follow a cursor from a cut page; re-request the original cursor with a smaller limit."
|
|
518
|
+
};
|
|
519
|
+
const skippedMetadata = () => {
|
|
520
|
+
summary.moreMetadataEntries = (summary.moreMetadataEntries ?? 0) + 1;
|
|
521
|
+
};
|
|
522
|
+
const record = (entries, path, value2) => {
|
|
523
|
+
if (Object.keys(entries).length >= MAX_SUMMARY_KEYS) {
|
|
524
|
+
skippedMetadata();
|
|
525
|
+
return false;
|
|
526
|
+
}
|
|
527
|
+
const key = projectionPath(path);
|
|
528
|
+
entries[key] = value2;
|
|
529
|
+
if (serializeResult(summary).length <= PROJECTION_METADATA_CHARS) return true;
|
|
530
|
+
delete entries[key];
|
|
531
|
+
skippedMetadata();
|
|
532
|
+
return false;
|
|
533
|
+
};
|
|
534
|
+
let dropped = 0;
|
|
535
|
+
const omit = (path) => {
|
|
536
|
+
dropped++;
|
|
537
|
+
if (summary.droppedKeys.length < MAX_SUMMARY_KEYS) {
|
|
538
|
+
summary.droppedKeys.push(projectionPath(path));
|
|
539
|
+
if (serializeResult(summary).length > PROJECTION_METADATA_CHARS) summary.droppedKeys.pop();
|
|
540
|
+
}
|
|
541
|
+
if (dropped > summary.droppedKeys.length) summary.moreDroppedKeys = dropped - summary.droppedKeys.length;
|
|
542
|
+
};
|
|
543
|
+
const cutOwners = /* @__PURE__ */ new Set();
|
|
544
|
+
const project = (input, budget, path, owner, ownerPath = "") => {
|
|
545
|
+
if (Array.isArray(input)) {
|
|
546
|
+
const rows = [];
|
|
547
|
+
let used2 = 2;
|
|
548
|
+
for (const row of input) {
|
|
549
|
+
const text = serializeResult(row);
|
|
550
|
+
const cost = text.length + (rows.length > 0 ? 1 : 0);
|
|
551
|
+
if (used2 + cost <= budget) {
|
|
552
|
+
rows.push(text);
|
|
553
|
+
used2 += cost;
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (partialRows && (rows.length === 0 || text.length > MAX_TOOL_RESULT_CHARS)) {
|
|
557
|
+
const before = { summary: serializeResult(summary), dropped };
|
|
558
|
+
const partial = project(row, budget - used2 - (rows.length > 0 ? 1 : 0), `${path || "items"}[${rows.length}]`);
|
|
559
|
+
if (partial !== void 0 && partial !== "{}" && partial !== "[]") {
|
|
560
|
+
partialRows.set(path || "items", rows.length);
|
|
561
|
+
rows.push(partial);
|
|
562
|
+
} else {
|
|
563
|
+
summary = JSON.parse(before.summary);
|
|
564
|
+
dropped = before.dropped;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
if (rows.length < input.length) {
|
|
570
|
+
if (partialRows && owner) cutOwners.add(owner);
|
|
571
|
+
record(summary.keptItems, path || "items", `${rows.length} of ${input.length}`);
|
|
572
|
+
if (rows.length === 0) omit(path || "items");
|
|
573
|
+
if (owner) {
|
|
574
|
+
const cursors = {};
|
|
575
|
+
noteCursor(owner, ownerPath, path, rows.length, input.length, cursors, isRecord2(value) ? value : owner);
|
|
576
|
+
for (const [cursor, note] of Object.entries(cursors)) {
|
|
577
|
+
record(summary.cursors ??= {}, cursor, note.replace(path, projectionPath(path)));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return `[${rows.join(",")}]`;
|
|
582
|
+
}
|
|
583
|
+
if (!isRecord2(input)) {
|
|
584
|
+
const text = serializeResult(input);
|
|
585
|
+
if (text.length <= budget) return text;
|
|
586
|
+
if (typeof input === "string" && budget > 2) {
|
|
587
|
+
const kept = largestFitting(Math.min(input.length, budget - 2), (length) => serializeResult(truncateUtf16(input, length)).length <= budget);
|
|
588
|
+
const prefix = truncateUtf16(input, kept);
|
|
589
|
+
if (prefix.length > 0 && record(summary.slicedKeys ??= {}, path || "(root)", { keptChars: prefix.length, totalChars: input.length })) return serializeResult(prefix);
|
|
590
|
+
}
|
|
591
|
+
omit(path || "(root)");
|
|
592
|
+
return void 0;
|
|
593
|
+
}
|
|
594
|
+
const priority = ([key, child]) => key === "queryPage" && isRecord2(child) ? 0 : typeof child === "string" && child.length > budget ? 2 : typeof child !== "object" || child === null ? 0 : partialRows && serializeResult(child).length > budget ? 2 : 1;
|
|
595
|
+
const fields = Object.entries(input).filter(([key]) => !key.startsWith("__")).map((field) => ({ field, rank: priority(field) })).sort((a, b) => a.rank - b.rank).map(({ field }) => field);
|
|
596
|
+
const shown2 = [];
|
|
597
|
+
let used = 2;
|
|
598
|
+
for (const [key, child] of fields) {
|
|
599
|
+
const childPath = path ? `${path}.${key}` : key;
|
|
600
|
+
const prefix = `${JSON.stringify(key)}:`;
|
|
601
|
+
const allowance = budget - used - prefix.length - (shown2.length > 0 ? 1 : 0);
|
|
602
|
+
if (allowance < 2) {
|
|
603
|
+
omit(childPath);
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
const text = project(child, allowance, childPath, input, path);
|
|
607
|
+
if (text === void 0) continue;
|
|
608
|
+
shown2.push(prefix + text);
|
|
609
|
+
used += prefix.length + text.length + (shown2.length > 1 ? 1 : 0);
|
|
610
|
+
}
|
|
611
|
+
if (path && cutOwners.has(input)) shown2.push('"__truncated":true');
|
|
612
|
+
return `{${shown2.join(",")}}`;
|
|
613
|
+
};
|
|
614
|
+
const projected = project(value, MAX_TOOL_RESULT_CHARS - PROJECTION_SUMMARY_CHARS - reserve, "");
|
|
615
|
+
const shown = projected === void 0 ? {} : JSON.parse(projected);
|
|
616
|
+
const output = isRecord2(shown) ? shown : { items: shown };
|
|
617
|
+
const result = { ...output, __truncated: true, [TRUNCATION_SUMMARY_KEY]: summary };
|
|
618
|
+
return serializeResult(partialRows ? withPartialLists(result) : result);
|
|
619
|
+
}
|
|
620
|
+
function rowsShown(cut, path) {
|
|
621
|
+
if (path.includes("[")) return Infinity;
|
|
622
|
+
const list = path.split(".").reduce((owner, key) => isRecord2(owner) ? owner[key] : void 0, cut);
|
|
623
|
+
return Array.isArray(list) ? list.length : 0;
|
|
624
|
+
}
|
|
625
|
+
function withPartialRows(full, whole) {
|
|
626
|
+
const rescued = /* @__PURE__ */ new Map();
|
|
627
|
+
let partial = boundedProjection(full, rescued);
|
|
628
|
+
if (!fitsCap(partial)) {
|
|
629
|
+
const { [PARTIAL_LISTS_KEY]: lists, __pagination: pagination } = JSON.parse(partial);
|
|
630
|
+
rescued.clear();
|
|
631
|
+
partial = boundedProjection(full, rescued, serializeResult({ lists, pagination }).length);
|
|
632
|
+
}
|
|
633
|
+
if (!fitsCap(partial)) return whole;
|
|
634
|
+
const cut = JSON.parse(whole);
|
|
635
|
+
return [...rescued].some(([path, index]) => rowsShown(cut, path) <= index) ? partial : whole;
|
|
636
|
+
}
|
|
637
|
+
function truncateToolResult(details, options = {}) {
|
|
638
|
+
const annotated = withPartialLists(details);
|
|
639
|
+
const full = serializeResult(annotated);
|
|
640
|
+
if (full.length <= MAX_TOOL_RESULT_CHARS) return full;
|
|
641
|
+
const whole = truncateWholeRows(details, full);
|
|
642
|
+
return options.partialRows ? withPartialRows(full, whole) : whole;
|
|
643
|
+
}
|
|
644
|
+
function truncateWholeRows(details, full) {
|
|
645
|
+
if (full.length > MAX_STRUCTURED_TRUNCATION_CHARS) return boundedProjection(full);
|
|
646
|
+
if (Array.isArray(details)) {
|
|
647
|
+
const render2 = (rows) => serializeResult({
|
|
648
|
+
items: rows,
|
|
649
|
+
__truncated: true,
|
|
650
|
+
__omittedRows: details.length - rows.length,
|
|
651
|
+
[TRUNCATION_SUMMARY_KEY]: keptSummary(/* @__PURE__ */ new Map([["items", { kept: rows.length, total: details.length }]]))
|
|
652
|
+
});
|
|
653
|
+
return render2(trimRowsToFit(details, render2));
|
|
654
|
+
}
|
|
655
|
+
if (details && typeof details === "object") {
|
|
656
|
+
const obj = details;
|
|
657
|
+
const arrayKey = largestArrayKey(obj);
|
|
658
|
+
if (!arrayKey) return trimNestedArrays(full) ?? boundedProjection(full);
|
|
659
|
+
const rows = obj[arrayKey];
|
|
660
|
+
const render2 = (kept) => {
|
|
661
|
+
const cursors = {};
|
|
662
|
+
noteCursor(obj, "", arrayKey, kept.length, rows.length, cursors);
|
|
663
|
+
return serializeResult(withPartialLists({
|
|
664
|
+
...obj,
|
|
665
|
+
[arrayKey]: kept,
|
|
666
|
+
__truncated: true,
|
|
667
|
+
__omittedRows: rows.length - kept.length,
|
|
668
|
+
[TRUNCATION_SUMMARY_KEY]: keptSummary(/* @__PURE__ */ new Map([[arrayKey, { kept: kept.length, total: rows.length }]]), cursors)
|
|
669
|
+
}));
|
|
670
|
+
};
|
|
671
|
+
const out = render2(trimRowsToFit(rows, render2));
|
|
672
|
+
const nested = !fitsCap(out) || hasOtherLists(obj, rows) ? trimNestedArrays(full) : void 0;
|
|
673
|
+
if (fitsCap(out) && (nested === void 0 || keptRowTotal(nested) <= keptRowTotal(out))) return out;
|
|
674
|
+
if (nested !== void 0) return nested;
|
|
675
|
+
}
|
|
676
|
+
return boundedProjection(full);
|
|
677
|
+
}
|
|
678
|
+
function textResult(details, responseSchemas = []) {
|
|
679
|
+
const components = responseSchemas.length > 0 ? responseComponents() : {};
|
|
680
|
+
const shown = responseSchemas.reduce((value, schema) => renderRatioUnits(schema, value, components), details);
|
|
681
|
+
return {
|
|
682
|
+
content: [{ type: "text", text: truncateToolResult(shown) }],
|
|
683
|
+
details
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
var MEMO_STORED_READS = /* @__PURE__ */ new Set([
|
|
687
|
+
CanonryMcpToolNames.canonry_competitor_landscape,
|
|
688
|
+
CanonryMcpToolNames.canonry_measurement_overview,
|
|
689
|
+
CanonryMcpToolNames.canonry_measurement_portfolio_summary,
|
|
690
|
+
CanonryMcpToolNames.canonry_measurement_property_evidence,
|
|
691
|
+
CanonryMcpToolNames.canonry_measurement_property_questions,
|
|
692
|
+
CanonryMcpToolNames.canonry_measurement_question_result,
|
|
693
|
+
CanonryMcpToolNames.canonry_measurement_property_competitors,
|
|
694
|
+
CanonryMcpToolNames.canonry_measurement_changes,
|
|
695
|
+
CanonryMcpToolNames.canonry_visibility_report,
|
|
696
|
+
CanonryMcpToolNames.canonry_visibility_stats,
|
|
697
|
+
CanonryMcpToolNames.canonry_visibility_compare,
|
|
698
|
+
CanonryMcpToolNames.canonry_sentiment,
|
|
699
|
+
CanonryMcpToolNames.canonry_sentiment_settings,
|
|
700
|
+
CanonryMcpToolNames.canonry_sentiment_evidence,
|
|
701
|
+
CanonryMcpToolNames.canonry_sentiment_compare,
|
|
702
|
+
CanonryMcpToolNames.canonry_sentiment_backfill_preview,
|
|
703
|
+
CanonryMcpToolNames.canonry_insights_list
|
|
704
|
+
]);
|
|
705
|
+
var STORED_PAGE_READS = /* @__PURE__ */ new Set([
|
|
706
|
+
...MEMO_STORED_READS,
|
|
707
|
+
CanonryMcpToolNames.canonry_project_overview,
|
|
708
|
+
CanonryMcpToolNames.canonry_measurement_data_quality,
|
|
709
|
+
CanonryMcpToolNames.canonry_sentiment_job,
|
|
710
|
+
CanonryMcpToolNames.canonry_sentiment_jobs
|
|
711
|
+
]);
|
|
712
|
+
var storedReadTools = /* @__PURE__ */ new WeakSet();
|
|
713
|
+
var storedPageReadTools = /* @__PURE__ */ new WeakSet();
|
|
714
|
+
function isStoredReadTool(tool) {
|
|
715
|
+
return storedReadTools.has(tool);
|
|
716
|
+
}
|
|
717
|
+
function isStoredPageReadTool(tool) {
|
|
718
|
+
return storedPageReadTools.has(tool);
|
|
719
|
+
}
|
|
720
|
+
function stripProjectFromJsonSchema(jsonSchema) {
|
|
721
|
+
if (!jsonSchema || typeof jsonSchema !== "object") {
|
|
722
|
+
return { schema: jsonSchema, hadProject: false };
|
|
723
|
+
}
|
|
724
|
+
const obj = jsonSchema;
|
|
725
|
+
const properties = obj.properties;
|
|
726
|
+
if (!properties || typeof properties !== "object" || !("project" in properties)) {
|
|
727
|
+
return { schema: jsonSchema, hadProject: false };
|
|
728
|
+
}
|
|
729
|
+
const { project: _project, ...remainingProps } = properties;
|
|
730
|
+
const required = Array.isArray(obj.required) ? obj.required.filter((name) => name !== "project") : obj.required;
|
|
731
|
+
const stripped = { ...obj, properties: remainingProps };
|
|
732
|
+
if (required === void 0) {
|
|
733
|
+
delete stripped.required;
|
|
734
|
+
} else {
|
|
735
|
+
stripped.required = required;
|
|
736
|
+
}
|
|
737
|
+
return { schema: stripped, hadProject: true };
|
|
738
|
+
}
|
|
739
|
+
function mcpToAgentTool(tool, ctx) {
|
|
740
|
+
const { schema: visibleSchema, hadProject } = stripProjectFromJsonSchema(tool.inputJsonSchema);
|
|
741
|
+
const parameters = Type.Unsafe(visibleSchema);
|
|
742
|
+
const responseSchemas = responseSchemasFor(tool.openApiOperations);
|
|
743
|
+
const execute = async (_toolCallId, params) => {
|
|
744
|
+
const handlerInput = hadProject ? { ...params, project: ctx.projectName } : params;
|
|
745
|
+
const result = await runWithUsageTags(ctx.client, { mcpTool: tool.name, mcpCall: randomUUID() }, () => tool.handler(ctx.client, handlerInput));
|
|
746
|
+
return textResult(result, responseSchemas);
|
|
747
|
+
};
|
|
748
|
+
const adapted = {
|
|
749
|
+
name: tool.name,
|
|
750
|
+
label: tool.title,
|
|
751
|
+
description: tool.description,
|
|
752
|
+
parameters,
|
|
753
|
+
execute
|
|
754
|
+
};
|
|
755
|
+
if (tool.access === "read" && MEMO_STORED_READS.has(tool.name)) storedReadTools.add(adapted);
|
|
756
|
+
if (tool.access === "read" && STORED_PAGE_READS.has(tool.name)) storedPageReadTools.add(adapted);
|
|
757
|
+
return adapted;
|
|
758
|
+
}
|
|
759
|
+
var AERO_EXCLUDED_MCP_TOOLS = /* @__PURE__ */ new Set([
|
|
760
|
+
// Reloading install-wide credentials remains an explicit operator action.
|
|
761
|
+
CanonryMcpToolNames.canonry_providers_reload,
|
|
762
|
+
// Aero reads stored sentiment. Configuration and backfill submission can
|
|
763
|
+
// start paid classifier work and remain operator actions.
|
|
764
|
+
"canonry_sentiment_configure",
|
|
765
|
+
"canonry_sentiment_backfill",
|
|
766
|
+
// Applying answer-derived competitor names changes the measured competitor
|
|
767
|
+
// identity and restates stored history. Aero may preview detection
|
|
768
|
+
// (`canonry_competitors_auto_aliases_detect`); applying stays an operator action.
|
|
769
|
+
// The project writes that set the mode refuse a change instead; see
|
|
770
|
+
// `refuseCompetitorAutoAliasModeChange`.
|
|
771
|
+
CanonryMcpToolNames.canonry_competitors_auto_aliases_apply,
|
|
772
|
+
CanonryMcpToolNames.canonry_agent_clear,
|
|
773
|
+
CanonryMcpToolNames.canonry_agent_conversations_new,
|
|
774
|
+
CanonryMcpToolNames.canonry_agent_conversations_resume,
|
|
775
|
+
CanonryMcpToolNames.canonry_agent_conversations_delete,
|
|
776
|
+
CanonryMcpToolNames.canonry_results_clear
|
|
777
|
+
]);
|
|
778
|
+
var AERO_MANAGED_SWEEP_MCP_TOOLS = /* @__PURE__ */ new Set([
|
|
779
|
+
CanonryMcpToolNames.canonry_run_trigger,
|
|
780
|
+
CanonryMcpToolNames.canonry_run_fill,
|
|
781
|
+
CanonryMcpToolNames.canonry_schedule_set,
|
|
782
|
+
CanonryMcpToolNames.canonry_schedule_delete,
|
|
783
|
+
CanonryMcpToolNames.canonry_apply_config
|
|
784
|
+
]);
|
|
785
|
+
var MANAGED_SWEEP_CANCEL_REFUSAL = "This install manages answer-visibility sweeps, so Aero cannot cancel one. Ask the operator to cancel it.";
|
|
786
|
+
function refuseManagedSweepCancel(tool, ctx) {
|
|
787
|
+
const cancel = tool.execute;
|
|
788
|
+
return {
|
|
789
|
+
...tool,
|
|
790
|
+
execute: async (toolCallId, params, ...rest) => {
|
|
791
|
+
const runId = params.runId;
|
|
792
|
+
if (typeof runId === "string") {
|
|
793
|
+
const run = await ctx.client.getRun(runId);
|
|
794
|
+
if (run.kind === RunKinds["answer-visibility"]) throw new Error(MANAGED_SWEEP_CANCEL_REFUSAL);
|
|
795
|
+
}
|
|
796
|
+
return cancel(toolCallId, params, ...rest);
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
}
|
|
800
|
+
var COMPETITOR_AUTO_ALIAS_MODE_REFUSAL = "Aero cannot change a project's competitorAutoAliases mode. Omit competitorAutoAliases to keep the stored mode, or ask the operator to change it.";
|
|
801
|
+
var COMPETITOR_AUTO_ALIAS_MODE_WRITES = /* @__PURE__ */ new Set([
|
|
802
|
+
CanonryMcpToolNames.canonry_project_upsert,
|
|
803
|
+
CanonryMcpToolNames.canonry_project_update,
|
|
804
|
+
CanonryMcpToolNames.canonry_apply_config
|
|
805
|
+
]);
|
|
806
|
+
function requestedCompetitorAutoAliasMode(toolName, params, ctx) {
|
|
807
|
+
if (!isRecord2(params)) return { project: void 0, mode: void 0 };
|
|
808
|
+
if (toolName === CanonryMcpToolNames.canonry_project_upsert) {
|
|
809
|
+
const request = isRecord2(params.request) ? params.request : {};
|
|
810
|
+
return { project: ctx.projectName, mode: request.competitorAutoAliases };
|
|
811
|
+
}
|
|
812
|
+
if (toolName === CanonryMcpToolNames.canonry_project_update) {
|
|
813
|
+
const request = isRecord2(params.request) ? params.request : {};
|
|
814
|
+
return { project: params.project, mode: request.competitorAutoAliases };
|
|
815
|
+
}
|
|
816
|
+
const config = isRecord2(params.config) ? params.config : {};
|
|
817
|
+
const metadata = isRecord2(config.metadata) ? config.metadata : {};
|
|
818
|
+
const spec = isRecord2(config.spec) ? config.spec : {};
|
|
819
|
+
return { project: metadata.name, mode: spec.competitorAutoAliases };
|
|
820
|
+
}
|
|
821
|
+
async function storedCompetitorAutoAliasMode(client, project) {
|
|
822
|
+
if (typeof project !== "string") return DEFAULT_COMPETITOR_AUTO_ALIAS_MODE;
|
|
823
|
+
try {
|
|
824
|
+
return (await client.getProject(project)).competitorAutoAliases ?? DEFAULT_COMPETITOR_AUTO_ALIAS_MODE;
|
|
825
|
+
} catch (err) {
|
|
826
|
+
if (err instanceof CliError && err.code === "NOT_FOUND") return DEFAULT_COMPETITOR_AUTO_ALIAS_MODE;
|
|
827
|
+
throw err;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
function refuseCompetitorAutoAliasModeChange(tool, ctx) {
|
|
831
|
+
const write = tool.execute;
|
|
832
|
+
return {
|
|
833
|
+
...tool,
|
|
834
|
+
execute: async (toolCallId, params, ...rest) => {
|
|
835
|
+
const { project, mode } = requestedCompetitorAutoAliasMode(tool.name, params, ctx);
|
|
836
|
+
if (mode !== void 0 && mode !== await storedCompetitorAutoAliasMode(ctx.client, project)) {
|
|
837
|
+
throw new Error(COMPETITOR_AUTO_ALIAS_MODE_REFUSAL);
|
|
838
|
+
}
|
|
839
|
+
return write(toolCallId, params, ...rest);
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
var COMPETITOR_BULK_ADD_REFUSAL = "Aero cannot acknowledge measured bulk competitor growth. Review the stored evidence and acknowledge this operator action explicitly.";
|
|
844
|
+
function refuseCompetitorBulkAddAcknowledgement(tool) {
|
|
845
|
+
const write = tool.execute;
|
|
846
|
+
return {
|
|
847
|
+
...tool,
|
|
848
|
+
execute: async (toolCallId, params, ...rest) => {
|
|
849
|
+
const input = typeof params === "object" && params !== null ? params : void 0;
|
|
850
|
+
const request = typeof input?.request === "object" && input.request !== null ? input.request : void 0;
|
|
851
|
+
if (request?.acknowledgeBulkAdd === true) throw new Error(COMPETITOR_BULK_ADD_REFUSAL);
|
|
852
|
+
return write(toolCallId, params, ...rest);
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function buildMcpAgentTools(registry, ctx, opts = {}) {
|
|
857
|
+
return registry.filter((tool) => !AERO_EXCLUDED_MCP_TOOLS.has(tool.name)).filter((tool) => opts.includeNames ? opts.includeNames.has(tool.name) : true).filter((tool) => opts.readOnly ? tool.access === "read" : true).filter((tool) => opts.managedSweeps ? !AERO_MANAGED_SWEEP_MCP_TOOLS.has(tool.name) : true).map((tool) => {
|
|
858
|
+
const agentTool = mcpToAgentTool(tool, ctx);
|
|
859
|
+
if (COMPETITOR_AUTO_ALIAS_MODE_WRITES.has(tool.name)) return refuseCompetitorAutoAliasModeChange(agentTool, ctx);
|
|
860
|
+
if (tool.name === "canonry_competitors_add") return refuseCompetitorBulkAddAcknowledgement(agentTool);
|
|
861
|
+
return opts.managedSweeps && tool.name === CanonryMcpToolNames.canonry_run_cancel ? refuseManagedSweepCancel(agentTool, ctx) : agentTool;
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// src/agent/tools.ts
|
|
866
|
+
var AeroToolScopes = Object.freeze({
|
|
867
|
+
all: "all",
|
|
868
|
+
readOnly: "read-only"
|
|
869
|
+
});
|
|
870
|
+
var AERO_TOOL_SCOPES = [
|
|
871
|
+
AeroToolScopes.all,
|
|
872
|
+
AeroToolScopes.readOnly
|
|
873
|
+
];
|
|
874
|
+
var AeroToolProfiles = Object.freeze({
|
|
875
|
+
default: "default",
|
|
876
|
+
adsOperator: "ads-operator"
|
|
877
|
+
});
|
|
878
|
+
var AERO_TOOL_PROFILES = [
|
|
879
|
+
AeroToolProfiles.default,
|
|
880
|
+
AeroToolProfiles.adsOperator
|
|
881
|
+
];
|
|
882
|
+
function isAeroToolProfile(value) {
|
|
883
|
+
return value !== void 0 && AERO_TOOL_PROFILES.includes(value);
|
|
884
|
+
}
|
|
885
|
+
var AeroAgentToolNames = Object.freeze({
|
|
886
|
+
adsOperatorContext: "canonry_ads_operator_context"
|
|
887
|
+
});
|
|
888
|
+
var AERO_ADS_OPERATOR_CONTEXT_TOOL_NAME = AeroAgentToolNames.adsOperatorContext;
|
|
889
|
+
var AERO_ADS_OPERATOR_MCP_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
890
|
+
CanonryMcpToolNames.canonry_project_get,
|
|
891
|
+
CanonryMcpToolNames.canonry_project_overview,
|
|
892
|
+
CanonryMcpToolNames.canonry_search,
|
|
893
|
+
CanonryMcpToolNames.canonry_doctor,
|
|
894
|
+
CanonryMcpToolNames.canonry_analytics_metrics,
|
|
895
|
+
CanonryMcpToolNames.canonry_analytics_sources,
|
|
896
|
+
CanonryMcpToolNames.canonry_runs_list,
|
|
897
|
+
CanonryMcpToolNames.canonry_runs_latest,
|
|
898
|
+
CanonryMcpToolNames.canonry_run_get,
|
|
899
|
+
CanonryMcpToolNames.canonry_insights_list,
|
|
900
|
+
CanonryMcpToolNames.canonry_insight_get,
|
|
901
|
+
CanonryMcpToolNames.canonry_health_latest,
|
|
902
|
+
CanonryMcpToolNames.canonry_queries_list,
|
|
903
|
+
CanonryMcpToolNames.canonry_competitors_list,
|
|
904
|
+
CanonryMcpToolNames.canonry_schedule_get,
|
|
905
|
+
CanonryMcpToolNames.canonry_memory_list,
|
|
906
|
+
CanonryMcpToolNames.canonry_memory_set,
|
|
907
|
+
CanonryMcpToolNames.canonry_memory_forget,
|
|
908
|
+
CanonryMcpToolNames.canonry_run_trigger,
|
|
909
|
+
CanonryMcpToolNames.canonry_ads_status,
|
|
910
|
+
CanonryMcpToolNames.canonry_ads_account,
|
|
911
|
+
CanonryMcpToolNames.canonry_ads_geo_search,
|
|
912
|
+
CanonryMcpToolNames.canonry_ads_conversion_pixels,
|
|
913
|
+
CanonryMcpToolNames.canonry_ads_conversion_event_settings,
|
|
914
|
+
CanonryMcpToolNames.canonry_ads_campaigns,
|
|
915
|
+
CanonryMcpToolNames.canonry_ads_insights,
|
|
916
|
+
CanonryMcpToolNames.canonry_ads_summary,
|
|
917
|
+
CanonryMcpToolNames.canonry_ads_delivery_diagnostics,
|
|
918
|
+
CanonryMcpToolNames.canonry_ads_live_delivery,
|
|
919
|
+
CanonryMcpToolNames.canonry_ads_operations_unresolved,
|
|
920
|
+
CanonryMcpToolNames.canonry_ads_operation_get,
|
|
921
|
+
CanonryMcpToolNames.canonry_ads_operation_reconcile,
|
|
922
|
+
CanonryMcpToolNames.canonry_ads_operation_resume_activation,
|
|
923
|
+
CanonryMcpToolNames.canonry_ads_image_upload,
|
|
924
|
+
CanonryMcpToolNames.canonry_ads_campaign_create,
|
|
925
|
+
CanonryMcpToolNames.canonry_ads_campaign_update,
|
|
926
|
+
CanonryMcpToolNames.canonry_ads_campaign_pause,
|
|
927
|
+
CanonryMcpToolNames.canonry_ads_campaign_activate_tree,
|
|
928
|
+
CanonryMcpToolNames.canonry_ads_ad_group_create,
|
|
929
|
+
CanonryMcpToolNames.canonry_ads_ad_group_update,
|
|
930
|
+
CanonryMcpToolNames.canonry_ads_ad_group_pause,
|
|
931
|
+
CanonryMcpToolNames.canonry_ads_ad_create,
|
|
932
|
+
CanonryMcpToolNames.canonry_ads_ad_update,
|
|
933
|
+
CanonryMcpToolNames.canonry_ads_ad_pause,
|
|
934
|
+
CanonryMcpToolNames.canonry_ads_sync
|
|
935
|
+
]);
|
|
936
|
+
function toolResult(details) {
|
|
937
|
+
return {
|
|
938
|
+
content: [{ type: "text", text: truncateToolResult(details) }],
|
|
939
|
+
details
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
async function readSection(fn) {
|
|
943
|
+
try {
|
|
944
|
+
return { status: "ok", data: await fn() };
|
|
945
|
+
} catch (err) {
|
|
946
|
+
return {
|
|
947
|
+
status: "error",
|
|
948
|
+
error: describeError(err)
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
function clampInteger(value, fallback, min, max) {
|
|
953
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
|
|
954
|
+
return Math.max(min, Math.min(max, Math.trunc(value)));
|
|
955
|
+
}
|
|
956
|
+
function isoDateDaysAgo(days) {
|
|
957
|
+
const d = new Date(Date.now() - (days - 1) * 24 * 60 * 60 * 1e3);
|
|
958
|
+
return d.toISOString().slice(0, 10);
|
|
959
|
+
}
|
|
960
|
+
function todayIsoDate() {
|
|
961
|
+
return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
962
|
+
}
|
|
963
|
+
function compactOverview(overview) {
|
|
964
|
+
return {
|
|
965
|
+
project: overview.project,
|
|
966
|
+
contextLabel: overview.contextLabel,
|
|
967
|
+
dateRangeLabel: overview.dateRangeLabel,
|
|
968
|
+
latestRun: overview.latestRun,
|
|
969
|
+
health: overview.health,
|
|
970
|
+
scores: overview.scores,
|
|
971
|
+
queryCounts: overview.queryCounts,
|
|
972
|
+
providers: overview.providers,
|
|
973
|
+
citationMovement: overview.citationMovement,
|
|
974
|
+
mentionMovement: overview.mentionMovement,
|
|
975
|
+
movementComparison: overview.movementComparison,
|
|
976
|
+
topInsights: overview.topInsights?.slice(0, 5) ?? [],
|
|
977
|
+
attentionItems: overview.attentionItems?.slice(0, 8) ?? [],
|
|
978
|
+
competitors: overview.competitors?.slice(0, 12) ?? []
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
function compactCampaigns(response, limit) {
|
|
982
|
+
return {
|
|
983
|
+
campaignCount: response.campaigns.length,
|
|
984
|
+
campaigns: response.campaigns.slice(0, limit).map((campaign) => ({
|
|
985
|
+
id: campaign.id,
|
|
986
|
+
name: campaign.name,
|
|
987
|
+
status: campaign.status,
|
|
988
|
+
biddingType: campaign.biddingType,
|
|
989
|
+
dailySpendLimitMicros: campaign.dailySpendLimitMicros,
|
|
990
|
+
lifetimeSpendLimitMicros: campaign.lifetimeSpendLimitMicros,
|
|
991
|
+
adGroupCount: campaign.adGroups.length,
|
|
992
|
+
adGroups: campaign.adGroups.slice(0, 8).map((group) => ({
|
|
993
|
+
id: group.id,
|
|
994
|
+
name: group.name,
|
|
995
|
+
description: group.description,
|
|
996
|
+
status: group.status,
|
|
997
|
+
billingEventType: group.billingEventType,
|
|
998
|
+
maxBidMicros: group.maxBidMicros,
|
|
999
|
+
contextHintCount: group.contextHints.length,
|
|
1000
|
+
contextHints: group.contextHints.slice(0, 3),
|
|
1001
|
+
adCount: group.ads.length,
|
|
1002
|
+
ads: group.ads.slice(0, 4).map((ad) => ({
|
|
1003
|
+
id: ad.id,
|
|
1004
|
+
name: ad.name,
|
|
1005
|
+
status: ad.status,
|
|
1006
|
+
reviewStatus: ad.reviewStatus,
|
|
1007
|
+
upstreamUpdatedAt: ad.upstreamUpdatedAt,
|
|
1008
|
+
syncedAt: ad.syncedAt,
|
|
1009
|
+
creative: ad.creative ? {
|
|
1010
|
+
type: ad.creative.type,
|
|
1011
|
+
title: ad.creative.title,
|
|
1012
|
+
body: ad.creative.body,
|
|
1013
|
+
targetUrl: ad.creative.targetUrl,
|
|
1014
|
+
fileId: ad.creative.fileId
|
|
1015
|
+
} : ad.creative
|
|
1016
|
+
})),
|
|
1017
|
+
upstreamUpdatedAt: group.upstreamUpdatedAt,
|
|
1018
|
+
syncedAt: group.syncedAt
|
|
1019
|
+
})),
|
|
1020
|
+
description: campaign.description,
|
|
1021
|
+
startTime: campaign.startTime,
|
|
1022
|
+
endTime: campaign.endTime,
|
|
1023
|
+
locationIds: campaign.locationIds ?? [],
|
|
1024
|
+
upstreamUpdatedAt: campaign.upstreamUpdatedAt,
|
|
1025
|
+
syncedAt: campaign.syncedAt
|
|
1026
|
+
}))
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
function compactInsights(response, rowLimit) {
|
|
1030
|
+
return {
|
|
1031
|
+
currencyCode: response.currencyCode,
|
|
1032
|
+
rowCount: response.rows.length,
|
|
1033
|
+
rows: response.rows.slice(-rowLimit)
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
function buildAdsOperatorContextTool(ctx) {
|
|
1037
|
+
return {
|
|
1038
|
+
name: AERO_ADS_OPERATOR_CONTEXT_TOOL_NAME,
|
|
1039
|
+
label: "Get ads operator context",
|
|
1040
|
+
description: "One-call Aero context pack for ads operations. Reads the project overview, stored ads delivery diagnostics, ads connection, paid summary, bounded campaign snapshots, recent paid rollups, ads doctor checks, and recent Aero memory. Use before diagnosing ChatGPT ads performance or planning the next operator action.",
|
|
1041
|
+
parameters: Type2.Object({
|
|
1042
|
+
windowDays: Type2.Optional(Type2.Integer({
|
|
1043
|
+
minimum: 1,
|
|
1044
|
+
maximum: 90,
|
|
1045
|
+
description: "Lookback window for paid rollup rows. Default 30 days."
|
|
1046
|
+
})),
|
|
1047
|
+
campaignLimit: Type2.Optional(Type2.Integer({
|
|
1048
|
+
minimum: 1,
|
|
1049
|
+
maximum: 25,
|
|
1050
|
+
description: "Max campaign snapshots to include. Default 8."
|
|
1051
|
+
})),
|
|
1052
|
+
insightRowLimit: Type2.Optional(Type2.Integer({
|
|
1053
|
+
minimum: 1,
|
|
1054
|
+
maximum: 100,
|
|
1055
|
+
description: "Max paid rollup rows to include per level. Default 40."
|
|
1056
|
+
}))
|
|
1057
|
+
}),
|
|
1058
|
+
execute: async (_toolCallId, rawParams) => {
|
|
1059
|
+
const params = rawParams;
|
|
1060
|
+
const windowDays = clampInteger(params.windowDays, 30, 1, 90);
|
|
1061
|
+
const campaignLimit = clampInteger(params.campaignLimit, 8, 1, 25);
|
|
1062
|
+
const insightRowLimit = clampInteger(params.insightRowLimit, 40, 1, 100);
|
|
1063
|
+
const from = isoDateDaysAgo(windowDays);
|
|
1064
|
+
const to = todayIsoDate();
|
|
1065
|
+
const [
|
|
1066
|
+
overview,
|
|
1067
|
+
adsStatus,
|
|
1068
|
+
deliveryDiagnostics,
|
|
1069
|
+
adsSummary,
|
|
1070
|
+
campaigns,
|
|
1071
|
+
campaignInsights,
|
|
1072
|
+
adGroupInsights,
|
|
1073
|
+
doctor,
|
|
1074
|
+
memory
|
|
1075
|
+
] = await Promise.all([
|
|
1076
|
+
readSection(() => ctx.client.getProjectOverview(ctx.projectName)),
|
|
1077
|
+
readSection(() => ctx.client.getAdsStatus(ctx.projectName)),
|
|
1078
|
+
readSection(() => ctx.client.getAdsDeliveryDiagnostics(ctx.projectName)),
|
|
1079
|
+
readSection(() => ctx.client.getAdsSummary(ctx.projectName)),
|
|
1080
|
+
readSection(async () => compactCampaigns(await ctx.client.getAdsCampaigns(ctx.projectName), campaignLimit)),
|
|
1081
|
+
readSection(
|
|
1082
|
+
async () => compactInsights(
|
|
1083
|
+
await ctx.client.getAdsInsights(ctx.projectName, { level: "campaign", from, to }),
|
|
1084
|
+
insightRowLimit
|
|
1085
|
+
)
|
|
1086
|
+
),
|
|
1087
|
+
readSection(
|
|
1088
|
+
async () => compactInsights(
|
|
1089
|
+
await ctx.client.getAdsInsights(ctx.projectName, { level: "ad_group", from, to }),
|
|
1090
|
+
insightRowLimit
|
|
1091
|
+
)
|
|
1092
|
+
),
|
|
1093
|
+
readSection(() => ctx.client.runDoctor({ project: ctx.projectName, checkIds: ["ads.*"] })),
|
|
1094
|
+
readSection(async () => {
|
|
1095
|
+
const result = await ctx.client.listAgentMemory(ctx.projectName);
|
|
1096
|
+
return { entries: result.entries.slice(0, 10) };
|
|
1097
|
+
})
|
|
1098
|
+
]);
|
|
1099
|
+
return toolResult({
|
|
1100
|
+
project: ctx.projectName,
|
|
1101
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1102
|
+
window: { days: windowDays, from, to },
|
|
1103
|
+
overview: overview.status === "ok" && overview.data ? { status: "ok", data: compactOverview(overview.data) } : overview,
|
|
1104
|
+
ads: {
|
|
1105
|
+
status: adsStatus,
|
|
1106
|
+
deliveryDiagnostics,
|
|
1107
|
+
summary: adsSummary,
|
|
1108
|
+
campaigns,
|
|
1109
|
+
insights: {
|
|
1110
|
+
campaign: campaignInsights,
|
|
1111
|
+
adGroup: adGroupInsights
|
|
1112
|
+
}
|
|
1113
|
+
},
|
|
1114
|
+
doctor,
|
|
1115
|
+
memory
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
function buildReadTools(ctx, opts = {}) {
|
|
1121
|
+
return buildMcpAgentTools(canonryMcpTools, ctx, { readOnly: true, managedSweeps: opts.managedSweeps });
|
|
1122
|
+
}
|
|
1123
|
+
function buildAllTools(ctx, opts = {}) {
|
|
1124
|
+
return buildMcpAgentTools(canonryMcpTools, ctx, { managedSweeps: opts.managedSweeps });
|
|
1125
|
+
}
|
|
1126
|
+
function buildAdsOperatorTools(ctx, opts = {}) {
|
|
1127
|
+
const mcpTools = buildMcpAgentTools(canonryMcpTools, ctx, {
|
|
1128
|
+
readOnly: opts.scope === AeroToolScopes.readOnly,
|
|
1129
|
+
includeNames: AERO_ADS_OPERATOR_MCP_TOOL_NAMES,
|
|
1130
|
+
managedSweeps: opts.managedSweeps
|
|
1131
|
+
});
|
|
1132
|
+
return [buildAdsOperatorContextTool(ctx), ...mcpTools];
|
|
1133
|
+
}
|
|
1134
|
+
function buildAeroStateTools(ctx, opts = {}) {
|
|
1135
|
+
const scope = opts.scope ?? AeroToolScopes.all;
|
|
1136
|
+
const profile = opts.profile ?? AeroToolProfiles.default;
|
|
1137
|
+
const managedSweeps = opts.managedSweeps;
|
|
1138
|
+
if (profile === AeroToolProfiles.adsOperator) {
|
|
1139
|
+
return buildAdsOperatorTools(ctx, { scope, managedSweeps });
|
|
1140
|
+
}
|
|
1141
|
+
return scope === AeroToolScopes.readOnly ? buildReadTools(ctx, { managedSweeps }) : buildAllTools(ctx, { managedSweeps });
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
export {
|
|
1145
|
+
truncateToolResult,
|
|
1146
|
+
isStoredReadTool,
|
|
1147
|
+
isStoredPageReadTool,
|
|
1148
|
+
AeroToolScopes,
|
|
1149
|
+
AERO_TOOL_SCOPES,
|
|
1150
|
+
AeroToolProfiles,
|
|
1151
|
+
AERO_TOOL_PROFILES,
|
|
1152
|
+
isAeroToolProfile,
|
|
1153
|
+
AeroAgentToolNames,
|
|
1154
|
+
AERO_ADS_OPERATOR_CONTEXT_TOOL_NAME,
|
|
1155
|
+
AERO_ADS_OPERATOR_MCP_TOOL_NAMES,
|
|
1156
|
+
buildReadTools,
|
|
1157
|
+
buildAllTools,
|
|
1158
|
+
buildAdsOperatorTools,
|
|
1159
|
+
buildAeroStateTools
|
|
1160
|
+
};
|