@smallwebco/tinypivot-mcp 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +22 -3
- package/.mcp.json +1 -1
- package/LICENSE.md +37 -57
- package/README.md +22 -5
- package/dist/app/index.html +89 -89
- package/dist/{chunk-E6DYPT62.js → chunk-4AG4LXY4.js} +889 -572
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +33 -55
- package/dist/index.js +1 -1
- package/package.json +6 -5
- package/server.json +2 -2
|
@@ -7620,6 +7620,39 @@ function processChartData(data, config) {
|
|
|
7620
7620
|
}
|
|
7621
7621
|
return { categories, series };
|
|
7622
7622
|
}
|
|
7623
|
+
function processChartDataForScatter(data, config) {
|
|
7624
|
+
if (!config.xAxis || !config.yAxis || data.length === 0) {
|
|
7625
|
+
return { series: [] };
|
|
7626
|
+
}
|
|
7627
|
+
const xField = config.xAxis.field;
|
|
7628
|
+
const yField = config.yAxis.field;
|
|
7629
|
+
const sizeField = config.sizeField?.field;
|
|
7630
|
+
const seriesField = config.seriesField?.field;
|
|
7631
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
7632
|
+
for (const row of data) {
|
|
7633
|
+
const x = Number(row[xField]);
|
|
7634
|
+
const y = Number(row[yField]);
|
|
7635
|
+
if (Number.isNaN(x) || Number.isNaN(y))
|
|
7636
|
+
continue;
|
|
7637
|
+
const point = { x, y };
|
|
7638
|
+
if (sizeField) {
|
|
7639
|
+
const z2 = Number(row[sizeField]);
|
|
7640
|
+
if (!Number.isNaN(z2)) {
|
|
7641
|
+
point.z = z2;
|
|
7642
|
+
}
|
|
7643
|
+
}
|
|
7644
|
+
const seriesName = seriesField ? String(row[seriesField] ?? "(blank)") : "_default";
|
|
7645
|
+
if (!grouped.has(seriesName)) {
|
|
7646
|
+
grouped.set(seriesName, []);
|
|
7647
|
+
}
|
|
7648
|
+
grouped.get(seriesName).push(point);
|
|
7649
|
+
}
|
|
7650
|
+
const series = Array.from(grouped.entries()).map(([name, points]) => ({
|
|
7651
|
+
name: name === "_default" ? config.yAxis?.label || "Data" : name,
|
|
7652
|
+
data: points
|
|
7653
|
+
}));
|
|
7654
|
+
return { series };
|
|
7655
|
+
}
|
|
7623
7656
|
|
|
7624
7657
|
// ../core/dist/theme/index.js
|
|
7625
7658
|
var UNIFIED_THEME_IDS = ["paper", "greenbar", "onebit", "crt-amber", "crt-green"];
|
|
@@ -8255,6 +8288,185 @@ function tokensToUsd(tokens, ratePerMillion) {
|
|
|
8255
8288
|
// src/studio-protocol.ts
|
|
8256
8289
|
var STUDIO_HEADER = "x-tinypivot";
|
|
8257
8290
|
|
|
8291
|
+
// src/card.ts
|
|
8292
|
+
var SUB_BLOCKS = ["", "\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589", "\u2588"];
|
|
8293
|
+
var SERIES_GLYPHS = ["\u2588", "\u2593", "\u2592", "\u2591"];
|
|
8294
|
+
var SPARK_CHARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
|
|
8295
|
+
var CARD_DIVIDER = "__TINYPIVOT_CARD_DIVIDER__";
|
|
8296
|
+
var BRAILLE_BITS = [
|
|
8297
|
+
[1, 8],
|
|
8298
|
+
[2, 16],
|
|
8299
|
+
[4, 32],
|
|
8300
|
+
[64, 128]
|
|
8301
|
+
];
|
|
8302
|
+
var ANSI_ESCAPE_RE = /\x1B\[[0-9;]*m/g;
|
|
8303
|
+
var ANSI_RESET = "\x1B[0m";
|
|
8304
|
+
var ANSI_BOLD = "\x1B[1m";
|
|
8305
|
+
function ansiFg(rgb, text) {
|
|
8306
|
+
return `\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
|
|
8307
|
+
}
|
|
8308
|
+
function ansiFgBold(rgb, text) {
|
|
8309
|
+
return `${ANSI_BOLD}\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
|
|
8310
|
+
}
|
|
8311
|
+
function codePointDisplayWidth(cp) {
|
|
8312
|
+
if (cp < 32 || cp >= 127 && cp < 160)
|
|
8313
|
+
return 0;
|
|
8314
|
+
if (cp >= 768 && cp <= 879 || cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8203 && cp <= 8207 || cp >= 8232 && cp <= 8239 || cp >= 8400 && cp <= 8447 || cp >= 65024 && cp <= 65039 || cp >= 65056 && cp <= 65071 || cp >= 917760 && cp <= 917999) {
|
|
8315
|
+
return 0;
|
|
8316
|
+
}
|
|
8317
|
+
if (cp >= 4352 && cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 12350 || cp >= 12352 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141) {
|
|
8318
|
+
return 2;
|
|
8319
|
+
}
|
|
8320
|
+
return 1;
|
|
8321
|
+
}
|
|
8322
|
+
function visualWidth(text) {
|
|
8323
|
+
const clean = text.replace(ANSI_ESCAPE_RE, "");
|
|
8324
|
+
let width = 0;
|
|
8325
|
+
for (const ch of clean) {
|
|
8326
|
+
const cp = ch.codePointAt(0);
|
|
8327
|
+
if (cp !== void 0)
|
|
8328
|
+
width += codePointDisplayWidth(cp);
|
|
8329
|
+
}
|
|
8330
|
+
return width;
|
|
8331
|
+
}
|
|
8332
|
+
function truncateVisual(text, maxWidth) {
|
|
8333
|
+
if (maxWidth <= 0)
|
|
8334
|
+
return "";
|
|
8335
|
+
if (visualWidth(text) <= maxWidth)
|
|
8336
|
+
return text;
|
|
8337
|
+
if (maxWidth === 1)
|
|
8338
|
+
return "\u2026";
|
|
8339
|
+
const target = maxWidth - 1;
|
|
8340
|
+
let out = "";
|
|
8341
|
+
let used = 0;
|
|
8342
|
+
for (const ch of text) {
|
|
8343
|
+
const cp = ch.codePointAt(0);
|
|
8344
|
+
const w = cp !== void 0 ? codePointDisplayWidth(cp) : 0;
|
|
8345
|
+
if (used + w > target)
|
|
8346
|
+
break;
|
|
8347
|
+
out += ch;
|
|
8348
|
+
used += w;
|
|
8349
|
+
}
|
|
8350
|
+
return `${out}\u2026`;
|
|
8351
|
+
}
|
|
8352
|
+
function padEndVisual(text, targetWidth) {
|
|
8353
|
+
const pad = Math.max(0, targetWidth - visualWidth(text));
|
|
8354
|
+
return pad > 0 ? `${text}${" ".repeat(pad)}` : text;
|
|
8355
|
+
}
|
|
8356
|
+
function padStartVisual(text, targetWidth) {
|
|
8357
|
+
const pad = Math.max(0, targetWidth - visualWidth(text));
|
|
8358
|
+
return pad > 0 ? `${" ".repeat(pad)}${text}` : text;
|
|
8359
|
+
}
|
|
8360
|
+
function formatCompactNumber(val) {
|
|
8361
|
+
if (!Number.isFinite(val))
|
|
8362
|
+
return "0";
|
|
8363
|
+
const abs = Math.abs(val);
|
|
8364
|
+
const sign = val < 0 ? "-" : "";
|
|
8365
|
+
if (abs >= 1e9)
|
|
8366
|
+
return `${sign}${(abs / 1e9).toFixed(2)}B`;
|
|
8367
|
+
if (abs >= 1e6)
|
|
8368
|
+
return `${sign}${(abs / 1e6).toFixed(2)}M`;
|
|
8369
|
+
if (abs >= 1e4)
|
|
8370
|
+
return `${sign}${(abs / 1e3).toFixed(1)}k`;
|
|
8371
|
+
if (abs >= 1e3)
|
|
8372
|
+
return `${sign}${Math.round(abs).toLocaleString("en-US")}`;
|
|
8373
|
+
return Number.isInteger(val) ? String(val) : val.toFixed(1);
|
|
8374
|
+
}
|
|
8375
|
+
function renderPreciseBar(ratio, width) {
|
|
8376
|
+
const clamped = Math.max(0, Math.min(1, ratio));
|
|
8377
|
+
if (clamped <= 0)
|
|
8378
|
+
return "";
|
|
8379
|
+
const totalEighths = Math.round(clamped * width * 8);
|
|
8380
|
+
if (totalEighths === 0)
|
|
8381
|
+
return "\u258F";
|
|
8382
|
+
const full = Math.floor(totalEighths / 8);
|
|
8383
|
+
const rem = totalEighths % 8;
|
|
8384
|
+
return `${"\u2588".repeat(full)}${SUB_BLOCKS[rem]}`;
|
|
8385
|
+
}
|
|
8386
|
+
function renderSparkline(values) {
|
|
8387
|
+
if (values.length === 0)
|
|
8388
|
+
return "";
|
|
8389
|
+
const min = Math.min(...values);
|
|
8390
|
+
const max = Math.max(...values);
|
|
8391
|
+
const span = max - min;
|
|
8392
|
+
return values.map((v) => {
|
|
8393
|
+
if (!Number.isFinite(v))
|
|
8394
|
+
return " ";
|
|
8395
|
+
if (span <= 0)
|
|
8396
|
+
return SPARK_CHARS[3];
|
|
8397
|
+
const idx = Math.min(SPARK_CHARS.length - 1, Math.max(0, Math.round((v - min) / span * (SPARK_CHARS.length - 1))));
|
|
8398
|
+
return SPARK_CHARS[idx];
|
|
8399
|
+
}).join("");
|
|
8400
|
+
}
|
|
8401
|
+
function buildTopBorder(title, rightBadge, innerWidth) {
|
|
8402
|
+
if (rightBadge) {
|
|
8403
|
+
const safeRight = truncateVisual(rightBadge, Math.max(8, Math.floor(innerWidth * 0.44)));
|
|
8404
|
+
const rightW = visualWidth(safeRight);
|
|
8405
|
+
const maxTitleW = Math.max(1, innerWidth - 5 - rightW);
|
|
8406
|
+
const safeTitle2 = truncateVisual(title, maxTitleW);
|
|
8407
|
+
const dashCount2 = Math.max(1, innerWidth - 4 - visualWidth(safeTitle2) - rightW);
|
|
8408
|
+
return `\u256D\u2500 ${safeTitle2} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256E`;
|
|
8409
|
+
}
|
|
8410
|
+
const safeTitle = truncateVisual(title, Math.max(1, innerWidth - 3));
|
|
8411
|
+
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeTitle));
|
|
8412
|
+
return `\u256D\u2500 ${safeTitle} ${"\u2500".repeat(dashCount)}\u2500\u256E`;
|
|
8413
|
+
}
|
|
8414
|
+
function buildBottomBorder(footerLeft, footerRight, innerWidth) {
|
|
8415
|
+
if (footerLeft && footerRight) {
|
|
8416
|
+
const safeLeft = truncateVisual(footerLeft, Math.max(8, Math.floor(innerWidth * 0.45)));
|
|
8417
|
+
const leftW = visualWidth(safeLeft);
|
|
8418
|
+
const maxRightW = innerWidth - 5 - leftW;
|
|
8419
|
+
if (maxRightW >= 4) {
|
|
8420
|
+
const safeRight = truncateVisual(footerRight, maxRightW);
|
|
8421
|
+
const rightW = visualWidth(safeRight);
|
|
8422
|
+
const dashCount2 = Math.max(1, innerWidth - 4 - leftW - rightW);
|
|
8423
|
+
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256F`;
|
|
8424
|
+
}
|
|
8425
|
+
const dashCount = Math.max(1, innerWidth - 2 - leftW);
|
|
8426
|
+
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
|
|
8427
|
+
}
|
|
8428
|
+
if (footerLeft) {
|
|
8429
|
+
const safeLeft = truncateVisual(footerLeft, Math.max(1, innerWidth - 3));
|
|
8430
|
+
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeLeft));
|
|
8431
|
+
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
|
|
8432
|
+
}
|
|
8433
|
+
if (footerRight) {
|
|
8434
|
+
const safeRight = truncateVisual(footerRight, Math.max(1, innerWidth - 3));
|
|
8435
|
+
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeRight));
|
|
8436
|
+
return `\u2570\u2500${"\u2500".repeat(dashCount)} ${safeRight} \u2500\u256F`;
|
|
8437
|
+
}
|
|
8438
|
+
return `\u2570${"\u2500".repeat(innerWidth + 2)}\u256F`;
|
|
8439
|
+
}
|
|
8440
|
+
function resolveTerminalPalette(theme) {
|
|
8441
|
+
if (!theme)
|
|
8442
|
+
return void 0;
|
|
8443
|
+
return TERMINAL_PALETTES[theme] ?? TERMINAL_PALETTES.code;
|
|
8444
|
+
}
|
|
8445
|
+
function wrapInCard(title, rightBadge, bodyLines, footerLeft, footerRight, minWidth = 66, options = {}) {
|
|
8446
|
+
const pal = options.palette;
|
|
8447
|
+
const contentLines = bodyLines.filter((l) => l !== CARD_DIVIDER);
|
|
8448
|
+
const longestBody = Math.max(...contentLines.map((l) => visualWidth(l)), 0);
|
|
8449
|
+
const desiredHeader = visualWidth(title) + visualWidth(rightBadge) + (rightBadge ? 6 : 4);
|
|
8450
|
+
const desiredFooter = visualWidth(footerLeft) + visualWidth(footerRight) + (footerLeft && footerRight ? 6 : 4);
|
|
8451
|
+
const innerWidth = Math.min(82, Math.max(minWidth, longestBody, Math.min(desiredHeader, 82), Math.min(desiredFooter, 82)));
|
|
8452
|
+
const topPlain = buildTopBorder(title, rightBadge, innerWidth);
|
|
8453
|
+
const topBorder = pal ? topPlain.replace(/^(╭─ )(.+?)( ─+ )(.+?)( ─╮)$/, (_, a, b, c, d, e) => `${ansiFg(pal.border, a)}${ansiFgBold(pal.text, b)}${ansiFg(pal.border, c)}${ansiFg(pal.accent, d)}${ansiFg(pal.border, e)}`) : topPlain;
|
|
8454
|
+
const dividerPlain = `\u251C${"\u2500".repeat(innerWidth + 2)}\u2524`;
|
|
8455
|
+
const dividerLine = pal ? ansiFg(pal.border, dividerPlain) : dividerPlain;
|
|
8456
|
+
const edge = pal ? ansiFg(pal.border, "\u2502") : "\u2502";
|
|
8457
|
+
const paddedBody = bodyLines.map((line) => {
|
|
8458
|
+
if (line === CARD_DIVIDER)
|
|
8459
|
+
return dividerLine;
|
|
8460
|
+
const clipped = visualWidth(line) > innerWidth ? truncateVisual(line, innerWidth) : line;
|
|
8461
|
+
return `${edge} ${padEndVisual(clipped, innerWidth)} ${edge}`;
|
|
8462
|
+
});
|
|
8463
|
+
const botPlain = buildBottomBorder(footerLeft, footerRight, innerWidth);
|
|
8464
|
+
const bottomBorder = pal ? ansiFg(pal.border, botPlain) : botPlain;
|
|
8465
|
+
if (options.raw)
|
|
8466
|
+
return [topBorder, ...paddedBody, bottomBorder].join("\n");
|
|
8467
|
+
return ["```text", topBorder, ...paddedBody, bottomBorder, "```"].join("\n");
|
|
8468
|
+
}
|
|
8469
|
+
|
|
8258
8470
|
// src/store.ts
|
|
8259
8471
|
import fsSync from "fs";
|
|
8260
8472
|
import fs from "fs/promises";
|
|
@@ -8859,184 +9071,7 @@ var DatasetStore = class {
|
|
|
8859
9071
|
}
|
|
8860
9072
|
};
|
|
8861
9073
|
|
|
8862
|
-
// src/
|
|
8863
|
-
var SUB_BLOCKS = ["", "\u258F", "\u258E", "\u258D", "\u258C", "\u258B", "\u258A", "\u2589", "\u2588"];
|
|
8864
|
-
var SERIES_GLYPHS = ["\u2588", "\u2593", "\u2592", "\u2591"];
|
|
8865
|
-
var SPARK_CHARS = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"];
|
|
8866
|
-
var CARD_DIVIDER = "__TINYPIVOT_CARD_DIVIDER__";
|
|
8867
|
-
var BRAILLE_BITS = [
|
|
8868
|
-
[1, 8],
|
|
8869
|
-
[2, 16],
|
|
8870
|
-
[4, 32],
|
|
8871
|
-
[64, 128]
|
|
8872
|
-
];
|
|
8873
|
-
var ANSI_ESCAPE_RE = /\x1B\[[0-9;]*m/g;
|
|
8874
|
-
var ANSI_RESET = "\x1B[0m";
|
|
8875
|
-
var ANSI_BOLD = "\x1B[1m";
|
|
8876
|
-
function ansiFg(rgb, text) {
|
|
8877
|
-
return `\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
|
|
8878
|
-
}
|
|
8879
|
-
function ansiFgBold(rgb, text) {
|
|
8880
|
-
return `${ANSI_BOLD}\x1B[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m${text}${ANSI_RESET}`;
|
|
8881
|
-
}
|
|
8882
|
-
function codePointDisplayWidth(cp) {
|
|
8883
|
-
if (cp < 32 || cp >= 127 && cp < 160)
|
|
8884
|
-
return 0;
|
|
8885
|
-
if (cp >= 768 && cp <= 879 || cp >= 6832 && cp <= 6911 || cp >= 7616 && cp <= 7679 || cp >= 8203 && cp <= 8207 || cp >= 8232 && cp <= 8239 || cp >= 8400 && cp <= 8447 || cp >= 65024 && cp <= 65039 || cp >= 65056 && cp <= 65071 || cp >= 917760 && cp <= 917999) {
|
|
8886
|
-
return 0;
|
|
8887
|
-
}
|
|
8888
|
-
if (cp >= 4352 && cp <= 4447 || cp === 9001 || cp === 9002 || cp >= 11904 && cp <= 12350 || cp >= 12352 && cp <= 42191 || cp >= 44032 && cp <= 55203 || cp >= 63744 && cp <= 64255 || cp >= 65040 && cp <= 65049 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65376 || cp >= 65504 && cp <= 65510 || cp >= 127744 && cp <= 129791 || cp >= 131072 && cp <= 262141) {
|
|
8889
|
-
return 2;
|
|
8890
|
-
}
|
|
8891
|
-
return 1;
|
|
8892
|
-
}
|
|
8893
|
-
function visualWidth(text) {
|
|
8894
|
-
const clean = text.replace(ANSI_ESCAPE_RE, "");
|
|
8895
|
-
let width = 0;
|
|
8896
|
-
for (const ch of clean) {
|
|
8897
|
-
const cp = ch.codePointAt(0);
|
|
8898
|
-
if (cp !== void 0)
|
|
8899
|
-
width += codePointDisplayWidth(cp);
|
|
8900
|
-
}
|
|
8901
|
-
return width;
|
|
8902
|
-
}
|
|
8903
|
-
function truncateVisual(text, maxWidth) {
|
|
8904
|
-
if (maxWidth <= 0)
|
|
8905
|
-
return "";
|
|
8906
|
-
if (visualWidth(text) <= maxWidth)
|
|
8907
|
-
return text;
|
|
8908
|
-
if (maxWidth === 1)
|
|
8909
|
-
return "\u2026";
|
|
8910
|
-
const target = maxWidth - 1;
|
|
8911
|
-
let out = "";
|
|
8912
|
-
let used = 0;
|
|
8913
|
-
for (const ch of text) {
|
|
8914
|
-
const cp = ch.codePointAt(0);
|
|
8915
|
-
const w = cp !== void 0 ? codePointDisplayWidth(cp) : 0;
|
|
8916
|
-
if (used + w > target)
|
|
8917
|
-
break;
|
|
8918
|
-
out += ch;
|
|
8919
|
-
used += w;
|
|
8920
|
-
}
|
|
8921
|
-
return `${out}\u2026`;
|
|
8922
|
-
}
|
|
8923
|
-
function padEndVisual(text, targetWidth) {
|
|
8924
|
-
const pad = Math.max(0, targetWidth - visualWidth(text));
|
|
8925
|
-
return pad > 0 ? `${text}${" ".repeat(pad)}` : text;
|
|
8926
|
-
}
|
|
8927
|
-
function padStartVisual(text, targetWidth) {
|
|
8928
|
-
const pad = Math.max(0, targetWidth - visualWidth(text));
|
|
8929
|
-
return pad > 0 ? `${" ".repeat(pad)}${text}` : text;
|
|
8930
|
-
}
|
|
8931
|
-
function formatCompactNumber(val) {
|
|
8932
|
-
if (!Number.isFinite(val))
|
|
8933
|
-
return "0";
|
|
8934
|
-
const abs = Math.abs(val);
|
|
8935
|
-
const sign = val < 0 ? "-" : "";
|
|
8936
|
-
if (abs >= 1e9)
|
|
8937
|
-
return `${sign}${(abs / 1e9).toFixed(2)}B`;
|
|
8938
|
-
if (abs >= 1e6)
|
|
8939
|
-
return `${sign}${(abs / 1e6).toFixed(2)}M`;
|
|
8940
|
-
if (abs >= 1e4)
|
|
8941
|
-
return `${sign}${(abs / 1e3).toFixed(1)}k`;
|
|
8942
|
-
if (abs >= 1e3)
|
|
8943
|
-
return `${sign}${Math.round(abs).toLocaleString("en-US")}`;
|
|
8944
|
-
return Number.isInteger(val) ? String(val) : val.toFixed(1);
|
|
8945
|
-
}
|
|
8946
|
-
function renderPreciseBar(ratio, width) {
|
|
8947
|
-
const clamped = Math.max(0, Math.min(1, ratio));
|
|
8948
|
-
if (clamped <= 0)
|
|
8949
|
-
return "";
|
|
8950
|
-
const totalEighths = Math.round(clamped * width * 8);
|
|
8951
|
-
if (totalEighths === 0)
|
|
8952
|
-
return "\u258F";
|
|
8953
|
-
const full = Math.floor(totalEighths / 8);
|
|
8954
|
-
const rem = totalEighths % 8;
|
|
8955
|
-
return `${"\u2588".repeat(full)}${SUB_BLOCKS[rem]}`;
|
|
8956
|
-
}
|
|
8957
|
-
function renderSparkline(values) {
|
|
8958
|
-
if (values.length === 0)
|
|
8959
|
-
return "";
|
|
8960
|
-
const min = Math.min(...values);
|
|
8961
|
-
const max = Math.max(...values);
|
|
8962
|
-
const span = max - min;
|
|
8963
|
-
return values.map((v) => {
|
|
8964
|
-
if (!Number.isFinite(v))
|
|
8965
|
-
return " ";
|
|
8966
|
-
if (span <= 0)
|
|
8967
|
-
return SPARK_CHARS[3];
|
|
8968
|
-
const idx = Math.min(SPARK_CHARS.length - 1, Math.max(0, Math.round((v - min) / span * (SPARK_CHARS.length - 1))));
|
|
8969
|
-
return SPARK_CHARS[idx];
|
|
8970
|
-
}).join("");
|
|
8971
|
-
}
|
|
8972
|
-
function buildTopBorder(title, rightBadge, innerWidth) {
|
|
8973
|
-
if (rightBadge) {
|
|
8974
|
-
const safeRight = truncateVisual(rightBadge, Math.max(8, Math.floor(innerWidth * 0.44)));
|
|
8975
|
-
const rightW = visualWidth(safeRight);
|
|
8976
|
-
const maxTitleW = Math.max(1, innerWidth - 5 - rightW);
|
|
8977
|
-
const safeTitle2 = truncateVisual(title, maxTitleW);
|
|
8978
|
-
const dashCount2 = Math.max(1, innerWidth - 4 - visualWidth(safeTitle2) - rightW);
|
|
8979
|
-
return `\u256D\u2500 ${safeTitle2} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256E`;
|
|
8980
|
-
}
|
|
8981
|
-
const safeTitle = truncateVisual(title, Math.max(1, innerWidth - 3));
|
|
8982
|
-
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeTitle));
|
|
8983
|
-
return `\u256D\u2500 ${safeTitle} ${"\u2500".repeat(dashCount)}\u2500\u256E`;
|
|
8984
|
-
}
|
|
8985
|
-
function buildBottomBorder(footerLeft, footerRight, innerWidth) {
|
|
8986
|
-
if (footerLeft && footerRight) {
|
|
8987
|
-
const safeLeft = truncateVisual(footerLeft, Math.max(8, Math.floor(innerWidth * 0.45)));
|
|
8988
|
-
const leftW = visualWidth(safeLeft);
|
|
8989
|
-
const maxRightW = innerWidth - 5 - leftW;
|
|
8990
|
-
if (maxRightW >= 4) {
|
|
8991
|
-
const safeRight = truncateVisual(footerRight, maxRightW);
|
|
8992
|
-
const rightW = visualWidth(safeRight);
|
|
8993
|
-
const dashCount2 = Math.max(1, innerWidth - 4 - leftW - rightW);
|
|
8994
|
-
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount2)} ${safeRight} \u2500\u256F`;
|
|
8995
|
-
}
|
|
8996
|
-
const dashCount = Math.max(1, innerWidth - 2 - leftW);
|
|
8997
|
-
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
|
|
8998
|
-
}
|
|
8999
|
-
if (footerLeft) {
|
|
9000
|
-
const safeLeft = truncateVisual(footerLeft, Math.max(1, innerWidth - 3));
|
|
9001
|
-
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeLeft));
|
|
9002
|
-
return `\u2570\u2500 ${safeLeft} ${"\u2500".repeat(dashCount)}\u2500\u256F`;
|
|
9003
|
-
}
|
|
9004
|
-
if (footerRight) {
|
|
9005
|
-
const safeRight = truncateVisual(footerRight, Math.max(1, innerWidth - 3));
|
|
9006
|
-
const dashCount = Math.max(1, innerWidth - 2 - visualWidth(safeRight));
|
|
9007
|
-
return `\u2570\u2500${"\u2500".repeat(dashCount)} ${safeRight} \u2500\u256F`;
|
|
9008
|
-
}
|
|
9009
|
-
return `\u2570${"\u2500".repeat(innerWidth + 2)}\u256F`;
|
|
9010
|
-
}
|
|
9011
|
-
function resolveTerminalPalette(theme) {
|
|
9012
|
-
if (!theme)
|
|
9013
|
-
return void 0;
|
|
9014
|
-
return TERMINAL_PALETTES[theme] ?? TERMINAL_PALETTES.code;
|
|
9015
|
-
}
|
|
9016
|
-
function wrapInCard(title, rightBadge, bodyLines, footerLeft, footerRight, minWidth = 66, options = {}) {
|
|
9017
|
-
const pal = options.palette;
|
|
9018
|
-
const contentLines = bodyLines.filter((l) => l !== CARD_DIVIDER);
|
|
9019
|
-
const longestBody = Math.max(...contentLines.map((l) => visualWidth(l)), 0);
|
|
9020
|
-
const desiredHeader = visualWidth(title) + visualWidth(rightBadge) + (rightBadge ? 6 : 4);
|
|
9021
|
-
const desiredFooter = visualWidth(footerLeft) + visualWidth(footerRight) + (footerLeft && footerRight ? 6 : 4);
|
|
9022
|
-
const innerWidth = Math.min(82, Math.max(minWidth, longestBody, Math.min(desiredHeader, 82), Math.min(desiredFooter, 82)));
|
|
9023
|
-
const topPlain = buildTopBorder(title, rightBadge, innerWidth);
|
|
9024
|
-
const topBorder = pal ? topPlain.replace(/^(╭─ )(.+?)( ─+ )(.+?)( ─╮)$/, (_, a, b, c, d, e) => `${ansiFg(pal.border, a)}${ansiFgBold(pal.text, b)}${ansiFg(pal.border, c)}${ansiFg(pal.accent, d)}${ansiFg(pal.border, e)}`) : topPlain;
|
|
9025
|
-
const dividerPlain = `\u251C${"\u2500".repeat(innerWidth + 2)}\u2524`;
|
|
9026
|
-
const dividerLine = pal ? ansiFg(pal.border, dividerPlain) : dividerPlain;
|
|
9027
|
-
const edge = pal ? ansiFg(pal.border, "\u2502") : "\u2502";
|
|
9028
|
-
const paddedBody = bodyLines.map((line) => {
|
|
9029
|
-
if (line === CARD_DIVIDER)
|
|
9030
|
-
return dividerLine;
|
|
9031
|
-
const clipped = visualWidth(line) > innerWidth ? truncateVisual(line, innerWidth) : line;
|
|
9032
|
-
return `${edge} ${padEndVisual(clipped, innerWidth)} ${edge}`;
|
|
9033
|
-
});
|
|
9034
|
-
const botPlain = buildBottomBorder(footerLeft, footerRight, innerWidth);
|
|
9035
|
-
const bottomBorder = pal ? ansiFg(pal.border, botPlain) : botPlain;
|
|
9036
|
-
if (options.raw)
|
|
9037
|
-
return [topBorder, ...paddedBody, bottomBorder].join("\n");
|
|
9038
|
-
return ["```text", topBorder, ...paddedBody, bottomBorder, "```"].join("\n");
|
|
9039
|
-
}
|
|
9074
|
+
// src/terminal-chart.ts
|
|
9040
9075
|
function computeBrailleYBounds(values) {
|
|
9041
9076
|
const rawMin = Math.min(...values);
|
|
9042
9077
|
const rawMax = Math.max(...values);
|
|
@@ -9066,9 +9101,11 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
|
|
|
9066
9101
|
const pxW = chartCols * 2;
|
|
9067
9102
|
const pxH = chartRows * 4;
|
|
9068
9103
|
const grid = Array.from({ length: chartRows }, () => Array.from({ length: chartCols }).fill(0));
|
|
9104
|
+
const owners = Array.from({ length: chartRows }, () => Array.from({ length: chartCols }).fill(-1));
|
|
9105
|
+
let drawing = 0;
|
|
9069
9106
|
const allFinite = seriesList.flatMap((s) => s.values.filter((v) => v !== null && Number.isFinite(v)));
|
|
9070
9107
|
if (allFinite.length === 0)
|
|
9071
|
-
return [];
|
|
9108
|
+
return { lines: [], plotStart: 0, owners };
|
|
9072
9109
|
const { minVal, maxVal, span } = computeBrailleYBounds(allFinite);
|
|
9073
9110
|
const setPixel = (x, y) => {
|
|
9074
9111
|
const cx = Math.max(0, Math.min(pxW - 1, Math.round(x)));
|
|
@@ -9076,6 +9113,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
|
|
|
9076
9113
|
const cellCol = Math.floor(cx / 2);
|
|
9077
9114
|
const cellRow = Math.floor(cy / 4);
|
|
9078
9115
|
grid[cellRow][cellCol] |= BRAILLE_BITS[cy % 4][cx % 2];
|
|
9116
|
+
owners[cellRow][cellCol] = drawing;
|
|
9079
9117
|
};
|
|
9080
9118
|
const curveY = Array.from({ length: pxW }).fill(pxH);
|
|
9081
9119
|
const plotPoint = (x, y, trackCurve) => {
|
|
@@ -9095,6 +9133,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
|
|
|
9095
9133
|
const count = categories.length;
|
|
9096
9134
|
for (let sIdx = 0; sIdx < seriesList.length; sIdx++) {
|
|
9097
9135
|
const series = seriesList[sIdx];
|
|
9136
|
+
drawing = sIdx;
|
|
9098
9137
|
const trackCurve = filledArea && sIdx === 0 && seriesList.length === 1;
|
|
9099
9138
|
let prev = null;
|
|
9100
9139
|
let dashCounter = 0;
|
|
@@ -9123,6 +9162,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
|
|
|
9123
9162
|
}
|
|
9124
9163
|
}
|
|
9125
9164
|
if (filledArea && seriesList.length === 1) {
|
|
9165
|
+
drawing = 0;
|
|
9126
9166
|
for (let cx = 0; cx < pxW; cx += 2) {
|
|
9127
9167
|
const topY = curveY[cx];
|
|
9128
9168
|
if (topY < pxH) {
|
|
@@ -9150,6 +9190,7 @@ function renderBrailleLineBody(categories, seriesList, filledArea = false, nonAd
|
|
|
9150
9190
|
lines.push(legendItems.join(" "));
|
|
9151
9191
|
lines.push("");
|
|
9152
9192
|
}
|
|
9193
|
+
const plotStart = lines.length;
|
|
9153
9194
|
for (let r = 0; r < chartRows; r++) {
|
|
9154
9195
|
let yTick = "";
|
|
9155
9196
|
let axisChar = "\u2502";
|
|
@@ -9184,173 +9225,312 @@ 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 };
|
|
9229
|
+
}
|
|
9230
|
+
function formatTrendDelta(values) {
|
|
9231
|
+
if (values.length < 2)
|
|
9232
|
+
return "";
|
|
9233
|
+
const first = values[0];
|
|
9234
|
+
const last = values[values.length - 1];
|
|
9235
|
+
if (!Number.isFinite(first) || !Number.isFinite(last) || first <= 0)
|
|
9236
|
+
return "";
|
|
9237
|
+
const pct = (last - first) / first * 100;
|
|
9238
|
+
const sign = pct >= 0 ? "+" : "";
|
|
9239
|
+
return `${sign}${pct.toFixed(1)}%`;
|
|
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);
|
|
9188
9386
|
}
|
|
9189
|
-
function
|
|
9190
|
-
|
|
9191
|
-
|
|
9192
|
-
const
|
|
9193
|
-
const
|
|
9194
|
-
|
|
9195
|
-
|
|
9196
|
-
|
|
9197
|
-
|
|
9198
|
-
|
|
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);
|
|
9199
9490
|
}
|
|
9200
9491
|
function formatTerminalChart(dataset, chartConfig, options = {}) {
|
|
9201
9492
|
if (!chartConfig?.xAxis || !chartConfig?.yAxis || dataset.rows.length === 0)
|
|
9202
9493
|
return "";
|
|
9203
|
-
const
|
|
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,
|
|
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
|
-
|
|
9220
|
-
let
|
|
9221
|
-
|
|
9222
|
-
|
|
9223
|
-
|
|
9224
|
-
|
|
9225
|
-
|
|
9226
|
-
|
|
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
|
|
9231
|
-
const
|
|
9232
|
-
|
|
9233
|
-
|
|
9234
|
-
|
|
9235
|
-
|
|
9236
|
-
|
|
9237
|
-
|
|
9238
|
-
|
|
9239
|
-
|
|
9240
|
-
|
|
9241
|
-
|
|
9242
|
-
|
|
9243
|
-
|
|
9244
|
-
|
|
9245
|
-
|
|
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) ??
|
|
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
|
-
|
|
9446
|
-
|
|
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
|
-
|
|
9570
|
-
|
|
9764
|
+
const note = cardNote(companionUrl, options);
|
|
9765
|
+
if (note)
|
|
9766
|
+
out.push(note);
|
|
9571
9767
|
return out.join("\n");
|
|
9572
9768
|
}
|
|
9573
9769
|
|
|
@@ -10102,65 +10298,6 @@ import fs3 from "fs/promises";
|
|
|
10102
10298
|
import http from "http";
|
|
10103
10299
|
import path3 from "path";
|
|
10104
10300
|
|
|
10105
|
-
// src/analyst-endpoint.ts
|
|
10106
|
-
var ANALYST_ROW_LIMIT = 1e4;
|
|
10107
|
-
function schemaFor(dataset) {
|
|
10108
|
-
return {
|
|
10109
|
-
table: dataset.id,
|
|
10110
|
-
columns: dataset.columns.map((column) => ({
|
|
10111
|
-
name: column.name,
|
|
10112
|
-
type: column.type === "null" ? "unknown" : column.type,
|
|
10113
|
-
nullable: true
|
|
10114
|
-
}))
|
|
10115
|
-
};
|
|
10116
|
-
}
|
|
10117
|
-
function queryableDatasets(studio) {
|
|
10118
|
-
return studio.queryViews().flatMap((view) => studio.store.get(view.name) ?? []);
|
|
10119
|
-
}
|
|
10120
|
-
function chatTurns(messages) {
|
|
10121
|
-
if (!Array.isArray(messages))
|
|
10122
|
-
return [];
|
|
10123
|
-
return messages.flatMap((message) => {
|
|
10124
|
-
const { role, content } = message ?? {};
|
|
10125
|
-
return (role === "user" || role === "assistant") && typeof content === "string" ? [{ role, content }] : [];
|
|
10126
|
-
});
|
|
10127
|
-
}
|
|
10128
|
-
async function runQuery(studio, sql) {
|
|
10129
|
-
if (typeof sql !== "string" || !sql.trim())
|
|
10130
|
-
return { status: 400, body: { success: false, error: "Send one SELECT statement." } };
|
|
10131
|
-
try {
|
|
10132
|
-
const result = await studio.duck.run(sql, studio.queryViews(), ANALYST_ROW_LIMIT);
|
|
10133
|
-
return { status: 200, body: { success: true, data: result.rows, rowCount: result.rows.length, truncated: result.truncated } };
|
|
10134
|
-
} catch (error) {
|
|
10135
|
-
return { status: 200, body: { success: false, error: error instanceof Error ? error.message : String(error) } };
|
|
10136
|
-
}
|
|
10137
|
-
}
|
|
10138
|
-
async function chat(studio, messages) {
|
|
10139
|
-
const turns = chatTurns(messages);
|
|
10140
|
-
const question = turns.filter((turn) => turn.role === "user").at(-1)?.content.trim();
|
|
10141
|
-
if (!question)
|
|
10142
|
-
return { status: 400, body: { error: "Ask a question." } };
|
|
10143
|
-
return { status: 200, body: { content: await studio.ask(question, { turns }) } };
|
|
10144
|
-
}
|
|
10145
|
-
async function handleAnalystAction(studio, body) {
|
|
10146
|
-
switch (body.action) {
|
|
10147
|
-
case "list-tables":
|
|
10148
|
-
return { status: 200, body: { tables: queryableDatasets(studio).map((ds) => ({ name: ds.id, description: `${ds.name}: ${ds.rows.length.toLocaleString("en-US")} rows` })) } };
|
|
10149
|
-
case "get-schema": {
|
|
10150
|
-
const wanted = new Set(Array.isArray(body.tables) ? body.tables.map(String) : []);
|
|
10151
|
-
return { status: 200, body: { schemas: queryableDatasets(studio).filter((ds) => wanted.has(ds.id)).map(schemaFor) } };
|
|
10152
|
-
}
|
|
10153
|
-
case "get-all-schemas":
|
|
10154
|
-
return { status: 200, body: { schemas: queryableDatasets(studio).map(schemaFor) } };
|
|
10155
|
-
case "query":
|
|
10156
|
-
return runQuery(studio, body.sql);
|
|
10157
|
-
case "chat":
|
|
10158
|
-
return chat(studio, body.messages);
|
|
10159
|
-
default:
|
|
10160
|
-
return { status: 400, body: { error: `Unknown action: ${String(body.action)}` } };
|
|
10161
|
-
}
|
|
10162
|
-
}
|
|
10163
|
-
|
|
10164
10301
|
// src/limits.ts
|
|
10165
10302
|
var INTERACTIVE_ROW_LIMIT = 1e5;
|
|
10166
10303
|
var ROW_PAGE_SIZE = 25e3;
|
|
@@ -10189,7 +10326,7 @@ function openAgentStream(studio, agentName, req, res) {
|
|
|
10189
10326
|
if (res.writableEnded)
|
|
10190
10327
|
return false;
|
|
10191
10328
|
res.write(`event: message
|
|
10192
|
-
data: ${JSON.stringify({ id: note.id,
|
|
10329
|
+
data: ${JSON.stringify({ id: note.id, text })}
|
|
10193
10330
|
|
|
10194
10331
|
`);
|
|
10195
10332
|
return true;
|
|
@@ -10202,6 +10339,19 @@ data: ${JSON.stringify({ id: note.id, kind: note.kind, text })}
|
|
|
10202
10339
|
disconnect();
|
|
10203
10340
|
});
|
|
10204
10341
|
}
|
|
10342
|
+
function colouredCard(store, title, companionUrl, isPro2) {
|
|
10343
|
+
if (!title)
|
|
10344
|
+
return null;
|
|
10345
|
+
for (const meta of store.listMetadata()) {
|
|
10346
|
+
const dataset = store.get(meta.id);
|
|
10347
|
+
if (!dataset)
|
|
10348
|
+
continue;
|
|
10349
|
+
const card = datasetCard(dataset, { colorTheme: store.getVisualTheme(), raw: true, companionUrl, showBranding: !isPro2 });
|
|
10350
|
+
if (card && cardTitle(card) === title)
|
|
10351
|
+
return card;
|
|
10352
|
+
}
|
|
10353
|
+
return null;
|
|
10354
|
+
}
|
|
10205
10355
|
function sendJson(res, status, body) {
|
|
10206
10356
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
10207
10357
|
res.end(JSON.stringify(body));
|
|
@@ -10277,13 +10427,13 @@ function buildFullCompanionPayload(store, datasetId, opts) {
|
|
|
10277
10427
|
async function startCompanionServer(options) {
|
|
10278
10428
|
const sseClients = /* @__PURE__ */ new Set();
|
|
10279
10429
|
const send = (event, payload) => {
|
|
10280
|
-
const
|
|
10430
|
+
const frame2 = `event: ${event}
|
|
10281
10431
|
data: ${JSON.stringify(payload)}
|
|
10282
10432
|
|
|
10283
10433
|
`;
|
|
10284
10434
|
for (const res of sseClients) {
|
|
10285
10435
|
try {
|
|
10286
|
-
res.write(
|
|
10436
|
+
res.write(frame2);
|
|
10287
10437
|
} catch {
|
|
10288
10438
|
sseClients.delete(res);
|
|
10289
10439
|
}
|
|
@@ -10330,17 +10480,13 @@ data: ${JSON.stringify(payload)}
|
|
|
10330
10480
|
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
10331
10481
|
if (!text)
|
|
10332
10482
|
return sendJson(res, 400, { error: "Send the reply text." });
|
|
10333
|
-
studio.reply(text.slice(0, 2e4)
|
|
10483
|
+
studio.reply(text.slice(0, 2e4));
|
|
10334
10484
|
return sendJson(res, 200, { ok: true });
|
|
10335
10485
|
}
|
|
10336
10486
|
if (pathname === "/api/studio/agent-status") {
|
|
10337
10487
|
studio.setAgentBusy(body.busy === true);
|
|
10338
10488
|
return sendJson(res, 200, { ok: true });
|
|
10339
10489
|
}
|
|
10340
|
-
if (pathname === "/api/studio/analyst") {
|
|
10341
|
-
const result = await handleAnalystAction(studio, body);
|
|
10342
|
-
return sendJson(res, result.status, result.body);
|
|
10343
|
-
}
|
|
10344
10490
|
if (pathname === "/api/studio/show") {
|
|
10345
10491
|
try {
|
|
10346
10492
|
const dataset = await studio.showStep(String(body.stepId ?? ""));
|
|
@@ -10361,17 +10507,17 @@ data: ${JSON.stringify(payload)}
|
|
|
10361
10507
|
}
|
|
10362
10508
|
return sendJson(res, 404, { error: "Not found" });
|
|
10363
10509
|
};
|
|
10510
|
+
let listenPort = 0;
|
|
10364
10511
|
const server = http.createServer(async (req, res) => {
|
|
10365
10512
|
const urlObj = new URL(req.url || "/", "http://127.0.0.1");
|
|
10366
10513
|
const pathname = urlObj.pathname;
|
|
10367
10514
|
res.setHeader("Cache-Control", "no-store");
|
|
10368
|
-
const port = server.address().port;
|
|
10369
10515
|
const allowed = isAllowedRequest({
|
|
10370
10516
|
method: req.method,
|
|
10371
10517
|
host: req.headers.host,
|
|
10372
10518
|
origin: req.headers.origin,
|
|
10373
10519
|
studioHeader: req.headers[STUDIO_HEADER]
|
|
10374
|
-
},
|
|
10520
|
+
}, listenPort);
|
|
10375
10521
|
if (!allowed)
|
|
10376
10522
|
return sendJson(res, 403, { error: "Forbidden" });
|
|
10377
10523
|
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
@@ -10403,6 +10549,11 @@ data: ${JSON.stringify(studio.snapshot())}
|
|
|
10403
10549
|
openAgentStream(studio, agentName, req, res);
|
|
10404
10550
|
return;
|
|
10405
10551
|
}
|
|
10552
|
+
if (req.method === "GET" && pathname === "/api/studio/card") {
|
|
10553
|
+
const title = urlObj.searchParams.get("title") ?? "";
|
|
10554
|
+
const ansi = colouredCard(options.store, title, `http://127.0.0.1:${listenPort}`, Boolean(options.licenseKey || options.demoToken));
|
|
10555
|
+
return ansi ? sendJson(res, 200, { ansi }) : sendJson(res, 404, { error: "No card with that title." });
|
|
10556
|
+
}
|
|
10406
10557
|
if (req.method === "GET" && pathname === "/api/studio") {
|
|
10407
10558
|
return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
|
|
10408
10559
|
}
|
|
@@ -10459,6 +10610,7 @@ data: ${JSON.stringify(studio.snapshot())}
|
|
|
10459
10610
|
server.listen(options.port ?? 0, "127.0.0.1", () => resolve());
|
|
10460
10611
|
});
|
|
10461
10612
|
const address = server.address();
|
|
10613
|
+
listenPort = address.port;
|
|
10462
10614
|
const url = `http://127.0.0.1:${address.port}`;
|
|
10463
10615
|
const sessionFile = getCompanionSessionFile();
|
|
10464
10616
|
try {
|
|
@@ -10486,6 +10638,7 @@ data: ${JSON.stringify(studio.snapshot())}
|
|
|
10486
10638
|
sseClients.clear();
|
|
10487
10639
|
await new Promise((resolve) => {
|
|
10488
10640
|
server.close(() => resolve());
|
|
10641
|
+
server.closeAllConnections();
|
|
10489
10642
|
});
|
|
10490
10643
|
try {
|
|
10491
10644
|
const raw = await fs3.readFile(sessionFile, "utf8");
|
|
@@ -10501,11 +10654,41 @@ data: ${JSON.stringify(studio.snapshot())}
|
|
|
10501
10654
|
};
|
|
10502
10655
|
}
|
|
10503
10656
|
|
|
10657
|
+
// src/agent-bridge.ts
|
|
10658
|
+
var EXTENSION_HEADER = "// Auto-installed by @smallwebco/tinypivot-mcp init";
|
|
10659
|
+
var AgentBridge = class {
|
|
10660
|
+
constructor(onChange) {
|
|
10661
|
+
this.onChange = onChange;
|
|
10662
|
+
}
|
|
10663
|
+
connectors = /* @__PURE__ */ new Set();
|
|
10664
|
+
/** Adds a way to reach the agent; the returned function removes it. */
|
|
10665
|
+
connect(connector) {
|
|
10666
|
+
this.connectors.add(connector);
|
|
10667
|
+
this.onChange();
|
|
10668
|
+
return () => {
|
|
10669
|
+
if (this.connectors.delete(connector))
|
|
10670
|
+
this.onChange();
|
|
10671
|
+
};
|
|
10672
|
+
}
|
|
10673
|
+
/** Names of the ways that reach the agent right now. */
|
|
10674
|
+
live() {
|
|
10675
|
+
return [...this.connectors].map((connector) => connector.name);
|
|
10676
|
+
}
|
|
10677
|
+
/** Delivers into the conversation through the first connector that takes it. */
|
|
10678
|
+
push(note, text) {
|
|
10679
|
+
for (const connector of this.connectors) {
|
|
10680
|
+
if (connector.push(note, text))
|
|
10681
|
+
return connector.name;
|
|
10682
|
+
}
|
|
10683
|
+
return void 0;
|
|
10684
|
+
}
|
|
10685
|
+
};
|
|
10686
|
+
|
|
10504
10687
|
// src/pi-extension.ts
|
|
10505
10688
|
function buildPiExtensionSource() {
|
|
10506
10689
|
const palettesJson = JSON.stringify(TERMINAL_PALETTES, null, 2);
|
|
10507
10690
|
const themeOrderJson = JSON.stringify(CHART_THEME_IDS);
|
|
10508
|
-
return
|
|
10691
|
+
return `${EXTENSION_HEADER} \u2014 do not edit by hand.
|
|
10509
10692
|
// Renders TinyPivot charts & pivot tables in full 24-bit truecolor inside pi
|
|
10510
10693
|
// and adds the /tinypivot-theme slash command.
|
|
10511
10694
|
|
|
@@ -10614,6 +10797,12 @@ function colorizeSegments(text: string, pal: Palette): string {
|
|
|
10614
10797
|
});
|
|
10615
10798
|
}
|
|
10616
10799
|
|
|
10800
|
+
// Makes the Studio address in a card clickable, as an OSC 8 terminal hyperlink.
|
|
10801
|
+
const CARD_LINK = /http:[/][/]127[.]0[.]0[.]1:[0-9]+/;
|
|
10802
|
+
function hyperlink(text: string): string {
|
|
10803
|
+
return text.replace(CARD_LINK, url => "\\x1b]8;;" + url + "\\x1b\\\\" + url + "\\x1b]8;;\\x1b\\\\");
|
|
10804
|
+
}
|
|
10805
|
+
|
|
10617
10806
|
function colorizeCardLine(line: string, pal: Palette): string {
|
|
10618
10807
|
if (line.startsWith("\u256D\u2500")) {
|
|
10619
10808
|
const withBadge = line.replace(/^(\u256D\u2500 )(.+?)( \u2500+ )(.+?)( \u2500\u256E)$/, (_m, a, b, c, d, e) =>
|
|
@@ -10638,7 +10827,7 @@ function colorizeCardLine(line: string, pal: Palette): string {
|
|
|
10638
10827
|
const edge = fg(pal.border, "\u2502");
|
|
10639
10828
|
|
|
10640
10829
|
if (inner.includes("\u2197 Live:")) {
|
|
10641
|
-
return \`\${edge}\${fgBold(pal.accent, inner)}\${edge}\`;
|
|
10830
|
+
return \`\${edge}\${fgBold(pal.accent, hyperlink(inner))}\${edge}\`;
|
|
10642
10831
|
}
|
|
10643
10832
|
if (inner.includes("\u25B2 ") && (inner.includes("Peak:") || inner.includes("peak:"))) {
|
|
10644
10833
|
return \`\${edge}\${fg(pal.muted, inner)}\${edge}\`;
|
|
@@ -10690,6 +10879,8 @@ function isTinyPivotTool(toolName: string): boolean {
|
|
|
10690
10879
|
interface TinyPivotCardEntryData {
|
|
10691
10880
|
cards: string[];
|
|
10692
10881
|
themeId: string;
|
|
10882
|
+
/** The same cards in full colour from the Studio, where it could provide them. */
|
|
10883
|
+
coloured?: Array<string | null>;
|
|
10693
10884
|
}
|
|
10694
10885
|
|
|
10695
10886
|
// TinyPivot Studio bridge: messages the user sends from the Studio arrive here, go into this
|
|
@@ -10717,14 +10908,15 @@ function lastAssistantText(messages: unknown): string {
|
|
|
10717
10908
|
function createStudioBridge(pi: any) {
|
|
10718
10909
|
let studioUrl: string | undefined;
|
|
10719
10910
|
let stream: AbortController | undefined;
|
|
10720
|
-
|
|
10911
|
+
/** Set while a turn that a Studio message started is running, so its answer goes back. */
|
|
10912
|
+
let awaiting = false;
|
|
10721
10913
|
|
|
10722
10914
|
function handleFrame(frame: string): void {
|
|
10723
10915
|
if (!frame.startsWith("event: message")) return;
|
|
10724
10916
|
const data = frame.split("\\n").find(line => line.startsWith("data: "));
|
|
10725
10917
|
if (!data) return;
|
|
10726
|
-
const message = JSON.parse(data.slice(6)) as {
|
|
10727
|
-
awaiting =
|
|
10918
|
+
const message = JSON.parse(data.slice(6)) as { text: string };
|
|
10919
|
+
awaiting = true;
|
|
10728
10920
|
pi.sendMessage(
|
|
10729
10921
|
{ customType: "tinypivot-studio", content: message.text, display: true },
|
|
10730
10922
|
{ triggerTurn: true, deliverAs: "steer" },
|
|
@@ -10779,11 +10971,25 @@ function createStudioBridge(pi: any) {
|
|
|
10779
10971
|
},
|
|
10780
10972
|
async onAgentEnd(messages: unknown): Promise<void> {
|
|
10781
10973
|
if (!awaiting || !studioUrl) return;
|
|
10782
|
-
|
|
10783
|
-
awaiting = undefined;
|
|
10974
|
+
awaiting = false;
|
|
10784
10975
|
const text = lastAssistantText(messages);
|
|
10785
10976
|
if (!text) return;
|
|
10786
|
-
await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({
|
|
10977
|
+
await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ text }) }).catch(() => {});
|
|
10978
|
+
},
|
|
10979
|
+
/** Each card in full colour from the Studio (lines in each series' colour), or null. */
|
|
10980
|
+
async colouredCards(cards: string[]): Promise<Array<string | null>> {
|
|
10981
|
+
if (!studioUrl) return cards.map(() => null);
|
|
10982
|
+
const url = studioUrl;
|
|
10983
|
+
return Promise.all(cards.map(async (card) => {
|
|
10984
|
+
const title = /\u256D\u2500 (.+?) \u2500/.exec(card)?.[1];
|
|
10985
|
+
if (!title) return null;
|
|
10986
|
+
try {
|
|
10987
|
+
const res = await fetch(url + "/api/studio/card?title=" + encodeURIComponent(title), { signal: AbortSignal.timeout(1500) });
|
|
10988
|
+
return res.ok ? ((await res.json()) as { ansi?: string }).ansi ?? null : null;
|
|
10989
|
+
} catch {
|
|
10990
|
+
return null;
|
|
10991
|
+
}
|
|
10992
|
+
}));
|
|
10787
10993
|
},
|
|
10788
10994
|
stop(): void {
|
|
10789
10995
|
stream?.abort();
|
|
@@ -10807,10 +11013,12 @@ export default function (pi: any) {
|
|
|
10807
11013
|
render(_width: number): string[] {
|
|
10808
11014
|
const themeId = data.themeId || readActiveThemeId();
|
|
10809
11015
|
const out: string[] = [""];
|
|
10810
|
-
|
|
10811
|
-
|
|
11016
|
+
data.cards.forEach((card, i) => {
|
|
11017
|
+
const coloured = data.coloured?.[i];
|
|
11018
|
+
const lines = coloured ? coloured.split("\\n").map(hyperlink) : renderColoredCard(card, themeId);
|
|
11019
|
+
out.push(...lines.map(l => \` \${l}\`));
|
|
10812
11020
|
out.push("");
|
|
10813
|
-
}
|
|
11021
|
+
});
|
|
10814
11022
|
return out;
|
|
10815
11023
|
},
|
|
10816
11024
|
invalidate() {},
|
|
@@ -10818,19 +11026,21 @@ export default function (pi: any) {
|
|
|
10818
11026
|
});
|
|
10819
11027
|
}
|
|
10820
11028
|
|
|
10821
|
-
pi.on("tool_execution_end", (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
|
|
11029
|
+
pi.on("tool_execution_end", async (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
|
|
10822
11030
|
if (event?.isError) return;
|
|
10823
11031
|
const text = extractResultText(event.result);
|
|
10824
11032
|
if (!text) return;
|
|
10825
11033
|
// TinyPivot calls made through codemode arrive under another tool's name, so look at the text.
|
|
10826
11034
|
studio.noticeToolText(text);
|
|
10827
|
-
|
|
11035
|
+
const fromTinyPivot = isTinyPivotTool(event?.toolName ?? "") || event?.toolName === "codemode";
|
|
11036
|
+
if (!fromTinyPivot || ctx?.hasUI === false) return;
|
|
10828
11037
|
const cards = extractTinyPivotCards(text);
|
|
10829
11038
|
if (cards.length === 0) return;
|
|
10830
11039
|
|
|
10831
11040
|
const themeId = readActiveThemeId();
|
|
11041
|
+
const coloured = await studio.colouredCards(cards);
|
|
10832
11042
|
if (typeof pi.appendEntry === "function") {
|
|
10833
|
-
pi.appendEntry("tinypivot-card", { cards, themeId });
|
|
11043
|
+
pi.appendEntry("tinypivot-card", { cards, themeId, coloured });
|
|
10834
11044
|
}
|
|
10835
11045
|
});
|
|
10836
11046
|
|
|
@@ -10872,13 +11082,163 @@ import fs4 from "fs/promises";
|
|
|
10872
11082
|
import os3 from "os";
|
|
10873
11083
|
import path4 from "path";
|
|
10874
11084
|
import { fileURLToPath } from "url";
|
|
11085
|
+
|
|
11086
|
+
// src/opencode-plugin.ts
|
|
11087
|
+
function buildOpenCodePluginSource() {
|
|
11088
|
+
return `${EXTENSION_HEADER} \u2014 do not edit by hand.
|
|
11089
|
+
// Connects this OpenCode session to TinyPivot Studio: messages sent from the Studio arrive here
|
|
11090
|
+
// as prompts, and the agent's answer goes back to the Studio.
|
|
11091
|
+
|
|
11092
|
+
// The Studio link TinyPivot puts in its replies ("Studio: \u2026" or a card's "Live: \u2026").
|
|
11093
|
+
const STUDIO_LINK = /(?:Studio|Live): (http:[/][/]127[.]0[.]0[.]1:[0-9]+)/;
|
|
11094
|
+
const STUDIO_HEADERS = { "Content-Type": "application/json", "x-tinypivot": "1" };
|
|
11095
|
+
|
|
11096
|
+
// OpenCode treats every exported function as a plugin, so only the plugin is exported.
|
|
11097
|
+
|
|
11098
|
+
/** The text of the newest assistant message, from \`client.session.messages\`. */
|
|
11099
|
+
function lastAssistantText(messages) {
|
|
11100
|
+
if (!Array.isArray(messages)) return "";
|
|
11101
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
11102
|
+
const message = messages[i];
|
|
11103
|
+
if (message?.info?.role !== "assistant") continue;
|
|
11104
|
+
return (message.parts ?? [])
|
|
11105
|
+
.filter(part => part?.type === "text" && !part.synthetic && !part.ignored)
|
|
11106
|
+
.map(part => part.text ?? "")
|
|
11107
|
+
.join("\\n")
|
|
11108
|
+
.trim();
|
|
11109
|
+
}
|
|
11110
|
+
return "";
|
|
11111
|
+
}
|
|
11112
|
+
|
|
11113
|
+
/** A tool's reply text: MCP tools hand over \`{ content: [{ type: "text", text }] }\`, built-in tools \`{ output }\`. */
|
|
11114
|
+
function toolText(output) {
|
|
11115
|
+
if (typeof output?.output === "string") return output.output;
|
|
11116
|
+
if (!Array.isArray(output?.content)) return "";
|
|
11117
|
+
return output.content.map(part => (part?.type === "text" ? part.text ?? "" : "")).join("\\n");
|
|
11118
|
+
}
|
|
11119
|
+
|
|
11120
|
+
export const TinyPivotStudio = async ({ client }) => {
|
|
11121
|
+
let studioUrl;
|
|
11122
|
+
let stream;
|
|
11123
|
+
/** The OpenCode session that called TinyPivot last: Studio messages go there. */
|
|
11124
|
+
let sessionID;
|
|
11125
|
+
/** Set while a turn that a Studio message started is running, so its answer goes back. */
|
|
11126
|
+
let awaiting = false;
|
|
11127
|
+
|
|
11128
|
+
function post(route, body) {
|
|
11129
|
+
if (!studioUrl) return Promise.resolve();
|
|
11130
|
+
return fetch(studioUrl + route, { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify(body) }).catch(() => {});
|
|
11131
|
+
}
|
|
11132
|
+
|
|
11133
|
+
async function deliver(text) {
|
|
11134
|
+
if (!sessionID) return;
|
|
11135
|
+
awaiting = true;
|
|
11136
|
+
try {
|
|
11137
|
+
await client.session.promptAsync({ path: { id: sessionID }, body: { parts: [{ type: "text", text }] } });
|
|
11138
|
+
} catch (error) {
|
|
11139
|
+
awaiting = false;
|
|
11140
|
+
console.error("[tinypivot] Could not send the Studio message to OpenCode:", error);
|
|
11141
|
+
}
|
|
11142
|
+
}
|
|
11143
|
+
|
|
11144
|
+
function handleFrame(frame) {
|
|
11145
|
+
if (!frame.startsWith("event: message")) return;
|
|
11146
|
+
const data = frame.split("\\n").find(line => line.startsWith("data: "));
|
|
11147
|
+
if (!data) return;
|
|
11148
|
+
const message = JSON.parse(data.slice(6));
|
|
11149
|
+
if (typeof message?.text === "string") void deliver(message.text);
|
|
11150
|
+
}
|
|
11151
|
+
|
|
11152
|
+
async function listen(url, signal) {
|
|
11153
|
+
let delay = 1000;
|
|
11154
|
+
while (!signal.aborted) {
|
|
11155
|
+
try {
|
|
11156
|
+
const res = await fetch(url + "/api/studio/agent-stream?agent=opencode", { headers: STUDIO_HEADERS, signal });
|
|
11157
|
+
if (!res.ok || !res.body) throw new Error("Studio stream " + res.status);
|
|
11158
|
+
delay = 1000;
|
|
11159
|
+
const reader = res.body.getReader();
|
|
11160
|
+
const decoder = new TextDecoder();
|
|
11161
|
+
let buffer = "";
|
|
11162
|
+
for (;;) {
|
|
11163
|
+
const { value, done } = await reader.read();
|
|
11164
|
+
if (done) break;
|
|
11165
|
+
buffer += decoder.decode(value, { stream: true });
|
|
11166
|
+
let end = buffer.indexOf("\\n\\n");
|
|
11167
|
+
while (end >= 0) {
|
|
11168
|
+
handleFrame(buffer.slice(0, end));
|
|
11169
|
+
buffer = buffer.slice(end + 2);
|
|
11170
|
+
end = buffer.indexOf("\\n\\n");
|
|
11171
|
+
}
|
|
11172
|
+
}
|
|
11173
|
+
} catch {
|
|
11174
|
+
// The Studio restarted or closed; try again after a pause.
|
|
11175
|
+
}
|
|
11176
|
+
if (signal.aborted) return;
|
|
11177
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
11178
|
+
delay = Math.min(delay * 2, 30000);
|
|
11179
|
+
}
|
|
11180
|
+
}
|
|
11181
|
+
|
|
11182
|
+
/** Starts listening to the Studio named in a TinyPivot tool reply. */
|
|
11183
|
+
function noticeToolText(text) {
|
|
11184
|
+
const url = STUDIO_LINK.exec(text)?.[1];
|
|
11185
|
+
if (!url || url === studioUrl) return;
|
|
11186
|
+
stream?.abort();
|
|
11187
|
+
studioUrl = url;
|
|
11188
|
+
stream = new AbortController();
|
|
11189
|
+
void listen(url, stream.signal);
|
|
11190
|
+
}
|
|
11191
|
+
|
|
11192
|
+
async function sendAnswer() {
|
|
11193
|
+
if (!awaiting || !sessionID) return;
|
|
11194
|
+
awaiting = false;
|
|
11195
|
+
try {
|
|
11196
|
+
const res = await client.session.messages({ path: { id: sessionID } });
|
|
11197
|
+
const text = lastAssistantText(res?.data);
|
|
11198
|
+
if (text) await post("/api/studio/reply", { text });
|
|
11199
|
+
} catch (error) {
|
|
11200
|
+
console.error("[tinypivot] Could not read OpenCode's answer for the Studio:", error);
|
|
11201
|
+
}
|
|
11202
|
+
}
|
|
11203
|
+
|
|
11204
|
+
return {
|
|
11205
|
+
"tool.execute.after": async (input, output) => {
|
|
11206
|
+
if (!String(input?.tool ?? "").toLowerCase().includes("tinypivot")) return;
|
|
11207
|
+
sessionID = input.sessionID;
|
|
11208
|
+
noticeToolText(toolText(output));
|
|
11209
|
+
},
|
|
11210
|
+
event: async ({ event }) => {
|
|
11211
|
+
if (!sessionID || event?.properties?.sessionID !== sessionID) return;
|
|
11212
|
+
// Tells the Studio whether OpenCode is working, so it can show progress.
|
|
11213
|
+
if (event.type === "session.status") await post("/api/studio/agent-status", { busy: event.properties.status?.type === "busy" });
|
|
11214
|
+
if (event.type === "session.idle") {
|
|
11215
|
+
await post("/api/studio/agent-status", { busy: false });
|
|
11216
|
+
await sendAnswer();
|
|
11217
|
+
}
|
|
11218
|
+
},
|
|
11219
|
+
};
|
|
11220
|
+
};
|
|
11221
|
+
`;
|
|
11222
|
+
}
|
|
11223
|
+
|
|
11224
|
+
// src/init.ts
|
|
10875
11225
|
var MCP_NPX_SPEC = "@smallwebco/tinypivot-mcp@latest";
|
|
10876
11226
|
var RULE_START = "<!-- tinypivot:start -->";
|
|
10877
11227
|
var RULE_END = "<!-- tinypivot:end -->";
|
|
10878
11228
|
var RULE_TEST_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/;
|
|
10879
11229
|
var RULE_REPLACE_RE = /<!-- tinypivot(?:-mcp)?:start -->[\s\S]*?<!-- tinypivot(?:-mcp)?:end -->/g;
|
|
10880
11230
|
var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
|
|
10881
|
-
var RULE_USE = "
|
|
11231
|
+
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.";
|
|
11232
|
+
var PI_ENTRY_EXTRAS = {
|
|
11233
|
+
description: "Show any table of figures, ranking, breakdown, trend, chart or pivot to the user. Use it instead of Markdown tables.",
|
|
11234
|
+
toolExposure: {
|
|
11235
|
+
load_file: "direct",
|
|
11236
|
+
load_data: "direct",
|
|
11237
|
+
query: "direct",
|
|
11238
|
+
configure_chart: "direct",
|
|
11239
|
+
configure_pivot: "direct"
|
|
11240
|
+
}
|
|
11241
|
+
};
|
|
10882
11242
|
var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
|
|
10883
11243
|
${RULE_HEADING}
|
|
10884
11244
|
${RULE_USE} In a terminal, show its \`text\` card verbatim with the Studio link.
|
|
@@ -11007,7 +11367,7 @@ function buildStdioServerEntry(opts, cliPath) {
|
|
|
11007
11367
|
entry.env = env;
|
|
11008
11368
|
return entry;
|
|
11009
11369
|
}
|
|
11010
|
-
async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath) {
|
|
11370
|
+
async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cliPath, extras = {}) {
|
|
11011
11371
|
const explicit = opts.targets?.has(id) ?? false;
|
|
11012
11372
|
const shouldInclude = opts.targets ? explicit : opts.all || await exists(configPath) || await exists(detectDir);
|
|
11013
11373
|
if (!shouldInclude) {
|
|
@@ -11016,8 +11376,14 @@ async function upsertStandardMcpJson(id, label, configPath, detectDir, opts, cli
|
|
|
11016
11376
|
try {
|
|
11017
11377
|
const json = await readJsonSafe(configPath);
|
|
11018
11378
|
const mcpServers = json.mcpServers && typeof json.mcpServers === "object" && !Array.isArray(json.mcpServers) ? { ...json.mcpServers } : {};
|
|
11019
|
-
const nextEntry = buildStdioServerEntry(opts, cliPath);
|
|
11379
|
+
const nextEntry = { ...buildStdioServerEntry(opts, cliPath) };
|
|
11020
11380
|
const existing = mcpServers.tinypivot;
|
|
11381
|
+
if (extras.description)
|
|
11382
|
+
nextEntry.description = extras.description;
|
|
11383
|
+
if (extras.toolExposure) {
|
|
11384
|
+
const chosen = existing?.toolExposure && typeof existing.toolExposure === "object" ? existing.toolExposure : {};
|
|
11385
|
+
nextEntry.toolExposure = { ...extras.toolExposure, ...chosen };
|
|
11386
|
+
}
|
|
11021
11387
|
if (existing?.env && typeof existing.env === "object" && !Array.isArray(existing.env)) {
|
|
11022
11388
|
nextEntry.env = {
|
|
11023
11389
|
...existing.env,
|
|
@@ -11203,47 +11569,56 @@ async function upsertRuleFile(targetId, ruleId, label, detectDir, ruleFilePath,
|
|
|
11203
11569
|
};
|
|
11204
11570
|
}
|
|
11205
11571
|
}
|
|
11206
|
-
|
|
11207
|
-
|
|
11208
|
-
|
|
11572
|
+
var AGENT_EXTENSIONS = {
|
|
11573
|
+
pi: {
|
|
11574
|
+
label: "pi Studio & UI",
|
|
11575
|
+
path: (home = os3.homedir()) => path4.join(home, ".pi", "agent", "extensions", "tinypivot.ts"),
|
|
11576
|
+
detectDir: (home = os3.homedir()) => path4.join(home, ".pi"),
|
|
11577
|
+
build: buildPiExtensionSource,
|
|
11578
|
+
installs: "Studio messages, 24-bit cards & /tinypivot-theme"
|
|
11579
|
+
},
|
|
11580
|
+
opencode: {
|
|
11581
|
+
label: "OpenCode Studio",
|
|
11582
|
+
path: (home = os3.homedir()) => path4.join(process.env.XDG_CONFIG_HOME || path4.join(home, ".config"), "opencode", "plugins", "tinypivot.js"),
|
|
11583
|
+
detectDir: (home = os3.homedir()) => path4.join(process.env.XDG_CONFIG_HOME || path4.join(home, ".config"), "opencode"),
|
|
11584
|
+
build: buildOpenCodePluginSource,
|
|
11585
|
+
installs: "live Studio messages plugin"
|
|
11586
|
+
}
|
|
11587
|
+
};
|
|
11588
|
+
async function refreshAgentExtension(agent, filePath = AGENT_EXTENSIONS[agent].path()) {
|
|
11589
|
+
const existing = await exists(filePath) ? await fs4.readFile(filePath, "utf8") : null;
|
|
11590
|
+
if (existing === null)
|
|
11591
|
+
return "absent";
|
|
11592
|
+
if (!existing.startsWith(EXTENSION_HEADER))
|
|
11593
|
+
return "custom";
|
|
11594
|
+
const next = AGENT_EXTENSIONS[agent].build();
|
|
11595
|
+
if (existing === next)
|
|
11596
|
+
return "current";
|
|
11597
|
+
await fs4.writeFile(filePath, next, "utf8");
|
|
11598
|
+
return "updated";
|
|
11599
|
+
}
|
|
11600
|
+
async function upsertAgentExtension(agent, opts) {
|
|
11601
|
+
const spec = AGENT_EXTENSIONS[agent];
|
|
11602
|
+
const explicit = opts.targets?.has(agent) ?? false;
|
|
11603
|
+
if (opts.targets && !explicit)
|
|
11209
11604
|
return null;
|
|
11210
11605
|
const home = os3.homedir();
|
|
11211
|
-
const
|
|
11212
|
-
|
|
11213
|
-
const explicit = opts.targets?.has("pi") ?? false;
|
|
11214
|
-
if (!opts.all && !explicit && !await exists(piDir))
|
|
11606
|
+
const filePath = spec.path(home);
|
|
11607
|
+
if (!opts.all && !explicit && !await exists(spec.detectDir(home)))
|
|
11215
11608
|
return null;
|
|
11609
|
+
const result = (status, detail) => ({ id: `${agent}-extension`, label: spec.label, configPath: filePath, status, detail });
|
|
11216
11610
|
try {
|
|
11217
|
-
const next =
|
|
11218
|
-
const existing = await exists(
|
|
11219
|
-
if (existing === next)
|
|
11220
|
-
return {
|
|
11221
|
-
id: "pi-extension",
|
|
11222
|
-
label: "pi Truecolor UI",
|
|
11223
|
-
configPath: extPath,
|
|
11224
|
-
status: "unchanged",
|
|
11225
|
-
detail: "24-bit theme renderer & /tinypivot-theme already installed"
|
|
11226
|
-
};
|
|
11227
|
-
}
|
|
11611
|
+
const next = spec.build();
|
|
11612
|
+
const existing = await exists(filePath) ? await fs4.readFile(filePath, "utf8") : "";
|
|
11613
|
+
if (existing === next)
|
|
11614
|
+
return result("unchanged", `${spec.installs} already installed`);
|
|
11228
11615
|
if (!opts.dryRun) {
|
|
11229
|
-
await fs4.mkdir(path4.dirname(
|
|
11230
|
-
await fs4.writeFile(
|
|
11616
|
+
await fs4.mkdir(path4.dirname(filePath), { recursive: true });
|
|
11617
|
+
await fs4.writeFile(filePath, next, "utf8");
|
|
11231
11618
|
}
|
|
11232
|
-
return {
|
|
11233
|
-
id: "pi-extension",
|
|
11234
|
-
label: "pi Truecolor UI",
|
|
11235
|
-
configPath: extPath,
|
|
11236
|
-
status: "updated",
|
|
11237
|
-
detail: opts.dryRun ? "would install 24-bit theme renderer & /tinypivot-theme" : "installed 24-bit theme renderer & /tinypivot-theme"
|
|
11238
|
-
};
|
|
11619
|
+
return result("updated", `${opts.dryRun ? "would install" : "installed"} ${spec.installs}`);
|
|
11239
11620
|
} catch (err) {
|
|
11240
|
-
return
|
|
11241
|
-
id: "pi-extension",
|
|
11242
|
-
label: "pi Truecolor UI",
|
|
11243
|
-
configPath: extPath,
|
|
11244
|
-
status: "error",
|
|
11245
|
-
detail: err instanceof Error ? err.message : String(err)
|
|
11246
|
-
};
|
|
11621
|
+
return result("error", err instanceof Error ? err.message : String(err));
|
|
11247
11622
|
}
|
|
11248
11623
|
}
|
|
11249
11624
|
async function upsertAllAgentRules(opts) {
|
|
@@ -11252,9 +11627,10 @@ async function upsertAllAgentRules(opts) {
|
|
|
11252
11627
|
const candidates = await Promise.all([
|
|
11253
11628
|
upsertRuleFile("claude", "claude-rules", "Claude Code Rules", path4.join(home, ".claude"), path4.join(home, ".claude", "CLAUDE.md"), opts),
|
|
11254
11629
|
upsertRuleFile("pi", "pi-rules", "pi Rules", path4.join(home, ".pi"), path4.join(home, ".pi", "agent", "AGENTS.md"), opts, TINYPIVOT_PI_RULE_BLOCK),
|
|
11255
|
-
|
|
11630
|
+
upsertAgentExtension("pi", opts),
|
|
11256
11631
|
upsertRuleFile("codex", "codex-rules", "Codex Rules", path4.join(home, ".codex"), path4.join(home, ".codex", "AGENTS.md"), opts),
|
|
11257
|
-
upsertRuleFile("opencode", "opencode-rules", "OpenCode Rules", path4.join(xdg, "opencode"), path4.join(xdg, "opencode", "AGENTS.md"), opts)
|
|
11632
|
+
upsertRuleFile("opencode", "opencode-rules", "OpenCode Rules", path4.join(xdg, "opencode"), path4.join(xdg, "opencode", "AGENTS.md"), opts),
|
|
11633
|
+
upsertAgentExtension("opencode", opts)
|
|
11258
11634
|
]);
|
|
11259
11635
|
return candidates.filter((r) => r !== null);
|
|
11260
11636
|
}
|
|
@@ -11315,7 +11691,8 @@ TinyPivot MCP Installer (${opts.local ? `local: ${cliPath}` : `npx ${MCP_NPX_SPE
|
|
|
11315
11691
|
path4.join(home, ".pi", "agent", "mcp.json"),
|
|
11316
11692
|
path4.join(home, ".pi"),
|
|
11317
11693
|
opts,
|
|
11318
|
-
cliPath
|
|
11694
|
+
cliPath,
|
|
11695
|
+
PI_ENTRY_EXTRAS
|
|
11319
11696
|
),
|
|
11320
11697
|
await upsertOpenCodeJson(opts, cliPath),
|
|
11321
11698
|
await upsertCodexToml(opts, cliPath)
|
|
@@ -11681,60 +12058,6 @@ async function executeReadOnlyPostgresQuery(config, sql) {
|
|
|
11681
12058
|
import fs7 from "fs";
|
|
11682
12059
|
import path7 from "path";
|
|
11683
12060
|
|
|
11684
|
-
// src/agent-bridge.ts
|
|
11685
|
-
var AgentBridge = class {
|
|
11686
|
-
constructor(onChange) {
|
|
11687
|
-
this.onChange = onChange;
|
|
11688
|
-
}
|
|
11689
|
-
connectors = /* @__PURE__ */ new Set();
|
|
11690
|
-
waiters = /* @__PURE__ */ new Map();
|
|
11691
|
-
/** Adds a way to reach the agent; the returned function removes it. */
|
|
11692
|
-
connect(connector) {
|
|
11693
|
-
this.connectors.add(connector);
|
|
11694
|
-
this.onChange();
|
|
11695
|
-
return () => {
|
|
11696
|
-
if (this.connectors.delete(connector))
|
|
11697
|
-
this.onChange();
|
|
11698
|
-
};
|
|
11699
|
-
}
|
|
11700
|
-
/** Names of the ways that reach the agent right now. */
|
|
11701
|
-
live() {
|
|
11702
|
-
return [...this.connectors].map((connector) => connector.name);
|
|
11703
|
-
}
|
|
11704
|
-
/** Delivers into the conversation through the first connector that can. */
|
|
11705
|
-
push(note, text) {
|
|
11706
|
-
for (const connector of this.connectors) {
|
|
11707
|
-
if (connector.push?.(note, text))
|
|
11708
|
-
return connector.name;
|
|
11709
|
-
}
|
|
11710
|
-
return void 0;
|
|
11711
|
-
}
|
|
11712
|
-
completer() {
|
|
11713
|
-
return [...this.connectors].find((connector) => connector.complete)?.complete;
|
|
11714
|
-
}
|
|
11715
|
-
/** Resolves with the agent's answer to `id`, or undefined after `ms`. */
|
|
11716
|
-
waitForReply(id, ms) {
|
|
11717
|
-
return new Promise((resolve) => {
|
|
11718
|
-
const timer = setTimeout(() => {
|
|
11719
|
-
this.waiters.delete(id);
|
|
11720
|
-
resolve(void 0);
|
|
11721
|
-
}, ms);
|
|
11722
|
-
timer.unref?.();
|
|
11723
|
-
this.waiters.set(id, (text) => {
|
|
11724
|
-
clearTimeout(timer);
|
|
11725
|
-
this.waiters.delete(id);
|
|
11726
|
-
resolve(text);
|
|
11727
|
-
});
|
|
11728
|
-
});
|
|
11729
|
-
}
|
|
11730
|
-
/** Hands an answer to whoever waits for `re`, or to the oldest waiter when `re` is unknown. */
|
|
11731
|
-
answer(text, re) {
|
|
11732
|
-
const waiter = re && this.waiters.get(re) || this.waiters.values().next().value;
|
|
11733
|
-
waiter?.(text);
|
|
11734
|
-
return Boolean(waiter);
|
|
11735
|
-
}
|
|
11736
|
-
};
|
|
11737
|
-
|
|
11738
12061
|
// src/duckdb.ts
|
|
11739
12062
|
import { spawn } from "child_process";
|
|
11740
12063
|
import fs5 from "fs";
|
|
@@ -11995,7 +12318,6 @@ function formatHistoryList(entries) {
|
|
|
11995
12318
|
// src/studio.ts
|
|
11996
12319
|
var STEPS_IN_MEMORY = 300;
|
|
11997
12320
|
var HISTORY_IN_SNAPSHOT = 50;
|
|
11998
|
-
var ANSWER_WAIT_MS = 4 * 60 * 1e3;
|
|
11999
12321
|
var ATTACHMENT_MAX_CHARS = 6e3;
|
|
12000
12322
|
var AGENT_NAMES = {
|
|
12001
12323
|
"claude-code": "Claude Code",
|
|
@@ -12076,10 +12398,11 @@ var Studio = class {
|
|
|
12076
12398
|
pullsByDataset = /* @__PURE__ */ new Map();
|
|
12077
12399
|
listeners = /* @__PURE__ */ new Set();
|
|
12078
12400
|
changeQueued = false;
|
|
12079
|
-
/** Ways to reach the user's agent
|
|
12401
|
+
/** Ways to reach the user's agent live; without one, notes wait for its next TinyPivot reply. */
|
|
12080
12402
|
agent = new AgentBridge(() => this.changed());
|
|
12081
12403
|
agentName;
|
|
12082
12404
|
agentBusy = false;
|
|
12405
|
+
agentHint;
|
|
12083
12406
|
/** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
|
|
12084
12407
|
subscribe(listener) {
|
|
12085
12408
|
this.listeners.add(listener);
|
|
@@ -12105,9 +12428,14 @@ var Studio = class {
|
|
|
12105
12428
|
history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
|
|
12106
12429
|
historyEnabled: this.history.enabled,
|
|
12107
12430
|
loadedIds: this.store.listMetadata(sessionKey).map((meta) => meta.id),
|
|
12108
|
-
agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy }
|
|
12431
|
+
agent: { name: this.agentName ? agentLabel(this.agentName) : void 0, live: this.agent.live(), busy: this.agentBusy, ...this.agentHint ? { hint: this.agentHint } : {} }
|
|
12109
12432
|
};
|
|
12110
12433
|
}
|
|
12434
|
+
/** What would let this agent receive Studio messages live, shown while it cannot. */
|
|
12435
|
+
setAgentHint(hint) {
|
|
12436
|
+
this.agentHint = hint;
|
|
12437
|
+
this.changed();
|
|
12438
|
+
}
|
|
12111
12439
|
/** Whether the agent is in the middle of a turn, as its extension reports it. */
|
|
12112
12440
|
setAgentBusy(busy) {
|
|
12113
12441
|
if (busy === this.agentBusy)
|
|
@@ -12276,10 +12604,9 @@ var Studio = class {
|
|
|
12276
12604
|
addNote(text, options = {}) {
|
|
12277
12605
|
const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
|
|
12278
12606
|
const note = {
|
|
12279
|
-
id: nextId(
|
|
12607
|
+
id: nextId("note"),
|
|
12280
12608
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
12281
12609
|
text: text.trim(),
|
|
12282
|
-
kind: options.kind ?? "note",
|
|
12283
12610
|
delivery: "queued",
|
|
12284
12611
|
...options.stepId ? { stepId: options.stepId } : {},
|
|
12285
12612
|
...attachment ? { attachment } : {}
|
|
@@ -12288,7 +12615,7 @@ var Studio = class {
|
|
|
12288
12615
|
note.delivery = "live";
|
|
12289
12616
|
else
|
|
12290
12617
|
this.notes.push(note);
|
|
12291
|
-
this.record({ actor: "user", tool:
|
|
12618
|
+
this.record({ actor: "user", tool: "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
|
|
12292
12619
|
return note;
|
|
12293
12620
|
}
|
|
12294
12621
|
/**
|
|
@@ -12297,7 +12624,7 @@ var Studio = class {
|
|
|
12297
12624
|
*/
|
|
12298
12625
|
describeNote(note, { withSource = false } = {}) {
|
|
12299
12626
|
const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
|
|
12300
|
-
const source = withSource
|
|
12627
|
+
const source = withSource ? "Message from the user in TinyPivot Studio: " : "";
|
|
12301
12628
|
const lines = [`${source}${note.text}`];
|
|
12302
12629
|
if (step)
|
|
12303
12630
|
lines.push(`About the step "${step.why ?? step.view ?? step.tool}"${step.datasetId ? ` on dataset \`${step.datasetId}\`` : ""}${step.sql ? `, SQL: ${step.sql.replace(/\s+/g, " ")}` : ""}`);
|
|
@@ -12305,31 +12632,9 @@ var Studio = class {
|
|
|
12305
12632
|
lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
|
|
12306
12633
|
return lines.join("\n");
|
|
12307
12634
|
}
|
|
12308
|
-
/**
|
|
12309
|
-
|
|
12310
|
-
|
|
12311
|
-
*/
|
|
12312
|
-
async ask(question, options = {}) {
|
|
12313
|
-
const complete = this.agent.completer();
|
|
12314
|
-
if (complete) {
|
|
12315
|
-
this.record({ actor: "user", tool: "ask", why: question });
|
|
12316
|
-
const answer2 = await complete(options.turns?.length ? options.turns : [{ role: "user", content: question }]);
|
|
12317
|
-
this.reply(answer2);
|
|
12318
|
-
return answer2;
|
|
12319
|
-
}
|
|
12320
|
-
const note = this.addNote(question, { kind: "question", attachment: options.attachment });
|
|
12321
|
-
const name = agentLabel(this.agentName);
|
|
12322
|
-
if (note.delivery === "queued")
|
|
12323
|
-
return `${name} is not connected to the Studio live, so this question goes to it with its next TinyPivot reply. To ask now, use Copy as prompt in the Studio and paste it into ${name}.`;
|
|
12324
|
-
const answer = await this.agent.waitForReply(note.id, options.waitMs ?? ANSWER_WAIT_MS);
|
|
12325
|
-
return answer ?? `${name} is still working on this. Its answer will appear in the Studio trace.`;
|
|
12326
|
-
}
|
|
12327
|
-
/** The agent's answer to a Studio message: recorded in the trace and handed to whoever waits for it. */
|
|
12328
|
-
reply(text, re) {
|
|
12329
|
-
const answer = withoutCards(text);
|
|
12330
|
-
const step = this.record({ actor: "agent", tool: "reply", why: answer });
|
|
12331
|
-
this.agent.answer(answer, re);
|
|
12332
|
-
return step;
|
|
12635
|
+
/** The agent's answer to a Studio message, recorded in the trace where the user reads it. */
|
|
12636
|
+
reply(text) {
|
|
12637
|
+
return this.record({ actor: "agent", tool: "reply", why: withoutCards(text) });
|
|
12333
12638
|
}
|
|
12334
12639
|
/** Drops a queued note the user no longer wants sent. */
|
|
12335
12640
|
removeNote(id) {
|
|
@@ -12469,7 +12774,7 @@ import fsSync2 from "fs";
|
|
|
12469
12774
|
import os6 from "os";
|
|
12470
12775
|
import path8 from "path";
|
|
12471
12776
|
var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
|
|
12472
|
-
var PACKAGE_VERSION = "0.
|
|
12777
|
+
var PACKAGE_VERSION = "0.6.1";
|
|
12473
12778
|
function isTelemetryEnabled() {
|
|
12474
12779
|
if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
|
|
12475
12780
|
return false;
|
|
@@ -12549,14 +12854,14 @@ var APP_RESOURCE_URI = "ui://tinypivot/app.html";
|
|
|
12549
12854
|
var APP_MIME_TYPE = "text/html;profile=mcp-app";
|
|
12550
12855
|
var LOAD_DATA_ROW_GUIDE = 50;
|
|
12551
12856
|
function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
|
|
12552
|
-
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link
|
|
12857
|
+
const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link, except in pi, which already shows it. Where TinyPivot shows its view in the chat, never repeat the card." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
|
|
12553
12858
|
return [
|
|
12554
|
-
"
|
|
12859
|
+
"Show figures through TinyPivot: any ranking, breakdown, comparison, trend, chart or pivot, instead of Markdown tables, HTML, SVG or matplotlib, passing chartConfig or pivotConfig in the same call.",
|
|
12555
12860
|
`For files use load_file, so the rows stay out of your context; to filter, join or aggregate files first, use query with SQL. Use load_data only for rows you already have, up to about ${LOAD_DATA_ROW_GUIDE}; write larger sets to a file first. history lists and reopens earlier pulls.`,
|
|
12556
12861
|
"Totals are exact. Compute ratios, shares and rates as numerator / denominator, one row per chart point, before loading; never add up percentage columns, and do not use percentOfTotal for a share within a period.",
|
|
12557
12862
|
"Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
|
|
12558
12863
|
"Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
|
|
12559
|
-
...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply
|
|
12864
|
+
...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply.'] : [],
|
|
12560
12865
|
cards
|
|
12561
12866
|
].join(" ");
|
|
12562
12867
|
}
|
|
@@ -12643,6 +12948,14 @@ function normalizePivot(pivotConfig) {
|
|
|
12643
12948
|
valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
|
|
12644
12949
|
};
|
|
12645
12950
|
}
|
|
12951
|
+
function extensionHint(agent, status) {
|
|
12952
|
+
const name = agentLabel(agent);
|
|
12953
|
+
if (status === "updated")
|
|
12954
|
+
return `TinyPivot's ${name} extension was just updated. Restart ${name} to send messages live.`;
|
|
12955
|
+
if (status === "absent")
|
|
12956
|
+
return `Run npx @smallwebco/tinypivot-mcp@latest init --targets=${agent}, then restart ${name}, to send messages live.`;
|
|
12957
|
+
return void 0;
|
|
12958
|
+
}
|
|
12646
12959
|
var whyParam = z.string().max(240).optional();
|
|
12647
12960
|
var DUCKDB_WAIT_MS = 45e3;
|
|
12648
12961
|
function toCoreChartConfig(input) {
|
|
@@ -12731,11 +13044,21 @@ function isMcpLicenseKey(key) {
|
|
|
12731
13044
|
return false;
|
|
12732
13045
|
return key.startsWith("TP-MCPP-") || key.startsWith("TP-MCPT-");
|
|
12733
13046
|
}
|
|
13047
|
+
var LICENSE_KEY_ENV_VARS = ["TINYPIVOT_LICENSE_KEY", "CLAUDE_PLUGIN_OPTION_LICENSE_KEY"];
|
|
13048
|
+
function licenseKeyFromEnv() {
|
|
13049
|
+
for (const name of LICENSE_KEY_ENV_VARS) {
|
|
13050
|
+
const value2 = process.env[name]?.trim();
|
|
13051
|
+
if (value2 && !value2.startsWith("${"))
|
|
13052
|
+
return value2;
|
|
13053
|
+
}
|
|
13054
|
+
return void 0;
|
|
13055
|
+
}
|
|
12734
13056
|
function resolveLicenseKey(explicit) {
|
|
12735
13057
|
if (explicit?.trim())
|
|
12736
13058
|
return explicit.trim();
|
|
12737
|
-
|
|
12738
|
-
|
|
13059
|
+
const fromEnv = licenseKeyFromEnv();
|
|
13060
|
+
if (fromEnv)
|
|
13061
|
+
return fromEnv;
|
|
12739
13062
|
const here = path9.dirname(fileURLToPath2(import.meta.url));
|
|
12740
13063
|
const candidates = [
|
|
12741
13064
|
path9.resolve(here, "../.license"),
|
|
@@ -12769,7 +13092,6 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12769
13092
|
};
|
|
12770
13093
|
const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
|
|
12771
13094
|
const claudeChannel = options.claudeChannel ?? claudeChannelEnabled();
|
|
12772
|
-
const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
|
|
12773
13095
|
const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
|
|
12774
13096
|
connectionString: process.env.DATABASE_URL,
|
|
12775
13097
|
allowedTables: process.env.TINYPIVOT_ALLOWED_TABLES ? process.env.TINYPIVOT_ALLOWED_TABLES.split(",").map((s) => s.trim()).filter(Boolean) : void 0
|
|
@@ -12777,7 +13099,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12777
13099
|
const server = new McpServer(
|
|
12778
13100
|
{
|
|
12779
13101
|
name: "tinypivot",
|
|
12780
|
-
version: "0.
|
|
13102
|
+
version: "0.6.1"
|
|
12781
13103
|
},
|
|
12782
13104
|
{
|
|
12783
13105
|
capabilities: {
|
|
@@ -12789,6 +13111,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12789
13111
|
}
|
|
12790
13112
|
);
|
|
12791
13113
|
const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
|
|
13114
|
+
const cardFormat = () => ({ showBranding: !isPro2, reprintNote: reprintCards, shownInWidget: clientRendersWidget() });
|
|
12792
13115
|
const resolveCompanionUrlForTool = async (forceCompanion = false) => {
|
|
12793
13116
|
if (activeCompanionUrl)
|
|
12794
13117
|
return activeCompanionUrl;
|
|
@@ -12805,7 +13128,7 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12805
13128
|
};
|
|
12806
13129
|
const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
|
|
12807
13130
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
12808
|
-
const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
|
|
13131
|
+
const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat())}${note}`);
|
|
12809
13132
|
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12810
13133
|
recordTelemetry({
|
|
12811
13134
|
event: "tool_call",
|
|
@@ -12826,31 +13149,25 @@ function createTinyPivotMcpServer(options = {}) {
|
|
|
12826
13149
|
}
|
|
12827
13150
|
const withNotes = (text) => `${text}${studio.takeNotes()}`;
|
|
12828
13151
|
const connectAgent = () => {
|
|
12829
|
-
|
|
13152
|
+
const clientName = server.server.getClientVersion()?.name;
|
|
13153
|
+
studio.setAgentName(clientName);
|
|
13154
|
+
if (clientName === "pi" || clientName === "opencode")
|
|
13155
|
+
void refreshAgentExtension(clientName).then((status) => studio.setAgentHint(extensionHint(clientName, status))).catch(() => {
|
|
13156
|
+
});
|
|
13157
|
+
if (clientName === "claude-code" && !claudeChannel)
|
|
13158
|
+
studio.setAgentHint("Start Claude Code with --dangerously-load-development-channels server:tinypivot to send messages live.");
|
|
12830
13159
|
if (claudeChannel) {
|
|
12831
13160
|
studio.agent.connect({
|
|
12832
13161
|
name: "Claude Code channel",
|
|
12833
13162
|
push: (note, text) => {
|
|
12834
13163
|
const content = `${text}
|
|
12835
13164
|
|
|
12836
|
-
Answer with studio_reply
|
|
12837
|
-
server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id
|
|
13165
|
+
Answer with studio_reply so the user sees it in TinyPivot Studio.`;
|
|
13166
|
+
server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id } } }).catch((error) => console.error("[tinypivot-mcp] Could not reach the Claude Code channel:", error));
|
|
12838
13167
|
return true;
|
|
12839
13168
|
}
|
|
12840
13169
|
});
|
|
12841
13170
|
}
|
|
12842
|
-
if (server.server.getClientCapabilities()?.sampling) {
|
|
12843
|
-
studio.agent.connect({
|
|
12844
|
-
name: "sampling",
|
|
12845
|
-
complete: async (turns) => {
|
|
12846
|
-
const result = await server.server.createMessage({
|
|
12847
|
-
messages: turns.map((turn) => ({ role: turn.role, content: { type: "text", text: turn.content } })),
|
|
12848
|
-
maxTokens: 2e3
|
|
12849
|
-
});
|
|
12850
|
-
return result.content.type === "text" ? result.content.text : "";
|
|
12851
|
-
}
|
|
12852
|
-
});
|
|
12853
|
-
}
|
|
12854
13171
|
};
|
|
12855
13172
|
if (claudeChannel) {
|
|
12856
13173
|
server.registerTool(
|
|
@@ -12858,10 +13175,10 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
|
|
|
12858
13175
|
{
|
|
12859
13176
|
title: "Reply in TinyPivot Studio",
|
|
12860
13177
|
description: "Answer a message from TinyPivot Studio. The user reads it there.",
|
|
12861
|
-
inputSchema: { text: z.string().min(1).max(8e3)
|
|
13178
|
+
inputSchema: { text: z.string().min(1).max(8e3) }
|
|
12862
13179
|
},
|
|
12863
|
-
async ({ text
|
|
12864
|
-
studio.reply(text
|
|
13180
|
+
async ({ text }) => {
|
|
13181
|
+
studio.reply(text);
|
|
12865
13182
|
return { content: [{ type: "text", text: "Shown in TinyPivot Studio." }] };
|
|
12866
13183
|
}
|
|
12867
13184
|
);
|
|
@@ -12980,7 +13297,7 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
|
|
|
12980
13297
|
store.setActive(ds.id, sessionKey);
|
|
12981
13298
|
}
|
|
12982
13299
|
const liveCompanionUrl = await resolveCompanionUrlForTool(Boolean(openBrowser));
|
|
12983
|
-
const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat);
|
|
13300
|
+
const summaryText = formatDatasetSummary(ds, liveCompanionUrl, cardFormat());
|
|
12984
13301
|
const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
|
|
12985
13302
|
recordTelemetry({
|
|
12986
13303
|
event: "tool_call",
|
|
@@ -13116,7 +13433,7 @@ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Stu
|
|
|
13116
13433
|
chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
|
|
13117
13434
|
}, sessionKey);
|
|
13118
13435
|
const liveCompanionUrl = await resolveCompanionUrlForTool();
|
|
13119
|
-
const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat));
|
|
13436
|
+
const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat()));
|
|
13120
13437
|
studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
|
|
13121
13438
|
const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
|
|
13122
13439
|
const payload = buildAppPayload(ds, store, {
|