@open-spreadsheet/core 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/charts.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Charts drawn as SVG from a range: bar (grouped), line and pie. Hand-written,
3
+ * like open-dashboard's: one y-axis, zero in the domain, a fixed categorical
4
+ * palette, ticks from one formatter, text in ink colours.
5
+ */
6
+ import { CellError, formatValue, } from '@open-spreadsheet/engine';
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ export const PALETTE = ['#2a78d6', '#e8710a', '#1e8e3e', '#d93025', '#9334e6', '#12b5cb', '#c5221f', '#7f6000'];
17
+
18
+ const text = (v ) => (v === null ? '' : v instanceof CellError ? v.code : typeof v === 'number' ? formatValue(v, '').text : String(v));
19
+
20
+ /**
21
+ * Reads a block of cells the way Excel's chart wizard does: if the top-left
22
+ * cell is empty or the first column is text, the first column holds the
23
+ * categories; a first row of text holds the series names.
24
+ */
25
+ /** Whether a block's first row holds series names and its first column categories. */
26
+ export function chartShape(cells ) {
27
+ const cols = cells[0]?.length ?? 0;
28
+ const isText = (v ) => typeof v === 'string' && v !== '';
29
+ const headerRow = Boolean(cells[0]?.slice(1).some(isText)) || (cols === 1 && isText(cells[0]?.[0] ?? null));
30
+ const labelCol = cols > 1 && cells.slice(headerRow ? 1 : 0).some((r) => typeof r[0] !== 'number');
31
+ return { headerRow, labelCol };
32
+ }
33
+
34
+ export function chartData(cells ) {
35
+ if (!cells.length || !cells[0]?.length) return { categories: [], series: [] };
36
+ const cols = cells[0] .length;
37
+ const { headerRow, labelCol } = chartShape(cells);
38
+ const r0 = headerRow ? 1 : 0;
39
+ const c0 = labelCol ? 1 : 0;
40
+ const categories = cells.slice(r0).map((r, i) => (labelCol ? text(r[0] ?? null) : String(i + 1)));
41
+ const series = [];
42
+ for (let c = c0; c < cols; c++) {
43
+ series.push({
44
+ name: headerRow ? text(cells[0] [c] ?? null) : `Series ${c - c0 + 1}`,
45
+ values: cells.slice(r0).map((r) => (typeof r[c] === 'number' ? (r[c] ) : null)),
46
+ });
47
+ }
48
+ return { categories, series };
49
+ }
50
+
51
+ /** Round axis steps: 1, 2 or 5 times a power of ten. */
52
+ export function niceTicks(min , max , count = 5) {
53
+ if (min === max) max = min + 1;
54
+ const raw = (max - min) / count;
55
+ const mag = 10 ** Math.floor(Math.log10(raw));
56
+ const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
57
+ // From the step at or below the minimum to the step at or above the maximum, so every mark fits.
58
+ const start = Math.floor(min / step) * step;
59
+ const end = Math.ceil(max / step - 1e-9) * step;
60
+ const out = [];
61
+ for (let v = start; v <= end + step * 1e-9; v += step) out.push(Number.parseFloat(v.toPrecision(12)));
62
+ return out;
63
+ }
64
+ function tickFormat(ticks ) {
65
+ const max = Math.max(...ticks.map(Math.abs));
66
+ if (max >= 1e6) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e6).toPrecision(3))}M`);
67
+ if (max >= 1e4) return (n) => (n === 0 ? '0' : `${Number.parseFloat((n / 1e3).toPrecision(3))}K`);
68
+ return (n) => formatValue(n, '#,##0.##').text.replace(/\.$/, '');
69
+ }
70
+ const esc = (s ) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
71
+
72
+ export function chartSvg(spec , data , w , h ) {
73
+ const titleH = spec.title ? 26 : 8;
74
+ const legendH = data.series.length > 1 || spec.type === 'pie' ? 22 : 0;
75
+ const title = spec.title ? `<text x="${w / 2}" y="18" text-anchor="middle" class="c-title">${esc(spec.title)}</text>` : '';
76
+ const empty = !data.series.length || data.series.every((s) => s.values.every((v) => v === null));
77
+ if (empty) return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}<text x="${w / 2}" y="${h / 2}" text-anchor="middle" class="c-muted">—</text></svg>`;
78
+
79
+ if (spec.type === 'pie') {
80
+ const s = data.series[0] ;
81
+ const items = s.values.map((v, i) => ({ v: Math.max(0, v ?? 0), name: data.categories[i] ?? '' })).filter((x) => x.v > 0);
82
+ const total = items.reduce((a, b) => a + b.v, 0);
83
+ const r = Math.max(10, Math.min(w, h - titleH - legendH) / 2 - 10);
84
+ const cx = w / 2;
85
+ const cy = titleH + (h - titleH - legendH) / 2;
86
+ let angle = -Math.PI / 2;
87
+ const slices = items
88
+ .map((it, i) => {
89
+ const a = (it.v / total) * Math.PI * 2;
90
+ const x0 = cx + r * Math.cos(angle);
91
+ const y0 = cy + r * Math.sin(angle);
92
+ angle += a;
93
+ const x1 = cx + r * Math.cos(angle);
94
+ const y1 = cy + r * Math.sin(angle);
95
+ const path = items.length === 1 ? `M${cx - r},${cy}a${r},${r} 0 1,0 ${2 * r},0a${r},${r} 0 1,0 ${-2 * r},0` : `M${cx},${cy}L${x0},${y0}A${r},${r} 0 ${a > Math.PI ? 1 : 0},1 ${x1},${y1}Z`;
96
+ return `<path d="${path}" fill="${PALETTE[i % PALETTE.length]}" stroke="var(--sheet)" stroke-width="2"><title>${esc(it.name)}: ${esc(formatValue(it.v, '#,##0.##').text.replace(/\.$/, ''))} (${Math.round((it.v / total) * 100)}%)</title></path>`;
97
+ })
98
+ .join('');
99
+ return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${slices}${legend(items.map((it) => it.name), w, h)}</svg>`;
100
+ }
101
+
102
+ const padL = 44;
103
+ const padR = 12;
104
+ const top = titleH + 4;
105
+ const bottom = h - legendH - 22;
106
+ const plotW = Math.max(10, w - padL - padR);
107
+ const plotH = Math.max(10, bottom - top);
108
+ const all = data.series.flatMap((s) => s.values.filter((v) => v !== null));
109
+ const ticks = niceTicks(Math.min(0, ...all), Math.max(0, ...all));
110
+ const lo = ticks[0] ;
111
+ const hi = ticks[ticks.length - 1] ;
112
+ const y = (v ) => bottom - ((v - lo) / (hi - lo)) * plotH;
113
+ const fmt = tickFormat(ticks);
114
+ const n = data.categories.length;
115
+ const band = plotW / Math.max(1, n);
116
+ const grid = ticks.map((t) => `<line x1="${padL}" x2="${w - padR}" y1="${y(t)}" y2="${y(t)}" class="c-grid"/><text x="${padL - 6}" y="${y(t) + 4}" text-anchor="end" class="c-tick">${esc(fmt(t))}</text>`).join('');
117
+ const every = Math.max(1, Math.ceil((n * 48) / plotW));
118
+ const xLabels = data.categories
119
+ .map((c, i) => (i % every ? '' : `<text x="${padL + band * (i + 0.5)}" y="${bottom + 15}" text-anchor="middle" class="c-tick">${esc(c.length > 10 ? `${c.slice(0, 9)}…` : c)}</text>`))
120
+ .join('');
121
+ let marks = '';
122
+ if (spec.type === 'bar') {
123
+ const k = data.series.length;
124
+ const barW = Math.min(24, (band * 0.72) / k);
125
+ data.series.forEach((s, si) => {
126
+ s.values.forEach((v, i) => {
127
+ if (v === null) return;
128
+ const x = padL + band * i + band / 2 - (barW * k) / 2 + si * barW;
129
+ const y0 = y(Math.max(0, v));
130
+ const hgt = Math.max(1, Math.abs(y(v) - y(0)));
131
+ marks += `<rect x="${x + 1}" y="${y0}" width="${Math.max(1, barW - 2)}" height="${hgt}" rx="2" fill="${PALETTE[si % PALETTE.length]}"><title>${esc(s.name)} · ${esc(data.categories[i] ?? '')}: ${esc(fmt(v))}</title></rect>`;
132
+ });
133
+ });
134
+ } else {
135
+ data.series.forEach((s, si) => {
136
+ const pts = s.values.map((v, i) => (v === null ? null : [padL + band * (i + 0.5), y(v)] ));
137
+ const d = pts.reduce((acc, p, i) => (p ? `${acc}${acc && pts[i - 1] ? 'L' : 'M'}${p[0]},${p[1]}` : acc), '');
138
+ marks += `<path d="${d}" fill="none" stroke="${PALETTE[si % PALETTE.length]}" stroke-width="2" stroke-linejoin="round"/>`;
139
+ pts.forEach((p, i) => {
140
+ if (p) marks += `<circle cx="${p[0]}" cy="${p[1]}" r="3" fill="${PALETTE[si % PALETTE.length]}"><title>${esc(s.name)} · ${esc(data.categories[i] ?? '')}: ${esc(fmt(s.values[i] ))}</title></circle>`;
141
+ });
142
+ });
143
+ }
144
+ const zero = `<line x1="${padL}" x2="${w - padR}" y1="${y(0)}" y2="${y(0)}" class="c-axis"/>`;
145
+ return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">${title}${grid}${zero}${marks}${xLabels}${legendH ? legend(data.series.map((s) => s.name), w, h) : ''}</svg>`;
146
+ }
147
+
148
+ function legend(names , w , h ) {
149
+ const items = names.slice(0, 8);
150
+ // Wide (CJK) characters take about twice the room of Latin ones at 11px.
151
+ const textWidth = (n ) => [...n.slice(0, 14)].reduce((w, ch) => w + (/[\u1100-\u11ff\u2e80-\ua4cf\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/.test(ch) ? 11.5 : 6.5), 0);
152
+ const widths = items.map((n) => 26 + textWidth(n));
153
+ const total = widths.reduce((a, b) => a + b, 0);
154
+ let x = Math.max(4, (w - total) / 2);
155
+ return items
156
+ .map((name, i) => {
157
+ const out = `<rect x="${x}" y="${h - 15}" width="9" height="9" rx="2" fill="${PALETTE[i % PALETTE.length]}"/><text x="${x + 13}" y="${h - 7}" class="c-tick">${esc(name.length > 14 ? `${name.slice(0, 13)}…` : name)}</text>`;
158
+ x += widths[i] ;
159
+ return out;
160
+ })
161
+ .join('');
162
+ }
163
+
164
+ /**
165
+ * A chart as a file of its own — for the Assets folder, a note or another
166
+ * program: the SVG with its namespace, a white background and the colours the
167
+ * page would give it written in, since no stylesheet comes with it.
168
+ */
169
+ export function chartFile(spec , data , w = 720, h = 405) {
170
+ const style =
171
+ '<style>text{font-family:-apple-system,BlinkMacSystemFont,"PingFang TC","Noto Sans TC","Segoe UI",sans-serif}' +
172
+ '.c-title{font-weight:600;font-size:13px;fill:#1f1f1f}.c-tick{font-size:11px;fill:#5f6368}.c-muted{font-size:14px;fill:#5f6368}' +
173
+ '.c-grid{stroke:#e8eaed;stroke-width:1}.c-axis{stroke:#9aa0a6;stroke-width:1}</style>';
174
+ return chartSvg(spec, data, w, h)
175
+ .replace(/^<svg /, '<svg xmlns="http://www.w3.org/2000/svg" ')
176
+ .replace('>', `>${style}<rect width="100%" height="100%" fill="#ffffff"/>`)
177
+ .replaceAll('var(--sheet)', '#ffffff');
178
+ }
package/mcp.js CHANGED
@@ -10,7 +10,8 @@
10
10
  *
11
11
  * Speaks JSON-RPC 2.0, one message per line, with no dependencies.
12
12
  */
13
- import { existsSync } from 'node:fs';
13
+ import { assetsDir, listAssets, readAsset, renderChart, trashAsset, writeNote } from './assets.js';
14
+ import { existsSync, cpSync } from 'node:fs';
14
15
  import path from 'node:path';
15
16
  import { createInterface } from 'node:readline';
16
17
  import { columnIndex, columnName, formatA1, parseA1, Workbook } from '@open-spreadsheet/engine';
@@ -94,8 +95,7 @@ const TOOLS = [
94
95
  charts: {
95
96
  type: 'array',
96
97
  items: { type: 'object' },
97
- description:
98
- 'Replaces the charts: [{ "id": "sales", "type": "bar"|"line"|"pie", "range": "A1:C13" (first column categories, first row series names), "title": "…", "x": 520, "y": 0, "w": 440, "h": 270 }] in px at 100% zoom',
98
+ description: 'Only [] is accepted: it removes charts an older workbook still has on its grid. New charts are images in Assets — use render_chart.',
99
99
  },
100
100
  hidden_rows: { type: 'array', items: { type: 'number' }, description: 'Replaces the rows hidden by hand (1-based numbers); [] shows them all' },
101
101
  hidden_cols: { type: 'array', items: { type: 'string' }, description: 'Replaces the columns hidden by hand (letters); [] shows them all' },
@@ -116,6 +116,47 @@ const TOOLS = [
116
116
  description: 'Create a workbook at sheets/<id>/workbook.json. sheets is optional: [{ name, cells, styles, cols, freeze }]; a blank Sheet1 otherwise.',
117
117
  inputSchema: { type: 'object', properties: { id: { ...str, description: 'lowercase letters, numbers and dashes' }, title: str, sheets: { type: 'array', items: { type: 'object' } } }, required: ['id', 'title'] },
118
118
  },
119
+ {
120
+ name: 'list_assets',
121
+ description:
122
+ "A workbook's images and Markdown notes (sheets/<id>/assets/), or the workspace's shared ones (scope \"shared\"). Notes are context people keep about the numbers — read them with read_asset before working on a workbook.",
123
+ inputSchema: { type: 'object', properties: { scope: { ...str, description: 'A workbook id, or "shared"' } }, required: ['scope'] },
124
+ },
125
+ {
126
+ name: 'read_asset',
127
+ description: 'The text of a Markdown note in a scope. Images are listed by list_assets; their content is not returned.',
128
+ inputSchema: { type: 'object', properties: { scope: str, name: { ...str, description: 'e.g. notes.md' } }, required: ['scope', 'name'] },
129
+ },
130
+ {
131
+ name: 'write_note',
132
+ description: 'Create or replace a Markdown note (a .md file) in a workbook\'s assets or the shared ones: explanations, sources, decisions, a summary of what you found.',
133
+ inputSchema: { type: 'object', properties: { scope: str, name: { ...str, description: 'ends in .md' }, text: str }, required: ['scope', 'name', 'text'] },
134
+ },
135
+ {
136
+ name: 'render_chart',
137
+ description:
138
+ 'Draw a chart from a range and save it as an SVG image in the workbook\'s assets (or shared): first column the categories, first row the series names when they are text. Charts are not placed on the grid; they live in Assets. Use it when a note or a person asks for a chart.',
139
+ inputSchema: {
140
+ type: 'object',
141
+ properties: {
142
+ workbook: str,
143
+ sheet: str,
144
+ range: { ...str, description: 'e.g. A1:C13' },
145
+ type: { type: 'string', enum: ['bar', 'line', 'pie'] },
146
+ title: str,
147
+ name: { ...str, description: 'file name; from the title when omitted' },
148
+ scope: { ...str, description: 'where to save: the workbook (default) or "shared"' },
149
+ replace: { type: 'boolean', description: 'overwrite an image of that name instead of numbering a new one' },
150
+ },
151
+ required: ['workbook', 'range'],
152
+ },
153
+ },
154
+ {
155
+ name: 'delete_asset',
156
+ description: 'Move an image or note to its folder\'s .trash (nothing is erased). Only when the person asked.',
157
+ inputSchema: { type: 'object', properties: { scope: str, name: str }, required: ['scope', 'name'] },
158
+ annotations: { destructiveHint: true },
159
+ },
119
160
  {
120
161
  name: 'rename_workbook',
121
162
  description: "Change a workbook's title (what the list shows). Its id, and so its address, stay.",
@@ -197,6 +238,34 @@ const TOOLS = [
197
238
 
198
239
  // ---------- tools ----------
199
240
 
241
+ /** Whether a cell lies in a protected range of the sheet. */
242
+ const isProtected = (sheet, row, col) =>
243
+ (sheet.protected ?? []).some((t) => {
244
+ const r = parseRange(t);
245
+ return row >= r.r0 && row <= r.r1 && col >= r.c0 && col <= r.c1;
246
+ });
247
+ const refuseProtected = (sheet, cells) => {
248
+ const hit = cells.find((c) => isProtected(sheet, c.row, c.col));
249
+ if (hit)
250
+ throw new OpsError(
251
+ 'protected',
252
+ `${formatA1(hit.row, hit.col)} on ${sheet.name} is in a protected range (${sheet.protected.join(', ')}). Ask the person to unprotect it in the editor; agents cannot change protected cells or remove protection.`,
253
+ );
254
+ };
255
+
256
+ /** Refuses a style change on a rectangle that overlaps a protected range. */
257
+ const refuseProtectedRect = (sheet, r) => {
258
+ const hit = (sheet.protected ?? []).find((t) => {
259
+ const p = parseRange(t);
260
+ return p.r0 <= r.r1 && r.r0 <= p.r1 && p.c0 <= r.c1 && r.c0 <= p.c1;
261
+ });
262
+ if (hit)
263
+ throw new OpsError(
264
+ 'protected',
265
+ `${hit} on ${sheet.name} is protected. Ask the person to unprotect it in the editor; agents cannot change protected cells or remove protection.`,
266
+ );
267
+ };
268
+
200
269
  const sheetOf = (data, name) => {
201
270
  const s = data.sheets.find((x) => x.name === name);
202
271
  if (!s) throw new OpsError('no_sheet', `No sheet "${name}". Sheets: ${data.sheets.map((x) => x.name).join(', ')}`);
@@ -248,6 +317,20 @@ function shiftMeta(sheet, axis, at, count) {
248
317
  }
249
318
  if (axis === 'col' && sheet.cols) sheet.cols = Object.fromEntries(Object.entries(sheet.cols).flatMap(([k, v]) => (move(columnIndex(k)) === null ? [] : [[columnName(move(columnIndex(k))), v]])));
250
319
  if (axis === 'row' && sheet.rows) sheet.rows = Object.fromEntries(Object.entries(sheet.rows).flatMap(([k, v]) => (move(Number(k) - 1) === null ? [] : [[String(move(Number(k) - 1) + 1), v]])));
320
+ if (sheet.protected) {
321
+ sheet.protected = sheet.protected.flatMap((t) => {
322
+ const r = parseRange(t);
323
+ const lo = axis === 'row' ? r.r0 : r.c0;
324
+ const hi = axis === 'row' ? r.r1 : r.c1;
325
+ const a = move(lo);
326
+ const b = move(hi);
327
+ if (a === null && b === null) return [];
328
+ const n = axis === 'row' ? { ...r, r0: a ?? at, r1: b ?? at - 1 } : { ...r, c0: a ?? at, c1: b ?? at - 1 };
329
+ if (n.r1 < n.r0 || n.c1 < n.c0) return [];
330
+ return [n.r0 === n.r1 && n.c0 === n.c1 ? formatA1(n.r0, n.c0) : `${formatA1(n.r0, n.c0)}:${formatA1(n.r1, n.c1)}`];
331
+ });
332
+ if (!sheet.protected.length) delete sheet.protected;
333
+ }
251
334
  if (sheet.merges) {
252
335
  sheet.merges = sheet.merges.flatMap((m) => {
253
336
  const r = parseRange(m);
@@ -275,13 +358,14 @@ async function callTool(root, name, a) {
275
358
  return traceCell(readWorkbook(root, a.workbook).data, a.sheet, a.address);
276
359
  case 'write_cells':
277
360
  return mutate(root, a.workbook, a.expected_hash, (data, wb) => {
278
- sheetOf(data, a.sheet);
361
+ const target = sheetOf(data, a.sheet);
279
362
  const cells = Object.entries(a.cells ?? {}).map(([addr, input]) => {
280
363
  const p = parseA1(addr);
281
364
  if (!p) throw new OpsError('bad_address', `Not an A1 address: ${addr}`);
282
365
  if (input !== null && typeof input !== 'string') throw new OpsError('bad_input', `${addr}: inputs are strings, e.g. "${input}"`);
283
366
  return { ...p, input: input ?? '' };
284
367
  });
368
+ refuseProtected(target, cells);
285
369
  wb.setCells(a.sheet, cells);
286
370
  const values = Object.fromEntries(cells.map((c) => [formatA1(c.row, c.col), wb.value(a.sheet, c.row, c.col)?.toString?.() ?? null]));
287
371
  return { written: cells.length, values };
@@ -290,6 +374,7 @@ async function callTool(root, name, a) {
290
374
  return mutate(root, a.workbook, a.expected_hash, (data) => {
291
375
  const sheet = sheetOf(data, a.sheet);
292
376
  const r = parseRange(a.range);
377
+ refuseProtectedRect(sheet, r);
293
378
  sheet.styles ??= {};
294
379
  for (let row = r.r0; row <= r.r1; row++) {
295
380
  for (let col = r.c0; col <= r.c1; col++) {
@@ -334,8 +419,8 @@ async function callTool(root, name, a) {
334
419
  }
335
420
  }
336
421
  if (a.charts !== undefined) {
337
- for (const ch of a.charts) parseRange(ch.range);
338
- sheet.charts = a.charts.length ? a.charts : undefined;
422
+ if (a.charts.length) throw new OpsError('charts_in_assets', 'Charts are not placed on the grid any more. Use render_chart to save one as an image in the workbook\'s Assets.');
423
+ sheet.charts = undefined;
339
424
  }
340
425
  if (a.hidden_rows !== undefined) sheet.hiddenRows = a.hidden_rows.length ? [...new Set(a.hidden_rows.map(Math.trunc))].sort((x, y) => x - y) : undefined;
341
426
  if (a.hidden_cols !== undefined) sheet.hiddenCols = a.hidden_cols.length ? [...new Set(a.hidden_cols.map((l) => String(l).toUpperCase()))] : undefined;
@@ -355,6 +440,18 @@ async function callTool(root, name, a) {
355
440
  const { hash } = await writeWorkbook(root, a.id, data, { create: true });
356
441
  return { id: a.id, hash, url: `/#/w/${a.id}`, problems: checkWorkbook(data) };
357
442
  }
443
+ case 'list_assets':
444
+ return { scope: a.scope, assets: listAssets(root, a.scope) };
445
+ case 'read_asset': {
446
+ if (!/\.md$/i.test(String(a.name ?? ''))) throw new OpsError('bad_name', 'read_asset reads notes (.md); images are listed by list_assets');
447
+ return { scope: a.scope, name: a.name, text: readAsset(root, a.scope, a.name) };
448
+ }
449
+ case 'write_note':
450
+ return writeNote(root, a.scope, a.name, a.text);
451
+ case 'render_chart':
452
+ return renderChart(root, a.workbook, a);
453
+ case 'delete_asset':
454
+ return trashAsset(root, a.scope, a.name);
358
455
  case 'rename_workbook': {
359
456
  const title = String(a.title ?? '').trim();
360
457
  if (!title || title.length > 200 || /[\n\r]/.test(title)) throw new OpsError('bad_title', 'A title is one line of 1 to 200 characters.');
@@ -372,6 +469,8 @@ async function callTool(root, name, a) {
372
469
  const id = a.new_id ?? nextCopyId(a.workbook, taken);
373
470
  const title = /\(copy( \d+)?\)$/.test(data.title) ? data.title : `${data.title} (copy)`;
374
471
  const { hash } = await writeWorkbook(root, id, { ...data, title }, { create: true });
472
+ const from = assetsDir(root, a.workbook);
473
+ if (existsSync(from)) cpSync(from, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
375
474
  return { id, title, hash, url: `/#/w/${id}` };
376
475
  }
377
476
  case 'delete_workbook':
@@ -391,8 +490,10 @@ async function callTool(root, name, a) {
391
490
  });
392
491
  case 'delete_sheet':
393
492
  return mutate(root, a.workbook, a.expected_hash, (data, wb) => {
394
- sheetOf(data, a.sheet);
493
+ const doomed = sheetOf(data, a.sheet);
395
494
  if (data.sheets.length === 1) throw new OpsError('last_sheet', 'A workbook needs at least one sheet.');
495
+ if (doomed.protected?.length)
496
+ throw new OpsError('protected', `${a.sheet} has protected ranges (${doomed.protected.join(', ')}). Ask the person to unprotect them in the editor before it can be deleted.`);
396
497
  wb.removeSheet(a.sheet);
397
498
  data.sheets = data.sheets.filter((s) => s.name !== a.sheet);
398
499
  });
package/ops.js CHANGED
@@ -119,6 +119,11 @@ export function nextCopyId(id, taken) {
119
119
 
120
120
  // ---------- reading cells for agents ----------
121
121
 
122
+ /** "B2:D9" or "B2" (with $ allowed) as rows and columns, or null. */
123
+ export function parseRangeText(text) {
124
+ return parseRange(text);
125
+ }
126
+
122
127
  function parseRange(text) {
123
128
  const [a, b] = String(text).toUpperCase().replaceAll('$', '').split(':');
124
129
  const p = parseA1(a ?? '');
@@ -271,7 +276,9 @@ export function checkWorkbook(data) {
271
276
  for (const a of Object.keys(s.styles ?? {})) if (!parseA1(a)) add('warning', s.name, a, 'Style on something that is not an A1 address.');
272
277
  for (const rule of s.conditional ?? []) {
273
278
  if (!parseRange(rule.range ?? '')) add('error', s.name, rule.range ?? '', 'A conditional format needs a range like B2:B20.');
274
- if (!['gt', 'lt', 'ge', 'le', 'eq', 'ne', 'between', 'contains', 'duplicate', 'colorScale', 'dataBar'].includes(rule.type)) add('error', s.name, rule.range ?? '', `Unknown conditional format type "${rule.type}".`);
279
+ if (!['gt', 'lt', 'ge', 'le', 'eq', 'ne', 'between', 'contains', 'duplicate', 'colorScale', 'dataBar', 'top', 'average', 'iconSet'].includes(rule.type)) add('error', s.name, rule.range ?? '', `Unknown conditional format type "${rule.type}".`);
280
+ if (rule.type === 'top' && !(Number(rule.rank) >= 1)) add('error', s.name, rule.range ?? '', 'A top/bottom rule needs a rank of 1 or more.');
281
+ if (rule.type === 'iconSet' && !/^[3-5][A-Za-z0-9]+$/.test(rule.set ?? '')) add('error', s.name, rule.range ?? '', 'An icon set is named like Excel\'s: "3Arrows", "3TrafficLights1", "5Rating".');
275
282
  }
276
283
  for (const v of s.validation ?? []) {
277
284
  if (!parseRange(v.range ?? '')) add('error', s.name, v.range ?? '', 'A validation rule needs a range.');
@@ -287,6 +294,7 @@ export function checkWorkbook(data) {
287
294
  if (!parseA1(a)) add('warning', s.name, a, 'Note on something that is not an A1 address.');
288
295
  else if (typeof t !== 'string') add('error', s.name, a, 'A note is a string.');
289
296
  }
297
+ for (const t of s.protected ?? []) if (!parseRange(t)) add('error', s.name, t, 'Not a protected range like A1:D1 or B2.');
290
298
  const merges = (s.merges ?? []).map((m) => ({ m, r: parseRange(m) }));
291
299
  for (const { m, r } of merges) if (!r || !m.includes(':')) add('error', s.name, m, 'Not a merge range like A1:C1.');
292
300
  for (let i = 0; i < merges.length; i++)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-spreadsheet/core",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "open-spreadsheet: an Excel-like spreadsheet for agents and people. The dev server, the grid editor and the CLI.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,11 +23,14 @@
23
23
  "mcp.js",
24
24
  "server.js",
25
25
  "ops.js",
26
+ "assets.js",
26
27
  "app",
27
28
  "skills",
28
- "templates"
29
+ "templates",
30
+ "dist"
29
31
  ],
30
32
  "publishConfig": {
31
33
  "access": "public"
32
- }
34
+ },
35
+ "scripts": {}
33
36
  }
package/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { assetPath, assetsDir, listAssets, MIME, readAsset, renderChart, saveImage, SHARED, trashAsset, writeNote } from './assets.js';
4
5
  import { currentFile, hashOf, ID, listWorkbooks, OpsError, readWorkbook, trashWorkbook, workbookFile, writeWorkbook } from './ops.js';
5
6
 
6
7
  const CORE = path.dirname(fileURLToPath(import.meta.url));
@@ -49,7 +50,12 @@ export function initWorkspace(dir) {
49
50
  )}\n`,
50
51
  );
51
52
  writeFileSync(path.join(root, 'open-spreadsheet.config.json'), '{}\n');
52
- writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n');
53
+ mkdirSync(path.join(root, 'assets'), { recursive: true });
54
+ writeFileSync(
55
+ path.join(root, 'assets', 'README.md'),
56
+ '# Shared notes\n\nMarkdown notes here are context for every workbook in this workspace: what the numbers mean, where they come from, conventions to keep. Agents read them before they work. Images here are shared too.\n',
57
+ );
58
+ writeFileSync(path.join(root, '.gitignore'), 'node_modules\n.DS_Store\n# workbooks moved to the trash from the viewer or an agent\nsheets/.trash\n**/assets/.trash\n');
53
59
  const agents = readFileSync(path.join(CORE, 'templates', 'AGENTS.md'), 'utf8');
54
60
  writeFileSync(path.join(root, 'AGENTS.md'), agents);
55
61
  writeFileSync(path.join(root, 'CLAUDE.md'), agents);
@@ -114,7 +120,21 @@ function allowedWrite(req) {
114
120
  }
115
121
  }
116
122
 
117
- const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412 };
123
+ const STATUS = { bad_id: 400, bad_data: 400, bad_json: 422, not_found: 404, exists: 409, conflict: 412, bad_name: 400, bad_range: 400, bad_type: 400, no_sheet: 404, too_big: 413 };
124
+
125
+ /** A request body as bytes, for image uploads; refused past `max`. */
126
+ const readBytes = (req, max = 15_000_000) =>
127
+ new Promise((resolve, reject) => {
128
+ const parts = [];
129
+ let size = 0;
130
+ req.on('data', (c) => {
131
+ size += c.length;
132
+ if (size > max) reject(new OpsError('too_big', 'An image is at most 15 MB.'));
133
+ else parts.push(c);
134
+ });
135
+ req.on('end', () => resolve(Buffer.concat(parts)));
136
+ req.on('error', reject);
137
+ });
118
138
 
119
139
  function apiPlugin(root) {
120
140
  // Bodies this server just wrote, so its own write does not come back as an outside change.
@@ -123,6 +143,14 @@ function apiPlugin(root) {
123
143
  name: 'open-spreadsheet:api',
124
144
  configureServer(server) {
125
145
  server.watcher.add(path.join(root, 'sheets'));
146
+ server.watcher.add(path.join(root, 'assets'));
147
+ // An asset written or removed (by an agent, apply-notes, the CLI): the Assets panel reloads its list.
148
+ const assetEvent = (file) => {
149
+ const rel = path.relative(root, file).split(path.sep);
150
+ const scope = rel[0] === 'assets' && rel.length === 2 ? SHARED : rel[0] === 'sheets' && rel[2] === 'assets' && rel.length === 4 ? rel[1] : null;
151
+ if (scope) server.ws.send({ type: 'custom', event: 'open-spreadsheet:assets', data: { scope } });
152
+ };
153
+ for (const ev of ['add', 'change', 'unlink']) server.watcher.on(ev, assetEvent);
126
154
  server.watcher.on('change', (file) => {
127
155
  const m = /sheets[\\/]([^\\/]+)[\\/]workbook\.json$/.exec(file);
128
156
  if (!m) return;
@@ -179,13 +207,50 @@ function apiPlugin(root) {
179
207
  const { id, title, data, from } = JSON.parse(await readBody(req));
180
208
  if (!ID.test(id ?? '')) return json(res, 400, { error: 'Use lowercase letters, numbers and dashes.' });
181
209
  if (existsSync(workbookFile(root, id))) return json(res, 409, { error: 'That name is taken.' });
210
+ const fromAssets = from !== undefined && ID.test(from) ? assetsDir(root, from) : null;
182
211
  let book = blankWorkbook(title || id);
183
212
  if (from !== undefined) book = { ...readWorkbook(root, from).data, ...(title ? { title } : {}) };
184
213
  else if (data !== undefined) book = { ...data, title: title || data.title || id };
185
214
  const { text } = await writeWorkbook(root, id, book, { create: true });
186
215
  ownWrites.set(id, text);
216
+ if (fromAssets && existsSync(fromAssets)) cpSync(fromAssets, assetsDir(root, id), { recursive: true, filter: (f) => !f.includes(`${path.sep}.trash`) });
187
217
  return json(res, 201, { id });
188
218
  }
219
+ // ---------- assets ----------
220
+ if (url.pathname.startsWith('/__api/assets')) {
221
+ const scope = url.searchParams.get('scope') ?? '';
222
+ const name = url.searchParams.get('name') ?? '';
223
+ if (url.pathname === '/__api/assets' && req.method === 'GET') return json(res, 200, { scope, assets: listAssets(root, scope) });
224
+ if (url.pathname === '/__api/assets/file' && req.method === 'GET') {
225
+ const body = readAsset(root, scope, name);
226
+ const ext = name.split('.').pop().toLowerCase();
227
+ res.writeHead(200, {
228
+ 'content-type': MIME[ext] ?? 'application/octet-stream',
229
+ // An SVG or note from the folder is shown, never run: no scripts, no requests, its own origin.
230
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox",
231
+ 'x-content-type-options': 'nosniff',
232
+ 'cache-control': 'no-store',
233
+ ...(url.searchParams.has('download') ? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}` } : {}),
234
+ });
235
+ return res.end(body);
236
+ }
237
+ if (!allowedWrite(req)) return json(res, 403, { error: 'forbidden' });
238
+ if (url.pathname === '/__api/assets/note' && req.method === 'PUT') {
239
+ const b = JSON.parse(await readBody(req));
240
+ return json(res, 200, writeNote(root, b.scope, b.name, b.text));
241
+ }
242
+ if (url.pathname === '/__api/assets/upload' && req.method === 'POST') {
243
+ assetPath(root, scope, name);
244
+ return json(res, 201, saveImage(root, scope, name, await readBytes(req)));
245
+ }
246
+ if (url.pathname === '/__api/assets/chart' && req.method === 'POST') {
247
+ const b = JSON.parse(await readBody(req));
248
+ return json(res, 201, await renderChart(root, b.workbook, b));
249
+ }
250
+ if (url.pathname === '/__api/assets' && req.method === 'DELETE') return json(res, 200, trashAsset(root, scope, name));
251
+ return json(res, 404, { error: 'not found' });
252
+ }
253
+
189
254
  const m = /^\/__api\/workbooks\/([^/]+)$/.exec(url.pathname);
190
255
  if (m && ID.test(m[1])) {
191
256
  const id = m[1];
@@ -14,8 +14,10 @@ People leave notes on cells in the editor (right-click → Add note, or ⇧F2).
14
14
  1. **Find them.** With the MCP server, call `list_notes` (all workbooks, or one). Otherwise read the `notes` of every sheet in `sheets/*/workbook.json`.
15
15
  2. **Sort them.** A note that asks for something ("make this a percentage", "add a total under this column", "this should use the March numbers") is a request. A note that only explains ("source: 2025 annual report") is documentation: leave it.
16
16
  3. **Do each request** on the cell the note is on and whatever it names — cells, formulas, styles, formats, layout — following the `sheet-authoring` skill. Keep totals as formulas.
17
+ - **A note asking for a chart or a picture** ("make a bar chart of this", "chart sales by month") gets an image in the workbook's Assets, never a chart on the grid: call `render_chart` with the range the note is about (its data, header row and first column included) and a title from the note. Say the file name in your report.
18
+ - **A note to remember** ("these figures are in thousands", "source: 2025 report") can go into a Markdown note in Assets with `write_note`, then the cell note is done.
17
19
  4. **Remove each note you carried out** (`set_note` with empty `text`, or delete the key from `notes`). If a request is unclear or impossible, leave the note and say why.
18
20
  5. **Check.** Run `open-spreadsheet check` (or the `check` tool) and fix what it reports.
19
- 6. **Report** which notes you applied, which you left and why.
21
+ 6. **Report** which notes you applied, which you left and why, and any chart images or notes you saved in Assets.
20
22
 
21
23
  The editor reloads as you write, so the person sees each change and the note disappear.
@@ -34,10 +34,11 @@ Each workbook is `sheets/<id>/workbook.json`. The grid editor at `pnpm dev` relo
34
34
  | `freeze` | `{ rows, cols }` frozen at the top and left |
35
35
  | `hiddenRows` / `hiddenCols` | Rows (1-based numbers) and columns (letters) hidden by hand |
36
36
  | `names` (top level, beside `sheets`) | Defined names: `{ "Sales": "Orders!$F$2:$F$200" }`, used in formulas as `=SUM(Sales)`; each points at a cell or range with its sheet |
37
- | `charts` | Charts over the grid: `[{ "id": "sales", "type": "bar", "range": "A1:C13", "title": "Sales by month", "x": 520, "y": 0, "w": 440, "h": 270 }]` — `type` is `bar`, `line` or `pie`; the range's first column holds the categories and its first row the series names; `x`/`y`/`w`/`h` are px at 100% zoom from the sheet's top-left |
37
+ | `protected` | Ranges a person locked, `["A1:D1", "F2"]`. The editor and MCP refuse to change them; never edit or remove them yourself — ask the person |
38
+ | `charts` | Not used for new work: charts are images in Assets (below). An older workbook may still have charts here; the editor offers to move them |
38
39
  | `color` | The sheet tab's colour |
39
40
  | `notes` | A1 address → a note left on the cell (see the `apply-notes` skill) |
40
- | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`) |
41
+ | `conditional` | Conditional formats, later ones win: `{ "range": "D2:D50", "type": "gt", "value": 10000, "style": { "bg": "#ffc7ce", "color": "#9c0006" } }`; types `gt lt ge le eq ne` (value), `between` (value, value2), `contains` (text), `duplicate`, `colorScale` (`colors`: 2 or 3 hex, low → high), `dataBar` (`color`), `top` (`rank`, optional `percent`, `bottom`), `average` (optional `below`, `equal`), `iconSet` (`set` as Excel names it — `3Arrows`, `3TrafficLights1`, `4Rating`, `5Arrows`…; optional `thresholds` in percent, `reverse`). All of them go to and from .xlsx |
41
42
  | `validation` | Dropdown lists: `[{ "range": "C2:C100", "list": ["Open", "In progress", "Done"] }]`; other input is refused in the editor |
42
43
  | `filter` | An autofilter: `{ "range": "A1:F200" }` (header row first); `hidden` maps a column letter to the shown values it hides |
43
44
 
@@ -73,3 +74,13 @@ Math and trigonometry (SUM, SUMIF(S), SUMPRODUCT, SUBTOTAL, ROUND/ROUNDUP/ROUNDD
73
74
 
74
75
  1. Run `open-spreadsheet check` (or the MCP `check` tool). It lists formulas that show `#NAME?`, `#REF!`, `#CIRC!`, `#VALUE!` and malformed entries.
75
76
  2. Read the result back with the MCP `read_range` tool, or open the workbook in the viewer.
77
+
78
+ ## Assets: chart images and notes
79
+
80
+ Each workbook has an assets folder, `sheets/<id>/assets/`, and the workspace has a shared one, `assets/`. They hold:
81
+
82
+ - **Chart images.** Charts are never placed on the grid. Draw one from a range with the MCP `render_chart` tool (`workbook`, `sheet`, `range`, `type` = `bar` | `line` | `pie`, `title`); it saves an SVG in the workbook's assets, the same picture the editor makes. The range's first column holds the categories and its first row the series names.
83
+ - **Notes (`.md`).** What people know about the numbers: sources, meanings, rules to keep. **Read the notes before you change a workbook** (`list_assets` then `read_asset`, or the files themselves), for that workbook and for `shared`. Write what you found or decided with `write_note` when it will help next time.
84
+
85
+ Without MCP, read and write the files directly. Never put an image or note anywhere else, and never name one with a folder in it.
86
+
@@ -45,6 +45,8 @@ npx open-spreadsheet export <id> --range A1:F200 --out data.csv # computed val
45
45
  - Sizes are pixels: `cols` by letter, `rows` by 1-based row number.
46
46
  - **Defined names** sit at the top level: `"names": { "Sales": "Orders!$F$2:$F$200" }`, then `=SUM(Sales)`.
47
47
  - **Conditional formats, dropdown lists and filters** live beside the cells too (`conditional`, `validation`, `filter`); see the `sheet-authoring` skill.
48
+ - **Assets** sit beside each workbook in `sheets/<id>/assets/` (and shared in `assets/`): chart images and Markdown notes. **Read a workbook's notes and the shared ones before you change it** — they say what the numbers mean and what to keep. Charts are never on the grid: make one with the MCP `render_chart` tool (an SVG in Assets). Keep what you learn with `write_note`.
49
+ - **Protected ranges** (`"protected": ["A1:D1"]` on a sheet) are cells a person locked. Do not change them, by MCP or by editing the JSON; if a task needs them changed, ask the person to unprotect them in the editor.
48
50
  - **Notes** are comments people leave on cells, often requests for you. "Apply the notes" means: do what each asks, then remove it (the `apply-notes` skill).
49
51
 
50
52
  ## Working rules