@smallwebco/tinypivot-mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5634,8 +5634,8 @@ var require_pgsql_ast_parser = __commonJS({
5634
5634
  }
5635
5635
  return x.path;
5636
5636
  } },
5637
- { "name": "path", "symbols": ["open_path"], "postprocess": ([path9]) => ({ closed: false, path: path9 }) },
5638
- { "name": "path", "symbols": ["closed_path"], "postprocess": ([path9]) => ({ closed: true, path: path9 }) },
5637
+ { "name": "path", "symbols": ["open_path"], "postprocess": ([path10]) => ({ closed: false, path: path10 }) },
5638
+ { "name": "path", "symbols": ["closed_path"], "postprocess": ([path10]) => ({ closed: true, path: path10 }) },
5639
5639
  { "name": "open_path$macrocall$2", "symbols": [geometric_lexer_1.lexerAny.has("lbracket") ? { type: "lbracket" } : lbracket] },
5640
5640
  { "name": "open_path$macrocall$3", "symbols": [geometric_lexer_1.lexerAny.has("rbracket") ? { type: "rbracket" } : rbracket] },
5641
5641
  { "name": "open_path$macrocall$1$macrocall$2", "symbols": ["point"] },
@@ -8252,6 +8252,9 @@ function tokensToUsd(tokens, ratePerMillion) {
8252
8252
  return Math.max(0, tokens) / 1e6 * ratePerMillion;
8253
8253
  }
8254
8254
 
8255
+ // src/studio-protocol.ts
8256
+ var STUDIO_HEADER = "x-tinypivot";
8257
+
8255
8258
  // src/store.ts
8256
8259
  import fsSync from "fs";
8257
8260
  import fs from "fs/promises";
@@ -9444,7 +9447,7 @@ function formatDatasetSummary(dataset, companionUrl, options = {}) {
9444
9447
  }
9445
9448
  parts.push("", formatColumnNotes(dataset.columns));
9446
9449
  if (companionUrl && !chartBlock)
9447
- parts.push(`Data IDE: ${companionUrl}`);
9450
+ parts.push(`Studio: ${companionUrl}`);
9448
9451
  return parts.join("\n");
9449
9452
  }
9450
9453
  function formatPivotSummary(dataset, config, companionUrl, options = {}) {
@@ -10099,15 +10102,129 @@ import fs3 from "fs/promises";
10099
10102
  import http from "http";
10100
10103
  import path3 from "path";
10101
10104
 
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
+
10102
10164
  // src/limits.ts
10103
10165
  var INTERACTIVE_ROW_LIMIT = 1e5;
10104
10166
  var ROW_PAGE_SIZE = 25e3;
10105
10167
 
10106
10168
  // src/companion.ts
10169
+ function isAllowedRequest(request, port) {
10170
+ const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`];
10171
+ if (!request.host || !allowedHosts.includes(request.host))
10172
+ return false;
10173
+ if (request.method === "GET" || request.method === "HEAD")
10174
+ return true;
10175
+ if (request.origin)
10176
+ return allowedHosts.some((host) => request.origin === `http://${host}`);
10177
+ return request.studioHeader === "1";
10178
+ }
10179
+ function parseAttachment(value2) {
10180
+ const { label, text } = value2 ?? {};
10181
+ return typeof label === "string" && typeof text === "string" && text.trim() ? { label, text } : void 0;
10182
+ }
10183
+ function openAgentStream(studio, agentName, req, res) {
10184
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
10185
+ res.write(": connected\n\n");
10186
+ const disconnect = studio.agent.connect({
10187
+ name: agentName,
10188
+ push: (note, text) => {
10189
+ if (res.writableEnded)
10190
+ return false;
10191
+ res.write(`event: message
10192
+ data: ${JSON.stringify({ id: note.id, kind: note.kind, text })}
10193
+
10194
+ `);
10195
+ return true;
10196
+ }
10197
+ });
10198
+ const keepAlive = setInterval(() => res.write(": ping\n\n"), 25e3);
10199
+ keepAlive.unref();
10200
+ req.on("close", () => {
10201
+ clearInterval(keepAlive);
10202
+ disconnect();
10203
+ });
10204
+ }
10205
+ function sendJson(res, status, body) {
10206
+ res.writeHead(status, { "Content-Type": "application/json" });
10207
+ res.end(JSON.stringify(body));
10208
+ }
10209
+ function errorMessage(error) {
10210
+ return error instanceof Error ? error.message : String(error);
10211
+ }
10212
+ var MAX_SQL_CHARS = 2e4;
10213
+ var MAX_NOTE_CHARS = 2e3;
10214
+ var MAX_BODY_BYTES = 256 * 1024;
10107
10215
  function readJsonBody(req) {
10108
10216
  return new Promise((resolve) => {
10109
10217
  const chunks = [];
10110
- req.on("data", (c) => chunks.push(c));
10218
+ let size = 0;
10219
+ req.on("data", (c) => {
10220
+ size += c.length;
10221
+ if (size > MAX_BODY_BYTES) {
10222
+ resolve({});
10223
+ req.destroy();
10224
+ return;
10225
+ }
10226
+ chunks.push(c);
10227
+ });
10111
10228
  req.on("end", () => {
10112
10229
  try {
10113
10230
  const text = Buffer.concat(chunks).toString("utf8").trim();
@@ -10159,11 +10276,8 @@ function buildFullCompanionPayload(store, datasetId, opts) {
10159
10276
  }
10160
10277
  async function startCompanionServer(options) {
10161
10278
  const sseClients = /* @__PURE__ */ new Set();
10162
- const broadcastUpdate = () => {
10163
- const payload = buildFullCompanionPayload(options.store, void 0, options);
10164
- if (!payload)
10165
- return;
10166
- const frame = `event: update
10279
+ const send = (event, payload) => {
10280
+ const frame = `event: ${event}
10167
10281
  data: ${JSON.stringify(payload)}
10168
10282
 
10169
10283
  `;
@@ -10175,10 +10289,91 @@ data: ${JSON.stringify(payload)}
10175
10289
  }
10176
10290
  }
10177
10291
  };
10292
+ const broadcastUpdate = () => {
10293
+ const payload = buildFullCompanionPayload(options.store, void 0, options);
10294
+ if (payload)
10295
+ send("update", payload);
10296
+ };
10297
+ const { studio } = options;
10298
+ studio?.subscribe(() => send("studio", studio.snapshot()));
10299
+ const handleStudioPost = async (pathname, body, res) => {
10300
+ if (!studio)
10301
+ return sendJson(res, 404, { error: "Studio is not available." });
10302
+ if (pathname === "/api/studio/query") {
10303
+ const sql = typeof body.sql === "string" ? body.sql.trim() : "";
10304
+ if (!sql || sql.length > MAX_SQL_CHARS)
10305
+ return sendJson(res, 400, { error: "Send one SELECT statement." });
10306
+ const name = typeof body.name === "string" && body.name.trim() ? body.name.trim().slice(0, 120) : void 0;
10307
+ try {
10308
+ const viewFromStepId = typeof body.fromStepId === "string" ? body.fromStepId : void 0;
10309
+ const { dataset, truncated } = await studio.runQuery({ sql, name, actor: "user", viewFromStepId });
10310
+ broadcastUpdate();
10311
+ return sendJson(res, 200, { datasetId: dataset.id, rows: dataset.rows.length, truncated });
10312
+ } catch (error) {
10313
+ return sendJson(res, 400, { error: errorMessage(error) });
10314
+ }
10315
+ }
10316
+ if (pathname === "/api/studio/note") {
10317
+ const text = typeof body.text === "string" ? body.text.trim() : "";
10318
+ if (!text || text.length > MAX_NOTE_CHARS)
10319
+ return sendJson(res, 400, { error: `Write a note of up to ${MAX_NOTE_CHARS.toLocaleString("en-US")} characters.` });
10320
+ const note = studio.addNote(text, {
10321
+ stepId: typeof body.stepId === "string" ? body.stepId : void 0,
10322
+ attachment: parseAttachment(body.attachment)
10323
+ });
10324
+ return sendJson(res, 200, { note });
10325
+ }
10326
+ if (pathname === "/api/studio/note/delete") {
10327
+ return sendJson(res, 200, { removed: typeof body.id === "string" && studio.removeNote(body.id) });
10328
+ }
10329
+ if (pathname === "/api/studio/reply") {
10330
+ const text = typeof body.text === "string" ? body.text.trim() : "";
10331
+ if (!text)
10332
+ return sendJson(res, 400, { error: "Send the reply text." });
10333
+ studio.reply(text.slice(0, 2e4), typeof body.re === "string" ? body.re : void 0);
10334
+ return sendJson(res, 200, { ok: true });
10335
+ }
10336
+ if (pathname === "/api/studio/agent-status") {
10337
+ studio.setAgentBusy(body.busy === true);
10338
+ return sendJson(res, 200, { ok: true });
10339
+ }
10340
+ if (pathname === "/api/studio/analyst") {
10341
+ const result = await handleAnalystAction(studio, body);
10342
+ return sendJson(res, result.status, result.body);
10343
+ }
10344
+ if (pathname === "/api/studio/show") {
10345
+ try {
10346
+ const dataset = await studio.showStep(String(body.stepId ?? ""));
10347
+ broadcastUpdate();
10348
+ return sendJson(res, 200, { datasetId: dataset.id });
10349
+ } catch (error) {
10350
+ return sendJson(res, 400, { error: errorMessage(error) });
10351
+ }
10352
+ }
10353
+ if (pathname === "/api/studio/open") {
10354
+ try {
10355
+ const dataset = await studio.reopen(String(body.id ?? ""), { actor: "user" });
10356
+ broadcastUpdate();
10357
+ return sendJson(res, 200, { datasetId: dataset.id });
10358
+ } catch (error) {
10359
+ return sendJson(res, 400, { error: errorMessage(error) });
10360
+ }
10361
+ }
10362
+ return sendJson(res, 404, { error: "Not found" });
10363
+ };
10178
10364
  const server = http.createServer(async (req, res) => {
10179
10365
  const urlObj = new URL(req.url || "/", "http://127.0.0.1");
10180
10366
  const pathname = urlObj.pathname;
10181
10367
  res.setHeader("Cache-Control", "no-store");
10368
+ const port = server.address().port;
10369
+ const allowed = isAllowedRequest({
10370
+ method: req.method,
10371
+ host: req.headers.host,
10372
+ origin: req.headers.origin,
10373
+ studioHeader: req.headers[STUDIO_HEADER]
10374
+ }, port);
10375
+ if (!allowed)
10376
+ return sendJson(res, 403, { error: "Forbidden" });
10182
10377
  if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
10183
10378
  const html = await options.loadHtml();
10184
10379
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -10192,20 +10387,37 @@ data: ${JSON.stringify(payload)}
10192
10387
  "Connection": "keep-alive"
10193
10388
  });
10194
10389
  res.write("retry: 2000\n\n");
10390
+ if (studio)
10391
+ res.write(`event: studio
10392
+ data: ${JSON.stringify(studio.snapshot())}
10393
+
10394
+ `);
10195
10395
  sseClients.add(res);
10196
10396
  req.on("close", () => sseClients.delete(res));
10197
10397
  return;
10198
10398
  }
10399
+ if (req.method === "GET" && pathname === "/api/studio/agent-stream") {
10400
+ if (!studio || req.headers[STUDIO_HEADER] !== "1")
10401
+ return sendJson(res, 403, { error: "Forbidden" });
10402
+ const agentName = (urlObj.searchParams.get("agent") || "agent").slice(0, 40);
10403
+ openAgentStream(studio, agentName, req, res);
10404
+ return;
10405
+ }
10406
+ if (req.method === "GET" && pathname === "/api/studio") {
10407
+ return studio ? sendJson(res, 200, studio.snapshot()) : sendJson(res, 404, { error: "Studio is not available." });
10408
+ }
10409
+ if (req.method === "POST" && pathname.startsWith("/api/studio/")) {
10410
+ await handleStudioPost(pathname, await readJsonBody(req), res);
10411
+ return;
10412
+ }
10199
10413
  if (req.method === "GET" && pathname === "/api/state") {
10200
10414
  const dsId = urlObj.searchParams.get("datasetId") ?? void 0;
10201
10415
  const payload = buildFullCompanionPayload(options.store, dsId, options);
10202
10416
  if (!payload) {
10203
- res.writeHead(404, { "Content-Type": "application/json" });
10204
- res.end(JSON.stringify({ error: "Dataset not found" }));
10417
+ sendJson(res, 404, { error: "Dataset not found" });
10205
10418
  return;
10206
10419
  }
10207
- res.writeHead(200, { "Content-Type": "application/json" });
10208
- res.end(JSON.stringify(payload));
10420
+ sendJson(res, 200, payload);
10209
10421
  return;
10210
10422
  }
10211
10423
  if (req.method === "POST" && pathname === "/api/model") {
@@ -10216,8 +10428,7 @@ data: ${JSON.stringify(payload)}
10216
10428
  typeof body.customRatePerMillion === "number" ? body.customRatePerMillion : void 0
10217
10429
  );
10218
10430
  }
10219
- res.writeHead(200, { "Content-Type": "application/json" });
10220
- res.end(JSON.stringify({ session: options.store.getSessionSavings() }));
10431
+ sendJson(res, 200, { session: options.store.getSessionSavings() });
10221
10432
  return;
10222
10433
  }
10223
10434
  if (req.method === "POST" && pathname === "/api/theme") {
@@ -10231,20 +10442,17 @@ data: ${JSON.stringify(payload)}
10231
10442
  options.store.setVisualTheme(requested);
10232
10443
  }
10233
10444
  }
10234
- res.writeHead(200, { "Content-Type": "application/json" });
10235
- res.end(JSON.stringify({ chartTheme: isPro2 ? options.store.getVisualTheme() : "code" }));
10445
+ sendJson(res, 200, { chartTheme: isPro2 ? options.store.getVisualTheme() : "code" });
10236
10446
  return;
10237
10447
  }
10238
10448
  if (req.method === "POST" && pathname === "/api/local-action") {
10239
10449
  const body = await readJsonBody(req);
10240
10450
  const dsId = typeof body.datasetId === "string" ? body.datasetId : void 0;
10241
10451
  const result = options.store.recordLocalAction(dsId);
10242
- res.writeHead(200, { "Content-Type": "application/json" });
10243
- res.end(JSON.stringify(result));
10452
+ sendJson(res, 200, result);
10244
10453
  return;
10245
10454
  }
10246
- res.writeHead(404, { "Content-Type": "application/json" });
10247
- res.end(JSON.stringify({ error: "Not found" }));
10455
+ sendJson(res, 404, { error: "Not found" });
10248
10456
  });
10249
10457
  await new Promise((resolve, reject) => {
10250
10458
  server.once("error", reject);
@@ -10264,6 +10472,7 @@ data: ${JSON.stringify(payload)}
10264
10472
  url,
10265
10473
  port: address.port,
10266
10474
  broadcastUpdate,
10475
+ clientCount: () => sseClients.size,
10267
10476
  close: () => {
10268
10477
  if (closePromise)
10269
10478
  return closePromise;
@@ -10366,7 +10575,7 @@ async function syncCompanionTheme(themeId: string): Promise<void> {
10366
10575
  if (!parsed.url) return;
10367
10576
  await fetch(\`\${parsed.url}/api/theme\`, {
10368
10577
  method: "POST",
10369
- headers: { "Content-Type": "application/json" },
10578
+ headers: { "Content-Type": "application/json", "x-tinypivot": "1" },
10370
10579
  body: JSON.stringify({ theme: themeId }),
10371
10580
  });
10372
10581
  } catch {
@@ -10483,8 +10692,113 @@ interface TinyPivotCardEntryData {
10483
10692
  themeId: string;
10484
10693
  }
10485
10694
 
10695
+ // TinyPivot Studio bridge: messages the user sends from the Studio arrive here, go into this
10696
+ // session as a turn, and the agent's final answer goes back to the Studio.
10697
+ // The Studio link TinyPivot puts in its replies ("Studio: \u2026" or a card's "Live: \u2026").
10698
+ const STUDIO_LINK = /(?:Studio|Live): (http:[/][/]127[.]0[.]0[.]1:[0-9]+)/;
10699
+ const STUDIO_HEADERS = { "Content-Type": "application/json", "x-tinypivot": "1" };
10700
+
10701
+ function lastAssistantText(messages: unknown): string {
10702
+ if (!Array.isArray(messages)) return "";
10703
+ for (let i = messages.length - 1; i >= 0; i--) {
10704
+ const message = messages[i] as { role?: string; content?: unknown };
10705
+ if (message?.role !== "assistant") continue;
10706
+ if (typeof message.content === "string") return message.content.trim();
10707
+ if (!Array.isArray(message.content)) return "";
10708
+ return message.content
10709
+ .map(part => (part && typeof part === "object" && (part as { type?: string }).type === "text" ? String((part as { text?: unknown }).text ?? "") : ""))
10710
+ .join("\\n")
10711
+ .trim();
10712
+ }
10713
+ return "";
10714
+ }
10715
+
10716
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10717
+ function createStudioBridge(pi: any) {
10718
+ let studioUrl: string | undefined;
10719
+ let stream: AbortController | undefined;
10720
+ let awaiting: string | undefined;
10721
+
10722
+ function handleFrame(frame: string): void {
10723
+ if (!frame.startsWith("event: message")) return;
10724
+ const data = frame.split("\\n").find(line => line.startsWith("data: "));
10725
+ if (!data) return;
10726
+ const message = JSON.parse(data.slice(6)) as { id: string; text: string };
10727
+ awaiting = message.id;
10728
+ pi.sendMessage(
10729
+ { customType: "tinypivot-studio", content: message.text, display: true },
10730
+ { triggerTurn: true, deliverAs: "steer" },
10731
+ );
10732
+ }
10733
+
10734
+ async function listen(url: string, signal: AbortSignal): Promise<void> {
10735
+ let delay = 1000;
10736
+ while (!signal.aborted) {
10737
+ try {
10738
+ const res = await fetch(url + "/api/studio/agent-stream?agent=pi", { headers: STUDIO_HEADERS, signal });
10739
+ if (!res.ok || !res.body) throw new Error("Studio stream " + res.status);
10740
+ delay = 1000;
10741
+ const reader = res.body.getReader();
10742
+ const decoder = new TextDecoder();
10743
+ let buffer = "";
10744
+ for (;;) {
10745
+ const { value, done } = await reader.read();
10746
+ if (done) break;
10747
+ buffer += decoder.decode(value, { stream: true });
10748
+ let end = buffer.indexOf("\\n\\n");
10749
+ while (end >= 0) {
10750
+ handleFrame(buffer.slice(0, end));
10751
+ buffer = buffer.slice(end + 2);
10752
+ end = buffer.indexOf("\\n\\n");
10753
+ }
10754
+ }
10755
+ } catch {
10756
+ // The Studio restarted or closed; try again after a pause.
10757
+ }
10758
+ if (signal.aborted) return;
10759
+ await new Promise(resolve => setTimeout(resolve, delay));
10760
+ delay = Math.min(delay * 2, 30000);
10761
+ }
10762
+ }
10763
+
10764
+ return {
10765
+ /** Starts listening to the Studio named in a TinyPivot tool reply. */
10766
+ noticeToolText(text: string): void {
10767
+ const url = STUDIO_LINK.exec(text)?.[1];
10768
+ if (!url || url === studioUrl) return;
10769
+ stream?.abort();
10770
+ studioUrl = url;
10771
+ stream = new AbortController();
10772
+ void listen(url, stream.signal);
10773
+ void this.status(true);
10774
+ },
10775
+ /** Tells the Studio whether pi is working, so it can show progress. */
10776
+ async status(busy: boolean): Promise<void> {
10777
+ if (!studioUrl) return;
10778
+ await fetch(studioUrl + "/api/studio/agent-status", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ busy }) }).catch(() => {});
10779
+ },
10780
+ async onAgentEnd(messages: unknown): Promise<void> {
10781
+ if (!awaiting || !studioUrl) return;
10782
+ const re = awaiting;
10783
+ awaiting = undefined;
10784
+ const text = lastAssistantText(messages);
10785
+ if (!text) return;
10786
+ await fetch(studioUrl + "/api/studio/reply", { method: "POST", headers: STUDIO_HEADERS, body: JSON.stringify({ re, text }) }).catch(() => {});
10787
+ },
10788
+ stop(): void {
10789
+ stream?.abort();
10790
+ stream = undefined;
10791
+ },
10792
+ };
10793
+ }
10794
+
10486
10795
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
10487
10796
  export default function (pi: any) {
10797
+ const studio = createStudioBridge(pi);
10798
+ pi.on("agent_start", () => studio.status(true));
10799
+ pi.on("agent_end", (event: { messages?: unknown }) => studio.onAgentEnd(event?.messages));
10800
+ pi.on("agent_settled", () => studio.status(false));
10801
+ pi.on("session_shutdown", () => studio.stop());
10488
10802
  if (typeof pi.registerEntryRenderer === "function") {
10489
10803
  pi.registerEntryRenderer("tinypivot-card", (entry: { data?: TinyPivotCardEntryData }) => {
10490
10804
  const data = entry?.data;
@@ -10505,11 +10819,12 @@ export default function (pi: any) {
10505
10819
  }
10506
10820
 
10507
10821
  pi.on("tool_execution_end", (event: { toolName?: string; result?: unknown; isError?: boolean }, ctx: { hasUI?: boolean }) => {
10508
- if (ctx?.hasUI === false || event?.isError) return;
10509
- if (!event?.toolName || !isTinyPivotTool(event.toolName)) return;
10510
-
10822
+ if (event?.isError) return;
10511
10823
  const text = extractResultText(event.result);
10512
10824
  if (!text) return;
10825
+ // TinyPivot calls made through codemode arrive under another tool's name, so look at the text.
10826
+ studio.noticeToolText(text);
10827
+ if (!event?.toolName || !isTinyPivotTool(event.toolName) || ctx?.hasUI === false) return;
10513
10828
  const cards = extractTinyPivotCards(text);
10514
10829
  if (cards.length === 0) return;
10515
10830
 
@@ -10521,7 +10836,7 @@ export default function (pi: any) {
10521
10836
 
10522
10837
  if (typeof pi.registerCommand === "function") {
10523
10838
  pi.registerCommand("tinypivot-theme", {
10524
- description: "Switch TinyPivot visual theme (all 10 palettes, synced with Companion IDE)",
10839
+ description: "Switch TinyPivot visual theme (all 10 palettes, synced with Studio)",
10525
10840
  handler: async (args: string, ctx: { ui?: { select?: (t: string, o: string[]) => Promise<string | undefined>; notify?: (m: string, t?: string) => void } }) => {
10526
10841
  const active = readActiveThemeId();
10527
10842
  let chosen = args?.trim().toLowerCase();
@@ -10566,11 +10881,11 @@ var RULE_HEADING = "## Charts & pivot tables (TinyPivot MCP)";
10566
10881
  var RULE_USE = "Use the `tinypivot` MCP server for charts, pivot tables and data exploration instead of drawing them yourself.";
10567
10882
  var TINYPIVOT_CLAUDE_RULE_BLOCK = `${RULE_START}
10568
10883
  ${RULE_HEADING}
10569
- ${RULE_USE} In a terminal, show its \`text\` card verbatim with the Data IDE link.
10884
+ ${RULE_USE} In a terminal, show its \`text\` card verbatim with the Studio link.
10570
10885
  ${RULE_END}`;
10571
10886
  var TINYPIVOT_PI_RULE_BLOCK = `${RULE_START}
10572
10887
  ${RULE_HEADING}
10573
- ${RULE_USE} The TinyPivot pi extension already shows each card, so reply with the takeaways and the Data IDE link. \`/tinypivot-theme\` switches themes.
10888
+ ${RULE_USE} The TinyPivot pi extension already shows each card, so reply with the takeaways and the Studio link. \`/tinypivot-theme\` switches themes.
10574
10889
  ${RULE_END}`;
10575
10890
  function upsertTinyPivotRuleBlock(existing, block = TINYPIVOT_CLAUDE_RULE_BLOCK) {
10576
10891
  if (RULE_TEST_RE.test(existing)) {
@@ -11362,13 +11677,63 @@ async function executeReadOnlyPostgresQuery(config, sql) {
11362
11677
  }
11363
11678
  }
11364
11679
 
11365
- // src/server.ts
11366
- import fsSync3 from "fs";
11367
- import fs7 from "fs/promises";
11368
- import path8 from "path";
11369
- import { fileURLToPath as fileURLToPath2 } from "url";
11370
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
11371
- import { z } from "zod";
11680
+ // src/studio.ts
11681
+ import fs7 from "fs";
11682
+ import path7 from "path";
11683
+
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
+ };
11372
11737
 
11373
11738
  // src/duckdb.ts
11374
11739
  import { spawn } from "child_process";
@@ -11627,6 +11992,415 @@ function formatHistoryList(entries) {
11627
11992
  return [`Saved pulls (newest first). Reopen one with history({ open: id }):`, ...lines].join("\n");
11628
11993
  }
11629
11994
 
11995
+ // src/studio.ts
11996
+ var STEPS_IN_MEMORY = 300;
11997
+ var HISTORY_IN_SNAPSHOT = 50;
11998
+ var ANSWER_WAIT_MS = 4 * 60 * 1e3;
11999
+ var ATTACHMENT_MAX_CHARS = 6e3;
12000
+ var AGENT_NAMES = {
12001
+ "claude-code": "Claude Code",
12002
+ "claude-ai": "Claude Desktop",
12003
+ "pi": "pi",
12004
+ "opencode": "OpenCode",
12005
+ "cursor-vscode": "Cursor",
12006
+ "codex-mcp-client": "Codex",
12007
+ "antigravity": "Antigravity",
12008
+ "Visual Studio Code": "VS Code"
12009
+ };
12010
+ function agentLabel(clientName) {
12011
+ return clientName && (AGENT_NAMES[clientName] ?? clientName) || "your agent";
12012
+ }
12013
+ var TRACE_FILE_MAX_BYTES = 5 * 1024 * 1024;
12014
+ function describeView(dataset) {
12015
+ const pivot = dataset.pivotConfig;
12016
+ if (dataset.viewMode === "pivot" && pivot?.valueFields?.length) {
12017
+ const values = pivot.valueFields.map((v) => `${v.aggregation}(${v.field})`).join(", ");
12018
+ const rows = pivot.rowFields?.length ? ` \xB7 rows ${pivot.rowFields.join(", ")}` : "";
12019
+ const columns = pivot.columnFields?.length ? ` \xB7 columns ${pivot.columnFields.join(", ")}` : "";
12020
+ return `pivot: ${values}${rows}${columns}`;
12021
+ }
12022
+ const chart = dataset.chartConfig;
12023
+ if (dataset.viewMode === "chart" && chart?.xAxis && chart.yAxis) {
12024
+ const series = chart.seriesField ? `, split by ${chart.seriesField.field}` : "";
12025
+ return `${chart.type ?? "bar"} chart: ${chart.yAxis.aggregation ?? "sum"}(${chart.yAxis.field}) by ${chart.xAxis.field}${series}`;
12026
+ }
12027
+ return "table";
12028
+ }
12029
+ function whereSql(where) {
12030
+ return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
12031
+ }
12032
+ function fileStepSql(file, where) {
12033
+ return `SELECT *
12034
+ FROM ${quoteLiteral(file)}${where?.length ? `
12035
+ WHERE ${whereSql(where)}` : ""}`;
12036
+ }
12037
+ function viewFields(dataset) {
12038
+ const chart = dataset.chartConfig;
12039
+ const pivot = dataset.pivotConfig;
12040
+ return [
12041
+ chart?.xAxis?.field,
12042
+ chart?.yAxis?.field,
12043
+ chart?.seriesField?.field,
12044
+ ...pivot?.rowFields ?? [],
12045
+ ...pivot?.columnFields ?? [],
12046
+ ...(pivot?.valueFields ?? []).map((value2) => value2.field)
12047
+ ].filter((field) => Boolean(field));
12048
+ }
12049
+ function historyTableExpression(entry, rowsPath) {
12050
+ if (entry.kind === "file") {
12051
+ const file = quoteLiteral(entry.source);
12052
+ return entry.where?.length ? `(SELECT * FROM ${file} WHERE ${whereSql(entry.where)})` : file;
12053
+ }
12054
+ return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
12055
+ }
12056
+ function withoutCards(text) {
12057
+ const stripped = text.replace(/```text\n[\s\S]*?```\n?/g, (block) => /[╭╰│┤├]/.test(block) ? "" : block);
12058
+ return stripped.replace(/\n{3,}/g, "\n\n").trim() || text.trim();
12059
+ }
12060
+ var sequence = 0;
12061
+ function nextId(prefix) {
12062
+ sequence += 1;
12063
+ return `${prefix}-${Date.now().toString(36)}-${sequence.toString(36)}`;
12064
+ }
12065
+ var Studio = class {
12066
+ constructor(store, options = {}) {
12067
+ this.store = store;
12068
+ this.history = options.history ?? new HistoryStore();
12069
+ this.duck = options.duck ?? new DuckDbRunner();
12070
+ this.steps = this.readTraceFile();
12071
+ }
12072
+ history;
12073
+ duck;
12074
+ steps = [];
12075
+ notes = [];
12076
+ pullsByDataset = /* @__PURE__ */ new Map();
12077
+ listeners = /* @__PURE__ */ new Set();
12078
+ changeQueued = false;
12079
+ /** Ways to reach the user's agent: live channels, sampling, or nothing (queued notes). */
12080
+ agent = new AgentBridge(() => this.changed());
12081
+ agentName;
12082
+ agentBusy = false;
12083
+ /** Calls `listener` (once per tick at most) whenever the trace or the notes change. */
12084
+ subscribe(listener) {
12085
+ this.listeners.add(listener);
12086
+ return () => this.listeners.delete(listener);
12087
+ }
12088
+ changed() {
12089
+ if (this.changeQueued)
12090
+ return;
12091
+ this.changeQueued = true;
12092
+ queueMicrotask(() => {
12093
+ this.changeQueued = false;
12094
+ for (const listener of this.listeners)
12095
+ listener();
12096
+ });
12097
+ }
12098
+ snapshot(sessionKey = DEFAULT_SESSION_KEY) {
12099
+ return {
12100
+ steps: this.steps.map((step) => ({
12101
+ ...step,
12102
+ editableSql: step.sql ?? (step.file ? fileStepSql(step.file, step.where) : void 0)
12103
+ })),
12104
+ notes: this.pendingNotes(),
12105
+ history: this.history.enabled ? this.history.list(HISTORY_IN_SNAPSHOT) : [],
12106
+ historyEnabled: this.history.enabled,
12107
+ 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 }
12109
+ };
12110
+ }
12111
+ /** Whether the agent is in the middle of a turn, as its extension reports it. */
12112
+ setAgentBusy(busy) {
12113
+ if (busy === this.agentBusy)
12114
+ return;
12115
+ this.agentBusy = busy;
12116
+ this.changed();
12117
+ }
12118
+ /** The MCP client's name, e.g. `claude-code`, shown in the Studio. */
12119
+ setAgentName(name) {
12120
+ this.agentName = name;
12121
+ this.changed();
12122
+ }
12123
+ get traceFile() {
12124
+ return path7.join(this.history.dir, "trace.jsonl");
12125
+ }
12126
+ readTraceFile() {
12127
+ if (!this.history.enabled || !fs7.existsSync(this.traceFile))
12128
+ return [];
12129
+ return fs7.readFileSync(this.traceFile, "utf8").split("\n").filter(Boolean).slice(-STEPS_IN_MEMORY).flatMap((line) => {
12130
+ try {
12131
+ return [JSON.parse(line)];
12132
+ } catch {
12133
+ return [];
12134
+ }
12135
+ });
12136
+ }
12137
+ appendToTraceFile(step) {
12138
+ if (!this.history.enabled)
12139
+ return;
12140
+ try {
12141
+ fs7.mkdirSync(this.history.dir, { recursive: true });
12142
+ fs7.appendFileSync(this.traceFile, `${JSON.stringify(step)}
12143
+ `);
12144
+ if (fs7.statSync(this.traceFile).size > TRACE_FILE_MAX_BYTES)
12145
+ fs7.writeFileSync(this.traceFile, `${this.steps.map((s) => JSON.stringify(s)).join("\n")}
12146
+ `);
12147
+ } catch (error) {
12148
+ console.error(`[tinypivot-mcp] Could not save the Studio trace: ${error instanceof Error ? error.message : String(error)}`);
12149
+ }
12150
+ }
12151
+ /** Adds a step to the trace and returns it. */
12152
+ record(step) {
12153
+ const full = { id: nextId("step"), at: (/* @__PURE__ */ new Date()).toISOString(), ...step };
12154
+ this.steps.push(full);
12155
+ if (this.steps.length > STEPS_IN_MEMORY)
12156
+ this.steps = this.steps.slice(-STEPS_IN_MEMORY);
12157
+ this.appendToTraceFile(full);
12158
+ this.changed();
12159
+ return full;
12160
+ }
12161
+ /** Records a step about a dataset, filling in its name, size, view and saved pull. */
12162
+ recordDatasetStep(dataset, step) {
12163
+ return this.record({
12164
+ ...step,
12165
+ datasetId: dataset.id,
12166
+ datasetName: dataset.name,
12167
+ rows: dataset.rows.length,
12168
+ view: describeView(dataset),
12169
+ viewMode: dataset.viewMode,
12170
+ ...dataset.chartConfig ? { chartConfig: structuredClone(dataset.chartConfig) } : {},
12171
+ ...dataset.pivotConfig ? { pivotConfig: structuredClone(dataset.pivotConfig) } : {},
12172
+ historyId: this.pullsByDataset.get(dataset.id)?.id
12173
+ });
12174
+ }
12175
+ /**
12176
+ * Shows a step's dataset as it was right after the step, reopening it from history when it is
12177
+ * no longer loaded. Looking is not a step, so nothing is recorded.
12178
+ */
12179
+ async showStep(stepId, sessionKey = DEFAULT_SESSION_KEY) {
12180
+ const step = this.steps.find((s) => s.id === stepId);
12181
+ if (!step?.datasetId)
12182
+ throw new Error("That step has no data to show.");
12183
+ let dataset = this.store.get(step.datasetId, sessionKey);
12184
+ if (!dataset) {
12185
+ if (!step.historyId)
12186
+ throw new Error("That data is no longer loaded and was not saved to history.");
12187
+ dataset = await this.reopen(step.historyId, { actor: "user", sessionKey, record: false });
12188
+ }
12189
+ return this.store.updateView(dataset.id, {
12190
+ ...step.viewMode ? { viewMode: step.viewMode } : {},
12191
+ ...step.chartConfig ? { chartConfig: { ...step.chartConfig, seriesField: step.chartConfig.seriesField } } : {},
12192
+ ...step.pivotConfig ? { pivotConfig: step.pivotConfig } : {}
12193
+ }, sessionKey) ?? dataset;
12194
+ }
12195
+ recentSteps(limit = STEPS_IN_MEMORY) {
12196
+ return this.steps.slice(-limit);
12197
+ }
12198
+ /** Saves a pull to history and remembers which entry backs the dataset. */
12199
+ remember(dataset, input) {
12200
+ const entry = this.history.record(dataset, input);
12201
+ if (entry)
12202
+ this.pullsByDataset.set(dataset.id, entry);
12203
+ return entry;
12204
+ }
12205
+ /** Loaded datasets as tables SQL can read, named by dataset id. */
12206
+ queryViews(sessionKey = DEFAULT_SESSION_KEY) {
12207
+ return this.store.listMetadata(sessionKey).flatMap((meta) => {
12208
+ const entry = this.pullsByDataset.get(meta.id);
12209
+ const from = entry && historyTableExpression(entry, this.history.rowsPath(entry));
12210
+ return from ? [{ name: meta.id, from }] : [];
12211
+ });
12212
+ }
12213
+ /** Runs read-only SQL, loads the result as a dataset, saves it and records the step. */
12214
+ async runQuery(input) {
12215
+ const sessionKey = input.sessionKey ?? DEFAULT_SESSION_KEY;
12216
+ const result = await this.duck.run(input.sql, this.queryViews(sessionKey));
12217
+ const dataset = this.store.register({
12218
+ name: input.name ?? (input.actor === "user" ? "Your query" : "SQL query"),
12219
+ source: input.sql,
12220
+ ingestionMode: "direct",
12221
+ rows: result.rows,
12222
+ viewMode: input.viewMode,
12223
+ pivotConfig: input.pivotConfig,
12224
+ chartConfig: input.chartConfig,
12225
+ sessionKey,
12226
+ keepExisting: input.keepExisting ?? true
12227
+ });
12228
+ const shown = this.keepViewOf(input.viewFromStepId, dataset, sessionKey) ?? dataset;
12229
+ this.remember(shown, { kind: "query", source: input.sql });
12230
+ this.recordDatasetStep(shown, { actor: input.actor, tool: "query", why: input.why, sql: input.sql });
12231
+ return { dataset: shown, truncated: result.truncated };
12232
+ }
12233
+ /** Gives `dataset` the view of the step's dataset when every field that view uses is in the result. */
12234
+ keepViewOf(stepId, dataset, sessionKey) {
12235
+ const step = stepId ? this.steps.find((s) => s.id === stepId) : void 0;
12236
+ const source = step?.datasetId ? this.store.get(step.datasetId, sessionKey) : void 0;
12237
+ if (!source)
12238
+ return void 0;
12239
+ const columns = new Set(dataset.columns.map((column) => column.name));
12240
+ const fields = viewFields(source);
12241
+ if (fields.length === 0 || !fields.every((field) => columns.has(field)))
12242
+ return void 0;
12243
+ return this.store.updateView(dataset.id, {
12244
+ viewMode: source.viewMode,
12245
+ // Set the series explicitly, so one picked for the new result does not survive the merge.
12246
+ ...source.chartConfig ? { chartConfig: { ...source.chartConfig, seriesField: source.chartConfig.seriesField } } : {},
12247
+ ...source.pivotConfig ? { pivotConfig: source.pivotConfig } : {}
12248
+ }, sessionKey);
12249
+ }
12250
+ /** Reopens a saved pull without re-querying, and records the step. */
12251
+ async reopen(id, options) {
12252
+ const entry = this.history.get(id);
12253
+ if (!entry)
12254
+ throw new Error(`No saved pull "${id}".`);
12255
+ const sessionKey = options.sessionKey ?? DEFAULT_SESSION_KEY;
12256
+ const dataset = entry.kind === "file" ? await this.store.loadFromFile(entry.source, entry.name, { sessionKey, keepExisting: true, where: entry.where }) : this.store.register({ name: entry.name, source: entry.source, ingestionMode: "direct", rows: this.history.readRows(entry), sessionKey, keepExisting: true });
12257
+ this.store.updateView(dataset.id, {
12258
+ ...entry.chartConfig ? { chartConfig: entry.chartConfig } : {},
12259
+ ...entry.pivotConfig ? { pivotConfig: entry.pivotConfig } : {}
12260
+ }, sessionKey);
12261
+ this.pullsByDataset.set(dataset.id, entry);
12262
+ if (options.record === false)
12263
+ return dataset;
12264
+ this.recordDatasetStep(dataset, {
12265
+ actor: options.actor,
12266
+ tool: "history",
12267
+ why: options.why,
12268
+ ...entry.kind === "file" ? { file: entry.source, where: entry.where } : { sql: entry.kind === "data" ? void 0 : entry.source }
12269
+ });
12270
+ return dataset;
12271
+ }
12272
+ /**
12273
+ * Sends the user's message to the agent: straight into its conversation when a live connector
12274
+ * takes it, otherwise queued for its next TinyPivot reply.
12275
+ */
12276
+ addNote(text, options = {}) {
12277
+ const attachment = options.attachment && { label: options.attachment.label.slice(0, 120), text: options.attachment.text.slice(0, ATTACHMENT_MAX_CHARS) };
12278
+ const note = {
12279
+ id: nextId(options.kind === "question" ? "ask" : "note"),
12280
+ at: (/* @__PURE__ */ new Date()).toISOString(),
12281
+ text: text.trim(),
12282
+ kind: options.kind ?? "note",
12283
+ delivery: "queued",
12284
+ ...options.stepId ? { stepId: options.stepId } : {},
12285
+ ...attachment ? { attachment } : {}
12286
+ };
12287
+ if (this.agent.push(note, this.describeNote(note, { withSource: true })))
12288
+ note.delivery = "live";
12289
+ else
12290
+ this.notes.push(note);
12291
+ this.record({ actor: "user", tool: note.kind === "question" ? "ask" : "note", why: note.text, ...attachment ? { view: `with ${attachment.label}` } : {} });
12292
+ return note;
12293
+ }
12294
+ /**
12295
+ * How a message reads to the agent: the text, the step it is about, and any attached data.
12296
+ * `withSource` says where it came from, for messages that arrive on their own in the conversation.
12297
+ */
12298
+ describeNote(note, { withSource = false } = {}) {
12299
+ const step = note.stepId ? this.steps.find((s) => s.id === note.stepId) : void 0;
12300
+ const source = withSource || note.kind === "question" ? `${note.kind === "question" ? "Question" : "Message"} from the user in TinyPivot Studio: ` : "";
12301
+ const lines = [`${source}${note.text}`];
12302
+ if (step)
12303
+ 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, " ")}` : ""}`);
12304
+ if (note.attachment)
12305
+ lines.push(`Attached (${note.attachment.label}):`, note.attachment.text);
12306
+ return lines.join("\n");
12307
+ }
12308
+ /**
12309
+ * Answers an AI Analyst question with the user's own agent: its model directly when the host
12310
+ * offers sampling, otherwise through its conversation, waiting for the reply.
12311
+ */
12312
+ async ask(question, options = {}) {
12313
+ const complete = this.agent.completer();
12314
+ if (complete) {
12315
+ this.record({ actor: "user", tool: "ask", why: question });
12316
+ const answer2 = await complete(options.turns?.length ? options.turns : [{ role: "user", content: question }]);
12317
+ this.reply(answer2);
12318
+ return answer2;
12319
+ }
12320
+ const note = this.addNote(question, { kind: "question", attachment: options.attachment });
12321
+ const name = agentLabel(this.agentName);
12322
+ if (note.delivery === "queued")
12323
+ return `${name} is not connected to the Studio live, so this question goes to it with its next TinyPivot reply. To ask now, use Copy as prompt in the Studio and paste it into ${name}.`;
12324
+ const answer = await this.agent.waitForReply(note.id, options.waitMs ?? ANSWER_WAIT_MS);
12325
+ return answer ?? `${name} is still working on this. Its answer will appear in the Studio trace.`;
12326
+ }
12327
+ /** The agent's answer to a Studio message: recorded in the trace and handed to whoever waits for it. */
12328
+ reply(text, re) {
12329
+ const answer = withoutCards(text);
12330
+ const step = this.record({ actor: "agent", tool: "reply", why: answer });
12331
+ this.agent.answer(answer, re);
12332
+ return step;
12333
+ }
12334
+ /** Drops a queued note the user no longer wants sent. */
12335
+ removeNote(id) {
12336
+ const before = this.notes.length;
12337
+ this.notes = this.notes.filter((note) => note.id !== id);
12338
+ if (this.notes.length !== before)
12339
+ this.changed();
12340
+ return this.notes.length !== before;
12341
+ }
12342
+ pendingNotes() {
12343
+ return [...this.notes];
12344
+ }
12345
+ /** The queued notes as text for the agent, emptying the queue. Empty when there are none. */
12346
+ takeNotes() {
12347
+ if (this.notes.length === 0)
12348
+ return "";
12349
+ const lines = this.notes.map((note) => `- ${this.describeNote(note).replace(/\n/g, "\n ")}`);
12350
+ this.notes = [];
12351
+ this.changed();
12352
+ return `
12353
+
12354
+ **Notes from the user in TinyPivot Studio** (act on these):
12355
+ ${lines.join("\n")}`;
12356
+ }
12357
+ };
12358
+
12359
+ // src/server.ts
12360
+ import fsSync3 from "fs";
12361
+ import fs8 from "fs/promises";
12362
+ import path9 from "path";
12363
+ import { fileURLToPath as fileURLToPath2 } from "url";
12364
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12365
+ import { z } from "zod";
12366
+
12367
+ // src/claude-channel.ts
12368
+ import { execFileSync } from "child_process";
12369
+ import process2 from "process";
12370
+ var CHANNEL_NOTIFICATION = "notifications/claude/channel";
12371
+ var CHANNEL_FLAGS = ["--channels", "--dangerously-load-development-channels"];
12372
+ var ANCESTORS_TO_CHECK = 5;
12373
+ function commandEnablesChannel(command, serverName) {
12374
+ if (!/\bclaude\b/.test(command) || !CHANNEL_FLAGS.some((flag) => command.includes(flag)))
12375
+ return false;
12376
+ return new RegExp(`(?:server:)?${serverName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).test(command);
12377
+ }
12378
+ function processInfo(pid) {
12379
+ try {
12380
+ const out = execFileSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 2e3 }).trim();
12381
+ const match = /^(\d+)\s+(.*)$/s.exec(out);
12382
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
12383
+ } catch {
12384
+ return void 0;
12385
+ }
12386
+ }
12387
+ function claudeChannelEnabled(serverName = "tinypivot", env = process2.env) {
12388
+ if (env.TINYPIVOT_CLAUDE_CHANNEL === "1")
12389
+ return true;
12390
+ if (env.TINYPIVOT_CLAUDE_CHANNEL === "0" || process2.platform === "win32")
12391
+ return false;
12392
+ let pid = process2.ppid;
12393
+ for (let i = 0; i < ANCESTORS_TO_CHECK && pid > 1; i++) {
12394
+ const info = processInfo(pid);
12395
+ if (!info)
12396
+ return false;
12397
+ if (commandEnablesChannel(info.command, serverName))
12398
+ return true;
12399
+ pid = info.ppid;
12400
+ }
12401
+ return false;
12402
+ }
12403
+
11630
12404
  // src/profile.ts
11631
12405
  var TOP_VALUES = 3;
11632
12406
  function compactNumber(value2) {
@@ -11693,9 +12467,9 @@ function formatProfile(dataset) {
11693
12467
  import crypto from "crypto";
11694
12468
  import fsSync2 from "fs";
11695
12469
  import os6 from "os";
11696
- import path7 from "path";
12470
+ import path8 from "path";
11697
12471
  var DEFAULT_TELEMETRY_URL = "https://tiny-pivot.com/api/telemetry";
11698
- var PACKAGE_VERSION = "0.3.0";
12472
+ var PACKAGE_VERSION = "0.5.0";
11699
12473
  function isTelemetryEnabled() {
11700
12474
  if (process.env.TINYPIVOT_TELEMETRY === "0" || process.env.TINYPIVOT_TELEMETRY === "false")
11701
12475
  return false;
@@ -11715,8 +12489,8 @@ function bucketRowCount(rows) {
11715
12489
  return "10k+";
11716
12490
  }
11717
12491
  function getPreferencesPath2() {
11718
- const base = process.env.XDG_CONFIG_HOME?.trim() || path7.join(os6.homedir(), ".config");
11719
- return path7.join(base, "tinypivot", "preferences.json");
12492
+ const base = process.env.XDG_CONFIG_HOME?.trim() || path8.join(os6.homedir(), ".config");
12493
+ return path8.join(base, "tinypivot", "preferences.json");
11720
12494
  }
11721
12495
  var cachedAnonId = null;
11722
12496
  function getAnonymousId() {
@@ -11734,7 +12508,7 @@ function getAnonymousId() {
11734
12508
  const fresh = crypto.randomUUID();
11735
12509
  cachedAnonId = fresh;
11736
12510
  try {
11737
- fsSync2.mkdirSync(path7.dirname(prefPath), { recursive: true });
12511
+ fsSync2.mkdirSync(path8.dirname(prefPath), { recursive: true });
11738
12512
  let existing = {};
11739
12513
  try {
11740
12514
  existing = JSON.parse(fsSync2.readFileSync(prefPath, "utf8"));
@@ -11774,13 +12548,15 @@ function recordTelemetry(ev) {
11774
12548
  var APP_RESOURCE_URI = "ui://tinypivot/app.html";
11775
12549
  var APP_MIME_TYPE = "text/html;profile=mcp-app";
11776
12550
  var LOAD_DATA_ROW_GUIDE = 50;
11777
- function buildInstructions({ reprintCards = true } = {}) {
11778
- const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Data IDE link in your reply, except in pi, whose TinyPivot extension already displays it." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Data IDE link.";
12551
+ function buildInstructions({ reprintCards = true, claudeChannel = false } = {}) {
12552
+ const cards = reprintCards ? "In a terminal, show the returned ```text card verbatim with the Studio link in your reply, except in pi, whose TinyPivot extension already displays it." : "Do not reprint the ```text card: the user sees it in TinyPivot. Reply with the takeaways and the Studio link.";
11779
12553
  return [
11780
12554
  "Use TinyPivot for charts, pivot tables, period comparisons and tabular exploration instead of drawing them yourself (HTML, SVG, matplotlib, Markdown tables), passing chartConfig or pivotConfig in the same call.",
11781
12555
  `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.`,
11782
12556
  "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.",
11783
12557
  "Use keepExisting: true only to compare datasets in one conversation; clear_datasets resets.",
12558
+ "Pass why on every data call: one short sentence the user sees in the TinyPivot Studio trace. Replies may end with notes the user wrote in the Studio; act on them.",
12559
+ ...claudeChannel ? ['Messages from TinyPivot Studio arrive as <channel source="tinypivot"> events: do what they ask, then answer with studio_reply, passing the message id as re.'] : [],
11784
12560
  cards
11785
12561
  ].join(" ");
11786
12562
  }
@@ -11867,17 +12643,8 @@ function normalizePivot(pivotConfig) {
11867
12643
  valueFields: pivotConfig.valueFields.map((v) => ({ field: v.field, aggregation: v.aggregation }))
11868
12644
  };
11869
12645
  }
12646
+ var whyParam = z.string().max(240).optional();
11870
12647
  var DUCKDB_WAIT_MS = 45e3;
11871
- function whereSql(where) {
11872
- return where.map((filter) => `CAST(${quoteIdentifier(filter.field)} AS VARCHAR) IN (${filter.equals.map((value2) => quoteLiteral(String(value2))).join(", ")})`).join(" AND ");
11873
- }
11874
- function historyTableExpression(entry, rowsPath) {
11875
- if (entry.kind === "file") {
11876
- const file = quoteLiteral(entry.source);
11877
- return entry.where?.length ? `(SELECT * FROM ${file} WHERE ${whereSql(entry.where)})` : file;
11878
- }
11879
- return rowsPath ? `read_json_auto(${quoteLiteral(rowsPath)})` : void 0;
11880
- }
11881
12648
  function toCoreChartConfig(input) {
11882
12649
  return {
11883
12650
  type: input.type,
@@ -11939,16 +12706,16 @@ function buildAppPayload(dataset, store, options) {
11939
12706
  }
11940
12707
  async function loadAppHtml(customPath) {
11941
12708
  const envPath = process.env.TINYPIVOT_MCP_APP_HTML;
11942
- const here = path8.dirname(fileURLToPath2(import.meta.url));
12709
+ const here = path9.dirname(fileURLToPath2(import.meta.url));
11943
12710
  const candidates = [
11944
12711
  customPath,
11945
12712
  envPath,
11946
- path8.resolve(here, "app/index.html"),
11947
- path8.resolve(here, "../dist/app/index.html")
12713
+ path9.resolve(here, "app/index.html"),
12714
+ path9.resolve(here, "../dist/app/index.html")
11948
12715
  ].filter((p) => Boolean(p));
11949
12716
  for (const candidate of candidates) {
11950
12717
  try {
11951
- const html = await fs7.readFile(candidate, "utf8");
12718
+ const html = await fs8.readFile(candidate, "utf8");
11952
12719
  if (html.trim().length > 0)
11953
12720
  return html;
11954
12721
  } catch {
@@ -11969,10 +12736,10 @@ function resolveLicenseKey(explicit) {
11969
12736
  return explicit.trim();
11970
12737
  if (process.env.TINYPIVOT_LICENSE_KEY?.trim())
11971
12738
  return process.env.TINYPIVOT_LICENSE_KEY.trim();
11972
- const here = path8.dirname(fileURLToPath2(import.meta.url));
12739
+ const here = path9.dirname(fileURLToPath2(import.meta.url));
11973
12740
  const candidates = [
11974
- path8.resolve(here, "../.license"),
11975
- path8.resolve(here, ".license")
12741
+ path9.resolve(here, "../.license"),
12742
+ path9.resolve(here, ".license")
11976
12743
  ];
11977
12744
  for (const file of candidates) {
11978
12745
  try {
@@ -12001,6 +12768,7 @@ function createTinyPivotMcpServer(options = {}) {
12001
12768
  options.onStateChanged?.();
12002
12769
  };
12003
12770
  const reprintCards = options.reprintCards ?? process.env.TINYPIVOT_REPRINT_CARDS !== "0";
12771
+ const claudeChannel = options.claudeChannel ?? claudeChannelEnabled();
12004
12772
  const cardFormat = { showBranding: !isPro2, reprintNote: reprintCards };
12005
12773
  const postgresConfig = options.postgres ?? (process.env.DATABASE_URL ? {
12006
12774
  connectionString: process.env.DATABASE_URL,
@@ -12009,14 +12777,15 @@ function createTinyPivotMcpServer(options = {}) {
12009
12777
  const server = new McpServer(
12010
12778
  {
12011
12779
  name: "tinypivot",
12012
- version: "0.3.0"
12780
+ version: "0.5.0"
12013
12781
  },
12014
12782
  {
12015
12783
  capabilities: {
12016
12784
  resources: {},
12017
- tools: {}
12785
+ tools: {},
12786
+ ...claudeChannel ? { experimental: { "claude/channel": {} } } : {}
12018
12787
  },
12019
- instructions: buildInstructions({ reprintCards })
12788
+ instructions: buildInstructions({ reprintCards, claudeChannel })
12020
12789
  }
12021
12790
  );
12022
12791
  const clientRendersWidget = () => clientSupportsMcpAppsUi(server.server.getClientCapabilities());
@@ -12036,7 +12805,7 @@ function createTinyPivotMcpServer(options = {}) {
12036
12805
  };
12037
12806
  const replyWithDataset = async (ds, sessionKey, tool, note = "") => {
12038
12807
  const liveCompanionUrl = await resolveCompanionUrlForTool();
12039
- const summaryText = `${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`;
12808
+ const summaryText = withNotes(`${formatDatasetSummary(ds, liveCompanionUrl, cardFormat)}${note}`);
12040
12809
  const payload = buildAppPayload(ds, store, { licenseKey, demoToken, summaryText, sessionKey });
12041
12810
  recordTelemetry({
12042
12811
  event: "tool_call",
@@ -12049,24 +12818,54 @@ function createTinyPivotMcpServer(options = {}) {
12049
12818
  notifyCompanion();
12050
12819
  return dataToolResult(summaryText, payload);
12051
12820
  };
12052
- const history = options.history ?? new HistoryStore();
12821
+ const studio = options.studio ?? new Studio(store);
12053
12822
  try {
12054
- history.prune();
12823
+ studio.history.prune();
12055
12824
  } catch (error) {
12056
12825
  console.error(`[tinypivot-mcp] Could not prune history: ${error instanceof Error ? error.message : String(error)}`);
12057
12826
  }
12058
- const pullsByDataset = /* @__PURE__ */ new Map();
12059
- const remember = (ds, input) => {
12060
- const entry = history.record(ds, input);
12061
- if (entry)
12062
- pullsByDataset.set(ds.id, entry);
12827
+ const withNotes = (text) => `${text}${studio.takeNotes()}`;
12828
+ const connectAgent = () => {
12829
+ studio.setAgentName(server.server.getClientVersion()?.name);
12830
+ if (claudeChannel) {
12831
+ studio.agent.connect({
12832
+ name: "Claude Code channel",
12833
+ push: (note, text) => {
12834
+ const content = `${text}
12835
+
12836
+ Answer with studio_reply (re: "${note.id}") so the user sees it in TinyPivot Studio.`;
12837
+ server.server.notification({ method: CHANNEL_NOTIFICATION, params: { content, meta: { message_id: note.id, kind: note.kind } } }).catch((error) => console.error("[tinypivot-mcp] Could not reach the Claude Code channel:", error));
12838
+ return true;
12839
+ }
12840
+ });
12841
+ }
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
+ }
12063
12854
  };
12064
- const duck = options.duckdb ?? new DuckDbRunner();
12065
- const queryViews = (sessionKey) => store.listMetadata(sessionKey).flatMap((meta) => {
12066
- const entry = pullsByDataset.get(meta.id);
12067
- const from = entry && historyTableExpression(entry, history.rowsPath(entry));
12068
- return from ? [{ name: meta.id, from }] : [];
12069
- });
12855
+ if (claudeChannel) {
12856
+ server.registerTool(
12857
+ "studio_reply",
12858
+ {
12859
+ title: "Reply in TinyPivot Studio",
12860
+ description: "Answer a message from TinyPivot Studio. The user reads it there.",
12861
+ inputSchema: { text: z.string().min(1).max(8e3), re: z.string().max(80).optional() }
12862
+ },
12863
+ async ({ text, re }) => {
12864
+ studio.reply(text, re);
12865
+ return { content: [{ type: "text", text: "Shown in TinyPivot Studio." }] };
12866
+ }
12867
+ );
12868
+ }
12070
12869
  const widgetOnlyTools = [];
12071
12870
  const widgetOnly = (tool) => {
12072
12871
  widgetOnlyTools.push(tool);
@@ -12092,6 +12891,11 @@ function createTinyPivotMcpServer(options = {}) {
12092
12891
  if (!clientRendersWidget())
12093
12892
  widgetOnlyTools.forEach((tool) => tool.disable());
12094
12893
  detectedClientName = server.server.getClientVersion()?.name;
12894
+ try {
12895
+ connectAgent();
12896
+ } catch (error) {
12897
+ console.error("[tinypivot-mcp] Could not connect the Studio to the agent:", error);
12898
+ }
12095
12899
  recordTelemetry({
12096
12900
  event: "server_start",
12097
12901
  client: detectedClientName,
@@ -12153,11 +12957,11 @@ function createTinyPivotMcpServer(options = {}) {
12153
12957
  "open_tinypivot",
12154
12958
  {
12155
12959
  title: "Open TinyPivot",
12156
- description: "Open the TinyPivot Data IDE (grid, pivot, chart). Shows sample data when nothing is loaded.",
12960
+ description: "Open the TinyPivot Studio (grid, pivot, chart). Shows sample data when nothing is loaded.",
12157
12961
  inputSchema: {
12158
12962
  datasetId: z.string().optional(),
12159
12963
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
12160
- openBrowser: z.boolean().optional().describe("Also start the localhost Data IDE in hosts with an inline widget")
12964
+ openBrowser: z.boolean().optional().describe("Also start the localhost Studio in hosts with an inline widget")
12161
12965
  },
12162
12966
  _meta: PANE_UI_META
12163
12967
  },
@@ -12198,6 +13002,7 @@ function createTinyPivotMcpServer(options = {}) {
12198
13002
  inputSchema: {
12199
13003
  filePath: z.string(),
12200
13004
  name: z.string().optional(),
13005
+ why: whyParam,
12201
13006
  where: z.array(rowFilterSchema).optional().describe('Keep only matching rows, e.g. [{"field":"year","equals":[2026]}]'),
12202
13007
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
12203
13008
  pivotConfig: pivotConfigSchema.optional(),
@@ -12206,11 +13011,11 @@ function createTinyPivotMcpServer(options = {}) {
12206
13011
  },
12207
13012
  _meta: INLINE_UI_META
12208
13013
  },
12209
- async ({ filePath, name, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13014
+ async ({ filePath, name, why, where, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
12210
13015
  try {
12211
13016
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
12212
13017
  const ds = await store.loadFromFile(filePath, name, { sessionKey, keepExisting: shouldKeep, where });
12213
- remember(ds, { kind: "file", source: ds.source, where });
13018
+ studio.remember(ds, { kind: "file", source: ds.source, where });
12214
13019
  const explicitChart = chartConfig ? toCoreChartConfig(chartConfig) : void 0;
12215
13020
  if (pivotConfig) {
12216
13021
  const normalizedPivot = normalizePivot(pivotConfig);
@@ -12225,6 +13030,7 @@ function createTinyPivotMcpServer(options = {}) {
12225
13030
  ...explicitChart ? { chartConfig: explicitChart } : {}
12226
13031
  }, sessionKey);
12227
13032
  }
13033
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_file", why, file: ds.source, where });
12228
13034
  return replyWithDataset(ds, sessionKey, "load_file");
12229
13035
  } catch (err) {
12230
13036
  return {
@@ -12241,6 +13047,7 @@ function createTinyPivotMcpServer(options = {}) {
12241
13047
  description: "Chart or pivot rows you already have, up to about 50. Every row you pass is billed as output; for more, write a file and use load_file.",
12242
13048
  inputSchema: {
12243
13049
  name: z.string(),
13050
+ why: whyParam,
12244
13051
  rows: z.array(z.record(z.string(), z.unknown())),
12245
13052
  source: z.string().optional(),
12246
13053
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
@@ -12250,7 +13057,7 @@ function createTinyPivotMcpServer(options = {}) {
12250
13057
  },
12251
13058
  _meta: INLINE_UI_META
12252
13059
  },
12253
- async ({ name, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13060
+ async ({ name, why, rows, source, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
12254
13061
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
12255
13062
  const ds = store.register({
12256
13063
  name,
@@ -12263,7 +13070,8 @@ function createTinyPivotMcpServer(options = {}) {
12263
13070
  sessionKey,
12264
13071
  keepExisting: shouldKeep
12265
13072
  });
12266
- remember(ds, { kind: "data", source: source ?? "inline JSON" });
13073
+ studio.remember(ds, { kind: "data", source: source ?? "inline JSON" });
13074
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "load_data", why });
12267
13075
  return replyWithDataset(ds, sessionKey, "load_data");
12268
13076
  }
12269
13077
  );
@@ -12277,12 +13085,13 @@ function createTinyPivotMcpServer(options = {}) {
12277
13085
  rowFields: z.array(z.string()).default([]),
12278
13086
  columnFields: z.array(z.string()).default([]),
12279
13087
  valueFields: z.array(pivotValueSchema).min(1),
13088
+ why: whyParam,
12280
13089
  showRowTotals: z.boolean().default(true),
12281
13090
  showColumnTotals: z.boolean().default(true)
12282
13091
  },
12283
13092
  _meta: INLINE_UI_META
12284
13093
  },
12285
- async ({ datasetId, rowFields, columnFields, valueFields, showRowTotals, showColumnTotals }, extra) => {
13094
+ async ({ datasetId, rowFields, columnFields, valueFields, why, showRowTotals, showColumnTotals }, extra) => {
12286
13095
  const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
12287
13096
  const ds = store.get(datasetId, sessionKey);
12288
13097
  if (!ds) {
@@ -12307,7 +13116,8 @@ function createTinyPivotMcpServer(options = {}) {
12307
13116
  chartConfig: chartConfigFromPivot(fullPivotConfig, ds.name) ?? ds.chartConfig
12308
13117
  }, sessionKey);
12309
13118
  const liveCompanionUrl = await resolveCompanionUrlForTool();
12310
- const summary = formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat);
13119
+ const summary = withNotes(formatPivotSummary(ds, fullPivotConfig, liveCompanionUrl, cardFormat));
13120
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_pivot", why });
12311
13121
  const pivotTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summary, "utf8") / 4));
12312
13122
  const payload = buildAppPayload(ds, store, {
12313
13123
  licenseKey,
@@ -12341,11 +13151,12 @@ function createTinyPivotMcpServer(options = {}) {
12341
13151
  aggregation: z.enum(CHART_AGG_VALUES).default("sum"),
12342
13152
  seriesField: z.string().optional(),
12343
13153
  title: z.string().optional(),
13154
+ why: whyParam,
12344
13155
  chartTheme: z.enum(VISUAL_THEME_VALUES).optional()
12345
13156
  },
12346
13157
  _meta: INLINE_UI_META
12347
13158
  },
12348
- async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, chartTheme }, extra) => {
13159
+ async ({ datasetId, type, xAxisField, yAxisField, aggregation, seriesField, title, why, chartTheme }, extra) => {
12349
13160
  const sessionKey = extractSessionKey(extra) ?? DEFAULT_SESSION_KEY;
12350
13161
  const ds = store.get(datasetId, sessionKey);
12351
13162
  if (!ds) {
@@ -12381,8 +13192,9 @@ function createTinyPivotMcpServer(options = {}) {
12381
13192
  if (asciiChart)
12382
13193
  summaryParts.push("", asciiChart);
12383
13194
  if (liveCompanionUrl)
12384
- summaryParts.push(`Data IDE: ${liveCompanionUrl}`);
12385
- const summaryText = summaryParts.join("\n");
13195
+ summaryParts.push(`Studio: ${liveCompanionUrl}`);
13196
+ const summaryText = withNotes(summaryParts.join("\n"));
13197
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "configure_chart", why });
12386
13198
  const chartTokensSaved = Math.max(0, ds.estimatedDatasetTokens - Math.round(Buffer.byteLength(summaryText, "utf8") / 4));
12387
13199
  const payload = buildAppPayload(ds, store, {
12388
13200
  licenseKey,
@@ -12411,6 +13223,7 @@ function createTinyPivotMcpServer(options = {}) {
12411
13223
  description: "Run a read-only SELECT on the configured Postgres database and chart the result.",
12412
13224
  inputSchema: {
12413
13225
  sql: z.string(),
13226
+ why: whyParam,
12414
13227
  name: z.string().optional(),
12415
13228
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
12416
13229
  pivotConfig: pivotConfigSchema.optional(),
@@ -12418,7 +13231,7 @@ function createTinyPivotMcpServer(options = {}) {
12418
13231
  },
12419
13232
  _meta: INLINE_UI_META
12420
13233
  },
12421
- async ({ sql, name, viewMode, pivotConfig, keepExisting }, extra) => {
13234
+ async ({ sql, why, name, viewMode, pivotConfig, keepExisting }, extra) => {
12422
13235
  if (!isPro2) {
12423
13236
  return {
12424
13237
  isError: true,
@@ -12441,7 +13254,8 @@ function createTinyPivotMcpServer(options = {}) {
12441
13254
  sessionKey,
12442
13255
  keepExisting: shouldKeep
12443
13256
  });
12444
- remember(ds, { kind: "postgres", source: sql });
13257
+ studio.remember(ds, { kind: "postgres", source: sql });
13258
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "query_postgres", why, sql });
12445
13259
  return replyWithDataset(ds, sessionKey, "query_postgres", res.truncated ? " (capped at max rows)" : "");
12446
13260
  } catch (err) {
12447
13261
  return {
@@ -12459,6 +13273,7 @@ function createTinyPivotMcpServer(options = {}) {
12459
13273
  description: "Run one read-only DuckDB SELECT over local CSV, Parquet or JSON files (FROM 'path') and loaded datasets (tables named by dataset id), then chart or pivot the result. Rows stay out of your context.",
12460
13274
  inputSchema: {
12461
13275
  sql: z.string(),
13276
+ why: whyParam,
12462
13277
  name: z.string().optional(),
12463
13278
  viewMode: z.enum(VIEW_MODE_VALUES).optional(),
12464
13279
  pivotConfig: pivotConfigSchema.optional(),
@@ -12467,27 +13282,25 @@ function createTinyPivotMcpServer(options = {}) {
12467
13282
  },
12468
13283
  _meta: INLINE_UI_META
12469
13284
  },
12470
- async ({ sql, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
13285
+ async ({ sql, why, name, viewMode, pivotConfig, chartConfig, keepExisting }, extra) => {
12471
13286
  const { sessionKey, keepExisting: shouldKeep } = resolveSessionContext(extra, keepExisting);
12472
13287
  try {
12473
- if (await withinBudget(duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
13288
+ if (await withinBudget(studio.duck.prepare(), DUCKDB_WAIT_MS) === "pending") {
12474
13289
  return { content: [{ type: "text", text: "DuckDB is downloading for its first use (about 20 MB, once). Run the same query again in a minute." }] };
12475
13290
  }
12476
- const result = await duck.run(sql, queryViews(sessionKey));
12477
- const ds = store.register({
12478
- name: name ?? "SQL query",
12479
- source: sql,
12480
- ingestionMode: "direct",
12481
- rows: result.rows,
13291
+ const { dataset, truncated } = await studio.runQuery({
13292
+ sql,
13293
+ name,
13294
+ why,
13295
+ actor: "agent",
13296
+ sessionKey,
13297
+ keepExisting: shouldKeep,
12482
13298
  viewMode: initialViewMode(viewMode, Boolean(pivotConfig), Boolean(chartConfig)),
12483
13299
  pivotConfig: pivotConfig ? normalizePivot(pivotConfig) : void 0,
12484
- chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0,
12485
- sessionKey,
12486
- keepExisting: shouldKeep
13300
+ chartConfig: chartConfig ? toCoreChartConfig(chartConfig) : void 0
12487
13301
  });
12488
- remember(ds, { kind: "query", source: sql });
12489
- return replyWithDataset(ds, sessionKey, "query", result.truncated ? `
12490
- _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
13302
+ return replyWithDataset(dataset, sessionKey, "query", truncated ? `
13303
+ _Result cut at ${dataset.rows.length.toLocaleString("en-US")} rows._` : "");
12491
13304
  } catch (error) {
12492
13305
  const message = error instanceof Error ? error.message : String(error);
12493
13306
  return { isError: true, content: [{ type: "text", text: error instanceof QueryRejected ? message : `Query failed: ${message}` }] };
@@ -12500,15 +13313,17 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
12500
13313
  title: "Profile Dataset",
12501
13314
  description: "Describe each column of a loaded dataset: empty share, number and date ranges, commonest values.",
12502
13315
  inputSchema: {
12503
- datasetId: z.string().optional()
13316
+ datasetId: z.string().optional(),
13317
+ why: whyParam
12504
13318
  }
12505
13319
  },
12506
- async ({ datasetId }, extra) => {
13320
+ async ({ datasetId, why }, extra) => {
12507
13321
  const { sessionKey } = resolveSessionContext(extra);
12508
13322
  const ds = store.get(datasetId, sessionKey);
12509
13323
  if (!ds)
12510
13324
  return { isError: true, content: [{ type: "text", text: `Dataset "${datasetId ?? "(active)"}" not found.` }] };
12511
- return { content: [{ type: "text", text: formatProfile(ds) }] };
13325
+ studio.recordDatasetStep(ds, { actor: "agent", tool: "profile", why });
13326
+ return { content: [{ type: "text", text: withNotes(formatProfile(ds)) }] };
12512
13327
  }
12513
13328
  );
12514
13329
  server.registerTool(
@@ -12518,29 +13333,24 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
12518
13333
  description: "List data pulled in earlier sessions, or reopen one by id at no cost: nothing is re-queried.",
12519
13334
  inputSchema: {
12520
13335
  open: z.string().optional(),
13336
+ why: whyParam,
12521
13337
  limit: z.number().int().min(1).max(100).optional()
12522
13338
  },
12523
13339
  _meta: INLINE_UI_META
12524
13340
  },
12525
- async ({ open, limit }, extra) => {
13341
+ async ({ open, why, limit }, extra) => {
13342
+ const { history } = studio;
12526
13343
  if (!history.enabled)
12527
13344
  return { content: [{ type: "text", text: "History is off (TINYPIVOT_HISTORY=0)." }] };
12528
13345
  if (!open)
12529
- return { content: [{ type: "text", text: formatHistoryList(history.list(limit ?? 15)) }] };
12530
- const entry = history.get(open);
12531
- if (!entry)
12532
- return { isError: true, content: [{ type: "text", text: `No saved pull "${open}". ${formatHistoryList(history.list(5))}` }] };
13346
+ return { content: [{ type: "text", text: withNotes(formatHistoryList(history.list(limit ?? 15))) }] };
12533
13347
  const { sessionKey } = resolveSessionContext(extra, true);
12534
13348
  try {
12535
- const ds = entry.kind === "file" ? await store.loadFromFile(entry.source, entry.name, { sessionKey, keepExisting: true, where: entry.where }) : store.register({ name: entry.name, source: entry.source, ingestionMode: "direct", rows: history.readRows(entry), sessionKey, keepExisting: true });
12536
- store.updateView(ds.id, {
12537
- ...entry.chartConfig ? { chartConfig: entry.chartConfig } : {},
12538
- ...entry.pivotConfig ? { pivotConfig: entry.pivotConfig } : {}
12539
- }, sessionKey);
12540
- pullsByDataset.set(ds.id, entry);
13349
+ const ds = await studio.reopen(open, { actor: "agent", why, sessionKey });
12541
13350
  return replyWithDataset(ds, sessionKey, "history");
12542
13351
  } catch (error) {
12543
- return { isError: true, content: [{ type: "text", text: `Could not reopen "${open}": ${error instanceof Error ? error.message : String(error)}` }] };
13352
+ const message = error instanceof Error ? error.message : String(error);
13353
+ return { isError: true, content: [{ type: "text", text: `Could not reopen "${open}": ${message} ${formatHistoryList(history.list(5))}` }] };
12544
13354
  }
12545
13355
  }
12546
13356
  );
@@ -12708,7 +13518,7 @@ _Result cut at ${result.rows.length.toLocaleString("en-US")} rows._` : "");
12708
13518
  "set_visual_theme",
12709
13519
  {
12710
13520
  title: "Set Visual Theme",
12711
- description: "Set the theme for charts, tables and the Data IDE.",
13521
+ description: "Set the theme for charts, tables and the Studio.",
12712
13522
  inputSchema: {
12713
13523
  theme: z.enum(VISUAL_THEME_VALUES)
12714
13524
  },
@@ -12760,6 +13570,7 @@ export {
12760
13570
  DEFAULT_MODEL_PRICING,
12761
13571
  resolveModelPricing,
12762
13572
  tokensToUsd,
13573
+ STUDIO_HEADER,
12763
13574
  getPreferencesPath,
12764
13575
  loadSavedVisualTheme,
12765
13576
  saveVisualThemePreference,
@@ -12783,6 +13594,9 @@ export {
12783
13594
  runInitCommand,
12784
13595
  listPostgresTables,
12785
13596
  executeReadOnlyPostgresQuery,
13597
+ describeView,
13598
+ fileStepSql,
13599
+ Studio,
12786
13600
  APP_RESOURCE_URI,
12787
13601
  APP_MIME_TYPE,
12788
13602
  TINYPIVOT_MCP_INSTRUCTIONS,