@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/lib.cjs CHANGED
@@ -447,7 +447,7 @@ function registerProjectTools(server, client) {
447
447
  "get_project_stats",
448
448
  {
449
449
  title: "Project health stats",
450
- 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.",
450
+ 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.`,
451
451
  inputSchema: { projectId: projectIdSchema },
452
452
  outputSchema: {
453
453
  status: import_v32.z.string().describe("Overall project health status"),
@@ -458,11 +458,23 @@ function registerProjectTools(server, client) {
458
458
  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"),
459
459
  beingAnalysed: import_v32.z.number().nullable().describe("Visitors still being analysed \u2014 usually settled within 3 hours; null on an older API"),
460
460
  automated: import_v32.z.number().nullable().describe("Automated visitors: AI assistants, search & AI crawlers and other automated; null on an older API"),
461
+ 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"),
461
462
  // Was "Total agent (MCP/API) calls" — but the count comes from
462
463
  // agent_events, which only the /v1/agent endpoint writes. MCP tool calls
463
464
  // are never in it, so an agent read its own activity as missing.
464
465
  agentCalls: import_v32.z.number().describe("All-time calls to the /v1/agent agent API (not MCP tool calls)"),
465
- lastEventAt: import_v32.z.string().nullable().describe("ISO timestamp of the last event, or null")
466
+ lastEventAt: import_v32.z.string().nullable().describe("ISO timestamp of the last event, or null"),
467
+ rejectedOrigins: import_v32.z.array(
468
+ import_v32.z.object({
469
+ origin: import_v32.z.string(),
470
+ minutesWithTraffic: import_v32.z.number().describe("Minutes in which visits were turned away \u2014 recorded at most once a minute, NOT a request count"),
471
+ firstSeenAt: import_v32.z.string(),
472
+ lastSeenAt: import_v32.z.string(),
473
+ message: import_v32.z.string()
474
+ })
475
+ ).describe(
476
+ "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."
477
+ )
466
478
  },
467
479
  annotations: {
468
480
  readOnlyHint: true,
@@ -471,20 +483,38 @@ function registerProjectTools(server, client) {
471
483
  }
472
484
  },
473
485
  withApiErrorGuidance(async ({ projectId }) => {
474
- var _a, _b, _c, _d, _e, _f, _g;
486
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
475
487
  const id = encodeURIComponent(projectId);
476
488
  const stats = await client.get(`/projects/${id}/health`);
477
- const peopleCount = (_b = stats.people) != null ? _b : (_a = stats.traffic) == null ? void 0 : _a.people;
489
+ const rejectedOrigins = ((_a = stats.rejectedOrigins) != null ? _a : []).map((r) => ({
490
+ origin: r.origin,
491
+ minutesWithTraffic: r.count,
492
+ firstSeenAt: r.firstSeenAt,
493
+ lastSeenAt: r.lastSeenAt,
494
+ message: r.message
495
+ }));
496
+ const peopleCount = (_c = stats.people) != null ? _c : (_b = stats.traffic) == null ? void 0 : _b.people;
478
497
  const classified = peopleCount !== void 0;
479
498
  const people = classified ? peopleCount : null;
480
- const beingAnalysed = classified ? (_d = (_c = stats.traffic) == null ? void 0 : _c.beingAnalysed) != null ? _d : 0 : null;
481
- const automated = classified ? (_f = (_e = stats.traffic) == null ? void 0 : _e.automated) != null ? _f : 0 : null;
499
+ const beingAnalysed = classified ? (_e = (_d = stats.traffic) == null ? void 0 : _d.beingAnalysed) != null ? _e : 0 : null;
500
+ const automated = classified ? (_g = (_f = stats.traffic) == null ? void 0 : _f.automated) != null ? _g : 0 : null;
501
+ const internalGroup = (_i = (_h = stats.traffic) == null ? void 0 : _h.groups) == null ? void 0 : _i.find((g) => g.group === "internal");
502
+ const internal = internalGroup ? internalGroup.count : null;
482
503
  const text2 = [
483
504
  `Status: ${stats.status}`,
484
505
  `Events (24h): ${stats.events24h}`,
485
- ...classified ? [`People (24h): ${people}`, `Being analysed: ${beingAnalysed}`, `Automated: ${automated}`] : [`Sessions (24h): ${stats.sessions24h}`],
506
+ ...classified ? [
507
+ `People (24h): ${people}`,
508
+ `Being analysed: ${beingAnalysed}`,
509
+ `Automated: ${automated}`,
510
+ ...internal !== null ? [`Your team / test sites (marked internal, not counted): ${internal}`] : []
511
+ ] : [`Sessions (24h): ${stats.sessions24h}`],
486
512
  `Agent API calls (/v1/agent, all-time): ${stats.agentCalls}`,
487
- `Last event: ${(_g = stats.lastEventAt) != null ? _g : "never"}`
513
+ `Last event: ${(_j = stats.lastEventAt) != null ? _j : "never"}`,
514
+ ...rejectedOrigins.length ? [
515
+ "Domains turned away (not on the allowed list \u2014 fix with add_origin if they are your sites):",
516
+ ...rejectedOrigins.map((r) => `- ${r.message}`)
517
+ ] : []
488
518
  ].join("\n");
489
519
  return {
490
520
  content: [{ type: "text", text: text2 }],
@@ -495,8 +525,10 @@ function registerProjectTools(server, client) {
495
525
  people,
496
526
  beingAnalysed,
497
527
  automated,
528
+ internal,
498
529
  agentCalls: stats.agentCalls,
499
- lastEventAt: stats.lastEventAt
530
+ lastEventAt: stats.lastEventAt,
531
+ rejectedOrigins
500
532
  }
501
533
  };
502
534
  })
@@ -625,16 +657,26 @@ var BOOTSTRAP_JS = `
625
657
  var RENDER_JS = {
626
658
  "persona-breakdown": `
627
659
  window.__render = function(data){
628
- var clusters = (data && data.clusters) || [];
629
- var total = (data && data.totalSessions) || 0;
630
- el('sub').textContent = total + ' total sessions across ' + clusters.length + ' persona' + (clusters.length === 1 ? '' : 's');
631
- if (!clusters.length) { showEmpty('No persona clusters yet \u2014 more visitor data is needed.'); return; }
632
- var sorted = clusters.slice().sort(function(a,b){ return (b.sharePct||0) - (a.sharePct||0); });
633
- el('viz').innerHTML = sorted.map(function(c){
634
- var rel = Math.round((c.reliability || 0) * 100);
635
- return barRow(c.label, pct1(c.sharePct), c.sharePct,
636
- c.sessionCount + ' sessions \xB7 reliability ' + rel + '%');
660
+ // Served-as audiences (the Matrix share), then behaviour groups \u2014 kept
661
+ // apart: a behaviour group is visitors who behaved alike, never an
662
+ // audience, and it is never drawn under an audience's name.
663
+ var personas = (data && data.personas) || [];
664
+ var groups = (data && data.behaviourGroups) || [];
665
+ var total = (data && data.totalPeople) || 0;
666
+ el('sub').textContent = total + ' people by the audience they were served as, last ' + ((data && data.windowDays) || 30) + ' days';
667
+ if (!total && !groups.length) { showEmpty('No served visitors yet \u2014 nothing to break down.'); return; }
668
+ var html = personas.map(function(p){
669
+ return barRow(p.name, pct1(p.sharePct), p.sharePct, p.people + ' people');
637
670
  }).join('');
671
+ if (groups.length) {
672
+ var groupTotal = groups.reduce(function(a, g){ return a + (Number(g.people) || 0); }, 0);
673
+ html += '<p class="sub" style="margin-top:14px">Behaviour groups \u2014 visitors who behaved alike. Not audiences: nothing is shown to a group.</p>';
674
+ html += groups.map(function(g){
675
+ var share = groupTotal > 0 ? (g.people / groupTotal) * 100 : 0;
676
+ return barRow(g.name, g.people + ' people', share, g.description || '');
677
+ }).join('');
678
+ }
679
+ el('viz').innerHTML = html;
638
680
  };
639
681
  `,
640
682
  "variant-performance": `
@@ -957,7 +999,16 @@ function registerComponentTools(server, client) {
957
999
  total: import_v34.z.number().describe("Total components in the project \u2014 larger than the list when truncated"),
958
1000
  truncated: import_v34.z.boolean().describe("True when the fetch cap was hit before listing every component"),
959
1001
  regions: regionOutputSchema,
960
- window: windowOutputSchema
1002
+ window: windowOutputSchema,
1003
+ audienceNamedVersions: import_v34.z.array(
1004
+ import_v34.z.object({
1005
+ componentId: import_v34.z.string(),
1006
+ versionKey: import_v34.z.string(),
1007
+ personaKey: import_v34.z.string().describe("The declared audience the key is named after"),
1008
+ pinned: import_v34.z.boolean().describe("Already pinned to that audience"),
1009
+ nudge: import_v34.z.string().describe("What the dashboard says about it \u2014 quote it")
1010
+ })
1011
+ ).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")
961
1012
  },
962
1013
  annotations: {
963
1014
  readOnlyHint: true,
@@ -966,29 +1017,44 @@ function registerComponentTools(server, client) {
966
1017
  }
967
1018
  },
968
1019
  withApiErrorGuidance(async ({ projectId, range, from, to }) => {
969
- const [componentsRes, regionsRes] = await Promise.all([
1020
+ var _a;
1021
+ const [componentsRes, regionsRes, namedRes] = await Promise.all([
970
1022
  settled(fetchAllComponents(client, projectId, { rangeArgs: { range, from, to } })),
971
- settled(fetchRegions(client, projectId, { range, from, to }))
1023
+ settled(fetchRegions(client, projectId, { range, from, to })),
1024
+ // Task 6: `variants={{ developer }}` reads as "developer copy for
1025
+ // developers", and nothing told the developer a key targets nobody.
1026
+ // Additive and best-effort, like regions.
1027
+ settled(client.get(
1028
+ `/projects/${encodeURIComponent(projectId)}/audience-named-versions`
1029
+ ))
972
1030
  ]);
973
1031
  throwIfNotDegradable([componentsRes, regionsRes]);
974
1032
  if (!componentsRes.ok) throw componentsRes.error;
975
1033
  const { components, total, window, truncated } = componentsRes.value;
976
1034
  const regions = regionsRes.ok ? regionsRes.value : [];
1035
+ const audienceNamedVersions = namedRes.ok ? ((_a = namedRes.value.versions) != null ? _a : []).map((v) => ({
1036
+ componentId: v.componentId,
1037
+ versionKey: v.versionKey,
1038
+ personaKey: v.personaKey,
1039
+ pinned: v.pinned,
1040
+ nudge: v.nudge
1041
+ })) : [];
977
1042
  const structuredContent = {
978
1043
  components: components.map((c) => {
979
- var _a;
1044
+ var _a2;
980
1045
  return {
981
1046
  componentId: c.component_id,
982
1047
  variantCount: c.variants.length,
983
1048
  impressions: c.total_impressions,
984
1049
  conversions: c.total_conversions,
985
- unconfirmedConversions: (_a = c.total_unconfirmed_conversions) != null ? _a : null
1050
+ unconfirmedConversions: (_a2 = c.total_unconfirmed_conversions) != null ? _a2 : null
986
1051
  };
987
1052
  }),
988
1053
  total,
989
1054
  truncated,
990
1055
  regions,
991
- window
1056
+ window,
1057
+ audienceNamedVersions
992
1058
  };
993
1059
  if (!components.length && !regions.length) {
994
1060
  return {
@@ -1008,6 +1074,11 @@ function registerComponentTools(server, client) {
1008
1074
  for (const r of regions) lines.push(regionText(r, untrusted));
1009
1075
  }
1010
1076
  if (!regionsRes.ok) lines.push("", "Regions could not be read just now \u2014 components served per visitor may be missing from this list.");
1077
+ const unpinned = audienceNamedVersions.filter((v) => !v.pinned);
1078
+ if (unpinned.length) {
1079
+ lines.push("", "Versions named after your audiences (a name doesn't target anyone):");
1080
+ for (const v of unpinned) lines.push(`- ${untrusted(v.componentId)} / ${untrusted(v.versionKey)}: ${v.nudge}`);
1081
+ }
1011
1082
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent };
1012
1083
  })
1013
1084
  );
@@ -1349,27 +1420,41 @@ function registerInsightTools(server, client) {
1349
1420
 
1350
1421
  // src/tools/personas.ts
1351
1422
  var import_v36 = require("zod/v3");
1423
+ function behaviourGroupName(label) {
1424
+ if (label == null || label === "" || label === "unclustered") return "Not grouped yet";
1425
+ const m = /^behaviour-(\d{1,4})$/.exec(label);
1426
+ return m ? `Behaviour group ${Number(m[1])}` : "Behaviour group";
1427
+ }
1352
1428
  function registerPersonaTools(server, client) {
1353
1429
  server.registerTool(
1354
1430
  "get_persona_breakdown",
1355
1431
  {
1356
1432
  title: "Persona breakdown",
1357
- // Takes no range/from/to on purpose: the API computes it over every
1358
- // retained session and has no window. Saying so stops an agent from
1359
- // reading it beside a 7d get_variant_performance as the same period.
1360
- 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,
1433
+ // Counted portrait clusters by a label named after the declared
1434
+ // personas until 2026-11-04, so an agent could report "Developer: 410
1435
+ // visitors" while the Matrix showed 0% for Developer. It now reads the
1436
+ // API's served-as breakdown — the Matrix share column's own numbers.
1437
+ 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,
1361
1438
  inputSchema: { projectId: projectIdSchema },
1362
1439
  _meta: uiMeta("persona-breakdown"),
1363
1440
  outputSchema: {
1364
- totalSessions: import_v36.z.number().describe("Total sessions across all clusters"),
1365
- clusters: import_v36.z.array(
1441
+ windowDays: import_v36.z.number().describe("Window in days (30)"),
1442
+ totalPeople: import_v36.z.number().describe("People with a served decision in the window \u2014 the share denominator"),
1443
+ personas: import_v36.z.array(
1444
+ import_v36.z.object({
1445
+ key: import_v36.z.string().describe("Persona key served (`unknown` = Everyone)"),
1446
+ name: import_v36.z.string().describe('Kind + name as the Matrix row reads it, e.g. "Declared: Developer"'),
1447
+ people: import_v36.z.number(),
1448
+ sharePct: import_v36.z.number().describe("Share of totalPeople (0-100) \u2014 the Matrix share")
1449
+ })
1450
+ ).describe("Everyone, then every Matrix audience row (zeros included), then any other served audience"),
1451
+ behaviourGroups: import_v36.z.array(
1366
1452
  import_v36.z.object({
1367
- label: import_v36.z.string(),
1368
- sessionCount: import_v36.z.number(),
1369
- sharePct: import_v36.z.number().describe("Share of total traffic (0-100)"),
1370
- reliability: import_v36.z.number().describe("Average cluster reliability (0-1)")
1453
+ name: import_v36.z.string().describe('"Behaviour group N" \u2014 never an audience'),
1454
+ description: import_v36.z.string().nullable(),
1455
+ people: import_v36.z.number()
1371
1456
  })
1372
- ).describe("Persona clusters (empty until enough visitor data)")
1457
+ ).describe("Visitors who behaved alike. Not audiences: nothing is served or targeted by them")
1373
1458
  },
1374
1459
  annotations: {
1375
1460
  readOnlyHint: true,
@@ -1379,33 +1464,21 @@ function registerPersonaTools(server, client) {
1379
1464
  },
1380
1465
  withApiErrorGuidance(async ({ projectId }) => {
1381
1466
  const id = encodeURIComponent(projectId);
1382
- const data = await client.get(`/projects/${id}/portraits`);
1467
+ const data = await client.get(`/projects/${id}/persona-breakdown`);
1383
1468
  const structuredContent = {
1384
- totalSessions: data.totalSessions,
1385
- clusters: data.clusters.map((c) => ({
1386
- label: c.label,
1387
- sessionCount: c.sessionCount,
1388
- sharePct: data.totalSessions > 0 ? c.sessionCount / data.totalSessions * 100 : 0,
1389
- reliability: c.avgReliability
1390
- }))
1469
+ windowDays: data.windowDays,
1470
+ totalPeople: data.totalPeople,
1471
+ personas: data.personas.map((p) => ({ key: p.key, name: p.name, people: p.people, sharePct: p.sharePct })),
1472
+ behaviourGroups: data.behaviourGroups.map((g) => ({ name: g.name, description: g.description, people: g.people }))
1391
1473
  };
1392
- if (!data.clusters.length) {
1393
- return {
1394
- content: [{ type: "text", text: "No persona clusters yet. More visitor data is needed." }],
1395
- structuredContent,
1396
- _meta: uiMeta("persona-breakdown")
1397
- };
1398
- }
1399
1474
  const lines = [
1400
- `Total sessions: ${data.totalSessions}`,
1475
+ `Visitors by the audience they were served as (last ${data.windowDays} days, ${data.totalPeople} people \u2014 same numbers as the Matrix share):`,
1476
+ // Audience names are customer-written — delimit them so a crafted
1477
+ // name can't pose as tool output (see untrusted()).
1478
+ ...data.totalPeople === 0 ? ["- No served decisions yet in this window."] : data.personas.map((p) => `- ${untrusted(p.name)}: ${p.people} people (${p.sharePct.toFixed(1)}%)`),
1401
1479
  "",
1402
- "Clusters:",
1403
- // Cluster labels derive from visitor behaviour — delimit them so a
1404
- // crafted label can't pose as tool output (see untrusted()).
1405
- ...data.clusters.map((c) => {
1406
- const pct3 = data.totalSessions > 0 ? c.sessionCount / data.totalSessions * 100 : 0;
1407
- return `- ${untrusted(c.label)}: ${c.sessionCount} sessions (${pct3.toFixed(1)}% of traffic, reliability ${(c.avgReliability * 100).toFixed(0)}%)`;
1408
- })
1480
+ "Behaviour groups (visitors who behaved alike \u2014 NOT audiences; nothing is shown to a group):",
1481
+ ...data.behaviourGroups.length === 0 ? ["- None yet."] : data.behaviourGroups.map((g) => `- ${g.name}: ${g.people} people${g.description ? ` \u2014 ${g.description}` : ""}`)
1409
1482
  ];
1410
1483
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent, _meta: uiMeta("persona-breakdown") };
1411
1484
  })
@@ -1835,6 +1908,12 @@ function stepChangeText(dropOffFromPrevious) {
1835
1908
  }
1836
1909
  return ` (${Math.round(dropOffFromPrevious * 100)}% drop-off from previous)`;
1837
1910
  }
1911
+ 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.");
1912
+ function stepSourceText(goalId, tracking, definedDaysAgo) {
1913
+ if (tracking === "none") return `Nothing sends ${untrusted(goalId)} yet`;
1914
+ if (tracking === "silent") return `${untrusted(goalId)} is set up but nothing has recorded it in ${definedDaysAgo != null ? definedDaysAgo : 7} days`;
1915
+ return null;
1916
+ }
1838
1917
  function registerFunnelTools(server, client) {
1839
1918
  server.registerTool(
1840
1919
  "list_funnels",
@@ -1854,7 +1933,9 @@ function registerFunnelTools(server, client) {
1854
1933
  import_v39.z.object({
1855
1934
  stepIndex: import_v39.z.number(),
1856
1935
  goalId: import_v39.z.string(),
1857
- weight: import_v39.z.number().nullable().describe("Manual optimizer credit for reaching this step (null = automatic end-weighted)")
1936
+ weight: import_v39.z.number().nullable().describe("Manual optimizer credit for reaching this step (null = automatic end-weighted)"),
1937
+ tracking: trackingSchema,
1938
+ definedDaysAgo: import_v39.z.number().nullable().describe("Days since an unfired goal was set up (null once it fires)")
1858
1939
  })
1859
1940
  ).describe("Ordered steps"),
1860
1941
  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)")
@@ -1875,11 +1956,16 @@ function registerFunnelTools(server, client) {
1875
1956
  windowDays: f.window_days,
1876
1957
  source: f.source,
1877
1958
  // NUMERIC arrives serialized as a string; coerce.
1878
- steps: f.steps.map((s) => ({
1879
- stepIndex: s.step_index,
1880
- goalId: s.goal_id,
1881
- weight: s.weight == null ? null : Number(s.weight)
1882
- })),
1959
+ steps: f.steps.map((s) => {
1960
+ var _a2, _b;
1961
+ return {
1962
+ stepIndex: s.step_index,
1963
+ goalId: s.goal_id,
1964
+ weight: s.weight == null ? null : Number(s.weight),
1965
+ tracking: (_a2 = s.tracking) != null ? _a2 : null,
1966
+ definedDaysAgo: (_b = s.defined_days_ago) != null ? _b : null
1967
+ };
1968
+ }),
1883
1969
  components: f.components.map((c) => {
1884
1970
  var _a2;
1885
1971
  return { componentId: c.component_id, stepIndex: (_a2 = c.step_index) != null ? _a2 : null };
@@ -1895,10 +1981,20 @@ function registerFunnelTools(server, client) {
1895
1981
  structuredContent
1896
1982
  };
1897
1983
  }
1898
- const lines = structuredContent.funnels.map(
1899
- (f) => `${untrusted(f.funnelId)} (${f.status}) \u2014 ${untrusted(f.displayName)}: ${f.steps.map((s) => untrusted(s.goalId)).join(" \u2192 ")}`
1900
- );
1984
+ const lines = [];
1985
+ let anyUnsourced = false;
1986
+ for (const f of structuredContent.funnels) {
1987
+ lines.push(`${untrusted(f.funnelId)} (${f.status}) \u2014 ${untrusted(f.displayName)}: ${f.steps.map((s) => untrusted(s.goalId)).join(" \u2192 ")}`);
1988
+ for (const s of f.steps) {
1989
+ const note = stepSourceText(s.goalId, s.tracking, s.definedDaysAgo);
1990
+ if (note) lines.push(` step ${s.stepIndex + 1}: ${note}`);
1991
+ if (s.tracking === "none") anyUnsourced = true;
1992
+ }
1993
+ }
1901
1994
  lines.push("", 'Reference a funnelId verbatim from code: <Adaptive funnel="<funnelId>">. Use get_funnel_report for drop-off numbers.');
1995
+ if (anyUnsourced) {
1996
+ 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.");
1997
+ }
1902
1998
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent };
1903
1999
  })
1904
2000
  );
@@ -1922,7 +2018,14 @@ function registerFunnelTools(server, client) {
1922
2018
  reached: import_v39.z.number().describe("Distinct People reaching this step in-window"),
1923
2019
  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"),
1924
2020
  dropOffFromPrevious: import_v39.z.number().nullable().describe("1 - reached/previousReached (null on the first step)"),
1925
- neverFired: import_v39.z.boolean().describe("True when the step goal has never been recorded anywhere \u2014 likely a typo"),
2021
+ neverFired: import_v39.z.boolean().describe("Legacy: no definition in any status and never recorded. Prefer tracking"),
2022
+ tracking: trackingSchema,
2023
+ definedDaysAgo: import_v39.z.number().nullable().describe("Days since an unfired goal was set up (null once it fires)"),
2024
+ fromCode: import_v39.z.object({
2025
+ client: import_v39.z.string().describe("Browser code: useGoal from @sentientui/react"),
2026
+ server: import_v39.z.string().describe("Server code: trackServerGoal from @sentientui/react/server"),
2027
+ serverCall: import_v39.z.string()
2028
+ }).nullable().describe("Exact code that sends this step's goal, present until it first fires. Repeat it verbatim."),
1926
2029
  variants: import_v39.z.array(import_v39.z.object({
1927
2030
  componentId: import_v39.z.string(),
1928
2031
  variantId: import_v39.z.string(),
@@ -1941,13 +2044,19 @@ function registerFunnelTools(server, client) {
1941
2044
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1942
2045
  },
1943
2046
  withApiErrorGuidance(async ({ projectId, funnelId }) => {
1944
- var _a, _b;
2047
+ var _a, _b, _c;
1945
2048
  const data = await client.get(`/projects/${encodeURIComponent(projectId)}/funnels/${encodeURIComponent(funnelId)}/report`);
1946
2049
  const lines = [`${untrusted(data.displayName)} \u2014 last ${data.windowDays} days`];
1947
2050
  for (const s of data.steps) {
2051
+ const tracking = (_a = s.tracking) != null ? _a : s.neverFired ? "none" : null;
2052
+ const note = stepSourceText(s.goalId, tracking, s.definedDaysAgo);
1948
2053
  lines.push(
1949
- `${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]" : "")
2054
+ `${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}]` : "")
1950
2055
  );
2056
+ if (tracking === "none" && s.fromCode && codeSafe(s.goalId) === s.goalId) {
2057
+ lines.push(" Send it from your server:", ...s.fromCode.server.split("\n").map((l) => ` ${l}`));
2058
+ lines.push(" \u2026or from the browser:", ...s.fromCode.client.split("\n").map((l) => ` ${l}`));
2059
+ }
1951
2060
  for (const v of s.variants) {
1952
2061
  lines.push(` ${untrusted(v.componentId)}/${untrusted(v.variantId)}: ${v.reached}/${v.assigned} assigned sessions reached this step`);
1953
2062
  }
@@ -1966,11 +2075,16 @@ function registerFunnelTools(server, client) {
1966
2075
  content: [{ type: "text", text: lines.join("\n") }],
1967
2076
  // Tolerate an API deployed before strict funnels existed.
1968
2077
  structuredContent: __spreadProps(__spreadValues({}, data), {
1969
- strictOrder: (_a = data.strictOrder) != null ? _a : true,
1970
- unconfirmedRevenue: (_b = data.unconfirmedRevenue) != null ? _b : null,
2078
+ strictOrder: (_b = data.strictOrder) != null ? _b : true,
2079
+ unconfirmedRevenue: (_c = data.unconfirmedRevenue) != null ? _c : null,
1971
2080
  steps: data.steps.map((s) => {
1972
- var _a2;
1973
- return __spreadProps(__spreadValues({}, s), { unconfirmedReached: (_a2 = s.unconfirmedReached) != null ? _a2 : null });
2081
+ var _a2, _b2, _c2, _d;
2082
+ return __spreadProps(__spreadValues({}, s), {
2083
+ unconfirmedReached: (_a2 = s.unconfirmedReached) != null ? _a2 : null,
2084
+ tracking: (_b2 = s.tracking) != null ? _b2 : null,
2085
+ definedDaysAgo: (_c2 = s.definedDaysAgo) != null ? _c2 : null,
2086
+ fromCode: (_d = s.fromCode) != null ? _d : null
2087
+ });
1974
2088
  })
1975
2089
  })
1976
2090
  };
@@ -2589,10 +2703,10 @@ function registerVariantBriefTools(server, client) {
2589
2703
  lines.push("");
2590
2704
  }
2591
2705
  if (clusters.length) {
2592
- lines.push(`Audience (${totalSessions} sessions):`);
2706
+ lines.push(`Behaviour groups (visitors who behaved alike \u2014 not audiences; ${totalSessions} sessions):`);
2593
2707
  for (const c of clusters) {
2594
2708
  const share = totalSessions > 0 ? (c.sessionCount / totalSessions * 100).toFixed(0) : "0";
2595
- lines.push(`- ${untrusted(c.label)}: ${share}% of traffic, ${c.sessionCount} sessions (reliability ${(c.avgReliability * 100).toFixed(0)}%)`);
2709
+ lines.push(`- ${behaviourGroupName(c.label)}: ${share}% of traffic, ${c.sessionCount} sessions (reliability ${(c.avgReliability * 100).toFixed(0)}%)`);
2596
2710
  }
2597
2711
  lines.push("");
2598
2712
  }
@@ -2777,11 +2891,14 @@ var import_v315 = require("zod/v3");
2777
2891
  var GUIDE = `# SentientUI integration guide \u2014 the adaptive ladder
2778
2892
 
2779
2893
  SentientUI adapts a site per visitor type (personas), learning from real conversions. Each
2780
- project has its own persona vocabulary (dashboard -> Settings -> Personas), and it starts
2781
- EMPTY: every visitor is 'unknown' until a persona exists, and the optimizer learns across all
2782
- traffic pooled in the meantime. Personas are DISCOVERED from behavior \u2014 or, far faster,
2783
- DECLARED by the app when it already knows the visitor's role: init({ persona: 'admin' }) /
2784
- <AdaptiveProvider persona=...> / window.sentient.persona. Declared beats discovered and serves
2894
+ project has its own persona vocabulary (dashboard -> Matrix -> Audiences), and it starts
2895
+ EMPTY: every visitor is 'unknown' (Everyone) until a persona exists, and the optimizer learns
2896
+ across all traffic pooled in the meantime. A visit is served as ONE persona, in order: DECLARED
2897
+ by the app when it already knows the visitor's role (init({ persona: 'admin' }) /
2898
+ <AdaptiveProvider persona=...> / window.sentient.persona), a running retargeting group, a
2899
+ DISCOVERED audience the visitor confidently belongs to, a campaign / arrival type, else
2900
+ Everyone. Behaviour groups (visitors who behaved alike, from portraits) are reporting only \u2014
2901
+ nothing is served to them and they are never personas. Declared beats everything and serves
2785
2902
  at full confidence; unrecognized values are ignored server-side and surfaced in the dashboard
2786
2903
  so the operator can add them. Keep persona a low-cardinality role slug \u2014 never a user id.
2787
2904
  Decisions are locked per visit: a first visit usually sees the original and the return visit adapts \u2014 the
@@ -2867,6 +2984,11 @@ Code variants \u2014 when you write the alternatives yourself:
2867
2984
  });
2868
2985
  return <div {...bind}>{value}</div>;
2869
2986
 
2987
+ Variant keys are versions, not audiences: naming one \`developer\` does NOT show it to
2988
+ developers \u2014 the optimizer may show any version to anyone. To show it to Developers, declare
2989
+ the persona on the site, then pin the version to that audience (Migrate the component in
2990
+ Matrix -> Components; the last step offers the pins).
2991
+
2870
2992
  Children or variants on one <Adaptive>, never both. With the hook, always attach bind \u2014 it
2871
2993
  wires exposure tracking and goal listeners. <AdaptiveText> swaps dashboard-managed text.
2872
2994
 
@@ -3141,14 +3263,14 @@ function registerTrafficTools(server, client) {
3141
3263
  "get_traffic_breakdown",
3142
3264
  {
3143
3265
  title: "Traffic breakdown",
3144
- 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,
3266
+ 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,
3145
3267
  inputSchema: { projectId: projectIdSchema, range: trafficRangeSchema },
3146
3268
  outputSchema: {
3147
3269
  window: import_v317.z.object({ from: import_v317.z.string(), to: import_v317.z.string() }),
3148
3270
  total: import_v317.z.number().describe("Visitors in the window; the groups add up to this"),
3149
3271
  groups: import_v317.z.array(
3150
3272
  import_v317.z.object({
3151
- group: import_v317.z.string().describe("people | loaded_no_interaction | not_verified | being_analysed | ai_assistant | crawler | other_automated"),
3273
+ group: import_v317.z.string().describe("people | loaded_no_interaction | not_verified | being_analysed | ai_assistant | crawler | other_automated | internal"),
3152
3274
  label: import_v317.z.string(),
3153
3275
  count: import_v317.z.number(),
3154
3276
  evidence: import_v317.z.array(import_v317.z.object({ code: import_v317.z.string(), label: import_v317.z.string(), count: import_v317.z.number() }))
@@ -3164,7 +3286,7 @@ function registerTrafficTools(server, client) {
3164
3286
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3165
3287
  },
3166
3288
  withApiErrorGuidance(async ({ projectId, range }) => {
3167
- var _a, _b, _c;
3289
+ var _a, _b, _c, _d, _e;
3168
3290
  const id = encodeURIComponent(projectId);
3169
3291
  const t = await client.get(`/projects/${id}/traffic${range ? `?range=${encodeURIComponent(range)}` : ""}`);
3170
3292
  const beingAnalysed = (_b = (_a = t.groups.find((g) => g.group === "being_analysed")) == null ? void 0 : _a.count) != null ? _b : 0;
@@ -3172,6 +3294,10 @@ function registerTrafficTools(server, client) {
3172
3294
  `Traffic from ${t.window.from.slice(0, 10)} to ${t.window.to.slice(0, 10)}: ${t.total} visitors.`,
3173
3295
  ...t.groups.map((g) => `- ${g.label}: ${g.count}`)
3174
3296
  ];
3297
+ const internal = (_d = (_c = t.groups.find((g) => g.group === "internal")) == null ? void 0 : _c.count) != null ? _d : 0;
3298
+ if (internal > 0) {
3299
+ 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.`);
3300
+ }
3175
3301
  if (beingAnalysed > 0) {
3176
3302
  lines.push("", `${beingAnalysed} visitors are being analysed \u2014 usually settled within 3 hours`);
3177
3303
  }
@@ -3179,7 +3305,7 @@ function registerTrafficTools(server, client) {
3179
3305
  lines.push("", "Named agents:", ...t.agents.map((a2) => `- ${untrusted(a2.name)}: ${a2.count}`));
3180
3306
  }
3181
3307
  lines.push("", `${t.conversions.total} conversions in total, ${t.conversions.fromPeople} from People.`);
3182
- for (const n of t.notices) lines.push((_c = NOTICE_TEXT[n]) != null ? _c : n);
3308
+ for (const n of t.notices) lines.push((_e = NOTICE_TEXT[n]) != null ? _e : n);
3183
3309
  return { content: [{ type: "text", text: lines.join("\n") }], structuredContent: t };
3184
3310
  }, {
3185
3311
  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."
@@ -3187,33 +3313,119 @@ function registerTrafficTools(server, client) {
3187
3313
  );
3188
3314
  }
3189
3315
 
3190
- // src/tools/cells.ts
3316
+ // src/tools/internal-traffic.ts
3191
3317
  var import_v318 = require("zod/v3");
3192
- var personaOutput = import_v318.z.object({
3193
- key: import_v318.z.string(),
3194
- displayName: import_v318.z.string(),
3195
- description: import_v318.z.string().nullable(),
3196
- share: import_v318.z.number().describe("Fraction of 30-day decided sessions")
3318
+ var INTERNAL_TRAFFIC_LABEL = "Your team / test sites";
3319
+ var REASONS = [
3320
+ { key: "site", words: "internal sites" },
3321
+ { key: "code", words: "code flag" },
3322
+ { key: "email_rule", words: "team emails" },
3323
+ { key: "domain_rule", words: "team domains" },
3324
+ { key: "browser", words: "browser link" }
3325
+ ];
3326
+ function registerInternalTrafficTools(server, client) {
3327
+ server.registerTool(
3328
+ "get_internal_traffic_rules",
3329
+ {
3330
+ title: "Internal traffic rules",
3331
+ 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.`,
3332
+ inputSchema: { projectId: projectIdSchema },
3333
+ outputSchema: {
3334
+ internalOrigins: import_v318.z.array(import_v318.z.string()).describe("Allowed domains whose every visit is marked internal"),
3335
+ allowedOrigins: import_v318.z.array(import_v318.z.string()).describe("Every allowed domain \u2014 only these can be made internal"),
3336
+ emailDomains: import_v318.z.array(import_v318.z.string()).describe("Email domains (no leading @) whose identified visitors are marked internal"),
3337
+ emails: import_v318.z.array(import_v318.z.string()).describe("Exact team emails, masked (c***@example.com); stored only as a hash"),
3338
+ 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)'),
3339
+ counts7d: import_v318.z.object({
3340
+ site: import_v318.z.number(),
3341
+ code: import_v318.z.number(),
3342
+ email_rule: import_v318.z.number(),
3343
+ domain_rule: import_v318.z.number(),
3344
+ browser: import_v318.z.number(),
3345
+ total: import_v318.z.number()
3346
+ }).describe("Sessions marked internal in the last 7 days, by the way that marked them first"),
3347
+ recordingSince: import_v318.z.string().nullable().describe("When sessions began recording which site they came from; visits before it cannot be separated")
3348
+ },
3349
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3350
+ },
3351
+ withApiErrorGuidance(async ({ projectId }) => {
3352
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
3353
+ const r = await client.get(
3354
+ `/projects/${encodeURIComponent(projectId)}/internal-traffic`
3355
+ );
3356
+ const internalOrigins = (_a = r.internalOrigins) != null ? _a : [];
3357
+ const allowedOrigins = (_b = r.allowedOrigins) != null ? _b : [];
3358
+ const emailDomains = (_c = r.emailDomains) != null ? _c : [];
3359
+ const emails = ((_d = r.emails) != null ? _d : []).map((e) => e.masked);
3360
+ const c = (_e = r.counts7d) != null ? _e : {};
3361
+ const counts7d = {
3362
+ site: (_f = c.site) != null ? _f : 0,
3363
+ code: (_g = c.code) != null ? _g : 0,
3364
+ email_rule: (_h = c.email_rule) != null ? _h : 0,
3365
+ domain_rule: (_i = c.domain_rule) != null ? _i : 0,
3366
+ browser: (_j = c.browser) != null ? _j : 0,
3367
+ total: (_k = c.total) != null ? _k : 0
3368
+ };
3369
+ const recordingSince = (_l = r.recordingSince) != null ? _l : null;
3370
+ const browserLinkExists = r.browserLink != null;
3371
+ const notInternal = allowedOrigins.filter((o) => !internalOrigins.includes(o));
3372
+ const lines = [
3373
+ `Internal traffic \u2014 reported as "${INTERNAL_TRAFFIC_LABEL}": these visits still see versions but never count and never teach the optimizer.`,
3374
+ `Internal sites: ${internalOrigins.length ? internalOrigins.join(", ") : "none"}.`,
3375
+ ...notInternal.length ? [`Allowed but counted normally: ${notInternal.join(", ")}.`] : [],
3376
+ `Team domains: ${emailDomains.length ? emailDomains.map((d) => `@${d}`).join(", ") : "none"}.`,
3377
+ `Team emails: ${emails.length ? emails.join(", ") : "none"} (stored only as a hash; they match visitors the site identifies with identify(userId, { email })).`,
3378
+ `Browser link: ${browserLinkExists ? "created \u2014 copy or rotate it in Settings \u2192 Internal traffic" : "not created"}.`,
3379
+ `Sessions marked internal, last 7 days: ${counts7d.total} (${REASONS.map((x) => `${x.words} ${counts7d[x.key]}`).join(", ")}).`,
3380
+ 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.",
3381
+ "To change these, a person uses Settings \u2192 Internal traffic in the dashboard."
3382
+ ];
3383
+ return {
3384
+ content: [{ type: "text", text: lines.join("\n") }],
3385
+ structuredContent: { internalOrigins, allowedOrigins, emailDomains, emails, browserLinkExists, counts7d, recordingSince }
3386
+ };
3387
+ })
3388
+ );
3389
+ }
3390
+
3391
+ // src/tools/cells.ts
3392
+ var import_v319 = require("zod/v3");
3393
+ var personaOutput = import_v319.z.object({
3394
+ key: import_v319.z.string(),
3395
+ displayName: import_v319.z.string(),
3396
+ description: import_v319.z.string().nullable(),
3397
+ share: import_v319.z.number().describe("Fraction of 30-day decided sessions"),
3398
+ // Both ride the API response; without them zod stripped them and an agent
3399
+ // reported a declared audience nothing declares as reachable.
3400
+ state: import_v319.z.string().optional().describe("everyone | declared | unlocked | candidate | starter \u2014 why the row exists"),
3401
+ declaredVisits14d: import_v319.z.number().nullable().optional().describe(
3402
+ "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."
3403
+ )
3197
3404
  });
3198
- var cellOutput = import_v318.z.object({
3199
- slotId: import_v318.z.string(),
3200
- persona: import_v318.z.string(),
3201
- status: import_v318.z.string().describe("pending | generating | review (waiting for approval) | live | error | rejected"),
3202
- requestedBy: import_v318.z.string(),
3203
- armId: import_v318.z.string().nullable(),
3204
- rationale: import_v318.z.string().nullable(),
3205
- error: import_v318.z.string().nullable(),
3206
- updatedAt: import_v318.z.string(),
3405
+ var blockedOutput = import_v319.z.enum(["variant_history"]).nullable().optional().describe(
3406
+ "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."
3407
+ );
3408
+ 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).";
3409
+ 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)";
3410
+ var cellOutput = import_v319.z.object({
3411
+ slotId: import_v319.z.string(),
3412
+ persona: import_v319.z.string(),
3413
+ status: import_v319.z.string().describe("pending | generating | review (waiting for approval) | live | error | rejected"),
3414
+ requestedBy: import_v319.z.string(),
3415
+ armId: import_v319.z.string().nullable(),
3416
+ rationale: import_v319.z.string().nullable(),
3417
+ error: import_v319.z.string().nullable(),
3418
+ updatedAt: import_v319.z.string(),
3207
3419
  // These ride the API response too; omitting them from the schema made zod
3208
3420
  // STRIP them, so agents could never see refinement or retry state.
3209
- 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"),
3210
- 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"),
3211
- attempts: import_v318.z.number().optional().describe("Generation attempts so far"),
3212
- performance: import_v318.z.object({
3213
- shown: import_v318.z.number(),
3214
- conversions: import_v318.z.number(),
3215
- deltaPct: import_v318.z.number().nullable().describe("Signed % vs the original conversion rate \u2014 a point estimate; only meaningful beside a winning/losing tier"),
3216
- tier: import_v318.z.string().describe(
3421
+ 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"),
3422
+ 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"),
3423
+ attempts: import_v319.z.number().optional().describe("Generation attempts so far"),
3424
+ performance: import_v319.z.object({
3425
+ shown: import_v319.z.number(),
3426
+ conversions: import_v319.z.number(),
3427
+ deltaPct: import_v319.z.number().nullable().describe("Signed % vs the original conversion rate \u2014 a point estimate; only meaningful beside a winning/losing tier"),
3428
+ tier: import_v319.z.string().describe(
3217
3429
  '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")'
3218
3430
  )
3219
3431
  }).optional().describe("Present on live cells (and, mid-refinement, the incumbent arm): the at-a-glance readout")
@@ -3226,28 +3438,29 @@ function registerCellTools(server, client) {
3226
3438
  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,
3227
3439
  inputSchema: { projectId: projectIdSchema },
3228
3440
  outputSchema: {
3229
- slots: import_v318.z.array(
3230
- import_v318.z.object({
3231
- slotId: import_v318.z.string(),
3232
- displayName: import_v318.z.string(),
3233
- supportsForms: import_v318.z.boolean(),
3441
+ slots: import_v319.z.array(
3442
+ import_v319.z.object({
3443
+ slotId: import_v319.z.string(),
3444
+ displayName: import_v319.z.string(),
3445
+ supportsForms: import_v319.z.boolean(),
3234
3446
  // API sends this; without it zod stripped the draft-vs-live signal.
3235
- live: import_v318.z.boolean().optional().describe("False for an sdk-registered draft column \u2014 nothing serves until its first generation publishes it")
3447
+ live: import_v319.z.boolean().optional().describe("False for an sdk-registered draft column \u2014 nothing serves until its first generation publishes it"),
3448
+ blocked: blockedOutput
3236
3449
  })
3237
3450
  ),
3238
- personas: import_v318.z.array(personaOutput),
3239
- cells: import_v318.z.array(cellOutput),
3240
- autoFill: import_v318.z.boolean(),
3451
+ personas: import_v319.z.array(personaOutput),
3452
+ cells: import_v319.z.array(cellOutput),
3453
+ autoFill: import_v319.z.boolean(),
3241
3454
  // The API has always sent this; without it in the schema zod stripped
3242
3455
  // it, and generate_cell had no way to know a version would wait for a
3243
3456
  // human instead of publishing.
3244
- reviewMode: import_v318.z.boolean().optional().describe("True when generated versions wait for approval (review_cell) instead of publishing automatically"),
3457
+ reviewMode: import_v319.z.boolean().optional().describe("True when generated versions wait for approval (review_cell) instead of publishing automatically"),
3245
3458
  // Nullable: a project with no persona set at all reports null, not a
3246
3459
  // string. That is the NORMAL state since the default vocabulary was
3247
3460
  // emptied, so a non-nullable schema failed output validation on most
3248
3461
  // projects and the tool returned nothing but a zod error.
3249
- 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)'),
3250
- undecidedShare: import_v318.z.number()
3462
+ 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)'),
3463
+ undecidedShare: import_v319.z.number()
3251
3464
  },
3252
3465
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3253
3466
  },
@@ -3256,22 +3469,27 @@ function registerCellTools(server, client) {
3256
3469
  const id = encodeURIComponent(projectId);
3257
3470
  const data = await client.get(`/projects/${id}/cells`);
3258
3471
  const byCell = new Map(data.cells.map((c) => [`${c.slotId}::${c.persona}`, c]));
3472
+ const blockedSlots = data.slots.filter((s) => s.blocked === "variant_history");
3259
3473
  const lines = [
3260
- `Slots: ${data.slots.map((s) => `${untrusted(s.displayName)}${s.live === false ? " [draft]" : ""}`).join(", ") || "(none published)"}`,
3474
+ `Slots: ${data.slots.map((s) => `${untrusted(s.displayName)}${s.live === false ? " [draft]" : ""}${s.blocked === "variant_history" ? " [not showing yet]" : ""}`).join(", ") || "(none published)"}`,
3475
+ ...blockedSlots.length > 0 ? [`${blockedSlots.map((s) => untrusted(s.displayName, 40)).join(", ")}: ${BLOCKED_LINE}`] : [],
3261
3476
  `Auto-fill on first miss: ${data.autoFill ? "ON" : "off"} \xB7 review before publishing: ${data.reviewMode ? "ON (approve with review_cell)" : "off"} \xB7 persona source: ${(_a = data.personaSource) != null ? _a : 'none (one "everyone" row)'}`
3262
3477
  ];
3263
3478
  for (const p of data.personas) {
3264
3479
  const states = data.slots.map((s) => {
3265
3480
  const c = byCell.get(`${s.slotId}::${p.key}`);
3266
3481
  let state = c ? c.status : "original";
3267
- if (c && (c.status === "pending" || c.status === "generating") && c.refinedFrom) {
3482
+ if (c && c.status === "live" && s.blocked === "variant_history") {
3483
+ state = "approved \u2014 not showing yet";
3484
+ } else if (c && (c.status === "pending" || c.status === "generating") && c.refinedFrom) {
3268
3485
  state = `${c.status} (improving on ${untrusted(c.refinedFrom, 64)} \u2014 current version still live)`;
3269
3486
  } else if (c && c.status === "pending" && c.notBefore && Date.parse(c.notBefore) > Date.now()) {
3270
3487
  state = `pending (waiting until ${c.notBefore})`;
3271
3488
  }
3272
3489
  return `${untrusted(s.displayName, 40)}: ${state}`;
3273
3490
  });
3274
- lines.push(`- ${untrusted(p.displayName)} (${Math.round(p.share * 100)}% of visitors) \u2014 ${states.join(" \xB7 ")}`);
3491
+ const undeclared = p.state === "declared" && p.declaredVisits14d === 0 ? ` [${NOT_DECLARED_LINE}]` : "";
3492
+ lines.push(`- ${untrusted(p.displayName)} (${Math.round(p.share * 100)}% of visitors)${undeclared} \u2014 ${states.join(" \xB7 ")}`);
3275
3493
  }
3276
3494
  lines.push(`Undecided visitors (${Math.round(data.undecidedShare * 100)}%) always see the original.`);
3277
3495
  return {
@@ -3287,26 +3505,27 @@ function registerCellTools(server, client) {
3287
3505
  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,
3288
3506
  inputSchema: {
3289
3507
  projectId: projectIdSchema,
3290
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3291
- persona: import_v318.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3508
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3509
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3292
3510
  },
3293
3511
  outputSchema: {
3294
3512
  cell: cellOutput.nullable(),
3295
- arm: import_v318.z.object({
3296
- id: import_v318.z.string(),
3297
- displayName: import_v318.z.string().nullable(),
3298
- content: import_v318.z.string().nullable(),
3299
- blocks: import_v318.z.unknown().nullable()
3513
+ arm: import_v319.z.object({
3514
+ id: import_v319.z.string(),
3515
+ displayName: import_v319.z.string().nullable(),
3516
+ content: import_v319.z.string().nullable(),
3517
+ blocks: import_v319.z.unknown().nullable()
3300
3518
  }).nullable(),
3301
- performance: import_v318.z.object({
3302
- shown: import_v318.z.number(),
3303
- conversions: import_v318.z.number(),
3304
- conversionRate: import_v318.z.number(),
3305
- baselineShown: import_v318.z.number(),
3306
- baselineConversions: import_v318.z.number(),
3307
- baselineConversionRate: import_v318.z.number()
3519
+ performance: import_v319.z.object({
3520
+ shown: import_v319.z.number(),
3521
+ conversions: import_v319.z.number(),
3522
+ conversionRate: import_v319.z.number(),
3523
+ baselineShown: import_v319.z.number(),
3524
+ baselineConversions: import_v319.z.number(),
3525
+ baselineConversionRate: import_v319.z.number()
3308
3526
  }).nullable(),
3309
- verdict: import_v318.z.string()
3527
+ verdict: import_v319.z.string(),
3528
+ blocked: blockedOutput
3310
3529
  },
3311
3530
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3312
3531
  },
@@ -3315,7 +3534,12 @@ function registerCellTools(server, client) {
3315
3534
  const id = encodeURIComponent(projectId);
3316
3535
  const data = await client.get(`/projects/${id}/cells/detail?slotId=${encodeURIComponent(slotId)}&persona=${encodeURIComponent(persona)}`);
3317
3536
  const lines = [];
3318
- if (data.arm) {
3537
+ if (data.arm && data.blocked === "variant_history") {
3538
+ lines.push(
3539
+ 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.`,
3540
+ BLOCKED_LINE
3541
+ );
3542
+ } else if (data.arm) {
3319
3543
  lines.push(
3320
3544
  data.arm.content !== null ? `They see: "${untrusted(data.arm.content, 300)}"` : `They see a designed layout (option ${untrusted(data.arm.id, 64)}).`
3321
3545
  );
@@ -3351,14 +3575,14 @@ function registerCellTools(server, client) {
3351
3575
  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.",
3352
3576
  inputSchema: {
3353
3577
  projectId: projectIdSchema,
3354
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3355
- persona: import_v318.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3578
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id (a matrix column)"),
3579
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key (a matrix row)")
3356
3580
  },
3357
3581
  outputSchema: {
3358
- slotId: import_v318.z.string(),
3359
- persona: import_v318.z.string(),
3360
- status: import_v318.z.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress"),
3361
- 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.")
3582
+ slotId: import_v319.z.string(),
3583
+ persona: import_v319.z.string(),
3584
+ status: import_v319.z.literal("pending").describe("Queued \u2014 check get_cell_matrix for progress"),
3585
+ 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.")
3362
3586
  },
3363
3587
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
3364
3588
  },
@@ -3386,19 +3610,20 @@ function registerCellTools(server, client) {
3386
3610
  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,
3387
3611
  inputSchema: { projectId: projectIdSchema },
3388
3612
  outputSchema: {
3389
- reviews: import_v318.z.array(
3390
- import_v318.z.object({
3391
- slotId: import_v318.z.string(),
3392
- slotName: import_v318.z.string(),
3393
- persona: import_v318.z.string(),
3394
- personaDisplay: import_v318.z.string(),
3395
- content: import_v318.z.string().nullable().describe("Proposed text, when the version is text (null for a block/layout version)"),
3396
- rationale: import_v318.z.string().nullable(),
3397
- refinedFrom: import_v318.z.string().nullable().describe("Live version this one would replace; that version keeps serving until approval"),
3398
- updatedAt: import_v318.z.string()
3613
+ reviews: import_v319.z.array(
3614
+ import_v319.z.object({
3615
+ slotId: import_v319.z.string(),
3616
+ slotName: import_v319.z.string(),
3617
+ persona: import_v319.z.string(),
3618
+ personaDisplay: import_v319.z.string(),
3619
+ content: import_v319.z.string().nullable().describe("Proposed text, when the version is text (null for a block/layout version)"),
3620
+ rationale: import_v319.z.string().nullable(),
3621
+ refinedFrom: import_v319.z.string().nullable().describe("Live version this one would replace; that version keeps serving until approval"),
3622
+ updatedAt: import_v319.z.string(),
3623
+ blocked: blockedOutput
3399
3624
  })
3400
3625
  ),
3401
- 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.")
3626
+ 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.")
3402
3627
  },
3403
3628
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
3404
3629
  },
@@ -3407,7 +3632,7 @@ function registerCellTools(server, client) {
3407
3632
  const id = encodeURIComponent(projectId);
3408
3633
  const data = await client.get(`/projects/${id}/cell-reviews`);
3409
3634
  const reviews = ((_a = data.reviews) != null ? _a : []).map((r) => {
3410
- var _a2, _b, _c;
3635
+ var _a2, _b, _c, _d;
3411
3636
  return {
3412
3637
  slotId: r.slotId,
3413
3638
  slotName: r.slotName,
@@ -3416,7 +3641,8 @@ function registerCellTools(server, client) {
3416
3641
  content: typeof ((_a2 = r.pendingArm) == null ? void 0 : _a2.content) === "string" ? r.pendingArm.content : null,
3417
3642
  rationale: (_b = r.rationale) != null ? _b : null,
3418
3643
  refinedFrom: (_c = r.refinedFrom) != null ? _c : null,
3419
- updatedAt: String(r.updatedAt)
3644
+ updatedAt: String(r.updatedAt),
3645
+ blocked: (_d = r.blocked) != null ? _d : null
3420
3646
  };
3421
3647
  });
3422
3648
  const total = typeof data.total === "number" ? data.total : reviews.length;
@@ -3431,7 +3657,8 @@ function registerCellTools(server, client) {
3431
3657
  `- ${untrusted(r.slotName, 60)} (slotId ${untrusted(r.slotId, 64)}) for ${untrusted(r.personaDisplay, 60)} (persona ${untrusted(r.persona, 64)})`,
3432
3658
  r.content !== null ? ` Proposed text: ${untrusted(r.content, 300)}` : " Proposed: a designed block/layout (preview it in the dashboard)",
3433
3659
  r.rationale ? ` Why: ${untrusted(r.rationale, 300)}` : null,
3434
- r.refinedFrom ? ` Would replace ${untrusted(r.refinedFrom, 64)}, which keeps serving until approval.` : null
3660
+ r.refinedFrom ? ` Would replace ${untrusted(r.refinedFrom, 64)}, which keeps serving until approval.` : null,
3661
+ r.blocked === "variant_history" ? ` Approving it will NOT show it yet: ${BLOCKED_LINE}` : null
3435
3662
  ].filter((l) => l !== null).join("\n")
3436
3663
  );
3437
3664
  if (total > reviews.length) {
@@ -3448,22 +3675,23 @@ function registerCellTools(server, client) {
3448
3675
  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.",
3449
3676
  inputSchema: {
3450
3677
  projectId: projectIdSchema,
3451
- slotId: import_v318.z.string().min(1).max(128).describe("The slot id of the version under review"),
3452
- persona: import_v318.z.string().min(1).max(64).describe("The persona key of the version under review"),
3453
- action: import_v318.z.enum(["approve", "reject"]),
3454
- feedback: import_v318.z.string().max(2e3).optional().describe("Optional reviewer note, stored with a rejection")
3678
+ slotId: import_v319.z.string().min(1).max(128).describe("The slot id of the version under review"),
3679
+ persona: import_v319.z.string().min(1).max(64).describe("The persona key of the version under review"),
3680
+ action: import_v319.z.enum(["approve", "reject"]),
3681
+ 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.")
3455
3682
  },
3456
3683
  outputSchema: {
3457
- slotId: import_v318.z.string(),
3458
- persona: import_v318.z.string(),
3459
- action: import_v318.z.enum(["approve", "reject"]),
3460
- status: import_v318.z.string().describe("live (approved, or a rejected refinement whose incumbent keeps serving) | rejected"),
3461
- armId: import_v318.z.string().nullable().describe("The published option id, on approval")
3684
+ slotId: import_v319.z.string(),
3685
+ persona: import_v319.z.string(),
3686
+ action: import_v319.z.enum(["approve", "reject"]),
3687
+ status: import_v319.z.string().describe("live (approved, or a rejected refinement whose incumbent keeps serving) | rejected"),
3688
+ armId: import_v319.z.string().nullable().describe("The published option id, on approval"),
3689
+ blocked: blockedOutput
3462
3690
  },
3463
3691
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
3464
3692
  },
3465
3693
  withApiErrorGuidance(async ({ projectId, slotId, persona, action, feedback }) => {
3466
- var _a, _b;
3694
+ var _a, _b, _c;
3467
3695
  const id = encodeURIComponent(projectId);
3468
3696
  const res = await client.post(`/projects/${id}/cells/review`, {
3469
3697
  slotId,
@@ -3472,10 +3700,11 @@ function registerCellTools(server, client) {
3472
3700
  feedback
3473
3701
  });
3474
3702
  const status = (_a = res.status) != null ? _a : action === "approve" ? "live" : "rejected";
3475
- 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.`;
3703
+ const blocked = (_b = res.blocked) != null ? _b : null;
3704
+ 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.`;
3476
3705
  return {
3477
3706
  content: [{ type: "text", text: text2 }],
3478
- structuredContent: { slotId, persona, action, status, armId: (_b = res.armId) != null ? _b : null }
3707
+ structuredContent: { slotId, persona, action, status, armId: (_c = res.armId) != null ? _c : null, blocked }
3479
3708
  };
3480
3709
  }, {
3481
3710
  not_found: "No version is waiting for review in that cell (it may already have been approved or rejected). Check list_cell_reviews.",
@@ -3485,7 +3714,7 @@ function registerCellTools(server, client) {
3485
3714
  }
3486
3715
 
3487
3716
  // src/tools/agent-reads.ts
3488
- var import_v319 = require("zod/v3");
3717
+ var import_v320 = require("zod/v3");
3489
3718
  var READ_ONLY = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
3490
3719
  var AREA_NAMES = {
3491
3720
  generate: "Generate",
@@ -3537,15 +3766,15 @@ function registerAgentReadTools(server, client) {
3537
3766
  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.",
3538
3767
  inputSchema: { projectId: projectIdSchema },
3539
3768
  outputSchema: {
3540
- areas: import_v319.z.object({
3541
- generate: import_v319.z.boolean(),
3542
- approve: import_v319.z.boolean(),
3543
- tests: import_v319.z.boolean(),
3544
- goals: import_v319.z.boolean(),
3545
- campaigns: import_v319.z.boolean(),
3546
- settings: import_v319.z.boolean()
3769
+ areas: import_v320.z.object({
3770
+ generate: import_v320.z.boolean(),
3771
+ approve: import_v320.z.boolean(),
3772
+ tests: import_v320.z.boolean(),
3773
+ goals: import_v320.z.boolean(),
3774
+ campaigns: import_v320.z.boolean(),
3775
+ settings: import_v320.z.boolean()
3547
3776
  }).describe("true = agents may act in this area"),
3548
- canEdit: import_v319.z.boolean().describe("Whether THIS credential could change the switches (always false for an agent)")
3777
+ canEdit: import_v320.z.boolean().describe("Whether THIS credential could change the switches (always false for an agent)")
3549
3778
  },
3550
3779
  annotations: READ_ONLY
3551
3780
  },
@@ -3572,35 +3801,35 @@ function registerAgentReadTools(server, client) {
3572
3801
  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,
3573
3802
  inputSchema: __spreadValues({
3574
3803
  projectId: projectIdSchema,
3575
- campaignId: import_v319.z.string().optional().describe("A campaign id from this tool's list; returns that campaign's card")
3804
+ campaignId: import_v320.z.string().optional().describe("A campaign id from this tool's list; returns that campaign's card")
3576
3805
  }, rangeInputSchema("30d")),
3577
3806
  outputSchema: {
3578
- campaigns: import_v319.z.array(import_v319.z.object({
3579
- id: import_v319.z.string(),
3580
- name: import_v319.z.string(),
3581
- status: import_v319.z.string().nullable(),
3582
- arrivalType: import_v319.z.string().nullable(),
3583
- landingPaths: import_v319.z.array(import_v319.z.string())
3807
+ campaigns: import_v320.z.array(import_v320.z.object({
3808
+ id: import_v320.z.string(),
3809
+ name: import_v320.z.string(),
3810
+ status: import_v320.z.string().nullable(),
3811
+ arrivalType: import_v320.z.string().nullable(),
3812
+ landingPaths: import_v320.z.array(import_v320.z.string())
3584
3813
  })).optional(),
3585
- retargeting: import_v319.z.array(import_v319.z.object({
3586
- groupId: import_v319.z.string(),
3587
- campaignId: import_v319.z.string().nullable(),
3588
- name: import_v319.z.string(),
3589
- status: import_v319.z.string().nullable(),
3590
- endsAt: import_v319.z.string().nullable(),
3591
- memberCount: import_v319.z.number()
3814
+ retargeting: import_v320.z.array(import_v320.z.object({
3815
+ groupId: import_v320.z.string(),
3816
+ campaignId: import_v320.z.string().nullable(),
3817
+ name: import_v320.z.string(),
3818
+ status: import_v320.z.string().nullable(),
3819
+ endsAt: import_v320.z.string().nullable(),
3820
+ memberCount: import_v320.z.number()
3592
3821
  })).optional(),
3593
- 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(),
3594
- card: import_v319.z.object({
3595
- campaignId: import_v319.z.string(),
3596
- name: import_v319.z.string(),
3597
- status: import_v319.z.string().nullable(),
3598
- clicks: import_v319.z.number(),
3599
- people: import_v319.z.number().describe("New people served as the campaign"),
3600
- cameBack: import_v319.z.number(),
3601
- controlGroup: import_v319.z.number().describe("Matched visits held back on the original site"),
3602
- 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"),
3603
- retargetingGroupId: import_v319.z.string().nullable()
3822
+ 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(),
3823
+ card: import_v320.z.object({
3824
+ campaignId: import_v320.z.string(),
3825
+ name: import_v320.z.string(),
3826
+ status: import_v320.z.string().nullable(),
3827
+ clicks: import_v320.z.number(),
3828
+ people: import_v320.z.number().describe("New people served as the campaign"),
3829
+ cameBack: import_v320.z.number(),
3830
+ controlGroup: import_v320.z.number().describe("Matched visits held back on the original site"),
3831
+ 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"),
3832
+ retargetingGroupId: import_v320.z.string().nullable()
3604
3833
  }).optional().describe("Only when campaignId was given")
3605
3834
  },
3606
3835
  annotations: READ_ONLY
@@ -3683,17 +3912,17 @@ function registerAgentReadTools(server, client) {
3683
3912
  {
3684
3913
  title: "Retargeting report",
3685
3914
  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,
3686
- inputSchema: { projectId: projectIdSchema, groupId: import_v319.z.string().describe("A retargeting group id from list_campaigns") },
3915
+ inputSchema: { projectId: projectIdSchema, groupId: import_v320.z.string().describe("A retargeting group id from list_campaigns") },
3687
3916
  outputSchema: {
3688
- groupId: import_v319.z.string(),
3689
- name: import_v319.z.string(),
3690
- status: import_v319.z.string().nullable(),
3691
- endsAt: import_v319.z.string().nullable(),
3692
- members: import_v319.z.number(),
3693
- cameBack: import_v319.z.number(),
3694
- converted: import_v319.z.number(),
3695
- clicks: import_v319.z.number(),
3696
- versions: import_v319.z.array(import_v319.z.object({ label: import_v319.z.string(), shown: import_v319.z.number(), conversions: import_v319.z.number() }))
3917
+ groupId: import_v320.z.string(),
3918
+ name: import_v320.z.string(),
3919
+ status: import_v320.z.string().nullable(),
3920
+ endsAt: import_v320.z.string().nullable(),
3921
+ members: import_v320.z.number(),
3922
+ cameBack: import_v320.z.number(),
3923
+ converted: import_v320.z.number(),
3924
+ clicks: import_v320.z.number(),
3925
+ versions: import_v320.z.array(import_v320.z.object({ label: import_v320.z.string(), shown: import_v320.z.number(), conversions: import_v320.z.number() }))
3697
3926
  },
3698
3927
  annotations: READ_ONLY
3699
3928
  },
@@ -3730,20 +3959,20 @@ function registerAgentReadTools(server, client) {
3730
3959
  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,
3731
3960
  inputSchema: { projectId: projectIdSchema },
3732
3961
  outputSchema: {
3733
- declared: import_v319.z.object({
3734
- source: import_v319.z.string().nullable(),
3735
- 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() }))
3962
+ declared: import_v320.z.object({
3963
+ source: import_v320.z.string().nullable(),
3964
+ 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() }))
3736
3965
  }).nullable(),
3737
- discovered: import_v319.z.object({
3738
- members: import_v319.z.array(import_v319.z.object({
3739
- key: import_v319.z.string(),
3740
- displayName: import_v319.z.string(),
3741
- sessions: import_v319.z.number().nullable(),
3742
- share: import_v319.z.number().nullable(),
3743
- evidence: import_v319.z.string().describe("strong_evidence | moderate_evidence | no_clear_difference | not_enough_data | not_checked_yet")
3966
+ discovered: import_v320.z.object({
3967
+ members: import_v320.z.array(import_v320.z.object({
3968
+ key: import_v320.z.string(),
3969
+ displayName: import_v320.z.string(),
3970
+ sessions: import_v320.z.number().nullable(),
3971
+ share: import_v320.z.number().nullable(),
3972
+ evidence: import_v320.z.string().describe("strong_evidence | moderate_evidence | no_clear_difference | not_enough_data | not_checked_yet")
3744
3973
  }))
3745
3974
  }).nullable().describe("null when no discovered set exists yet"),
3746
- promotion: import_v319.z.object({ eligible: import_v319.z.boolean(), blockers: import_v319.z.array(import_v319.z.string()) }).nullable()
3975
+ promotion: import_v320.z.object({ eligible: import_v320.z.boolean(), blockers: import_v320.z.array(import_v320.z.string()) }).nullable()
3747
3976
  },
3748
3977
  annotations: READ_ONLY
3749
3978
  },
@@ -3809,18 +4038,18 @@ function registerAgentReadTools(server, client) {
3809
4038
  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,
3810
4039
  inputSchema: { projectId: projectIdSchema },
3811
4040
  outputSchema: {
3812
- colorsMeasured: import_v319.z.boolean().describe("false when no captured style has a measured text or background color"),
3813
- roles: import_v319.z.array(import_v319.z.object({
3814
- role: import_v319.z.string(),
3815
- count: import_v319.z.number(),
3816
- measuredColors: import_v319.z.number().describe("How many of these styles have a measured color")
4041
+ colorsMeasured: import_v320.z.boolean().describe("false when no captured style has a measured text or background color"),
4042
+ roles: import_v320.z.array(import_v320.z.object({
4043
+ role: import_v320.z.string(),
4044
+ count: import_v320.z.number(),
4045
+ measuredColors: import_v320.z.number().describe("How many of these styles have a measured color")
3817
4046
  })),
3818
- lastScan: import_v319.z.object({ editorAt: import_v319.z.string().nullable(), crawlAt: import_v319.z.string().nullable() }),
3819
- audit: import_v319.z.object({
3820
- status: import_v319.z.string().nullable(),
3821
- score: import_v319.z.number().nullable(),
3822
- auditedAt: import_v319.z.string().nullable(),
3823
- checking: import_v319.z.boolean()
4047
+ lastScan: import_v320.z.object({ editorAt: import_v320.z.string().nullable(), crawlAt: import_v320.z.string().nullable() }),
4048
+ audit: import_v320.z.object({
4049
+ status: import_v320.z.string().nullable(),
4050
+ score: import_v320.z.number().nullable(),
4051
+ auditedAt: import_v320.z.string().nullable(),
4052
+ checking: import_v320.z.boolean()
3824
4053
  }).nullable().describe("null when the audit could not be read")
3825
4054
  },
3826
4055
  annotations: READ_ONLY
@@ -3876,13 +4105,13 @@ function registerAgentReadTools(server, client) {
3876
4105
  {
3877
4106
  title: "Region history",
3878
4107
  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,
3879
- inputSchema: { projectId: projectIdSchema, regionId: import_v319.z.string().describe("The region's id (the slot id shown by list_components)") },
4108
+ inputSchema: { projectId: projectIdSchema, regionId: import_v320.z.string().describe("The region's id (the slot id shown by list_components)") },
3880
4109
  outputSchema: {
3881
- regionId: import_v319.z.string(),
3882
- currentVersion: import_v319.z.number(),
3883
- 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() })),
3884
- recentDecisions: import_v319.z.array(import_v319.z.object({ action: import_v319.z.string(), at: import_v319.z.string().nullable() })),
3885
- 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")
4110
+ regionId: import_v320.z.string(),
4111
+ currentVersion: import_v320.z.number(),
4112
+ 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() })),
4113
+ recentDecisions: import_v320.z.array(import_v320.z.object({ action: import_v320.z.string(), at: import_v320.z.string().nullable() })),
4114
+ 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")
3886
4115
  },
3887
4116
  annotations: READ_ONLY
3888
4117
  },
@@ -3916,7 +4145,7 @@ function registerAgentReadTools(server, client) {
3916
4145
  }
3917
4146
 
3918
4147
  // src/tools/manage.ts
3919
- var import_v320 = require("zod/v3");
4148
+ var import_v321 = require("zod/v3");
3920
4149
  var a = (method, route, extra = {}) => __spreadValues({ method, route }, extra);
3921
4150
  var ACTIONS = {
3922
4151
  manage_generation: {
@@ -4054,13 +4283,13 @@ function registerManageTools(server, client) {
4054
4283
  const meta = TOOLS[tool];
4055
4284
  const shape = {
4056
4285
  projectId: projectIdSchema,
4057
- action: import_v320.z.enum(names).describe("What to do. Each action needs only the fields noted below."),
4058
- enabled: import_v320.z.boolean().optional().describe("For set_auto_fill, set_require_approval, set_observation_mode: on (true) or off (false)"),
4059
- 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")
4286
+ action: import_v321.z.enum(names).describe("What to do. Each action needs only the fields noted below."),
4287
+ enabled: import_v321.z.boolean().optional().describe("For set_auto_fill, set_require_approval, set_observation_mode: on (true) or off (false)"),
4288
+ 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")
4060
4289
  };
4061
- if (tool === "manage_generation") shape.depth = import_v320.z.enum(["auto", "rewrite", "redesign"]).optional().describe("For set_depth: how far a rewrite may go");
4062
- 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");
4063
- for (const p of paramNames(tool)) shape[p] = import_v320.z.string().optional().describe(`Required by the actions whose route has :${p}`);
4290
+ if (tool === "manage_generation") shape.depth = import_v321.z.enum(["auto", "rewrite", "redesign"]).optional().describe("For set_depth: how far a rewrite may go");
4291
+ 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");
4292
+ for (const p of paramNames(tool)) shape[p] = import_v321.z.string().optional().describe(`Required by the actions whose route has :${p}`);
4064
4293
  server.registerTool(
4065
4294
  tool,
4066
4295
  {
@@ -4100,8 +4329,32 @@ function registerManageTools(server, client) {
4100
4329
  }
4101
4330
  }
4102
4331
 
4332
+ // src/instructions.ts
4333
+ 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.
4334
+
4335
+ Audiences, and what makes each one serve (precedence: declared > retargeting > discovered > campaign > arrival > everyone):
4336
+ - everyone (key "unknown"): every visitor no other audience claims.
4337
+ - 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).
4338
+ - Discovered audience ("d-" key): found in behaviour; serves only after it is promoted (evidence that it wants something different).
4339
+ - 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.
4340
+ - 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.
4341
+ - 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.
4342
+
4343
+ 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).
4344
+
4345
+ 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.
4346
+
4347
+ Server goal, exact shape (server only, never the browser):
4348
+ import { trackServerGoal } from '@sentientui/react/server'; // or '@sentientui/core/server'
4349
+ await trackServerGoal({ serverKey: process.env.SENTIENT_SECRET_KEY!, userId: user.id, name: 'subscribed', dedupeKey: user.id });
4350
+ 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.
4351
+
4352
+ 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.
4353
+
4354
+ Write tools change what real visitors see: confirm with the user first. Call get_agent_access before a manage_* write.`;
4355
+
4103
4356
  // src/server.ts
4104
- var PKG_VERSION = true ? "0.26.0" : "0.0.0-dev";
4357
+ var PKG_VERSION = true ? "0.27.0" : "0.0.0-dev";
4105
4358
  function createMcpServer(client) {
4106
4359
  const server = new import_mcp.McpServer(
4107
4360
  {
@@ -4119,7 +4372,11 @@ function createMcpServer(client) {
4119
4372
  mimeTypes: [RESOURCE_MIME_TYPE]
4120
4373
  }
4121
4374
  }
4122
- }
4375
+ },
4376
+ // Sent in the initialize result: the facts an agent otherwise gets
4377
+ // wrong (which audiences serve, clusters are not personas, hybrids need
4378
+ // Migrate, the server goal call shape). See instructions.ts.
4379
+ instructions: SERVER_INSTRUCTIONS
4123
4380
  }
4124
4381
  );
4125
4382
  registerUiResources(server);
@@ -4138,6 +4395,7 @@ function createMcpServer(client) {
4138
4395
  registerIntegrationGuideTools(server);
4139
4396
  registerAgentTrafficTools(server, client);
4140
4397
  registerTrafficTools(server, client);
4398
+ registerInternalTrafficTools(server, client);
4141
4399
  registerCellTools(server, client);
4142
4400
  registerAgentReadTools(server, client);
4143
4401
  registerManageTools(server, client);
@@ -4171,7 +4429,7 @@ var TOOL_CATALOG = [
4171
4429
  { name: "get_funnel_report", access: "read", summary: "Step-by-step funnel drop-off" },
4172
4430
  { name: "list_guardrail_events", access: "read", summary: "Every variant currently paused by a guardrail (optionally only pauses from the last N days)" },
4173
4431
  // Audience and layout
4174
- { name: "get_persona_breakdown", access: "read", summary: "Visitor clusters with session counts and reliability (all retained sessions)" },
4432
+ { name: "get_persona_breakdown", access: "read", summary: "Visitors per audience they were served as (30 days, the Matrix share), plus behaviour groups \u2014 visitors who behaved alike, never audiences" },
4175
4433
  { name: "get_stage_breakdown", access: "read", summary: "E-commerce funnel stages: stage mix, arrival channel x stage, stage moves between visits, tested holdout lift per first-visit context and channel, and versions per context (windowed, observational)" },
4176
4434
  { name: "get_layout_stats", access: "read", summary: "Per-persona section order with bandit pulls and reward (cumulative state)" },
4177
4435
  // Insights
@@ -4185,7 +4443,8 @@ var TOOL_CATALOG = [
4185
4443
  { name: "review_cell", access: "write", summary: "Approve (publish) or reject one generated version waiting for review" },
4186
4444
  // Agent traffic
4187
4445
  { name: "get_agent_traffic", access: "read", summary: "Which AI crawlers, automated browser sessions and agent API callers read the site (windowed)" },
4188
- { name: "get_traffic_breakdown", access: "read", summary: "Where traffic came from: People vs visitors we could not confirm vs automated (7 groups, windowed)" },
4446
+ { name: "get_traffic_breakdown", access: "read", summary: "Where traffic came from: People vs visitors we could not confirm vs automated vs your team / test sites (windowed)" },
4447
+ { name: "get_internal_traffic_rules", access: "read", summary: "How the project keeps its team and test sites out of its numbers: internal sites, team email domains and masked emails, browser link, sessions marked internal (7 days)" },
4189
4448
  { name: "get_agent_legibility", access: "read", summary: "Whether the pages agents read are machine-legible, with fixes" },
4190
4449
  // Agent access reads
4191
4450
  { name: "get_agent_access", access: "read", summary: "Which areas a person has allowed agents to change in this project (Generate, Approve and publish, Run tests, Goals and funnels, Campaigns and audiences, Project settings)" },