@ofrnsb/whiteboard 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2272 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/illustrations.ts
4
+ var ILLUSTRATIONS = [
5
+ // money and documents
6
+ "invoice",
7
+ "receipt",
8
+ "banknote",
9
+ "coin",
10
+ "wallet",
11
+ "credit-card",
12
+ "bank",
13
+ "piggy-bank",
14
+ "safe",
15
+ "cash-register",
16
+ "calculator",
17
+ "ledger",
18
+ "budget",
19
+ "tax",
20
+ "refund",
21
+ "loan",
22
+ "audit",
23
+ "currency-dollar",
24
+ "file-text",
25
+ "file-check",
26
+ "file-spreadsheet",
27
+ "clipboard-check",
28
+ "rubber-stamp",
29
+ "signature",
30
+ // performance and planning
31
+ "trending-up",
32
+ "bar-chart",
33
+ "line-chart",
34
+ "pie-chart",
35
+ "darts",
36
+ "trophy",
37
+ "medal",
38
+ "rocket",
39
+ "bulb",
40
+ "milestone",
41
+ "kanban",
42
+ "layout-dashboard",
43
+ "presentation",
44
+ // time and contact
45
+ "calendar",
46
+ "calendar-check",
47
+ "clock",
48
+ "hourglass",
49
+ "timer",
50
+ "phone",
51
+ "mail",
52
+ "chat",
53
+ "messages",
54
+ "megaphone",
55
+ "bell-ring",
56
+ // people
57
+ "user",
58
+ "users",
59
+ "briefcase",
60
+ "id-card",
61
+ "office-chair",
62
+ // operations and logistics
63
+ "truck",
64
+ "van",
65
+ "forklift",
66
+ "warehouse",
67
+ "factory",
68
+ "store",
69
+ "shopping-cart",
70
+ "cargo-ship",
71
+ "route",
72
+ "map-pin",
73
+ "globe",
74
+ "barcode",
75
+ "archive",
76
+ "toolbox",
77
+ // control and risk
78
+ "alert-triangle",
79
+ "check-circle",
80
+ "shield-check",
81
+ "lock",
82
+ "courthouse",
83
+ "hammer",
84
+ "scale",
85
+ "search",
86
+ "flag",
87
+ "stop-sign",
88
+ "signpost",
89
+ // systems
90
+ "database",
91
+ "server",
92
+ "cloud",
93
+ "settings",
94
+ "refresh",
95
+ "laptop",
96
+ "exchange"
97
+ ];
98
+ var NAMES = new Set(ILLUSTRATIONS);
99
+ var isIllustration = (x) => typeof x === "string" && NAMES.has(x);
100
+
101
+ // src/core/board-geometry.ts
102
+ var POLYGONS = {
103
+ diamond: { pts: [[0.5, 0], [1, 0.5], [0.5, 1], [0, 0.5]], inset: [0.24, 0.22, 0.24, 0.22] },
104
+ triangle: { pts: [[0.5, 0], [1, 1], [0, 1]], inset: [0.46, 0.24, 0.06, 0.24] },
105
+ pentagon: { pts: [[0.5, 0], [1, 0.38], [0.81, 1], [0.19, 1], [0, 0.38]], inset: [0.26, 0.15, 0.06, 0.15] },
106
+ hexagon: { pts: [[0.24, 0], [0.76, 0], [1, 0.5], [0.76, 1], [0.24, 1], [0, 0.5]], inset: [0.08, 0.17, 0.08, 0.17] },
107
+ parallelogram: { pts: [[0.16, 0], [1, 0], [0.84, 1], [0, 1]], inset: [0.06, 0.17, 0.06, 0.17] }
108
+ };
109
+ var isPolygon = (s) => typeof s === "string" && s in POLYGONS;
110
+ function wrapLines(s, charW, width) {
111
+ if (!s) return 0;
112
+ const max = Math.max(40, width);
113
+ let n2 = 0;
114
+ for (const part of s.split("\n")) {
115
+ let line = 0;
116
+ n2 += 1;
117
+ for (const word of part.split(/\s+/).filter(Boolean)) {
118
+ const ww = word.length * charW;
119
+ if (line && line + charW + ww > max) {
120
+ n2 += 1;
121
+ line = 0;
122
+ }
123
+ if (ww > max) {
124
+ n2 += Math.ceil(ww / max) - 1;
125
+ line = ww % max;
126
+ } else line += (line ? charW : 0) + ww;
127
+ }
128
+ }
129
+ return n2;
130
+ }
131
+ var hits = (a, b, gap2 = 0) => a.x < b.x + b.w + gap2 && b.x < a.x + a.w + gap2 && a.y < b.y + b.h + gap2 && b.y < a.y + a.h + gap2;
132
+ var overlaps = (a, list, gap2 = 0) => list.some((b) => hits(a, b, gap2));
133
+ function freeSpot(want, taken, gap2, step = 24, reach = 4e3) {
134
+ if (!overlaps(want, taken, gap2)) return want;
135
+ for (let r = step; r <= reach; r += step) {
136
+ const ring = [];
137
+ for (let d = -r; d <= r; d += step) ring.push([d, -r], [d, r], [-r, d], [r, d]);
138
+ ring.sort((p, q) => Math.hypot(p[0], p[1]) - Math.hypot(q[0], q[1]) || p[1] - q[1] || p[0] - q[0]);
139
+ for (const [dx, dy] of ring) {
140
+ const b = { ...want, x: want.x + dx, y: want.y + dy };
141
+ if (!overlaps(b, taken, gap2)) return b;
142
+ }
143
+ }
144
+ return want;
145
+ }
146
+ var WIRE = { cell: 16, clear: 18, margin: 360, bend: 20, cross: 6, along: 30, away: 8 };
147
+ var labelSize = (label, charW) => ({ w: Math.round(label.length * charW + 24), h: 30 });
148
+ var DX = [0, 1, 0, -1];
149
+ var DY = [-1, 0, 1, 0];
150
+ var Heap = class {
151
+ a = [];
152
+ k = [];
153
+ get size() {
154
+ return this.a.length;
155
+ }
156
+ // Ties break on the node number, so the same board always routes the same way.
157
+ less(i, j) {
158
+ return this.k[i] < this.k[j] || this.k[i] === this.k[j] && this.a[i] < this.a[j];
159
+ }
160
+ swap(i, j) {
161
+ [this.a[i], this.a[j]] = [this.a[j], this.a[i]];
162
+ [this.k[i], this.k[j]] = [this.k[j], this.k[i]];
163
+ }
164
+ push(v, key2) {
165
+ this.a.push(v);
166
+ this.k.push(key2);
167
+ let i = this.a.length - 1;
168
+ while (i > 0) {
169
+ const p = i - 1 >> 1;
170
+ if (!this.less(i, p)) break;
171
+ this.swap(i, p);
172
+ i = p;
173
+ }
174
+ }
175
+ pop() {
176
+ const top = this.a[0], last = this.a.length - 1;
177
+ this.swap(0, last);
178
+ this.a.pop();
179
+ this.k.pop();
180
+ let i = 0;
181
+ for (; ; ) {
182
+ const l = i * 2 + 1, r = l + 1;
183
+ let m = i;
184
+ if (l < this.a.length && this.less(l, m)) m = l;
185
+ if (r < this.a.length && this.less(r, m)) m = r;
186
+ if (m === i) break;
187
+ this.swap(i, m);
188
+ i = m;
189
+ }
190
+ return top;
191
+ }
192
+ };
193
+ var ALONG = {
194
+ ellipse: [[0.5], [0.5], [0.5], [0.5]],
195
+ cloud: [[0.5], [0.5], [0.5], [0.5]],
196
+ diamond: [[0.5], [0.5], [0.5], [0.5]],
197
+ triangle: [[0.5], [], [0.5, 0.3, 0.7], []],
198
+ pentagon: [[0.5], [0.38], [0.5, 0.3, 0.7], [0.38]],
199
+ hexagon: [[0.5, 0.35, 0.65], [0.5], [0.5, 0.35, 0.65], [0.5]],
200
+ parallelogram: [[0.58, 0.35, 0.8], [], [0.42, 0.2, 0.65], []]
201
+ };
202
+ var BOX_ALONG = [[0.5, 0.25, 0.75], [0.5, 0.25, 0.75], [0.5, 0.25, 0.75], [0.5, 0.25, 0.75]];
203
+ var FLAT = /* @__PURE__ */ new Set([void 0, "box", "note", "cylinder", "text"]);
204
+ function ports(b, other) {
205
+ const out = [];
206
+ const along = (b.shape && ALONG[b.shape] || BOX_ALONG).map((fs) => [...fs]);
207
+ if (FLAT.has(b.shape) && FLAT.has(other.shape)) {
208
+ const y0 = Math.max(b.y, other.y), y1 = Math.min(b.y + b.h, other.y + other.h);
209
+ if (y1 - y0 > 24) {
210
+ const f = ((y0 + y1) / 2 - b.y) / b.h;
211
+ along[1].unshift(f);
212
+ along[3].unshift(f);
213
+ }
214
+ const x0 = Math.max(b.x, other.x), x1 = Math.min(b.x + b.w, other.x + other.w);
215
+ if (x1 - x0 > 24) {
216
+ const f = ((x0 + x1) / 2 - b.x) / b.w;
217
+ along[0].unshift(f);
218
+ along[2].unshift(f);
219
+ }
220
+ }
221
+ const dx = other.x + other.w / 2 - (b.x + b.w / 2), dy = other.y + other.h / 2 - (b.y + b.h / 2);
222
+ const facing = [dy < 0, dx > 0, dy > 0, dx < 0];
223
+ along.forEach((fs, side) => fs.forEach((f, k) => {
224
+ const off = (k === 0 ? 0 : 2) + (facing[side] ? 0 : WIRE.away);
225
+ if (side === 0) out.push({ x: b.x + b.w * f, y: b.y, side: 0, off });
226
+ else if (side === 1) out.push({ x: b.x + b.w, y: b.y + b.h * f, side: 1, off });
227
+ else if (side === 2) out.push({ x: b.x + b.w * f, y: b.y + b.h, side: 2, off });
228
+ else out.push({ x: b.x, y: b.y + b.h * f, side: 3, off });
229
+ }));
230
+ return out;
231
+ }
232
+ function routeWires(items, wires, labelW) {
233
+ const out = /* @__PURE__ */ new Map();
234
+ const boxes = [...items.values()];
235
+ const usedH = /* @__PURE__ */ new Set(), usedV = /* @__PURE__ */ new Set();
236
+ const labels = [];
237
+ wires.forEach((wire, i) => {
238
+ const a = items.get(wire.from), c = items.get(wire.to);
239
+ if (!a || !c || wire.from === wire.to) return;
240
+ const pts = routeOne(a, c, boxes, usedH, usedV) ?? fallback(a, c);
241
+ for (let k = 0; k + 3 < pts.length; k += 2) mark(pts[k], pts[k + 1], pts[k + 2], pts[k + 3], usedH, usedV);
242
+ const r = { pts };
243
+ if (wire.label) {
244
+ const spot = labelSpot(pts, labelW(wire.label), [...boxes, ...labels]);
245
+ r.label = spot;
246
+ labels.push(spot);
247
+ }
248
+ out.set(i, r);
249
+ });
250
+ return out;
251
+ }
252
+ var key = (x, y) => `${Math.round(x / WIRE.cell)},${Math.round(y / WIRE.cell)}`;
253
+ function mark(x1, y1, x2, y2, usedH, usedV) {
254
+ const n2 = Math.max(1, Math.round(Math.hypot(x2 - x1, y2 - y1) / WIRE.cell));
255
+ const set = y1 === y2 ? usedH : usedV;
256
+ for (let s = 0; s <= n2; s++) set.add(key(x1 + (x2 - x1) * s / n2, y1 + (y2 - y1) * s / n2));
257
+ }
258
+ function routeOne(a, c, boxes, usedH, usedV) {
259
+ for (const margin of [WIRE.margin, WIRE.margin * 3]) {
260
+ const r = search(a, c, boxes, usedH, usedV, margin);
261
+ if (r) return r;
262
+ }
263
+ return null;
264
+ }
265
+ function search(a, c, boxes, usedH, usedV, margin) {
266
+ const C = WIRE.cell;
267
+ const x0 = Math.floor((Math.min(a.x, c.x) - margin) / C) * C, y0 = Math.floor((Math.min(a.y, c.y) - margin) / C) * C;
268
+ const x1 = Math.max(a.x + a.w, c.x + c.w) + margin, y1 = Math.max(a.y + a.h, c.y + c.h) + margin;
269
+ const W = Math.ceil((x1 - x0) / C) + 1, H = Math.ceil((y1 - y0) / C) + 1;
270
+ if (W * H > 4e5) return null;
271
+ const cx = (i) => x0 + i * C, cy = (j) => y0 + j * C;
272
+ const blocked = new Uint8Array(W * H);
273
+ for (const b of boxes) {
274
+ if (!hits(b, { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })) continue;
275
+ const i0 = Math.max(0, Math.ceil((b.x - WIRE.clear - x0) / C)), i1 = Math.min(W - 1, Math.floor((b.x + b.w + WIRE.clear - x0) / C));
276
+ const j0 = Math.max(0, Math.ceil((b.y - WIRE.clear - y0) / C)), j1 = Math.min(H - 1, Math.floor((b.y + b.h + WIRE.clear - y0) / C));
277
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) blocked[j * W + i] = 1;
278
+ }
279
+ const exits = (b, other) => ports(b, other).map((p) => {
280
+ let i = Math.round((p.x - x0) / C), j = Math.round((p.y - y0) / C);
281
+ if (p.side === 0 || p.side === 2) i = Math.min(Math.max(i, Math.ceil((b.x + 4 - x0) / C)), Math.floor((b.x + b.w - 4 - x0) / C));
282
+ else j = Math.min(Math.max(j, Math.ceil((b.y + 4 - y0) / C)), Math.floor((b.y + b.h - 4 - y0) / C));
283
+ const px = p.side === 0 || p.side === 2 ? cx(i) : p.x, py = p.side === 1 || p.side === 3 ? cy(j) : p.y;
284
+ const own = { x: b.x - WIRE.clear - 1, y: b.y - WIRE.clear - 1, w: b.w + WIRE.clear * 2 + 2, h: b.h + WIRE.clear * 2 + 2 };
285
+ let steps = 0;
286
+ while (steps === 0 || cx(i) >= own.x && cx(i) <= own.x + own.w && cy(j) >= own.y && cy(j) <= own.y + own.h) {
287
+ i += DX[p.side];
288
+ j += DY[p.side];
289
+ steps++;
290
+ }
291
+ return { i, j, px, py, side: p.side, steps, off: p.off };
292
+ }).filter((e) => e.i >= 0 && e.j >= 0 && e.i < W && e.j < H && !blocked[e.j * W + e.i]);
293
+ const from = exits(a, c), to = exits(c, a);
294
+ if (!from.length || !to.length) return null;
295
+ const goal = /* @__PURE__ */ new Map();
296
+ for (const e of to) {
297
+ const n2 = e.j * W + e.i, d = (e.side + 2) % 4;
298
+ if (!goal.has(n2 * 4 + d)) goal.set(n2 * 4 + d, e);
299
+ }
300
+ const g = new Float64Array(W * H * 4).fill(Infinity), prev = new Int32Array(W * H * 4).fill(-1);
301
+ const start = /* @__PURE__ */ new Map();
302
+ const heap = new Heap();
303
+ const hx = (i, j) => Math.min(...to.map((e) => Math.abs(e.i - i) + Math.abs(e.j - j)));
304
+ for (const e of from) {
305
+ const s2 = (e.j * W + e.i) * 4 + e.side;
306
+ const cost = e.steps + e.off;
307
+ if (cost < g[s2]) {
308
+ g[s2] = cost;
309
+ start.set(s2, e);
310
+ heap.push(s2, cost + hx(e.i, e.j));
311
+ }
312
+ }
313
+ let end = -1;
314
+ while (heap.size) {
315
+ const s2 = heap.pop();
316
+ if (goal.has(s2)) {
317
+ end = s2;
318
+ break;
319
+ }
320
+ const n2 = s2 >> 2, d = s2 & 3, i = n2 % W, j = (n2 - i) / W;
321
+ for (let nd = 0; nd < 4; nd++) {
322
+ if (nd === (d + 2) % 4) continue;
323
+ const ni = i + DX[nd], nj = j + DY[nd];
324
+ if (ni < 0 || nj < 0 || ni >= W || nj >= H || blocked[nj * W + ni]) continue;
325
+ const k = key(cx(ni), cy(nj));
326
+ const horiz = nd === 1 || nd === 3;
327
+ const pen = (horiz ? usedH : usedV).has(k) ? WIRE.along : (horiz ? usedV : usedH).has(k) ? WIRE.cross : 0;
328
+ const t = (nj * W + ni) * 4 + nd, cost = g[s2] + 1 + (nd !== d ? WIRE.bend : 0) + pen;
329
+ if (cost < g[t]) {
330
+ g[t] = cost;
331
+ prev[t] = s2;
332
+ heap.push(t, cost + hx(ni, nj));
333
+ }
334
+ }
335
+ }
336
+ if (end < 0) return null;
337
+ const cells = [];
338
+ let s = end;
339
+ while (s >= 0) {
340
+ const n2 = s >> 2, i = n2 % W;
341
+ cells.push([cx(i), cy((n2 - i) / W)]);
342
+ if (start.has(s)) break;
343
+ s = prev[s];
344
+ }
345
+ cells.reverse();
346
+ const a0 = start.get(s), c0 = goal.get(end);
347
+ const raw = [[a0.px, a0.py], ...cells, [c0.px, c0.py]];
348
+ return simplify(raw);
349
+ }
350
+ function simplify(p) {
351
+ const out = [];
352
+ for (const q of p) {
353
+ if (out.length && out[out.length - 1][0] === q[0] && out[out.length - 1][1] === q[1]) continue;
354
+ if (out.length >= 2) {
355
+ const [ax, ay] = out[out.length - 2], [bx, by] = out[out.length - 1];
356
+ if (ax === bx && bx === q[0] || ay === by && by === q[1]) {
357
+ out[out.length - 1] = q;
358
+ continue;
359
+ }
360
+ }
361
+ out.push(q);
362
+ }
363
+ return out.flat();
364
+ }
365
+ function fallback(a, c) {
366
+ const ax = a.x + a.w / 2, ay = a.y + a.h / 2, cx = c.x + c.w / 2, cy = c.y + c.h / 2;
367
+ if (Math.abs(cx - ax) >= Math.abs(cy - ay)) {
368
+ const x1 = cx > ax ? a.x + a.w : a.x, x2 = cx > ax ? c.x : c.x + c.w, mx = (x1 + x2) / 2;
369
+ return [x1, ay, mx, ay, mx, cy, x2, cy];
370
+ }
371
+ const y1 = cy > ay ? a.y + a.h : a.y, y2 = cy > ay ? c.y : c.y + c.h, my = (y1 + y2) / 2;
372
+ return [ax, y1, ax, my, cx, my, cx, y2];
373
+ }
374
+ function labelSpot(pts, size, avoid) {
375
+ const runs = [];
376
+ for (let k = 0; k + 3 < pts.length; k += 2) runs.push({ x1: pts[k], y1: pts[k + 1], x2: pts[k + 2], y2: pts[k + 3], len: Math.hypot(pts[k + 2] - pts[k], pts[k + 3] - pts[k + 1]) });
377
+ const order = [...runs].sort((p, q) => q.len - p.len);
378
+ const at = (x, y) => ({ x: Math.round(x - size.w / 2), y: Math.round(y - size.h / 2), w: size.w, h: size.h });
379
+ const SHOW = 28;
380
+ for (const r2 of order) {
381
+ const horiz = r2.y1 === r2.y2;
382
+ if (r2.len < (horiz ? size.w : size.h) + SHOW * 2) continue;
383
+ const b = at((r2.x1 + r2.x2) / 2, (r2.y1 + r2.y2) / 2);
384
+ if (!overlaps(b, avoid, 4)) return b;
385
+ }
386
+ for (const r2 of order) {
387
+ const horiz = r2.y1 === r2.y2, mx = (r2.x1 + r2.x2) / 2, my = (r2.y1 + r2.y2) / 2;
388
+ const sides = horiz ? [at(mx, my - size.h / 2 - 6), at(mx, my + size.h / 2 + 6)] : [at(mx + size.w / 2 + 8, my), at(mx - size.w / 2 - 8, my)];
389
+ for (const b of sides) if (!overlaps(b, avoid, 4)) return b;
390
+ }
391
+ const r = order[0];
392
+ return r ? at((r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2 - size.h) : at(pts[0], pts[1]);
393
+ }
394
+ function wireBoxes(pts, pad = 6) {
395
+ const out = [];
396
+ for (let k = 0; k + 3 < pts.length; k += 2) {
397
+ const x = Math.min(pts[k], pts[k + 2]), y = Math.min(pts[k + 1], pts[k + 3]);
398
+ out.push({ x: x - pad, y: y - pad, w: Math.abs(pts[k + 2] - pts[k]) + pad * 2, h: Math.abs(pts[k + 3] - pts[k + 1]) + pad * 2 });
399
+ }
400
+ return out;
401
+ }
402
+
403
+ // src/core/line-icons.ts
404
+ var LINE_ICONS = [
405
+ "phone",
406
+ "phone-call",
407
+ "phone-incoming",
408
+ "phone-missed",
409
+ "headset",
410
+ "message-circle",
411
+ "message-square",
412
+ "messages-square",
413
+ "mail",
414
+ "send",
415
+ "bell",
416
+ "megaphone",
417
+ "user",
418
+ "users",
419
+ "user-check",
420
+ "user-x",
421
+ "user-plus",
422
+ "contact",
423
+ "crown",
424
+ "star",
425
+ "heart",
426
+ "handshake",
427
+ "briefcase",
428
+ "building",
429
+ "landmark",
430
+ "store",
431
+ "house",
432
+ "credit-card",
433
+ "wallet",
434
+ "banknote",
435
+ "coins",
436
+ "piggy-bank",
437
+ "receipt",
438
+ "percent",
439
+ "badge-dollar-sign",
440
+ "hand-coins",
441
+ "globe",
442
+ "plane",
443
+ "map-pin",
444
+ "car",
445
+ "database",
446
+ "server",
447
+ "cloud",
448
+ "cpu",
449
+ "bot",
450
+ "brain",
451
+ "sparkles",
452
+ "wand",
453
+ "zap",
454
+ "plug",
455
+ "workflow",
456
+ "network",
457
+ "git-branch",
458
+ "layers",
459
+ "boxes",
460
+ "package",
461
+ "truck",
462
+ "search",
463
+ "list-checks",
464
+ "clipboard-check",
465
+ "clipboard-list",
466
+ "file-text",
467
+ "files",
468
+ "folder",
469
+ "book-open",
470
+ "notebook-pen",
471
+ "pencil",
472
+ "calculator",
473
+ "chart-bar",
474
+ "chart-line",
475
+ "chart-pie",
476
+ "chart-no-axes-combined",
477
+ "trending-up",
478
+ "trending-down",
479
+ "target",
480
+ "gauge",
481
+ "activity",
482
+ "funnel",
483
+ "calendar",
484
+ "calendar-check",
485
+ "calendar-clock",
486
+ "clock",
487
+ "timer",
488
+ "hourglass",
489
+ "repeat",
490
+ "refresh-cw",
491
+ "infinity",
492
+ "rocket",
493
+ "flag",
494
+ "milestone",
495
+ "check",
496
+ "circle-check",
497
+ "x",
498
+ "circle-x",
499
+ "octagon-x",
500
+ "shield",
501
+ "shield-check",
502
+ "lock",
503
+ "key",
504
+ "eye",
505
+ "thumbs-up",
506
+ "thumbs-down",
507
+ "lightbulb",
508
+ "info",
509
+ "scale",
510
+ "gavel",
511
+ "award",
512
+ "trophy",
513
+ "gift",
514
+ "ticket",
515
+ "tag",
516
+ "shopping-cart",
517
+ "smartphone",
518
+ "laptop",
519
+ "monitor",
520
+ "wifi",
521
+ "arrow-right",
522
+ "arrow-down",
523
+ "arrow-up-right",
524
+ "corner-down-right",
525
+ "split",
526
+ "merge",
527
+ "plus",
528
+ "minus",
529
+ "equal",
530
+ "ban",
531
+ "hand",
532
+ "pointer"
533
+ ];
534
+ var NAMES2 = new Set(LINE_ICONS);
535
+ var isLineIcon = (x) => typeof x === "string" && NAMES2.has(x);
536
+
537
+ // src/core/copy.ts
538
+ var ERR = {
539
+ nBarisLagi: (a) => `
540
+ ... ${a} more rows`,
541
+ membuatPapan: "made the board",
542
+ batchNotFound: "That piece of agent work is not in this board's history.",
543
+ batchChangedSince: (who) => `${who.join(", ")} changed the board after the agent did. Undo version by version from History so their changes are not lost.`,
544
+ versionNotKept: (v) => `Version ${v} is no longer kept in this board's history.`,
545
+ luarBagianN: (a) => `Outside sections
546
+ ${a}`
547
+ };
548
+ var WORDS = { yes: "Yes", no: "No", agent: "Agent", untitled: "Untitled", created: "created", you: "You" };
549
+
550
+ // src/core/config.ts
551
+ var LEN = {
552
+ prefix: 6,
553
+ short: 12,
554
+ tag: 30,
555
+ id: 40,
556
+ name: 60,
557
+ key: 64,
558
+ label: 80,
559
+ title: 120,
560
+ ident: 128,
561
+ line: 200,
562
+ host: 255,
563
+ message: 300,
564
+ note: 400,
565
+ para: 500,
566
+ detail: 600,
567
+ text: 1e3,
568
+ long: 2e3,
569
+ doc: 4e3,
570
+ instructions: 12e3
571
+ };
572
+ var BOARD = {
573
+ note: { w: 200, h: 120 },
574
+ gap: 16,
575
+ pad: 24,
576
+ head: 48,
577
+ maxNotes: 400,
578
+ maxLinks: 400,
579
+ maxTabs: 12,
580
+ maxRows: 2e3,
581
+ maxCols: 40,
582
+ maxText: 2e3,
583
+ maxInkPoints: 4e3,
584
+ inkWeight: { min: 1, max: 400 },
585
+ coordLimit: 1e5,
586
+ minSize: { mark: { w: 24, h: 16 }, shape: { w: 80, h: 40 }, note: { w: 120, h: 80 } },
587
+ frame: { default: { w: 480, h: 360 }, min: { w: 160, h: 100 } },
588
+ gridSectionsPerRow: 3,
589
+ gridNotesPerRow: 2,
590
+ textRows: 200,
591
+ draw: {
592
+ pad: 24,
593
+ head: 48,
594
+ gapX: 16,
595
+ gapY: 12,
596
+ sectionGap: 40,
597
+ wrapAt: 1150,
598
+ stackSlack: 160,
599
+ aspect: 2.2,
600
+ flowGapX: 56,
601
+ diagramGap: { x: 64, y: 48 },
602
+ belowExisting: 96,
603
+ item: { stack: { w: 560, h: 56 }, grid: { w: 200, h: 88 }, row: { w: 184, h: 80 }, flow: { w: 168, h: 88 }, diagram: { w: 184, h: 72 }, timeline: { w: 200, h: 120 }, matrix: { w: 176, h: 56 } },
604
+ heading: { w: 720, h: 44, step: 52, subH: 28, subStep: 36, titleRoom: 40, titleCharW: 22, stickerGap: 24 },
605
+ /** An emoji card: room for the illustration above the title. */
606
+ iconCard: { extraH: 64 },
607
+ sticker: { w: 112, h: 112, captionH: 28 },
608
+ /** The road: cards alternate above and below a gentle wave; `step` is the distance between milestones. */
609
+ timeline: { step: 136, amp: 34, waveSteps: 2.4, sample: 24, lead: 56, cardGap: 56, pill: { w: 88, h: 32 }, dot: { w: 22, h: 22 }, trackPad: 24, labelH: 32 },
610
+ matrix: { headW: 132, headH: 40, cellW: 208, cellMinH: 96, cellPad: 12, itemGap: 8, gap: 6 },
611
+ /** A hand-composed section: its own space in board units, and the limits on what the agent may place in it. */
612
+ free: { w: 2200, h: 920, titleH: 56, titleGap: 12, titleMinW: 320, titleCharW: 13, itemW: 220, itemH: 120, gap: 24, strokes: 24, points: 80, strokeW: { pena: { s: 3, m: 6, l: 10 }, spidol: { s: 8, m: 14, l: 22 } } },
613
+ /**
614
+ * The marker sketch. Letter widths are Patrick Hand's measured average advance per em (lower and upper case), with a
615
+ * little slack for word wrap. Blocks and loose text come in four sizes; the board measures every item with these
616
+ * same numbers before placing it, so words always fit their outline.
617
+ */
618
+ sketch: {
619
+ lower: 0.36,
620
+ upper: 0.43,
621
+ wrapSlack: 1.12,
622
+ pad: 14,
623
+ gap: 18,
624
+ groupPad: 26,
625
+ groupTitle: 40,
626
+ roundInner: 0.76,
627
+ block: { s: { title: 19, titleLh: 23, text: 16, textLh: 20, icon: 34 }, m: { title: 24, titleLh: 28, text: 20, textLh: 25, icon: 52 }, l: { title: 32, titleLh: 37, text: 24, textLh: 30, icon: 72 }, xl: { title: 44, titleLh: 50, text: 30, textLh: 37, icon: 92 } },
628
+ words: { s: { size: 20, lh: 25, upper: false }, m: { size: 26, lh: 31, upper: false }, l: { size: 32, lh: 37, upper: true }, xl: { size: 46, lh: 50, upper: true } },
629
+ headline: { w: 1500, gapBelow: 10, contextW: 1500, below: 34, iconGap: 28, icon: 96 },
630
+ pillH: 46,
631
+ maxPush: 60
632
+ },
633
+ /**
634
+ * A free board: items where the agent put them, `gap` kept between any two, sticky notes `noteW` wide parked
635
+ * `noteGap` from what they are about. Sticky notes are lettered in the board's own type: about `noteChar` wide
636
+ * per letter at 14px, `noteLh` a line, `noteTop` for the margins.
637
+ */
638
+ tell: {
639
+ widths: { s: 240, m: 300, l: 380, xl: 480 },
640
+ minTextW: 150,
641
+ gap: 56,
642
+ noteW: 230,
643
+ noteMaxW: 330,
644
+ noteGap: 16,
645
+ below: 80,
646
+ minAspect: { diamond: 0.75, triangle: 0.8, pentagon: 0.85, hexagon: 0.5, parallelogram: 0.3 },
647
+ noteChar: 7.2,
648
+ noteLh: 20,
649
+ noteTop: 34,
650
+ notePad: 32,
651
+ maxItems: 40,
652
+ legend: { fact: "black: facts", problem: "red: what goes wrong", action: "green: what we do", insight: "purple: what it means", person: "blue: people and desks", system: "orange: systems and data", note: "yellow notes: what I said while drawing", wires: "black wires: the main flow; each layer of detail below it has its own wire colour (1 blue, 2 teal, 3 violet, 4 orange, 5 magenta, 6 olive, 7 brown, 8 slate, 9 cyan)" }
653
+ },
654
+ sectionItems: 60,
655
+ gridColumns: 6,
656
+ gridColumnsDefault: 2,
657
+ textItemH: 32,
658
+ minFrameW: 280,
659
+ titleCharW: 8,
660
+ minFrameExtraH: 40,
661
+ fit: { charW: 7.2, minLineW: 80, inset: 28, base: 24, lineH: 20, titleGap: 4 }
662
+ },
663
+ /** Sticky notes of a column or grid board (retro, brainstorm): square-ish with large text. */
664
+ sticky: { w: 168, h: 140, top: 30, titleLh: 21, titleCharW: 8.4, byH: 16, charW: 7.2, lh: 20, pad: 32 }
665
+ };
666
+ var COUNT = { xxs: 3, xs: 4, s: 5, sm: 6, ms: 8, m: 10, ml: 12, l: 20, xl: 30, wide: 40, xxl: 50, long: 60, huge: 100, max: 200, bulk: 500, points: 4e3 };
667
+ var BOARD_ARGS = {
668
+ ref: 40,
669
+ why: 200,
670
+ title: { min: 3, max: 120 },
671
+ noteText: 1e3,
672
+ owner: 80,
673
+ due: 40,
674
+ sectionTitle: 120,
675
+ sectionNotes: 60,
676
+ sections: 12,
677
+ cell: 1e3,
678
+ colName: 60,
679
+ options: 40,
680
+ option: 80,
681
+ formula: 200,
682
+ itemTitle: 120,
683
+ itemText: 600,
684
+ gridMax: 12,
685
+ subtitle: 200,
686
+ sectionCols: 6,
687
+ items: 60,
688
+ linkLabel: 60,
689
+ headingTitle: 200,
690
+ headingSubtitle: 300,
691
+ connectors: 80,
692
+ beats: 16,
693
+ beatItems: 40,
694
+ say: 220,
695
+ freeSpan: 2e4,
696
+ kids: 8,
697
+ answer: 320,
698
+ noteIds: 200,
699
+ columns: 40,
700
+ rows: 2e3,
701
+ tabs: 8,
702
+ addNotes: 100,
703
+ moveNotes: 400,
704
+ updates: 200,
705
+ addLinks: 60,
706
+ addColumns: 20,
707
+ addTabs: 6,
708
+ editNote: 120,
709
+ listed: 40
710
+ };
711
+ var LOOSE_NOTES = { perRow: 3, dx: 216, dy: 136 };
712
+ var SECTION_NOTE_INSET = 24;
713
+ var BOARD_EDITS_KEPT = 20;
714
+ var BOARD_CHATS_KEPT = 20;
715
+ var BOARD_HISTORY = { whiteboardEdits: 60, opsMax: 400, opsBytes: 2e5, activityMs: 3e4, stepMs: 900, stepsTotalMs: 12e3, beat: { baseMs: 1600, perItemMs: 320, maxMs: 4800, sayChars: 140 }, cardsPerStep: 2, planMs: 1400, planMax: 200 };
716
+
717
+ // src/core/boards.ts
718
+ var NOTE_COLORS = ["yellow", "blue", "green", "pink", "purple", "gray", "paper", "ink", "red", "outline", "new", "orange", "peach", "sand"];
719
+ var SHAPES = ["note", "box", "text", "ellipse", "cloud", "cylinder", "ink", "track", "pill", "dot", "cell", "sticker", "diamond", "triangle", "pentagon", "hexagon", "parallelogram"];
720
+ var OUTLINED = /* @__PURE__ */ new Set(["box", "ellipse", "cloud", "cylinder", "diamond", "triangle", "pentagon", "hexagon", "parallelogram"]);
721
+ var TEXT_SIZES = ["s", "m", "l", "xl"];
722
+ var BRUSHES = ["pena", "spidol"];
723
+ var ROUTES = ["straight", "elbow", "curve", "auto"];
724
+ var MAX_LAYER = 9;
725
+ var COL_TYPES = ["text", "number", "money", "date", "select", "check"];
726
+ var NOTE_W = BOARD.note.w;
727
+ var NOTE_H = BOARD.note.h;
728
+ var GAP = BOARD.gap;
729
+ var PAD = BOARD.pad;
730
+ var HEAD = BOARD.head;
731
+ var MAX_NOTES = BOARD.maxNotes;
732
+ var MAX_ROWS = BOARD.maxRows;
733
+ var MAX_COLS = BOARD.maxCols;
734
+ var MAX_TEXT = BOARD.maxText;
735
+ function taskShape(b) {
736
+ const tab = b.tabs[0];
737
+ const lane = tab?.columns.find((c) => c.type === "select");
738
+ const title = tab?.columns.find((c) => c.type === "text" && !c.formula);
739
+ if (!tab || !lane || !title) return null;
740
+ return { tab, lane, title, lanes: lane.options ?? [], fields: tab.columns.filter((c) => c.id !== lane.id && c.id !== title.id) };
741
+ }
742
+ var noEmoji = (s) => s.replace(/[\p{Extended_Pictographic}\p{Regional_Indicator}\u{FE0F}\u{200D}]/gu, "").replace(/\s{2,}/g, " ").trim();
743
+ function validIcon(s) {
744
+ const t = s?.trim().toLowerCase();
745
+ return isIllustration(t) || isLineIcon(t) ? t : void 0;
746
+ }
747
+ var PENS = ["black", "blue", "green", "red", "purple", "orange"];
748
+ var uid = (prefix) => `${prefix}${Math.random().toString(36).slice(2, 8)}${Date.now().toString(36).slice(-3)}`;
749
+ var clampText = (s) => s.slice(0, MAX_TEXT);
750
+ var finite = (n2, d = 0) => typeof n2 === "number" && Number.isFinite(n2) ? Math.max(-BOARD.coordLimit, Math.min(BOARD.coordLimit, n2)) : d;
751
+ function frameAt(b, x, y) {
752
+ for (let i = b.frames.length - 1; i >= 0; i--) {
753
+ const f = b.frames[i];
754
+ if (x >= f.x && x <= f.x + f.w && y >= f.y && y <= f.y + f.h) return f.id;
755
+ }
756
+ return null;
757
+ }
758
+ function cellFor(col2, v) {
759
+ if (v === null || v === "") return null;
760
+ switch (col2.type) {
761
+ case "number":
762
+ case "money": {
763
+ const n2 = typeof v === "number" ? v : Number(String(v).replace(/\s/g, "").replace(/^Rp/i, "").replace(/\.(?=\d{3}(\D|$))/g, "").replace(",", "."));
764
+ return Number.isFinite(n2) ? n2 : null;
765
+ }
766
+ case "check":
767
+ return v === true || v === 1 || typeof v === "string" && ["true", "ya", "yes", "1", "x", "\u2713"].includes(v.trim().toLowerCase());
768
+ case "date":
769
+ return /^\d{4}-\d{2}-\d{2}/.test(String(v)) ? String(v).slice(0, 10) : null;
770
+ case "select":
771
+ return String(v).slice(0, LEN.label);
772
+ default:
773
+ return clampText(String(v));
774
+ }
775
+ }
776
+ var MARKS = ["text", "ink", "track", "pill", "dot", "cell", "sticker"];
777
+ function minSize(shape) {
778
+ return { ...MARKS.includes(shape) ? BOARD.minSize.mark : shape && OUTLINED.has(shape) ? BOARD.minSize.shape : BOARD.minSize.note };
779
+ }
780
+ function shapeFields(n2) {
781
+ const out = {};
782
+ if (n2.shape && SHAPES.includes(n2.shape) && n2.shape !== "note") out.shape = n2.shape;
783
+ if (n2.title) out.title = noEmoji(n2.title).slice(0, LEN.title);
784
+ if (n2.size && TEXT_SIZES.includes(n2.size)) out.size = n2.size;
785
+ const icon2 = validIcon(n2.icon);
786
+ if (icon2) out.icon = icon2;
787
+ if (n2.pen && PENS.includes(n2.pen)) out.pen = n2.pen;
788
+ if (n2.dashed === true) out.dashed = true;
789
+ if (Array.isArray(n2.points) && (n2.shape === "ink" || n2.shape === "track")) out.points = n2.points.slice(0, BOARD.maxInkPoints).map((v) => Math.round(finite(v) * 10) / 10);
790
+ if (n2.shape === "ink" && n2.brush && BRUSHES.includes(n2.brush)) out.brush = n2.brush;
791
+ if (n2.shape === "ink" && typeof n2.weight === "number" && Number.isFinite(n2.weight)) out.weight = Math.round(Math.min(BOARD.inkWeight.max, Math.max(BOARD.inkWeight.min, n2.weight)) * 10) / 10;
792
+ if (Array.isArray(n2.pressure) && n2.shape === "ink") out.pressure = n2.pressure.slice(0, BOARD.maxInkPoints / 2).map((v) => Math.round(Math.min(1, Math.max(0, finite(v))) * 100) / 100);
793
+ return out;
794
+ }
795
+ function linkFields(l) {
796
+ return {
797
+ ...l.label ? { label: l.label.slice(0, LEN.name) } : {},
798
+ ...l.route && ROUTES.includes(l.route) ? { route: l.route } : {},
799
+ ...l.dashed ? { dashed: true } : {},
800
+ ...l.arrow === "both" || l.arrow === "none" ? { arrow: l.arrow } : {},
801
+ ...typeof l.layer === "number" && l.layer >= 1 ? { layer: Math.min(MAX_LAYER, Math.round(l.layer)) } : {}
802
+ };
803
+ }
804
+ function applyOps(board2, ops, by, now = (/* @__PURE__ */ new Date()).toISOString()) {
805
+ const b = structuredClone(board2);
806
+ const tab = (id2) => b.tabs.find((t) => t.id === id2);
807
+ for (const o of ops) {
808
+ switch (o.op) {
809
+ case "title":
810
+ b.title = o.title.trim().slice(0, LEN.title) || b.title;
811
+ break;
812
+ case "note.add": {
813
+ if (b.notes.length >= MAX_NOTES || b.notes.some((n2) => n2.id === o.note.id)) break;
814
+ const x = finite(o.note.x), y = finite(o.note.y);
815
+ const color2 = NOTE_COLORS.includes(o.note.color) ? o.note.color : "yellow";
816
+ const min = minSize(o.note.shape);
817
+ b.notes.push({
818
+ id: o.note.id,
819
+ text: clampText(o.note.text),
820
+ x,
821
+ y,
822
+ w: Math.max(min.w, finite(o.note.w, NOTE_W) || NOTE_W),
823
+ h: Math.max(min.h, finite(o.note.h, NOTE_H) || NOTE_H),
824
+ color: color2,
825
+ frame: o.note.frame !== void 0 ? o.note.frame : frameAt(b, x + NOTE_W / 2, y + NOTE_H / 2),
826
+ ...o.note.owner ? { owner: o.note.owner.slice(0, LEN.label) } : {},
827
+ ...o.note.due ? { due: o.note.due.slice(0, LEN.id) } : {},
828
+ by,
829
+ ...shapeFields(o.note)
830
+ });
831
+ break;
832
+ }
833
+ case "note.update": {
834
+ const n2 = b.notes.find((x) => x.id === o.id);
835
+ if (!n2) break;
836
+ const p = o.patch;
837
+ if (p.text !== void 0) n2.text = clampText(p.text);
838
+ if (p.x !== void 0) n2.x = finite(p.x, n2.x);
839
+ if (p.y !== void 0) n2.y = finite(p.y, n2.y);
840
+ const min = minSize(p.shape ?? n2.shape);
841
+ if (p.w !== void 0) n2.w = Math.max(min.w, finite(p.w, n2.w));
842
+ if (p.h !== void 0) n2.h = Math.max(min.h, finite(p.h, n2.h));
843
+ Object.assign(n2, shapeFields({ ...n2, ...p }));
844
+ if (p.title === "") delete n2.title;
845
+ if (p.color && NOTE_COLORS.includes(p.color)) n2.color = p.color;
846
+ if (p.owner !== void 0) n2.owner = p.owner?.slice(0, LEN.label) || void 0;
847
+ if (p.due !== void 0) n2.due = p.due?.slice(0, LEN.id) || void 0;
848
+ if (p.frame !== void 0) n2.frame = p.frame && b.frames.some((f) => f.id === p.frame) ? p.frame : null;
849
+ else if (p.x !== void 0 || p.y !== void 0) n2.frame = frameAt(b, n2.x + n2.w / 2, n2.y + n2.h / 2);
850
+ break;
851
+ }
852
+ case "note.remove":
853
+ b.notes = b.notes.filter((n2) => n2.id !== o.id);
854
+ b.links = b.links.filter((l) => l.from !== o.id && l.to !== o.id);
855
+ break;
856
+ case "frame.add":
857
+ if (b.frames.some((f) => f.id === o.frame.id)) break;
858
+ b.frames.push({ id: o.frame.id, title: o.frame.title.slice(0, LEN.title), x: finite(o.frame.x), y: finite(o.frame.y), w: Math.max(BOARD.frame.min.w, finite(o.frame.w, BOARD.frame.default.w)), h: Math.max(BOARD.frame.min.h, finite(o.frame.h, BOARD.frame.default.h)), ...o.frame.subtitle ? { subtitle: o.frame.subtitle.slice(0, 200) } : {} });
859
+ break;
860
+ case "frame.update": {
861
+ const f = b.frames.find((x) => x.id === o.id);
862
+ if (!f) break;
863
+ if (o.patch.title !== void 0) f.title = o.patch.title.slice(0, LEN.title);
864
+ if (o.patch.x !== void 0) f.x = finite(o.patch.x, f.x);
865
+ if (o.patch.y !== void 0) f.y = finite(o.patch.y, f.y);
866
+ if (o.patch.w !== void 0) f.w = Math.max(BOARD.frame.min.w, finite(o.patch.w, f.w));
867
+ if (o.patch.h !== void 0) f.h = Math.max(BOARD.frame.min.h, finite(o.patch.h, f.h));
868
+ if (o.patch.subtitle !== void 0) {
869
+ if (o.patch.subtitle) f.subtitle = o.patch.subtitle.slice(0, LEN.line);
870
+ else delete f.subtitle;
871
+ }
872
+ break;
873
+ }
874
+ case "frame.move": {
875
+ const f = b.frames.find((x) => x.id === o.id);
876
+ if (!f) break;
877
+ const dx = finite(o.dx), dy = finite(o.dy);
878
+ f.x += dx;
879
+ f.y += dy;
880
+ for (const n2 of b.notes) if (n2.frame === f.id) {
881
+ n2.x += dx;
882
+ n2.y += dy;
883
+ }
884
+ break;
885
+ }
886
+ case "frame.remove":
887
+ b.frames = b.frames.filter((f) => f.id !== o.id);
888
+ b.notes = o.keepNotes === false ? b.notes.filter((n2) => n2.frame !== o.id) : b.notes.map((n2) => n2.frame === o.id ? { ...n2, frame: null } : n2);
889
+ break;
890
+ case "link.add":
891
+ if (b.links.length < BOARD.maxLinks && !b.links.some((l) => l.id === o.link.id) && [o.link.from, o.link.to].every((id2) => b.notes.some((n2) => n2.id === id2) || b.frames.some((f) => f.id === id2)))
892
+ b.links.push({ id: o.link.id, from: o.link.from, to: o.link.to, ...linkFields(o.link) });
893
+ break;
894
+ case "link.update": {
895
+ const l = b.links.find((x) => x.id === o.id);
896
+ if (!l) break;
897
+ Object.assign(l, linkFields({ ...l, ...o.patch }));
898
+ if (o.patch.label === "") delete l.label;
899
+ break;
900
+ }
901
+ case "link.remove":
902
+ b.links = b.links.filter((l) => l.id !== o.id);
903
+ break;
904
+ case "tab.add":
905
+ if (b.tabs.length < BOARD.maxTabs && !tab(o.tab.id)) b.tabs.push({ id: o.tab.id, name: o.tab.name.slice(0, LEN.name) || `Tab ${b.tabs.length + 1}`, columns: (o.tab.columns ?? []).slice(0, MAX_COLS), rows: [] });
906
+ break;
907
+ case "tab.rename": {
908
+ const t = tab(o.tab);
909
+ if (t) t.name = o.name.slice(0, LEN.name) || t.name;
910
+ break;
911
+ }
912
+ case "tab.remove":
913
+ if (b.tabs.length > 1) b.tabs = b.tabs.filter((t) => t.id !== o.tab);
914
+ break;
915
+ case "col.add": {
916
+ const t = tab(o.tab);
917
+ if (!t || t.columns.length >= MAX_COLS || t.columns.some((c2) => c2.id === o.col.id)) break;
918
+ const c = { ...o.col, name: o.col.name.slice(0, LEN.name), type: COL_TYPES.includes(o.col.type) ? o.col.type : "text" };
919
+ t.columns.splice(o.at ?? t.columns.length, 0, c);
920
+ break;
921
+ }
922
+ case "col.update": {
923
+ const c = tab(o.tab)?.columns.find((x) => x.id === o.id);
924
+ if (!c) break;
925
+ Object.assign(c, o.patch);
926
+ if (!COL_TYPES.includes(c.type)) c.type = "text";
927
+ c.name = c.name.slice(0, LEN.name);
928
+ break;
929
+ }
930
+ case "col.remove": {
931
+ const t = tab(o.tab);
932
+ if (!t) break;
933
+ t.columns = t.columns.filter((c) => c.id !== o.id);
934
+ for (const r of t.rows) delete r.cells[o.id];
935
+ break;
936
+ }
937
+ case "row.add": {
938
+ const t = tab(o.tab);
939
+ if (!t || t.rows.length >= MAX_ROWS || t.rows.some((r) => r.id === o.row.id)) break;
940
+ const cells = {};
941
+ for (const c of t.columns) if (o.row.cells[c.id] !== void 0 && !c.formula) cells[c.id] = cellFor(c, o.row.cells[c.id]);
942
+ t.rows.splice(o.at ?? t.rows.length, 0, { id: o.row.id, cells });
943
+ break;
944
+ }
945
+ case "row.remove": {
946
+ const t = tab(o.tab);
947
+ if (t) t.rows = t.rows.filter((r) => r.id !== o.id);
948
+ break;
949
+ }
950
+ case "restore": {
951
+ const to = structuredClone(o.to);
952
+ b.title = to.title;
953
+ b.frames = to.frames;
954
+ b.notes = to.notes;
955
+ b.links = to.links;
956
+ b.tabs = to.tabs;
957
+ break;
958
+ }
959
+ case "cell.set": {
960
+ const t = tab(o.tab);
961
+ const c = t?.columns.find((x) => x.id === o.col);
962
+ const r = t?.rows.find((x) => x.id === o.row);
963
+ if (c && r && !c.formula) r.cells[c.id] = cellFor(c, o.value);
964
+ break;
965
+ }
966
+ }
967
+ }
968
+ b.version = board2.version + 1;
969
+ b.updatedAt = now;
970
+ b.updatedBy = by;
971
+ return b;
972
+ }
973
+ function opKeys(ops) {
974
+ return ops.flatMap((o) => {
975
+ switch (o.op) {
976
+ case "note.add":
977
+ return [o.note.id];
978
+ case "note.update":
979
+ case "note.remove":
980
+ case "frame.update":
981
+ case "frame.move":
982
+ case "frame.remove":
983
+ case "link.remove":
984
+ case "link.update":
985
+ case "row.remove":
986
+ return [o.id];
987
+ case "frame.add":
988
+ return [o.frame.id];
989
+ case "cell.set":
990
+ return [`${o.row}:${o.col}`];
991
+ case "row.add":
992
+ return [o.row.id];
993
+ case "col.add":
994
+ return [o.col.id];
995
+ case "col.update":
996
+ case "col.remove":
997
+ return [o.id];
998
+ default:
999
+ return [];
1000
+ }
1001
+ });
1002
+ }
1003
+ var contentOf = (b) => structuredClone({ version: b.version, title: b.title, frames: b.frames, notes: b.notes, links: b.links, tabs: b.tabs });
1004
+ function historyOf(board2) {
1005
+ const from = board2.base?.version ?? Infinity;
1006
+ return board2.edits.flatMap((e) => e.version === void 0 ? [] : [{
1007
+ version: e.version,
1008
+ at: e.at,
1009
+ by: e.by,
1010
+ agent: e.agent,
1011
+ what: e.what,
1012
+ ...e.why ? { why: e.why } : {},
1013
+ keys: e.keys,
1014
+ replayable: !!e.ops && e.version > from,
1015
+ ...e.batch ? { batch: e.batch } : {},
1016
+ ...e.decided ? { decided: e.decided } : {},
1017
+ ...e.told ? { told: true } : {}
1018
+ }]);
1019
+ }
1020
+ var PLAN_KIND = { note: "card", box: "shape", ellipse: "shape", cloud: "shape", cylinder: "shape", diamond: "shape", triangle: "shape", pentagon: "shape", hexagon: "shape", parallelogram: "shape", text: "text", track: "track", pill: "pill", dot: "dot", cell: "cell", sticker: "sticker" };
1021
+ function planOf(ops, max = 200) {
1022
+ const out = [];
1023
+ for (const o of ops) {
1024
+ if (out.length >= max) break;
1025
+ if (o.op === "frame.add") out.push({ id: o.frame.id, kind: "frame", x: o.frame.x, y: o.frame.y, w: o.frame.w ?? NOTE_W, h: o.frame.h ?? NOTE_H });
1026
+ else if (o.op === "note.add" && o.note.shape !== "ink") {
1027
+ const k = PLAN_KIND[o.note.shape ?? "note"];
1028
+ if (k) out.push({ id: o.note.id, kind: k, x: o.note.x, y: o.note.y, w: o.note.w ?? NOTE_W, h: o.note.h ?? NOTE_H });
1029
+ }
1030
+ }
1031
+ return out;
1032
+ }
1033
+ function pendingBatchOf(board2) {
1034
+ const last = [...board2.edits].reverse().find((e) => e.agent && e.batch);
1035
+ if (!last?.batch) return null;
1036
+ const mine = board2.edits.filter((e) => e.batch === last.batch);
1037
+ if (mine.some((e) => e.decided)) return null;
1038
+ const first = mine[0];
1039
+ return { id: last.batch, by: first.by, what: first.what, ...first.why ? { why: first.why } : {}, keys: [...new Set(mine.flatMap((e) => e.keys))].slice(0, 400), at: last.at };
1040
+ }
1041
+ function boardAt(board2, version) {
1042
+ if (version === board2.version) return board2;
1043
+ const base = board2.base;
1044
+ if (!base || version < base.version || version > board2.version) return null;
1045
+ let b = { ...structuredClone(board2), ...structuredClone(base), activity: void 0 };
1046
+ for (const e of board2.edits) {
1047
+ if (e.version === void 0 || e.version <= base.version) continue;
1048
+ if (e.version > version) break;
1049
+ if (!e.ops || e.version !== b.version + 1) return null;
1050
+ b = applyOps(b, e.ops, e.by, e.at);
1051
+ }
1052
+ return b.version === version ? b : null;
1053
+ }
1054
+ function foldIntoBase(base, e, shell) {
1055
+ if (e.version === void 0 || e.version <= base.version || !e.ops) return base;
1056
+ return contentOf(applyOps({ ...shell, ...structuredClone(base) }, e.ops, e.by, e.at));
1057
+ }
1058
+ var CARD_SHAPES = /* @__PURE__ */ new Set([void 0, "note", ...OUTLINED]);
1059
+ function stepsOf(ops, perStep = 6) {
1060
+ const frame = [], road = [], marks = [], cards = [], changes = [], links = [], stickers = [];
1061
+ for (const o of ops) {
1062
+ if (o.op === "frame.add" || o.op === "title") frame.push(o);
1063
+ else if (o.op === "link.add") links.push(o);
1064
+ else if (o.op !== "note.add") changes.push(o);
1065
+ else if (o.note.shape === "text" || o.note.shape === "cell") frame.push(o);
1066
+ else if (o.note.shape === "track") road.push(o);
1067
+ else if (o.note.shape === "pill" || o.note.shape === "dot") marks.push(o);
1068
+ else if (o.note.shape === "sticker") stickers.push(o);
1069
+ else if (CARD_SHAPES.has(o.note.shape)) cards.push(o);
1070
+ else changes.push(o);
1071
+ }
1072
+ const along = road.length > 0;
1073
+ cards.sort((a, b) => along ? a.note.x - b.note.x : Math.round(a.note.y / 40) - Math.round(b.note.y / 40) || a.note.x - b.note.x);
1074
+ const steps = [];
1075
+ if (frame.length) steps.push({ kind: "frame", ops: frame });
1076
+ if (road.length) steps.push({ kind: "road", ops: road });
1077
+ if (marks.length) steps.push({ kind: "marks", ops: marks });
1078
+ for (let i = 0; i < cards.length; i += Math.max(1, perStep)) steps.push({ kind: "cards", ops: cards.slice(i, i + Math.max(1, perStep)) });
1079
+ if (changes.length) steps.push({ kind: "changes", ops: changes });
1080
+ if (links.length) steps.push({ kind: "links", ops: links });
1081
+ if (stickers.length) steps.push({ kind: "stickers", ops: stickers });
1082
+ return steps.length ? steps : [{ kind: "changes", ops }];
1083
+ }
1084
+ var MEANING = [
1085
+ [/baik|berhasil|sukses|lancar|good|well|win|keep/i, "green"],
1086
+ [/kendala|masalah|hambatan|gagal|problem|issue|obstacle|block|challenge/i, "pink"],
1087
+ [/peluang|ide|usul|perbaik|opportunit|idea|improve|try/i, "blue"],
1088
+ [/risiko|bahaya|ancaman|risk|concern|threat/i, "purple"]
1089
+ ];
1090
+ var colorFor = (title, fallback2) => MEANING.find(([re]) => re.test(title))?.[1] ?? fallback2;
1091
+ var DRH = BOARD.draw.heading;
1092
+ function headingOps(ops, h, x, y, id2 = () => uid("n")) {
1093
+ const top = y;
1094
+ const lines2 = Math.max(1, Math.ceil(h.title.length * DRH.titleCharW / DRH.w));
1095
+ ops.push({ op: "note.add", note: { id: id2(), shape: "text", size: "xl", text: noEmoji(h.title).slice(0, LEN.line), x, y, w: DRH.w, h: DRH.h * lines2, color: "paper", frame: null } });
1096
+ let right = x + DRH.w;
1097
+ let subW = DRH.w;
1098
+ const icon2 = validIcon(h.icon);
1099
+ if (icon2) {
1100
+ const sx = x + Math.min(DRH.w, h.title.length * DRH.titleCharW) + DRH.stickerGap;
1101
+ subW = Math.min(DRH.w, sx - x - DRH.stickerGap / 2);
1102
+ ops.push({ op: "note.add", note: { id: id2(), shape: "sticker", icon: icon2, text: "", x: sx, y: y - BOARD.draw.sticker.h / 4, w: BOARD.draw.sticker.w, h: BOARD.draw.sticker.h, color: "paper", frame: null } });
1103
+ right = Math.max(right, sx + BOARD.draw.sticker.w);
1104
+ }
1105
+ y += DRH.step + (lines2 - 1) * DRH.h;
1106
+ if (h.subtitle) {
1107
+ ops.push({ op: "note.add", note: { id: id2(), shape: "text", size: "m", color: "gray", text: noEmoji(h.subtitle).slice(0, LEN.message), x, y, w: subW, h: DRH.subH * (subW < DRH.w ? 2 : 1), frame: null } });
1108
+ y += DRH.subStep + (subW < DRH.w ? DRH.subH : 0);
1109
+ }
1110
+ return { h: y - top + DRH.titleRoom, right };
1111
+ }
1112
+ var STICKY = BOARD.sticky;
1113
+ function layoutOps(sections, layout, origin = { x: 0, y: 0 }, palette = ["yellow", "blue", "green", "pink", "purple"], heading2) {
1114
+ const ops = [];
1115
+ const frameIds = [];
1116
+ const perRow = layout === "grid" ? Math.min(BOARD.gridSectionsPerRow, Math.max(1, Math.ceil(Math.sqrt(sections.length)))) : sections.length;
1117
+ const inner = layout === "grid" ? BOARD.gridNotesPerRow : 1;
1118
+ const fw = PAD * 2 + inner * STICKY.w + (inner - 1) * GAP;
1119
+ const top = heading2 ? headingOps(ops, heading2, origin.x, origin.y).h : 0;
1120
+ let x = origin.x, y = origin.y + top, rowH = 0;
1121
+ sections.forEach((s, i) => {
1122
+ if (i > 0 && i % perRow === 0) {
1123
+ x = origin.x;
1124
+ y += rowH + GAP * 2;
1125
+ rowH = 0;
1126
+ }
1127
+ const lines2 = Math.max(1, Math.ceil(s.notes.length / inner));
1128
+ const head = HEAD + (s.subtitle ? BOARD.draw.heading.subH : 0);
1129
+ const textW = STICKY.w - STICKY.pad;
1130
+ const noteH = (n2) => Math.max(STICKY.h, STICKY.top + wrapLines(n2.title ? noEmoji(n2.title) : "", STICKY.titleCharW, textW) * STICKY.titleLh + wrapLines(noEmoji(n2.text), STICKY.charW, textW) * STICKY.lh + STICKY.byH);
1131
+ const noteRows = Array.from({ length: lines2 }, (_, r) => Math.max(...s.notes.slice(r * inner, r * inner + inner).map(noteH), STICKY.h));
1132
+ const rowY = noteRows.map((_, r) => noteRows.slice(0, r).reduce((t, v) => t + v + GAP, 0));
1133
+ const fh = head + PAD + noteRows.reduce((t, v) => t + v, 0) + (lines2 - 1) * GAP + PAD;
1134
+ const fid = uid("f");
1135
+ frameIds.push(fid);
1136
+ ops.push({ op: "frame.add", frame: { id: fid, title: s.title, ...s.subtitle ? { subtitle: s.subtitle } : {}, x, y, w: fw, h: fh } });
1137
+ const color2 = colorFor(s.title, palette[i % palette.length]);
1138
+ s.notes.forEach((n2, k) => {
1139
+ const icon2 = validIcon(n2.icon);
1140
+ ops.push({ op: "note.add", note: {
1141
+ id: uid("n"),
1142
+ text: noEmoji(n2.text),
1143
+ ...n2.title ? { title: noEmoji(n2.title) } : {},
1144
+ ...icon2 ? { icon: icon2 } : {},
1145
+ size: "m",
1146
+ x: x + PAD + k % inner * (STICKY.w + GAP),
1147
+ y: y + head + rowY[Math.floor(k / inner)],
1148
+ w: STICKY.w,
1149
+ h: noteRows[Math.floor(k / inner)],
1150
+ color: n2.color ?? color2,
1151
+ frame: fid,
1152
+ ...n2.owner ? { owner: n2.owner } : {},
1153
+ ...n2.due ? { due: n2.due } : {}
1154
+ } });
1155
+ });
1156
+ if (layout === "timeline" && i > 0) ops.push({ op: "link.add", link: { id: uid("l"), from: frameIds[i - 1], to: fid } });
1157
+ x += fw + GAP * 2;
1158
+ rowH = Math.max(rowH, fh);
1159
+ });
1160
+ return { ops, frameIds };
1161
+ }
1162
+ function nextOrigin(b) {
1163
+ const right = Math.max(0, ...b.frames.map((f) => f.x + f.w), ...b.notes.map((n2) => n2.x + n2.w));
1164
+ const top = Math.min(0, ...b.frames.map((f) => f.y), ...b.notes.map((n2) => n2.y));
1165
+ return b.frames.length || b.notes.length ? { x: right + GAP * 4, y: top } : { x: 0, y: 0 };
1166
+ }
1167
+ var STRUCTURE = ["track", "pill", "dot", "cell", "sticker"];
1168
+ function tidyOps(b) {
1169
+ const ops = [];
1170
+ for (const f of b.frames) {
1171
+ const notes = b.notes.filter((n2) => n2.frame === f.id);
1172
+ if (notes.some((n2) => STRUCTURE.includes(n2.shape))) continue;
1173
+ const nw = Math.max(NOTE_W, ...notes.map((n2) => n2.w)), nh = Math.max(NOTE_H, ...notes.map((n2) => n2.h));
1174
+ const head = HEAD + (f.subtitle ? BOARD.draw.heading.subH : 0);
1175
+ const inner = Math.max(1, Math.floor((f.w - PAD * 2 + GAP) / (nw + GAP)));
1176
+ notes.forEach((n2, k) => ops.push({ op: "note.update", id: n2.id, patch: { x: f.x + PAD + k % inner * (nw + GAP), y: f.y + head + Math.floor(k / inner) * (nh + GAP), frame: f.id } }));
1177
+ const lines2 = Math.max(1, Math.ceil(notes.length / inner));
1178
+ ops.push({ op: "frame.update", id: f.id, patch: { h: head + PAD + lines2 * nh + (lines2 - 1) * GAP + PAD } });
1179
+ }
1180
+ return ops;
1181
+ }
1182
+ function tokens(src) {
1183
+ const out = [];
1184
+ let i = 0;
1185
+ while (i < src.length) {
1186
+ const ch = src[i];
1187
+ if (/\s/.test(ch)) {
1188
+ i++;
1189
+ continue;
1190
+ }
1191
+ if (ch === "{") {
1192
+ const j = src.indexOf("}", i);
1193
+ if (j < 0) return null;
1194
+ out.push({ t: "ref", v: src.slice(i + 1, j).trim() });
1195
+ i = j + 1;
1196
+ continue;
1197
+ }
1198
+ if ("+-*/()".includes(ch)) {
1199
+ out.push({ t: "op", v: ch });
1200
+ i++;
1201
+ continue;
1202
+ }
1203
+ const m = /^\d+(\.\d+)?/.exec(src.slice(i));
1204
+ if (m) {
1205
+ out.push({ t: "num", v: Number(m[0]) });
1206
+ i += m[0].length;
1207
+ continue;
1208
+ }
1209
+ return null;
1210
+ }
1211
+ return out;
1212
+ }
1213
+ function evalFormula(src, value) {
1214
+ const toks = tokens(src);
1215
+ if (!toks?.length) return null;
1216
+ let p = 0;
1217
+ const peek = () => toks[p];
1218
+ const expr = () => {
1219
+ let l = term();
1220
+ while (l !== null && peek()?.t === "op" && (peek().v === "+" || peek().v === "-")) {
1221
+ const op = toks[p++].v;
1222
+ const r = term();
1223
+ if (r === null) return null;
1224
+ l = op === "+" ? l + r : l - r;
1225
+ }
1226
+ return l;
1227
+ };
1228
+ const term = () => {
1229
+ let l = factor();
1230
+ while (l !== null && peek()?.t === "op" && (peek().v === "*" || peek().v === "/")) {
1231
+ const op = toks[p++].v;
1232
+ const r = factor();
1233
+ if (r === null || op === "/" && r === 0) return null;
1234
+ l = op === "*" ? l * r : l / r;
1235
+ }
1236
+ return l;
1237
+ };
1238
+ const factor = () => {
1239
+ const t = toks[p++];
1240
+ if (!t) return null;
1241
+ if (t.t === "num") return t.v;
1242
+ if (t.t === "ref") return value(t.v);
1243
+ if (t.v === "-") {
1244
+ const v2 = factor();
1245
+ return v2 === null ? null : -v2;
1246
+ }
1247
+ if (t.v === "(") {
1248
+ const v2 = expr();
1249
+ if (toks[p++]?.v !== ")") return null;
1250
+ return v2;
1251
+ }
1252
+ return null;
1253
+ };
1254
+ const v = expr();
1255
+ return p === toks.length && v !== null && Number.isFinite(v) ? Math.round(v * 1e6) / 1e6 : null;
1256
+ }
1257
+ var num = (v) => typeof v === "number" ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : null;
1258
+ function cellValue(t, r, c, seen = /* @__PURE__ */ new Set()) {
1259
+ if (!c.formula) return r.cells[c.id] ?? null;
1260
+ if (seen.has(c.id)) return null;
1261
+ seen.add(c.id);
1262
+ const byName = new Map(t.columns.map((x) => [x.name.toLowerCase(), x]));
1263
+ return evalFormula(c.formula, (name) => {
1264
+ const ref = byName.get(name.toLowerCase());
1265
+ return ref ? num(cellValue(t, r, ref, new Set(seen))) : null;
1266
+ });
1267
+ }
1268
+ function tabRows(t) {
1269
+ return { columns: t.columns, rows: t.rows.map((r) => t.columns.map((c) => cellValue(t, r, c))) };
1270
+ }
1271
+ function boardText(b, only, maxRows = BOARD.textRows) {
1272
+ const tasks = b.mode === "tasks" ? taskShape(b) : null;
1273
+ if (tasks) {
1274
+ const { tab, lane, title, lanes, fields } = tasks;
1275
+ const inLane = (l, first) => tab.rows.filter((r) => r.cells[lane.id] === l || first && !lanes.includes(String(r.cells[lane.id])));
1276
+ const card = (r) => `- ${r.id} (#${tab.rows.indexOf(r) + 1}): ${String(r.cells[title.id] ?? "")}${fields.map((f) => r.cells[f.id] === null || r.cells[f.id] === void 0 || r.cells[f.id] === "" ? "" : `; ${f.name}: ${String(r.cells[f.id])}`).join("")}`;
1277
+ return `Lane field "${lane.name}"; lanes in order: ${lanes.join(", ")}
1278
+ ${lanes.map((l, k) => {
1279
+ const cs = inLane(l, k === 0);
1280
+ return `Lane "${l}" (${cs.length})${cs.length ? `
1281
+ ${cs.slice(0, maxRows).map(card).join("\n")}` : ""}`;
1282
+ }).join("\n")}`;
1283
+ }
1284
+ if (b.mode === "sheet" || b.mode === "tasks") {
1285
+ return b.tabs.map((t) => {
1286
+ const { columns, rows } = tabRows(t);
1287
+ const head = columns.map((c) => `${c.name}${c.formula ? ` (=${c.formula})` : ""} [${c.type}] id=${c.id}`).join(" | ");
1288
+ const body2 = rows.slice(0, maxRows).map((r, i) => `${t.rows[i].id}: ${r.map((v) => v === null ? "" : String(v)).join(" | ")}`).join("\n");
1289
+ return `Tab "${t.name}" id=${t.id}, ${t.rows.length} baris
1290
+ Kolom: ${head}
1291
+ ${body2}${t.rows.length > maxRows ? ERR.nBarisLagi(t.rows.length - maxRows) : ""}`;
1292
+ }).join("\n\n");
1293
+ }
1294
+ const drawing = (n2) => n2.shape === "track" || n2.shape === "dot" || n2.shape === "cell" && !n2.text;
1295
+ const pick = (id2) => !only || only.has(id2);
1296
+ const line = (n2) => `- ${n2.id}${n2.shape && n2.shape !== "note" ? ` [${n2.shape}${n2.color === "ink" || n2.color === "red" ? `, ${n2.color}` : ""}]` : ""}: ${n2.icon ? `(${n2.icon}) ` : ""}${n2.title ? `${n2.title}: ` : ""}${n2.text.replace(/\n/g, " ")}${n2.owner ? ` (PJ ${n2.owner})` : ""}${n2.due ? ` (tenggat ${n2.due})` : ""} [oleh ${n2.by}]`;
1297
+ const parts = b.frames.filter((f) => pick(f.id) || b.notes.some((n2) => n2.frame === f.id && pick(n2.id))).map((f) => {
1298
+ const ns = b.notes.filter((n2) => n2.frame === f.id && !drawing(n2) && (pick(n2.id) || pick(f.id)));
1299
+ return `Bagian "${f.title}"${f.subtitle ? ` (${f.subtitle})` : ""} id=${f.id}
1300
+ ${ns.map(line).join("\n") || "(kosong)"}`;
1301
+ });
1302
+ const loose = b.notes.filter((n2) => !n2.frame && !drawing(n2) && pick(n2.id));
1303
+ if (loose.length) parts.push(ERR.luarBagianN(loose.map(line).join("\n")));
1304
+ const name = (id2) => b.frames.find((f) => f.id === id2)?.title ?? b.notes.find((n2) => n2.id === id2)?.text.slice(0, LEN.id) ?? id2;
1305
+ const arrows = b.links.filter((l) => !only || only.has(l.from) || only.has(l.to));
1306
+ if (arrows.length) parts.push(`Panah
1307
+ ${arrows.map((l) => `- ${l.id}: ${l.from} "${name(l.from)}" \u2192 ${l.to} "${name(l.to)}"${l.label ? ` (${l.label})` : ""}${l.route === "straight" ? " lurus" : ""}${l.dashed ? " putus-putus" : ""}`).join("\n")}`);
1308
+ return parts.join("\n\n") || "(empty board)";
1309
+ }
1310
+ var DR = BOARD.draw;
1311
+ var D_PAD = DR.pad;
1312
+ var HEAD_H = DR.head;
1313
+ var GAP_X = DR.gapX;
1314
+ var GAP_Y = DR.gapY;
1315
+ var SECTION_GAP = DR.sectionGap;
1316
+ var ITEM = DR.item;
1317
+ var DIAGRAM_GAP = DR.diagramGap;
1318
+ function fitH(it, w, base) {
1319
+ const chars = (it.title ? it.title.length + 2 : 0) + (it.text?.length ?? 0);
1320
+ const lines2 = Math.ceil(chars * DR.fit.charW / Math.max(DR.fit.minLineW, w - DR.fit.inset));
1321
+ return Math.max(base, DR.fit.base + lines2 * DR.fit.lineH + (it.title && it.text ? DR.fit.titleGap : 0));
1322
+ }
1323
+ var STK = DR.sticker;
1324
+ var stickerH = (it) => STK.h + (it.text ? STK.captionH : 0);
1325
+ var cardH = (it, w, base) => fitH(it, w, base) + (validIcon(it.icon) ? DR.iconCard.extraH : 0);
1326
+ function itemNote(it, id2, shape, color2, x, y, w, h, frame) {
1327
+ const icon2 = validIcon(it.icon);
1328
+ return { op: "note.add", note: {
1329
+ id: id2,
1330
+ shape,
1331
+ text: noEmoji(it.text ?? "").slice(0, MAX_TEXT),
1332
+ ...it.title ? { title: noEmoji(it.title) } : {},
1333
+ ...icon2 ? { icon: icon2 } : {},
1334
+ ...it.size ? { size: it.size } : {},
1335
+ color: color2,
1336
+ x,
1337
+ y,
1338
+ w,
1339
+ h,
1340
+ frame,
1341
+ ...it.pen ? { pen: it.pen } : {},
1342
+ ...it.dashed ? { dashed: true } : {},
1343
+ ...it.owner ? { owner: it.owner } : {},
1344
+ ...it.due ? { due: it.due } : {}
1345
+ } };
1346
+ }
1347
+ var TL = DR.timeline;
1348
+ var WARM = ["sand", "peach", "orange", "yellow"];
1349
+ function extendTimelineOps(b, items, trackId, ids = () => uid("n")) {
1350
+ const roads = b.notes.filter((n2) => n2.shape === "track");
1351
+ const track = (trackId ? roads.find((n2) => n2.id === trackId) : null) ?? roads.at(-1);
1352
+ if (!track || !items.length) return null;
1353
+ const base = ITEM.timeline;
1354
+ const period = TL.step * TL.waveSteps;
1355
+ const road = track.y + TL.amp + TL.trackPad;
1356
+ const wave = (rel) => road + TL.amp * Math.sin(2 * Math.PI * rel / period);
1357
+ const along = (n2) => n2.x + n2.w / 2 - track.x;
1358
+ const onRoad = b.notes.filter((n2) => (n2.shape === "pill" || n2.shape === "sticker") && along(n2) >= 0 && along(n2) <= track.w + base.w && Math.abs(n2.y + n2.h / 2 - road) <= TL.amp + base.h);
1359
+ const index = (rel) => Math.round((rel - TL.lead - base.w / 2) / TL.step);
1360
+ let next = onRoad.length ? Math.max(...onRoad.map((n2) => index(along(n2)))) + 1 : 0;
1361
+ let cards = onRoad.filter((n2) => n2.shape === "pill").length;
1362
+ let prevPill = onRoad.filter((n2) => n2.shape === "pill").reduce((m, n2) => m === null || along(n2) > m ? along(n2) : m, null);
1363
+ const cx = (i) => TL.lead + base.w / 2 + i * TL.step;
1364
+ const ops = [];
1365
+ const keys = {};
1366
+ for (const it of items) {
1367
+ const x = cx(next), yc = wave(x);
1368
+ next += 1;
1369
+ if (it.shape === "sticker") {
1370
+ const id3 = ids();
1371
+ if (it.key) keys[it.key] = id3;
1372
+ ops.push(itemNote(it, id3, "sticker", "paper", track.x + x - STK.w / 2, yc - STK.h + TL.trackPad, STK.w, stickerH(it), null));
1373
+ continue;
1374
+ }
1375
+ if (prevPill !== null) {
1376
+ const mx = (prevPill + x) / 2;
1377
+ ops.push({ op: "note.add", note: { id: ids(), shape: "dot", text: "", x: track.x + mx - TL.dot.w / 2, y: wave(mx) - TL.dot.h / 2, w: TL.dot.w, h: TL.dot.h, color: "paper", frame: null } });
1378
+ }
1379
+ prevPill = x;
1380
+ const pill = ids();
1381
+ ops.push({ op: "note.add", note: { id: pill, shape: "pill", text: (it.when ?? String(cards + 1)).slice(0, LEN.label), x: track.x + x - TL.pill.w / 2, y: yc - TL.pill.h / 2, w: TL.pill.w, h: TL.pill.h, color: "red", frame: null } });
1382
+ const hgt = cardH(it, base.w, base.h);
1383
+ const top = cards % 2 === 0 ? road - TL.amp - TL.cardGap - hgt : road + TL.amp + TL.cardGap;
1384
+ const id2 = ids();
1385
+ if (it.key) keys[it.key] = id2;
1386
+ ops.push(itemNote(it, id2, it.shape ?? "note", it.color ?? WARM[cards % WARM.length], track.x + x - base.w / 2, top, base.w, hgt, null));
1387
+ ops.push({ op: "link.add", link: { id: uid("l"), from: id2, to: pill, route: "straight", arrow: "none" } });
1388
+ cards++;
1389
+ }
1390
+ const width = cx(next - 1) + base.w / 2 + TL.lead;
1391
+ if (width > track.w) {
1392
+ const ty = track.y;
1393
+ const points = [];
1394
+ for (let x = 0; x <= width; x += TL.sample) points.push(Math.round(x * 10) / 10, Math.round((wave(x) - ty) * 10) / 10);
1395
+ points.push(Math.round(width * 10) / 10, Math.round((wave(width) - ty) * 10) / 10);
1396
+ ops.unshift({ op: "note.update", id: track.id, patch: { w: width, points } });
1397
+ }
1398
+ return { ops, keys };
1399
+ }
1400
+ var MX = DR.matrix;
1401
+
1402
+ // src/core/agent.ts
1403
+ import { z as z2 } from "zod";
1404
+ import { zodToJsonSchema } from "zod-to-json-schema";
1405
+
1406
+ // src/core/free-board.ts
1407
+ var SK = BOARD.draw.sketch;
1408
+ var T = BOARD.draw.tell;
1409
+ var TONES = ["fact", "problem", "action", "insight", "person", "system"];
1410
+ var FORMS = ["rect", "square", "circle", "ellipse", "diamond", "triangle", "pentagon", "hexagon", "parallelogram", "cylinder", "cloud", "pill", "sticky", "text"];
1411
+ var PEN = { fact: "black", problem: "red", action: "green", insight: "purple", person: "blue", system: "orange" };
1412
+ var SHAPE = {
1413
+ rect: "box",
1414
+ square: "box",
1415
+ circle: "ellipse",
1416
+ ellipse: "ellipse",
1417
+ diamond: "diamond",
1418
+ triangle: "triangle",
1419
+ pentagon: "pentagon",
1420
+ hexagon: "hexagon",
1421
+ parallelogram: "parallelogram",
1422
+ cylinder: "cylinder",
1423
+ cloud: "cloud",
1424
+ pill: "pill",
1425
+ sticky: "note",
1426
+ text: "text"
1427
+ };
1428
+ var round = (n2) => Math.round(n2);
1429
+ var LABEL_CHAR = 19 * SK.lower * SK.wrapSlack;
1430
+ var wireLabel = (s) => labelSize(s, LABEL_CHAR);
1431
+ var lines = (s, size, upper, w) => wrapLines(s, size * (upper ? SK.upper : SK.lower) * SK.wrapSlack, w);
1432
+ function blockHeight(title, text, icon2, size, w, shape = "box") {
1433
+ const t = SK.block[size];
1434
+ const poly = isPolygon(shape) ? POLYGONS[shape].inset : null;
1435
+ const roundish = shape === "ellipse" || shape === "cloud";
1436
+ const inner = poly ? w * (1 - poly[1] - poly[3]) - SK.pad * 2 : (w - SK.pad * 2) * (roundish ? SK.roundInner : 1);
1437
+ const body2 = (validIcon(icon2) ? t.icon + 6 : 0) + lines(title, t.title, true, inner) * t.titleLh + lines(text, t.text, false, inner) * t.textLh;
1438
+ if (poly) return round((body2 + SK.pad * 2) / (1 - poly[0] - poly[2]));
1439
+ return round((body2 + SK.pad * 2) / (roundish ? SK.roundInner : 1)) + (shape === "cylinder" ? 28 : 0);
1440
+ }
1441
+ var noteHeight = (text, w) => T.noteTop + Math.max(1, wrapLines(text, T.noteChar, w - T.notePad)) * T.noteLh;
1442
+ function body(n2) {
1443
+ const qa2 = [["Why", n2.why], ["Who", n2.who], ["When", n2.when], ["Where", n2.where], ["How", n2.how], ["How much", n2.howMuch], ["Assumes", n2.assumes]];
1444
+ return [n2.text, ...qa2.filter(([, v]) => v).map(([k, v]) => `${k}: ${v}`)].filter(Boolean).map((s) => noEmoji(s)).join("\n").slice(0, BOARD.maxText);
1445
+ }
1446
+ var obstacles = (notes) => new Map(notes.filter((n2) => n2.shape !== "ink" && n2.shape !== "track").map((n2) => [n2.id, { x: n2.x, y: n2.y, w: n2.w, h: n2.h, ...n2.shape ? { shape: n2.shape } : {} }]));
1447
+ var autoWires = (links) => links.filter((l) => l.route === "auto");
1448
+ function sizeOf(it, shape, form, size, text) {
1449
+ const title = it.title ? noEmoji(it.title) : void 0;
1450
+ if (form === "sticky") {
1451
+ const w2 = Math.min(T.noteMaxW, it.w ?? T.noteW);
1452
+ return { w: w2, h: noteHeight([title, text].filter(Boolean).join("\n"), w2) };
1453
+ }
1454
+ if (form === "pill") {
1455
+ const t = SK.words[size], label = title ?? "";
1456
+ return { w: Math.max(T.minTextW, round(label.length * t.size * SK.upper * SK.wrapSlack) + 40), h: SK.pillH };
1457
+ }
1458
+ if (form === "text") {
1459
+ const t = SK.words[size], words = [title, text].filter(Boolean).join("\n");
1460
+ const w2 = it.w ?? Math.min(T.widths.xl * 2, round(Math.max(...words.split("\n").map((l) => l.length)) * t.size * (t.upper ? SK.upper : SK.lower) * SK.wrapSlack) + 8);
1461
+ return { w: w2, h: lines(words, t.size, t.upper, w2) * t.lh + 4 };
1462
+ }
1463
+ let w = Math.max(T.minTextW, it.w ?? T.widths[size]);
1464
+ if (form === "square" || form === "circle") {
1465
+ for (let i = 0; i < 16; i++) {
1466
+ const h = blockHeight(title, text, it.icon, size, w, shape);
1467
+ if (h <= w) break;
1468
+ w = round((w + h) / 2) + 8;
1469
+ }
1470
+ return { w, h: w };
1471
+ }
1472
+ const min = isPolygon(shape) ? T.minAspect[shape] * w : 0;
1473
+ return { w, h: Math.max(round(min), it.h ?? 0, blockHeight(title, text, it.icon, size, w, shape)) };
1474
+ }
1475
+ function layFree(story, origin = { x: 0, y: 0 }, board2, ids = () => uid("n")) {
1476
+ const steps = [];
1477
+ const skipped = [];
1478
+ const notes = [...board2?.notes ?? []];
1479
+ const links = [...board2?.links ?? []];
1480
+ const add = (ops, n2) => {
1481
+ const min = minSize(n2.shape);
1482
+ const sized = { ...n2, w: Math.max(min.w, n2.w), h: Math.max(min.h, n2.h) };
1483
+ ops.push({ op: "note.add", note: sized });
1484
+ notes.push(sized);
1485
+ };
1486
+ const H = SK.headline, head = [];
1487
+ const title = noEmoji(story.headline).slice(0, LEN.line);
1488
+ const titleW = Math.min(H.w, round(title.length * SK.words.xl.size * SK.upper * SK.wrapSlack) + 8);
1489
+ const titleH = lines(title, SK.words.xl.size, true, titleW) * SK.words.xl.lh + 4;
1490
+ add(head, { id: ids(), shape: "text", size: "xl", pen: "black", text: title, color: "paper", x: origin.x, y: origin.y, w: titleW, h: titleH, frame: null });
1491
+ const icon2 = validIcon(story.icon);
1492
+ if (icon2) add(head, { id: ids(), shape: "sticker", icon: icon2, text: "", color: "paper", x: origin.x + titleW + H.iconGap, y: origin.y - 8, w: H.icon, h: H.icon, frame: null });
1493
+ let y = origin.y + titleH + H.gapBelow;
1494
+ const items = story.beats.flatMap((b) => b.items ?? []);
1495
+ const used = new Set(items.map((n2) => n2.tone ?? "fact"));
1496
+ const deep = items.some((n2) => (n2.layer ?? 0) > 0);
1497
+ const legend = [...TONES.filter((t) => used.has(t)).map((t) => T.legend[t]), T.legend.note, ...deep ? [T.legend.wires] : []].join(" \xB7 ");
1498
+ for (const text of [story.context ? noEmoji(story.context).slice(0, LEN.message) : "", legend]) {
1499
+ if (!text) continue;
1500
+ const h = lines(text, SK.words.s.size, false, H.contextW) * SK.words.s.lh + 4;
1501
+ add(head, { id: ids(), shape: "text", size: "s", pen: "black", text, color: "paper", x: origin.x, y, w: H.contextW, h, frame: null });
1502
+ y += h + 6;
1503
+ }
1504
+ steps.push({ say: title, ops: head });
1505
+ const ox = origin.x, oy = y + T.below;
1506
+ const byKey = /* @__PURE__ */ new Map();
1507
+ const layerOf = /* @__PURE__ */ new Map();
1508
+ const derived = items.every((n2) => n2.layer === void 0) ? depthByWires(story.beats) : null;
1509
+ let routed = route(notes, links);
1510
+ const taken = () => [...obstacles(notes).values(), ...routed.wires, ...routed.labels];
1511
+ const sticky = (ops, text, near) => {
1512
+ const min = minSize(void 0), h = Math.max(min.h, noteHeight(text, T.noteW)), w = Math.max(min.w, T.noteW), g = T.noteGap;
1513
+ const tries = [{ x: near.x, y: near.y - h - g, w, h }, { x: near.x, y: near.y + near.h + g, w, h }, { x: near.x + near.w + g, y: near.y, w, h }, { x: near.x - w - g, y: near.y, w, h }];
1514
+ const all = taken();
1515
+ const spot = tries.find((b) => !overlaps(b, all, 8)) ?? freeSpot(tries[0], all, 8);
1516
+ add(ops, { id: ids(), text, color: "yellow", x: spot.x, y: spot.y, w, h, frame: null });
1517
+ };
1518
+ for (const beat of story.beats) {
1519
+ const ops = [];
1520
+ const say = noEmoji(beat.say).slice(0, LEN.message);
1521
+ const drawn = [];
1522
+ for (const it of (beat.items ?? []).slice(0, T.maxItems)) {
1523
+ if (byKey.has(it.key)) {
1524
+ skipped.push(it.key);
1525
+ continue;
1526
+ }
1527
+ const text = body(it);
1528
+ const form = it.form === "pill" && text ? "rect" : it.form ?? "rect", shape = SHAPE[form], size = it.size ?? "m";
1529
+ const min = minSize(form === "sticky" ? void 0 : shape), sz = sizeOf(it, shape, form, size, text);
1530
+ const w = Math.max(min.w, sz.w), h = Math.max(min.h, sz.h);
1531
+ const spot = freeSpot({ x: round(ox + it.x), y: round(oy + it.y), w, h }, taken(), T.gap);
1532
+ const id2 = ids();
1533
+ byKey.set(it.key, id2);
1534
+ layerOf.set(it.key, Math.max(0, Math.min(MAX_LAYER, Math.round(it.layer ?? derived?.get(it.key) ?? 0))));
1535
+ const ic = validIcon(it.icon);
1536
+ const pen = it.tone ? PEN[it.tone] : "black";
1537
+ const titled = it.title ? noEmoji(it.title).slice(0, LEN.title) : void 0;
1538
+ const n2 = form === "sticky" ? { id: id2, text: [titled, text].filter(Boolean).join("\n"), color: "yellow", ...spot, frame: null } : form === "text" ? { id: id2, shape: "text", size, pen, text: [titled, text].filter(Boolean).join("\n"), color: "paper", ...spot, frame: null } : form === "pill" ? { id: id2, shape: "pill", size, pen, text: titled ?? "", color: "paper", ...spot, frame: null } : { id: id2, shape, pen, size, ...titled ? { title: titled } : {}, text, color: "paper", ...spot, frame: null, ...ic ? { icon: ic } : {} };
1539
+ add(ops, n2);
1540
+ drawn.push(spot);
1541
+ if (it.note) sticky(ops, noEmoji(it.note).slice(0, LEN.message), spot);
1542
+ }
1543
+ const firstLink = beat.links?.find((l) => byKey.has(l.from));
1544
+ const near = drawn[0] ?? (firstLink ? notes.find((n2) => n2.id === byKey.get(firstLink.from)) : void 0);
1545
+ if (near) sticky(ops, say, near);
1546
+ for (const l of beat.links ?? []) {
1547
+ const from = byKey.get(l.from), to = byKey.get(l.to);
1548
+ if (!from || !to) {
1549
+ skipped.push(`${l.from} -> ${l.to}`);
1550
+ continue;
1551
+ }
1552
+ const layer = Math.max(layerOf.get(l.from) ?? 0, layerOf.get(l.to) ?? 0);
1553
+ const link = { id: uid("l"), from, to, route: "auto", ...l.label ? { label: noEmoji(l.label).slice(0, LEN.label) } : {}, ...l.dashed ? { dashed: true } : {}, ...layer ? { layer } : {} };
1554
+ ops.push({ op: "link.add", link });
1555
+ links.push(link);
1556
+ }
1557
+ routed = route(notes, links);
1558
+ steps.push({ say, ops });
1559
+ }
1560
+ return { steps, skipped };
1561
+ }
1562
+ function depthByWires(beats) {
1563
+ const keys = beats.flatMap((b) => (b.items ?? []).map((i) => i.key));
1564
+ const links = beats.flatMap((b) => b.links ?? []);
1565
+ const into = new Set(links.map((l) => l.to));
1566
+ const depth = new Map(keys.filter((k) => !into.has(k)).map((k) => [k, 0]));
1567
+ for (let queue = [...depth.keys()]; queue.length; ) {
1568
+ const k = queue.shift(), d = depth.get(k);
1569
+ for (const l of links) if (l.from === k && !depth.has(l.to)) {
1570
+ depth.set(l.to, Math.min(MAX_LAYER, d + 1));
1571
+ queue.push(l.to);
1572
+ }
1573
+ }
1574
+ return depth;
1575
+ }
1576
+ function route(notes, links) {
1577
+ const auto = autoWires(links);
1578
+ const r = routeWires(obstacles(notes), auto.map((l) => ({ from: l.from, to: l.to, ...l.label ? { label: l.label } : {} })), wireLabel);
1579
+ const wires = [], labels = [];
1580
+ for (const x of r.values()) {
1581
+ wires.push(...wireBoxes(x.pts));
1582
+ if (x.label) labels.push(x.label);
1583
+ }
1584
+ return { wires, labels };
1585
+ }
1586
+
1587
+ // src/core/agent-copy.ts
1588
+ var TK_BOARDS = {
1589
+ agent: "Agent",
1590
+ sheetKind: "sheet",
1591
+ boardKind: "whiteboard",
1592
+ sheetShort: "sheet",
1593
+ boardShort: "board",
1594
+ tasksKind: "task board",
1595
+ /** The card title field of a task board the agent makes. */
1596
+ taskTitle: "Task",
1597
+ tasksShort: "tasks",
1598
+ arg: {
1599
+ why: `one line in the user's language (English by default): why this change, grounded in the business rule or the data behind it (e.g. "Day 21 added: at most 1 reminder per 7 days"). It is read out when the board's history is replayed.`,
1600
+ noteOwner: "person responsible, by name",
1601
+ noteDue: "due date as the user would read it, e.g. 14 Nov",
1602
+ options: "choices for a select column",
1603
+ formula: "computed column, e.g. {Qty} * {Price}; refers to other columns by name in braces",
1604
+ total: "footer total for this column",
1605
+ itemKey: "your name for this item, to connect it",
1606
+ shape: "note (sticky card, default in grid, row, timeline, matrix), box (default in stack, flow, diagram), text, ellipse, cloud (an outside service), cylinder (a database), sticker (a big illustration on its own: its name in icon, an optional caption in text)",
1607
+ itemTitle: "bold first line, e.g. Agent core",
1608
+ color: "paper (default box), ink = the one highlighted element, red = needs action, outline = not built yet, new = new in this step; tints yellow, blue, green, pink, purple, gray group things; sand, peach, orange are the warm card tones of a timeline (picked for you)",
1609
+ icon: `a drawing for this item, by name. Line drawings for a marker sketch: ${LINE_ICONS.join(", ")}. Full-colour illustrations for a sticker or a sticky note: ${ILLUSTRATIONS.join(", ")}. Never an emoji.`,
1610
+ when: "timeline only: the milestone on the road, e.g. Day 7, Week 2, 14 Nov",
1611
+ cell: 'matrix only: [column, row] by header name or number, e.g. ["Wednesday", "Week 2"]',
1612
+ across: "matrix only: column headers left to right, e.g. Monday\u2026Friday",
1613
+ down: "matrix only: row headers top to bottom, e.g. Week 1\u20264, or owners",
1614
+ heading: "big title and one-line subtitle with the concrete scope and numbers; icon is one illustration (by name) shown as a sticker beside the title",
1615
+ at: "diagram layout only: [column, row]",
1616
+ box: "[x, y, width, height]. Lay the story out left to right, then start a new row below; keep each beat's items together and leave 30 to 60 between neighbours. A block of 260 to 360 wide holds a title and one line; a wide block (500+) with size l or xl is for the one thing that must be seen; text notes 300 to 500 wide",
1617
+ tone: "what kind of thing it is, which sets its colour everywhere: fact (black), problem (red, what goes wrong), action (green, what we do), insight (purple, what it means), person (blue, a person, team or desk), system (orange, a system or data store)",
1618
+ freeKey: 'a short name for this item, unique on the board, used by links ("calls", "no-offer", "mb-787860")',
1619
+ itemX: "where the item's left edge goes, in pixels from the left of the drawing space; the board is as wide as you need (3,000 to 5,000 is normal)",
1620
+ itemY: "where the item's top goes, in pixels from the top of the drawing space under the headline",
1621
+ form: "the item's shape: rect (default), square, circle, ellipse, diamond (a decision or a question), triangle (a warning or a peak), pentagon, hexagon (a process step), parallelogram (an input or a record), cylinder (a system or data store), cloud (outside the company), pill (a short tag), sticky (a yellow note in your voice), text (bare lettering: a caption, a heading over a group)",
1622
+ itemW: "width in pixels; leave out for the size's normal width (s 240, m 300, l 380, xl 480). For a horizontal bar chart, make each bar's width proportional to its value, scaled so the smallest bar is at least 150 wide (never narrower: its words must fit)",
1623
+ itemH: "height in pixels, at least what the words need (it grows to fit them). For a vertical bar chart, give every bar the same width (150 or more), its height proportional to its value, all on one baseline; a bar's own words are only its label and figure (the explanation goes in a text item or note beside the chart), so even a short bar keeps its true height",
1624
+ layer: "how deep in the explanation this item sits: 0 the main flow (the story's spine), 1 what a main item breaks down into, 2 what that breaks down into, and so on to 9. Wires take a colour per layer (black along the main flow), so a reader can follow one level of detail across the board",
1625
+ qWhy: "why it is so: the cause, the rule or the reason, with the evidence",
1626
+ qWho: "who: the customer, agent, desk, team or owner, by name",
1627
+ qWhen: "when: the date, period, deadline or how often",
1628
+ qWhere: "where: the desk, channel, branch, system or step it happens in",
1629
+ qHow: "how: the method, the source of the figure (system, table, filter) or the steps taken",
1630
+ qHowMuch: "how much or how many: the amount, count, rate or cost, with its unit",
1631
+ qAssumes: "what this figure or claim rests on that the data does not prove: a past rate that still holds, a price from the catalogue, a definition you chose, a period you picked",
1632
+ freeTitle: 'what this is, with its number when it has one ("950 eligible callers"). Short: it is lettered in capitals',
1633
+ itemText: 'what it means in plain words, the line a newcomer needs ("asked for a product, do not hold it, no complaint open on the call")',
1634
+ linkFrom: "key of the item the wire starts at (drawn in this beat or an earlier one)",
1635
+ linkTo: "key of the item the wire ends at, with the arrowhead",
1636
+ linkLabel: 'a few words on the wire saying what happens along it ("603 of them", "because", "hands over to")',
1637
+ beatItems: "the items drawn while saying this beat's sentence",
1638
+ beatLinks: "the wires drawn in this beat, each between two keyed items",
1639
+ nodeNote: "a remark you would make out loud about this thing, stuck beside it as a yellow sticky note (the so-what, a caution, the source)",
1640
+ say: 'what you would say aloud while drawing this beat, one sentence a listener could follow with their eyes closed ("Of those 1,147, only 950 can actually be offered something")',
1641
+ size: "lettering size: s for fine print and definitions, m normal, l for what matters, xl for the one number the board is about",
1642
+ itemLine: "the line under the title: the figure and what it means in plain words",
1643
+ beatConnectors: "arrows drawn in this beat, between keyed items (from this beat or an earlier one), each with a label saying what happens on it: how many move on, how many drop and why, who hands over to whom",
1644
+ pen: "the marker this item is drawn in (black, blue, green, red, purple, orange): its outline, words and drawing take that colour. Use colour to carry meaning across the board (one colour per idea or side), not decoration",
1645
+ dashed: "draw the outline as dashes: something optional, planned, not there yet, or a loose group around other items",
1646
+ marks: "what a person does with a marker to make a point: ring (circle an item), underline, highlight (yellow marker through it), cross (strike it out), tick. Give the item's key; the board draws the mark properly round it",
1647
+ strokes: "free layout only: lines you draw by hand over the items, each a list of [x, y] points in the same space: an underline under the key figure, a bracket, a divider between two halves, an axis, a curved arrow; three or four points are enough, the board smooths them into one flowing line. To circle or underline an item use marks instead. marker true for a thick highlighter",
1648
+ layout: "always free",
1649
+ beside: "place right of the previous section instead of below",
1650
+ route: "elbow (default), straight, or curve (default between matrix items)",
1651
+ sectionSubtitle: "one line under the section title saying what goes in it",
1652
+ noteTitle: "bold first line of the sticky (at most 4 words)",
1653
+ board: "board ref (WB-\u2026/SH-\u2026) or id, from create_*, list_boards or the user's message"
1654
+ },
1655
+ notFound: (key2) => `Board ${key2} is not in this team. Find it with list_boards.`,
1656
+ wrongKind: (ref, kind) => `${ref} is a ${kind}; use the tools for that kind.`,
1657
+ badFormula: (name) => `The formula in column ${name} is not valid: use {Column name}, numbers, + - * / and brackets.`,
1658
+ formulaMissing: (name, refs) => `The formula in column ${name} refers to columns that do not exist: ${refs}.`,
1659
+ sheetSummary: (tabs, rows) => `${tabs} tabs, ${rows} rows`,
1660
+ tasksSummary: (lanes, cards) => `${cards} cards in lanes ${lanes}`,
1661
+ boardSummary: (sections, notes) => `${sections} sections, ${notes} notes`,
1662
+ listSep: ", ",
1663
+ problemSep: "; ",
1664
+ skipped: (problems) => ` Skipped: ${problems}.`,
1665
+ createWhiteboard: {
1666
+ description: "Make a sticky-note board the team edits with you: a heading, then sections (frames) with a one-line description, of big square sticky notes coloured by meaning (green went well, pink a problem, blue an idea, purple a risk). Use for retros, brainstorms and risk or stakeholder maps. For a plan, rollout, timeline, schedule or any explanation use draw_whiteboard. Write each note as a short title and one line. Show it with present: whiteboard block and the ref.",
1667
+ layout: "columns: sections side by side; timeline: phases left to right joined by arrows; grid: many sections in rows. A plan or explanation over time is drawn with draw_whiteboard instead",
1668
+ running: (title) => `Building board ${title}`,
1669
+ done: (title) => `Board ${title} built`,
1670
+ result: (id2, ref, title, summary2) => `ref=${id2} board ${ref} "${title}": ${summary2}. Show it with present (whiteboard, this ref). The team can add notes; read it again with read_board.`
1671
+ },
1672
+ createSheet: {
1673
+ description: "Make a spreadsheet the team edits with you: tabs, typed columns (text, number, money, date, select with options, check), formulas between columns ({Qty} * {Price}) and footer totals. Fill rows yourself, or from a rows result with from_ref (its columns come along). Use only when the user asks for a sheet or wants something the team will keep filling in: trackers, budgets, checklists with owners. Never to answer a question: a ranking, a comparison, rates or totals from the data are shown as a built screen with present (figures, rings, bars), not as a sheet. Show it with present: sheet block and the ref.",
1674
+ rows: "values in column order (formula columns skipped), or objects keyed by column name",
1675
+ fromRef: "fill this tab from a rows result: its columns and rows",
1676
+ running: (title) => `Building sheet ${title}`,
1677
+ done: (title) => `Sheet ${title} built`,
1678
+ result: (id2, ref, title, summary2) => `ref=${id2} sheet ${ref} "${title}": ${summary2}. Show it with present (sheet, this ref).`
1679
+ },
1680
+ createTaskboard: {
1681
+ description: "Make a task board the team works on with you: lanes in process order (any process: To do, In progress, Done; Lead, Qualified, Won; Admitted, Ward, Discharged), cards with a title and fields (owner, due date, priority, anything the work needs). People drag cards between lanes themselves; you move, add and assign them with update_taskboard. Use when the user wants to track work, a pipeline or a queue the team keeps moving. For records that live in a company system, show them as a board block instead: those moves are writes.",
1682
+ lane: "name of the lane field, in the team's words (Status, Stage, Tahap)",
1683
+ lanes: "the lanes, in process order",
1684
+ fields: "card fields beside the title and lane: owner, due date, priority...",
1685
+ cards: "objects keyed by field name: the title field, the lane field (one of the lanes), and any other field",
1686
+ running: (title) => `Building task board ${title}`,
1687
+ done: (title) => `Task board ${title} built`,
1688
+ result: (id2, ref, title, summary2) => `ref=${id2} task board ${ref} "${title}": ${summary2}. Show it with present (taskboard, this ref).`
1689
+ },
1690
+ updateTaskboard: {
1691
+ description: "Change a task board: move cards to another lane (one or many at once), add cards, set card fields (owner, due date...), remove cards, add or rename lanes. Cards are found by their id from read_board, their title, or their 1-based number. Every change is kept in the board's history and the team sees it live.",
1692
+ move: "cards to move: card (id, title or number) and the lane to put it in",
1693
+ running: "Updating the task board",
1694
+ done: "Task board updated",
1695
+ noLane: (lane, lanes) => `no lane "${lane}" (lanes: ${lanes})`,
1696
+ noCard: (card) => `no card "${card}"`,
1697
+ noField: (field) => `no field "${field}"`,
1698
+ notTasks: (ref) => `${ref} is not a task board`,
1699
+ edit: "updated the task board",
1700
+ result: (id2, ref, summary2, skipped) => `ref=${id2} task board ${ref}: ${summary2}.${skipped} Show it with present (taskboard, this ref).`
1701
+ },
1702
+ draw: {
1703
+ description: "Explain something on a whiteboard the way a sharp colleague does standing at one, or the way an investigator pins up an evidence wall, so that someone who was not there understands all of it without asking anything. You compose the board yourself: what goes where, in which shape, how big, and what joins what. Give a headline (the finding in one line), context (period, source, how many, what the terms mean) and beats in the order you would explain them. Each beat has say (the sentence you speak while drawing it; it is pinned up as a sticky note beside that beat), the items you draw in it, and the links you draw in it. Each item has a key, x and y (where its top-left goes, in board pixels, from the top-left of the space under the headline), a form (rect, square, circle, ellipse, diamond, triangle, pentagon, hexagon, parallelogram, cylinder, cloud, pill, sticky, text: whatever suits the thing), a title and text, a layer (0 the main flow, 1 to 9 each level of detail below it), and answers why, who, when, where, how and how much wherever they have an answer (nearly always). Always explain everything in full detail, whether or not the person asked for detail: a board full of detail is the point, not a problem; a reader should never need to ask anything. Say what the board assumes: on each item whose figure rests on an assumption (assumes), and in a closing group of the board headed Assumptions and open questions (its items wired with dashed links to what they underpin). Charts are drawn the same way: bars are rect items sized in proportion to their values (w for horizontal bars, h for vertical bars on one baseline), each labelled with its figure. Put the main finding where the eye lands first, group what belongs together, spread causes around their effect, chain a process along a line, branch a breakdown out from its whole, and drill every part down to the actual calls or records, up to ten layers deep (the part the story is about the deepest). Leave room for wires between things (about 120 to 200 pixels). The board keeps your picture clean: an item that would cover another moves to the nearest free spot, wires are routed around every item, never through one, and their labels sit where the wire still shows. Query your data down to the depth you draw before drawing. tone sets meaning and colour: fact, problem, action, insight, person, system. Use real names, numbers and dates from your tools. No emoji. Leave board out to start a new board with title; pass board to continue an existing one.",
1704
+ headline: 'the finding in one line, as you would write it across the top ("2 in 3 callers who ask never hear an offer")',
1705
+ context: "one or two lines under the headline: the period, the source, how many, and what a term in the headline means",
1706
+ beats: "the explanation in the order you would give it, 4 to 12 beats: each beat is what you draw while saying one sentence (one to eight items and the links between them)",
1707
+ skippedKeys: (keys) => ` Not drawn, keys repeated or not found: ${keys.join(", ")}.`,
1708
+ board: "existing board ref or id; leave out to make a new board",
1709
+ title: "title of a new board",
1710
+ running: "Drawing on the board",
1711
+ writing: "Planning the board",
1712
+ done: "Board drawn",
1713
+ needTarget: "Give title for a new board, or board to add to an existing one.",
1714
+ result: (id2, ref, summary2, missing) => `ref=${id2} board ${ref}: ${summary2}.${missing.length ? ` Connectors skipped, keys not found: ${missing.join(", ")}.` : ""} Show it with present (whiteboard, this ref).`
1715
+ },
1716
+ read: {
1717
+ description: "Read a whiteboard (sections and notes with their ids, owners, due dates and who wrote them, including the team's own notes) or a sheet (tabs, columns and rows with formulas computed). Pass note_ids to read only a selection the user asked about.",
1718
+ running: "Reading the board",
1719
+ done: "Board read",
1720
+ head: (ref, title, kind, summary2, by) => `${ref} "${title}" (${kind}, ${summary2}, last changed by ${by}).`
1721
+ },
1722
+ updateWhiteboard: {
1723
+ description: "Change a whiteboard: extend a timeline road with new milestones (extend_timeline), add sections or notes (a note without a section sits on its own), move notes between sections (to group by theme: add the theme sections, move each note, then remove the emptied ones), edit (text, owner, due, colour) or remove notes, rename or remove sections, draw or remove arrows between notes or sections (dependencies, flow, cause and effect). Read it first with read_board for the ids. The board tidies itself after moves. Show it again with present (whiteboard) and the returned ref.",
1724
+ extendTimeline: "carry a timeline road on with new milestones (when, title, text, icon), in order, after the last one: the road is drawn further and each item gets its milestone and card on the right side. Use this, never loose notes, to add steps, phases or dates to a timeline. road: the track id from read_board when the board has more than one road",
1725
+ extendWhat: "Extending the timeline",
1726
+ noRoad: "This board has no timeline to extend yet; add one with draw_whiteboard (layout timeline).",
1727
+ noteSection: "section id or title; leave out for a note on its own",
1728
+ updateLinks: "restyle arrows: elbow or straight, dashed, label, arrowheads",
1729
+ removeSections: "section ids or titles; their notes stay on the board unless also removed",
1730
+ addLinks: "arrows; from and to are note ids, section ids or section titles",
1731
+ removeLinks: "arrow ids from read_board",
1732
+ running: "Updating the board",
1733
+ done: "Board updated",
1734
+ addSections: "adding sections",
1735
+ edit: "updating the board",
1736
+ noSection: (s) => `section "${s}" does not exist`,
1737
+ noNote: (id2) => `note ${id2} does not exist`,
1738
+ noEnds: (from, to) => `arrow ${from} \u2192 ${to}: an end does not exist`,
1739
+ noLink: (id2) => `arrow ${id2} does not exist`,
1740
+ result: (id2, ref, summary2, skipped) => `ref=${id2} board ${ref}: ${summary2}.${skipped}`
1741
+ },
1742
+ updateSheet: {
1743
+ description: "Change a sheet: set cells (row by id from read_board or by 1-based number; column by name), add or remove rows, add, change (type, options, formula, total) or remove columns, add tabs or rename the tab. The team sees your changes outlined. Read it first with read_board. Show it again with present (sheet) and the returned ref.",
1744
+ tab: "tab name or id; the first tab when left out",
1745
+ removeRows: "row ids from read_board or 1-based row numbers",
1746
+ removeColumns: "column names or ids",
1747
+ renameTab: "new name for the tab",
1748
+ running: "Updating the sheet",
1749
+ done: "Sheet updated",
1750
+ addTabs: "adding tabs",
1751
+ noTab: (tab, tabs) => `Tab ${tab} does not exist. Tabs available: ${tabs}.`,
1752
+ addColumns: "adding columns",
1753
+ noColumn: (c) => `column ${c} does not exist`,
1754
+ invalidFormula: "(invalid formula)",
1755
+ formulaRefs: (name, refs) => `formula ${name} refers to ${refs}`,
1756
+ noCell: (row, col2) => `cell ${row}/${col2} does not exist`,
1757
+ formulaCol: (name) => `${name} is a formula column`,
1758
+ noRow: (key2) => `row ${key2} does not exist`,
1759
+ usedBy: (name, users) => `column ${name} is used by formula ${users}`,
1760
+ edit: "updating the sheet",
1761
+ result: (id2, ref, summary2, skipped) => `ref=${id2} sheet ${ref}: ${summary2}.${skipped}`
1762
+ },
1763
+ open: {
1764
+ description: "Open an existing whiteboard, sheet or task board of the team so you can show it with present (the returned ref).",
1765
+ running: "Opening the board",
1766
+ done: "Board opened",
1767
+ result: (id2, ref, title, summary2, mode) => `ref=${id2} ${ref} "${title}" (${summary2}). Show it with present (${mode}, this ref).`
1768
+ },
1769
+ list: {
1770
+ description: "List the team's whiteboards, sheets and task boards, newest change first, with refs, to find one the user mentions.",
1771
+ running: "Finding the team's boards",
1772
+ done: "Team boards found",
1773
+ line: (ref, kind, title, summary2, day, by) => `${ref} ${kind} "${title}", ${summary2}, changed ${day} by ${by}`,
1774
+ none: "This team has no whiteboards, sheets or task boards yet."
1775
+ }
1776
+ };
1777
+ var BOARD_STEPS = {
1778
+ frame: "Laying out the title and frame",
1779
+ road: "Drawing the road",
1780
+ marks: "Placing milestones",
1781
+ marksRange: (from, to) => `${from} to ${to}`,
1782
+ cards: (titles) => titles.length ? `Cards: ${titles.join(", ")}` : "Placing cards",
1783
+ changes: "Tidying up",
1784
+ links: "Connecting steps",
1785
+ stickers: "Placing illustrations",
1786
+ what: { frame: "laying out the frame", road: "drawing the road", marks: "placing milestones", cards: "placing cards", changes: "tidying up", links: "connecting steps", stickers: "placing illustrations" },
1787
+ restoreWhat: "restored a version",
1788
+ restoreWhy: (v) => `Restored to version ${v}`,
1789
+ undoWhat: "undid the agent's work",
1790
+ undoWhy: (what) => `Undone: ${what}`,
1791
+ reading: "reading the board",
1792
+ editing: "editing the board"
1793
+ };
1794
+
1795
+ // src/core/service.ts
1796
+ import { z } from "zod";
1797
+ var maxEdits = (b) => b.mode === "whiteboard" ? BOARD_HISTORY.whiteboardEdits : BOARD_EDITS_KEPT;
1798
+ var keepable = (ops) => ops.length <= BOARD_HISTORY.opsMax && JSON.stringify(ops).length <= BOARD_HISTORY.opsBytes;
1799
+ function withEdit(prev, next, e, ops, more = {}) {
1800
+ const kept = keepable(ops);
1801
+ let base = kept ? prev.base ?? contentOf(prev) : contentOf(next);
1802
+ const edits = [...prev.edits, { ...e, version: next.version, ...more.why ? { why: more.why.slice(0, LEN.line) } : {}, ...more.batch ? { batch: more.batch } : {}, ...more.told ? { told: true } : {}, ...kept ? { ops } : {} }];
1803
+ const shell = { ...next, edits: [] };
1804
+ while (edits.length > maxEdits(next)) base = foldIntoBase(base, edits.shift(), shell);
1805
+ const activity = more.activity === null ? void 0 : more.activity ? { ...more.activity, at: next.updatedAt } : prev.activity;
1806
+ return { ...next, edits, base, activity };
1807
+ }
1808
+ var newBatch = () => `bt_${crypto.randomUUID().replace(/-/g, "").slice(0, 10)}`;
1809
+ var newRef = (mode) => {
1810
+ const d = /* @__PURE__ */ new Date();
1811
+ return `${mode === "sheet" ? "SH" : mode === "tasks" ? "TB" : "WB"}-${String(d.getFullYear()).slice(2)}${String(d.getMonth() + 1).padStart(2, "0")}-${crypto.randomUUID().slice(0, 4).toUpperCase()}`;
1812
+ };
1813
+ var RANK = { read: 0, edited: 1, created: 2 };
1814
+ function withChat(b, via, what, at = (/* @__PURE__ */ new Date()).toISOString()) {
1815
+ if (!via) return b;
1816
+ const prev = b.chats?.find((c) => c.chatId === via.chatId);
1817
+ const kept = { chatId: via.chatId, userId: via.userId, at, what: prev && RANK[prev.what] > RANK[what] ? prev.what : what };
1818
+ return { ...b, chats: [kept, ...(b.chats ?? []).filter((c) => c.chatId !== via.chatId)].slice(0, BOARD_CHATS_KEPT) };
1819
+ }
1820
+ function createBoard(owner, input, ops, agent, by, via, more = {}) {
1821
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1822
+ const mode = input.mode ?? "whiteboard";
1823
+ const who = agent ? WORDS.agent : by;
1824
+ const empty = {
1825
+ id: input.id ?? `brd_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`,
1826
+ ref: input.ref ?? newRef(mode),
1827
+ tenantId: owner.tenantId,
1828
+ unitId: owner.unitId ?? owner.tenantId,
1829
+ projectId: owner.projectId ?? null,
1830
+ title: input.title.trim().slice(0, LEN.title) || WORDS.untitled,
1831
+ mode,
1832
+ createdBy: by,
1833
+ createdAt: now,
1834
+ updatedAt: now,
1835
+ updatedBy: who,
1836
+ version: 0,
1837
+ frames: [],
1838
+ notes: [],
1839
+ links: [],
1840
+ tabs: [],
1841
+ edits: []
1842
+ };
1843
+ const b = applyOps(empty, ops, who, now);
1844
+ const made = withEdit(empty, b, { at: now, by: who, agent, what: agent ? ERR.membuatPapan : WORDS.created, keys: [] }, ops, more);
1845
+ return withChat({ ...made, base: made.base ?? contentOf(empty) }, via, "created", now);
1846
+ }
1847
+ function editBoard(board2, ops, agent, by, what, keys = opKeys(ops), via, more = {}) {
1848
+ if (!ops.length) return board2;
1849
+ const who = agent ? WORDS.agent : by;
1850
+ const next = applyOps(board2, ops, who);
1851
+ const done = withEdit(board2, next, { at: next.updatedAt, by: who, agent, what, keys: [...new Set(keys)].slice(0, 400) }, ops, more);
1852
+ return withChat(done, via, "edited", next.updatedAt);
1853
+ }
1854
+ function setActivity(board2, activity) {
1855
+ return { ...board2, activity: activity ? { ...activity, at: (/* @__PURE__ */ new Date()).toISOString() } : void 0 };
1856
+ }
1857
+ function liveActivity(board2, now = Date.now()) {
1858
+ const a = board2.activity;
1859
+ return a && now - Date.parse(a.at) < BOARD_HISTORY.activityMs ? a : null;
1860
+ }
1861
+ function publicBoard(b) {
1862
+ const { base: _base, activity: _a, ...rest } = b;
1863
+ const activity = liveActivity(b);
1864
+ return { ...rest, edits: b.edits.map(({ ops: _ops, ...e }) => e), ...activity ? { activity } : {}, pendingBatch: pendingBatchOf(b) };
1865
+ }
1866
+ function snapshot(b, since) {
1867
+ return since === b.version ? { same: true, version: b.version, activity: liveActivity(b), pendingBatch: pendingBatchOf(b) } : { board: publicBoard(b) };
1868
+ }
1869
+ var STEP_WHY = {
1870
+ frame: () => BOARD_STEPS.frame,
1871
+ road: () => BOARD_STEPS.road,
1872
+ marks: (s) => {
1873
+ const labels = s.ops.flatMap((o) => o.op === "note.add" && o.note.shape === "pill" && o.note.text ? [o.note.text] : []);
1874
+ return labels.length > 1 ? BOARD_STEPS.marksRange(labels[0], labels[labels.length - 1]) : BOARD_STEPS.marks;
1875
+ },
1876
+ cards: (s) => BOARD_STEPS.cards(s.ops.flatMap((o) => o.op === "note.add" ? [o.note.title || o.note.text] : []).filter(Boolean).slice(0, 3)),
1877
+ changes: () => BOARD_STEPS.changes,
1878
+ links: () => BOARD_STEPS.links,
1879
+ stickers: () => BOARD_STEPS.stickers
1880
+ };
1881
+ var gap = (n2) => n2 > 1 ? Math.min(BOARD_HISTORY.stepMs, Math.floor(BOARD_HISTORY.stepsTotalMs / (n2 - 1))) : 0;
1882
+ function buildSteps(ops, batch, via, what, why2, planFirst = false) {
1883
+ const steps = stepsOf(ops, BOARD_HISTORY.cardsPerStep);
1884
+ const plan = planOf(ops, BOARD_HISTORY.planMax);
1885
+ const pauseMs = gap(steps.length);
1886
+ return steps.map((s, i) => ({
1887
+ ops: s.ops,
1888
+ what: i === 0 && what ? what : BOARD_STEPS.what[s.kind],
1889
+ why: i === 0 && why2 ? why2 : STEP_WHY[s.kind](s),
1890
+ activity: { by: WORDS.agent, agent: true, what: BOARD_STEPS.what[s.kind], ...via ? { chatId: via.chatId } : {}, keys: opKeys(s.ops).slice(0, 60), plan, batch },
1891
+ pauseMs,
1892
+ ...i === 0 && planFirst && plan.length ? { planFirst: true } : {}
1893
+ }));
1894
+ }
1895
+ function toldSteps(beats, batch, via, why2) {
1896
+ const P = BOARD_HISTORY.beat;
1897
+ return beats.map((bt, i) => ({
1898
+ ops: bt.ops,
1899
+ what: bt.say.slice(0, P.sayChars),
1900
+ why: i === 0 ? why2?.trim() || bt.say : bt.say,
1901
+ activity: { by: WORDS.agent, agent: true, what: bt.say.slice(0, P.sayChars), ...via ? { chatId: via.chatId } : {}, keys: opKeys(bt.ops).slice(0, 60), plan: planOf(bt.ops, BOARD_HISTORY.planMax), batch },
1902
+ told: true,
1903
+ pauseMs: Math.min(P.maxMs, P.baseMs + P.perItemMs * bt.ops.length)
1904
+ }));
1905
+ }
1906
+ var planActivity = (ops, what, batch, via) => {
1907
+ const plan = planOf(ops, BOARD_HISTORY.planMax);
1908
+ return { by: WORDS.agent, agent: true, what, ...via ? { chatId: via.chatId } : {}, keys: plan.map((p) => p.id).slice(0, 60), plan, batch };
1909
+ };
1910
+ function applyStep(owner, target, step, via) {
1911
+ const more = { why: step.why, activity: step.activity, batch: step.activity.batch, told: step.told };
1912
+ if ("edits" in target) return editBoard(target, step.ops, true, WORDS.agent, step.what, void 0, via, more);
1913
+ return createBoard(owner, target, step.ops, true, WORDS.agent, via, more);
1914
+ }
1915
+ var decide = (b, batch, by, how, at = (/* @__PURE__ */ new Date()).toISOString()) => ({ ...b, edits: b.edits.map((e) => e.batch === batch ? { ...e, decided: { by, at, how } } : e) });
1916
+ function keepBatch(board2, batch, by) {
1917
+ if (!board2.edits.some((e) => e.batch === batch)) return { error: ERR.batchNotFound };
1918
+ return decide(board2, batch, by, "kept");
1919
+ }
1920
+ function undoBatch(board2, batch, by) {
1921
+ const mine = board2.edits.filter((e) => e.batch === batch);
1922
+ const first = mine[0];
1923
+ if (!first?.version) return { error: ERR.batchNotFound };
1924
+ const after = board2.edits.filter((e) => (e.version ?? 0) > first.version && e.batch !== batch && e.ops?.length !== 0);
1925
+ const others = [...new Set(after.map((e) => e.by === by ? WORDS.you : e.by))];
1926
+ if (others.length) return { error: ERR.batchChangedSince(others), conflict: true };
1927
+ const then = boardAt(board2, first.version - 1);
1928
+ if (!then) return { error: ERR.versionNotKept(first.version - 1) };
1929
+ const back = editBoard(board2, [{ op: "restore", to: contentOf(then) }], false, by, BOARD_STEPS.undoWhat, [], void 0, { why: BOARD_STEPS.undoWhy(first.why || first.what), activity: null });
1930
+ return decide(back, batch, by, "undone");
1931
+ }
1932
+ function restoreBoard(board2, version, by) {
1933
+ const then = boardAt(board2, version);
1934
+ if (!then) return { error: ERR.versionNotKept(version) };
1935
+ return editBoard(board2, [{ op: "restore", to: contentOf(then) }], false, by, BOARD_STEPS.restoreWhat, [], void 0, { why: BOARD_STEPS.restoreWhy(version), activity: null });
1936
+ }
1937
+ var id = z.string().min(1).max(LEN.id);
1938
+ var n = z.number().finite();
1939
+ var color = z.enum(NOTE_COLORS);
1940
+ var cell = z.union([z.string().max(LEN.text), z.number().finite(), z.boolean(), z.null()]);
1941
+ var col = z.object({ id, name: z.string().max(LEN.name), type: z.enum(COL_TYPES), options: z.array(z.string().max(LEN.label)).max(COUNT.wide).optional(), formula: z.string().max(LEN.line).optional(), total: z.enum(["sum", "avg", "count"]).nullable().optional(), width: n.optional() });
1942
+ var notePatch = z.object({
1943
+ text: z.string().max(BOARD.maxText),
1944
+ x: n,
1945
+ y: n,
1946
+ w: n,
1947
+ h: n,
1948
+ color,
1949
+ frame: z.string().max(LEN.id).nullable(),
1950
+ owner: z.string().max(LEN.label),
1951
+ due: z.string().max(LEN.id),
1952
+ shape: z.enum(SHAPES),
1953
+ title: z.string().max(LEN.title),
1954
+ size: z.enum(TEXT_SIZES),
1955
+ points: z.array(n).max(COUNT.points),
1956
+ icon: z.string().max(LEN.short),
1957
+ pen: z.enum(PENS),
1958
+ dashed: z.boolean(),
1959
+ pressure: z.array(n).max(COUNT.points),
1960
+ brush: z.enum(BRUSHES),
1961
+ weight: n
1962
+ }).partial();
1963
+ var framePatch = z.object({ title: z.string().max(LEN.title), subtitle: z.string().max(LEN.line), x: n, y: n, w: n, h: n }).partial();
1964
+ var linkPatch = z.object({ label: z.string().max(LEN.name), route: z.enum(ROUTES), dashed: z.boolean(), arrow: z.enum(["end", "both", "none"]) }).partial();
1965
+ var OpSchema = z.discriminatedUnion("op", [
1966
+ z.object({ op: z.literal("title"), title: z.string().max(LEN.title) }),
1967
+ z.object({ op: z.literal("note.add"), note: notePatch.extend({ id, text: z.string().max(BOARD.maxText), x: n, y: n }) }),
1968
+ z.object({ op: z.literal("note.update"), id, patch: notePatch }),
1969
+ z.object({ op: z.literal("note.remove"), id }),
1970
+ z.object({ op: z.literal("frame.add"), frame: framePatch.extend({ id, title: z.string().max(LEN.title), x: n, y: n }) }),
1971
+ z.object({ op: z.literal("frame.update"), id, patch: framePatch }),
1972
+ z.object({ op: z.literal("frame.move"), id, dx: n, dy: n }),
1973
+ z.object({ op: z.literal("frame.remove"), id, keepNotes: z.boolean().optional() }),
1974
+ z.object({ op: z.literal("link.add"), link: linkPatch.extend({ id, from: id, to: id }) }),
1975
+ z.object({ op: z.literal("link.update"), id, patch: linkPatch }),
1976
+ z.object({ op: z.literal("link.remove"), id }),
1977
+ z.object({ op: z.literal("tab.add"), tab: z.object({ id, name: z.string().max(LEN.name), columns: z.array(col).max(COUNT.wide).optional() }) }),
1978
+ z.object({ op: z.literal("tab.rename"), tab: id, name: z.string().max(LEN.name) }),
1979
+ z.object({ op: z.literal("tab.remove"), tab: id }),
1980
+ z.object({ op: z.literal("col.add"), tab: id, col, at: z.number().int().min(0).optional() }),
1981
+ z.object({ op: z.literal("col.update"), tab: id, id, patch: col.omit({ id: true }).partial() }),
1982
+ z.object({ op: z.literal("col.remove"), tab: id, id }),
1983
+ z.object({ op: z.literal("row.add"), tab: id, row: z.object({ id, cells: z.record(z.string(), cell) }), at: z.number().int().min(0).optional() }),
1984
+ z.object({ op: z.literal("row.remove"), tab: id, id }),
1985
+ z.object({ op: z.literal("cell.set"), tab: id, row: id, col: id, value: cell })
1986
+ ]);
1987
+ var PatchInput = z.object({ ops: z.array(OpSchema).min(1).max(COUNT.bulk) });
1988
+
1989
+ // src/core/agent.ts
1990
+ var icon = z2.string().trim().max(BOARD_ARGS.ref).optional().describe(TK_BOARDS.arg.icon);
1991
+ var heading = z2.object({ title: z2.string().trim().min(1).max(BOARD_ARGS.headingTitle), subtitle: z2.string().trim().max(BOARD_ARGS.headingSubtitle).optional(), icon }).describe(TK_BOARDS.arg.heading);
1992
+ var note = z2.object({
1993
+ text: z2.string().trim().min(1).max(BOARD_ARGS.noteText),
1994
+ title: z2.string().trim().max(BOARD_ARGS.itemTitle).optional().describe(TK_BOARDS.arg.noteTitle),
1995
+ icon,
1996
+ owner: z2.string().trim().max(BOARD_ARGS.owner).optional().describe(TK_BOARDS.arg.noteOwner),
1997
+ due: z2.string().trim().max(BOARD_ARGS.due).optional().describe(TK_BOARDS.arg.noteDue),
1998
+ color: z2.enum(NOTE_COLORS).optional()
1999
+ });
2000
+ var section = z2.object({ title: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle), subtitle: z2.string().trim().max(BOARD_ARGS.subtitle).optional().describe(TK_BOARDS.arg.sectionSubtitle), notes: z2.array(note).max(BOARD_ARGS.sectionNotes).default([]) });
2001
+ var FREE = BOARD.draw.free;
2002
+ var drawItem = z2.object({
2003
+ key: z2.string().trim().min(1).max(BOARD_ARGS.ref).optional().describe(TK_BOARDS.arg.itemKey),
2004
+ shape: z2.enum(["box", "note", "ellipse", "pill", "cloud", "cylinder", "text", "sticker", "dot"]).optional().describe(TK_BOARDS.arg.shape),
2005
+ pen: z2.enum(PENS).optional().describe(TK_BOARDS.arg.pen),
2006
+ dashed: z2.boolean().optional().describe(TK_BOARDS.arg.dashed),
2007
+ title: z2.string().trim().max(BOARD_ARGS.itemTitle).optional().describe(TK_BOARDS.arg.itemTitle),
2008
+ text: z2.string().trim().max(BOARD_ARGS.itemText).optional(),
2009
+ icon,
2010
+ when: z2.string().trim().max(BOARD_ARGS.linkLabel).optional().describe(TK_BOARDS.arg.when),
2011
+ color: z2.enum(NOTE_COLORS).optional().describe(TK_BOARDS.arg.color),
2012
+ size: z2.enum(TEXT_SIZES).optional(),
2013
+ owner: z2.string().trim().max(BOARD_ARGS.owner).optional(),
2014
+ due: z2.string().trim().max(BOARD_ARGS.due).optional()
2015
+ });
2016
+ var boardArg = z2.string().trim().min(1).max(BOARD_ARGS.ref).describe(TK_BOARDS.arg.board);
2017
+ var answer = z2.string().trim().max(BOARD_ARGS.answer).optional();
2018
+ var qa = { why: answer.describe(TK_BOARDS.arg.qWhy), who: answer.describe(TK_BOARDS.arg.qWho), when: answer.describe(TK_BOARDS.arg.qWhen), where: answer.describe(TK_BOARDS.arg.qWhere), how: answer.describe(TK_BOARDS.arg.qHow), howMuch: answer.describe(TK_BOARDS.arg.qHowMuch), assumes: answer.describe(TK_BOARDS.arg.qAssumes) };
2019
+ var freeItem = z2.object({
2020
+ key: z2.string().trim().min(1).max(BOARD_ARGS.ref).describe(TK_BOARDS.arg.freeKey),
2021
+ x: z2.number().finite().min(0).max(BOARD_ARGS.freeSpan).describe(TK_BOARDS.arg.itemX),
2022
+ y: z2.number().finite().min(0).max(BOARD_ARGS.freeSpan).describe(TK_BOARDS.arg.itemY),
2023
+ form: z2.enum(FORMS).optional().describe(TK_BOARDS.arg.form),
2024
+ size: z2.enum(["s", "m", "l", "xl"]).optional().describe(TK_BOARDS.arg.size),
2025
+ w: z2.number().finite().min(BOARD.minSize.shape.w).max(FREE.w).optional().describe(TK_BOARDS.arg.itemW),
2026
+ h: z2.number().finite().min(BOARD.minSize.shape.h).max(FREE.w).optional().describe(TK_BOARDS.arg.itemH),
2027
+ layer: z2.number().int().min(0).max(9).optional().describe(TK_BOARDS.arg.layer),
2028
+ title: z2.string().trim().max(BOARD_ARGS.itemTitle).optional().describe(TK_BOARDS.arg.freeTitle),
2029
+ text: z2.string().trim().max(BOARD_ARGS.itemText).optional().describe(TK_BOARDS.arg.itemText),
2030
+ tone: z2.enum(TONES).optional().describe(TK_BOARDS.arg.tone),
2031
+ icon,
2032
+ ...qa,
2033
+ note: z2.string().trim().max(BOARD_ARGS.say).optional().describe(TK_BOARDS.arg.nodeNote)
2034
+ });
2035
+ var freeLink = z2.object({
2036
+ from: z2.string().trim().min(1).max(BOARD_ARGS.ref).describe(TK_BOARDS.arg.linkFrom),
2037
+ to: z2.string().trim().min(1).max(BOARD_ARGS.ref).describe(TK_BOARDS.arg.linkTo),
2038
+ label: z2.string().trim().max(BOARD_ARGS.linkLabel).optional().describe(TK_BOARDS.arg.linkLabel),
2039
+ dashed: z2.boolean().optional().describe(TK_BOARDS.arg.dashed)
2040
+ });
2041
+ var freeBeat = z2.object({
2042
+ say: z2.string().trim().min(1).max(BOARD_ARGS.say).describe(TK_BOARDS.arg.say),
2043
+ items: z2.array(freeItem).max(BOARD_ARGS.beatItems).optional().describe(TK_BOARDS.arg.beatItems),
2044
+ links: z2.array(freeLink).max(BOARD_ARGS.beatItems).optional().describe(TK_BOARDS.arg.beatLinks)
2045
+ });
2046
+ var why = z2.string().trim().max(BOARD_ARGS.why).optional().describe(TK_BOARDS.arg.why);
2047
+ var CreateWhiteboardInput = z2.object({
2048
+ title: z2.string().trim().min(BOARD_ARGS.title.min).max(BOARD_ARGS.title.max),
2049
+ layout: z2.enum(["columns", "timeline", "grid"]).default("columns").describe(TK_BOARDS.createWhiteboard.layout),
2050
+ heading: heading.optional(),
2051
+ sections: z2.array(section).min(1).max(BOARD_ARGS.sections),
2052
+ why
2053
+ });
2054
+ var DrawWhiteboardInput = z2.object({
2055
+ board: z2.string().trim().min(1).max(BOARD_ARGS.ref).optional().describe(TK_BOARDS.draw.board),
2056
+ title: z2.string().trim().min(BOARD_ARGS.title.min).max(BOARD_ARGS.title.max).optional().describe(TK_BOARDS.draw.title),
2057
+ headline: z2.string().trim().min(1).max(BOARD_ARGS.headingTitle).optional().describe(TK_BOARDS.draw.headline),
2058
+ context: z2.string().trim().max(BOARD_ARGS.headingSubtitle).optional().describe(TK_BOARDS.draw.context),
2059
+ icon,
2060
+ beats: z2.array(freeBeat).min(1).max(BOARD_ARGS.beats).describe(TK_BOARDS.draw.beats),
2061
+ why
2062
+ });
2063
+ var UpdateWhiteboardInput = z2.object({
2064
+ board: boardArg,
2065
+ add_sections: z2.array(section).max(BOARD_ARGS.sections).optional(),
2066
+ add_notes: z2.array(note.extend({ section: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle).optional().describe(TK_BOARDS.updateWhiteboard.noteSection) })).max(BOARD_ARGS.addNotes).optional(),
2067
+ move_notes: z2.array(z2.object({ note_id: z2.string().min(1).max(BOARD_ARGS.ref), section: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle) })).max(BOARD_ARGS.moveNotes).optional(),
2068
+ update_notes: z2.array(note.partial().extend({ note_id: z2.string().min(1).max(BOARD_ARGS.ref), title: z2.string().trim().max(BOARD_ARGS.itemTitle).optional(), shape: z2.enum(SHAPES).optional(), size: z2.enum(TEXT_SIZES).optional() })).max(BOARD_ARGS.updates).optional(),
2069
+ update_links: z2.array(z2.object({ link_id: z2.string().min(1).max(BOARD_ARGS.ref), label: z2.string().trim().max(BOARD_ARGS.linkLabel).optional(), route: z2.enum(ROUTES).optional(), dashed: z2.boolean().optional(), arrow: z2.enum(["end", "both", "none"]).optional() })).max(BOARD_ARGS.updates).optional().describe(TK_BOARDS.updateWhiteboard.updateLinks),
2070
+ remove_notes: z2.array(z2.string().min(1).max(BOARD_ARGS.ref)).max(BOARD_ARGS.moveNotes).optional(),
2071
+ rename_sections: z2.array(z2.object({ section: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle), title: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle) })).max(BOARD_ARGS.sections).optional(),
2072
+ remove_sections: z2.array(z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle)).max(BOARD_ARGS.sections).optional().describe(TK_BOARDS.updateWhiteboard.removeSections),
2073
+ add_links: z2.array(z2.object({ from: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle), to: z2.string().trim().min(1).max(BOARD_ARGS.sectionTitle), label: z2.string().trim().max(BOARD_ARGS.linkLabel).optional() })).max(BOARD_ARGS.addLinks).optional().describe(TK_BOARDS.updateWhiteboard.addLinks),
2074
+ remove_links: z2.array(z2.string().min(1).max(BOARD_ARGS.ref)).max(BOARD_ARGS.updates).optional().describe(TK_BOARDS.updateWhiteboard.removeLinks),
2075
+ extend_timeline: z2.object({ road: z2.string().trim().min(1).max(BOARD_ARGS.ref).optional(), items: z2.array(drawItem).min(1).max(BOARD_ARGS.sectionNotes) }).optional().describe(TK_BOARDS.updateWhiteboard.extendTimeline),
2076
+ why
2077
+ });
2078
+ var ReadBoardInput = z2.object({ board: boardArg, note_ids: z2.array(z2.string().min(1).max(BOARD_ARGS.ref)).max(BOARD_ARGS.noteIds).optional() });
2079
+ var DEFAULT_NAMES = { create: "create_whiteboard", draw: "draw_whiteboard", update: "update_whiteboard", read: "read_board", list: "list_boards" };
2080
+ var hostWords = (text, names, show) => text.replace(/\s*Show it (again )?with present[^.]*\.?/g, "").replace(/\bcreate_whiteboard\b/g, names.create).replace(/\bdraw_whiteboard\b/g, names.draw).replace(/\bupdate_whiteboard\b/g, names.update).replace(/\bread_board\b/g, names.read).replace(/\blist_boards\b/g, names.list).trim();
2081
+ function toolSpecs(show, names = DEFAULT_NAMES) {
2082
+ const spec = (name, description, schema, shows = true) => ({
2083
+ name,
2084
+ description: `${hostWords(description, names, show)}${shows && show ? ` ${show}` : ""}`,
2085
+ parameters: zodToJsonSchema(schema, { $refStrategy: "none" })
2086
+ });
2087
+ return [
2088
+ spec(names.create, TK_BOARDS.createWhiteboard.description, CreateWhiteboardInput),
2089
+ spec(names.draw, TK_BOARDS.draw.description, DrawWhiteboardInput),
2090
+ spec(names.update, TK_BOARDS.updateWhiteboard.description, UpdateWhiteboardInput),
2091
+ spec(names.read, TK_BOARDS.read.description, ReadBoardInput, false)
2092
+ ];
2093
+ }
2094
+ var summary = (b) => TK_BOARDS.boardSummary(b.frames.length, b.notes.length);
2095
+ function planCreate(raw, via, batch = newBatch()) {
2096
+ const i = CreateWhiteboardInput.parse(raw);
2097
+ const ops = layoutOps(i.sections, i.layout, void 0, void 0, i.heading ?? { title: i.title }).ops;
2098
+ return { create: { title: i.title, mode: "whiteboard" }, steps: buildSteps(ops, batch, via, void 0, i.why), problems: [] };
2099
+ }
2100
+ function planDraw(raw, target, via, batch = newBatch()) {
2101
+ const i = DrawWhiteboardInput.parse(raw);
2102
+ if (!target && !i.title) throw new Error(TK_BOARDS.draw.needTarget);
2103
+ const story = { headline: i.headline ?? i.title ?? target.title, ...i.context ? { context: i.context } : {}, ...i.icon ? { icon: i.icon } : {}, beats: i.beats };
2104
+ const { steps, skipped } = layFree(story, target ? nextOrigin(target) : { x: 0, y: 0 }, target ?? void 0);
2105
+ return { ...target ? {} : { create: { title: i.title, mode: "whiteboard" } }, steps: toldSteps(steps, batch, via, i.why), problems: [], skippedKeys: skipped };
2106
+ }
2107
+ var sectionOf = (b, key2) => b.frames.find((f) => f.id === key2) ?? b.frames.find((f) => f.title.toLowerCase() === key2.trim().toLowerCase());
2108
+ function planUpdate(raw, board2, via, batch = newBatch()) {
2109
+ const i = UpdateWhiteboardInput.parse(raw);
2110
+ let b = board2;
2111
+ const steps = [];
2112
+ const problems = [];
2113
+ const stage = (s) => {
2114
+ for (const step of s) b = applyOps(b, step.ops, TK_BOARDS.agent);
2115
+ steps.push(...s);
2116
+ };
2117
+ if (i.extend_timeline) {
2118
+ const ext = extendTimelineOps(b, i.extend_timeline.items, i.extend_timeline.road);
2119
+ if (!ext) problems.push(TK_BOARDS.updateWhiteboard.noRoad);
2120
+ else stage(buildSteps(ext.ops, batch, via, TK_BOARDS.updateWhiteboard.extendWhat, i.why, true));
2121
+ }
2122
+ if (i.add_sections?.length) {
2123
+ const added = layoutOps(i.add_sections, "columns", nextOrigin(b)).ops;
2124
+ stage([{ ops: added, what: TK_BOARDS.updateWhiteboard.addSections, why: i.why ?? TK_BOARDS.updateWhiteboard.addSections, activity: planActivity(added, TK_BOARDS.updateWhiteboard.addSections, batch, via), pauseMs: 0, planFirst: true }]);
2125
+ }
2126
+ const ops = [];
2127
+ let loose = 0;
2128
+ const free = nextOrigin(b);
2129
+ for (const n2 of i.add_notes ?? []) {
2130
+ const f = n2.section ? sectionOf(b, n2.section) : null;
2131
+ if (n2.section && !f) {
2132
+ problems.push(TK_BOARDS.updateWhiteboard.noSection(n2.section));
2133
+ continue;
2134
+ }
2135
+ const at = f ? { x: f.x + SECTION_NOTE_INSET, y: f.y + f.h } : { x: free.x + loose % LOOSE_NOTES.perRow * LOOSE_NOTES.dx, y: free.y + Math.floor(loose++ / LOOSE_NOTES.perRow) * LOOSE_NOTES.dy };
2136
+ ops.push({ op: "note.add", note: { id: uid("n"), text: n2.text, ...at, frame: f?.id ?? null, ...n2.owner ? { owner: n2.owner } : {}, ...n2.due ? { due: n2.due } : {}, ...n2.color ? { color: n2.color } : {} } });
2137
+ }
2138
+ for (const m of i.move_notes ?? []) {
2139
+ const f = sectionOf(b, m.section);
2140
+ if (!f) problems.push(TK_BOARDS.updateWhiteboard.noSection(m.section));
2141
+ else if (!b.notes.some((x) => x.id === m.note_id)) problems.push(TK_BOARDS.updateWhiteboard.noNote(m.note_id));
2142
+ else ops.push({ op: "note.update", id: m.note_id, patch: { frame: f.id } });
2143
+ }
2144
+ for (const u of i.update_notes ?? []) {
2145
+ if (!b.notes.some((x) => x.id === u.note_id)) {
2146
+ problems.push(TK_BOARDS.updateWhiteboard.noNote(u.note_id));
2147
+ continue;
2148
+ }
2149
+ const { note_id, ...patch } = u;
2150
+ ops.push({ op: "note.update", id: note_id, patch });
2151
+ }
2152
+ for (const id2 of i.remove_notes ?? []) ops.push({ op: "note.remove", id: id2 });
2153
+ for (const r of i.rename_sections ?? []) {
2154
+ const f = sectionOf(b, r.section);
2155
+ if (f) ops.push({ op: "frame.update", id: f.id, patch: { title: r.title } });
2156
+ else problems.push(TK_BOARDS.updateWhiteboard.noSection(r.section));
2157
+ }
2158
+ for (const s of i.remove_sections ?? []) {
2159
+ const f = sectionOf(b, s);
2160
+ if (f) ops.push({ op: "frame.remove", id: f.id });
2161
+ else problems.push(TK_BOARDS.updateWhiteboard.noSection(s));
2162
+ }
2163
+ const endOf = (key2) => b.notes.find((x) => x.id === key2)?.id ?? sectionOf(b, key2)?.id;
2164
+ for (const l of i.add_links ?? []) {
2165
+ const from = endOf(l.from), to = endOf(l.to);
2166
+ if (!from || !to) {
2167
+ problems.push(TK_BOARDS.updateWhiteboard.noEnds(l.from, l.to));
2168
+ continue;
2169
+ }
2170
+ if (from === to || b.links.some((x) => x.from === from && x.to === to)) continue;
2171
+ const auto = b.links.some((x) => x.route === "auto") || b.edits.some((e) => e.told);
2172
+ ops.push({ op: "link.add", link: { id: uid("l"), from, to, ...auto ? { route: "auto" } : {}, ...l.label ? { label: l.label } : {} } });
2173
+ }
2174
+ for (const u of i.update_links ?? []) {
2175
+ const { link_id, ...patch } = u;
2176
+ if (b.links.some((x) => x.id === link_id)) ops.push({ op: "link.update", id: link_id, patch });
2177
+ else problems.push(TK_BOARDS.updateWhiteboard.noLink(link_id));
2178
+ }
2179
+ for (const id2 of i.remove_links ?? []) {
2180
+ if (b.links.some((x) => x.id === id2)) ops.push({ op: "link.remove", id: id2 });
2181
+ else problems.push(TK_BOARDS.updateWhiteboard.noLink(id2));
2182
+ }
2183
+ const tidy = i.move_notes?.length || i.add_notes?.some((n2) => n2.section) || i.remove_sections?.length ? tidyOps(applyOps(b, ops, TK_BOARDS.agent)) : [];
2184
+ if (ops.length) {
2185
+ const all = [...ops, ...tidy];
2186
+ steps.push({ ops: all, what: TK_BOARDS.updateWhiteboard.edit, why: i.why ?? TK_BOARDS.updateWhiteboard.edit, activity: { ...planActivity(ops, TK_BOARDS.updateWhiteboard.edit, batch, via), keys: opKeys(ops).slice(0, 60) }, pauseMs: 0, planFirst: true });
2187
+ }
2188
+ return { steps, problems };
2189
+ }
2190
+ function readBoard(raw, board2) {
2191
+ const i = ReadBoardInput.parse(raw);
2192
+ const last = board2.edits.at(-1);
2193
+ return `${TK_BOARDS.read.head(board2.ref, board2.title, TK_BOARDS.boardKind, summary(board2), last?.by ?? board2.updatedBy)}
2194
+ ${boardText(board2, i.note_ids ? new Set(i.note_ids) : void 0)}`;
2195
+ }
2196
+ function resultText(board2, plan, show) {
2197
+ const problems = plan.problems.length ? TK_BOARDS.skipped(plan.problems.join(TK_BOARDS.problemSep)) : "";
2198
+ const keys = plan.skippedKeys?.length ? TK_BOARDS.draw.skippedKeys(plan.skippedKeys) : "";
2199
+ return `Board ${board2.ref} "${board2.title}": ${summary(board2)}.${problems}${keys} ${show}`.trim();
2200
+ }
2201
+
2202
+ // src/cli/index.ts
2203
+ var board = (r) => r.board;
2204
+ var failed = (x) => !!x && typeof x === "object" && "error" in x && !("edits" in x);
2205
+ function run(r) {
2206
+ switch (r.cmd) {
2207
+ case "tools":
2208
+ return toolSpecs(String(r.show ?? ""), r.names);
2209
+ case "plan": {
2210
+ const via = r.via;
2211
+ const batch = r.batch;
2212
+ if (r.tool === "create") return planCreate(r.input, via, batch);
2213
+ if (r.tool === "draw") return planDraw(r.input, r.board ?? null, via, batch);
2214
+ if (r.tool === "update") return planUpdate(r.input, board(r), via, batch);
2215
+ throw new Error(`unknown tool ${String(r.tool)}`);
2216
+ }
2217
+ case "step":
2218
+ return applyStep(r.owner, r.board ?? r.create, r.step, r.via);
2219
+ case "create":
2220
+ return createBoard(r.owner, r.input, r.ops ?? [], !!r.agent, String(r.by ?? ""), r.via, r.more ?? {});
2221
+ case "edit": {
2222
+ const ops = r.agent ? r.ops : PatchInput.parse({ ops: r.ops }).ops;
2223
+ return editBoard(board(r), ops, !!r.agent, String(r.by ?? ""), String(r.what ?? "edited the board"), void 0, r.via, r.more ?? {});
2224
+ }
2225
+ case "activity":
2226
+ return setActivity(board(r), r.activity ?? null);
2227
+ case "snapshot":
2228
+ return snapshot(board(r), typeof r.since === "number" ? r.since : void 0);
2229
+ case "history":
2230
+ return { board: publicBoard(board(r)), history: historyOf(board(r)) };
2231
+ case "at": {
2232
+ const then = boardAt(board(r), Number(r.version));
2233
+ if (!then) throw new Error(`Version ${String(r.version)} is no longer kept in this board's history.`);
2234
+ return { board: publicBoard({ ...then, activity: void 0 }) };
2235
+ }
2236
+ case "restore": {
2237
+ const out = restoreBoard(board(r), Number(r.version), String(r.by ?? ""));
2238
+ if (failed(out)) throw new Error(out.error);
2239
+ return out;
2240
+ }
2241
+ case "keep": {
2242
+ const out = keepBatch(board(r), String(r.batch), String(r.by ?? ""));
2243
+ if (failed(out)) throw new Error(out.error);
2244
+ return out;
2245
+ }
2246
+ case "undo": {
2247
+ const out = undoBatch(board(r), String(r.batch), String(r.by ?? ""));
2248
+ if (failed(out)) return { conflict: "conflict" in out, error: out.error };
2249
+ return out;
2250
+ }
2251
+ case "read":
2252
+ return readBoard(r.input, board(r));
2253
+ case "result":
2254
+ return resultText(board(r), r.plan, String(r.show ?? ""));
2255
+ default:
2256
+ throw new Error(`unknown command ${r.cmd}`);
2257
+ }
2258
+ }
2259
+ async function main() {
2260
+ const chunks = [];
2261
+ for await (const c of process.stdin) chunks.push(c);
2262
+ try {
2263
+ const req = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2264
+ process.stdout.write(JSON.stringify({ ok: true, result: run(req) }));
2265
+ } catch (e) {
2266
+ const issues = e.issues;
2267
+ const error = issues ? issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") : e instanceof Error ? e.message : String(e);
2268
+ process.stdout.write(JSON.stringify({ ok: false, error }));
2269
+ process.exitCode = 1;
2270
+ }
2271
+ }
2272
+ void main();