@sentientui/mcp 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -421,7 +421,7 @@ function registerProjectTools(server, client) {
421
421
  "get_project_stats",
422
422
  {
423
423
  title: "Project health stats",
424
- description: "Get ingestion health for a project: status, events in the last 24 hours, the People count for the same window (visitors who ran the page, interacted and passed the bot check), how many visitors are still being analysed, how many are automated, the time of the last event, and the all-time count of calls to the SentientUI agent API (/v1/agent) \u2014 NOT MCP tool calls.",
424
+ description: `Get ingestion health for a project: status, events in the last 24 hours, the People count for the same window (visitors who ran the page, interacted and passed the bot check), how many visitors are still being analysed, how many are automated, the time of the last event, and the all-time count of calls to the SentientUI agent API (/v1/agent) \u2014 NOT MCP tool calls. Also lists domains the snippet keeps running on that are NOT allowed, so their visits are turned away (the usual answer to "why isn't my site tracking?"; fix with add_origin). Use this first when a site reports no data.`,
425
425
  inputSchema: { projectId: projectIdSchema },
426
426
  outputSchema: {
427
427
  status: import_v32.z.string().describe("Overall project health status"),
@@ -432,11 +432,23 @@ function registerProjectTools(server, client) {
432
432
  people: import_v32.z.number().nullable().describe("People in the last 24 hours: visitors who ran the page, interacted and passed the bot check; null when the API predates the traffic classification"),
433
433
  beingAnalysed: import_v32.z.number().nullable().describe("Visitors still being analysed \u2014 usually settled within 3 hours; null on an older API"),
434
434
  automated: import_v32.z.number().nullable().describe("Automated visitors: AI assistants, search & AI crawlers and other automated; null on an older API"),
435
+ internal: import_v32.z.number().nullable().describe("Visitors the project marked internal (Your team / test sites): never People, never counted; null when the API sends no such group"),
435
436
  // Was "Total agent (MCP/API) calls" — but the count comes from
436
437
  // agent_events, which only the /v1/agent endpoint writes. MCP tool calls
437
438
  // are never in it, so an agent read its own activity as missing.
438
439
  agentCalls: import_v32.z.number().describe("All-time calls to the /v1/agent agent API (not MCP tool calls)"),
439
- lastEventAt: import_v32.z.string().nullable().describe("ISO timestamp of the last event, or null")
440
+ lastEventAt: import_v32.z.string().nullable().describe("ISO timestamp of the last event, or null"),
441
+ rejectedOrigins: import_v32.z.array(
442
+ import_v32.z.object({
443
+ origin: import_v32.z.string(),
444
+ minutesWithTraffic: import_v32.z.number().describe("Minutes in which visits were turned away \u2014 recorded at most once a minute, NOT a request count"),
445
+ firstSeenAt: import_v32.z.string(),
446
+ lastSeenAt: import_v32.z.string(),
447
+ message: import_v32.z.string()
448
+ })
449
+ ).describe(
450
+ "Sustained turned-away domains: at least 50 minutes with traffic over at least 2 days, previews, translate proxies and trailing-dot variants excluded. Empty on an older API."
451
+ )
440
452
  },
441
453
  annotations: {
442
454
  readOnlyHint: true,
@@ -445,20 +457,38 @@ function registerProjectTools(server, client) {
445
457
  }
446
458
  },
447
459
  withApiErrorGuidance(async ({ projectId }) => {
448
- var _a2, _b, _c, _d, _e, _f, _g;
460
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j;
449
461
  const id = encodeURIComponent(projectId);
450
462
  const stats = await client.get(`/projects/${id}/health`);
451
- const peopleCount = (_b = stats.people) != null ? _b : (_a2 = stats.traffic) == null ? void 0 : _a2.people;
463
+ const rejectedOrigins = ((_a2 = stats.rejectedOrigins) != null ? _a2 : []).map((r) => ({
464
+ origin: r.origin,
465
+ minutesWithTraffic: r.count,
466
+ firstSeenAt: r.firstSeenAt,
467
+ lastSeenAt: r.lastSeenAt,
468
+ message: r.message
469
+ }));
470
+ const peopleCount = (_c = stats.people) != null ? _c : (_b = stats.traffic) == null ? void 0 : _b.people;
452
471
  const classified = peopleCount !== void 0;
453
472
  const people = classified ? peopleCount : null;
454
- const beingAnalysed = classified ? (_d = (_c = stats.traffic) == null ? void 0 : _c.beingAnalysed) != null ? _d : 0 : null;
455
- const automated = classified ? (_f = (_e = stats.traffic) == null ? void 0 : _e.automated) != null ? _f : 0 : null;
473
+ const beingAnalysed = classified ? (_e = (_d = stats.traffic) == null ? void 0 : _d.beingAnalysed) != null ? _e : 0 : null;
474
+ const automated = classified ? (_g = (_f = stats.traffic) == null ? void 0 : _f.automated) != null ? _g : 0 : null;
475
+ const internalGroup = (_i = (_h = stats.traffic) == null ? void 0 : _h.groups) == null ? void 0 : _i.find((g) => g.group === "internal");
476
+ const internal = internalGroup ? internalGroup.count : null;
456
477
  const text2 = [
457
478
  `Status: ${stats.status}`,
458
479
  `Events (24h): ${stats.events24h}`,
459
- ...classified ? [`People (24h): ${people}`, `Being analysed: ${beingAnalysed}`, `Automated: ${automated}`] : [`Sessions (24h): ${stats.sessions24h}`],
480
+ ...classified ? [
481
+ `People (24h): ${people}`,
482
+ `Being analysed: ${beingAnalysed}`,
483
+ `Automated: ${automated}`,
484
+ ...internal !== null ? [`Your team / test sites (marked internal, not counted): ${internal}`] : []
485
+ ] : [`Sessions (24h): ${stats.sessions24h}`],
460
486
  `Agent API calls (/v1/agent, all-time): ${stats.agentCalls}`,
461
- `Last event: ${(_g = stats.lastEventAt) != null ? _g : "never"}`
487
+ `Last event: ${(_j = stats.lastEventAt) != null ? _j : "never"}`,
488
+ ...rejectedOrigins.length ? [
489
+ "Domains turned away (not on the allowed list \u2014 fix with add_origin if they are your sites):",
490
+ ...rejectedOrigins.map((r) => `- ${r.message}`)
491
+ ] : []
462
492
  ].join("\n");
463
493
  return {
464
494
  content: [{ type: "text", text: text2 }],
@@ -469,8 +499,10 @@ function registerProjectTools(server, client) {
469
499
  people,
470
500
  beingAnalysed,
471
501
  automated,
502
+ internal,
472
503
  agentCalls: stats.agentCalls,
473
- lastEventAt: stats.lastEventAt
504
+ lastEventAt: stats.lastEventAt,
505
+ rejectedOrigins
474
506
  }
475
507
  };
476
508
  })
@@ -599,16 +631,26 @@ var BOOTSTRAP_JS = `
599
631
  var RENDER_JS = {
600
632
  "persona-breakdown": `
601
633
  window.__render = function(data){
602
- var clusters = (data && data.clusters) || [];
603
- var total = (data && data.totalSessions) || 0;
604
- el('sub').textContent = total + ' total sessions across ' + clusters.length + ' persona' + (clusters.length === 1 ? '' : 's');
605
- if (!clusters.length) { showEmpty('No persona clusters yet \u2014 more visitor data is needed.'); return; }
606
- var sorted = clusters.slice().sort(function(a,b){ return (b.sharePct||0) - (a.sharePct||0); });
607
- el('viz').innerHTML = sorted.map(function(c){
608
- var rel = Math.round((c.reliability || 0) * 100);
609
- return barRow(c.label, pct1(c.sharePct), c.sharePct,
610
- c.sessionCount + ' sessions \xB7 reliability ' + rel + '%');
634
+ // Served-as audiences (the Matrix share), then behaviour groups \u2014 kept
635
+ // apart: a behaviour group is visitors who behaved alike, never an
636
+ // audience, and it is never drawn under an audience's name.
637
+ var personas = (data && data.personas) || [];
638
+ var groups = (data && data.behaviourGroups) || [];
639
+ var total = (data && data.totalPeople) || 0;
640
+ el('sub').textContent = total + ' people by the audience they were served as, last ' + ((data && data.windowDays) || 30) + ' days';
641
+ if (!total && !groups.length) { showEmpty('No served visitors yet \u2014 nothing to break down.'); return; }
642
+ var html = personas.map(function(p){
643
+ return barRow(p.name, pct1(p.sharePct), p.sharePct, p.people + ' people');
611
644
  }).join('');
645
+ if (groups.length) {
646
+ var groupTotal = groups.reduce(function(a, g){ return a + (Number(g.people) || 0); }, 0);
647
+ html += '<p class="sub" style="margin-top:14px">Behaviour groups \u2014 visitors who behaved alike. Not audiences: nothing is shown to a group.</p>';
648
+ html += groups.map(function(g){
649
+ var share = groupTotal > 0 ? (g.people / groupTotal) * 100 : 0;
650
+ return barRow(g.name, g.people + ' people', share, g.description || '');
651
+ }).join('');
652
+ }
653
+ el('viz').innerHTML = html;
612
654
  };
613
655
  `,
614
656
  "variant-performance": `
@@ -931,7 +973,16 @@ function registerComponentTools(server, client) {
931
973
  total: import_v34.z.number().describe("Total components in the project \u2014 larger than the list when truncated"),
932
974
  truncated: import_v34.z.boolean().describe("True when the fetch cap was hit before listing every component"),
933
975
  regions: regionOutputSchema,
934
- window: windowOutputSchema
976
+ window: windowOutputSchema,
977
+ audienceNamedVersions: import_v34.z.array(
978
+ import_v34.z.object({
979
+ componentId: import_v34.z.string(),
980
+ versionKey: import_v34.z.string(),
981
+ personaKey: import_v34.z.string().describe("The declared audience the key is named after"),
982
+ pinned: import_v34.z.boolean().describe("Already pinned to that audience"),
983
+ nudge: import_v34.z.string().describe("What the dashboard says about it \u2014 quote it")
984
+ })
985
+ ).describe("Versions whose key names one of the project's declared audiences. A name targets nobody: declare the persona on the site, then pin the version. Empty on an older API")
935
986
  },
936
987
  annotations: {
937
988
  readOnlyHint: true,
@@ -940,29 +991,44 @@ function registerComponentTools(server, client) {
940
991
  }
941
992
  },
942
993
  withApiErrorGuidance(async ({ projectId, range, from, to }) => {
943
- const [componentsRes, regionsRes] = await Promise.all([
994
+ var _a2;
995
+ const [componentsRes, regionsRes, namedRes] = await Promise.all([
944
996
  settled(fetchAllComponents(client, projectId, { rangeArgs: { range, from, to } })),
945
- settled(fetchRegions(client, projectId, { range, from, to }))
997
+ settled(fetchRegions(client, projectId, { range, from, to })),
998
+ // Task 6: `variants={{ developer }}` reads as "developer copy for
999
+ // developers", and nothing told the developer a key targets nobody.
1000
+ // Additive and best-effort, like regions.
1001
+ settled(client.get(
1002
+ `/projects/${encodeURIComponent(projectId)}/audience-named-versions`
1003
+ ))
946
1004
  ]);
947
1005
  throwIfNotDegradable([componentsRes, regionsRes]);
948
1006
  if (!componentsRes.ok) throw componentsRes.error;
949
1007
  const { components, total, window, truncated } = componentsRes.value;
950
1008
  const regions = regionsRes.ok ? regionsRes.value : [];
1009
+ const audienceNamedVersions = namedRes.ok ? ((_a2 = namedRes.value.versions) != null ? _a2 : []).map((v) => ({
1010
+ componentId: v.componentId,
1011
+ versionKey: v.versionKey,
1012
+ personaKey: v.personaKey,
1013
+ pinned: v.pinned,
1014
+ nudge: v.nudge
1015
+ })) : [];
951
1016
  const structuredContent = {
952
1017
  components: components.map((c) => {
953
- var _a2;
1018
+ var _a3;
954
1019
  return {
955
1020
  componentId: c.component_id,
956
1021
  variantCount: c.variants.length,
957
1022
  impressions: c.total_impressions,
958
1023
  conversions: c.total_conversions,
959
- unconfirmedConversions: (_a2 = c.total_unconfirmed_conversions) != null ? _a2 : null
1024
+ unconfirmedConversions: (_a3 = c.total_unconfirmed_conversions) != null ? _a3 : null
960
1025
  };
961
1026
  }),
962
1027
  total,
963
1028
  truncated,
964
1029
  regions,
965
- window
1030
+ window,
1031
+ audienceNamedVersions
966
1032
  };
967
1033
  if (!components.length && !regions.length) {
968
1034
  return {
@@ -982,6 +1048,11 @@ function registerComponentTools(server, client) {
982
1048
  for (const r of regions) lines.push(regionText(r, untrusted));
983
1049
  }
984
1050
  if (!regionsRes.ok) lines.push("", "Regions could not be read just now \u2014 components served per visitor may be missing from this list.");
1051
+ const unpinned = audienceNamedVersions.filter((v) => !v.pinned);
1052
+ if (unpinned.length) {
1053
+ lines.push("", "Versions named after your audiences (a name doesn't target anyone):");
1054
+ for (const v of unpinned) lines.push(`- ${untrusted(v.componentId)} / ${untrusted(v.versionKey)}: ${v.nudge}`);
1055
+ }
985
1056
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent };
986
1057
  })
987
1058
  );
@@ -1323,27 +1394,41 @@ function registerInsightTools(server, client) {
1323
1394
 
1324
1395
  // src/tools/personas.ts
1325
1396
  var import_v36 = require("zod/v3");
1397
+ function behaviourGroupName(label) {
1398
+ if (label == null || label === "" || label === "unclustered") return "Not grouped yet";
1399
+ const m = /^behaviour-(\d{1,4})$/.exec(label);
1400
+ return m ? `Behaviour group ${Number(m[1])}` : "Behaviour group";
1401
+ }
1326
1402
  function registerPersonaTools(server, client) {
1327
1403
  server.registerTool(
1328
1404
  "get_persona_breakdown",
1329
1405
  {
1330
1406
  title: "Persona breakdown",
1331
- // Takes no range/from/to on purpose: the API computes it over every
1332
- // retained session and has no window. Saying so stops an agent from
1333
- // reading it beside a 7d get_variant_performance as the same period.
1334
- description: "Get the distribution of visitor persona clusters with session counts and reliability scores, over ALL retained human sessions (not windowed \u2014 this has no range input, unlike the conversion tools)." + UNTRUSTED_FIELDS_NOTE,
1407
+ // Counted portrait clusters by a label named after the declared
1408
+ // personas until 2026-11-04, so an agent could report "Developer: 410
1409
+ // visitors" while the Matrix showed 0% for Developer. It now reads the
1410
+ // API's served-as breakdown — the Matrix share column's own numbers.
1411
+ description: 'Visitors per audience they were SERVED as, last 30 days, People only \u2014 the same numbers as the Matrix share column (Everyone = no audience applied; a declared audience at 0 means the site never declared anyone as it). Separately, `behaviourGroups`: groups of visitors who behaved alike ("Behaviour group N" + what sets them apart). Behaviour groups are NOT audiences \u2014 nothing is shown to them; never describe one by an audience name.' + UNTRUSTED_FIELDS_NOTE,
1335
1412
  inputSchema: { projectId: projectIdSchema },
1336
1413
  _meta: uiMeta("persona-breakdown"),
1337
1414
  outputSchema: {
1338
- totalSessions: import_v36.z.number().describe("Total sessions across all clusters"),
1339
- clusters: import_v36.z.array(
1415
+ windowDays: import_v36.z.number().describe("Window in days (30)"),
1416
+ totalPeople: import_v36.z.number().describe("People with a served decision in the window \u2014 the share denominator"),
1417
+ personas: import_v36.z.array(
1418
+ import_v36.z.object({
1419
+ key: import_v36.z.string().describe("Persona key served (`unknown` = Everyone)"),
1420
+ name: import_v36.z.string().describe('Kind + name as the Matrix row reads it, e.g. "Declared: Developer"'),
1421
+ people: import_v36.z.number(),
1422
+ sharePct: import_v36.z.number().describe("Share of totalPeople (0-100) \u2014 the Matrix share")
1423
+ })
1424
+ ).describe("Everyone, then every Matrix audience row (zeros included), then any other served audience"),
1425
+ behaviourGroups: import_v36.z.array(
1340
1426
  import_v36.z.object({
1341
- label: import_v36.z.string(),
1342
- sessionCount: import_v36.z.number(),
1343
- sharePct: import_v36.z.number().describe("Share of total traffic (0-100)"),
1344
- reliability: import_v36.z.number().describe("Average cluster reliability (0-1)")
1427
+ name: import_v36.z.string().describe('"Behaviour group N" \u2014 never an audience'),
1428
+ description: import_v36.z.string().nullable(),
1429
+ people: import_v36.z.number()
1345
1430
  })
1346
- ).describe("Persona clusters (empty until enough visitor data)")
1431
+ ).describe("Visitors who behaved alike. Not audiences: nothing is served or targeted by them")
1347
1432
  },
1348
1433
  annotations: {
1349
1434
  readOnlyHint: true,
@@ -1353,33 +1438,21 @@ function registerPersonaTools(server, client) {
1353
1438
  },
1354
1439
  withApiErrorGuidance(async ({ projectId }) => {
1355
1440
  const id = encodeURIComponent(projectId);
1356
- const data = await client.get(`/projects/${id}/portraits`);
1441
+ const data = await client.get(`/projects/${id}/persona-breakdown`);
1357
1442
  const structuredContent = {
1358
- totalSessions: data.totalSessions,
1359
- clusters: data.clusters.map((c) => ({
1360
- label: c.label,
1361
- sessionCount: c.sessionCount,
1362
- sharePct: data.totalSessions > 0 ? c.sessionCount / data.totalSessions * 100 : 0,
1363
- reliability: c.avgReliability
1364
- }))
1443
+ windowDays: data.windowDays,
1444
+ totalPeople: data.totalPeople,
1445
+ personas: data.personas.map((p) => ({ key: p.key, name: p.name, people: p.people, sharePct: p.sharePct })),
1446
+ behaviourGroups: data.behaviourGroups.map((g) => ({ name: g.name, description: g.description, people: g.people }))
1365
1447
  };
1366
- if (!data.clusters.length) {
1367
- return {
1368
- content: [{ type: "text", text: "No persona clusters yet. More visitor data is needed." }],
1369
- structuredContent,
1370
- _meta: uiMeta("persona-breakdown")
1371
- };
1372
- }
1373
1448
  const lines = [
1374
- `Total sessions: ${data.totalSessions}`,
1449
+ `Visitors by the audience they were served as (last ${data.windowDays} days, ${data.totalPeople} people \u2014 same numbers as the Matrix share):`,
1450
+ // Audience names are customer-written — delimit them so a crafted
1451
+ // name can't pose as tool output (see untrusted()).
1452
+ ...data.totalPeople === 0 ? ["- No served decisions yet in this window."] : data.personas.map((p) => `- ${untrusted(p.name)}: ${p.people} people (${p.sharePct.toFixed(1)}%)`),
1375
1453
  "",
1376
- "Clusters:",
1377
- // Cluster labels derive from visitor behaviour — delimit them so a
1378
- // crafted label can't pose as tool output (see untrusted()).
1379
- ...data.clusters.map((c) => {
1380
- const pct3 = data.totalSessions > 0 ? c.sessionCount / data.totalSessions * 100 : 0;
1381
- return `- ${untrusted(c.label)}: ${c.sessionCount} sessions (${pct3.toFixed(1)}% of traffic, reliability ${(c.avgReliability * 100).toFixed(0)}%)`;
1382
- })
1454
+ "Behaviour groups (visitors who behaved alike \u2014 NOT audiences; nothing is shown to a group):",
1455
+ ...data.behaviourGroups.length === 0 ? ["- None yet."] : data.behaviourGroups.map((g) => `- ${g.name}: ${g.people} people${g.description ? ` \u2014 ${g.description}` : ""}`)
1383
1456
  ];
1384
1457
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent, _meta: uiMeta("persona-breakdown") };
1385
1458
  })
@@ -1809,6 +1882,12 @@ function stepChangeText(dropOffFromPrevious) {
1809
1882
  }
1810
1883
  return ` (${Math.round(dropOffFromPrevious * 100)}% drop-off from previous)`;
1811
1884
  }
1885
+ var trackingSchema = import_v39.z.enum(["recorded", "defined", "silent", "none"]).nullable().describe("What sends this step's goal: recorded (it has fired), defined (set up, nothing recorded yet, under 7 days), silent (set up 7+ days ago, never recorded), none (nothing sends it: no active definition and never fired, so this step can never fill). Null on an older API.");
1886
+ function stepSourceText(goalId, tracking, definedDaysAgo) {
1887
+ if (tracking === "none") return `Nothing sends ${untrusted(goalId)} yet`;
1888
+ if (tracking === "silent") return `${untrusted(goalId)} is set up but nothing has recorded it in ${definedDaysAgo != null ? definedDaysAgo : 7} days`;
1889
+ return null;
1890
+ }
1812
1891
  function registerFunnelTools(server, client) {
1813
1892
  server.registerTool(
1814
1893
  "list_funnels",
@@ -1828,7 +1907,9 @@ function registerFunnelTools(server, client) {
1828
1907
  import_v39.z.object({
1829
1908
  stepIndex: import_v39.z.number(),
1830
1909
  goalId: import_v39.z.string(),
1831
- weight: import_v39.z.number().nullable().describe("Manual optimizer credit for reaching this step (null = automatic end-weighted)")
1910
+ weight: import_v39.z.number().nullable().describe("Manual optimizer credit for reaching this step (null = automatic end-weighted)"),
1911
+ tracking: trackingSchema,
1912
+ definedDaysAgo: import_v39.z.number().nullable().describe("Days since an unfired goal was set up (null once it fires)")
1832
1913
  })
1833
1914
  ).describe("Ordered steps"),
1834
1915
  components: import_v39.z.array(import_v39.z.object({ componentId: import_v39.z.string(), stepIndex: import_v39.z.number().nullable() })).describe("Components serving this funnel (stepIndex null = whole funnel)")
@@ -1849,11 +1930,16 @@ function registerFunnelTools(server, client) {
1849
1930
  windowDays: f.window_days,
1850
1931
  source: f.source,
1851
1932
  // NUMERIC arrives serialized as a string; coerce.
1852
- steps: f.steps.map((s) => ({
1853
- stepIndex: s.step_index,
1854
- goalId: s.goal_id,
1855
- weight: s.weight == null ? null : Number(s.weight)
1856
- })),
1933
+ steps: f.steps.map((s) => {
1934
+ var _a3, _b;
1935
+ return {
1936
+ stepIndex: s.step_index,
1937
+ goalId: s.goal_id,
1938
+ weight: s.weight == null ? null : Number(s.weight),
1939
+ tracking: (_a3 = s.tracking) != null ? _a3 : null,
1940
+ definedDaysAgo: (_b = s.defined_days_ago) != null ? _b : null
1941
+ };
1942
+ }),
1857
1943
  components: f.components.map((c) => {
1858
1944
  var _a3;
1859
1945
  return { componentId: c.component_id, stepIndex: (_a3 = c.step_index) != null ? _a3 : null };
@@ -1869,10 +1955,20 @@ function registerFunnelTools(server, client) {
1869
1955
  structuredContent
1870
1956
  };
1871
1957
  }
1872
- const lines = structuredContent.funnels.map(
1873
- (f) => `${untrusted(f.funnelId)} (${f.status}) \u2014 ${untrusted(f.displayName)}: ${f.steps.map((s) => untrusted(s.goalId)).join(" \u2192 ")}`
1874
- );
1958
+ const lines = [];
1959
+ let anyUnsourced = false;
1960
+ for (const f of structuredContent.funnels) {
1961
+ lines.push(`${untrusted(f.funnelId)} (${f.status}) \u2014 ${untrusted(f.displayName)}: ${f.steps.map((s) => untrusted(s.goalId)).join(" \u2192 ")}`);
1962
+ for (const s of f.steps) {
1963
+ const note = stepSourceText(s.goalId, s.tracking, s.definedDaysAgo);
1964
+ if (note) lines.push(` step ${s.stepIndex + 1}: ${note}`);
1965
+ if (s.tracking === "none") anyUnsourced = true;
1966
+ }
1967
+ }
1875
1968
  lines.push("", 'Reference a funnelId verbatim from code: <Adaptive funnel="<funnelId>">. Use get_funnel_report for drop-off numbers.');
1969
+ if (anyUnsourced) {
1970
+ lines.push("A step nothing sends can never fill: get_funnel_report gives the exact code to send it (useGoal in the browser, trackServerGoal on the server), or define it as a page visit with define_goal.");
1971
+ }
1876
1972
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent };
1877
1973
  })
1878
1974
  );
@@ -1896,7 +1992,14 @@ function registerFunnelTools(server, client) {
1896
1992
  reached: import_v39.z.number().describe("Distinct People reaching this step in-window"),
1897
1993
  unconfirmedReached: import_v39.z.number().nullable().describe("Visitors we couldn't confirm as people who reached this step (the API's own remainder; not in reached or any drop-off); null on an older API"),
1898
1994
  dropOffFromPrevious: import_v39.z.number().nullable().describe("1 - reached/previousReached (null on the first step)"),
1899
- neverFired: import_v39.z.boolean().describe("True when the step goal has never been recorded anywhere \u2014 likely a typo"),
1995
+ neverFired: import_v39.z.boolean().describe("Legacy: no definition in any status and never recorded. Prefer tracking"),
1996
+ tracking: trackingSchema,
1997
+ definedDaysAgo: import_v39.z.number().nullable().describe("Days since an unfired goal was set up (null once it fires)"),
1998
+ fromCode: import_v39.z.object({
1999
+ client: import_v39.z.string().describe("Browser code: useGoal from @sentientui/react"),
2000
+ server: import_v39.z.string().describe("Server code: trackServerGoal from @sentientui/react/server"),
2001
+ serverCall: import_v39.z.string()
2002
+ }).nullable().describe("Exact code that sends this step's goal, present until it first fires. Repeat it verbatim."),
1900
2003
  variants: import_v39.z.array(import_v39.z.object({
1901
2004
  componentId: import_v39.z.string(),
1902
2005
  variantId: import_v39.z.string(),
@@ -1915,13 +2018,19 @@ function registerFunnelTools(server, client) {
1915
2018
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1916
2019
  },
1917
2020
  withApiErrorGuidance(async ({ projectId, funnelId }) => {
1918
- var _a2, _b;
2021
+ var _a2, _b, _c;
1919
2022
  const data = await client.get(`/projects/${encodeURIComponent(projectId)}/funnels/${encodeURIComponent(funnelId)}/report`);
1920
2023
  const lines = [`${untrusted(data.displayName)} \u2014 last ${data.windowDays} days`];
1921
2024
  for (const s of data.steps) {
2025
+ const tracking = (_a2 = s.tracking) != null ? _a2 : s.neverFired ? "none" : null;
2026
+ const note = stepSourceText(s.goalId, tracking, s.definedDaysAgo);
1922
2027
  lines.push(
1923
- `${s.stepIndex + 1}. ${untrusted(s.displayName)}: ${s.reached} People reached` + (s.unconfirmedReached ? ` (${s.unconfirmedReached} more from visitors we couldn't confirm as people)` : "") + stepChangeText(s.dropOffFromPrevious) + (s.neverFired ? " [never recorded \u2014 check the goal name]" : "")
2028
+ `${s.stepIndex + 1}. ${untrusted(s.displayName)}: ${s.reached} People reached` + (s.unconfirmedReached ? ` (${s.unconfirmedReached} more from visitors we couldn't confirm as people)` : "") + stepChangeText(s.dropOffFromPrevious) + (note ? ` [${note}]` : "")
1924
2029
  );
2030
+ if (tracking === "none" && s.fromCode && codeSafe(s.goalId) === s.goalId) {
2031
+ lines.push(" Send it from your server:", ...s.fromCode.server.split("\n").map((l) => ` ${l}`));
2032
+ lines.push(" \u2026or from the browser:", ...s.fromCode.client.split("\n").map((l) => ` ${l}`));
2033
+ }
1925
2034
  for (const v of s.variants) {
1926
2035
  lines.push(` ${untrusted(v.componentId)}/${untrusted(v.variantId)}: ${v.reached}/${v.assigned} assigned sessions reached this step`);
1927
2036
  }
@@ -1940,11 +2049,16 @@ function registerFunnelTools(server, client) {
1940
2049
  content: [{ type: "text", text: lines.join("\n") }],
1941
2050
  // Tolerate an API deployed before strict funnels existed.
1942
2051
  structuredContent: __spreadProps(__spreadValues({}, data), {
1943
- strictOrder: (_a2 = data.strictOrder) != null ? _a2 : true,
1944
- unconfirmedRevenue: (_b = data.unconfirmedRevenue) != null ? _b : null,
2052
+ strictOrder: (_b = data.strictOrder) != null ? _b : true,
2053
+ unconfirmedRevenue: (_c = data.unconfirmedRevenue) != null ? _c : null,
1945
2054
  steps: data.steps.map((s) => {
1946
- var _a3;
1947
- return __spreadProps(__spreadValues({}, s), { unconfirmedReached: (_a3 = s.unconfirmedReached) != null ? _a3 : null });
2055
+ var _a3, _b2, _c2, _d;
2056
+ return __spreadProps(__spreadValues({}, s), {
2057
+ unconfirmedReached: (_a3 = s.unconfirmedReached) != null ? _a3 : null,
2058
+ tracking: (_b2 = s.tracking) != null ? _b2 : null,
2059
+ definedDaysAgo: (_c2 = s.definedDaysAgo) != null ? _c2 : null,
2060
+ fromCode: (_d = s.fromCode) != null ? _d : null
2061
+ });
1948
2062
  })
1949
2063
  })
1950
2064
  };
@@ -2563,10 +2677,10 @@ function registerVariantBriefTools(server, client) {
2563
2677
  lines.push("");
2564
2678
  }
2565
2679
  if (clusters.length) {
2566
- lines.push(`Audience (${totalSessions} sessions):`);
2680
+ lines.push(`Behaviour groups (visitors who behaved alike \u2014 not audiences; ${totalSessions} sessions):`);
2567
2681
  for (const c of clusters) {
2568
2682
  const share = totalSessions > 0 ? (c.sessionCount / totalSessions * 100).toFixed(0) : "0";
2569
- lines.push(`- ${untrusted(c.label)}: ${share}% of traffic, ${c.sessionCount} sessions (reliability ${(c.avgReliability * 100).toFixed(0)}%)`);
2683
+ lines.push(`- ${behaviourGroupName(c.label)}: ${share}% of traffic, ${c.sessionCount} sessions (reliability ${(c.avgReliability * 100).toFixed(0)}%)`);
2570
2684
  }
2571
2685
  lines.push("");
2572
2686
  }
@@ -2751,11 +2865,14 @@ var import_v315 = require("zod/v3");
2751
2865
  var GUIDE = `# SentientUI integration guide \u2014 the adaptive ladder
2752
2866
 
2753
2867
  SentientUI adapts a site per visitor type (personas), learning from real conversions. Each
2754
- project has its own persona vocabulary (dashboard -> Settings -> Personas), and it starts
2755
- EMPTY: every visitor is 'unknown' until a persona exists, and the optimizer learns across all
2756
- traffic pooled in the meantime. Personas are DISCOVERED from behavior \u2014 or, far faster,
2757
- DECLARED by the app when it already knows the visitor's role: init({ persona: 'admin' }) /
2758
- <AdaptiveProvider persona=...> / window.sentient.persona. Declared beats discovered and serves
2868
+ project has its own persona vocabulary (dashboard -> Matrix -> Audiences), and it starts
2869
+ EMPTY: every visitor is 'unknown' (Everyone) until a persona exists, and the optimizer learns
2870
+ across all traffic pooled in the meantime. A visit is served as ONE persona, in order: DECLARED
2871
+ by the app when it already knows the visitor's role (init({ persona: 'admin' }) /
2872
+ <AdaptiveProvider persona=...> / window.sentient.persona), a running retargeting group, a
2873
+ DISCOVERED audience the visitor confidently belongs to, a campaign / arrival type, else
2874
+ Everyone. Behaviour groups (visitors who behaved alike, from portraits) are reporting only \u2014
2875
+ nothing is served to them and they are never personas. Declared beats everything and serves
2759
2876
  at full confidence; unrecognized values are ignored server-side and surfaced in the dashboard
2760
2877
  so the operator can add them. Keep persona a low-cardinality role slug \u2014 never a user id.
2761
2878
  Decisions are locked per visit: a first visit usually sees the original and the return visit adapts \u2014 the
@@ -2841,6 +2958,11 @@ Code variants \u2014 when you write the alternatives yourself:
2841
2958
  });
2842
2959
  return <div {...bind}>{value}</div>;
2843
2960
 
2961
+ Variant keys are versions, not audiences: naming one \`developer\` does NOT show it to
2962
+ developers \u2014 the optimizer may show any version to anyone. To show it to Developers, declare
2963
+ the persona on the site, then pin the version to that audience (Migrate the component in
2964
+ Matrix -> Components; the last step offers the pins).
2965
+
2844
2966
  Children or variants on one <Adaptive>, never both. With the hook, always attach bind \u2014 it
2845
2967
  wires exposure tracking and goal listeners. <AdaptiveText> swaps dashboard-managed text.
2846
2968
 
@@ -3115,14 +3237,14 @@ function registerTrafficTools(server, client) {
3115
3237
  "get_traffic_breakdown",
3116
3238
  {
3117
3239
  title: "Traffic breakdown",
3118
- description: "Where a project\u2019s traffic came from. Every visitor (one per browser or device) last seen in the window falls into exactly one of seven groups that add up to the total: People (ran the page, interacted (click, scroll, mouse, touch or key) and passed the bot check), Loaded but didn\u2019t interact, Not verified \u2014 no browser activity, Being analysed (usually settled within 3 hours), AI assistants, Search & AI crawlers and Other automated. Each group carries plain-English evidence counts; named AI assistants and crawlers, conversions (total and from People) and notices are included. Conversion rates elsewhere are conversion rate among People. Reporting only \u2014 it does not change what the optimizer learns from." + UNTRUSTED_FIELDS_NOTE,
3240
+ description: "Where a project\u2019s traffic came from. Every visitor (one per browser or device) last seen in the window falls into exactly one group, and the groups add up to the total: People (ran the page, interacted (click, scroll, mouse, touch or key) and passed the bot check), Loaded but didn\u2019t interact, Not verified \u2014 no browser activity, Being analysed (usually settled within 3 hours), AI assistants, Search & AI crawlers, Other automated, and Your team / test sites (visits the project marked internal \u2014 never People, never counted, never learned from; see get_internal_traffic_rules). Each group carries plain-English evidence counts; named AI assistants and crawlers, conversions (total and from People) and notices are included. Conversion rates elsewhere are conversion rate among People. Reporting only \u2014 it does not change what the optimizer learns from." + UNTRUSTED_FIELDS_NOTE,
3119
3241
  inputSchema: { projectId: projectIdSchema, range: trafficRangeSchema },
3120
3242
  outputSchema: {
3121
3243
  window: import_v317.z.object({ from: import_v317.z.string(), to: import_v317.z.string() }),
3122
3244
  total: import_v317.z.number().describe("Visitors in the window; the groups add up to this"),
3123
3245
  groups: import_v317.z.array(
3124
3246
  import_v317.z.object({
3125
- group: import_v317.z.string().describe("people | loaded_no_interaction | not_verified | being_analysed | ai_assistant | crawler | other_automated"),
3247
+ group: import_v317.z.string().describe("people | loaded_no_interaction | not_verified | being_analysed | ai_assistant | crawler | other_automated | internal"),
3126
3248
  label: import_v317.z.string(),
3127
3249
  count: import_v317.z.number(),
3128
3250
  evidence: import_v317.z.array(import_v317.z.object({ code: import_v317.z.string(), label: import_v317.z.string(), count: import_v317.z.number() }))
@@ -3138,7 +3260,7 @@ function registerTrafficTools(server, client) {
3138
3260
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3139
3261
  },
3140
3262
  withApiErrorGuidance(async ({ projectId, range }) => {
3141
- var _a2, _b, _c;
3263
+ var _a2, _b, _c, _d, _e;
3142
3264
  const id = encodeURIComponent(projectId);
3143
3265
  const t = await client.get(`/projects/${id}/traffic${range ? `?range=${encodeURIComponent(range)}` : ""}`);
3144
3266
  const beingAnalysed = (_b = (_a2 = t.groups.find((g) => g.group === "being_analysed")) == null ? void 0 : _a2.count) != null ? _b : 0;
@@ -3146,6 +3268,10 @@ function registerTrafficTools(server, client) {
3146
3268
  `Traffic from ${t.window.from.slice(0, 10)} to ${t.window.to.slice(0, 10)}: ${t.total} visitors.`,
3147
3269
  ...t.groups.map((g) => `- ${g.label}: ${g.count}`)
3148
3270
  ];
3271
+ const internal = (_d = (_c = t.groups.find((g) => g.group === "internal")) == null ? void 0 : _c.count) != null ? _d : 0;
3272
+ if (internal > 0) {
3273
+ lines.push("", `${internal} visitors were marked internal by the project's own rules (your team / test sites) \u2014 not in People and not learned from. get_internal_traffic_rules shows which rules.`);
3274
+ }
3149
3275
  if (beingAnalysed > 0) {
3150
3276
  lines.push("", `${beingAnalysed} visitors are being analysed \u2014 usually settled within 3 hours`);
3151
3277
  }
@@ -3153,7 +3279,7 @@ function registerTrafficTools(server, client) {
3153
3279
  lines.push("", "Named agents:", ...t.agents.map((a2) => `- ${untrusted(a2.name)}: ${a2.count}`));
3154
3280
  }
3155
3281
  lines.push("", `${t.conversions.total} conversions in total, ${t.conversions.fromPeople} from People.`);
3156
- for (const n of t.notices) lines.push((_c = NOTICE_TEXT[n]) != null ? _c : n);
3282
+ for (const n of t.notices) lines.push((_e = NOTICE_TEXT[n]) != null ? _e : n);
3157
3283
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent: t };
3158
3284
  }, {
3159
3285
  range_too_large: "That window has too much traffic to break down in one go. Ask for a shorter range (24h, 7d or 30d) and try again."
@@ -3161,33 +3287,119 @@ function registerTrafficTools(server, client) {
3161
3287
  );
3162
3288
  }
3163
3289
 
3164
- // src/tools/cells.ts
3290
+ // src/tools/internal-traffic.ts
3165
3291
  var import_v318 = require("zod/v3");
3166
- var personaOutput = import_v318.z.object({
3167
- key: import_v318.z.string(),
3168
- displayName: import_v318.z.string(),
3169
- description: import_v318.z.string().nullable(),
3170
- share: import_v318.z.number().describe("Fraction of 30-day decided sessions")
3292
+ var INTERNAL_TRAFFIC_LABEL = "Your team / test sites";
3293
+ var REASONS = [
3294
+ { key: "site", words: "internal sites" },
3295
+ { key: "code", words: "code flag" },
3296
+ { key: "email_rule", words: "team emails" },
3297
+ { key: "domain_rule", words: "team domains" },
3298
+ { key: "browser", words: "browser link" }
3299
+ ];
3300
+ function registerInternalTrafficTools(server, client) {
3301
+ server.registerTool(
3302
+ "get_internal_traffic_rules",
3303
+ {
3304
+ title: "Internal traffic rules",
3305
+ description: `Read how this project keeps its own team and test sites out of its numbers (dashboard Settings \u2192 Internal traffic): which allowed domains are internal sites, the team email domains and masked exact emails, whether a "mark this browser" link exists, and how many sessions each way marked internal in the last 7 days. Internal visits still see versions (QA works) but never count in any report or teach the optimizer; get_traffic_breakdown lists them as "${INTERNAL_TRAFFIC_LABEL}". Exact emails are stored only as a hash \u2014 this tool returns the masked form, never an address or the hash. Rules apply from when they are turned on; earlier visits cannot be separated. Read-only: a person changes them in the dashboard.`,
3306
+ inputSchema: { projectId: projectIdSchema },
3307
+ outputSchema: {
3308
+ internalOrigins: import_v318.z.array(import_v318.z.string()).describe("Allowed domains whose every visit is marked internal"),
3309
+ allowedOrigins: import_v318.z.array(import_v318.z.string()).describe("Every allowed domain \u2014 only these can be made internal"),
3310
+ emailDomains: import_v318.z.array(import_v318.z.string()).describe("Email domains (no leading @) whose identified visitors are marked internal"),
3311
+ emails: import_v318.z.array(import_v318.z.string()).describe("Exact team emails, masked (c***@example.com); stored only as a hash"),
3312
+ browserLinkExists: import_v318.z.boolean().describe('Whether a "mark this browser internal" link has been created (copy or rotate it in Settings \u2192 Internal traffic)'),
3313
+ counts7d: import_v318.z.object({
3314
+ site: import_v318.z.number(),
3315
+ code: import_v318.z.number(),
3316
+ email_rule: import_v318.z.number(),
3317
+ domain_rule: import_v318.z.number(),
3318
+ browser: import_v318.z.number(),
3319
+ total: import_v318.z.number()
3320
+ }).describe("Sessions marked internal in the last 7 days, by the way that marked them first"),
3321
+ recordingSince: import_v318.z.string().nullable().describe("When sessions began recording which site they came from; visits before it cannot be separated")
3322
+ },
3323
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3324
+ },
3325
+ withApiErrorGuidance(async ({ projectId }) => {
3326
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
3327
+ const r = await client.get(
3328
+ `/projects/${encodeURIComponent(projectId)}/internal-traffic`
3329
+ );
3330
+ const internalOrigins = (_a2 = r.internalOrigins) != null ? _a2 : [];
3331
+ const allowedOrigins = (_b = r.allowedOrigins) != null ? _b : [];
3332
+ const emailDomains = (_c = r.emailDomains) != null ? _c : [];
3333
+ const emails = ((_d = r.emails) != null ? _d : []).map((e) => e.masked);
3334
+ const c = (_e = r.counts7d) != null ? _e : {};
3335
+ const counts7d = {
3336
+ site: (_f = c.site) != null ? _f : 0,
3337
+ code: (_g = c.code) != null ? _g : 0,
3338
+ email_rule: (_h = c.email_rule) != null ? _h : 0,
3339
+ domain_rule: (_i = c.domain_rule) != null ? _i : 0,
3340
+ browser: (_j = c.browser) != null ? _j : 0,
3341
+ total: (_k = c.total) != null ? _k : 0
3342
+ };
3343
+ const recordingSince = (_l = r.recordingSince) != null ? _l : null;
3344
+ const browserLinkExists = r.browserLink != null;
3345
+ const notInternal = allowedOrigins.filter((o) => !internalOrigins.includes(o));
3346
+ const lines = [
3347
+ `Internal traffic \u2014 reported as "${INTERNAL_TRAFFIC_LABEL}": these visits still see versions but never count and never teach the optimizer.`,
3348
+ `Internal sites: ${internalOrigins.length ? internalOrigins.join(", ") : "none"}.`,
3349
+ ...notInternal.length ? [`Allowed but counted normally: ${notInternal.join(", ")}.`] : [],
3350
+ `Team domains: ${emailDomains.length ? emailDomains.map((d) => `@${d}`).join(", ") : "none"}.`,
3351
+ `Team emails: ${emails.length ? emails.join(", ") : "none"} (stored only as a hash; they match visitors the site identifies with identify(userId, { email })).`,
3352
+ `Browser link: ${browserLinkExists ? "created \u2014 copy or rotate it in Settings \u2192 Internal traffic" : "not created"}.`,
3353
+ `Sessions marked internal, last 7 days: ${counts7d.total} (${REASONS.map((x) => `${x.words} ${counts7d[x.key]}`).join(", ")}).`,
3354
+ recordingSince ? `Applies from when each rule is turned on; visits before ${recordingSince.slice(0, 10)} cannot be separated (which site a visit came from was not recorded).` : "Applies from when each rule is turned on; earlier visits cannot be separated.",
3355
+ "To change these, a person uses Settings \u2192 Internal traffic in the dashboard."
3356
+ ];
3357
+ return {
3358
+ content: [{ type: "text", text: lines.join("\n") }],
3359
+ structuredContent: { internalOrigins, allowedOrigins, emailDomains, emails, browserLinkExists, counts7d, recordingSince }
3360
+ };
3361
+ })
3362
+ );
3363
+ }
3364
+
3365
+ // src/tools/cells.ts
3366
+ var import_v319 = require("zod/v3");
3367
+ var personaOutput = import_v319.z.object({
3368
+ key: import_v319.z.string(),
3369
+ displayName: import_v319.z.string(),
3370
+ description: import_v319.z.string().nullable(),
3371
+ share: import_v319.z.number().describe("Fraction of 30-day decided sessions"),
3372
+ // Both ride the API response; without them zod stripped them and an agent
3373
+ // reported a declared audience nothing declares as reachable.
3374
+ state: import_v319.z.string().optional().describe("everyone | declared | unlocked | candidate | starter \u2014 why the row exists"),
3375
+ declaredVisits14d: import_v319.z.number().nullable().optional().describe(
3376
+ "Declared rows only: visits in 14 days whose site declared this persona. 0 = not declared yet \u2014 nobody sees versions written for it until the site sends it."
3377
+ )
3171
3378
  });
3172
- var cellOutput = import_v318.z.object({
3173
- slotId: import_v318.z.string(),
3174
- persona: import_v318.z.string(),
3175
- status: import_v318.z.string().describe("pending | generating | review (waiting for approval) | live | error | rejected"),
3176
- requestedBy: import_v318.z.string(),
3177
- armId: import_v318.z.string().nullable(),
3178
- rationale: import_v318.z.string().nullable(),
3179
- error: import_v318.z.string().nullable(),
3180
- updatedAt: import_v318.z.string(),
3379
+ var blockedOutput = import_v319.z.enum(["variant_history"]).nullable().optional().describe(
3380
+ "variant_history: the component's code still runs its own variants test, so versions written here are approved but NOT showing until it is migrated (dashboard Components \u2192 Migrate). Null when the column can serve."
3381
+ );
3382
+ var BLOCKED_LINE = "Not showing yet \u2014 your code's own test still runs here. Versions written for this part of the page are approved but no visitor sees them until it is migrated (Components \u2192 this component \u2192 Migrate).";
3383
+ var NOT_DECLARED_LINE = "not declared yet \u2014 your site has not told us anyone is this persona in 14 days, so nobody sees versions written for them until your code sends it (the persona prop, init({ persona }) or window.sentient.persona)";
3384
+ var cellOutput = import_v319.z.object({
3385
+ slotId: import_v319.z.string(),
3386
+ persona: import_v319.z.string(),
3387
+ status: import_v319.z.string().describe("pending | generating | review (waiting for approval) | live | error | rejected"),
3388
+ requestedBy: import_v319.z.string(),
3389
+ armId: import_v319.z.string().nullable(),
3390
+ rationale: import_v319.z.string().nullable(),
3391
+ error: import_v319.z.string().nullable(),
3392
+ updatedAt: import_v319.z.string(),
3181
3393
  // These ride the API response too; omitting them from the schema made zod
3182
3394
  // STRIP them, so agents could never see refinement or retry state.
3183
- refinedFrom: import_v318.z.string().nullable().optional().describe("Incumbent arm this cell is improving on \u2014 a pending cell with this set still SERVES the incumbent"),
3184
- notBefore: import_v318.z.string().nullable().optional().describe("ISO time the queue will next consider this cell (retry backoff / daily-cap deferral); null when due now"),
3185
- attempts: import_v318.z.number().optional().describe("Generation attempts so far"),
3186
- performance: import_v318.z.object({
3187
- shown: import_v318.z.number(),
3188
- conversions: import_v318.z.number(),
3189
- deltaPct: import_v318.z.number().nullable().describe("Signed % vs the original conversion rate \u2014 a point estimate; only meaningful beside a winning/losing tier"),
3190
- tier: import_v318.z.string().describe(
3395
+ refinedFrom: import_v319.z.string().nullable().optional().describe("Incumbent arm this cell is improving on \u2014 a pending cell with this set still SERVES the incumbent"),
3396
+ notBefore: import_v319.z.string().nullable().optional().describe("ISO time the queue will next consider this cell (retry backoff / daily-cap deferral); null when due now"),
3397
+ attempts: import_v319.z.number().optional().describe("Generation attempts so far"),
3398
+ performance: import_v319.z.object({
3399
+ shown: import_v319.z.number(),
3400
+ conversions: import_v319.z.number(),
3401
+ deltaPct: import_v319.z.number().nullable().describe("Signed % vs the original conversion rate \u2014 a point estimate; only meaningful beside a winning/losing tier"),
3402
+ tier: import_v319.z.string().describe(
3191
3403
  'early | no_baseline (under 100 views) | winning | losing (posterior separated from the original, corrected across the slot column) | flat (NOT separated yet \u2014 not "equal")'
3192
3404
  )
3193
3405
  }).optional().describe("Present on live cells (and, mid-refinement, the incumbent arm): the at-a-glance readout")
@@ -3200,28 +3412,29 @@ function registerCellTools(server, client) {
3200
3412
  description: 'The "Who sees what" matrix: which visitor types (personas) have an AI-generated version live in each personalizable region (slot), with per-persona traffic share and the first-miss auto-fill setting. A cell with no row means that visitor type sees the original.' + UNTRUSTED_FIELDS_NOTE,
3201
3413
  inputSchema: { projectId: projectIdSchema },
3202
3414
  outputSchema: {
3203
- slots: import_v318.z.array(
3204
- import_v318.z.object({
3205
- slotId: import_v318.z.string(),
3206
- displayName: import_v318.z.string(),
3207
- supportsForms: import_v318.z.boolean(),
3415
+ slots: import_v319.z.array(
3416
+ import_v319.z.object({
3417
+ slotId: import_v319.z.string(),
3418
+ displayName: import_v319.z.string(),
3419
+ supportsForms: import_v319.z.boolean(),
3208
3420
  // API sends this; without it zod stripped the draft-vs-live signal.
3209
- live: import_v318.z.boolean().optional().describe("False for an sdk-registered draft column \u2014 nothing serves until its first generation publishes it")
3421
+ live: import_v319.z.boolean().optional().describe("False for an sdk-registered draft column \u2014 nothing serves until its first generation publishes it"),
3422
+ blocked: blockedOutput
3210
3423
  })
3211
3424
  ),
3212
- personas: import_v318.z.array(personaOutput),
3213
- cells: import_v318.z.array(cellOutput),
3214
- autoFill: import_v318.z.boolean(),
3425
+ personas: import_v319.z.array(personaOutput),
3426
+ cells: import_v319.z.array(cellOutput),
3427
+ autoFill: import_v319.z.boolean(),
3215
3428
  // The API has always sent this; without it in the schema zod stripped
3216
3429
  // it, and generate_cell had no way to know a version would wait for a
3217
3430
  // human instead of publishing.
3218
- reviewMode: import_v318.z.boolean().optional().describe("True when generated versions wait for approval (review_cell) instead of publishing automatically"),
3431
+ reviewMode: import_v319.z.boolean().optional().describe("True when generated versions wait for approval (review_cell) instead of publishing automatically"),
3219
3432
  // Nullable: a project with no persona set at all reports null, not a
3220
3433
  // string. That is the NORMAL state since the default vocabulary was
3221
3434
  // emptied, so a non-nullable schema failed output validation on most
3222
3435
  // projects and the tool returned nothing but a zod error.
3223
- personaSource: import_v318.z.string().nullable().describe('Active persona-set source: default | declared | discovered, or null when the project has no persona set (one "everyone" row)'),
3224
- undecidedShare: import_v318.z.number()
3436
+ personaSource: import_v319.z.string().nullable().describe('Active persona-set source: default | declared | discovered, or null when the project has no persona set (one "everyone" row)'),
3437
+ undecidedShare: import_v319.z.number()
3225
3438
  },
3226
3439
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3227
3440
  },
@@ -3230,22 +3443,27 @@ function registerCellTools(server, client) {
3230
3443
  const id = encodeURIComponent(projectId);
3231
3444
  const data = await client.get(`/projects/${id}/cells`);
3232
3445
  const byCell = new Map(data.cells.map((c) => [`${c.slotId}::${c.persona}`, c]));
3446
+ const blockedSlots = data.slots.filter((s) => s.blocked === "variant_history");
3233
3447
  const lines = [
3234
- `Slots: ${data.slots.map((s) => `${untrusted(s.displayName)}${s.live === false ? " [draft]" : ""}`).join(", ") || "(none published)"}`,
3448
+ `Slots: ${data.slots.map((s) => `${untrusted(s.displayName)}${s.live === false ? " [draft]" : ""}${s.blocked === "variant_history" ? " [not showing yet]" : ""}`).join(", ") || "(none published)"}`,
3449
+ ...blockedSlots.length > 0 ? [`${blockedSlots.map((s) => untrusted(s.displayName, 40)).join(", ")}: ${BLOCKED_LINE}`] : [],
3235
3450
  `Auto-fill on first miss: ${data.autoFill ? "ON" : "off"} \xB7 review before publishing: ${data.reviewMode ? "ON (approve with review_cell)" : "off"} \xB7 persona source: ${(_a2 = data.personaSource) != null ? _a2 : 'none (one "everyone" row)'}`
3236
3451
  ];
3237
3452
  for (const p of data.personas) {
3238
3453
  const states = data.slots.map((s) => {
3239
3454
  const c = byCell.get(`${s.slotId}::${p.key}`);
3240
3455
  let state = c ? c.status : "original";
3241
- if (c && (c.status === "pending" || c.status === "generating") && c.refinedFrom) {
3456
+ if (c && c.status === "live" && s.blocked === "variant_history") {
3457
+ state = "approved \u2014 not showing yet";
3458
+ } else if (c && (c.status === "pending" || c.status === "generating") && c.refinedFrom) {
3242
3459
  state = `${c.status} (improving on ${untrusted(c.refinedFrom, 64)} \u2014 current version still live)`;
3243
3460
  } else if (c && c.status === "pending" && c.notBefore && Date.parse(c.notBefore) > Date.now()) {
3244
3461
  state = `pending (waiting until ${c.notBefore})`;
3245
3462
  }
3246
3463
  return `${untrusted(s.displayName, 40)}: ${state}`;
3247
3464
  });
3248
- lines.push(`- ${untrusted(p.displayName)} (${Math.round(p.share * 100)}% of visitors) \u2014 ${states.join(" \xB7 ")}`);
3465
+ const undeclared = p.state === "declared" && p.declaredVisits14d === 0 ? ` [${NOT_DECLARED_LINE}]` : "";
3466
+ lines.push(`- ${untrusted(p.displayName)} (${Math.round(p.share * 100)}% of visitors)${undeclared} \u2014 ${states.join(" \xB7 ")}`);
3249
3467
  }
3250
3468
  lines.push(`Undecided visitors (${Math.round(data.undecidedShare * 100)}%) always see the original.`);
3251
3469
  return {
@@ -3261,26 +3479,27 @@ function registerCellTools(server, client) {
3261
3479
  description: "One cell's full story: the generated option a visitor type sees in a slot, why it was written (the stored generation rationale), and how it is performing vs the original (deterministic plain-language verdict)." + UNTRUSTED_FIELDS_NOTE,
3262
3480
  inputSchema: {
3263
3481
  projectId: projectIdSchema,
3264
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3265
- persona: import_v318.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3482
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3483
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3266
3484
  },
3267
3485
  outputSchema: {
3268
3486
  cell: cellOutput.nullable(),
3269
- arm: import_v318.z.object({
3270
- id: import_v318.z.string(),
3271
- displayName: import_v318.z.string().nullable(),
3272
- content: import_v318.z.string().nullable(),
3273
- blocks: import_v318.z.unknown().nullable()
3487
+ arm: import_v319.z.object({
3488
+ id: import_v319.z.string(),
3489
+ displayName: import_v319.z.string().nullable(),
3490
+ content: import_v319.z.string().nullable(),
3491
+ blocks: import_v319.z.unknown().nullable()
3274
3492
  }).nullable(),
3275
- performance: import_v318.z.object({
3276
- shown: import_v318.z.number(),
3277
- conversions: import_v318.z.number(),
3278
- conversionRate: import_v318.z.number(),
3279
- baselineShown: import_v318.z.number(),
3280
- baselineConversions: import_v318.z.number(),
3281
- baselineConversionRate: import_v318.z.number()
3493
+ performance: import_v319.z.object({
3494
+ shown: import_v319.z.number(),
3495
+ conversions: import_v319.z.number(),
3496
+ conversionRate: import_v319.z.number(),
3497
+ baselineShown: import_v319.z.number(),
3498
+ baselineConversions: import_v319.z.number(),
3499
+ baselineConversionRate: import_v319.z.number()
3282
3500
  }).nullable(),
3283
- verdict: import_v318.z.string()
3501
+ verdict: import_v319.z.string(),
3502
+ blocked: blockedOutput
3284
3503
  },
3285
3504
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3286
3505
  },
@@ -3289,7 +3508,12 @@ function registerCellTools(server, client) {
3289
3508
  const id = encodeURIComponent(projectId);
3290
3509
  const data = await client.get(`/projects/${id}/cells/detail?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`);
3291
3510
  const lines = [];
3292
- if (data.arm) {
3511
+ if (data.arm && data.blocked === "variant_history") {
3512
+ lines.push(
3513
+ data.arm.content !== null ? `Approved version (not showing yet): "${untrusted(data.arm.content, 300)}"` : `Approved designed layout (option ${untrusted(data.arm.id, 64)}), not showing yet.`,
3514
+ BLOCKED_LINE
3515
+ );
3516
+ } else if (data.arm) {
3293
3517
  lines.push(
3294
3518
  data.arm.content !== null ? `They see: "${untrusted(data.arm.content, 300)}"` : `They see a designed layout (option ${untrusted(data.arm.id, 64)}).`
3295
3519
  );
@@ -3325,14 +3549,14 @@ function registerCellTools(server, client) {
3325
3549
  description: "Queue AI generation of a version for one (persona, slot) cell; the worker writes it asynchronously, brand-locked. If the project has review mode on, the finished version WAITS for approval (list_cell_reviews / review_cell) and serves nobody until approved; otherwise it publishes automatically as a named option the optimizer explores. Also regenerates or retries a failed cell. Generation volume is capped per plan (Free included). Check get_cell_matrix for progress. Confirm with the user before calling \u2014 each generation is a model call against the plan quota.",
3326
3550
  inputSchema: {
3327
3551
  projectId: projectIdSchema,
3328
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3329
- persona: import_v318.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3552
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3553
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3330
3554
  },
3331
3555
  outputSchema: {
3332
- slotId: import_v318.z.string(),
3333
- persona: import_v318.z.string(),
3334
- status: import_v318.z.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress"),
3335
- reviewMode: import_v318.z.boolean().nullable().describe("True: the version will wait for review_cell approval. False: it publishes automatically. Null: could not be read.")
3556
+ slotId: import_v319.z.string(),
3557
+ persona: import_v319.z.string(),
3558
+ status: import_v319.z.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress"),
3559
+ reviewMode: import_v319.z.boolean().nullable().describe("True: the version will wait for review_cell approval. False: it publishes automatically. Null: could not be read.")
3336
3560
  },
3337
3561
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
3338
3562
  },
@@ -3360,19 +3584,20 @@ function registerCellTools(server, client) {
3360
3584
  description: "Generated versions waiting for approval (review mode): which slot and visitor type, the proposed text or layout, and why it was written. Approve or reject each with review_cell after the user decides." + UNTRUSTED_FIELDS_NOTE,
3361
3585
  inputSchema: { projectId: projectIdSchema },
3362
3586
  outputSchema: {
3363
- reviews: import_v318.z.array(
3364
- import_v318.z.object({
3365
- slotId: import_v318.z.string(),
3366
- slotName: import_v318.z.string(),
3367
- persona: import_v318.z.string(),
3368
- personaDisplay: import_v318.z.string(),
3369
- content: import_v318.z.string().nullable().describe("Proposed text, when the version is text (null for a block/layout version)"),
3370
- rationale: import_v318.z.string().nullable(),
3371
- refinedFrom: import_v318.z.string().nullable().describe("Live version this one would replace; that version keeps serving until approval"),
3372
- updatedAt: import_v318.z.string()
3587
+ reviews: import_v319.z.array(
3588
+ import_v319.z.object({
3589
+ slotId: import_v319.z.string(),
3590
+ slotName: import_v319.z.string(),
3591
+ persona: import_v319.z.string(),
3592
+ personaDisplay: import_v319.z.string(),
3593
+ content: import_v319.z.string().nullable().describe("Proposed text, when the version is text (null for a block/layout version)"),
3594
+ rationale: import_v319.z.string().nullable(),
3595
+ refinedFrom: import_v319.z.string().nullable().describe("Live version this one would replace; that version keeps serving until approval"),
3596
+ updatedAt: import_v319.z.string(),
3597
+ blocked: blockedOutput
3373
3598
  })
3374
3599
  ),
3375
- total: import_v318.z.number().int().describe("How many versions are waiting in all. The list holds at most the oldest 200; decide those to see the rest.")
3600
+ total: import_v319.z.number().int().describe("How many versions are waiting in all. The list holds at most the oldest 200; decide those to see the rest.")
3376
3601
  },
3377
3602
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3378
3603
  },
@@ -3381,7 +3606,7 @@ function registerCellTools(server, client) {
3381
3606
  const id = encodeURIComponent(projectId);
3382
3607
  const data = await client.get(`/projects/${id}/cell-reviews`);
3383
3608
  const reviews = ((_a2 = data.reviews) != null ? _a2 : []).map((r) => {
3384
- var _a3, _b, _c;
3609
+ var _a3, _b, _c, _d;
3385
3610
  return {
3386
3611
  slotId: r.slotId,
3387
3612
  slotName: r.slotName,
@@ -3390,7 +3615,8 @@ function registerCellTools(server, client) {
3390
3615
  content: typeof ((_a3 = r.pendingArm) == null ? void 0 : _a3.content) === "string" ? r.pendingArm.content : null,
3391
3616
  rationale: (_b = r.rationale) != null ? _b : null,
3392
3617
  refinedFrom: (_c = r.refinedFrom) != null ? _c : null,
3393
- updatedAt: String(r.updatedAt)
3618
+ updatedAt: String(r.updatedAt),
3619
+ blocked: (_d = r.blocked) != null ? _d : null
3394
3620
  };
3395
3621
  });
3396
3622
  const total = typeof data.total === "number" ? data.total : reviews.length;
@@ -3405,7 +3631,8 @@ function registerCellTools(server, client) {
3405
3631
  `- ${untrusted(r.slotName, 60)} (slotId ${untrusted(r.slotId, 64)}) for ${untrusted(r.personaDisplay, 60)} (persona ${untrusted(r.persona, 64)})`,
3406
3632
  r.content !== null ? ` Proposed text: ${untrusted(r.content, 300)}` : " Proposed: a designed block/layout (preview it in the dashboard)",
3407
3633
  r.rationale ? ` Why: ${untrusted(r.rationale, 300)}` : null,
3408
- r.refinedFrom ? ` Would replace ${untrusted(r.refinedFrom, 64)}, which keeps serving until approval.` : null
3634
+ r.refinedFrom ? ` Would replace ${untrusted(r.refinedFrom, 64)}, which keeps serving until approval.` : null,
3635
+ r.blocked === "variant_history" ? ` Approving it will NOT show it yet: ${BLOCKED_LINE}` : null
3409
3636
  ].filter((l) => l !== null).join("\n")
3410
3637
  );
3411
3638
  if (total > reviews.length) {
@@ -3422,22 +3649,23 @@ function registerCellTools(server, client) {
3422
3649
  description: "Approve or reject ONE generated version waiting for review (see list_cell_reviews). 'approve' publishes it to live visitors of that type; 'reject' discards it (a rejected refinement leaves the current live version in place). This is the human decision review mode exists for \u2014 only call it with the user's explicit go-ahead.",
3423
3650
  inputSchema: {
3424
3651
  projectId: projectIdSchema,
3425
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id of the version under review"),
3426
- persona: import_v318.z.string().min(1).max(64).describe("The persona key of the version under review"),
3427
- action: import_v318.z.enum(["approve", "reject"]),
3428
- feedback: import_v318.z.string().max(2e3).optional().describe("Optional reviewer note, stored with a rejection")
3652
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id of the version under review"),
3653
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key of the version under review"),
3654
+ action: import_v319.z.enum(["approve", "reject"]),
3655
+ feedback: import_v319.z.string().max(2e3).optional().describe("On reject: what was wrong, in the user's words. The next version written for that square is told to address it.")
3429
3656
  },
3430
3657
  outputSchema: {
3431
- slotId: import_v318.z.string(),
3432
- persona: import_v318.z.string(),
3433
- action: import_v318.z.enum(["approve", "reject"]),
3434
- status: import_v318.z.string().describe("live (approved, or a rejected refinement whose incumbent keeps serving) | rejected"),
3435
- armId: import_v318.z.string().nullable().describe("The published option id, on approval")
3658
+ slotId: import_v319.z.string(),
3659
+ persona: import_v319.z.string(),
3660
+ action: import_v319.z.enum(["approve", "reject"]),
3661
+ status: import_v319.z.string().describe("live (approved, or a rejected refinement whose incumbent keeps serving) | rejected"),
3662
+ armId: import_v319.z.string().nullable().describe("The published option id, on approval"),
3663
+ blocked: blockedOutput
3436
3664
  },
3437
3665
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
3438
3666
  },
3439
3667
  withApiErrorGuidance(async ({ projectId, slotId, persona, action, feedback }) => {
3440
- var _a2, _b;
3668
+ var _a2, _b, _c;
3441
3669
  const id = encodeURIComponent(projectId);
3442
3670
  const res = await client.post(`/projects/${id}/cells/review`, {
3443
3671
  slotId,
@@ -3446,10 +3674,11 @@ function registerCellTools(server, client) {
3446
3674
  feedback
3447
3675
  });
3448
3676
  const status = (_a2 = res.status) != null ? _a2 : action === "approve" ? "live" : "rejected";
3449
- const text2 = action === "approve" ? `Approved: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} is now live${res.armId ? ` as option ${untrusted(res.armId, 64)}` : ""}.` : status === "live" ? `Rejected: the proposed refinement for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; the current live version keeps serving.` : `Rejected: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; that visitor type keeps seeing the original.`;
3677
+ const blocked = (_b = res.blocked) != null ? _b : null;
3678
+ const text2 = action === "approve" && blocked === "variant_history" ? `Approved the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)}, but it is not showing yet. ${BLOCKED_LINE}` : action === "approve" ? `Approved: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} is now live${res.armId ? ` as option ${untrusted(res.armId, 64)}` : ""}.` : status === "live" ? `Rejected: the proposed refinement for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; the current live version keeps serving.` : `Rejected: the version for ${untrusted(persona, 64)} in ${untrusted(slotId, 64)} was discarded; that visitor type keeps seeing the original.`;
3450
3679
  return {
3451
3680
  content: [{ type: "text", text: text2 }],
3452
- structuredContent: { slotId, persona, action, status, armId: (_b = res.armId) != null ? _b : null }
3681
+ structuredContent: { slotId, persona, action, status, armId: (_c = res.armId) != null ? _c : null, blocked }
3453
3682
  };
3454
3683
  }, {
3455
3684
  not_found: "No version is waiting for review in that cell (it may already have been approved or rejected). Check list_cell_reviews.",
@@ -3459,7 +3688,7 @@ function registerCellTools(server, client) {
3459
3688
  }
3460
3689
 
3461
3690
  // src/tools/agent-reads.ts
3462
- var import_v319 = require("zod/v3");
3691
+ var import_v320 = require("zod/v3");
3463
3692
  var READ_ONLY = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
3464
3693
  var AREA_NAMES = {
3465
3694
  generate: "Generate",
@@ -3511,15 +3740,15 @@ function registerAgentReadTools(server, client) {
3511
3740
  description: "See which areas of this project a person has allowed agents to change: Generate, Approve and publish, Run tests, Goals and funnels, Campaigns and audiences, Project settings. Reading is always allowed; this tells you what a write tool will be refused for before you try it. Agents cannot change these switches \u2014 only a person can, in Settings \u2192 Agent access.",
3512
3741
  inputSchema: { projectId: projectIdSchema },
3513
3742
  outputSchema: {
3514
- areas: import_v319.z.object({
3515
- generate: import_v319.z.boolean(),
3516
- approve: import_v319.z.boolean(),
3517
- tests: import_v319.z.boolean(),
3518
- goals: import_v319.z.boolean(),
3519
- campaigns: import_v319.z.boolean(),
3520
- settings: import_v319.z.boolean()
3743
+ areas: import_v320.z.object({
3744
+ generate: import_v320.z.boolean(),
3745
+ approve: import_v320.z.boolean(),
3746
+ tests: import_v320.z.boolean(),
3747
+ goals: import_v320.z.boolean(),
3748
+ campaigns: import_v320.z.boolean(),
3749
+ settings: import_v320.z.boolean()
3521
3750
  }).describe("true = agents may act in this area"),
3522
- canEdit: import_v319.z.boolean().describe("Whether THIS credential could change the switches (always false for an agent)")
3751
+ canEdit: import_v320.z.boolean().describe("Whether THIS credential could change the switches (always false for an agent)")
3523
3752
  },
3524
3753
  annotations: READ_ONLY
3525
3754
  },
@@ -3546,35 +3775,35 @@ function registerAgentReadTools(server, client) {
3546
3775
  description: "List this project's named campaigns, their retargeting groups, and the campaigns seen in traffic. Pass campaignId to get one campaign's card instead: clicks, new people, how many came back, conversions per version, and the control group (visitors held back on the original site). Counts only \u2014 no lift is claimed." + UNTRUSTED_FIELDS_NOTE,
3547
3776
  inputSchema: __spreadValues({
3548
3777
  projectId: projectIdSchema,
3549
- campaignId: import_v319.z.string().optional().describe("A campaign id from this tool's list; returns that campaign's card")
3778
+ campaignId: import_v320.z.string().optional().describe("A campaign id from this tool's list; returns that campaign's card")
3550
3779
  }, rangeInputSchema("30d")),
3551
3780
  outputSchema: {
3552
- campaigns: import_v319.z.array(import_v319.z.object({
3553
- id: import_v319.z.string(),
3554
- name: import_v319.z.string(),
3555
- status: import_v319.z.string().nullable(),
3556
- arrivalType: import_v319.z.string().nullable(),
3557
- landingPaths: import_v319.z.array(import_v319.z.string())
3781
+ campaigns: import_v320.z.array(import_v320.z.object({
3782
+ id: import_v320.z.string(),
3783
+ name: import_v320.z.string(),
3784
+ status: import_v320.z.string().nullable(),
3785
+ arrivalType: import_v320.z.string().nullable(),
3786
+ landingPaths: import_v320.z.array(import_v320.z.string())
3558
3787
  })).optional(),
3559
- retargeting: import_v319.z.array(import_v319.z.object({
3560
- groupId: import_v319.z.string(),
3561
- campaignId: import_v319.z.string().nullable(),
3562
- name: import_v319.z.string(),
3563
- status: import_v319.z.string().nullable(),
3564
- endsAt: import_v319.z.string().nullable(),
3565
- memberCount: import_v319.z.number()
3788
+ retargeting: import_v320.z.array(import_v320.z.object({
3789
+ groupId: import_v320.z.string(),
3790
+ campaignId: import_v320.z.string().nullable(),
3791
+ name: import_v320.z.string(),
3792
+ status: import_v320.z.string().nullable(),
3793
+ endsAt: import_v320.z.string().nullable(),
3794
+ memberCount: import_v320.z.number()
3566
3795
  })).optional(),
3567
- observed: import_v319.z.array(import_v319.z.object({ campaign: import_v319.z.string(), sessions: import_v319.z.number(), channel: import_v319.z.string().nullable() })).optional(),
3568
- card: import_v319.z.object({
3569
- campaignId: import_v319.z.string(),
3570
- name: import_v319.z.string(),
3571
- status: import_v319.z.string().nullable(),
3572
- clicks: import_v319.z.number(),
3573
- people: import_v319.z.number().describe("New people served as the campaign"),
3574
- cameBack: import_v319.z.number(),
3575
- controlGroup: import_v319.z.number().describe("Matched visits held back on the original site"),
3576
- versions: import_v319.z.array(import_v319.z.object({ label: import_v319.z.string(), shown: import_v319.z.number(), conversions: import_v319.z.number() })).describe("Per section and version; one visitor can appear in several rows, so do not add them up"),
3577
- retargetingGroupId: import_v319.z.string().nullable()
3796
+ observed: import_v320.z.array(import_v320.z.object({ campaign: import_v320.z.string(), sessions: import_v320.z.number(), channel: import_v320.z.string().nullable() })).optional(),
3797
+ card: import_v320.z.object({
3798
+ campaignId: import_v320.z.string(),
3799
+ name: import_v320.z.string(),
3800
+ status: import_v320.z.string().nullable(),
3801
+ clicks: import_v320.z.number(),
3802
+ people: import_v320.z.number().describe("New people served as the campaign"),
3803
+ cameBack: import_v320.z.number(),
3804
+ controlGroup: import_v320.z.number().describe("Matched visits held back on the original site"),
3805
+ versions: import_v320.z.array(import_v320.z.object({ label: import_v320.z.string(), shown: import_v320.z.number(), conversions: import_v320.z.number() })).describe("Per section and version; one visitor can appear in several rows, so do not add them up"),
3806
+ retargetingGroupId: import_v320.z.string().nullable()
3578
3807
  }).optional().describe("Only when campaignId was given")
3579
3808
  },
3580
3809
  annotations: READ_ONLY
@@ -3657,17 +3886,17 @@ function registerAgentReadTools(server, client) {
3657
3886
  {
3658
3887
  title: "Retargeting report",
3659
3888
  description: "One retargeting group's numbers: how many people it started with, how many came back, clicks and conversions. These are counts, not lift. Get the group id from list_campaigns." + UNTRUSTED_FIELDS_NOTE,
3660
- inputSchema: { projectId: projectIdSchema, groupId: import_v319.z.string().describe("A retargeting group id from list_campaigns") },
3889
+ inputSchema: { projectId: projectIdSchema, groupId: import_v320.z.string().describe("A retargeting group id from list_campaigns") },
3661
3890
  outputSchema: {
3662
- groupId: import_v319.z.string(),
3663
- name: import_v319.z.string(),
3664
- status: import_v319.z.string().nullable(),
3665
- endsAt: import_v319.z.string().nullable(),
3666
- members: import_v319.z.number(),
3667
- cameBack: import_v319.z.number(),
3668
- converted: import_v319.z.number(),
3669
- clicks: import_v319.z.number(),
3670
- versions: import_v319.z.array(import_v319.z.object({ label: import_v319.z.string(), shown: import_v319.z.number(), conversions: import_v319.z.number() }))
3891
+ groupId: import_v320.z.string(),
3892
+ name: import_v320.z.string(),
3893
+ status: import_v320.z.string().nullable(),
3894
+ endsAt: import_v320.z.string().nullable(),
3895
+ members: import_v320.z.number(),
3896
+ cameBack: import_v320.z.number(),
3897
+ converted: import_v320.z.number(),
3898
+ clicks: import_v320.z.number(),
3899
+ versions: import_v320.z.array(import_v320.z.object({ label: import_v320.z.string(), shown: import_v320.z.number(), conversions: import_v320.z.number() }))
3671
3900
  },
3672
3901
  annotations: READ_ONLY
3673
3902
  },
@@ -3704,20 +3933,20 @@ function registerAgentReadTools(server, client) {
3704
3933
  description: "The audiences visitors are sorted into: the ones the site declares, the ones discovered from behaviour (with how many sessions, their share of traffic, and how much evidence there is), and whether the discovered set can be promoted to serving yet, with what is blocking it in plain words." + UNTRUSTED_FIELDS_NOTE,
3705
3934
  inputSchema: { projectId: projectIdSchema },
3706
3935
  outputSchema: {
3707
- declared: import_v319.z.object({
3708
- source: import_v319.z.string().nullable(),
3709
- members: import_v319.z.array(import_v319.z.object({ key: import_v319.z.string(), displayName: import_v319.z.string(), status: import_v319.z.string().nullable() }))
3936
+ declared: import_v320.z.object({
3937
+ source: import_v320.z.string().nullable(),
3938
+ members: import_v320.z.array(import_v320.z.object({ key: import_v320.z.string(), displayName: import_v320.z.string(), status: import_v320.z.string().nullable() }))
3710
3939
  }).nullable(),
3711
- discovered: import_v319.z.object({
3712
- members: import_v319.z.array(import_v319.z.object({
3713
- key: import_v319.z.string(),
3714
- displayName: import_v319.z.string(),
3715
- sessions: import_v319.z.number().nullable(),
3716
- share: import_v319.z.number().nullable(),
3717
- evidence: import_v319.z.string().describe("strong_evidence | moderate_evidence | no_clear_difference | not_enough_data | not_checked_yet")
3940
+ discovered: import_v320.z.object({
3941
+ members: import_v320.z.array(import_v320.z.object({
3942
+ key: import_v320.z.string(),
3943
+ displayName: import_v320.z.string(),
3944
+ sessions: import_v320.z.number().nullable(),
3945
+ share: import_v320.z.number().nullable(),
3946
+ evidence: import_v320.z.string().describe("strong_evidence | moderate_evidence | no_clear_difference | not_enough_data | not_checked_yet")
3718
3947
  }))
3719
3948
  }).nullable().describe("null when no discovered set exists yet"),
3720
- promotion: import_v319.z.object({ eligible: import_v319.z.boolean(), blockers: import_v319.z.array(import_v319.z.string()) }).nullable()
3949
+ promotion: import_v320.z.object({ eligible: import_v320.z.boolean(), blockers: import_v320.z.array(import_v320.z.string()) }).nullable()
3721
3950
  },
3722
3951
  annotations: READ_ONLY
3723
3952
  },
@@ -3783,18 +4012,18 @@ function registerAgentReadTools(server, client) {
3783
4012
  description: "The styles captured from the site (what generated sections borrow), grouped by role, whether their colors were actually measured, when the scan last ran, and the site audit score. Without measured colors a style cannot be checked for readable contrast." + UNTRUSTED_FIELDS_NOTE,
3784
4013
  inputSchema: { projectId: projectIdSchema },
3785
4014
  outputSchema: {
3786
- colorsMeasured: import_v319.z.boolean().describe("false when no captured style has a measured text or background color"),
3787
- roles: import_v319.z.array(import_v319.z.object({
3788
- role: import_v319.z.string(),
3789
- count: import_v319.z.number(),
3790
- measuredColors: import_v319.z.number().describe("How many of these styles have a measured color")
4015
+ colorsMeasured: import_v320.z.boolean().describe("false when no captured style has a measured text or background color"),
4016
+ roles: import_v320.z.array(import_v320.z.object({
4017
+ role: import_v320.z.string(),
4018
+ count: import_v320.z.number(),
4019
+ measuredColors: import_v320.z.number().describe("How many of these styles have a measured color")
3791
4020
  })),
3792
- lastScan: import_v319.z.object({ editorAt: import_v319.z.string().nullable(), crawlAt: import_v319.z.string().nullable() }),
3793
- audit: import_v319.z.object({
3794
- status: import_v319.z.string().nullable(),
3795
- score: import_v319.z.number().nullable(),
3796
- auditedAt: import_v319.z.string().nullable(),
3797
- checking: import_v319.z.boolean()
4021
+ lastScan: import_v320.z.object({ editorAt: import_v320.z.string().nullable(), crawlAt: import_v320.z.string().nullable() }),
4022
+ audit: import_v320.z.object({
4023
+ status: import_v320.z.string().nullable(),
4024
+ score: import_v320.z.number().nullable(),
4025
+ auditedAt: import_v320.z.string().nullable(),
4026
+ checking: import_v320.z.boolean()
3798
4027
  }).nullable().describe("null when the audit could not be read")
3799
4028
  },
3800
4029
  annotations: READ_ONLY
@@ -3850,13 +4079,13 @@ function registerAgentReadTools(server, client) {
3850
4079
  {
3851
4080
  title: "Region history",
3852
4081
  description: "A region's published versions over time (newest first, which one is live) and whether the region is still found on the live page. Get the region id from list_components." + UNTRUSTED_FIELDS_NOTE,
3853
- inputSchema: { projectId: projectIdSchema, regionId: import_v319.z.string().describe("The region's id (the slot id shown by list_components)") },
4082
+ inputSchema: { projectId: projectIdSchema, regionId: import_v320.z.string().describe("The region's id (the slot id shown by list_components)") },
3854
4083
  outputSchema: {
3855
- regionId: import_v319.z.string(),
3856
- currentVersion: import_v319.z.number(),
3857
- versions: import_v319.z.array(import_v319.z.object({ version: import_v319.z.number(), publishedAt: import_v319.z.string().nullable(), isCurrent: import_v319.z.boolean() })),
3858
- recentDecisions: import_v319.z.array(import_v319.z.object({ action: import_v319.z.string(), at: import_v319.z.string().nullable() })),
3859
- drift: import_v319.z.object({ verdict: import_v319.z.string(), message: import_v319.z.string(), checkedUrl: import_v319.z.string().nullable() }).nullable().describe("Whether the region is still found on the live page; null when the check could not run")
4084
+ regionId: import_v320.z.string(),
4085
+ currentVersion: import_v320.z.number(),
4086
+ versions: import_v320.z.array(import_v320.z.object({ version: import_v320.z.number(), publishedAt: import_v320.z.string().nullable(), isCurrent: import_v320.z.boolean() })),
4087
+ recentDecisions: import_v320.z.array(import_v320.z.object({ action: import_v320.z.string(), at: import_v320.z.string().nullable() })),
4088
+ drift: import_v320.z.object({ verdict: import_v320.z.string(), message: import_v320.z.string(), checkedUrl: import_v320.z.string().nullable() }).nullable().describe("Whether the region is still found on the live page; null when the check could not run")
3860
4089
  },
3861
4090
  annotations: READ_ONLY
3862
4091
  },
@@ -3890,7 +4119,7 @@ function registerAgentReadTools(server, client) {
3890
4119
  }
3891
4120
 
3892
4121
  // src/tools/manage.ts
3893
- var import_v320 = require("zod/v3");
4122
+ var import_v321 = require("zod/v3");
3894
4123
  var a = (method, route, extra = {}) => __spreadValues({ method, route }, extra);
3895
4124
  var ACTIONS = {
3896
4125
  manage_generation: {
@@ -4028,13 +4257,13 @@ function registerManageTools(server, client) {
4028
4257
  const meta = TOOLS[tool];
4029
4258
  const shape = {
4030
4259
  projectId: projectIdSchema,
4031
- action: import_v320.z.enum(names).describe("What to do. Each action needs only the fields noted below."),
4032
- enabled: import_v320.z.boolean().optional().describe("For set_auto_fill, set_require_approval, set_observation_mode: on (true) or off (false)"),
4033
- body: import_v320.z.record(import_v320.z.unknown()).optional().describe("The fields to send, for actions that change several things at once; the API checks them and says what's wrong")
4260
+ action: import_v321.z.enum(names).describe("What to do. Each action needs only the fields noted below."),
4261
+ enabled: import_v321.z.boolean().optional().describe("For set_auto_fill, set_require_approval, set_observation_mode: on (true) or off (false)"),
4262
+ body: import_v321.z.record(import_v321.z.unknown()).optional().describe("The fields to send, for actions that change several things at once; the API checks them and says what's wrong")
4034
4263
  };
4035
- if (tool === "manage_generation") shape.depth = import_v320.z.enum(["auto", "rewrite", "redesign"]).optional().describe("For set_depth: how far a rewrite may go");
4036
- if (tool === "manage_settings") shape.origin = import_v320.z.string().optional().describe("For remove_origin: the origin to stop allowing, e.g. https://example.com");
4037
- for (const p of paramNames(tool)) shape[p] = import_v320.z.string().optional().describe(`Required by the actions whose route has :${p}`);
4264
+ if (tool === "manage_generation") shape.depth = import_v321.z.enum(["auto", "rewrite", "redesign"]).optional().describe("For set_depth: how far a rewrite may go");
4265
+ if (tool === "manage_settings") shape.origin = import_v321.z.string().optional().describe("For remove_origin: the origin to stop allowing, e.g. https://example.com");
4266
+ for (const p of paramNames(tool)) shape[p] = import_v321.z.string().optional().describe(`Required by the actions whose route has :${p}`);
4038
4267
  server.registerTool(
4039
4268
  tool,
4040
4269
  {
@@ -4074,8 +4303,32 @@ function registerManageTools(server, client) {
4074
4303
  }
4075
4304
  }
4076
4305
 
4306
+ // src/instructions.ts
4307
+ var SERVER_INSTRUCTIONS = `SentientUI serves each visitor the version of each adaptive component that works best for their audience, measured against a control group kept on the original.
4308
+
4309
+ Audiences, and what makes each one serve (precedence: declared > retargeting > discovered > campaign > arrival > everyone):
4310
+ - everyone (key "unknown"): every visitor no other audience claims.
4311
+ - Declared persona (bare key, e.g. "developer"): serves ONLY on visits where the site declares it \u2014 the persona prop on <AdaptiveRoot>/<AdaptiveProvider>, init({ persona }) in @sentientui/core, or window.sentient.persona on the script tag. Adding it to the vocabulary only names it; a declared persona the site never sends has no visitors and nobody sees its versions. Undeclared visitors are never guessed into one. Use declared personas for roles the site knows (signed-in users).
4312
+ - Discovered audience ("d-" key): found in behaviour; serves only after it is promoted (evidence that it wants something different).
4313
+ - Campaign, arrival type, retargeting group ("c-", "a-", "r-" keys): visitors who arrived on a named campaign link, arrived a certain way, or were moved into a retargeting group. This is how to reach anonymous traffic.
4314
+ - get_persona_breakdown personas counts the audience each visit was actually served as (the same number as the Matrix share in get_cell_matrix). Its behaviourGroups ("Behaviour group N") are visitors who behaved alike: not personas or audiences, they serve nothing \u2014 never report one as an audience's visitors.
4315
+ - A version's name, or a code variants key, never targets an audience. To give one audience one version, pin it (manage_approvals pin); pinned visitors stop teaching the optimizer for that component.
4316
+
4317
+ Components: an <Adaptive> with children and variants whose id already ran a variants test keeps serving that old test; dashboard-written or generated versions for it do not serve until it is migrated (dashboard Matrix -> Components -> Migrate..., or manage_tests migrate_component).
4318
+
4319
+ Funnels: every step must have something that sends it (a page-visit rule, a click or form goal, useGoal in the browser, or trackServerGoal from the server), or that step never fills.
4320
+
4321
+ Server goal, exact shape (server only, never the browser):
4322
+ import { trackServerGoal } from '@sentientui/react/server'; // or '@sentientui/core/server'
4323
+ await trackServerGoal({ serverKey: process.env.SENTIENT_SECRET_KEY!, userId: user.id, name: 'subscribed', dedupeKey: user.id });
4324
+ userId must be the id the site identifies the visitor with (<AdaptiveRoot userId={user.id}>); in the visitor's own request pass sessionId: readSessionCookie(cookies, publicKey) instead.
4325
+
4326
+ Excluding the team and test sites (dashboard Settings -> Internal traffic): visits marked internal still see versions (QA works) but never count in any report and never teach the optimizer; get_traffic_breakdown lists them as "Your team / test sites". They are marked by internal sites (allowed domains such as staging or localhost), team emails and domains (they match visitors the site identifies with identify(userId, { email }); the SDK sends only a SHA-256 of the address and its domain, never the address), a browser link, or the code flag (the internal prop on <AdaptiveRoot>/<AdaptiveProvider>, init({ internal }), window.sentient.internal). There is no report filter or IP rule, and visits from before a rule was turned on cannot be separated. Read the rules with get_internal_traffic_rules; a person changes them in the dashboard.
4327
+
4328
+ Write tools change what real visitors see: confirm with the user first. Call get_agent_access before a manage_* write.`;
4329
+
4077
4330
  // src/server.ts
4078
- var PKG_VERSION = true ? "0.26.0" : "0.0.0-dev";
4331
+ var PKG_VERSION = true ? "0.27.0" : "0.0.0-dev";
4079
4332
  function createMcpServer(client) {
4080
4333
  const server = new import_mcp.McpServer(
4081
4334
  {
@@ -4093,7 +4346,11 @@ function createMcpServer(client) {
4093
4346
  mimeTypes: [RESOURCE_MIME_TYPE]
4094
4347
  }
4095
4348
  }
4096
- }
4349
+ },
4350
+ // Sent in the initialize result: the facts an agent otherwise gets
4351
+ // wrong (which audiences serve, clusters are not personas, hybrids need
4352
+ // Migrate, the server goal call shape). See instructions.ts.
4353
+ instructions: SERVER_INSTRUCTIONS
4097
4354
  }
4098
4355
  );
4099
4356
  registerUiResources(server);
@@ -4112,6 +4369,7 @@ function createMcpServer(client) {
4112
4369
  registerIntegrationGuideTools(server);
4113
4370
  registerAgentTrafficTools(server, client);
4114
4371
  registerTrafficTools(server, client);
4372
+ registerInternalTrafficTools(server, client);
4115
4373
  registerCellTools(server, client);
4116
4374
  registerAgentReadTools(server, client);
4117
4375
  registerManageTools(server, client);