@smallwebco/tinypivot-mcp 0.5.0 → 0.6.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.
@@ -7620,6 +7620,39 @@ function processChartData(data, config) {
7620
7620
  }
7621
7621
  return { categories, series };
7622
7622
  }
7623
+ function processChartDataForScatter(data, config) {
7624
+ if (!config.xAxis || !config.yAxis || data.length === 0) {
7625
+ return { series: [] };
7626
+ }
7627
+ const xField = config.xAxis.field;
7628
+ const yField = config.yAxis.field;
7629
+ const sizeField = config.sizeField?.field;
7630
+ const seriesField = config.seriesField?.field;
7631
+ const grouped = /* @__PURE__ */ new Map();
7632
+ for (const row of data) {
7633
+ const x = Number(row[xField]);
7634
+ const y = Number(row[yField]);
7635
+ if (Number.isNaN(x) || Number.isNaN(y))
7636
+ continue;
7637
+ const point = { x, y };
7638
+ if (sizeField) {
7639
+ const z2 = Number(row[sizeField]);
7640
+ if (!Number.isNaN(z2)) {
7641
+ point.z = z2;
7642
+ }
7643
+ }
7644
+ const seriesName = seriesField ? String(row[seriesField] ?? "(blank)") : "_default";
7645
+ if (!grouped.has(seriesName)) {
7646
+ grouped.set(seriesName, []);
7647
+ }
7648
+ grouped.get(seriesName).push(point);
7649
+ }
7650
+ const series = Array.from(grouped.entries()).map(([name, points]) => ({
7651
+ name: name === "_default" ? config.yAxis?.label || "Data" : name,
7652
+ data: points
7653
+ }));
7654
+ return { series };
7655
+ }
7623
7656
 
7624
7657
  // ../core/dist/theme/index.js
7625
7658
  var UNIFIED_THEME_IDS = ["paper", "greenbar", "onebit", "crt-amber", "crt-green"];
@@ -8255,6 +8288,185 @@ function tokensToUsd(tokens, ratePerMillion) {
8255
8288
  // src/studio-protocol.ts
8256
8289
  var STUDIO_HEADER = "x-tinypivot";
8257
8290
 
8291
+ // src/card.ts
8292
+ var SUB_BLOCKS = ["", "\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589", "\u2588"];
8293
+ var SERIES_GLYPHS = ["\u2588", "\u2593", "\u2592", "\u2591"];
8294
+ var SPARK_CHARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
8295
+ var CARD_DIVIDER = "__TINYPIVOT_CARD_DIVIDER__";
8296
+ var BRAILLE_BITS = [
8297
+ [1, 8],
8298
+ [2, 16],
8299
+ [4, 32],
8300
+ [64, 128]
8301
+ ];
8302
+ var ANSI_ESCAPE_RE = /\x1B\[[0-9;]*m/g;
8303
+ var ANSI_RESET = "\x1B[0m";
8304
+ var ANSI_BOLD = "\x1B[1m";
8305
+ function ansiFg(rgb, text) {
8306
+ return `\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
8307
+ }
8308
+ function ansiFgBold(rgb, text) {
8309
+ return `${ANSI_BOLD}\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
8310
+ }
8311
+ function codePointDisplayWidth(cp) {
8312
+ if (cp < 32 || cp >= 127 && cp < 160)
8313
+ return 0;
8314
+ if (cp >= 768 && cp <= 879 || cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8203 && cp <= 8207 || cp >= 8232 && cp <= 8239 || cp >= 8400 && cp <= 8447 || cp >= 65024 && cp <= 65039 || cp >= 65056 && cp <= 65071 || cp >= 917760 && cp <= 917999) {
8315
+ return 0;
8316
+ }
8317
+ if (cp >= 4352 && cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 12350 || cp >= 12352 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141) {
8318
+ return 2;
8319
+ }
8320
+ return 1;
8321
+ }
8322
+ function visualWidth(text) {
8323
+ const clean = text.replace(ANSI_ESCAPE_RE, "");
8324
+ let width = 0;
8325
+ for (const ch of clean) {
8326
+ const cp = ch.codePointAt(0);
8327
+ if (cp !== void 0)
8328
+ width += codePointDisplayWidth(cp);
8329
+ }
8330
+ return width;
8331
+ }
8332
+ function truncateVisual(text, maxWidth) {
8333
+ if (maxWidth <= 0)
8334
+ return "";
8335
+ if (visualWidth(text) <= maxWidth)
8336
+ return text;
8337
+ if (maxWidth === 1)
8338
+ return "\u2026";
8339
+ const target = maxWidth - 1;
8340
+ let out = "";
8341
+ let used = 0;
8342
+ for (const ch of text) {
8343
+ const cp = ch.codePointAt(0);
8344
+ const w = cp !== void 0 ? codePointDisplayWidth(cp) : 0;
8345
+ if (used + w > target)
8346
+ break;
8347
+ out += ch;
8348
+ used += w;
8349
+ }
8350
+ return `${out}\u2026`;
8351
+ }
8352
+ function padEndVisual(text, targetWidth) {
8353
+ const pad = Math.max(0, targetWidth - visualWidth(text));
8354
+ return pad > 0 ? `${text}${" ".repeat(pad)}` : text;
8355
+ }
8356
+ function padStartVisual(text, targetWidth) {
8357
+ const pad = Math.max(0, targetWidth - visualWidth(text));
8358
+ return pad > 0 ? `${" ".repeat(pad)}${text}` : text;
8359
+ }
8360
+ function formatCompactNumber(val) {
8361
+ if (!Number.isFinite(val))
8362
+ return "0";
8363
+ const abs = Math.abs(val);
8364
+ const sign = val < 0 ? "-" : "";
8365
+ if (abs >= 1e9)
8366
+ return `${sign}${(abs / 1e9).toFixed(2)}B`;
8367
+ if (abs >= 1e6)
8368
+ return `${sign}${(abs / 1e6).toFixed(2)}M`;
8369
+ if (abs >= 1e4)
8370
+ return `${sign}${(abs / 1e3).toFixed(1)}k`;
8371
+ if (abs >= 1e3)
8372
+ return `${sign}${Math.round(abs).toLocaleString("en-US")}`;
8373
+ return Number.isInteger(val) ? String(val) : val.toFixed(1);
8374
+ }
8375
+ function renderPreciseBar(ratio, width) {
8376
+ const clamped = Math.max(0, Math.min(1, ratio));
8377
+ if (clamped <= 0)
8378
+ return "";
8379
+ const totalEighths = Math.round(clamped * width * 8);
8380
+ if (totalEighths === 0)
8381
+ return "\u258F";
8382
+ const full = Math.floor(totalEighths / 8);
8383
+ const rem = totalEighths % 8;
8384
+ return `${"\u2588".repeat(full)}${SUB_BLOCKS[rem]}`;
8385
+ }
8386
+ function renderSparkline(values) {
8387
+ if (values.length === 0)
8388
+ return "";
8389
+ const min = Math.min(...values);
8390
+ const max = Math.max(...values);
8391
+ const span = max - min;
8392
+ return values.map((v) => {
8393
+ if (!Number.isFinite(v))
8394
+ return " ";
8395
+ if (span <= 0)
8396
+ return SPARK_CHARS[3];
8397
+ const idx = Math.min(SPARK_CHARS.length - 1, Math.max(0, Math.round((v - min) / span * (SPARK_CHARS.length - 1))));
8398
+ return SPARK_CHARS[idx];
8399
+ }).join("");
8400
+ }
8401
+ function buildTopBorder(title, rightBadge, innerWidth) {
8402
+ if (rightBadge) {
8403
+ const safeRight = truncateVisual(rightBadge, Math.max(8, Math.floor(innerWidth * 0.44)));
8404
+ const rightW = visualWidth(safeRight);
8405
+ const maxTitleW = Math.max(1, innerWidth - 5 - rightW);
8406
+ const safeTitle2 = truncateVisual(title, maxTitleW);
8407
+ const dashCount2 = Math.max(1, innerWidth - 4 - visualWidth(safeTitle2) - rightW);
8408
+ return `\u256D\u2500 ${safeTitle2} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256E`;
8409
+ }
8410
+ const safeTitle = truncateVisual(title, Math.max(1, innerWidth - 3));
8411
+ const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeTitle));
8412
+ return `\u256D\u2500 ${safeTitle} ${"\u2500".repeat(dashCount)}\u2500\u256E`;
8413
+ }
8414
+ function buildBottomBorder(footerLeft, footerRight, innerWidth) {
8415
+ if (footerLeft && footerRight) {
8416
+ const safeLeft = truncateVisual(footerLeft, Math.max(8, Math.floor(innerWidth * 0.45)));
8417
+ const leftW = visualWidth(safeLeft);
8418
+ const maxRightW = innerWidth - 5 - leftW;
8419
+ if (maxRightW >= 4) {
8420
+ const safeRight = truncateVisual(footerRight, maxRightW);
8421
+ const rightW = visualWidth(safeRight);
8422
+ const dashCount2 = Math.max(1, innerWidth - 4 - leftW - rightW);
8423
+ return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256F`;
8424
+ }
8425
+ const dashCount = Math.max(1, innerWidth - 2 - leftW);
8426
+ return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
8427
+ }
8428
+ if (footerLeft) {
8429
+ const safeLeft = truncateVisual(footerLeft, Math.max(1, innerWidth - 3));
8430
+ const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeLeft));
8431
+ return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
8432
+ }
8433
+ if (footerRight) {
8434
+ const safeRight = truncateVisual(footerRight, Math.max(1, innerWidth - 3));
8435
+ const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeRight));
8436
+ return `\u2570\u2500${"\u2500".repeat(dashCount)} ${safeRight} \u2500\u256F`;
8437
+ }
8438
+ return `\u2570${"\u2500".repeat(innerWidth + 2)}\u256F`;
8439
+ }
8440
+ function resolveTerminalPalette(theme) {
8441
+ if (!theme)
8442
+ return void 0;
8443
+ return TERMINAL_PALETTES[theme] ?? TERMINAL_PALETTES.code;
8444
+ }
8445
+ function wrapInCard(title, rightBadge, bodyLines, footerLeft, footerRight, minWidth = 66, options = {}) {
8446
+ const pal = options.palette;
8447
+ const contentLines = bodyLines.filter((l) => l !== CARD_DIVIDER);
8448
+ const longestBody = Math.max(...contentLines.map((l) => visualWidth(l)), 0);
8449
+ const desiredHeader = visualWidth(title) + visualWidth(rightBadge) + (rightBadge ? 6 : 4);
8450
+ const desiredFooter = visualWidth(footerLeft) + visualWidth(footerRight) + (footerLeft && footerRight ? 6 : 4);
8451
+ const innerWidth = Math.min(82, Math.max(minWidth, longestBody, Math.min(desiredHeader, 82), Math.min(desiredFooter, 82)));
8452
+ const topPlain = buildTopBorder(title, rightBadge, innerWidth);
8453
+ const topBorder = pal ? topPlain.replace(/^(╭─ )(.+?)( ─+ )(.+?)( ─╮)$/, (_, a, b, c, d, e) => `${ansiFg(pal.border, a)}${ansiFgBold(pal.text, b)}${ansiFg(pal.border, c)}${ansiFg(pal.accent, d)}${ansiFg(pal.border, e)}`) : topPlain;
8454
+ const dividerPlain = `\u251C${"\u2500".repeat(innerWidth + 2)}\u2524`;
8455
+ const dividerLine = pal ? ansiFg(pal.border, dividerPlain) : dividerPlain;
8456
+ const edge = pal ? ansiFg(pal.border, "\u2502") : "\u2502";
8457
+ const paddedBody = bodyLines.map((line) => {
8458
+ if (line === CARD_DIVIDER)
8459
+ return dividerLine;
8460
+ const clipped = visualWidth(line) > innerWidth ? truncateVisual(line, innerWidth) : line;
8461
+ return `${edge} ${padEndVisual(clipped, innerWidth)} ${edge}`;
8462
+ });
8463
+ const botPlain = buildBottomBorder(footerLeft, footerRight, innerWidth);
8464
+ const bottomBorder = pal ? ansiFg(pal.border, botPlain) : botPlain;
8465
+ if (options.raw)
8466
+ return [topBorder, ...paddedBody, bottomBorder].join("\n");
8467
+ return ["```text", topBorder, ...paddedBody, bottomBorder, "```"].join("\n");
8468
+ }
8469
+
8258
8470
  // src/store.ts
8259
8471
  import fsSync from "fs";
8260
8472
  import fs from "fs/promises";
@@ -8859,184 +9071,7 @@ var DatasetStore = class {
8859
9071
  }
8860
9072
  };
8861
9073
 
8862
- // src/summary.ts
8863
- var SUB_BLOCKS = ["", "\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589", "\u2588"];
8864
- var SERIES_GLYPHS = ["\u2588", "\u2593", "\u2592", "\u2591"];
8865
- var SPARK_CHARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
8866
- var CARD_DIVIDER = "__TINYPIVOT_CARD_DIVIDER__";
8867
- var BRAILLE_BITS = [
8868
- [1, 8],
8869
- [2, 16],
8870
- [4, 32],
8871
- [64, 128]
8872
- ];
8873
- var ANSI_ESCAPE_RE = /\x1B\[[0-9;]*m/g;
8874
- var ANSI_RESET = "\x1B[0m";
8875
- var ANSI_BOLD = "\x1B[1m";
8876
- function ansiFg(rgb, text) {
8877
- return `\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
8878
- }
8879
- function ansiFgBold(rgb, text) {
8880
- return `${ANSI_BOLD}\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
8881
- }
8882
- function codePointDisplayWidth(cp) {
8883
- if (cp < 32 || cp >= 127 && cp < 160)
8884
- return 0;
8885
- if (cp >= 768 && cp <= 879 || cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8203 && cp <= 8207 || cp >= 8232 && cp <= 8239 || cp >= 8400 && cp <= 8447 || cp >= 65024 && cp <= 65039 || cp >= 65056 && cp <= 65071 || cp >= 917760 && cp <= 917999) {
8886
- return 0;
8887
- }
8888
- if (cp >= 4352 && cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 12350 || cp >= 12352 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141) {
8889
- return 2;
8890
- }
8891
- return 1;
8892
- }
8893
- function visualWidth(text) {
8894
- const clean = text.replace(ANSI_ESCAPE_RE, "");
8895
- let width = 0;
8896
- for (const ch of clean) {
8897
- const cp = ch.codePointAt(0);
8898
- if (cp !== void 0)
8899
- width += codePointDisplayWidth(cp);
8900
- }
8901
- return width;
8902
- }
8903
- function truncateVisual(text, maxWidth) {
8904
- if (maxWidth <= 0)
8905
- return "";
8906
- if (visualWidth(text) <= maxWidth)
8907
- return text;
8908
- if (maxWidth === 1)
8909
- return "\u2026";
8910
- const target = maxWidth - 1;
8911
- let out = "";
8912
- let used = 0;
8913
- for (const ch of text) {
8914
- const cp = ch.codePointAt(0);
8915
- const w = cp !== void 0 ? codePointDisplayWidth(cp) : 0;
8916
- if (used + w > target)
8917
- break;
8918
- out += ch;
8919
- used += w;
8920
- }
8921
- return `${out}\u2026`;
8922
- }
8923
- function padEndVisual(text, targetWidth) {
8924
- const pad = Math.max(0, targetWidth - visualWidth(text));
8925
- return pad > 0 ? `${text}${" ".repeat(pad)}` : text;
8926
- }
8927
- function padStartVisual(text, targetWidth) {
8928
- const pad = Math.max(0, targetWidth - visualWidth(text));
8929
- return pad > 0 ? `${" ".repeat(pad)}${text}` : text;
8930
- }
8931
- function formatCompactNumber(val) {
8932
- if (!Number.isFinite(val))
8933
- return "0";
8934
- const abs = Math.abs(val);
8935
- const sign = val < 0 ? "-" : "";
8936
- if (abs >= 1e9)
8937
- return `${sign}${(abs / 1e9).toFixed(2)}B`;
8938
- if (abs >= 1e6)
8939
- return `${sign}${(abs / 1e6).toFixed(2)}M`;
8940
- if (abs >= 1e4)
8941
- return `${sign}${(abs / 1e3).toFixed(1)}k`;
8942
- if (abs >= 1e3)
8943
- return `${sign}${Math.round(abs).toLocaleString("en-US")}`;
8944
- return Number.isInteger(val) ? String(val) : val.toFixed(1);
8945
- }
8946
- function renderPreciseBar(ratio, width) {
8947
- const clamped = Math.max(0, Math.min(1, ratio));
8948
- if (clamped <= 0)
8949
- return "";
8950
- const totalEighths = Math.round(clamped * width * 8);
8951
- if (totalEighths === 0)
8952
- return "\u258F";
8953
- const full = Math.floor(totalEighths / 8);
8954
- const rem = totalEighths % 8;
8955
- return `${"\u2588".repeat(full)}${SUB_BLOCKS[rem]}`;
8956
- }
8957
- function renderSparkline(values) {
8958
- if (values.length === 0)
8959
- return "";
8960
- const min = Math.min(...values);
8961
- const max = Math.max(...values);
8962
- const span = max - min;
8963
- return values.map((v) => {
8964
- if (!Number.isFinite(v))
8965
- return " ";
8966
- if (span <= 0)
8967
- return SPARK_CHARS[3];
8968
- const idx = Math.min(SPARK_CHARS.length - 1, Math.max(0, Math.round((v - min) / span * (SPARK_CHARS.length - 1))));
8969
- return SPARK_CHARS[idx];
8970
- }).join("");
8971
- }
8972
- function buildTopBorder(title, rightBadge, innerWidth) {
8973
- if (rightBadge) {
8974
- const safeRight = truncateVisual(rightBadge, Math.max(8, Math.floor(innerWidth * 0.44)));
8975
- const rightW = visualWidth(safeRight);
8976
- const maxTitleW = Math.max(1, innerWidth - 5 - rightW);
8977
- const safeTitle2 = truncateVisual(title, maxTitleW);
8978
- const dashCount2 = Math.max(1, innerWidth - 4 - visualWidth(safeTitle2) - rightW);
8979
- return `\u256D\u2500 ${safeTitle2} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256E`;
8980
- }
8981
- const safeTitle = truncateVisual(title, Math.max(1, innerWidth - 3));
8982
- const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeTitle));
8983
- return `\u256D\u2500 ${safeTitle} ${"\u2500".repeat(dashCount)}\u2500\u256E`;
8984
- }
8985
- function buildBottomBorder(footerLeft, footerRight, innerWidth) {
8986
- if (footerLeft && footerRight) {
8987
- const safeLeft = truncateVisual(footerLeft, Math.max(8, Math.floor(innerWidth * 0.45)));
8988
- const leftW = visualWidth(safeLeft);
8989
- const maxRightW = innerWidth - 5 - leftW;
8990
- if (maxRightW >= 4) {
8991
- const safeRight = truncateVisual(footerRight, maxRightW);
8992
- const rightW = visualWidth(safeRight);
8993
- const dashCount2 = Math.max(1, innerWidth - 4 - leftW - rightW);
8994
- return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256F`;
8995
- }
8996
- const dashCount = Math.max(1, innerWidth - 2 - leftW);
8997
- return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
8998
- }
8999
- if (footerLeft) {
9000
- const safeLeft = truncateVisual(footerLeft, Math.max(1, innerWidth - 3));
9001
- const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeLeft));
9002
- return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
9003
- }
9004
- if (footerRight) {
9005
- const safeRight = truncateVisual(footerRight, Math.max(1, innerWidth - 3));
9006
- const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeRight));
9007
- return `\u2570\u2500${"\u2500".repeat(dashCount)} ${safeRight} \u2500\u256F`;
9008
- }
9009
- return `\u2570${"\u2500".repeat(innerWidth + 2)}\u256F`;
9010
- }
9011
- function resolveTerminalPalette(theme) {
9012
- if (!theme)
9013
- return void 0;
9014
- return TERMINAL_PALETTES[theme] ?? TERMINAL_PALETTES.code;
9015
- }
9016
- function wrapInCard(title, rightBadge, bodyLines, footerLeft, footerRight, minWidth = 66, options = {}) {
9017
- const pal = options.palette;
9018
- const contentLines = bodyLines.filter((l) => l !== CARD_DIVIDER);
9019
- const longestBody = Math.max(...contentLines.map((l) => visualWidth(l)), 0);
9020
- const desiredHeader = visualWidth(title) + visualWidth(rightBadge) + (rightBadge ? 6 : 4);
9021
- const desiredFooter = visualWidth(footerLeft) + visualWidth(footerRight) + (footerLeft && footerRight ? 6 : 4);
9022
- const innerWidth = Math.min(82, Math.max(minWidth, longestBody, Math.min(desiredHeader, 82), Math.min(desiredFooter, 82)));
9023
- const topPlain = buildTopBorder(title, rightBadge, innerWidth);
9024
- const topBorder = pal ? topPlain.replace(/^(╭─ )(.+?)( ─+ )(.+?)( ─╮)$/, (_, a, b, c, d, e) => `${ansiFg(pal.border, a)}${ansiFgBold(pal.text, b)}${ansiFg(pal.border, c)}${ansiFg(pal.accent, d)}${ansiFg(pal.border, e)}`) : topPlain;
9025
- const dividerPlain = `\u251C${"\u2500".repeat(innerWidth + 2)}\u2524`;
9026
- const dividerLine = pal ? ansiFg(pal.border, dividerPlain) : dividerPlain;
9027
- const edge = pal ? ansiFg(pal.border, "\u2502") : "\u2502";
9028
- const paddedBody = bodyLines.map((line) => {
9029
- if (line === CARD_DIVIDER)
9030
- return dividerLine;
9031
- const clipped = visualWidth(line) > innerWidth ? truncateVisual(line, innerWidth) : line;
9032
- return `${edge} ${padEndVisual(clipped, innerWidth)} ${edge}`;
9033
- });
9034
- const botPlain = buildBottomBorder(footerLeft, footerRight, innerWidth);
9035
- const bottomBorder = pal ? ansiFg(pal.border, botPlain) : botPlain;
9036
- if (options.raw)
9037
- return [topBorder, ...paddedBody, bottomBorder].join("\n");
9038
- return ["```text", topBorder, ...paddedBody, bottomBorder, "```"].join("\n");
9039
- }
9074
+ // src/terminal-chart.ts
9040
9075
  function computeBrailleYBounds(values) {
9041
9076
  const rawMin = Math.min(...values);
9042
9077
  const rawMax = Math.max(...values);
@@ -9066,9 +9101,11 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9066
9101
  const pxW = chartCols * 2;
9067
9102
  const pxH = chartRows * 4;
9068
9103
  const grid = Array.from({ length: chartRows }, () => Array.from({ length: chartCols }).fill(0));
9104
+ const owners = Array.from({ length: chartRows }, () => Array.from({ length: chartCols }).fill(-1));
9105
+ let drawing = 0;
9069
9106
  const allFinite = seriesList.flatMap((s) => s.values.filter((v) => v !== null && Number.isFinite(v)));
9070
9107
  if (allFinite.length === 0)
9071
- return [];
9108
+ return { lines: [], plotStart: 0, owners };
9072
9109
  const { minVal, maxVal, span } = computeBrailleYBounds(allFinite);
9073
9110
  const setPixel = (x, y) => {
9074
9111
  const cx = Math.max(0, Math.min(pxW - 1, Math.round(x)));
@@ -9076,6 +9113,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9076
9113
  const cellCol = Math.floor(cx / 2);
9077
9114
  const cellRow = Math.floor(cy / 4);
9078
9115
  grid[cellRow][cellCol] |= BRAILLE_BITS[cy % 4][cx % 2];
9116
+ owners[cellRow][cellCol] = drawing;
9079
9117
  };
9080
9118
  const curveY = Array.from({ length: pxW }).fill(pxH);
9081
9119
  const plotPoint = (x, y, trackCurve) => {
@@ -9095,6 +9133,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9095
9133
  const count = categories.length;
9096
9134
  for (let sIdx = 0; sIdx < seriesList.length; sIdx++) {
9097
9135
  const series = seriesList[sIdx];
9136
+ drawing = sIdx;
9098
9137
  const trackCurve = filledArea && sIdx === 0 && seriesList.length === 1;
9099
9138
  let prev = null;
9100
9139
  let dashCounter = 0;
@@ -9123,6 +9162,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9123
9162
  }
9124
9163
  }
9125
9164
  if (filledArea && seriesList.length === 1) {
9165
+ drawing = 0;
9126
9166
  for (let cx = 0; cx < pxW; cx += 2) {
9127
9167
  const topY = curveY[cx];
9128
9168
  if (topY < pxH) {
@@ -9150,6 +9190,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9150
9190
  lines.push(legendItems.join(" "));
9151
9191
  lines.push("");
9152
9192
  }
9193
+ const plotStart = lines.length;
9153
9194
  for (let r = 0; r < chartRows; r++) {
9154
9195
  let yTick = "";
9155
9196
  let axisChar = "\u2502";
@@ -9184,7 +9225,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
9184
9225
  const gap = Math.max(1, chartCols - firstW - lastW);
9185
9226
  lines.push(`${axisPad}${firstX}${" ".repeat(gap)}${lastX}`);
9186
9227
  }
9187
- return lines;
9228
+ return { lines, plotStart, owners };
9188
9229
  }
9189
9230
  function formatTrendDelta(values) {
9190
9231
  if (values.length < 2)
@@ -9197,160 +9238,299 @@ function formatTrendDelta(values) {
9197
9238
  const sign = pct >= 0 ? "+" : "";
9198
9239
  return `${sign}${pct.toFixed(1)}%`;
9199
9240
  }
9241
+ function paint(ctx, rgb, text) {
9242
+ return ctx.pal ? ansiFg(ctx.pal[rgb], text) : text;
9243
+ }
9244
+ function paintSeries(ctx, index, text) {
9245
+ return ctx.pal ? ansiFg(ctx.pal.series[index % ctx.pal.series.length], text) : text;
9246
+ }
9247
+ function frame(ctx, badge, body, kind, stats = ctx.statsLine) {
9248
+ body.push(CARD_DIVIDER, paint(ctx, "muted", stats));
9249
+ if (ctx.liveRow)
9250
+ body.push(ctx.liveRow);
9251
+ const footerRight = `${ctx.dataset.rows.length.toLocaleString()} rows \xB7 ${kind}`;
9252
+ return wrapInCard(ctx.title, badge, body, ctx.footerLeft, footerRight, 66, { palette: ctx.pal, raw: ctx.raw });
9253
+ }
9254
+ function totalBadge(ctx) {
9255
+ const avg = ctx.grandTotal / Math.max(1, ctx.totalsPerCat.length);
9256
+ return ctx.nonAdditive ? `Avg ${formatCompactNumber(avg)} \xB7 ${ctx.processed.categories.length} pts` : `Total ${formatCompactNumber(ctx.grandTotal)}`;
9257
+ }
9258
+ function paintPlotRow(ctx, row, owners, multiSeries) {
9259
+ const axisAt = Math.max(row.indexOf("\u2524"), row.indexOf("\u2502"));
9260
+ const cells = [...row.slice(axisAt + 1)];
9261
+ let out = `${paint(ctx, "muted", row.slice(0, axisAt))}${paint(ctx, "border", row[axisAt])}`;
9262
+ let start = 0;
9263
+ for (let i = 1; i <= cells.length; i++) {
9264
+ if (i < cells.length && owners[i] === owners[start])
9265
+ continue;
9266
+ const run = cells.slice(start, i).join("");
9267
+ out += owners[start] < 0 ? run : multiSeries ? paintSeries(ctx, owners[start], run) : paint(ctx, "accent", run);
9268
+ start = i;
9269
+ }
9270
+ return out;
9271
+ }
9272
+ function lineBadge(ctx, series) {
9273
+ if (!ctx.nonAdditive)
9274
+ return series.length === 1 && formatTrendDelta(ctx.totalsPerCat) ? `${totalBadge(ctx)} \xB7 ${formatTrendDelta(ctx.totalsPerCat)}` : totalBadge(ctx);
9275
+ const points = series.flatMap((s) => s.values.filter((v) => v !== null));
9276
+ if (series.length === 1)
9277
+ return `Avg ${formatCompactNumber(points.reduce((a, b) => a + b, 0) / Math.max(1, points.length))} \xB7 ${ctx.processed.categories.length} pts`;
9278
+ return `Range ${formatCompactNumber(Math.min(...points))}\u2013${formatCompactNumber(Math.max(...points))} \xB7 ${ctx.processed.categories.length} pts`;
9279
+ }
9280
+ function seriesPeaks(series, categories) {
9281
+ const peaks = series.slice(0, 3).map((s) => {
9282
+ let best = -1;
9283
+ s.values.forEach((v, i) => {
9284
+ if (v !== null && (best < 0 || v > (s.values[best] ?? Number.NEGATIVE_INFINITY)))
9285
+ best = i;
9286
+ });
9287
+ return best >= 0 ? `${truncateVisual(s.name, 10)} peak: ${truncateVisual(categories[best], 8)} (${formatCompactNumber(s.values[best])})` : `${truncateVisual(s.name, 10)}: \u2014`;
9288
+ });
9289
+ return `\u25B2 ${peaks.join(" \xB7 ")}`;
9290
+ }
9291
+ function lineCard(ctx) {
9292
+ const categories = ctx.processed.categories.map(String);
9293
+ const series = ctx.processed.series.map((s) => ({
9294
+ name: s.name,
9295
+ values: s.data.map((val) => val !== null && Number.isFinite(val) ? val : null)
9296
+ }));
9297
+ const multi = series.length > 1;
9298
+ const plot = renderBrailleLineBody(categories, series, ctx.config.type === "area", ctx.nonAdditive);
9299
+ const body = plot.lines.map((row, i) => {
9300
+ if (!ctx.pal)
9301
+ return row;
9302
+ const plotRow = i - plot.plotStart;
9303
+ if (plotRow >= 0 && plotRow < plot.owners.length)
9304
+ return paintPlotRow(ctx, row, plot.owners[plotRow], multi);
9305
+ if (multi && i === 0)
9306
+ return row.split(" ").map((item, s) => paintSeries(ctx, s, item)).join(" ");
9307
+ return paint(ctx, row.includes("\u2514") ? "border" : "muted", row);
9308
+ });
9309
+ const stats = multi ? seriesPeaks(series, categories) : ctx.statsLine;
9310
+ return frame(ctx, lineBadge(ctx, series), body, ctx.config.type === "area" ? "Area" : "Line", stats);
9311
+ }
9312
+ var MAX_BAR_ENTRIES = 14;
9313
+ var BAR_WIDTH = 34;
9314
+ function barRow(ctx, label, labelWidth, bar, barPlainWidth, value2, valWidth, pct) {
9315
+ const labelText = paint(ctx, "text", padEndVisual(truncateVisual(label, labelWidth), labelWidth));
9316
+ const valueText = padStartVisual(formatCompactNumber(value2), valWidth);
9317
+ const pctText = pct === void 0 ? "" : ` ${paint(ctx, "muted", `${pct.toFixed(1).padStart(5)}%`)}`;
9318
+ return `${labelText} ${paint(ctx, "border", "\u2502")} ${bar}${" ".repeat(Math.max(0, BAR_WIDTH - barPlainWidth))} ${ctx.pal ? ansiFgBold(ctx.pal.text, valueText) : valueText}${pctText}`;
9319
+ }
9320
+ function seriesLegend(ctx) {
9321
+ const shown = ctx.processed.series.slice(0, SERIES_GLYPHS.length).map((s, i) => `${paintSeries(ctx, i, SERIES_GLYPHS[i])} ${paint(ctx, "text", truncateVisual(s.name, 14))}`);
9322
+ const more = ctx.processed.series.length - SERIES_GLYPHS.length;
9323
+ return [...shown, ...more > 0 ? [paint(ctx, "muted", `+${more} more`)] : []].join(" ");
9324
+ }
9325
+ function moreCategoriesNote(ctx, shown) {
9326
+ const more = ctx.processed.categories.length - shown;
9327
+ return more > 0 ? [paint(ctx, "muted", `\u2026 +${more} more categories (all interactive in TinyPivot)`)] : [];
9328
+ }
9329
+ function stackedCard(ctx) {
9330
+ const entries = ctx.processed.categories.slice(0, MAX_BAR_ENTRIES).map((cat, idx) => ({
9331
+ label: String(cat),
9332
+ total: ctx.totalsPerCat[idx],
9333
+ segments: ctx.processed.series.map((s) => Math.max(0, Number(s.data[idx]) || 0))
9334
+ }));
9335
+ const maxVal = Math.max(...entries.map((e) => Math.abs(e.total)), 1);
9336
+ const labelWidth = Math.min(20, Math.max(...entries.map((e) => visualWidth(e.label)), 6));
9337
+ const valWidth = Math.max(...entries.map((e) => visualWidth(formatCompactNumber(e.total))), 5);
9338
+ const body = [seriesLegend(ctx), ""];
9339
+ for (const entry of entries) {
9340
+ const width = entry.total === 0 ? 0 : Math.max(1, Math.round(Math.abs(entry.total) / maxVal * BAR_WIDTH));
9341
+ const sum = entry.segments.reduce((a, b) => a + b, 0) || 1;
9342
+ let used = 0;
9343
+ let bar = "";
9344
+ entry.segments.forEach((segment, i) => {
9345
+ const len = i === entry.segments.length - 1 ? Math.max(0, width - used) : Math.min(width - used, Math.round(segment / sum * width));
9346
+ if (len > 0) {
9347
+ bar += paintSeries(ctx, i, SERIES_GLYPHS[i % SERIES_GLYPHS.length].repeat(len));
9348
+ used += len;
9349
+ }
9350
+ });
9351
+ const pct = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
9352
+ body.push(barRow(ctx, entry.label, labelWidth, bar, used, entry.total, valWidth, pct));
9353
+ }
9354
+ body.push(...moreCategoriesNote(ctx, entries.length));
9355
+ return frame(ctx, totalBadge(ctx), body, "Stacked Bar");
9356
+ }
9357
+ function groupedStats(ctx, bars) {
9358
+ const values = bars.map((bar) => bar.value);
9359
+ const peak = bars.reduce((best, bar) => bar.value > best.value ? bar : best, bars[0]);
9360
+ const low = bars.reduce((worst, bar) => bar.value < worst.value ? bar : worst, bars[0]);
9361
+ const avg = values.reduce((sum, v) => sum + v, 0) / Math.max(1, values.length);
9362
+ const badge = ctx.nonAdditive ? `Range ${formatCompactNumber(Math.min(...values))}\u2013${formatCompactNumber(Math.max(...values))} \xB7 ${bars.length} bars` : `Total ${formatCompactNumber(ctx.grandTotal)}`;
9363
+ const stats = `\u25B2 Peak: ${truncateVisual(peak.label, 20)} (${formatCompactNumber(peak.value)}) \xB7 \u25BC Low: ${truncateVisual(low.label, 20)} (${formatCompactNumber(low.value)}) \xB7 \u25C6 Avg: ${formatCompactNumber(avg)}`;
9364
+ return { badge, stats };
9365
+ }
9366
+ var MAX_GROUPED_CATEGORIES = 8;
9367
+ function groupedCard(ctx) {
9368
+ const series = ctx.processed.series.slice(0, SERIES_GLYPHS.length);
9369
+ const categories = ctx.processed.categories.slice(0, MAX_GROUPED_CATEGORIES);
9370
+ const bars = categories.flatMap((cat, idx) => series.map((s) => ({ label: `${cat} \xB7 ${s.name}`, value: Number(s.data[idx]) || 0 })));
9371
+ const maxVal = Math.max(...bars.map((bar) => Math.abs(bar.value)), 1);
9372
+ const labelWidth = Math.min(18, Math.max(...series.map((s) => visualWidth(s.name)), 6));
9373
+ const valWidth = Math.max(...bars.map((bar) => visualWidth(formatCompactNumber(bar.value))), 5);
9374
+ const body = [seriesLegend(ctx), ""];
9375
+ categories.forEach((cat, idx) => {
9376
+ body.push(paint(ctx, "text", truncateVisual(String(cat), 40)));
9377
+ series.forEach((s, i) => {
9378
+ const value2 = Number(s.data[idx]) || 0;
9379
+ const plain = renderPreciseBar(Math.abs(value2) / maxVal, BAR_WIDTH).replace(/[█▏▎▍▌▋▊▉]/g, (m) => m === "\u2588" ? SERIES_GLYPHS[i] : m);
9380
+ body.push(` ${barRow(ctx, s.name, labelWidth, paintSeries(ctx, i, plain), visualWidth(plain), value2, valWidth)}`);
9381
+ });
9382
+ });
9383
+ body.push(...moreCategoriesNote(ctx, categories.length));
9384
+ const { badge, stats } = groupedStats(ctx, bars);
9385
+ return frame(ctx, badge, body, "Grouped Bar", stats);
9386
+ }
9387
+ function barCard(ctx) {
9388
+ const entries = ctx.processed.categories.slice(0, MAX_BAR_ENTRIES).map((cat, idx) => ({ label: String(cat), total: ctx.totalsPerCat[idx] }));
9389
+ const maxVal = Math.max(...entries.map((e) => Math.abs(e.total)), 1);
9390
+ const labelWidth = Math.min(20, Math.max(...entries.map((e) => visualWidth(e.label)), 6));
9391
+ const valWidth = Math.max(...entries.map((e) => visualWidth(formatCompactNumber(e.total))), 5);
9392
+ const body = entries.map((entry) => {
9393
+ const plain = renderPreciseBar(Math.abs(entry.total) / maxVal, BAR_WIDTH);
9394
+ const pct = !ctx.nonAdditive && ctx.grandTotal > 0 ? entry.total / ctx.grandTotal * 100 : void 0;
9395
+ return barRow(ctx, entry.label, labelWidth, paint(ctx, "accent", plain), visualWidth(plain), entry.total, valWidth, pct);
9396
+ });
9397
+ body.push(...moreCategoriesNote(ctx, entries.length));
9398
+ return frame(ctx, totalBadge(ctx), body, "Bar");
9399
+ }
9400
+ var MAX_SHARE_SLICES = 9;
9401
+ function shareCard(ctx) {
9402
+ const slices = ctx.processed.categories.map((cat, idx) => ({ label: String(cat), value: Math.max(0, ctx.totalsPerCat[idx]) })).sort((a, b) => b.value - a.value);
9403
+ const shown = slices.slice(0, MAX_SHARE_SLICES);
9404
+ const rest = slices.slice(MAX_SHARE_SLICES).reduce((sum, s) => sum + s.value, 0);
9405
+ if (rest > 0)
9406
+ shown.push({ label: `Other (${slices.length - MAX_SHARE_SLICES})`, value: rest });
9407
+ const total = shown.reduce((sum, s) => sum + s.value, 0) || 1;
9408
+ const labelWidth = Math.min(20, Math.max(...shown.map((s) => visualWidth(s.label)), 6));
9409
+ const valWidth = Math.max(...shown.map((s) => visualWidth(formatCompactNumber(s.value))), 5);
9410
+ const body = shown.map((slice, i) => {
9411
+ const plain = renderPreciseBar(slice.value / total, BAR_WIDTH);
9412
+ return barRow(ctx, slice.label, labelWidth, paintSeries(ctx, i, plain), visualWidth(plain), slice.value, valWidth, slice.value / total * 100);
9413
+ });
9414
+ const top = shown[0];
9415
+ const stats = `\u25CF Largest: ${truncateVisual(top.label, 16)} (${(top.value / total * 100).toFixed(1)}%) \xB7 ${slices.length} slices`;
9416
+ return frame(ctx, `Total ${formatCompactNumber(total)}`, body, ctx.config.type === "donut" ? "Donut" : "Pie", stats);
9417
+ }
9418
+ var HEAT_SHADES = ["\xB7", "\u2591", "\u2592", "\u2593", "\u2588"];
9419
+ var MAX_HEAT_ROWS = 14;
9420
+ var MAX_HEAT_COLUMNS = 8;
9421
+ var HEAT_CELL = 7;
9422
+ function heatmapCard(ctx) {
9423
+ const rows = ctx.processed.categories.slice(0, MAX_HEAT_ROWS).map(String);
9424
+ const cols = ctx.processed.series.slice(0, MAX_HEAT_COLUMNS);
9425
+ const values = cols.flatMap((c) => rows.map((_, r) => Number(c.data[r]) || 0));
9426
+ const min = Math.min(...values);
9427
+ const span = Math.max(...values) - min || 1;
9428
+ const labelWidth = Math.min(18, Math.max(...rows.map((r) => visualWidth(r)), 6));
9429
+ const header = `${" ".repeat(labelWidth)} ${cols.map((c) => padEndVisual(truncateVisual(c.name, HEAT_CELL - 1), HEAT_CELL)).join("")}`;
9430
+ const body = [paint(ctx, "muted", header)];
9431
+ rows.forEach((row, r) => {
9432
+ const cells = cols.map((c) => {
9433
+ const level = Math.round(((Number(c.data[r]) || 0) - min) / span * (HEAT_SHADES.length - 1));
9434
+ return `${paint(ctx, "accent", HEAT_SHADES[level].repeat(HEAT_CELL - 1))} `;
9435
+ });
9436
+ body.push(`${paint(ctx, "text", padEndVisual(truncateVisual(row, labelWidth), labelWidth))} ${cells.join("")}`);
9437
+ });
9438
+ body.push("", paint(ctx, "muted", `\xB7 low ${formatCompactNumber(min)} \u2588 high ${formatCompactNumber(min + span)}`));
9439
+ return frame(ctx, totalBadge(ctx), body, "Heatmap");
9440
+ }
9441
+ function scatterCard(ctx) {
9442
+ const data = processChartDataForScatter(ctx.dataset.rows, ctx.config);
9443
+ const points = data.series.flatMap((s, i) => s.data.map((p) => ({ ...p, series: i })));
9444
+ if (points.length === 0)
9445
+ return null;
9446
+ const cols = 58;
9447
+ const rows = 10;
9448
+ const grid = Array.from({ length: rows }, () => Array.from({ length: cols }).fill(0));
9449
+ const owners = Array.from({ length: rows }, () => Array.from({ length: cols }).fill(-1));
9450
+ const xs = points.map((p) => p.x);
9451
+ const ys = points.map((p) => p.y);
9452
+ const [xMin, xMax, yMin, yMax] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
9453
+ for (const p of points) {
9454
+ const px = Math.round((p.x - xMin) / (xMax - xMin || 1) * (cols * 2 - 1));
9455
+ const py = Math.round((1 - (p.y - yMin) / (yMax - yMin || 1)) * (rows * 4 - 1));
9456
+ const [r, c] = [Math.floor(py / 4), Math.floor(px / 2)];
9457
+ grid[r][c] |= BRAILLE_BITS[py % 4][px % 2];
9458
+ owners[r][c] = p.series;
9459
+ }
9460
+ const yWidth = Math.max(visualWidth(formatCompactNumber(yMax)), visualWidth(formatCompactNumber(yMin)), 6);
9461
+ const multi = data.series.length > 1;
9462
+ const body = multi ? [data.series.slice(0, 4).map((s, i) => paintSeries(ctx, i, `\u25CF ${truncateVisual(s.name, 14)}`)).join(" "), ""] : [];
9463
+ grid.forEach((cells, r) => {
9464
+ const tick = r === 0 ? formatCompactNumber(yMax) : r === rows - 1 ? formatCompactNumber(yMin) : "";
9465
+ const row = `${padStartVisual(tick, yWidth)} \u2524${cells.map((mask) => String.fromCharCode(10240 + mask)).join("")}`;
9466
+ body.push(ctx.pal ? paintPlotRow(ctx, row, owners[r], multi) : row);
9467
+ });
9468
+ body.push(paint(ctx, "border", `${" ".repeat(yWidth)} \u2514${"\u2500".repeat(cols)}`));
9469
+ const xMinLabel = formatCompactNumber(xMin);
9470
+ const xMaxLabel = formatCompactNumber(xMax);
9471
+ body.push(paint(ctx, "muted", `${" ".repeat(yWidth + 2)}${xMinLabel}${" ".repeat(Math.max(1, cols - visualWidth(xMinLabel) - visualWidth(xMaxLabel)))}${xMaxLabel}`));
9472
+ const stats = `${points.length.toLocaleString()} points \xB7 ${ctx.config.xAxis?.field} ${formatCompactNumber(xMin)}\u2013${formatCompactNumber(xMax)} \xB7 ${ctx.config.yAxis?.field} ${formatCompactNumber(yMin)}\u2013${formatCompactNumber(yMax)}`;
9473
+ return frame(ctx, `${points.length.toLocaleString()} pts`, body, ctx.config.type === "bubble" ? "Bubble" : "Scatter", stats);
9474
+ }
9475
+ var UNSTACKABLE_AGGREGATIONS = /* @__PURE__ */ new Set(["avg", "median", "min", "max", "stdDev"]);
9476
+ function chartCard(ctx) {
9477
+ const type = ctx.config.type;
9478
+ const multi = ctx.processed.series.length > 1;
9479
+ if ((type === "line" || type === "area") && ctx.processed.categories.length >= 3)
9480
+ return lineCard(ctx);
9481
+ if (type === "pie" || type === "donut")
9482
+ return shareCard(ctx);
9483
+ if (type === "scatter" || type === "bubble")
9484
+ return scatterCard(ctx) ?? barCard({ ...ctx, statsLine: `Scatter needs numbers on both axes; ${ctx.config.xAxis?.field} is not numeric, so it is shown as bars.` });
9485
+ if (type === "heatmap" && multi)
9486
+ return heatmapCard(ctx);
9487
+ if (multi && (type === "bar" || UNSTACKABLE_AGGREGATIONS.has(ctx.config.yAxis?.aggregation ?? "sum")))
9488
+ return groupedCard(ctx);
9489
+ return multi ? stackedCard(ctx) : barCard(ctx);
9490
+ }
9200
9491
  function formatTerminalChart(dataset, chartConfig, options = {}) {
9201
9492
  if (!chartConfig?.xAxis || !chartConfig?.yAxis || dataset.rows.length === 0)
9202
9493
  return "";
9203
- const fullConfig = {
9494
+ const config = {
9204
9495
  type: chartConfig.type ?? "bar",
9205
9496
  xAxis: chartConfig.xAxis,
9206
9497
  yAxis: chartConfig.yAxis,
9207
9498
  seriesField: chartConfig.seriesField,
9499
+ sizeField: chartConfig.sizeField,
9208
9500
  options: chartConfig.options
9209
9501
  };
9210
- const processed = processChartData(dataset.rows, fullConfig);
9502
+ const processed = processChartData(dataset.rows, config);
9211
9503
  if (!processed.categories.length || !processed.series.length)
9212
9504
  return "";
9213
- const title = chartConfig.options?.title || `${dataset.name} \xB7 ${chartConfig.yAxis.field} by ${chartConfig.xAxis.field}`;
9214
- const nonAdditive = isNonAdditiveMeasure(chartConfig.yAxis.field, chartConfig.yAxis.aggregation);
9215
9505
  const totalsPerCat = processed.categories.map(
9216
9506
  (_, idx) => processed.series.reduce((sum, s) => sum + (Number(s.data[idx]) || 0), 0)
9217
9507
  );
9218
9508
  const grandTotal = totalsPerCat.reduce((sum, v) => sum + v, 0);
9219
- const avgVal = grandTotal / totalsPerCat.length;
9220
- let peakIdx = 0;
9221
- let lowIdx = 0;
9222
- for (let i = 1; i < totalsPerCat.length; i++) {
9223
- if (totalsPerCat[i] > totalsPerCat[peakIdx])
9224
- peakIdx = i;
9225
- if (totalsPerCat[i] < totalsPerCat[lowIdx])
9226
- lowIdx = i;
9227
- }
9228
- const showBranding = options.showBranding !== false;
9509
+ let peak = 0;
9510
+ let low = 0;
9511
+ totalsPerCat.forEach((v, i) => {
9512
+ if (v > totalsPerCat[peak])
9513
+ peak = i;
9514
+ if (v < totalsPerCat[low])
9515
+ low = i;
9516
+ });
9229
9517
  const pal = resolveTerminalPalette(options.colorTheme);
9230
- const liveRow = options.companionUrl ? pal ? ansiFg(pal.accent, `\u2197 Live: ${options.companionUrl}`) : `\u2197 Live: ${options.companionUrl}` : null;
9231
- const peakCat = truncateVisual(String(processed.categories[peakIdx]), 14);
9232
- const lowCat = truncateVisual(String(processed.categories[lowIdx]), 14);
9233
- const statsLine = `\u25B2 Peak: ${peakCat} (${formatCompactNumber(totalsPerCat[peakIdx])}) \xB7 \u25BC Low: ${lowCat} (${formatCompactNumber(totalsPerCat[lowIdx])}) \xB7 \u25C6 Avg: ${formatCompactNumber(avgVal)}`;
9234
- if ((fullConfig.type === "line" || fullConfig.type === "area") && processed.categories.length >= 3) {
9235
- const categoriesStr = processed.categories.map(String);
9236
- const brailleSeries = processed.series.map((s) => ({
9237
- name: s.name,
9238
- values: s.data.map((val) => val !== null && Number.isFinite(val) ? val : null)
9239
- }));
9240
- const body2 = renderBrailleLineBody(categoriesStr, brailleSeries, fullConfig.type === "area", nonAdditive).map((row, rIdx) => {
9241
- if (!pal)
9242
- return row;
9243
- if (brailleSeries.length > 1 && rIdx === 0)
9244
- return ansiFg(pal.accent, row);
9245
- if (row.includes("\u2524") || row.includes("\u2502")) {
9246
- const splitIdx = Math.max(row.indexOf("\u2524"), row.indexOf("\u2502"));
9247
- return `${ansiFg(pal.muted, row.slice(0, splitIdx))}${ansiFg(pal.border, row[splitIdx])}${ansiFg(pal.accent, row.slice(splitIdx + 1))}`;
9248
- }
9249
- if (row.includes("\u2514"))
9250
- return ansiFg(pal.border, row);
9251
- return ansiFg(pal.muted, row);
9252
- });
9253
- let lineStats = statsLine;
9254
- let badge = `Total ${formatCompactNumber(grandTotal)}`;
9255
- if (nonAdditive) {
9256
- const allPts = brailleSeries.flatMap((s) => s.values.filter((v) => v !== null && Number.isFinite(v)));
9257
- if (brailleSeries.length === 1) {
9258
- const ptAvg = allPts.length > 0 ? allPts.reduce((a, b) => a + b, 0) / allPts.length : avgVal;
9259
- badge = `Avg ${formatCompactNumber(ptAvg)} \xB7 ${categoriesStr.length} pts`;
9260
- } else {
9261
- const ptMin = allPts.length > 0 ? Math.min(...allPts) : 0;
9262
- const ptMax = allPts.length > 0 ? Math.max(...allPts) : 0;
9263
- badge = `Range ${formatCompactNumber(ptMin)}\u2013${formatCompactNumber(ptMax)} \xB7 ${categoriesStr.length} pts`;
9264
- }
9265
- } else if (brailleSeries.length === 1) {
9266
- const delta = formatTrendDelta(totalsPerCat);
9267
- badge = delta ? `Total ${formatCompactNumber(grandTotal)} \xB7 ${delta}` : badge;
9268
- }
9269
- if (brailleSeries.length > 1) {
9270
- const perSeriesPeaks = brailleSeries.slice(0, 3).map((s) => {
9271
- let bestIdx = -1;
9272
- for (let i = 0; i < s.values.length; i++) {
9273
- const v = s.values[i];
9274
- if (v !== null && (bestIdx === -1 || v > (s.values[bestIdx] ?? Number.NEGATIVE_INFINITY)))
9275
- bestIdx = i;
9276
- }
9277
- return bestIdx >= 0 ? `${truncateVisual(s.name, 10)} peak: ${truncateVisual(categoriesStr[bestIdx], 8)} (${formatCompactNumber(s.values[bestIdx])})` : `${truncateVisual(s.name, 10)}: \u2014`;
9278
- });
9279
- lineStats = `\u25B2 ${perSeriesPeaks.join(" \xB7 ")}`;
9280
- }
9281
- body2.push(CARD_DIVIDER, pal ? ansiFg(pal.muted, lineStats) : lineStats);
9282
- if (liveRow)
9283
- body2.push(liveRow);
9284
- const chartKind2 = fullConfig.type === "area" ? "Area" : "Line";
9285
- const footerLeft2 = showBranding ? "tiny-pivot.com" : "";
9286
- const footerRight2 = `${dataset.rows.length.toLocaleString()} rows \xB7 ${chartKind2}`;
9287
- return wrapInCard(title, badge, body2, footerLeft2, footerRight2, 66, { palette: pal, raw: options.raw });
9288
- }
9289
- const maxEntries = 14;
9290
- const entries = processed.categories.slice(0, maxEntries).map((cat, idx) => ({
9291
- label: String(cat),
9292
- total: totalsPerCat[idx],
9293
- segments: processed.series.map((s) => Math.max(0, Number(s.data[idx]) || 0))
9294
- }));
9295
- const maxVal = Math.max(...entries.map((e) => Math.abs(e.total)), 1);
9296
- const labelWidth = Math.min(20, Math.max(...entries.map((e) => visualWidth(e.label)), 6));
9297
- const valWidth = Math.max(...entries.map((e) => visualWidth(formatCompactNumber(e.total))), 5);
9298
- const barWidth = 34;
9299
- const isMultiSeries = processed.series.length > 1 && (fullConfig.type === "stackedBar" || fullConfig.type === "bar");
9300
- const body = [];
9301
- if (isMultiSeries) {
9302
- const visibleLegend = processed.series.slice(0, SERIES_GLYPHS.length).map((s, i) => {
9303
- const glyph = pal ? ansiFg(pal.series[i % pal.series.length], SERIES_GLYPHS[i]) : SERIES_GLYPHS[i];
9304
- const name = pal ? ansiFg(pal.text, truncateVisual(s.name, 14)) : truncateVisual(s.name, 14);
9305
- return `${glyph} ${name}`;
9306
- });
9307
- if (processed.series.length > SERIES_GLYPHS.length)
9308
- visibleLegend.push(pal ? ansiFg(pal.muted, `+${processed.series.length - SERIES_GLYPHS.length} more`) : `+${processed.series.length - SERIES_GLYPHS.length} more`);
9309
- body.push(visibleLegend.join(" "));
9310
- body.push("");
9311
- }
9312
- for (const entry of entries) {
9313
- const labelPlain = padEndVisual(truncateVisual(entry.label, labelWidth), labelWidth);
9314
- const label = pal ? ansiFg(pal.text, labelPlain) : labelPlain;
9315
- let bar;
9316
- if (isMultiSeries) {
9317
- const totalWidth = entry.total === 0 ? 0 : Math.max(1, Math.round(Math.abs(entry.total) / maxVal * barWidth));
9318
- const segSum = entry.segments.reduce((a, b) => a + b, 0) || 1;
9319
- let builtPlainLen = 0;
9320
- let built = "";
9321
- for (let i = 0; i < entry.segments.length && builtPlainLen < totalWidth; i++) {
9322
- const segLen = i === entry.segments.length - 1 ? Math.max(0, totalWidth - builtPlainLen) : Math.round(entry.segments[i] / segSum * totalWidth);
9323
- if (segLen <= 0)
9324
- continue;
9325
- const segStr = SERIES_GLYPHS[i % SERIES_GLYPHS.length].repeat(segLen);
9326
- built += pal ? ansiFg(pal.series[i % pal.series.length], segStr) : segStr;
9327
- builtPlainLen += segLen;
9328
- }
9329
- bar = `${built}${" ".repeat(Math.max(0, barWidth - builtPlainLen))}`;
9330
- } else {
9331
- const rawBar = renderPreciseBar(Math.abs(entry.total) / maxVal, barWidth);
9332
- const coloredBar = pal ? ansiFg(pal.accent, rawBar) : rawBar;
9333
- bar = `${coloredBar}${" ".repeat(Math.max(0, barWidth - visualWidth(rawBar)))}`;
9334
- }
9335
- const valStr = padStartVisual(formatCompactNumber(entry.total), valWidth);
9336
- const pctStr = !nonAdditive && grandTotal > 0 ? `${(entry.total / grandTotal * 100).toFixed(1).padStart(5)}%` : "";
9337
- const sep = pal ? ansiFg(pal.border, "\u2502") : "\u2502";
9338
- const valOut = pal ? ansiFgBold(pal.text, valStr) : valStr;
9339
- const pctOut = pctStr ? pal ? ansiFg(pal.muted, pctStr) : pctStr : "";
9340
- body.push(`${label} ${sep} ${bar} ${valOut}${pctOut ? ` ${pctOut}` : ""}`);
9341
- }
9342
- if (processed.categories.length > entries.length) {
9343
- const more = `\u2026 +${processed.categories.length - entries.length} more categories (all interactive in TinyPivot)`;
9344
- body.push(pal ? ansiFg(pal.muted, more) : more);
9345
- }
9346
- body.push(CARD_DIVIDER, pal ? ansiFg(pal.muted, statsLine) : statsLine);
9347
- if (liveRow)
9348
- body.push(liveRow);
9349
- const footerLeft = showBranding ? "tiny-pivot.com" : "";
9350
- const chartKind = isMultiSeries ? "Stacked Bar" : "Bar";
9351
- const footerRight = `${dataset.rows.length.toLocaleString()} rows \xB7 ${chartKind}`;
9352
- const barBadge = nonAdditive ? `Avg ${formatCompactNumber(avgVal)} \xB7 ${processed.categories.length} pts` : `Total ${formatCompactNumber(grandTotal)}`;
9353
- return wrapInCard(title, barBadge, body, footerLeft, footerRight, 66, { palette: pal, raw: options.raw });
9518
+ const live = options.companionUrl ? `\u2197 Live: ${options.companionUrl}` : null;
9519
+ const ctx = {
9520
+ dataset,
9521
+ config,
9522
+ processed,
9523
+ title: chartConfig.options?.title || `${dataset.name} \xB7 ${chartConfig.yAxis.field} by ${chartConfig.xAxis.field}`,
9524
+ nonAdditive: isNonAdditiveMeasure(chartConfig.yAxis.field, chartConfig.yAxis.aggregation),
9525
+ totalsPerCat,
9526
+ grandTotal,
9527
+ pal,
9528
+ liveRow: live && pal ? ansiFg(pal.accent, live) : live,
9529
+ statsLine: `\u25B2 Peak: ${truncateVisual(String(processed.categories[peak]), 14)} (${formatCompactNumber(totalsPerCat[peak])}) \xB7 \u25BC Low: ${truncateVisual(String(processed.categories[low]), 14)} (${formatCompactNumber(totalsPerCat[low])}) \xB7 \u25C6 Avg: ${formatCompactNumber(grandTotal / totalsPerCat.length)}`,
9530
+ footerLeft: options.showBranding !== false ? "tiny-pivot.com" : "",
9531
+ raw: options.raw
9532
+ };
9533
+ return chartCard(ctx);
9354
9534
  }
9355
9535
  function detectNonAdditiveSumWarning(dataset, chartConfig) {
9356
9536
  const xField = chartConfig?.xAxis?.field;
@@ -9377,6 +9557,8 @@ function detectNonAdditiveSumWarning(dataset, chartConfig) {
9377
9557
  const grain = sField ? `\`(${xField}, ${sField})\`` : `\`${xField}\``;
9378
9558
  return `> **Data Integrity Warning:** \`${yField}\` appears to be a non-additive percentage/ratio, and **${collisions}** ${grain} bucket${collisions === 1 ? "" : "s"} contain multiple rows that were summed (\`aggregation: "sum"\`). Re-aggregate in SQL or Python to strictly 1 row per ${grain} using \`SUM(numerator) / SUM(denominator)\` before passing to TinyPivot.`;
9379
9559
  }
9560
+
9561
+ // src/summary.ts
9380
9562
  var SMALL_GRID_MAX_ROWS = 25;
9381
9563
  var SMALL_GRID_MAX_COLUMNS = 10;
9382
9564
  function tableCell(value2) {
@@ -9423,9 +9605,21 @@ function formatColumnNotes(columns) {
9423
9605
  return `Columns: ${notes.join(" \xB7 ") || "none"}`;
9424
9606
  }
9425
9607
  var REPRINT_NOTE = "Show the card above to the user verbatim.";
9608
+ var WIDGET_NOTE = "The user already sees this in the TinyPivot view in the chat: do not repeat the card or a table of it. Reply with the takeaways.";
9609
+ function cardNote(companionUrl, options) {
9610
+ if (options.shownInWidget)
9611
+ return WIDGET_NOTE;
9612
+ return companionUrl && options.reprintNote !== false ? REPRINT_NOTE : null;
9613
+ }
9614
+ function datasetCard(dataset, options = {}) {
9615
+ return pivotTableCard(dataset, options) ?? (formatTerminalChart(dataset, dataset.chartConfig, options) || null);
9616
+ }
9617
+ function cardTitle(card) {
9618
+ return /╭─ (.+?) ─/.exec(card.replace(/\x1B\[[0-9;]*m/g, ""))?.[1] ?? null;
9619
+ }
9426
9620
  function formatDatasetSummary(dataset, companionUrl, options = {}) {
9427
9621
  const cardOptions = { ...options, companionUrl: options.companionUrl ?? companionUrl };
9428
- const chartBlock = smallGridTable(dataset) ?? pivotTableCard(dataset, cardOptions) ?? formatTerminalChart(dataset, dataset.chartConfig, cardOptions);
9622
+ const chartBlock = smallGridTable(dataset) ?? datasetCard(dataset, cardOptions);
9429
9623
  const rowHeadline = dataset.truncatedForFreeTier ? `**${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows (Free tier limit)**` : `**${dataset.rows.length.toLocaleString()} rows**`;
9430
9624
  const parts = [
9431
9625
  `Loaded **${dataset.name}** (\`${dataset.id}\`): ${rowHeadline}, ${dataset.columns.length} columns.`
@@ -9442,11 +9636,12 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
9442
9636
  }
9443
9637
  if (chartBlock) {
9444
9638
  parts.push("", chartBlock);
9445
- if (companionUrl && options.reprintNote !== false)
9446
- parts.push(REPRINT_NOTE);
9639
+ const note = cardNote(companionUrl, options);
9640
+ if (note)
9641
+ parts.push(note);
9447
9642
  }
9448
9643
  parts.push("", formatColumnNotes(dataset.columns));
9449
- if (companionUrl && !chartBlock)
9644
+ if (companionUrl && !chartBlock?.includes(companionUrl))
9450
9645
  parts.push(`Studio: ${companionUrl}`);
9451
9646
  return parts.join("\n");
9452
9647
  }
@@ -9566,8 +9761,9 @@ function formatPivotSummary(dataset, config, companionUrl, options = {}) {
9566
9761
  }
9567
9762
  const headline = dataset.truncatedForFreeTier ? `Pivot on **${dataset.name}** (**first ${dataset.rows.length.toLocaleString()} of ${dataset.sourceTotalRows.toLocaleString()} rows \u2014 Free tier subset**):` : `Pivot on **${dataset.name}** (${dataset.rows.length.toLocaleString()} source rows):`;
9568
9763
  const out = [headline, "", tableLines.join("\n")];
9569
- if (companionUrl && options.reprintNote !== false)
9570
- out.push(REPRINT_NOTE);
9764
+ const note = cardNote(companionUrl, options);
9765
+ if (note)
9766
+ out.push(note);
9571
9767
  return out.join("\n");
9572
9768
  }
9573
9769
 
@@ -10102,65 +10298,6 @@ import fs3 from "fs/promises";
10102
10298
  import http from "http";
10103
10299
  import path3 from "path";
10104
10300
 
10105
- // src/analyst-endpoint.ts
10106
- var ANALYST_ROW_LIMIT = 1e4;
10107
- function schemaFor(dataset) {
10108
- return {
10109
- table: dataset.id,
10110
- columns: dataset.columns.map((column) => ({
10111
- name: column.name,
10112
- type: column.type === "null" ? "unknown" : column.type,
10113
- nullable: true
10114
- }))
10115
- };
10116
- }
10117
- function queryableDatasets(studio) {
10118
- return studio.queryViews().flatMap((view) => studio.store.get(view.name) ?? []);
10119
- }
10120
- function chatTurns(messages) {
10121
- if (!Array.isArray(messages))
10122
- return [];
10123
- return messages.flatMap((message) => {
10124
- const { role, content } = message ?? {};
10125
- return (role === "user" || role === "assistant") && typeof content === "string" ? [{ role, content }] : [];
10126
- });
10127
- }
10128
- async function runQuery(studio, sql) {
10129
- if (typeof sql !== "string" || !sql.trim())
10130
- return { status: 400, body: { success: false, error: "Send one SELECT statement." } };
10131
- try {
10132
- const result = await studio.duck.run(sql, studio.queryViews(), ANALYST_ROW_LIMIT);
10133
- return { status: 200, body: { success: true, data: result.rows, rowCount: result.rows.length, truncated: result.truncated } };
10134
- } catch (error) {
10135
- return { status: 200, body: { success: false, error: error instanceof Error ? error.message : String(error) } };
10136
- }
10137
- }
10138
- async function chat(studio, messages) {
10139
- const turns = chatTurns(messages);
10140
- const question = turns.filter((turn) => turn.role === "user").at(-1)?.content.trim();
10141
- if (!question)
10142
- return { status: 400, body: { error: "Ask a question." } };
10143
- return { status: 200, body: { content: await studio.ask(question, { turns }) } };
10144
- }
10145
- async function handleAnalystAction(studio, body) {
10146
- switch (body.action) {
10147
- case "list-tables":
10148
- return { status: 200, body: { tables: queryableDatasets(studio).map((ds) => ({ name: ds.id, description: `${ds.name}: ${ds.rows.length.toLocaleString("en-US")} rows` })) } };
10149
- case "get-schema": {
10150
- const wanted = new Set(Array.isArray(body.tables) ? body.tables.map(String) : []);
10151
- return { status: 200, body: { schemas: queryableDatasets(studio).filter((ds) => wanted.has(ds.id)).map(schemaFor) } };
10152
- }
10153
- case "get-all-schemas":
10154
- return { status: 200, body: { schemas: queryableDatasets(studio).map(schemaFor) } };
10155
- case "query":
10156
- return runQuery(studio, body.sql);
10157
- case "chat":
10158
- return chat(studio, body.messages);
10159
- default:
10160
- return { status: 400, body: { error: `Unknown action: ${String(body.action)}` } };
10161
- }
10162
- }
10163
-
10164
10301
  // src/limits.ts
10165
10302
  var INTERACTIVE_ROW_LIMIT = 1e5;
10166
10303
  var ROW_PAGE_SIZE = 25e3;
@@ -10189,7 +10326,7 @@ function openAgentStream(studio, agentName, req, res) {
10189
10326
  if (res.writableEnded)
10190
10327
  return false;
10191
10328
  res.write(`event: message
10192
- data: ${JSON.stringify({ id: note.id, kind: note.kind, text })}
10329
+ data: ${JSON.stringify({ id: note.id, text })}
10193
10330
 
10194
10331
  `);
10195
10332
  return true;
@@ -10202,6 +10339,19 @@ data: ${JSON.stringify({ id: note.id, kind: note.kind, text })}
10202
10339
  disconnect();
10203
10340
  });
10204
10341
  }
10342
+ function colouredCard(store, title, companionUrl, isPro2) {
10343
+ if (!title)
10344
+ return null;
10345
+ for (const meta of store.listMetadata()) {
10346
+ const dataset = store.get(meta.id);
10347
+ if (!dataset)
10348
+ continue;
10349
+ const card = datasetCard(dataset, { colorTheme: store.getVisualTheme(), raw: true, companionUrl, showBranding: !isPro2 });
10350
+ if (card && cardTitle(card) === title)
10351
+ return card;
10352
+ }
10353
+ return null;
10354
+ }
10205
10355
  function sendJson(res, status, body) {
10206
10356
  res.writeHead(status, { "Content-Type": "application/json" });
10207
10357
  res.end(JSON.stringify(body));
@@ -10277,13 +10427,13 @@ function buildFullCompanionPayload(store, datasetId, opts) {
10277
10427
  async function startCompanionServer(options) {
10278
10428
  const sseClients = /* @__PURE__ */ new Set();
10279
10429
  const send = (event, payload) => {
10280
- const frame = `event: ${event}
10430
+ const frame2 = `event: ${event}
10281
10431
  data: ${JSON.stringify(payload)}
10282
10432
 
10283
10433
  `;
10284
10434
  for (const res of sseClients) {
10285
10435
  try {
10286
- res.write(frame);
10436
+ res.write(frame2);
10287
10437
  } catch {
10288
10438
  sseClients.delete(res);
10289
10439
  }
@@ -10330,17 +10480,13 @@ data: ${JSON.stringify(payload)}
10330
10480
  const text = typeof body.text === "string" ? body.text.trim() : "";
10331
10481
  if (!text)
10332
10482
  return sendJson(res, 400, { error: "Send the reply text." });
10333
- studio.reply(text.slice(0, 2e4), typeof body.re === "string" ? body.re : void 0);
10483
+ studio.reply(text.slice(0, 2e4));
10334
10484
  return sendJson(res, 200, { ok: true });
10335
10485
  }
10336
10486
  if (pathname === "/api/studio/agent-status") {
10337
10487
  studio.setAgentBusy(body.busy === true);
10338
10488
  return sendJson(res, 200, { ok: true });
10339
10489
  }
10340
- if (pathname === "/api/studio/analyst") {
10341
- const result = await handleAnalystAction(studio, body);
10342
- return sendJson(res, result.status, result.body);
10343
- }
10344
10490
  if (pathname === "/api/studio/show") {
10345
10491
  try {
10346
10492
  const dataset = await studio.showStep(String(body.stepId ?? ""));
@@ -10361,17 +10507,17 @@ data: ${JSON.stringify(payload)}
10361
10507
  }
10362
10508
  return sendJson(res, 404, { error: "Not found" });
10363
10509
  };
10510
+ let listenPort = 0;
10364
10511
  const server = http.createServer(async (req, res) => {
10365
10512
  const urlObj = new URL(req.url || "/", "http://127.0.0.1");
10366
10513
  const pathname = urlObj.pathname;
10367
10514
  res.setHeader("Cache-Control", "no-store");
10368
- const port = server.address().port;
10369
10515
  const allowed = isAllowedRequest({
10370
10516
  method: req.method,
10371
10517
  host: req.headers.host,
10372
10518
  origin: req.headers.origin,
10373
10519
  studioHeader: req.headers[STUDIO_HEADER]
10374
- }, port);
10520
+ }, listenPort);
10375
10521
  if (!allowed)
10376
10522
  return sendJson(res, 403, { error: "Forbidden" });
10377
10523
  if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
@@ -10403,6 +10549,11 @@ data: ${JSON.stringify(studio.snapshot())}
10403
10549
  openAgentStream(studio, agentName, req, res);
10404
10550
  return;
10405
10551
  }
10552
+ if (req.method === "GET" && pathname === "/api/studio/card") {
10553
+ const title = urlObj.searchParams.get("title") ?? "";
10554
+ const ansi = colouredCard(options.store, title, `http://127.0.0.1:${listenPort}`, Boolean(options.licenseKey || options.demoToken));
10555
+ return ansi ? sendJson(res, 200, { ansi }) : sendJson(res, 404, { error: "No card with that title." });
10556
+ }
10406
10557
  if (req.method === "GET" && pathname === "/api/studio") {
10407
10558
  return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
10408
10559
  }
@@ -10459,6 +10610,7 @@ data: ${JSON.stringify(studio.snapshot())}
10459
10610
  server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
10460
10611
  });
10461
10612
  const address = server.address();
10613
+ listenPort = address.port;
10462
10614
  const url = `http://127.0.0.1:${address.port}`;
10463
10615
  const sessionFile = getCompanionSessionFile();
10464
10616
  try {
@@ -10486,6 +10638,7 @@ data: ${JSON.stringify(studio.snapshot())}
10486
10638
  sseClients.clear();
10487
10639
  await new Promise((resolve) => {
10488
10640
  server.close(() => resolve());
10641
+ server.closeAllConnections();
10489
10642
  });
10490
10643
  try {
10491
10644
  const raw = await fs3.readFile(sessionFile, "utf8");
@@ -10614,6 +10767,12 @@ function colorizeSegments(text: string, pal: Palette): string {
10614
10767
  });
10615
10768
  }
10616
10769
 
10770
+ // Makes the Studio address in a card clickable, as an OSC 8 terminal hyperlink.
10771
+ const CARD_LINK = /http:[/][/]127[.]0[.]0[.]1:[0-9]+/;
10772
+ function hyperlink(text: string): string {
10773
+ return text.replace(CARD_LINK, url => "\\x1b]8;;" + url + "\\x1b\\\\" + url + "\\x1b]8;;\\x1b\\\\");
10774
+ }
10775
+
10617
10776
  function colorizeCardLine(line: string, pal: Palette): string {
10618
10777
  if (line.startsWith("\u256D\u2500")) {
10619
10778
  const withBadge = line.replace(/^(\u256D\u2500 )(.+?)( \u2500+ )(.+?)( \u2500\u256E)$/, (_m, a, b, c, d, e) =>
@@ -10638,7 +10797,7 @@ function colorizeCardLine(line: string, pal: Palette): string {
10638
10797
  const edge = fg(pal.border, "\u2502");
10639
10798
 
10640
10799
  if (inner.includes("\u2197 Live:")) {
10641
- return \`\${edge}\${fgBold(pal.accent, inner)}\${edge}\`;
10800
+ return \`\${edge}\${fgBold(pal.accent, hyperlink(inner))}\${edge}\`;
10642
10801
  }
10643
10802
  if (inner.includes("\u25B2 ") && (inner.includes("Peak:") || inner.includes("peak:"))) {
10644
10803
  return \`\${edge}\${fg(pal.muted, inner)}\${edge}\`;
@@ -10690,6 +10849,8 @@ function isTinyPivotTool(toolName: string): boolean {
10690
10849
  interface TinyPivotCardEntryData {
10691
10850
  cards: string[];
10692
10851
  themeId: string;
10852
+ /** The same cards in full colour from the Studio, where it could provide them. */
10853
+ coloured?: Array<string | null>;
10693
10854
  }
10694
10855
 
10695
10856
  // TinyPivot Studio bridge: messages the user sends from the Studio arrive here, go into this
@@ -10717,14 +10878,15 @@ function lastAssistantText(messages: unknown): string {
10717
10878
  function createStudioBridge(pi: any) {
10718
10879
  let studioUrl: string | undefined;
10719
10880
  let stream: AbortController | undefined;
10720
- let awaiting: string | undefined;
10881
+ /** Set while a turn that a Studio message started is running, so its answer goes back. */
10882
+ let awaiting = false;
10721
10883
 
10722
10884
  function handleFrame(frame: string): void {
10723
10885
  if (!frame.startsWith("event: message")) return;
10724
10886
  const data = frame.split("\\n").find(line => line.startsWith("data: "));
10725
10887
  if (!data) return;
10726
- const message = JSON.parse(data.slice(6)) as { id: string; text: string };
10727
- awaiting = message.id;
10888
+ const message = JSON.parse(data.slice(6)) as { text: string };
10889
+ awaiting = true;
10728
10890
  pi.sendMessage(
10729
10891
  { customType: "tinypivot-studio", content: message.text, display: true },
10730
10892
  { triggerTurn: true, deliverAs: "steer" },
@@ -10779,11 +10941,25 @@ function createStudioBridge(pi: any) {
10779
10941
  },
10780
10942
  async onAgentEnd(messages: unknown): Promise<void> {
10781
10943
  if (!awaiting || !studioUrl) return;
10782
- const re = awaiting;
10783
- awaiting = undefined;
10944
+ awaiting = false;
10784
10945
  const text = lastAssistantText(messages);
10785
10946
  if (!text) return;
10786
- await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ re, text }) }).catch(() => {});
10947
+ await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ text }) }).catch(() => {});
10948
+ },
10949
+ /** Each card in full colour from the Studio (lines in each series' colour), or null. */
10950
+ async colouredCards(cards: string[]): Promise<Array<string | null>> {
10951
+ if (!studioUrl) return cards.map(() => null);
10952
+ const url = studioUrl;
10953
+ return Promise.all(cards.map(async (card) => {
10954
+ const title = /\u256D\u2500 (.+?) \u2500/.exec(card)?.[1];
10955
+ if (!title) return null;
10956
+ try {
10957
+ const res = await fetch(url + "/api/studio/card?title=" + encodeURIComponent(title), { signal: AbortSignal.timeout(1500) });
10958
+ return res.ok ? ((await res.json()) as { ansi?: string }).ansi ?? null : null;
10959
+ } catch {
10960
+ return null;
10961
+ }
10962
+ }));
10787
10963
  },
10788
10964
  stop(): void {
10789
10965
  stream?.abort();
@@ -10807,10 +10983,12 @@ export default function (pi: any) {
10807
10983
  render(_width: number): string[] {
10808
10984
  const themeId = data.themeId || readActiveThemeId();
10809
10985
  const out: string[] = [""];
10810
- for (const card of data.cards) {
10811
- out.push(...renderColoredCard(card, themeId).map(l => \` \${l}\`));
10986
+ data.cards.forEach((card, i) => {
10987
+ const coloured = data.coloured?.[i];
10988
+ const lines = coloured ? coloured.split("\\n").map(hyperlink) : renderColoredCard(card, themeId);
10989
+ out.push(...lines.map(l => \` \${l}\`));
10812
10990
  out.push("");
10813
- }
10991
+ });
10814
10992
  return out;
10815
10993
  },
10816
10994
  invalidate() {},
@@ -10818,19 +10996,21 @@ export default function (pi: any) {
10818
10996
  });
10819
10997
  }
10820
10998
 
10821
- pi.on("tool_execution_end", (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
10999
+ pi.on("tool_execution_end", async (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
10822
11000
  if (event?.isError) return;
10823
11001
  const text = extractResultText(event.result);
10824
11002
  if (!text) return;
10825
11003
  // TinyPivot calls made through codemode arrive under another tool's name, so look at the text.
10826
11004
  studio.noticeToolText(text);
10827
- if (!event?.toolName || !isTinyPivotTool(event.toolName) || ctx?.hasUI === false) return;
11005
+ const fromTinyPivot = isTinyPivotTool(event?.toolName ?? "") || event?.toolName === "codemode";
11006
+ if (!fromTinyPivot || ctx?.hasUI === false) return;
10828
11007
  const cards = extractTinyPivotCards(text);
10829
11008
  if (cards.length === 0) return;
10830
11009
 
10831
11010
  const themeId = readActiveThemeId();
11011
+ const coloured = await studio.colouredCards(cards);
10832
11012
  if (typeof pi.appendEntry === "function") {
10833
- pi.appendEntry("tinypivot-card", { cards, themeId });
11013
+ pi.appendEntry("tinypivot-card", { cards, themeId, coloured });
10834
11014
  }
10835
11015
  });
10836
11016
 
@@ -10878,7 +11058,17 @@ var RULE_END = "<!-- tinypivot:end -->";
10878
11058
  var RULE_TEST_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/;
10879
11059
  var RULE_REPLACE_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/g;
10880
11060
  var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
10881
- var RULE_USE = "Use the `tinypivot` MCP server for charts, pivot tables and data exploration instead of drawing them yourself.";
11061
+ var RULE_USE = "Whenever an answer shows figures (a ranking, a breakdown by category, a comparison, a trend, a chart or a pivot), present them with the `tinypivot` MCP server instead of a Markdown table or a chart you draw yourself.";
11062
+ var PI_ENTRY_EXTRAS = {
11063
+ description: "Show any table of figures, ranking, breakdown, trend, chart or pivot to the user. Use it instead of Markdown tables.",
11064
+ toolExposure: {
11065
+ load_file: "direct",
11066
+ load_data: "direct",
11067
+ query: "direct",
11068
+ configure_chart: "direct",
11069
+ configure_pivot: "direct"
11070
+ }
11071
+ };
10882
11072
  var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
10883
11073
  ${RULE_HEADING}
10884
11074
  ${RULE_USE} In a terminal, show its \`text\` card verbatim with the Studio link.
@@ -11007,7 +11197,7 @@ function buildStdioServerEntry(opts, cliPath) {
11007
11197
  entry.env = env;
11008
11198
  return entry;
11009
11199
  }
11010
- async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath) {
11200
+ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath, extras = {}) {
11011
11201
  const explicit = opts.targets?.has(id) ?? false;
11012
11202
  const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(detectDir);
11013
11203
  if (!shouldInclude) {
@@ -11016,8 +11206,14 @@ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cli
11016
11206
  try {
11017
11207
  const json = await readJsonSafe(configPath);
11018
11208
  const mcpServers = json.mcpServers && typeof json.mcpServers === "object" && !Array.isArray(json.mcpServers) ? { ...json.mcpServers } : {};
11019
- const nextEntry = buildStdioServerEntry(opts, cliPath);
11209
+ const nextEntry = { ...buildStdioServerEntry(opts, cliPath) };
11020
11210
  const existing = mcpServers.tinypivot;
11211
+ if (extras.description)
11212
+ nextEntry.description = extras.description;
11213
+ if (extras.toolExposure) {
11214
+ const chosen = existing?.toolExposure && typeof existing.toolExposure === "object" ? existing.toolExposure : {};
11215
+ nextEntry.toolExposure = { ...extras.toolExposure, ...chosen };
11216
+ }
11021
11217
  if (existing?.env && typeof existing.env === "object" && !Array.isArray(existing.env)) {
11022
11218
  nextEntry.env = {
11023
11219
  ...existing.env,
@@ -11203,13 +11399,29 @@ async function upsertRuleFile(targetId, ruleId, label, detectDir, ruleFilePath,
11203
11399
  };
11204
11400
  }
11205
11401
  }
11402
+ function piExtensionPath(home = os3.homedir()) {
11403
+ return path4.join(home, ".pi", "agent", "extensions", "tinypivot.ts");
11404
+ }
11405
+ var PI_EXTENSION_HEADER = "// Auto-installed by @smallwebco/tinypivot-mcp init";
11406
+ async function refreshPiExtension(extPath = piExtensionPath()) {
11407
+ const existing = await exists(extPath) ? await fs4.readFile(extPath, "utf8") : null;
11408
+ if (existing === null)
11409
+ return "absent";
11410
+ if (!existing.startsWith(PI_EXTENSION_HEADER))
11411
+ return "custom";
11412
+ const next = buildPiExtensionSource();
11413
+ if (existing === next)
11414
+ return "current";
11415
+ await fs4.writeFile(extPath, next, "utf8");
11416
+ return "updated";
11417
+ }
11206
11418
  async function upsertPiExtension(opts) {
11207
11419
  const targeting = opts.targets ? opts.targets.has("pi") : true;
11208
11420
  if (!targeting)
11209
11421
  return null;
11210
11422
  const home = os3.homedir();
11211
11423
  const piDir = path4.join(home, ".pi");
11212
- const extPath = path4.join(piDir, "agent", "extensions", "tinypivot.ts");
11424
+ const extPath = piExtensionPath(home);
11213
11425
  const explicit = opts.targets?.has("pi") ?? false;
11214
11426
  if (!opts.all && !explicit && !await exists(piDir))
11215
11427
  return null;
@@ -11315,7 +11527,8 @@ TinyPivot MCP Installer (${opts.local ? `local: ${cliPath}` : `npx ${MCP_NPX_SPE
11315
11527
  path4.join(home, ".pi", "agent", "mcp.json"),
11316
11528
  path4.join(home, ".pi"),
11317
11529
  opts,
11318
- cliPath
11530
+ cliPath,
11531
+ PI_ENTRY_EXTRAS
11319
11532
  ),
11320
11533
  await upsertOpenCodeJson(opts, cliPath),
11321
11534
  await upsertCodexToml(opts, cliPath)
@@ -11687,7 +11900,6 @@ var AgentBridge = class {
11687
11900
  this.onChange = onChange;
11688
11901
  }
11689
11902
  connectors = /* @__PURE__ */ new Set();
11690
- waiters = /* @__PURE__ */ new Map();
11691
11903
  /** Adds a way to reach the agent; the returned function removes it. */
11692
11904
  connect(connector) {
11693
11905
  this.connectors.add(connector);
@@ -11701,38 +11913,14 @@ var AgentBridge = class {
11701
11913
  live() {
11702
11914
  return [...this.connectors].map((connector) => connector.name);
11703
11915
  }
11704
- /** Delivers into the conversation through the first connector that can. */
11916
+ /** Delivers into the conversation through the first connector that takes it. */
11705
11917
  push(note, text) {
11706
11918
  for (const connector of this.connectors) {
11707
- if (connector.push?.(note, text))
11919
+ if (connector.push(note, text))
11708
11920
  return connector.name;
11709
11921
  }
11710
11922
  return void 0;
11711
11923
  }
11712
- completer() {
11713
- return [...this.connectors].find((connector) => connector.complete)?.complete;
11714
- }
11715
- /** Resolves with the agent's answer to `id`, or undefined after `ms`. */
11716
- waitForReply(id, ms) {
11717
- return new Promise((resolve) => {
11718
- const timer = setTimeout(() => {
11719
- this.waiters.delete(id);
11720
- resolve(void 0);
11721
- }, ms);
11722
- timer.unref?.();
11723
- this.waiters.set(id, (text) => {
11724
- clearTimeout(timer);
11725
- this.waiters.delete(id);
11726
- resolve(text);
11727
- });
11728
- });
11729
- }
11730
- /** Hands an answer to whoever waits for `re`, or to the oldest waiter when `re` is unknown. */
11731
- answer(text, re) {
11732
- const waiter = re && this.waiters.get(re) || this.waiters.values().next().value;
11733
- waiter?.(text);
11734
- return Boolean(waiter);
11735
- }
11736
11924
  };
11737
11925
 
11738
11926
  // src/duckdb.ts
@@ -11995,7 +12183,6 @@ function formatHistoryList(entries) {
11995
12183
  // src/studio.ts
11996
12184
  var STEPS_IN_MEMORY = 300;
11997
12185
  var HISTORY_IN_SNAPSHOT = 50;
11998
- var ANSWER_WAIT_MS = 4 * 60 * 1e3;
11999
12186
  var ATTACHMENT_MAX_CHARS = 6e3;
12000
12187
  var AGENT_NAMES = {
12001
12188
  "claude-code": "Claude Code",
@@ -12076,10 +12263,11 @@ var Studio = class {
12076
12263
  pullsByDataset = /* @__PURE__ */ new Map();
12077
12264
  listeners = /* @__PURE__ */ new Set();
12078
12265
  changeQueued = false;
12079
- /** Ways to reach the user's agent: live channels, sampling, or nothing (queued notes). */
12266
+ /** Ways to reach the user's agent live; without one, notes wait for its next TinyPivot reply. */
12080
12267
  agent = new AgentBridge(() => this.changed());
12081
12268
  agentName;
12082
12269
  agentBusy = false;
12270
+ agentHint;
12083
12271
  /** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
12084
12272
  subscribe(listener) {
12085
12273
  this.listeners.add(listener);
@@ -12105,9 +12293,14 @@ var Studio = class {
12105
12293
  history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
12106
12294
  historyEnabled: this.history.enabled,
12107
12295
  loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
12108
- agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy }
12296
+ agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy, ...this.agentHint ? { hint: this.agentHint } : {} }
12109
12297
  };
12110
12298
  }
12299
+ /** What would let this agent receive Studio messages live, shown while it cannot. */
12300
+ setAgentHint(hint) {
12301
+ this.agentHint = hint;
12302
+ this.changed();
12303
+ }
12111
12304
  /** Whether the agent is in the middle of a turn, as its extension reports it. */
12112
12305
  setAgentBusy(busy) {
12113
12306
  if (busy === this.agentBusy)
@@ -12276,10 +12469,9 @@ var Studio = class {
12276
12469
  addNote(text, options = {}) {
12277
12470
  const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
12278
12471
  const note = {
12279
- id: nextId(options.kind === "question" ? "ask" : "note"),
12472
+ id: nextId("note"),
12280
12473
  at: (/* @__PURE__ */ new Date()).toISOString(),
12281
12474
  text: text.trim(),
12282
- kind: options.kind ?? "note",
12283
12475
  delivery: "queued",
12284
12476
  ...options.stepId ? { stepId: options.stepId } : {},
12285
12477
  ...attachment ? { attachment } : {}
@@ -12288,7 +12480,7 @@ var Studio = class {
12288
12480
  note.delivery = "live";
12289
12481
  else
12290
12482
  this.notes.push(note);
12291
- this.record({ actor: "user", tool: note.kind === "question" ? "ask" : "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
12483
+ this.record({ actor: "user", tool: "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
12292
12484
  return note;
12293
12485
  }
12294
12486
  /**
@@ -12297,7 +12489,7 @@ var Studio = class {
12297
12489
  */
12298
12490
  describeNote(note, { withSource = false } = {}) {
12299
12491
  const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
12300
- const source = withSource || note.kind === "question" ? `${note.kind === "question" ? "Question" : "Message"} from the user in TinyPivot Studio: ` : "";
12492
+ const source = withSource ? "Message from the user in TinyPivot Studio: " : "";
12301
12493
  const lines = [`${source}${note.text}`];
12302
12494
  if (step)
12303
12495
  lines.push(`About the step "${step.why ?? step.view ?? step.tool}"${step.datasetId ? ` on dataset \`${step.datasetId}\`` : ""}${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""}`);
@@ -12305,31 +12497,9 @@ var Studio = class {
12305
12497
  lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
12306
12498
  return lines.join("\n");
12307
12499
  }
12308
- /**
12309
- * Answers an AI Analyst question with the user's own agent: its model directly when the host
12310
- * offers sampling, otherwise through its conversation, waiting for the reply.
12311
- */
12312
- async ask(question, options = {}) {
12313
- const complete = this.agent.completer();
12314
- if (complete) {
12315
- this.record({ actor: "user", tool: "ask", why: question });
12316
- const answer2 = await complete(options.turns?.length ? options.turns : [{ role: "user", content: question }]);
12317
- this.reply(answer2);
12318
- return answer2;
12319
- }
12320
- const note = this.addNote(question, { kind: "question", attachment: options.attachment });
12321
- const name = agentLabel(this.agentName);
12322
- if (note.delivery === "queued")
12323
- return `${name} is not connected to the Studio live, so this question goes to it with its next TinyPivot reply. To ask now, use Copy as prompt in the Studio and paste it into ${name}.`;
12324
- const answer = await this.agent.waitForReply(note.id, options.waitMs ?? ANSWER_WAIT_MS);
12325
- return answer ?? `${name} is still working on this. Its answer will appear in the Studio trace.`;
12326
- }
12327
- /** The agent's answer to a Studio message: recorded in the trace and handed to whoever waits for it. */
12328
- reply(text, re) {
12329
- const answer = withoutCards(text);
12330
- const step = this.record({ actor: "agent", tool: "reply", why: answer });
12331
- this.agent.answer(answer, re);
12332
- return step;
12500
+ /** The agent's answer to a Studio message, recorded in the trace where the user reads it. */
12501
+ reply(text) {
12502
+ return this.record({ actor: "agent", tool: "reply", why: withoutCards(text) });
12333
12503
  }
12334
12504
  /** Drops a queued note the user no longer wants sent. */
12335
12505
  removeNote(id) {
@@ -12469,7 +12639,7 @@ import fsSync2 from "fs";
12469
12639
  import os6 from "os";
12470
12640
  import path8 from "path";
12471
12641
  var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
12472
- var PACKAGE_VERSION = "0.5.0";
12642
+ var PACKAGE_VERSION = "0.6.0";
12473
12643
  function isTelemetryEnabled() {
12474
12644
  if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
12475
12645
  return false;
@@ -12549,14 +12719,14 @@ var APP_RESOURCE_URI = "ui://tinypivot/app.html";
12549
12719
  var APP_MIME_TYPE = "text/html;profile=mcp-app";
12550
12720
  var LOAD_DATA_ROW_GUIDE = 50;
12551
12721
  function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
12552
- const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link in your reply, except in pi, whose TinyPivot extension already displays it." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
12722
+ const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link, except in pi, which already shows it. Where TinyPivot shows its view in the chat, never repeat the card." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
12553
12723
  return [
12554
- "Use TinyPivot for charts, pivot tables, period comparisons and tabular exploration instead of drawing them yourself (HTML, SVG, matplotlib, Markdown tables), passing chartConfig or pivotConfig in the same call.",
12724
+ "Show figures through TinyPivot: any ranking, breakdown, comparison, trend, chart or pivot, instead of Markdown tables, HTML, SVG or matplotlib, passing chartConfig or pivotConfig in the same call.",
12555
12725
  `For files use load_file, so the rows stay out of your context; to filter, join or aggregate files first, use query with SQL. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first. history lists and reopens earlier pulls.`,
12556
12726
  "Totals are exact. Compute ratios, shares and rates as numerator / denominator, one row per chart point, before loading; never add up percentage columns, and do not use percentOfTotal for a share within a period.",
12557
12727
  "Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
12558
12728
  "Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
12559
- ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply, passing the message id as re.'] : [],
12729
+ ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply.'] : [],
12560
12730
  cards
12561
12731
  ].join(" ");
12562
12732
  }
@@ -12643,6 +12813,12 @@ function normalizePivot(pivotConfig) {
12643
12813
  valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
12644
12814
  };
12645
12815
  }
12816
+ var PI_HINTS = {
12817
+ current: void 0,
12818
+ custom: void 0,
12819
+ updated: "TinyPivot's pi extension was just updated. Restart pi to send messages live.",
12820
+ absent: "Run npx @smallwebco/tinypivot-mcp@latest init --targets=pi, then restart pi, to send messages live."
12821
+ };
12646
12822
  var whyParam = z.string().max(240).optional();
12647
12823
  var DUCKDB_WAIT_MS = 45e3;
12648
12824
  function toCoreChartConfig(input) {
@@ -12769,7 +12945,6 @@ function createTinyPivotMcpServer(options = {}) {
12769
12945
  };
12770
12946
  const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
12771
12947
  const claudeChannel = options.claudeChannel ?? claudeChannelEnabled();
12772
- const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
12773
12948
  const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
12774
12949
  connectionString: process.env.DATABASE_URL,
12775
12950
  allowedTables: process.env.TINYPIVOT_ALLOWED_TABLES ? process.env.TINYPIVOT_ALLOWED_TABLES.split(",").map((s) => s.trim()).filter(Boolean) : void 0
@@ -12777,7 +12952,7 @@ function createTinyPivotMcpServer(options = {}) {
12777
12952
  const server = new McpServer(
12778
12953
  {
12779
12954
  name: "tinypivot",
12780
- version: "0.5.0"
12955
+ version: "0.6.0"
12781
12956
  },
12782
12957
  {
12783
12958
  capabilities: {
@@ -12789,6 +12964,7 @@ function createTinyPivotMcpServer(options = {}) {
12789
12964
  }
12790
12965
  );
12791
12966
  const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
12967
+ const cardFormat = () => ({ showBranding: !isPro2, reprintNote: reprintCards, shownInWidget: clientRendersWidget() });
12792
12968
  const resolveCompanionUrlForTool = async (forceCompanion = false) => {
12793
12969
  if (activeCompanionUrl)
12794
12970
  return activeCompanionUrl;
@@ -12805,7 +12981,7 @@ function createTinyPivotMcpServer(options = {}) {
12805
12981
  };
12806
12982
  const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
12807
12983
  const liveCompanionUrl = await resolveCompanionUrlForTool();
12808
- const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
12984
+ const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`);
12809
12985
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
12810
12986
  recordTelemetry({
12811
12987
  event: "tool_call",
@@ -12826,31 +13002,25 @@ function createTinyPivotMcpServer(options = {}) {
12826
13002
  }
12827
13003
  const withNotes = (text) => `${text}${studio.takeNotes()}`;
12828
13004
  const connectAgent = () => {
12829
- studio.setAgentName(server.server.getClientVersion()?.name);
13005
+ const clientName = server.server.getClientVersion()?.name;
13006
+ studio.setAgentName(clientName);
13007
+ if (clientName === "pi")
13008
+ void refreshPiExtension().then((status) => studio.setAgentHint(PI_HINTS[status])).catch(() => {
13009
+ });
13010
+ if (clientName === "claude-code" && !claudeChannel)
13011
+ studio.setAgentHint("Start Claude Code with --dangerously-load-development-channels server:tinypivot to send messages live.");
12830
13012
  if (claudeChannel) {
12831
13013
  studio.agent.connect({
12832
13014
  name: "Claude Code channel",
12833
13015
  push: (note, text) => {
12834
13016
  const content = `${text}
12835
13017
 
12836
- Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Studio.`;
12837
- server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id, kind: note.kind } } }).catch((error) => console.error("[tinypivot-mcp] Could not reach the Claude Code channel:", error));
13018
+ Answer with studio_reply so the user sees it in TinyPivot Studio.`;
13019
+ server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id } } }).catch((error) => console.error("[tinypivot-mcp] Could not reach the Claude Code channel:", error));
12838
13020
  return true;
12839
13021
  }
12840
13022
  });
12841
13023
  }
12842
- if (server.server.getClientCapabilities()?.sampling) {
12843
- studio.agent.connect({
12844
- name: "sampling",
12845
- complete: async (turns) => {
12846
- const result = await server.server.createMessage({
12847
- messages: turns.map((turn) => ({ role: turn.role, content: { type: "text", text: turn.content } })),
12848
- maxTokens: 2e3
12849
- });
12850
- return result.content.type === "text" ? result.content.text : "";
12851
- }
12852
- });
12853
- }
12854
13024
  };
12855
13025
  if (claudeChannel) {
12856
13026
  server.registerTool(
@@ -12858,10 +13028,10 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
12858
13028
  {
12859
13029
  title: "Reply in TinyPivot Studio",
12860
13030
  description: "Answer a message from TinyPivot Studio. The user reads it there.",
12861
- inputSchema: { text: z.string().min(1).max(8e3), re: z.string().max(80).optional() }
13031
+ inputSchema: { text: z.string().min(1).max(8e3) }
12862
13032
  },
12863
- async ({ text, re }) => {
12864
- studio.reply(text, re);
13033
+ async ({ text }) => {
13034
+ studio.reply(text);
12865
13035
  return { content: [{ type: "text", text: "Shown in TinyPivot Studio." }] };
12866
13036
  }
12867
13037
  );
@@ -12980,7 +13150,7 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
12980
13150
  store.setActive(ds.id, sessionKey);
12981
13151
  }
12982
13152
  const liveCompanionUrl = await resolveCompanionUrlForTool(Boolean(openBrowser));
12983
- const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat);
13153
+ const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat());
12984
13154
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
12985
13155
  recordTelemetry({
12986
13156
  event: "tool_call",
@@ -13116,7 +13286,7 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
13116
13286
  chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
13117
13287
  }, sessionKey);
13118
13288
  const liveCompanionUrl = await resolveCompanionUrlForTool();
13119
- const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat));
13289
+ const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat()));
13120
13290
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
13121
13291
  const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
13122
13292
  const payload = buildAppPayload(ds, store, {