@smallwebco/tinypivot-mcp 0.4.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";
@@ -8827,216 +9039,39 @@ var DatasetStore = class {
8827
9039
  if (modelInput || customRatePerMillion !== void 0) {
8828
9040
  this.activeModel = resolveModelPricing(modelInput ?? this.activeModel.name, customRatePerMillion);
8829
9041
  }
8830
- return this.activeModel;
8831
- }
8832
- recordTurnSavings(tokensSaved, modelInput) {
8833
- if (modelInput) {
8834
- this.activeModel = resolveModelPricing(modelInput);
8835
- }
8836
- this.sessionTurns++;
8837
- this.sessionTokensSaved += Math.max(0, Math.round(tokensSaved));
8838
- return this.getSessionSavings();
8839
- }
8840
- recordLocalAction(datasetId) {
8841
- const ds = this.get(datasetId);
8842
- const addedTokens = ds ? Math.round(ds.estimatedDatasetTokens * 0.1) + 2500 : 0;
8843
- this.sessionLocalActions++;
8844
- this.sessionTokensSaved += addedTokens;
8845
- return {
8846
- addedTokens,
8847
- session: this.getSessionSavings()
8848
- };
8849
- }
8850
- getSessionSavings() {
8851
- const model = this.activeModel ?? DEFAULT_MODEL_PRICING;
8852
- return {
8853
- model,
8854
- turns: this.sessionTurns,
8855
- localActions: this.sessionLocalActions,
8856
- tokensSaved: this.sessionTokensSaved,
8857
- usdSaved: tokensToUsd(this.sessionTokensSaved, model.ratePerMillion)
8858
- };
8859
- }
8860
- };
8861
-
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`;
9042
+ return this.activeModel;
9043
+ }
9044
+ recordTurnSavings(tokensSaved, modelInput) {
9045
+ if (modelInput) {
9046
+ this.activeModel = resolveModelPricing(modelInput);
8995
9047
  }
8996
- const dashCount = Math.max(1, innerWidth - 2 - leftW);
8997
- return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
9048
+ this.sessionTurns++;
9049
+ this.sessionTokensSaved += Math.max(0, Math.round(tokensSaved));
9050
+ return this.getSessionSavings();
8998
9051
  }
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`;
9052
+ recordLocalAction(datasetId) {
9053
+ const ds = this.get(datasetId);
9054
+ const addedTokens = ds ? Math.round(ds.estimatedDatasetTokens * 0.1) + 2500 : 0;
9055
+ this.sessionLocalActions++;
9056
+ this.sessionTokensSaved += addedTokens;
9057
+ return {
9058
+ addedTokens,
9059
+ session: this.getSessionSavings()
9060
+ };
9003
9061
  }
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`;
9062
+ getSessionSavings() {
9063
+ const model = this.activeModel ?? DEFAULT_MODEL_PRICING;
9064
+ return {
9065
+ model,
9066
+ turns: this.sessionTurns,
9067
+ localActions: this.sessionLocalActions,
9068
+ tokensSaved: this.sessionTokensSaved,
9069
+ usdSaved: tokensToUsd(this.sessionTokensSaved, model.ratePerMillion)
9070
+ };
9008
9071
  }
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
- }
9072
+ };
9073
+
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
 
@@ -10113,9 +10309,48 @@ function isAllowedRequest(request, port) {
10113
10309
  return false;
10114
10310
  if (request.method === "GET" || request.method === "HEAD")
10115
10311
  return true;
10116
- if (request.studioHeader !== "1")
10117
- return false;
10118
- return !request.origin || allowedHosts.some((host) => request.origin === `http://${host}`);
10312
+ if (request.origin)
10313
+ return allowedHosts.some((host) => request.origin === `http://${host}`);
10314
+ return request.studioHeader === "1";
10315
+ }
10316
+ function parseAttachment(value2) {
10317
+ const { label, text } = value2 ?? {};
10318
+ return typeof label === "string" && typeof text === "string" && text.trim() ? { label, text } : void 0;
10319
+ }
10320
+ function openAgentStream(studio, agentName, req, res) {
10321
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
10322
+ res.write(": connected\n\n");
10323
+ const disconnect = studio.agent.connect({
10324
+ name: agentName,
10325
+ push: (note, text) => {
10326
+ if (res.writableEnded)
10327
+ return false;
10328
+ res.write(`event: message
10329
+ data: ${JSON.stringify({ id: note.id, text })}
10330
+
10331
+ `);
10332
+ return true;
10333
+ }
10334
+ });
10335
+ const keepAlive = setInterval(() => res.write(": ping\n\n"), 25e3);
10336
+ keepAlive.unref();
10337
+ req.on("close", () => {
10338
+ clearInterval(keepAlive);
10339
+ disconnect();
10340
+ });
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;
10119
10354
  }
10120
10355
  function sendJson(res, status, body) {
10121
10356
  res.writeHead(status, { "Content-Type": "application/json" });
@@ -10192,13 +10427,13 @@ function buildFullCompanionPayload(store, datasetId, opts) {
10192
10427
  async function startCompanionServer(options) {
10193
10428
  const sseClients = /* @__PURE__ */ new Set();
10194
10429
  const send = (event, payload) => {
10195
- const frame = `event: ${event}
10430
+ const frame2 = `event: ${event}
10196
10431
  data: ${JSON.stringify(payload)}
10197
10432
 
10198
10433
  `;
10199
10434
  for (const res of sseClients) {
10200
10435
  try {
10201
- res.write(frame);
10436
+ res.write(frame2);
10202
10437
  } catch {
10203
10438
  sseClients.delete(res);
10204
10439
  }
@@ -10232,12 +10467,26 @@ data: ${JSON.stringify(payload)}
10232
10467
  const text = typeof body.text === "string" ? body.text.trim() : "";
10233
10468
  if (!text || text.length > MAX_NOTE_CHARS)
10234
10469
  return sendJson(res, 400, { error: `Write a note of up to ${MAX_NOTE_CHARS.toLocaleString("en-US")} characters.` });
10235
- const note = studio.addNote(text, typeof body.stepId === "string" ? body.stepId : void 0);
10470
+ const note = studio.addNote(text, {
10471
+ stepId: typeof body.stepId === "string" ? body.stepId : void 0,
10472
+ attachment: parseAttachment(body.attachment)
10473
+ });
10236
10474
  return sendJson(res, 200, { note });
10237
10475
  }
10238
10476
  if (pathname === "/api/studio/note/delete") {
10239
10477
  return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
10240
10478
  }
10479
+ if (pathname === "/api/studio/reply") {
10480
+ const text = typeof body.text === "string" ? body.text.trim() : "";
10481
+ if (!text)
10482
+ return sendJson(res, 400, { error: "Send the reply text." });
10483
+ studio.reply(text.slice(0, 2e4));
10484
+ return sendJson(res, 200, { ok: true });
10485
+ }
10486
+ if (pathname === "/api/studio/agent-status") {
10487
+ studio.setAgentBusy(body.busy === true);
10488
+ return sendJson(res, 200, { ok: true });
10489
+ }
10241
10490
  if (pathname === "/api/studio/show") {
10242
10491
  try {
10243
10492
  const dataset = await studio.showStep(String(body.stepId ?? ""));
@@ -10258,17 +10507,17 @@ data: ${JSON.stringify(payload)}
10258
10507
  }
10259
10508
  return sendJson(res, 404, { error: "Not found" });
10260
10509
  };
10510
+ let listenPort = 0;
10261
10511
  const server = http.createServer(async (req, res) => {
10262
10512
  const urlObj = new URL(req.url || "/", "http://127.0.0.1");
10263
10513
  const pathname = urlObj.pathname;
10264
10514
  res.setHeader("Cache-Control", "no-store");
10265
- const port = server.address().port;
10266
10515
  const allowed = isAllowedRequest({
10267
10516
  method: req.method,
10268
10517
  host: req.headers.host,
10269
10518
  origin: req.headers.origin,
10270
10519
  studioHeader: req.headers[STUDIO_HEADER]
10271
- }, port);
10520
+ }, listenPort);
10272
10521
  if (!allowed)
10273
10522
  return sendJson(res, 403, { error: "Forbidden" });
10274
10523
  if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
@@ -10293,6 +10542,18 @@ data: ${JSON.stringify(studio.snapshot())}
10293
10542
  req.on("close", () => sseClients.delete(res));
10294
10543
  return;
10295
10544
  }
10545
+ if (req.method === "GET" && pathname === "/api/studio/agent-stream") {
10546
+ if (!studio || req.headers[STUDIO_HEADER] !== "1")
10547
+ return sendJson(res, 403, { error: "Forbidden" });
10548
+ const agentName = (urlObj.searchParams.get("agent") || "agent").slice(0, 40);
10549
+ openAgentStream(studio, agentName, req, res);
10550
+ return;
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
+ }
10296
10557
  if (req.method === "GET" && pathname === "/api/studio") {
10297
10558
  return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
10298
10559
  }
@@ -10349,6 +10610,7 @@ data: ${JSON.stringify(studio.snapshot())}
10349
10610
  server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
10350
10611
  });
10351
10612
  const address = server.address();
10613
+ listenPort = address.port;
10352
10614
  const url = `http://127.0.0.1:${address.port}`;
10353
10615
  const sessionFile = getCompanionSessionFile();
10354
10616
  try {
@@ -10376,6 +10638,7 @@ data: ${JSON.stringify(studio.snapshot())}
10376
10638
  sseClients.clear();
10377
10639
  await new Promise((resolve) => {
10378
10640
  server.close(() => resolve());
10641
+ server.closeAllConnections();
10379
10642
  });
10380
10643
  try {
10381
10644
  const raw = await fs3.readFile(sessionFile, "utf8");
@@ -10465,7 +10728,7 @@ async function syncCompanionTheme(themeId: string): Promise<void> {
10465
10728
  if (!parsed.url) return;
10466
10729
  await fetch(\`\${parsed.url}/api/theme\`, {
10467
10730
  method: "POST",
10468
- headers: { "Content-Type": "application/json" },
10731
+ headers: { "Content-Type": "application/json", "x-tinypivot": "1" },
10469
10732
  body: JSON.stringify({ theme: themeId }),
10470
10733
  });
10471
10734
  } catch {
@@ -10504,6 +10767,12 @@ function colorizeSegments(text: string, pal: Palette): string {
10504
10767
  });
10505
10768
  }
10506
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
+
10507
10776
  function colorizeCardLine(line: string, pal: Palette): string {
10508
10777
  if (line.startsWith("\u256D\u2500")) {
10509
10778
  const withBadge = line.replace(/^(\u256D\u2500 )(.+?)( \u2500+ )(.+?)( \u2500\u256E)$/, (_m, a, b, c, d, e) =>
@@ -10528,7 +10797,7 @@ function colorizeCardLine(line: string, pal: Palette): string {
10528
10797
  const edge = fg(pal.border, "\u2502");
10529
10798
 
10530
10799
  if (inner.includes("\u2197 Live:")) {
10531
- return \`\${edge}\${fgBold(pal.accent, inner)}\${edge}\`;
10800
+ return \`\${edge}\${fgBold(pal.accent, hyperlink(inner))}\${edge}\`;
10532
10801
  }
10533
10802
  if (inner.includes("\u25B2 ") && (inner.includes("Peak:") || inner.includes("peak:"))) {
10534
10803
  return \`\${edge}\${fg(pal.muted, inner)}\${edge}\`;
@@ -10580,10 +10849,132 @@ function isTinyPivotTool(toolName: string): boolean {
10580
10849
  interface TinyPivotCardEntryData {
10581
10850
  cards: string[];
10582
10851
  themeId: string;
10852
+ /** The same cards in full colour from the Studio, where it could provide them. */
10853
+ coloured?: Array<string | null>;
10854
+ }
10855
+
10856
+ // TinyPivot Studio bridge: messages the user sends from the Studio arrive here, go into this
10857
+ // session as a turn, and the agent's final answer goes back to the Studio.
10858
+ // The Studio link TinyPivot puts in its replies ("Studio: \u2026" or a card's "Live: \u2026").
10859
+ const STUDIO_LINK = /(?:Studio|Live): (http:[/][/]127[.]0[.]0[.]1:[0-9]+)/;
10860
+ const STUDIO_HEADERS = { "Content-Type": "application/json", "x-tinypivot": "1" };
10861
+
10862
+ function lastAssistantText(messages: unknown): string {
10863
+ if (!Array.isArray(messages)) return "";
10864
+ for (let i = messages.length - 1; i >= 0; i--) {
10865
+ const message = messages[i] as { role?: string; content?: unknown };
10866
+ if (message?.role !== "assistant") continue;
10867
+ if (typeof message.content === "string") return message.content.trim();
10868
+ if (!Array.isArray(message.content)) return "";
10869
+ return message.content
10870
+ .map(part => (part && typeof part === "object" && (part as { type?: string }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
10871
+ .join("\\n")
10872
+ .trim();
10873
+ }
10874
+ return "";
10875
+ }
10876
+
10877
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10878
+ function createStudioBridge(pi: any) {
10879
+ let studioUrl: string | undefined;
10880
+ let stream: AbortController | undefined;
10881
+ /** Set while a turn that a Studio message started is running, so its answer goes back. */
10882
+ let awaiting = false;
10883
+
10884
+ function handleFrame(frame: string): void {
10885
+ if (!frame.startsWith("event: message")) return;
10886
+ const data = frame.split("\\n").find(line => line.startsWith("data: "));
10887
+ if (!data) return;
10888
+ const message = JSON.parse(data.slice(6)) as { text: string };
10889
+ awaiting = true;
10890
+ pi.sendMessage(
10891
+ { customType: "tinypivot-studio", content: message.text, display: true },
10892
+ { triggerTurn: true, deliverAs: "steer" },
10893
+ );
10894
+ }
10895
+
10896
+ async function listen(url: string, signal: AbortSignal): Promise<void> {
10897
+ let delay = 1000;
10898
+ while (!signal.aborted) {
10899
+ try {
10900
+ const res = await fetch(url + "/api/studio/agent-stream?agent=pi", { headers: STUDIO_HEADERS, signal });
10901
+ if (!res.ok || !res.body) throw new Error("Studio stream " + res.status);
10902
+ delay = 1000;
10903
+ const reader = res.body.getReader();
10904
+ const decoder = new TextDecoder();
10905
+ let buffer = "";
10906
+ for (;;) {
10907
+ const { value, done } = await reader.read();
10908
+ if (done) break;
10909
+ buffer += decoder.decode(value, { stream: true });
10910
+ let end = buffer.indexOf("\\n\\n");
10911
+ while (end >= 0) {
10912
+ handleFrame(buffer.slice(0, end));
10913
+ buffer = buffer.slice(end + 2);
10914
+ end = buffer.indexOf("\\n\\n");
10915
+ }
10916
+ }
10917
+ } catch {
10918
+ // The Studio restarted or closed; try again after a pause.
10919
+ }
10920
+ if (signal.aborted) return;
10921
+ await new Promise(resolve => setTimeout(resolve, delay));
10922
+ delay = Math.min(delay * 2, 30000);
10923
+ }
10924
+ }
10925
+
10926
+ return {
10927
+ /** Starts listening to the Studio named in a TinyPivot tool reply. */
10928
+ noticeToolText(text: string): void {
10929
+ const url = STUDIO_LINK.exec(text)?.[1];
10930
+ if (!url || url === studioUrl) return;
10931
+ stream?.abort();
10932
+ studioUrl = url;
10933
+ stream = new AbortController();
10934
+ void listen(url, stream.signal);
10935
+ void this.status(true);
10936
+ },
10937
+ /** Tells the Studio whether pi is working, so it can show progress. */
10938
+ async status(busy: boolean): Promise<void> {
10939
+ if (!studioUrl) return;
10940
+ await fetch(studioUrl + "/api/studio/agent-status", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ busy }) }).catch(() => {});
10941
+ },
10942
+ async onAgentEnd(messages: unknown): Promise<void> {
10943
+ if (!awaiting || !studioUrl) return;
10944
+ awaiting = false;
10945
+ const text = lastAssistantText(messages);
10946
+ if (!text) return;
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
+ }));
10963
+ },
10964
+ stop(): void {
10965
+ stream?.abort();
10966
+ stream = undefined;
10967
+ },
10968
+ };
10583
10969
  }
10584
10970
 
10585
10971
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
10586
10972
  export default function (pi: any) {
10973
+ const studio = createStudioBridge(pi);
10974
+ pi.on("agent_start", () => studio.status(true));
10975
+ pi.on("agent_end", (event: { messages?: unknown }) => studio.onAgentEnd(event?.messages));
10976
+ pi.on("agent_settled", () => studio.status(false));
10977
+ pi.on("session_shutdown", () => studio.stop());
10587
10978
  if (typeof pi.registerEntryRenderer === "function") {
10588
10979
  pi.registerEntryRenderer("tinypivot-card", (entry: { data?: TinyPivotCardEntryData }) => {
10589
10980
  const data = entry?.data;
@@ -10592,10 +10983,12 @@ export default function (pi: any) {
10592
10983
  render(_width: number): string[] {
10593
10984
  const themeId = data.themeId || readActiveThemeId();
10594
10985
  const out: string[] = [""];
10595
- for (const card of data.cards) {
10596
- 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}\`));
10597
10990
  out.push("");
10598
- }
10991
+ });
10599
10992
  return out;
10600
10993
  },
10601
10994
  invalidate() {},
@@ -10603,18 +10996,21 @@ export default function (pi: any) {
10603
10996
  });
10604
10997
  }
10605
10998
 
10606
- pi.on("tool_execution_end", (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
10607
- if (ctx?.hasUI === false || event?.isError) return;
10608
- if (!event?.toolName || !isTinyPivotTool(event.toolName)) return;
10609
-
10999
+ pi.on("tool_execution_end", async (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
11000
+ if (event?.isError) return;
10610
11001
  const text = extractResultText(event.result);
10611
11002
  if (!text) return;
11003
+ // TinyPivot calls made through codemode arrive under another tool's name, so look at the text.
11004
+ studio.noticeToolText(text);
11005
+ const fromTinyPivot = isTinyPivotTool(event?.toolName ?? "") || event?.toolName === "codemode";
11006
+ if (!fromTinyPivot || ctx?.hasUI === false) return;
10612
11007
  const cards = extractTinyPivotCards(text);
10613
11008
  if (cards.length === 0) return;
10614
11009
 
10615
11010
  const themeId = readActiveThemeId();
11011
+ const coloured = await studio.colouredCards(cards);
10616
11012
  if (typeof pi.appendEntry === "function") {
10617
- pi.appendEntry("tinypivot-card", { cards, themeId });
11013
+ pi.appendEntry("tinypivot-card", { cards, themeId, coloured });
10618
11014
  }
10619
11015
  });
10620
11016
 
@@ -10662,7 +11058,17 @@ var RULE_END = "<!-- tinypivot:end -->";
10662
11058
  var RULE_TEST_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/;
10663
11059
  var RULE_REPLACE_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/g;
10664
11060
  var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
10665
- 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
+ };
10666
11072
  var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
10667
11073
  ${RULE_HEADING}
10668
11074
  ${RULE_USE} In a terminal, show its \`text\` card verbatim with the Studio link.
@@ -10791,7 +11197,7 @@ function buildStdioServerEntry(opts, cliPath) {
10791
11197
  entry.env = env;
10792
11198
  return entry;
10793
11199
  }
10794
- async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath) {
11200
+ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath, extras = {}) {
10795
11201
  const explicit = opts.targets?.has(id) ?? false;
10796
11202
  const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(detectDir);
10797
11203
  if (!shouldInclude) {
@@ -10800,8 +11206,14 @@ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cli
10800
11206
  try {
10801
11207
  const json = await readJsonSafe(configPath);
10802
11208
  const mcpServers = json.mcpServers && typeof json.mcpServers === "object" && !Array.isArray(json.mcpServers) ? { ...json.mcpServers } : {};
10803
- const nextEntry = buildStdioServerEntry(opts, cliPath);
11209
+ const nextEntry = { ...buildStdioServerEntry(opts, cliPath) };
10804
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
+ }
10805
11217
  if (existing?.env && typeof existing.env === "object" && !Array.isArray(existing.env)) {
10806
11218
  nextEntry.env = {
10807
11219
  ...existing.env,
@@ -10987,13 +11399,29 @@ async function upsertRuleFile(targetId, ruleId, label, detectDir, ruleFilePath,
10987
11399
  };
10988
11400
  }
10989
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
+ }
10990
11418
  async function upsertPiExtension(opts) {
10991
11419
  const targeting = opts.targets ? opts.targets.has("pi") : true;
10992
11420
  if (!targeting)
10993
11421
  return null;
10994
11422
  const home = os3.homedir();
10995
11423
  const piDir = path4.join(home, ".pi");
10996
- const extPath = path4.join(piDir, "agent", "extensions", "tinypivot.ts");
11424
+ const extPath = piExtensionPath(home);
10997
11425
  const explicit = opts.targets?.has("pi") ?? false;
10998
11426
  if (!opts.all && !explicit && !await exists(piDir))
10999
11427
  return null;
@@ -11099,7 +11527,8 @@ TinyPivot MCP Installer (${opts.local ? `local: ${cliPath}` : `npx ${MCP_NPX_SPE
11099
11527
  path4.join(home, ".pi", "agent", "mcp.json"),
11100
11528
  path4.join(home, ".pi"),
11101
11529
  opts,
11102
- cliPath
11530
+ cliPath,
11531
+ PI_ENTRY_EXTRAS
11103
11532
  ),
11104
11533
  await upsertOpenCodeJson(opts, cliPath),
11105
11534
  await upsertCodexToml(opts, cliPath)
@@ -11465,6 +11894,35 @@ async function executeReadOnlyPostgresQuery(config, sql) {
11465
11894
  import fs7 from "fs";
11466
11895
  import path7 from "path";
11467
11896
 
11897
+ // src/agent-bridge.ts
11898
+ var AgentBridge = class {
11899
+ constructor(onChange) {
11900
+ this.onChange = onChange;
11901
+ }
11902
+ connectors = /* @__PURE__ */ new Set();
11903
+ /** Adds a way to reach the agent; the returned function removes it. */
11904
+ connect(connector) {
11905
+ this.connectors.add(connector);
11906
+ this.onChange();
11907
+ return () => {
11908
+ if (this.connectors.delete(connector))
11909
+ this.onChange();
11910
+ };
11911
+ }
11912
+ /** Names of the ways that reach the agent right now. */
11913
+ live() {
11914
+ return [...this.connectors].map((connector) => connector.name);
11915
+ }
11916
+ /** Delivers into the conversation through the first connector that takes it. */
11917
+ push(note, text) {
11918
+ for (const connector of this.connectors) {
11919
+ if (connector.push(note, text))
11920
+ return connector.name;
11921
+ }
11922
+ return void 0;
11923
+ }
11924
+ };
11925
+
11468
11926
  // src/duckdb.ts
11469
11927
  import { spawn } from "child_process";
11470
11928
  import fs5 from "fs";
@@ -11725,6 +12183,20 @@ function formatHistoryList(entries) {
11725
12183
  // src/studio.ts
11726
12184
  var STEPS_IN_MEMORY = 300;
11727
12185
  var HISTORY_IN_SNAPSHOT = 50;
12186
+ var ATTACHMENT_MAX_CHARS = 6e3;
12187
+ var AGENT_NAMES = {
12188
+ "claude-code": "Claude Code",
12189
+ "claude-ai": "Claude Desktop",
12190
+ "pi": "pi",
12191
+ "opencode": "OpenCode",
12192
+ "cursor-vscode": "Cursor",
12193
+ "codex-mcp-client": "Codex",
12194
+ "antigravity": "Antigravity",
12195
+ "Visual Studio Code": "VS Code"
12196
+ };
12197
+ function agentLabel(clientName) {
12198
+ return clientName && (AGENT_NAMES[clientName] ?? clientName) || "your agent";
12199
+ }
11728
12200
  var TRACE_FILE_MAX_BYTES = 5 * 1024 * 1024;
11729
12201
  function describeView(dataset) {
11730
12202
  const pivot = dataset.pivotConfig;
@@ -11768,6 +12240,10 @@ function historyTableExpression(entry, rowsPath) {
11768
12240
  }
11769
12241
  return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
11770
12242
  }
12243
+ function withoutCards(text) {
12244
+ const stripped = text.replace(/```text\n[\s\S]*?```\n?/g, (block) => /[╭╰│┤├]/.test(block) ? "" : block);
12245
+ return stripped.replace(/\n{3,}/g, "\n\n").trim() || text.trim();
12246
+ }
11771
12247
  var sequence = 0;
11772
12248
  function nextId(prefix) {
11773
12249
  sequence += 1;
@@ -11787,6 +12263,11 @@ var Studio = class {
11787
12263
  pullsByDataset = /* @__PURE__ */ new Map();
11788
12264
  listeners = /* @__PURE__ */ new Set();
11789
12265
  changeQueued = false;
12266
+ /** Ways to reach the user's agent live; without one, notes wait for its next TinyPivot reply. */
12267
+ agent = new AgentBridge(() => this.changed());
12268
+ agentName;
12269
+ agentBusy = false;
12270
+ agentHint;
11790
12271
  /** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
11791
12272
  subscribe(listener) {
11792
12273
  this.listeners.add(listener);
@@ -11811,9 +12292,27 @@ var Studio = class {
11811
12292
  notes: this.pendingNotes(),
11812
12293
  history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
11813
12294
  historyEnabled: this.history.enabled,
11814
- loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id)
12295
+ loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
12296
+ agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy, ...this.agentHint ? { hint: this.agentHint } : {} }
11815
12297
  };
11816
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
+ }
12304
+ /** Whether the agent is in the middle of a turn, as its extension reports it. */
12305
+ setAgentBusy(busy) {
12306
+ if (busy === this.agentBusy)
12307
+ return;
12308
+ this.agentBusy = busy;
12309
+ this.changed();
12310
+ }
12311
+ /** The MCP client's name, e.g. `claude-code`, shown in the Studio. */
12312
+ setAgentName(name) {
12313
+ this.agentName = name;
12314
+ this.changed();
12315
+ }
11817
12316
  get traceFile() {
11818
12317
  return path7.join(this.history.dir, "trace.jsonl");
11819
12318
  }
@@ -11963,13 +12462,45 @@ var Studio = class {
11963
12462
  });
11964
12463
  return dataset;
11965
12464
  }
11966
- /** Queues a note for the agent; it is delivered with the next TinyPivot reply. */
11967
- addNote(text, stepId) {
11968
- const note = { id: nextId("note"), at: (/* @__PURE__ */ new Date()).toISOString(), text: text.trim(), ...stepId ? { stepId } : {} };
11969
- this.notes.push(note);
11970
- this.record({ actor: "user", tool: "note", why: note.text });
12465
+ /**
12466
+ * Sends the user's message to the agent: straight into its conversation when a live connector
12467
+ * takes it, otherwise queued for its next TinyPivot reply.
12468
+ */
12469
+ addNote(text, options = {}) {
12470
+ const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
12471
+ const note = {
12472
+ id: nextId("note"),
12473
+ at: (/* @__PURE__ */ new Date()).toISOString(),
12474
+ text: text.trim(),
12475
+ delivery: "queued",
12476
+ ...options.stepId ? { stepId: options.stepId } : {},
12477
+ ...attachment ? { attachment } : {}
12478
+ };
12479
+ if (this.agent.push(note, this.describeNote(note, { withSource: true })))
12480
+ note.delivery = "live";
12481
+ else
12482
+ this.notes.push(note);
12483
+ this.record({ actor: "user", tool: "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
11971
12484
  return note;
11972
12485
  }
12486
+ /**
12487
+ * How a message reads to the agent: the text, the step it is about, and any attached data.
12488
+ * `withSource` says where it came from, for messages that arrive on their own in the conversation.
12489
+ */
12490
+ describeNote(note, { withSource = false } = {}) {
12491
+ const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
12492
+ const source = withSource ? "Message from the user in TinyPivot Studio: " : "";
12493
+ const lines = [`${source}${note.text}`];
12494
+ if (step)
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, " ")}` : ""}`);
12496
+ if (note.attachment)
12497
+ lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
12498
+ return lines.join("\n");
12499
+ }
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) });
12503
+ }
11973
12504
  /** Drops a queued note the user no longer wants sent. */
11974
12505
  removeNote(id) {
11975
12506
  const before = this.notes.length;
@@ -11985,11 +12516,7 @@ var Studio = class {
11985
12516
  takeNotes() {
11986
12517
  if (this.notes.length === 0)
11987
12518
  return "";
11988
- const lines = this.notes.map((note) => {
11989
- const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
11990
- const about = step ? ` (about "${step.why ?? step.view ?? step.tool}"${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""})` : "";
11991
- return `- ${note.text}${about}`;
11992
- });
12519
+ const lines = this.notes.map((note) => `- ${this.describeNote(note).replace(/\n/g, "\n ")}`);
11993
12520
  this.notes = [];
11994
12521
  this.changed();
11995
12522
  return `
@@ -12007,6 +12534,43 @@ import { fileURLToPath as fileURLToPath2 } from "url";
12007
12534
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12008
12535
  import { z } from "zod";
12009
12536
 
12537
+ // src/claude-channel.ts
12538
+ import { execFileSync } from "child_process";
12539
+ import process2 from "process";
12540
+ var CHANNEL_NOTIFICATION = "notifications/claude/channel";
12541
+ var CHANNEL_FLAGS = ["--channels", "--dangerously-load-development-channels"];
12542
+ var ANCESTORS_TO_CHECK = 5;
12543
+ function commandEnablesChannel(command, serverName) {
12544
+ if (!/\bclaude\b/.test(command) || !CHANNEL_FLAGS.some((flag) => command.includes(flag)))
12545
+ return false;
12546
+ return new RegExp(`(?:server:)?${serverName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(command);
12547
+ }
12548
+ function processInfo(pid) {
12549
+ try {
12550
+ const out = execFileSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 2e3 }).trim();
12551
+ const match = /^(\d+)\s+(.*)$/s.exec(out);
12552
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
12553
+ } catch {
12554
+ return void 0;
12555
+ }
12556
+ }
12557
+ function claudeChannelEnabled(serverName = "tinypivot", env = process2.env) {
12558
+ if (env.TINYPIVOT_CLAUDE_CHANNEL === "1")
12559
+ return true;
12560
+ if (env.TINYPIVOT_CLAUDE_CHANNEL === "0" || process2.platform === "win32")
12561
+ return false;
12562
+ let pid = process2.ppid;
12563
+ for (let i = 0; i < ANCESTORS_TO_CHECK && pid > 1; i++) {
12564
+ const info = processInfo(pid);
12565
+ if (!info)
12566
+ return false;
12567
+ if (commandEnablesChannel(info.command, serverName))
12568
+ return true;
12569
+ pid = info.ppid;
12570
+ }
12571
+ return false;
12572
+ }
12573
+
12010
12574
  // src/profile.ts
12011
12575
  var TOP_VALUES = 3;
12012
12576
  function compactNumber(value2) {
@@ -12075,7 +12639,7 @@ import fsSync2 from "fs";
12075
12639
  import os6 from "os";
12076
12640
  import path8 from "path";
12077
12641
  var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
12078
- var PACKAGE_VERSION = "0.4.0";
12642
+ var PACKAGE_VERSION = "0.6.0";
12079
12643
  function isTelemetryEnabled() {
12080
12644
  if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
12081
12645
  return false;
@@ -12154,14 +12718,15 @@ function recordTelemetry(ev) {
12154
12718
  var APP_RESOURCE_URI = "ui://tinypivot/app.html";
12155
12719
  var APP_MIME_TYPE = "text/html;profile=mcp-app";
12156
12720
  var LOAD_DATA_ROW_GUIDE = 50;
12157
- function buildInstructions({ reprintCards = true } = {}) {
12158
- 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.";
12721
+ function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
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.";
12159
12723
  return [
12160
- "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.",
12161
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.`,
12162
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.",
12163
12727
  "Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
12164
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.",
12729
+ ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply.'] : [],
12165
12730
  cards
12166
12731
  ].join(" ");
12167
12732
  }
@@ -12248,6 +12813,12 @@ function normalizePivot(pivotConfig) {
12248
12813
  valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
12249
12814
  };
12250
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
+ };
12251
12822
  var whyParam = z.string().max(240).optional();
12252
12823
  var DUCKDB_WAIT_MS = 45e3;
12253
12824
  function toCoreChartConfig(input) {
@@ -12373,7 +12944,7 @@ function createTinyPivotMcpServer(options = {}) {
12373
12944
  options.onStateChanged?.();
12374
12945
  };
12375
12946
  const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
12376
- const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
12947
+ const claudeChannel = options.claudeChannel ?? claudeChannelEnabled();
12377
12948
  const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
12378
12949
  connectionString: process.env.DATABASE_URL,
12379
12950
  allowedTables: process.env.TINYPIVOT_ALLOWED_TABLES ? process.env.TINYPIVOT_ALLOWED_TABLES.split(",").map((s) => s.trim()).filter(Boolean) : void 0
@@ -12381,17 +12952,19 @@ function createTinyPivotMcpServer(options = {}) {
12381
12952
  const server = new McpServer(
12382
12953
  {
12383
12954
  name: "tinypivot",
12384
- version: "0.4.0"
12955
+ version: "0.6.0"
12385
12956
  },
12386
12957
  {
12387
12958
  capabilities: {
12388
12959
  resources: {},
12389
- tools: {}
12960
+ tools: {},
12961
+ ...claudeChannel ? { experimental: { "claude/channel": {} } } : {}
12390
12962
  },
12391
- instructions: buildInstructions({ reprintCards })
12963
+ instructions: buildInstructions({ reprintCards, claudeChannel })
12392
12964
  }
12393
12965
  );
12394
12966
  const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
12967
+ const cardFormat = () => ({ showBranding: !isPro2, reprintNote: reprintCards, shownInWidget: clientRendersWidget() });
12395
12968
  const resolveCompanionUrlForTool = async (forceCompanion = false) => {
12396
12969
  if (activeCompanionUrl)
12397
12970
  return activeCompanionUrl;
@@ -12408,7 +12981,7 @@ function createTinyPivotMcpServer(options = {}) {
12408
12981
  };
12409
12982
  const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
12410
12983
  const liveCompanionUrl = await resolveCompanionUrlForTool();
12411
- const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
12984
+ const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`);
12412
12985
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
12413
12986
  recordTelemetry({
12414
12987
  event: "tool_call",
@@ -12428,6 +13001,41 @@ function createTinyPivotMcpServer(options = {}) {
12428
13001
  console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
12429
13002
  }
12430
13003
  const withNotes = (text) => `${text}${studio.takeNotes()}`;
13004
+ const connectAgent = () => {
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.");
13012
+ if (claudeChannel) {
13013
+ studio.agent.connect({
13014
+ name: "Claude Code channel",
13015
+ push: (note, text) => {
13016
+ const content = `${text}
13017
+
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));
13020
+ return true;
13021
+ }
13022
+ });
13023
+ }
13024
+ };
13025
+ if (claudeChannel) {
13026
+ server.registerTool(
13027
+ "studio_reply",
13028
+ {
13029
+ title: "Reply in TinyPivot Studio",
13030
+ description: "Answer a message from TinyPivot Studio. The user reads it there.",
13031
+ inputSchema: { text: z.string().min(1).max(8e3) }
13032
+ },
13033
+ async ({ text }) => {
13034
+ studio.reply(text);
13035
+ return { content: [{ type: "text", text: "Shown in TinyPivot Studio." }] };
13036
+ }
13037
+ );
13038
+ }
12431
13039
  const widgetOnlyTools = [];
12432
13040
  const widgetOnly = (tool) => {
12433
13041
  widgetOnlyTools.push(tool);
@@ -12453,6 +13061,11 @@ function createTinyPivotMcpServer(options = {}) {
12453
13061
  if (!clientRendersWidget())
12454
13062
  widgetOnlyTools.forEach((tool) => tool.disable());
12455
13063
  detectedClientName = server.server.getClientVersion()?.name;
13064
+ try {
13065
+ connectAgent();
13066
+ } catch (error) {
13067
+ console.error("[tinypivot-mcp] Could not connect the Studio to the agent:", error);
13068
+ }
12456
13069
  recordTelemetry({
12457
13070
  event: "server_start",
12458
13071
  client: detectedClientName,
@@ -12537,7 +13150,7 @@ function createTinyPivotMcpServer(options = {}) {
12537
13150
  store.setActive(ds.id, sessionKey);
12538
13151
  }
12539
13152
  const liveCompanionUrl = await resolveCompanionUrlForTool(Boolean(openBrowser));
12540
- const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat);
13153
+ const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat());
12541
13154
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
12542
13155
  recordTelemetry({
12543
13156
  event: "tool_call",
@@ -12673,7 +13286,7 @@ function createTinyPivotMcpServer(options = {}) {
12673
13286
  chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
12674
13287
  }, sessionKey);
12675
13288
  const liveCompanionUrl = await resolveCompanionUrlForTool();
12676
- const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat));
13289
+ const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat()));
12677
13290
  studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
12678
13291
  const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
12679
13292
  const payload = buildAppPayload(ds, store, {