@kombai/cli 0.1.2-beta.1 → 0.1.2-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kombai.mjs CHANGED
@@ -48,6 +48,955 @@ var init_define_KOMBAI_TELEMETRY = __esm({
48
48
  }
49
49
  });
50
50
 
51
+ // ../design-mode/node_modules/fflate/esm/index.mjs
52
+ import { createRequire } from "module";
53
+ function deflateSync(data, opts) {
54
+ return dopt(data, opts || {}, 0, 0);
55
+ }
56
+ function strToU8(str, latin1) {
57
+ if (latin1) {
58
+ var ar_1 = new u8(str.length);
59
+ for (var i = 0; i < str.length; ++i)
60
+ ar_1[i] = str.charCodeAt(i);
61
+ return ar_1;
62
+ }
63
+ if (te)
64
+ return te.encode(str);
65
+ var l = str.length;
66
+ var ar = new u8(str.length + (str.length >> 1));
67
+ var ai = 0;
68
+ var w = function(v) {
69
+ ar[ai++] = v;
70
+ };
71
+ for (var i = 0; i < l; ++i) {
72
+ if (ai + 5 > ar.length) {
73
+ var n = new u8(ai + 8 + (l - i << 1));
74
+ n.set(ar);
75
+ ar = n;
76
+ }
77
+ var c = str.charCodeAt(i);
78
+ if (c < 128 || latin1)
79
+ w(c);
80
+ else if (c < 2048)
81
+ w(192 | c >> 6), w(128 | c & 63);
82
+ else if (c > 55295 && c < 57344)
83
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
84
+ else
85
+ w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
86
+ }
87
+ return slc(ar, 0, ai);
88
+ }
89
+ function zipSync(data, opts) {
90
+ if (!opts)
91
+ opts = {};
92
+ var r = {};
93
+ var files = [];
94
+ fltn(data, "", r, opts);
95
+ var o = 0;
96
+ var tot = 0;
97
+ for (var fn in r) {
98
+ var _a3 = r[fn], file2 = _a3[0], p = _a3[1];
99
+ var compression = p.level == 0 ? 0 : 8;
100
+ var f = strToU8(fn), s = f.length;
101
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
102
+ var exl = exfl(p.extra);
103
+ if (s > 65535)
104
+ err(11);
105
+ var d = compression ? deflateSync(file2, p) : file2, l = d.length;
106
+ var c = crc();
107
+ c.p(file2);
108
+ files.push(mrg(p, {
109
+ size: file2.length,
110
+ crc: c.d(),
111
+ c: d,
112
+ f,
113
+ m,
114
+ u: s != fn.length || m && com.length != ms,
115
+ o,
116
+ compression
117
+ }));
118
+ o += 30 + s + exl + l;
119
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
120
+ }
121
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
122
+ for (var i = 0; i < files.length; ++i) {
123
+ var f = files[i];
124
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
125
+ var badd = 30 + f.f.length + exfl(f.extra);
126
+ out.set(f.c, f.o + badd);
127
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
128
+ }
129
+ wzf(out, o, files.length, cdl, oe);
130
+ return out;
131
+ }
132
+ var require2, _a, Worker, isMarkedAsUntransferable, u8, u16, i32, fleb, fdeb, clim, freb, _a, fl, revfl, _b, fd, revfd, rev, x, i, hMap, flt, i, i, i, i, fdt, i, flm, fdm, shft, slc, ec, err, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, deo, et, dflt, crct, crc, dopt, mrg, wbytes, fltn, te, td, tds, exfl, wzh, wzf;
133
+ var init_esm = __esm({
134
+ "../design-mode/node_modules/fflate/esm/index.mjs"() {
135
+ init_define_KOMBAI_TELEMETRY();
136
+ require2 = createRequire("/");
137
+ try {
138
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
139
+ } catch (e) {
140
+ }
141
+ u8 = Uint8Array;
142
+ u16 = Uint16Array;
143
+ i32 = Int32Array;
144
+ fleb = new u8([
145
+ 0,
146
+ 0,
147
+ 0,
148
+ 0,
149
+ 0,
150
+ 0,
151
+ 0,
152
+ 0,
153
+ 1,
154
+ 1,
155
+ 1,
156
+ 1,
157
+ 2,
158
+ 2,
159
+ 2,
160
+ 2,
161
+ 3,
162
+ 3,
163
+ 3,
164
+ 3,
165
+ 4,
166
+ 4,
167
+ 4,
168
+ 4,
169
+ 5,
170
+ 5,
171
+ 5,
172
+ 5,
173
+ 0,
174
+ /* unused */
175
+ 0,
176
+ 0,
177
+ /* impossible */
178
+ 0
179
+ ]);
180
+ fdeb = new u8([
181
+ 0,
182
+ 0,
183
+ 0,
184
+ 0,
185
+ 1,
186
+ 1,
187
+ 2,
188
+ 2,
189
+ 3,
190
+ 3,
191
+ 4,
192
+ 4,
193
+ 5,
194
+ 5,
195
+ 6,
196
+ 6,
197
+ 7,
198
+ 7,
199
+ 8,
200
+ 8,
201
+ 9,
202
+ 9,
203
+ 10,
204
+ 10,
205
+ 11,
206
+ 11,
207
+ 12,
208
+ 12,
209
+ 13,
210
+ 13,
211
+ /* unused */
212
+ 0,
213
+ 0
214
+ ]);
215
+ clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
216
+ freb = function(eb, start) {
217
+ var b = new u16(31);
218
+ for (var i = 0; i < 31; ++i) {
219
+ b[i] = start += 1 << eb[i - 1];
220
+ }
221
+ var r = new i32(b[30]);
222
+ for (var i = 1; i < 30; ++i) {
223
+ for (var j = b[i]; j < b[i + 1]; ++j) {
224
+ r[j] = j - b[i] << 5 | i;
225
+ }
226
+ }
227
+ return { b, r };
228
+ };
229
+ _a = freb(fleb, 2);
230
+ fl = _a.b;
231
+ revfl = _a.r;
232
+ fl[28] = 258, revfl[258] = 28;
233
+ _b = freb(fdeb, 0);
234
+ fd = _b.b;
235
+ revfd = _b.r;
236
+ rev = new u16(32768);
237
+ for (i = 0; i < 32768; ++i) {
238
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
239
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
240
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
241
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
242
+ }
243
+ hMap = (function(cd, mb, r) {
244
+ var s = cd.length;
245
+ var i = 0;
246
+ var l = new u16(mb);
247
+ for (; i < s; ++i) {
248
+ if (cd[i])
249
+ ++l[cd[i] - 1];
250
+ }
251
+ var le = new u16(mb);
252
+ for (i = 1; i < mb; ++i) {
253
+ le[i] = le[i - 1] + l[i - 1] << 1;
254
+ }
255
+ var co;
256
+ if (r) {
257
+ co = new u16(1 << mb);
258
+ var rvb = 15 - mb;
259
+ for (i = 0; i < s; ++i) {
260
+ if (cd[i]) {
261
+ var sv = i << 4 | cd[i];
262
+ var r_1 = mb - cd[i];
263
+ var v = le[cd[i] - 1]++ << r_1;
264
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
265
+ co[rev[v] >> rvb] = sv;
266
+ }
267
+ }
268
+ }
269
+ } else {
270
+ co = new u16(s);
271
+ for (i = 0; i < s; ++i) {
272
+ if (cd[i]) {
273
+ co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
274
+ }
275
+ }
276
+ }
277
+ return co;
278
+ });
279
+ flt = new u8(288);
280
+ for (i = 0; i < 144; ++i)
281
+ flt[i] = 8;
282
+ for (i = 144; i < 256; ++i)
283
+ flt[i] = 9;
284
+ for (i = 256; i < 280; ++i)
285
+ flt[i] = 7;
286
+ for (i = 280; i < 288; ++i)
287
+ flt[i] = 8;
288
+ fdt = new u8(32);
289
+ for (i = 0; i < 32; ++i)
290
+ fdt[i] = 5;
291
+ flm = /* @__PURE__ */ hMap(flt, 9, 0);
292
+ fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
293
+ shft = function(p) {
294
+ return (p + 7) / 8 | 0;
295
+ };
296
+ slc = function(v, s, e) {
297
+ if (s == null || s < 0)
298
+ s = 0;
299
+ if (e == null || e > v.length)
300
+ e = v.length;
301
+ return new u8(v.subarray(s, e));
302
+ };
303
+ ec = [
304
+ "unexpected EOF",
305
+ "invalid block type",
306
+ "invalid length/literal",
307
+ "invalid distance",
308
+ "stream finished",
309
+ "no stream handler",
310
+ ,
311
+ // determined by compression function
312
+ "no callback",
313
+ "invalid UTF-8 data",
314
+ "extra field too long",
315
+ "date not in range 1980-2099",
316
+ "filename too long",
317
+ "stream finishing",
318
+ "invalid zip data"
319
+ // determined by unknown compression method
320
+ ];
321
+ err = function(ind, msg, nt) {
322
+ var e = new Error(msg || ec[ind]);
323
+ e.code = ind;
324
+ if (Error.captureStackTrace)
325
+ Error.captureStackTrace(e, err);
326
+ if (!nt)
327
+ throw e;
328
+ return e;
329
+ };
330
+ wbits = function(d, p, v) {
331
+ v <<= p & 7;
332
+ var o = p / 8 | 0;
333
+ d[o] |= v;
334
+ d[o + 1] |= v >> 8;
335
+ };
336
+ wbits16 = function(d, p, v) {
337
+ v <<= p & 7;
338
+ var o = p / 8 | 0;
339
+ d[o] |= v;
340
+ d[o + 1] |= v >> 8;
341
+ d[o + 2] |= v >> 16;
342
+ };
343
+ hTree = function(d, mb) {
344
+ var t = [];
345
+ for (var i = 0; i < d.length; ++i) {
346
+ if (d[i])
347
+ t.push({ s: i, f: d[i] });
348
+ }
349
+ var s = t.length;
350
+ var t2 = t.slice();
351
+ if (!s)
352
+ return { t: et, l: 0 };
353
+ if (s == 1) {
354
+ var v = new u8(t[0].s + 1);
355
+ v[t[0].s] = 1;
356
+ return { t: v, l: 1 };
357
+ }
358
+ t.sort(function(a, b) {
359
+ return a.f - b.f;
360
+ });
361
+ t.push({ s: -1, f: 25001 });
362
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2;
363
+ t[0] = { s: -1, f: l.f + r.f, l, r };
364
+ while (i1 != s - 1) {
365
+ l = t[t[i0].f < t[i2].f ? i0++ : i2++];
366
+ r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++];
367
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
368
+ }
369
+ var maxSym = t2[0].s;
370
+ for (var i = 1; i < s; ++i) {
371
+ if (t2[i].s > maxSym)
372
+ maxSym = t2[i].s;
373
+ }
374
+ var tr = new u16(maxSym + 1);
375
+ var mbt = ln(t[i1 - 1], tr, 0);
376
+ if (mbt > mb) {
377
+ var i = 0, dt = 0;
378
+ var lft = mbt - mb, cst = 1 << lft;
379
+ t2.sort(function(a, b) {
380
+ return tr[b.s] - tr[a.s] || a.f - b.f;
381
+ });
382
+ for (; i < s; ++i) {
383
+ var i2_1 = t2[i].s;
384
+ if (tr[i2_1] > mb) {
385
+ dt += cst - (1 << mbt - tr[i2_1]);
386
+ tr[i2_1] = mb;
387
+ } else
388
+ break;
389
+ }
390
+ dt >>= lft;
391
+ while (dt > 0) {
392
+ var i2_2 = t2[i].s;
393
+ if (tr[i2_2] < mb)
394
+ dt -= 1 << mb - tr[i2_2]++ - 1;
395
+ else
396
+ ++i;
397
+ }
398
+ for (; i >= 0 && dt; --i) {
399
+ var i2_3 = t2[i].s;
400
+ if (tr[i2_3] == mb) {
401
+ --tr[i2_3];
402
+ ++dt;
403
+ }
404
+ }
405
+ mbt = mb;
406
+ }
407
+ return { t: new u8(tr), l: mbt };
408
+ };
409
+ ln = function(n, l, d) {
410
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
411
+ };
412
+ lc = function(c) {
413
+ var s = c.length;
414
+ while (s && !c[--s])
415
+ ;
416
+ var cl = new u16(++s);
417
+ var cli = 0, cln = c[0], cls = 1;
418
+ var w = function(v) {
419
+ cl[cli++] = v;
420
+ };
421
+ for (var i = 1; i <= s; ++i) {
422
+ if (c[i] == cln && i != s)
423
+ ++cls;
424
+ else {
425
+ if (!cln && cls > 2) {
426
+ for (; cls > 138; cls -= 138)
427
+ w(32754);
428
+ if (cls > 2) {
429
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
430
+ cls = 0;
431
+ }
432
+ } else if (cls > 3) {
433
+ w(cln), --cls;
434
+ for (; cls > 6; cls -= 6)
435
+ w(8304);
436
+ if (cls > 2)
437
+ w(cls - 3 << 5 | 8208), cls = 0;
438
+ }
439
+ while (cls--)
440
+ w(cln);
441
+ cls = 1;
442
+ cln = c[i];
443
+ }
444
+ }
445
+ return { c: cl.subarray(0, cli), n: s };
446
+ };
447
+ clen = function(cf, cl) {
448
+ var l = 0;
449
+ for (var i = 0; i < cl.length; ++i)
450
+ l += cf[i] * cl[i];
451
+ return l;
452
+ };
453
+ wfblk = function(out, pos, dat) {
454
+ var s = dat.length;
455
+ var o = shft(pos + 2);
456
+ out[o] = s & 255;
457
+ out[o + 1] = s >> 8;
458
+ out[o + 2] = out[o] ^ 255;
459
+ out[o + 3] = out[o + 1] ^ 255;
460
+ for (var i = 0; i < s; ++i)
461
+ out[o + i + 4] = dat[i];
462
+ return (o + 4 + s) * 8;
463
+ };
464
+ wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
465
+ wbits(out, p++, final);
466
+ ++lf[256];
467
+ var _a3 = hTree(lf, 15), dlt = _a3.t, mlb = _a3.l;
468
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
469
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
470
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
471
+ var lcfreq = new u16(19);
472
+ for (var i = 0; i < lclt.length; ++i)
473
+ ++lcfreq[lclt[i] & 31];
474
+ for (var i = 0; i < lcdt.length; ++i)
475
+ ++lcfreq[lcdt[i] & 31];
476
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
477
+ var nlcc = 19;
478
+ for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
479
+ ;
480
+ var flen = bl + 5 << 3;
481
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
482
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
483
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
484
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
485
+ var lm, ll, dm, dl;
486
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
487
+ if (dtlen < ftlen) {
488
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
489
+ var llm = hMap(lct, mlcb, 0);
490
+ wbits(out, p, nlc - 257);
491
+ wbits(out, p + 5, ndc - 1);
492
+ wbits(out, p + 10, nlcc - 4);
493
+ p += 14;
494
+ for (var i = 0; i < nlcc; ++i)
495
+ wbits(out, p + 3 * i, lct[clim[i]]);
496
+ p += 3 * nlcc;
497
+ var lcts = [lclt, lcdt];
498
+ for (var it = 0; it < 2; ++it) {
499
+ var clct = lcts[it];
500
+ for (var i = 0; i < clct.length; ++i) {
501
+ var len = clct[i] & 31;
502
+ wbits(out, p, llm[len]), p += lct[len];
503
+ if (len > 15)
504
+ wbits(out, p, clct[i] >> 5 & 127), p += clct[i] >> 12;
505
+ }
506
+ }
507
+ } else {
508
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
509
+ }
510
+ for (var i = 0; i < li; ++i) {
511
+ var sym = syms[i];
512
+ if (sym > 255) {
513
+ var len = sym >> 18 & 31;
514
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
515
+ if (len > 7)
516
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
517
+ var dst = sym & 31;
518
+ wbits16(out, p, dm[dst]), p += dl[dst];
519
+ if (dst > 3)
520
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
521
+ } else {
522
+ wbits16(out, p, lm[sym]), p += ll[sym];
523
+ }
524
+ }
525
+ wbits16(out, p, lm[256]);
526
+ return p + ll[256];
527
+ };
528
+ deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
529
+ et = /* @__PURE__ */ new u8(0);
530
+ dflt = function(dat, lvl, plvl, pre, post, st) {
531
+ var s = st.z || dat.length;
532
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post);
533
+ var w = o.subarray(pre, o.length - post);
534
+ var lst = st.l;
535
+ var pos = (st.r || 0) & 7;
536
+ if (lvl) {
537
+ if (pos)
538
+ w[0] = st.r >> 3;
539
+ var opt = deo[lvl - 1];
540
+ var n = opt >> 13, c = opt & 8191;
541
+ var msk_1 = (1 << plvl) - 1;
542
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
543
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
544
+ var hsh = function(i2) {
545
+ return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1;
546
+ };
547
+ var syms = new i32(25e3);
548
+ var lf = new u16(288), df = new u16(32);
549
+ var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
550
+ for (; i + 2 < s; ++i) {
551
+ var hv = hsh(i);
552
+ var imod = i & 32767, pimod = head[hv];
553
+ prev[imod] = pimod;
554
+ head[hv] = imod;
555
+ if (wi <= i) {
556
+ var rem = s - i;
557
+ if ((lc_1 > 7e3 || li > 24576) && (rem > 423 || !lst)) {
558
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos);
559
+ li = lc_1 = eb = 0, bs = i;
560
+ for (var j = 0; j < 286; ++j)
561
+ lf[j] = 0;
562
+ for (var j = 0; j < 30; ++j)
563
+ df[j] = 0;
564
+ }
565
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
566
+ if (rem > 2 && hv == hsh(i - dif)) {
567
+ var maxn = Math.min(n, rem) - 1;
568
+ var maxd = Math.min(32767, i);
569
+ var ml = Math.min(258, rem);
570
+ while (dif <= maxd && --ch_1 && imod != pimod) {
571
+ if (dat[i + l] == dat[i + l - dif]) {
572
+ var nl = 0;
573
+ for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl)
574
+ ;
575
+ if (nl > l) {
576
+ l = nl, d = dif;
577
+ if (nl > maxn)
578
+ break;
579
+ var mmd = Math.min(dif, nl - 2);
580
+ var md = 0;
581
+ for (var j = 0; j < mmd; ++j) {
582
+ var ti = i - dif + j & 32767;
583
+ var pti = prev[ti];
584
+ var cd = ti - pti & 32767;
585
+ if (cd > md)
586
+ md = cd, pimod = ti;
587
+ }
588
+ }
589
+ }
590
+ imod = pimod, pimod = prev[imod];
591
+ dif += imod - pimod & 32767;
592
+ }
593
+ }
594
+ if (d) {
595
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
596
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
597
+ eb += fleb[lin] + fdeb[din];
598
+ ++lf[257 + lin];
599
+ ++df[din];
600
+ wi = i + l;
601
+ ++lc_1;
602
+ } else {
603
+ syms[li++] = dat[i];
604
+ ++lf[dat[i]];
605
+ }
606
+ }
607
+ }
608
+ for (i = Math.max(i, wi); i < s; ++i) {
609
+ syms[li++] = dat[i];
610
+ ++lf[dat[i]];
611
+ }
612
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos);
613
+ if (!lst) {
614
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
615
+ pos -= 7;
616
+ st.h = head, st.p = prev, st.i = i, st.w = wi;
617
+ }
618
+ } else {
619
+ for (var i = st.w || 0; i < s + lst; i += 65535) {
620
+ var e = i + 65535;
621
+ if (e >= s) {
622
+ w[pos / 8 | 0] = lst;
623
+ e = s;
624
+ }
625
+ pos = wfblk(w, pos + 1, dat.subarray(i, e));
626
+ }
627
+ st.i = s;
628
+ }
629
+ return slc(o, 0, pre + shft(pos) + post);
630
+ };
631
+ crct = /* @__PURE__ */ (function() {
632
+ var t = new Int32Array(256);
633
+ for (var i = 0; i < 256; ++i) {
634
+ var c = i, k = 9;
635
+ while (--k)
636
+ c = (c & 1 && -306674912) ^ c >>> 1;
637
+ t[i] = c;
638
+ }
639
+ return t;
640
+ })();
641
+ crc = function() {
642
+ var c = -1;
643
+ return {
644
+ p: function(d) {
645
+ var cr = c;
646
+ for (var i = 0; i < d.length; ++i)
647
+ cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8;
648
+ c = cr;
649
+ },
650
+ d: function() {
651
+ return ~c;
652
+ }
653
+ };
654
+ };
655
+ dopt = function(dat, opt, pre, post, st) {
656
+ if (!st) {
657
+ st = { l: 1 };
658
+ if (opt.dictionary) {
659
+ var dict = opt.dictionary.subarray(-32768);
660
+ var newDat = new u8(dict.length + dat.length);
661
+ newDat.set(dict);
662
+ newDat.set(dat, dict.length);
663
+ dat = newDat;
664
+ st.w = dict.length;
665
+ }
666
+ }
667
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
668
+ };
669
+ mrg = function(a, b) {
670
+ var o = {};
671
+ for (var k in a)
672
+ o[k] = a[k];
673
+ for (var k in b)
674
+ o[k] = b[k];
675
+ return o;
676
+ };
677
+ wbytes = function(d, b, v) {
678
+ for (; v; ++b)
679
+ d[b] = v, v >>>= 8;
680
+ };
681
+ fltn = function(d, p, t, o) {
682
+ for (var k in d) {
683
+ var val = d[k], n = p + k, op = o;
684
+ if (Array.isArray(val))
685
+ op = mrg(o, val[1]), val = val[0];
686
+ if (ArrayBuffer.isView(val))
687
+ t[n] = [val, op];
688
+ else {
689
+ t[n += "/"] = [new u8(0), op];
690
+ fltn(val, n, t, o);
691
+ }
692
+ }
693
+ };
694
+ te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder();
695
+ td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
696
+ tds = 0;
697
+ try {
698
+ td.decode(et, { stream: true });
699
+ tds = 1;
700
+ } catch (e) {
701
+ }
702
+ exfl = function(ex) {
703
+ var le = 0;
704
+ if (ex) {
705
+ for (var k in ex) {
706
+ var l = ex[k].length;
707
+ if (l > 65535)
708
+ err(9);
709
+ le += l + 4;
710
+ }
711
+ }
712
+ return le;
713
+ };
714
+ wzh = function(d, b, f, fn, u, c, ce, co) {
715
+ var fl2 = fn.length, ex = f.extra, col = co && co.length;
716
+ var exl = exfl(ex);
717
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
718
+ if (ce != null)
719
+ d[b++] = 20, d[b++] = f.os;
720
+ d[b] = 20, b += 2;
721
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
722
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
723
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
724
+ if (y < 0 || y > 119)
725
+ err(10);
726
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
727
+ if (c != -1) {
728
+ wbytes(d, b, f.crc);
729
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
730
+ wbytes(d, b + 8, f.size);
731
+ }
732
+ wbytes(d, b + 12, fl2);
733
+ wbytes(d, b + 14, exl), b += 16;
734
+ if (ce != null) {
735
+ wbytes(d, b, col);
736
+ wbytes(d, b + 6, f.attrs);
737
+ wbytes(d, b + 10, ce), b += 14;
738
+ }
739
+ d.set(fn, b);
740
+ b += fl2;
741
+ if (exl) {
742
+ for (var k in ex) {
743
+ var exf = ex[k], l = exf.length;
744
+ wbytes(d, b, +k);
745
+ wbytes(d, b + 2, l);
746
+ d.set(exf, b + 4), b += 4 + l;
747
+ }
748
+ }
749
+ if (col)
750
+ d.set(co, b), b += col;
751
+ return b;
752
+ };
753
+ wzf = function(o, b, c, d, e) {
754
+ wbytes(o, b, 101010256);
755
+ wbytes(o, b + 8, c);
756
+ wbytes(o, b + 10, c);
757
+ wbytes(o, b + 12, d);
758
+ wbytes(o, b + 16, e);
759
+ };
760
+ }
761
+ });
762
+
763
+ // ../design-mode/packages/shared/src/canvas-document.ts
764
+ function sanitizeCanvasSegment(segment) {
765
+ return segment.replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "");
766
+ }
767
+ var CANVAS_ASSET_SRC_RE;
768
+ var init_canvas_document = __esm({
769
+ "../design-mode/packages/shared/src/canvas-document.ts"() {
770
+ "use strict";
771
+ init_define_KOMBAI_TELEMETRY();
772
+ CANVAS_ASSET_SRC_RE = /^\/api\/local\/images\/\.kombai\/canvas\/assets\/[a-f0-9]{64}\.(?:png|jpe?g|webp|gif|svg)$/;
773
+ }
774
+ });
775
+
776
+ // ../design-mode/packages/shared/src/canvas-download.ts
777
+ function canvasDownloadBaseName(name) {
778
+ const base = sanitizeCanvasSegment(name) || CANVAS_DOWNLOAD_FALLBACK_NAME;
779
+ return WINDOWS_DEVICE_NAME_RE.test(base) ? `${base}${WINDOWS_DEVICE_SUFFIX}` : base;
780
+ }
781
+ function downloadAssetPathOf(image) {
782
+ const own = `${LOCAL_IMAGES_PREFIX}${CANVAS_DOWNLOAD_ASSETS_DIR}/${image.sha256}.`;
783
+ if (image.path.startsWith(own) && CANVAS_ASSET_SRC_RE.test(image.path)) {
784
+ return image.path.slice(LOCAL_IMAGES_PREFIX.length);
785
+ }
786
+ return `${CANVAS_DOWNLOAD_ASSETS_DIR}/${image.sha256}.${EXTENSION_OF_TYPE[image.contentType]}`;
787
+ }
788
+ function swapReferences(text, swaps) {
789
+ if (swaps.size === 0) return text;
790
+ const pattern = new RegExp(
791
+ [...swaps.keys()].sort((a, b) => b.length - a.length).map(escapeForRegExp).join("|"),
792
+ "g"
793
+ );
794
+ return text.replace(pattern, (found) => swaps.get(found) ?? found);
795
+ }
796
+ function swapOverrides(overrides, swaps) {
797
+ const out = {};
798
+ if (overrides.htmlAttrs !== void 0) out.htmlAttrs = swapReferences(overrides.htmlAttrs, swaps);
799
+ if (overrides.bodyAttrs !== void 0) out.bodyAttrs = swapReferences(overrides.bodyAttrs, swaps);
800
+ if (overrides.head !== void 0) out.head = swapReferences(overrides.head, swaps);
801
+ return out;
802
+ }
803
+ function downloadNodeOf(lite, body, swaps) {
804
+ switch (lite.type) {
805
+ case "variant":
806
+ return {
807
+ ...lite,
808
+ html: swapReferences(body.html ?? "", swaps),
809
+ ...body.overrides ? { overrides: swapOverrides(body.overrides, swaps) } : {}
810
+ };
811
+ case "text":
812
+ return { ...lite, html: swapReferences(body.html ?? "", swaps) };
813
+ case "drawing": {
814
+ if (!body.content) return null;
815
+ const content = body.content.kind === "image" ? { ...body.content, src: swaps.get(body.content.src) ?? body.content.src } : body.content;
816
+ return { ...lite, content };
817
+ }
818
+ case "frame":
819
+ return { ...lite };
820
+ }
821
+ }
822
+ function buildCanvasDownload(read2, bodies) {
823
+ const nodes = {};
824
+ const assets = /* @__PURE__ */ new Map();
825
+ const unlisted = /* @__PURE__ */ new Set();
826
+ for (const [nodeId, lite] of Object.entries(read2.document.nodes)) {
827
+ const files = read2.nodeFiles[nodeId];
828
+ if (!files || files.state === "pending") continue;
829
+ const swaps = /* @__PURE__ */ new Map();
830
+ const nodeAssets = [];
831
+ for (const image of files.images ?? []) {
832
+ const path25 = downloadAssetPathOf(image);
833
+ swaps.set(image.path, `${LOCAL_IMAGES_PREFIX}${path25}`);
834
+ nodeAssets.push({ path: path25, url: image.url, contentType: image.contentType });
835
+ }
836
+ const body = bodies[nodeId] ?? {};
837
+ const node = downloadNodeOf(lite, body, swaps);
838
+ if (!node) continue;
839
+ nodes[nodeId] = node;
840
+ for (const asset of nodeAssets) if (!assets.has(asset.path)) assets.set(asset.path, asset);
841
+ const src = body.content?.kind === "image" ? body.content.src : null;
842
+ if (src !== null && src.startsWith(LOCAL_IMAGES_PREFIX) && !swaps.has(src)) unlisted.add(src);
843
+ }
844
+ for (const node of Object.values(nodes)) {
845
+ if (node.parentId !== null && !Object.hasOwn(nodes, node.parentId)) node.parentId = null;
846
+ if ((node.type === "text" || node.type === "drawing") && node.frameId && !Object.hasOwn(nodes, node.frameId)) {
847
+ node.frameId = null;
848
+ }
849
+ }
850
+ const document2 = {
851
+ created: read2.document.created,
852
+ modified: read2.document.modified,
853
+ canvas: {
854
+ viewport: { ...read2.document.canvas.viewport },
855
+ selected: read2.document.canvas.selected.filter((id) => Object.hasOwn(nodes, id))
856
+ },
857
+ nodes,
858
+ comments: read2.document.comments,
859
+ nextCommentNumber: read2.document.nextCommentNumber
860
+ };
861
+ const baseName = canvasDownloadBaseName(read2.document.name);
862
+ return {
863
+ baseName,
864
+ canvasPath: `${CANVAS_DOWNLOAD_DIR}/${baseName}.canvas`,
865
+ canvasText: JSON.stringify(document2, null, 2),
866
+ assets: [...assets.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0),
867
+ // An image another node lists, and so packed, is not left out.
868
+ unlistedImages: [...unlisted].filter((src) => !assets.has(src.slice(LOCAL_IMAGES_PREFIX.length))).sort(),
869
+ designCount: Object.values(nodes).filter((node) => node.type === "variant").length,
870
+ modified: read2.document.modified
871
+ };
872
+ }
873
+ function canvasDownloadFiles(download, assetBytes) {
874
+ const files = { [download.canvasPath]: strToU8(download.canvasText) };
875
+ for (const asset of download.assets) {
876
+ const bytes = assetBytes.get(asset.path);
877
+ if (bytes) files[asset.path] = bytes;
878
+ }
879
+ return files;
880
+ }
881
+ function zipCanvasDownload(download, files) {
882
+ const parsed = Date.parse(download.modified);
883
+ const mtime = Number.isFinite(parsed) ? parsed : FALLBACK_ENTRY_TIME;
884
+ const entries = {};
885
+ for (const [path25, bytes] of Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
886
+ entries[path25] = [bytes, { level: entryLevel(path25), mtime }];
887
+ }
888
+ return zipSync(entries);
889
+ }
890
+ async function mapPooled(items, limit, run3) {
891
+ const results = new Array(items.length);
892
+ let next = 0;
893
+ let failed2 = false;
894
+ const worker = async () => {
895
+ while (!failed2 && next < items.length) {
896
+ const index = next++;
897
+ try {
898
+ results[index] = await run3(items[index]);
899
+ } catch (err2) {
900
+ failed2 = true;
901
+ throw err2;
902
+ }
903
+ }
904
+ };
905
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
906
+ return results;
907
+ }
908
+ async function nodeBodiesOf(read2, fetchText) {
909
+ const jobs = [];
910
+ for (const [nodeId, files] of Object.entries(read2.nodeFiles)) {
911
+ if (files.state !== "stored" || !Object.hasOwn(read2.document.nodes, nodeId)) continue;
912
+ if (files.html) jobs.push({ nodeId, file: "html", url: files.html });
913
+ if (files.overrides) jobs.push({ nodeId, file: "overrides", url: files.overrides });
914
+ if (files.content) jobs.push({ nodeId, file: "content", url: files.content });
915
+ }
916
+ const texts = await mapPooled(jobs, CANVAS_DOWNLOAD_FETCH_CONCURRENCY, (job) => fetchText(job.url));
917
+ const bodies = {};
918
+ jobs.forEach((job, index) => {
919
+ const text = texts[index];
920
+ const body = bodies[job.nodeId] ??= {};
921
+ if (job.file === "html") body.html = text;
922
+ else if (job.file === "overrides") body.overrides = JSON.parse(text);
923
+ else body.content = JSON.parse(text);
924
+ });
925
+ return bodies;
926
+ }
927
+ async function downloadCanvasZip(read2, fetchers) {
928
+ let bodies;
929
+ try {
930
+ bodies = await nodeBodiesOf(read2, fetchers.fetchText);
931
+ } catch (err2) {
932
+ throw new CanvasDownloadFetchError("node-file" /* NodeFile */, { cause: err2 });
933
+ }
934
+ const download = buildCanvasDownload(read2, bodies);
935
+ let fetched;
936
+ try {
937
+ fetched = await mapPooled(download.assets, CANVAS_DOWNLOAD_FETCH_CONCURRENCY, async (asset) => ({
938
+ asset,
939
+ bytes: await fetchers.fetchBytes(asset.url)
940
+ }));
941
+ } catch (err2) {
942
+ throw new CanvasDownloadFetchError("image" /* Image */, { cause: err2 });
943
+ }
944
+ const assetBytes = /* @__PURE__ */ new Map();
945
+ const missingImages = [];
946
+ for (const { asset, bytes } of fetched) {
947
+ if (bytes) assetBytes.set(asset.path, bytes);
948
+ else missingImages.push(asset);
949
+ }
950
+ const files = canvasDownloadFiles(download, assetBytes);
951
+ return {
952
+ fileName: `${download.baseName}.zip`,
953
+ zip: zipCanvasDownload(download, files),
954
+ files,
955
+ designCount: download.designCount,
956
+ imageCount: assetBytes.size,
957
+ missingImages,
958
+ unlistedImages: download.unlistedImages
959
+ };
960
+ }
961
+ var CANVAS_DOWNLOAD_DIR, CANVAS_DOWNLOAD_ASSETS_DIR, LOCAL_IMAGES_PREFIX, CANVAS_DOWNLOAD_FALLBACK_NAME, WINDOWS_DEVICE_NAME_RE, WINDOWS_DEVICE_SUFFIX, FALLBACK_ENTRY_TIME, CANVAS_DOWNLOAD_FETCH_CONCURRENCY, EXTENSION_OF_TYPE, CanvasDownloadFetchError, escapeForRegExp, entryLevel;
962
+ var init_canvas_download = __esm({
963
+ "../design-mode/packages/shared/src/canvas-download.ts"() {
964
+ "use strict";
965
+ init_define_KOMBAI_TELEMETRY();
966
+ init_esm();
967
+ init_canvas_document();
968
+ CANVAS_DOWNLOAD_DIR = ".kombai/canvas";
969
+ CANVAS_DOWNLOAD_ASSETS_DIR = ".kombai/canvas/assets";
970
+ LOCAL_IMAGES_PREFIX = "/api/local/images/";
971
+ CANVAS_DOWNLOAD_FALLBACK_NAME = "canvas";
972
+ WINDOWS_DEVICE_NAME_RE = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
973
+ WINDOWS_DEVICE_SUFFIX = "-canvas";
974
+ FALLBACK_ENTRY_TIME = Date.UTC(2026, 0, 1);
975
+ CANVAS_DOWNLOAD_FETCH_CONCURRENCY = 8;
976
+ EXTENSION_OF_TYPE = {
977
+ "image/png": "png",
978
+ "image/jpeg": "jpg",
979
+ "image/webp": "webp",
980
+ "image/gif": "gif",
981
+ "image/svg+xml": "svg",
982
+ "video/mp4": "mp4",
983
+ "video/webm": "webm"
984
+ };
985
+ CanvasDownloadFetchError = class extends Error {
986
+ constructor(failure, options) {
987
+ super(
988
+ failure === "node-file" /* NodeFile */ ? "A design file could not be fetched" : "An image could not be fetched",
989
+ options
990
+ );
991
+ this.failure = failure;
992
+ this.name = "CanvasDownloadFetchError";
993
+ }
994
+ };
995
+ escapeForRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
996
+ entryLevel = (path25) => path25.endsWith(".canvas") || path25.endsWith(".svg") ? 6 : 0;
997
+ }
998
+ });
999
+
51
1000
  // ../design-mode/packages/shared/src/design-api.ts
52
1001
  function normalizeGitRemote(remote) {
53
1002
  const trimmed = remote.trim();
@@ -176,21 +1125,12 @@ var init_id = __esm({
176
1125
  }
177
1126
  });
178
1127
 
179
- // ../design-mode/packages/shared/src/canvas-document.ts
180
- var CANVAS_ASSET_SRC_RE;
181
- var init_canvas_document = __esm({
182
- "../design-mode/packages/shared/src/canvas-document.ts"() {
183
- "use strict";
184
- init_define_KOMBAI_TELEMETRY();
185
- CANVAS_ASSET_SRC_RE = /^\/api\/local\/images\/\.kombai\/canvas\/assets\/[a-f0-9]{64}\.(?:png|jpe?g|webp|gif|svg)$/;
186
- }
187
- });
188
-
189
1128
  // src/lib/contract.js
190
1129
  var init_contract = __esm({
191
1130
  "src/lib/contract.js"() {
192
1131
  "use strict";
193
1132
  init_define_KOMBAI_TELEMETRY();
1133
+ init_canvas_download();
194
1134
  init_design_api();
195
1135
  init_id();
196
1136
  init_canvas_document();
@@ -818,7 +1758,7 @@ var init_version = __esm({
818
1758
  "src/lib/version.js"() {
819
1759
  "use strict";
820
1760
  init_define_KOMBAI_TELEMETRY();
821
- CLI_VERSION = true ? "0.1.2-beta.1" : (
1761
+ CLI_VERSION = true ? "0.1.2-beta.3" : (
822
1762
  /** @type {{ version: string }} */
823
1763
  JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version
824
1764
  );
@@ -849,7 +1789,7 @@ function retryAfterMs(value) {
849
1789
  const at = Date.parse(value ?? "");
850
1790
  return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 2e3;
851
1791
  }
852
- function apiError(status, body, method, path22) {
1792
+ function apiError(status, body, method, path25) {
853
1793
  const {
854
1794
  errorCode,
855
1795
  apiMessage,
@@ -863,7 +1803,7 @@ function apiError(status, body, method, path22) {
863
1803
  ...extras
864
1804
  };
865
1805
  const code2 = typeof errorCode === "string" ? errorCode : `HTTP_${status}`;
866
- const message = code2 === "DESIGN_NOT_FOUND" && rest.what === "canvas" ? PRIVATE_CANVAS : typeof apiMessage === "string" && apiMessage ? apiMessage : `${method} ${path22} answered ${status}.`;
1806
+ const message = code2 === "DESIGN_NOT_FOUND" && rest.what === "canvas" ? PRIVATE_CANVAS : typeof apiMessage === "string" && apiMessage ? apiMessage : `${method} ${path25} answered ${status}.`;
867
1807
  const guestRow = GUEST_ERRORS[code2];
868
1808
  const needsLogin = status === 401 || guestRow !== void 0;
869
1809
  const text = guestRow?.message?.(rest, typeof apiMessage === "string" ? apiMessage : "") ?? message;
@@ -874,8 +1814,8 @@ function apiError(status, body, method, path22) {
874
1814
  details: Object.keys(rest).length ? rest : void 0
875
1815
  });
876
1816
  }
877
- function timedOut(method, path22) {
878
- return new CliError("CLI_TIMEOUT", `The command's deadline passed during ${method} ${path22}.`, {
1817
+ function timedOut(method, path25) {
1818
+ return new CliError("CLI_TIMEOUT", `The command's deadline passed during ${method} ${path25}.`, {
879
1819
  exit: Exit.TIMED_OUT
880
1820
  });
881
1821
  }
@@ -910,10 +1850,10 @@ var init_api = __esm({
910
1850
  * @param {string} path
911
1851
  * @param {number | undefined} status
912
1852
  */
913
- constructor(method, path22, status) {
914
- super("CLI_NETWORK", `${method} ${path22} got no usable answer${status ? ` (${status})` : ""}.`, {
1853
+ constructor(method, path25, status) {
1854
+ super("CLI_NETWORK", `${method} ${path25} got no usable answer${status ? ` (${status})` : ""}.`, {
915
1855
  status,
916
- details: { method, path: path22 }
1856
+ details: { method, path: path25 }
917
1857
  });
918
1858
  this.lost = true;
919
1859
  }
@@ -948,9 +1888,9 @@ var init_api = __esm({
948
1888
  * @returns {Promise<ApiResponse>}
949
1889
  */
950
1890
  async call(options) {
951
- const { method, path: path22, retry = "safe" } = options;
1891
+ const { method, path: path25, retry = "safe" } = options;
952
1892
  const deadline = options.deadline ?? this.deadline;
953
- const url2 = `${this.baseUrl}${path22}${queryString(options.query)}`;
1893
+ const url2 = `${this.baseUrl}${path25}${queryString(options.query)}`;
954
1894
  const headers = {
955
1895
  "x-kombai-cli": this.ctx.version,
956
1896
  "x-type": "agent",
@@ -964,7 +1904,7 @@ var init_api = __esm({
964
1904
  let lostTries = 0;
965
1905
  for (; ; ) {
966
1906
  const limit = deadline.clamp(CALL_LIMIT_MS);
967
- if (limit <= 0) throw timedOut(method, path22);
1907
+ if (limit <= 0) throw timedOut(method, path25);
968
1908
  let res;
969
1909
  if (method !== "GET") this.ctx.changeSent = true;
970
1910
  try {
@@ -978,12 +1918,12 @@ var init_api = __esm({
978
1918
  } catch (error3) {
979
1919
  const blocked = blockedRequest(this.ctx.sandbox, error3);
980
1920
  if (blocked) throw blocked;
981
- if (deadline.expired()) throw timedOut(method, path22);
1921
+ if (deadline.expired()) throw timedOut(method, path25);
982
1922
  if (retry === "safe" && lostTries < LOST_ANSWER_BACKOFF_MS.length) {
983
- await this.wait(LOST_ANSWER_BACKOFF_MS[lostTries++], deadline, method, path22);
1923
+ await this.wait(LOST_ANSWER_BACKOFF_MS[lostTries++], deadline, method, path25);
984
1924
  continue;
985
1925
  }
986
- throw new LostAnswer(method, path22, void 0);
1926
+ throw new LostAnswer(method, path25, void 0);
987
1927
  }
988
1928
  this.checkContractVersion(res.headers);
989
1929
  const parsed = await readBody(res);
@@ -997,17 +1937,17 @@ var init_api = __esm({
997
1937
  }
998
1938
  if (UNKNOWN_OUTCOME_STATUSES.has(res.status)) {
999
1939
  if (retry === "safe" && lostTries < LOST_ANSWER_BACKOFF_MS.length) {
1000
- await this.wait(LOST_ANSWER_BACKOFF_MS[lostTries++], deadline, method, path22);
1940
+ await this.wait(LOST_ANSWER_BACKOFF_MS[lostTries++], deadline, method, path25);
1001
1941
  continue;
1002
1942
  }
1003
- if (retry === "once") throw new LostAnswer(method, path22, res.status);
1943
+ if (retry === "once") throw new LostAnswer(method, path25, res.status);
1004
1944
  }
1005
1945
  if (res.ok) {
1006
1946
  if (headers["x-kombai-guest"] && parsed?.guest === true && typeof parsed.guestExpiresAt === "string")
1007
1947
  await this.onGuestExpires?.(parsed.guestExpiresAt);
1008
1948
  return { status: res.status, body: parsed, headers: res.headers };
1009
1949
  }
1010
- const error2 = apiError(res.status, parsed, method, path22);
1950
+ const error2 = apiError(res.status, parsed, method, path25);
1011
1951
  if (res.status === 503 && res.headers.has("retry-after")) {
1012
1952
  error2.details = { ...error2.details, retryAfter: res.headers.get("retry-after") };
1013
1953
  }
@@ -1034,10 +1974,10 @@ var init_api = __esm({
1034
1974
  if (typeof form.maxBytes === "number" && data.byteLength > form.maxBytes)
1035
1975
  throw tooLarge("CLI_FILE_TOO_LARGE", "The file", data.byteLength, form.maxBytes);
1036
1976
  return this.storage(form.url, deadline, () => {
1037
- const fd = new FormData();
1038
- for (const [name, value] of Object.entries(form.fields)) fd.append(name, value);
1039
- fd.append("file", new Blob([data], { type: contentType }));
1040
- return { method: "POST", body: fd };
1977
+ const fd2 = new FormData();
1978
+ for (const [name, value] of Object.entries(form.fields)) fd2.append(name, value);
1979
+ fd2.append("file", new Blob([data], { type: contentType }));
1980
+ return { method: "POST", body: fd2 };
1041
1981
  });
1042
1982
  }
1043
1983
  /**
@@ -1092,8 +2032,8 @@ var init_api = __esm({
1092
2032
  * @param {string} method
1093
2033
  * @param {string} path
1094
2034
  */
1095
- async wait(ms, deadline, method, path22) {
1096
- if (deadline.remaining() <= ms) throw timedOut(method, path22);
2035
+ async wait(ms, deadline, method, path25) {
2036
+ if (deadline.remaining() <= ms) throw timedOut(method, path25);
1097
2037
  await this.ctx.sleep(ms);
1098
2038
  }
1099
2039
  /** @param {Headers} headers */
@@ -1252,7 +2192,8 @@ function storePaths(home) {
1252
2192
  credentialsLock: path4.join(home, "credentials.lock"),
1253
2193
  browser: path4.join(home, "browser"),
1254
2194
  render: path4.join(home, "render"),
1255
- claims: path4.join(home, "claims")
2195
+ claims: path4.join(home, "claims"),
2196
+ appSkillsRemoved: path4.join(home, "app-skills-removed")
1256
2197
  };
1257
2198
  }
1258
2199
  async function readRecord(file2, after) {
@@ -2504,6 +3445,10 @@ var init_asset = __esm({
2504
3445
 
2505
3446
  // src/commands/auth.js
2506
3447
  import { constants, generateKeyPairSync, privateDecrypt, randomBytes as randomBytes4 } from "node:crypto";
3448
+ function loginBudgetMs(expiresAt, serverDate) {
3449
+ const budget = Date.parse(expiresAt) - Date.parse(serverDate ?? "");
3450
+ return Number.isFinite(budget) ? budget : LOGIN_WINDOW_MS;
3451
+ }
2507
3452
  async function claimGuest(ctx, env) {
2508
3453
  if (!await readGuest(ctx.home, env)) return {};
2509
3454
  const outcome = await settleClaim(ctx, await openSession(ctx, { claim: false }));
@@ -2571,7 +3516,7 @@ function loginExpired() {
2571
3516
  next: "kombai login"
2572
3517
  });
2573
3518
  }
2574
- var REUSE_KEY_MS, POLL_MS2, RSA_BITS, login, logout, whoami, guest, claim;
3519
+ var REUSE_KEY_MS, POLL_MS2, RSA_BITS, LOGIN_WINDOW_MS, login, logout, whoami, guest, claim;
2575
3520
  var init_auth = __esm({
2576
3521
  "src/commands/auth.js"() {
2577
3522
  "use strict";
@@ -2588,6 +3533,7 @@ var init_auth = __esm({
2588
3533
  REUSE_KEY_MS = 3 * 24 * 60 * 60 * 1e3;
2589
3534
  POLL_MS2 = 2e3;
2590
3535
  RSA_BITS = 3072;
3536
+ LOGIN_WINDOW_MS = 6e5;
2591
3537
  login = {
2592
3538
  name: "login",
2593
3539
  summary: "Sign in through the browser. Prints a waiting line with a match code at once, then the signed-in line. A key with more than 3 days left is reused. With a guest token here, it then claims the guest canvas into the account.",
@@ -2606,6 +3552,7 @@ var init_auth = __esm({
2606
3552
  const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: RSA_BITS });
2607
3553
  const api = new ApiClient({ ctx, baseUrl: hosts.api, key: null, deadline: new Deadline(null, ctx.now) });
2608
3554
  let started;
3555
+ let serverDate;
2609
3556
  try {
2610
3557
  const res = await api.call({
2611
3558
  method: "POST",
@@ -2625,6 +3572,7 @@ var init_auth = __esm({
2625
3572
  if (!b || typeof b.code !== "string" || typeof b.matchCode !== "string" || typeof b.approveUrl !== "string" || !b.approveUrl.startsWith(`${hosts.web}/`) || !Number.isFinite(Date.parse(b.expiresAt)))
2626
3573
  throw new CliError("CLI_BAD_ANSWER", "The sign-in answer was not a login code.", { next: "kombai login" });
2627
3574
  started = b;
3575
+ serverDate = res.headers.get("date");
2628
3576
  } catch (error2) {
2629
3577
  if (error2 instanceof LostAnswer) error2.next = "kombai login";
2630
3578
  throw error2;
@@ -2636,7 +3584,7 @@ var init_auth = __esm({
2636
3584
  expiresAt: started.expiresAt
2637
3585
  });
2638
3586
  if (!flags["no-browser"] && ctx.hasDisplay) await ctx.openUrl(started.approveUrl);
2639
- const deadline = new Deadline(Date.parse(started.expiresAt) - ctx.now(), ctx.now);
3587
+ const deadline = new Deadline(loginBudgetMs(started.expiresAt, serverDate), ctx.now);
2640
3588
  for (; ; ) {
2641
3589
  let answer2;
2642
3590
  try {
@@ -3938,11 +4886,11 @@ var require_is_docker = __commonJS({
3938
4886
  "../../node_modules/is-docker/index.js"(exports, module) {
3939
4887
  "use strict";
3940
4888
  init_define_KOMBAI_TELEMETRY();
3941
- var fs19 = __require("fs");
4889
+ var fs20 = __require("fs");
3942
4890
  var isDocker;
3943
4891
  function hasDockerEnv() {
3944
4892
  try {
3945
- fs19.statSync("/.dockerenv");
4893
+ fs20.statSync("/.dockerenv");
3946
4894
  return true;
3947
4895
  } catch (_) {
3948
4896
  return false;
@@ -3950,7 +4898,7 @@ var require_is_docker = __commonJS({
3950
4898
  }
3951
4899
  function hasDockerCGroup() {
3952
4900
  try {
3953
- return fs19.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
4901
+ return fs20.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
3954
4902
  } catch (_) {
3955
4903
  return false;
3956
4904
  }
@@ -3970,7 +4918,7 @@ var require_is_wsl = __commonJS({
3970
4918
  "use strict";
3971
4919
  init_define_KOMBAI_TELEMETRY();
3972
4920
  var os5 = __require("os");
3973
- var fs19 = __require("fs");
4921
+ var fs20 = __require("fs");
3974
4922
  var isDocker = require_is_docker();
3975
4923
  var isWsl3 = () => {
3976
4924
  if (process.platform !== "linux") {
@@ -3983,7 +4931,7 @@ var require_is_wsl = __commonJS({
3983
4931
  return true;
3984
4932
  }
3985
4933
  try {
3986
- return fs19.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
4934
+ return fs20.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft") ? !isDocker() : false;
3987
4935
  } catch (_) {
3988
4936
  return false;
3989
4937
  }
@@ -4047,15 +4995,15 @@ function toWSLPath(dir, fallback) {
4047
4995
  return fallback;
4048
4996
  }
4049
4997
  }
4050
- function getLocalAppDataPath(path22) {
4998
+ function getLocalAppDataPath(path25) {
4051
4999
  const userRegExp = /\/mnt\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
4052
- const results = userRegExp.exec(path22) || [];
5000
+ const results = userRegExp.exec(path25) || [];
4053
5001
  return `/mnt/${results[1]}/Users/${results[2]}/AppData/Local`;
4054
5002
  }
4055
- function getWSLLocalAppDataPath(path22) {
5003
+ function getWSLLocalAppDataPath(path25) {
4056
5004
  const userRegExp = /\/([a-z])\/Users\/([^\/:]+)\/AppData\//;
4057
- const results = userRegExp.exec(path22) || [];
4058
- return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path22));
5005
+ const results = userRegExp.exec(path25) || [];
5006
+ return toWSLPath(`${results[1]}:\\Users\\${results[2]}\\AppData\\Local`, getLocalAppDataPath(path25));
4059
5007
  }
4060
5008
  function makeUnixTmpDir() {
4061
5009
  return childProcess.execSync("mktemp -d -t lighthouse.XXXXXXX").toString().trim();
@@ -4520,8 +5468,8 @@ var init_chrome_launcher = __esm({
4520
5468
  } else {
4521
5469
  this.fs.writeFileSync(preferenceFile, JSON.stringify({ ...this.prefs }), "utf-8");
4522
5470
  }
4523
- } catch (err) {
4524
- lighthouse_logger_default.log("ChromeLauncher", `Failed to set browser prefs: ${err.message}`);
5471
+ } catch (err2) {
5472
+ lighthouse_logger_default.log("ChromeLauncher", `Failed to set browser prefs: ${err2.message}`);
4525
5473
  }
4526
5474
  }
4527
5475
  async launch() {
@@ -4531,7 +5479,7 @@ var init_chrome_launcher = __esm({
4531
5479
  await this.isDebuggerReady();
4532
5480
  lighthouse_logger_default.log("ChromeLauncher", `Found existing Chrome already running using port ${this.port}, using that.`);
4533
5481
  return;
4534
- } catch (err) {
5482
+ } catch (err2) {
4535
5483
  if (this.portStrictMode) {
4536
5484
  throw new Error(`found no Chrome at port ${this.requestedPort}`);
4537
5485
  }
@@ -4604,9 +5552,9 @@ var init_chrome_launcher = __esm({
4604
5552
  isDebuggerReady() {
4605
5553
  return new Promise((resolve, reject) => {
4606
5554
  const client = net.createConnection(this.port, "127.0.0.1");
4607
- client.once("error", (err) => {
5555
+ client.once("error", (err2) => {
4608
5556
  this.cleanup(client);
4609
- reject(err);
5557
+ reject(err2);
4610
5558
  });
4611
5559
  client.once("connect", () => {
4612
5560
  this.cleanup(client);
@@ -4630,13 +5578,13 @@ var init_chrome_launcher = __esm({
4630
5578
  launcher.isDebuggerReady().then(() => {
4631
5579
  lighthouse_logger_default.log("ChromeLauncher", waitStatus + `${lighthouse_logger_default.greenify(lighthouse_logger_default.tick)}`);
4632
5580
  resolve();
4633
- }).catch((err) => {
5581
+ }).catch((err2) => {
4634
5582
  if (retries > launcher.maxConnectionRetries) {
4635
- lighthouse_logger_default.error("ChromeLauncher", err.message);
5583
+ lighthouse_logger_default.error("ChromeLauncher", err2.message);
4636
5584
  const stderr = this.fs.readFileSync(`${this.userDataDir}/chrome-err.log`, { encoding: "utf-8" });
4637
5585
  lighthouse_logger_default.error("ChromeLauncher", `Logging contents of ${this.userDataDir}/chrome-err.log`);
4638
5586
  lighthouse_logger_default.error("ChromeLauncher", stderr);
4639
- return reject(err);
5587
+ return reject(err2);
4640
5588
  }
4641
5589
  delay(launcher.connectionPollInterval).then(poll);
4642
5590
  });
@@ -4664,8 +5612,8 @@ var init_chrome_launcher = __esm({
4664
5612
  process.kill(-this.chromeProcess.pid, "SIGKILL");
4665
5613
  }
4666
5614
  }
4667
- } catch (err) {
4668
- const message = `Chrome could not be killed ${err.message}`;
5615
+ } catch (err2) {
5616
+ const message = `Chrome could not be killed ${err2.message}`;
4669
5617
  lighthouse_logger_default.warn("ChromeLauncher", message);
4670
5618
  }
4671
5619
  this.destroyTmp();
@@ -4703,8 +5651,8 @@ var require_windows = __commonJS({
4703
5651
  init_define_KOMBAI_TELEMETRY();
4704
5652
  module.exports = isexe;
4705
5653
  isexe.sync = sync;
4706
- var fs19 = __require("fs");
4707
- function checkPathExt(path22, options) {
5654
+ var fs20 = __require("fs");
5655
+ function checkPathExt(path25, options) {
4708
5656
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
4709
5657
  if (!pathext) {
4710
5658
  return true;
@@ -4715,25 +5663,25 @@ var require_windows = __commonJS({
4715
5663
  }
4716
5664
  for (var i = 0; i < pathext.length; i++) {
4717
5665
  var p = pathext[i].toLowerCase();
4718
- if (p && path22.substr(-p.length).toLowerCase() === p) {
5666
+ if (p && path25.substr(-p.length).toLowerCase() === p) {
4719
5667
  return true;
4720
5668
  }
4721
5669
  }
4722
5670
  return false;
4723
5671
  }
4724
- function checkStat(stat, path22, options) {
5672
+ function checkStat(stat, path25, options) {
4725
5673
  if (!stat.isSymbolicLink() && !stat.isFile()) {
4726
5674
  return false;
4727
5675
  }
4728
- return checkPathExt(path22, options);
5676
+ return checkPathExt(path25, options);
4729
5677
  }
4730
- function isexe(path22, options, cb) {
4731
- fs19.stat(path22, function(er, stat) {
4732
- cb(er, er ? false : checkStat(stat, path22, options));
5678
+ function isexe(path25, options, cb) {
5679
+ fs20.stat(path25, function(er, stat) {
5680
+ cb(er, er ? false : checkStat(stat, path25, options));
4733
5681
  });
4734
5682
  }
4735
- function sync(path22, options) {
4736
- return checkStat(fs19.statSync(path22), path22, options);
5683
+ function sync(path25, options) {
5684
+ return checkStat(fs20.statSync(path25), path25, options);
4737
5685
  }
4738
5686
  }
4739
5687
  });
@@ -4744,14 +5692,14 @@ var require_mode = __commonJS({
4744
5692
  init_define_KOMBAI_TELEMETRY();
4745
5693
  module.exports = isexe;
4746
5694
  isexe.sync = sync;
4747
- var fs19 = __require("fs");
4748
- function isexe(path22, options, cb) {
4749
- fs19.stat(path22, function(er, stat) {
5695
+ var fs20 = __require("fs");
5696
+ function isexe(path25, options, cb) {
5697
+ fs20.stat(path25, function(er, stat) {
4750
5698
  cb(er, er ? false : checkStat(stat, options));
4751
5699
  });
4752
5700
  }
4753
- function sync(path22, options) {
4754
- return checkStat(fs19.statSync(path22), options);
5701
+ function sync(path25, options) {
5702
+ return checkStat(fs20.statSync(path25), options);
4755
5703
  }
4756
5704
  function checkStat(stat, options) {
4757
5705
  return stat.isFile() && checkMode(stat, options);
@@ -4776,7 +5724,7 @@ var require_mode = __commonJS({
4776
5724
  var require_isexe = __commonJS({
4777
5725
  "../../node_modules/isexe/index.js"(exports, module) {
4778
5726
  init_define_KOMBAI_TELEMETRY();
4779
- var fs19 = __require("fs");
5727
+ var fs20 = __require("fs");
4780
5728
  var core;
4781
5729
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
4782
5730
  core = require_windows();
@@ -4785,7 +5733,7 @@ var require_isexe = __commonJS({
4785
5733
  }
4786
5734
  module.exports = isexe;
4787
5735
  isexe.sync = sync;
4788
- function isexe(path22, options, cb) {
5736
+ function isexe(path25, options, cb) {
4789
5737
  if (typeof options === "function") {
4790
5738
  cb = options;
4791
5739
  options = {};
@@ -4795,7 +5743,7 @@ var require_isexe = __commonJS({
4795
5743
  throw new TypeError("callback not provided");
4796
5744
  }
4797
5745
  return new Promise(function(resolve, reject) {
4798
- isexe(path22, options || {}, function(er, is) {
5746
+ isexe(path25, options || {}, function(er, is) {
4799
5747
  if (er) {
4800
5748
  reject(er);
4801
5749
  } else {
@@ -4804,7 +5752,7 @@ var require_isexe = __commonJS({
4804
5752
  });
4805
5753
  });
4806
5754
  }
4807
- core(path22, options || {}, function(er, is) {
5755
+ core(path25, options || {}, function(er, is) {
4808
5756
  if (er) {
4809
5757
  if (er.code === "EACCES" || options && options.ignoreErrors) {
4810
5758
  er = null;
@@ -4814,9 +5762,9 @@ var require_isexe = __commonJS({
4814
5762
  cb(er, is);
4815
5763
  });
4816
5764
  }
4817
- function sync(path22, options) {
5765
+ function sync(path25, options) {
4818
5766
  try {
4819
- return core.sync(path22, options || {});
5767
+ return core.sync(path25, options || {});
4820
5768
  } catch (er) {
4821
5769
  if (options && options.ignoreErrors || er.code === "EACCES") {
4822
5770
  return false;
@@ -4833,7 +5781,7 @@ var require_which = __commonJS({
4833
5781
  "../../node_modules/which/which.js"(exports, module) {
4834
5782
  init_define_KOMBAI_TELEMETRY();
4835
5783
  var isWindows3 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
4836
- var path22 = __require("path");
5784
+ var path25 = __require("path");
4837
5785
  var COLON = isWindows3 ? ";" : ":";
4838
5786
  var isexe = require_isexe();
4839
5787
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -4871,7 +5819,7 @@ var require_which = __commonJS({
4871
5819
  return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
4872
5820
  const ppRaw = pathEnv[i];
4873
5821
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
4874
- const pCmd = path22.join(pathPart, cmd);
5822
+ const pCmd = path25.join(pathPart, cmd);
4875
5823
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
4876
5824
  resolve(subStep(p, i, 0));
4877
5825
  });
@@ -4898,7 +5846,7 @@ var require_which = __commonJS({
4898
5846
  for (let i = 0; i < pathEnv.length; i++) {
4899
5847
  const ppRaw = pathEnv[i];
4900
5848
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
4901
- const pCmd = path22.join(pathPart, cmd);
5849
+ const pCmd = path25.join(pathPart, cmd);
4902
5850
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
4903
5851
  for (let j = 0; j < pathExt.length; j++) {
4904
5852
  const cur = p + pathExt[j];
@@ -4930,8 +5878,8 @@ import { existsSync } from "fs";
4930
5878
  import path10 from "path";
4931
5879
  function getEdgeLinux(name) {
4932
5880
  try {
4933
- let path22 = import_which.default.sync(name);
4934
- return path22;
5881
+ let path25 = import_which.default.sync(name);
5882
+ return path25;
4935
5883
  } catch (e) {
4936
5884
  }
4937
5885
  return null;
@@ -5168,7 +6116,7 @@ async function markLaunchFailed(ctx, browserPath) {
5168
6116
  }
5169
6117
  async function saveBrowser(ctx, change) {
5170
6118
  await updateConfig(ctx.home, (c) => {
5171
- const { launchFailed: _f, failedPath: _p, failedAt: _a2, ...rest } = c.browser ?? {};
6119
+ const { launchFailed: _f, failedPath: _p, failedAt: _a3, ...rest } = c.browser ?? {};
5172
6120
  return { ...c, browser: { ...rest, ...change, checkedAt: new Date(ctx.now()).toISOString() } };
5173
6121
  });
5174
6122
  }
@@ -5530,13 +6478,7 @@ import dns from "node:dns/promises";
5530
6478
  import http from "node:http";
5531
6479
  import net2 from "node:net";
5532
6480
  function isPrivateAddress(ip) {
5533
- const v4 = net2.isIPv4(ip) ? ip : /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip)?.[1];
5534
- if (v4) {
5535
- const [a, b] = v4.split(".").map(Number);
5536
- return a === 0 || a === 10 || a === 127 || a >= 224 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19);
5537
- }
5538
- const lower = ip.toLowerCase();
5539
- return lower === "::" || lower === "::1" || /^f[cd]/.test(lower) || /^fe[89ab]/.test(lower) || /^ff/.test(lower);
6481
+ return PRIVATE.check(ip, net2.isIPv4(ip) ? "ipv4" : "ipv6");
5540
6482
  }
5541
6483
  async function publicAddress(host) {
5542
6484
  const bare = host.replace(/^\[|\]$/g, "");
@@ -5630,12 +6572,44 @@ async function startProxy() {
5630
6572
  })
5631
6573
  };
5632
6574
  }
5633
- var PAGE_HOST;
6575
+ var PAGE_HOST, PRIVATE;
5634
6576
  var init_proxy = __esm({
5635
6577
  "src/render/proxy.js"() {
5636
6578
  "use strict";
5637
6579
  init_define_KOMBAI_TELEMETRY();
5638
6580
  PAGE_HOST = "render.kombai.invalid";
6581
+ PRIVATE = new net2.BlockList();
6582
+ for (
6583
+ const [prefix, bits] of
6584
+ /** @type {const} */
6585
+ [
6586
+ ["0.0.0.0", 8],
6587
+ ["10.0.0.0", 8],
6588
+ ["100.64.0.0", 10],
6589
+ ["127.0.0.0", 8],
6590
+ ["169.254.0.0", 16],
6591
+ ["172.16.0.0", 12],
6592
+ ["192.168.0.0", 16],
6593
+ ["198.18.0.0", 15],
6594
+ ["224.0.0.0", 3]
6595
+ ]
6596
+ ) {
6597
+ PRIVATE.addSubnet(prefix, bits, "ipv4");
6598
+ }
6599
+ for (
6600
+ const [prefix, bits] of
6601
+ /** @type {const} */
6602
+ [
6603
+ ["::", 96],
6604
+ ["64:ff9b::", 96],
6605
+ ["64:ff9b:1::", 48],
6606
+ ["fc00::", 7],
6607
+ ["fe80::", 10],
6608
+ ["ff00::", 8]
6609
+ ]
6610
+ ) {
6611
+ PRIVATE.addSubnet(prefix, bits, "ipv6");
6612
+ }
5639
6613
  }
5640
6614
  });
5641
6615
 
@@ -6114,6 +7088,18 @@ async function rememberGuestCanvas(ctx, cc, canvasId) {
6114
7088
  if (cc.session.kind !== "guest") return;
6115
7089
  await writeGuest(ctx.home, cc.session.env, { canvasId }, { ifGuest: cc.session.guest.guest });
6116
7090
  }
7091
+ async function deleteStoredCanvas(api, canvasId) {
7092
+ for (let attempt = 0; ; attempt++) {
7093
+ try {
7094
+ await api.call({ method: "DELETE", path: `/design/canvases/${canvasId}`, retry: "once" });
7095
+ return;
7096
+ } catch (error2) {
7097
+ if (error2 instanceof CliError && error2.status === 410) return;
7098
+ if (error2 instanceof LostAnswer && attempt < 3) continue;
7099
+ throw error2;
7100
+ }
7101
+ }
7102
+ }
6117
7103
  function named(nodeIds) {
6118
7104
  if (nodeIds.length === 1) return nodeIds[0];
6119
7105
  return nodeIds.length <= 5 ? `${nodeIds.length} nodes (${nodeIds.join(", ")})` : `${nodeIds.length} nodes`;
@@ -6589,16 +7575,7 @@ var init_canvas = __esm({
6589
7575
  /** @type {{ canvasId: string, paths: import('../lib/canvasdir.js').CanvasPaths }} */
6590
7576
  cc
6591
7577
  );
6592
- for (let attempt = 0; ; attempt++) {
6593
- try {
6594
- await cc.session.api.call({ method: "DELETE", path: `/design/canvases/${canvasId}`, retry: "once" });
6595
- break;
6596
- } catch (error2) {
6597
- if (error2 instanceof CliError && error2.status === 410) break;
6598
- if (error2 instanceof LostAnswer && attempt < 3) continue;
6599
- throw error2;
6600
- }
6601
- }
7578
+ await deleteStoredCanvas(cc.session.api, canvasId);
6602
7579
  return { status: "deleted", kept: await forgetCanvas(cc, canvasId, paths) };
6603
7580
  }
6604
7581
  };
@@ -8250,8 +9227,8 @@ var init_parseUtil = __esm({
8250
9227
  init_errors();
8251
9228
  init_en();
8252
9229
  makeIssue = (params) => {
8253
- const { data, path: path22, errorMaps, issueData } = params;
8254
- const fullPath = [...path22, ...issueData.path || []];
9230
+ const { data, path: path25, errorMaps, issueData } = params;
9231
+ const fullPath = [...path25, ...issueData.path || []];
8255
9232
  const fullIssue = {
8256
9233
  ...issueData,
8257
9234
  path: fullPath
@@ -8534,11 +9511,11 @@ var init_types = __esm({
8534
9511
  init_parseUtil();
8535
9512
  init_util();
8536
9513
  ParseInputLazyPath = class {
8537
- constructor(parent, value, path22, key) {
9514
+ constructor(parent, value, path25, key) {
8538
9515
  this._cachedPath = [];
8539
9516
  this.parent = parent;
8540
9517
  this.data = value;
8541
- this._path = path22;
9518
+ this._path = path25;
8542
9519
  this._key = key;
8543
9520
  }
8544
9521
  get path() {
@@ -8654,8 +9631,8 @@ var init_types = __esm({
8654
9631
  } : {
8655
9632
  issues: ctx.common.issues
8656
9633
  };
8657
- } catch (err) {
8658
- if (err?.message?.toLowerCase()?.includes("encountered")) {
9634
+ } catch (err2) {
9635
+ if (err2?.message?.toLowerCase()?.includes("encountered")) {
8659
9636
  this["~standard"].async = true;
8660
9637
  }
8661
9638
  ctx.common = {
@@ -11827,10 +12804,10 @@ function $constructor(name, initializer3, params) {
11827
12804
  }
11828
12805
  Object.defineProperty(Definition, "name", { value: name });
11829
12806
  function _(def) {
11830
- var _a2;
12807
+ var _a3;
11831
12808
  const inst = params?.Parent ? new Definition() : this;
11832
12809
  init(inst, def);
11833
- (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
12810
+ (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
11834
12811
  for (const fn of inst._zod.deferred) {
11835
12812
  fn();
11836
12813
  }
@@ -12047,10 +13024,10 @@ function mergeDefs(...defs) {
12047
13024
  function cloneDef(schema) {
12048
13025
  return mergeDefs(schema._zod.def);
12049
13026
  }
12050
- function getElementAtPath(obj, path22) {
12051
- if (!path22)
13027
+ function getElementAtPath(obj, path25) {
13028
+ if (!path25)
12052
13029
  return obj;
12053
- return path22.reduce((acc, key) => acc?.[key], obj);
13030
+ return path25.reduce((acc, key) => acc?.[key], obj);
12054
13031
  }
12055
13032
  function promiseAllObject(promisesObj) {
12056
13033
  const keys = Object.keys(promisesObj);
@@ -12362,11 +13339,11 @@ function aborted(x, startIndex = 0) {
12362
13339
  }
12363
13340
  return false;
12364
13341
  }
12365
- function prefixIssues(path22, issues) {
13342
+ function prefixIssues(path25, issues) {
12366
13343
  return issues.map((iss) => {
12367
- var _a2;
12368
- (_a2 = iss).path ?? (_a2.path = []);
12369
- iss.path.unshift(path22);
13344
+ var _a3;
13345
+ (_a3 = iss).path ?? (_a3.path = []);
13346
+ iss.path.unshift(path25);
12370
13347
  return iss;
12371
13348
  });
12372
13349
  }
@@ -12901,10 +13878,10 @@ var init_checks = __esm({
12901
13878
  init_regexes();
12902
13879
  init_util2();
12903
13880
  $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
12904
- var _a2;
13881
+ var _a3;
12905
13882
  inst._zod ?? (inst._zod = {});
12906
13883
  inst._zod.def = def;
12907
- (_a2 = inst._zod).onattach ?? (_a2.onattach = []);
13884
+ (_a3 = inst._zod).onattach ?? (_a3.onattach = []);
12908
13885
  });
12909
13886
  numericOriginMap = {
12910
13887
  number: "number",
@@ -12970,8 +13947,8 @@ var init_checks = __esm({
12970
13947
  $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
12971
13948
  $ZodCheck.init(inst, def);
12972
13949
  inst._zod.onattach.push((inst2) => {
12973
- var _a2;
12974
- (_a2 = inst2._zod.bag).multipleOf ?? (_a2.multipleOf = def.value);
13950
+ var _a3;
13951
+ (_a3 = inst2._zod.bag).multipleOf ?? (_a3.multipleOf = def.value);
12975
13952
  });
12976
13953
  inst._zod.check = (payload) => {
12977
13954
  if (typeof payload.value !== typeof def.value)
@@ -13104,9 +14081,9 @@ var init_checks = __esm({
13104
14081
  };
13105
14082
  });
13106
14083
  $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
13107
- var _a2;
14084
+ var _a3;
13108
14085
  $ZodCheck.init(inst, def);
13109
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14086
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13110
14087
  const val = payload.value;
13111
14088
  return !nullish(val) && val.size !== void 0;
13112
14089
  });
@@ -13132,9 +14109,9 @@ var init_checks = __esm({
13132
14109
  };
13133
14110
  });
13134
14111
  $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
13135
- var _a2;
14112
+ var _a3;
13136
14113
  $ZodCheck.init(inst, def);
13137
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14114
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13138
14115
  const val = payload.value;
13139
14116
  return !nullish(val) && val.size !== void 0;
13140
14117
  });
@@ -13160,9 +14137,9 @@ var init_checks = __esm({
13160
14137
  };
13161
14138
  });
13162
14139
  $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
13163
- var _a2;
14140
+ var _a3;
13164
14141
  $ZodCheck.init(inst, def);
13165
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14142
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13166
14143
  const val = payload.value;
13167
14144
  return !nullish(val) && val.size !== void 0;
13168
14145
  });
@@ -13190,9 +14167,9 @@ var init_checks = __esm({
13190
14167
  };
13191
14168
  });
13192
14169
  $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
13193
- var _a2;
14170
+ var _a3;
13194
14171
  $ZodCheck.init(inst, def);
13195
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14172
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13196
14173
  const val = payload.value;
13197
14174
  return !nullish(val) && val.length !== void 0;
13198
14175
  });
@@ -13219,9 +14196,9 @@ var init_checks = __esm({
13219
14196
  };
13220
14197
  });
13221
14198
  $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
13222
- var _a2;
14199
+ var _a3;
13223
14200
  $ZodCheck.init(inst, def);
13224
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14201
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13225
14202
  const val = payload.value;
13226
14203
  return !nullish(val) && val.length !== void 0;
13227
14204
  });
@@ -13248,9 +14225,9 @@ var init_checks = __esm({
13248
14225
  };
13249
14226
  });
13250
14227
  $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
13251
- var _a2;
14228
+ var _a3;
13252
14229
  $ZodCheck.init(inst, def);
13253
- (_a2 = inst._zod.def).when ?? (_a2.when = (payload) => {
14230
+ (_a3 = inst._zod.def).when ?? (_a3.when = (payload) => {
13254
14231
  const val = payload.value;
13255
14232
  return !nullish(val) && val.length !== void 0;
13256
14233
  });
@@ -13279,7 +14256,7 @@ var init_checks = __esm({
13279
14256
  };
13280
14257
  });
13281
14258
  $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
13282
- var _a2, _b;
14259
+ var _a3, _b2;
13283
14260
  $ZodCheck.init(inst, def);
13284
14261
  inst._zod.onattach.push((inst2) => {
13285
14262
  const bag = inst2._zod.bag;
@@ -13290,7 +14267,7 @@ var init_checks = __esm({
13290
14267
  }
13291
14268
  });
13292
14269
  if (def.pattern)
13293
- (_a2 = inst._zod).check ?? (_a2.check = (payload) => {
14270
+ (_a3 = inst._zod).check ?? (_a3.check = (payload) => {
13294
14271
  def.pattern.lastIndex = 0;
13295
14272
  if (def.pattern.test(payload.value))
13296
14273
  return;
@@ -13305,7 +14282,7 @@ var init_checks = __esm({
13305
14282
  });
13306
14283
  });
13307
14284
  else
13308
- (_b = inst._zod).check ?? (_b.check = () => {
14285
+ (_b2 = inst._zod).check ?? (_b2.check = () => {
13309
14286
  });
13310
14287
  });
13311
14288
  $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
@@ -13870,7 +14847,7 @@ var init_schemas = __esm({
13870
14847
  init_versions();
13871
14848
  init_util2();
13872
14849
  $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
13873
- var _a2;
14850
+ var _a3;
13874
14851
  inst ?? (inst = {});
13875
14852
  inst._zod.def = def;
13876
14853
  inst._zod.bag = inst._zod.bag || {};
@@ -13885,7 +14862,7 @@ var init_schemas = __esm({
13885
14862
  }
13886
14863
  }
13887
14864
  if (checks.length === 0) {
13888
- (_a2 = inst._zod).deferred ?? (_a2.deferred = []);
14865
+ (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
13889
14866
  inst._zod.deferred?.push(() => {
13890
14867
  inst._zod.run = inst._zod.parse;
13891
14868
  });
@@ -16044,7 +17021,7 @@ var init_locales = __esm({
16044
17021
  function registry() {
16045
17022
  return new $ZodRegistry();
16046
17023
  }
16047
- var _a, $output, $input, $ZodRegistry, globalRegistry;
17024
+ var _a2, $output, $input, $ZodRegistry, globalRegistry;
16048
17025
  var init_registries = __esm({
16049
17026
  "../../node_modules/zod/v4/core/registries.js"() {
16050
17027
  init_define_KOMBAI_TELEMETRY();
@@ -16090,7 +17067,7 @@ var init_registries = __esm({
16090
17067
  return this._map.has(schema);
16091
17068
  }
16092
17069
  };
16093
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
17070
+ (_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
16094
17071
  globalRegistry = globalThis.__zod_globalRegistry;
16095
17072
  }
16096
17073
  });
@@ -16931,7 +17908,7 @@ function initializeContext(params) {
16931
17908
  };
16932
17909
  }
16933
17910
  function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
16934
- var _a2;
17911
+ var _a3;
16935
17912
  const def = schema._zod.def;
16936
17913
  const seen = ctx.seen.get(schema);
16937
17914
  if (seen) {
@@ -16979,7 +17956,7 @@ function process3(schema, ctx, _params = { path: [], schemaPath: [] }) {
16979
17956
  delete result.schema.default;
16980
17957
  }
16981
17958
  if (ctx.io === "input" && result.schema._prefault)
16982
- (_a2 = result.schema).default ?? (_a2.default = result.schema._prefault);
17959
+ (_a3 = result.schema).default ?? (_a3.default = result.schema._prefault);
16983
17960
  delete result.schema._prefault;
16984
17961
  const _result = ctx.seen.get(schema);
16985
17962
  return _result.schema;
@@ -21297,7 +22274,7 @@ var init_zodToJsonSchema = __esm({
21297
22274
  });
21298
22275
 
21299
22276
  // ../../node_modules/zod-to-json-schema/dist/esm/index.js
21300
- var init_esm = __esm({
22277
+ var init_esm2 = __esm({
21301
22278
  "../../node_modules/zod-to-json-schema/dist/esm/index.js"() {
21302
22279
  init_define_KOMBAI_TELEMETRY();
21303
22280
  init_Options();
@@ -21367,7 +22344,7 @@ var init_zod_json_schema_compat = __esm({
21367
22344
  init_define_KOMBAI_TELEMETRY();
21368
22345
  init_v4_mini();
21369
22346
  init_zod_compat();
21370
- init_esm();
22347
+ init_esm2();
21371
22348
  }
21372
22349
  });
21373
22350
 
@@ -22361,12 +23338,12 @@ var require_code = __commonJS({
22361
23338
  return item === "" || item === '""';
22362
23339
  }
22363
23340
  get str() {
22364
- var _a2;
22365
- return (_a2 = this._str) !== null && _a2 !== void 0 ? _a2 : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
23341
+ var _a3;
23342
+ return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
22366
23343
  }
22367
23344
  get names() {
22368
- var _a2;
22369
- return (_a2 = this._names) !== null && _a2 !== void 0 ? _a2 : this._names = this._items.reduce((names, c) => {
23345
+ var _a3;
23346
+ return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c) => {
22370
23347
  if (c instanceof Name)
22371
23348
  names[c.str] = (names[c.str] || 0) + 1;
22372
23349
  return names;
@@ -22513,8 +23490,8 @@ var require_scope = __commonJS({
22513
23490
  return `${prefix}${ng.index++}`;
22514
23491
  }
22515
23492
  _nameGroup(prefix) {
22516
- var _a2, _b;
22517
- if (((_b = (_a2 = this._parent) === null || _a2 === void 0 ? void 0 : _a2._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
23493
+ var _a3, _b2;
23494
+ if (((_b2 = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b2 === void 0 ? void 0 : _b2.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
22518
23495
  throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
22519
23496
  }
22520
23497
  return this._names[prefix] = { prefix, index: 0 };
@@ -22547,12 +23524,12 @@ var require_scope = __commonJS({
22547
23524
  return new ValueScopeName(prefix, this._newName(prefix));
22548
23525
  }
22549
23526
  value(nameOrPrefix, value) {
22550
- var _a2;
23527
+ var _a3;
22551
23528
  if (value.ref === void 0)
22552
23529
  throw new Error("CodeGen: ref must be passed in value");
22553
23530
  const name = this.toName(nameOrPrefix);
22554
23531
  const { prefix } = name;
22555
- const valueKey = (_a2 = value.key) !== null && _a2 !== void 0 ? _a2 : value.ref;
23532
+ const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref;
22556
23533
  let vs = this._values[prefix];
22557
23534
  if (vs) {
22558
23535
  const _name = vs.get(valueKey);
@@ -22871,8 +23848,8 @@ var require_codegen = __commonJS({
22871
23848
  return this;
22872
23849
  }
22873
23850
  optimizeNames(names, constants2) {
22874
- var _a2;
22875
- this.else = (_a2 = this.else) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants2);
23851
+ var _a3;
23852
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
22876
23853
  if (!(super.optimizeNames(names, constants2) || this.else))
22877
23854
  return;
22878
23855
  this.condition = optimizeExpr(this.condition, names, constants2);
@@ -22976,17 +23953,17 @@ var require_codegen = __commonJS({
22976
23953
  return code2;
22977
23954
  }
22978
23955
  optimizeNodes() {
22979
- var _a2, _b;
23956
+ var _a3, _b2;
22980
23957
  super.optimizeNodes();
22981
- (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNodes();
22982
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
23958
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes();
23959
+ (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
22983
23960
  return this;
22984
23961
  }
22985
23962
  optimizeNames(names, constants2) {
22986
- var _a2, _b;
23963
+ var _a3, _b2;
22987
23964
  super.optimizeNames(names, constants2);
22988
- (_a2 = this.catch) === null || _a2 === void 0 ? void 0 : _a2.optimizeNames(names, constants2);
22989
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
23965
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
23966
+ (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants2);
22990
23967
  return this;
22991
23968
  }
22992
23969
  get names() {
@@ -23592,21 +24569,21 @@ var require_errors = __commonJS({
23592
24569
  function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
23593
24570
  if (errsCount === void 0)
23594
24571
  throw new Error("ajv implementation error");
23595
- const err = gen.name("err");
24572
+ const err2 = gen.name("err");
23596
24573
  gen.forRange("i", errsCount, names_1.default.errors, (i) => {
23597
- gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
23598
- gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
23599
- gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
24574
+ gen.const(err2, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
24575
+ gen.if((0, codegen_1._)`${err2}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err2}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
24576
+ gen.assign((0, codegen_1._)`${err2}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
23600
24577
  if (it.opts.verbose) {
23601
- gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
23602
- gen.assign((0, codegen_1._)`${err}.data`, data);
24578
+ gen.assign((0, codegen_1._)`${err2}.schema`, schemaValue);
24579
+ gen.assign((0, codegen_1._)`${err2}.data`, data);
23603
24580
  }
23604
24581
  });
23605
24582
  }
23606
24583
  exports.extendErrors = extendErrors;
23607
24584
  function addError(gen, errObj) {
23608
- const err = gen.const("err", errObj);
23609
- gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
24585
+ const err2 = gen.const("err", errObj);
24586
+ gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err2}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err2})`);
23610
24587
  gen.code((0, codegen_1._)`${names_1.default.errors}++`);
23611
24588
  }
23612
24589
  function returnErrors(it, errs) {
@@ -23771,8 +24748,8 @@ var require_applicability = __commonJS({
23771
24748
  }
23772
24749
  exports.shouldUseGroup = shouldUseGroup;
23773
24750
  function shouldUseRule(schema, rule) {
23774
- var _a2;
23775
- return schema[rule.keyword] !== void 0 || ((_a2 = rule.definition.implements) === null || _a2 === void 0 ? void 0 : _a2.some((kwd) => schema[kwd] !== void 0));
24751
+ var _a3;
24752
+ return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0));
23776
24753
  }
23777
24754
  exports.shouldUseRule = shouldUseRule;
23778
24755
  }
@@ -24164,14 +25141,14 @@ var require_keyword = __commonJS({
24164
25141
  }
24165
25142
  exports.macroKeywordCode = macroKeywordCode;
24166
25143
  function funcKeywordCode(cxt, def) {
24167
- var _a2;
25144
+ var _a3;
24168
25145
  const { gen, keyword, schema, parentSchema, $data, it } = cxt;
24169
25146
  checkAsyncKeyword(it, def);
24170
25147
  const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
24171
25148
  const validateRef = useKeyword(gen, keyword, validate);
24172
25149
  const valid = gen.let("valid");
24173
25150
  cxt.block$data(valid, validateKeyword);
24174
- cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid);
25151
+ cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid);
24175
25152
  function validateKeyword() {
24176
25153
  if (def.errors === false) {
24177
25154
  assignValid();
@@ -24202,8 +25179,8 @@ var require_keyword = __commonJS({
24202
25179
  gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
24203
25180
  }
24204
25181
  function reportErrs(errors) {
24205
- var _a3;
24206
- gen.if((0, codegen_1.not)((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid), errors);
25182
+ var _a4;
25183
+ gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors);
24207
25184
  }
24208
25185
  }
24209
25186
  exports.funcKeywordCode = funcKeywordCode;
@@ -25179,7 +26156,7 @@ var require_compile = __commonJS({
25179
26156
  var validate_1 = require_validate();
25180
26157
  var SchemaEnv = class {
25181
26158
  constructor(env) {
25182
- var _a2;
26159
+ var _a3;
25183
26160
  this.refs = {};
25184
26161
  this.dynamicAnchors = {};
25185
26162
  let schema;
@@ -25188,7 +26165,7 @@ var require_compile = __commonJS({
25188
26165
  this.schema = env.schema;
25189
26166
  this.schemaId = env.schemaId;
25190
26167
  this.root = env.root || this;
25191
- this.baseId = (_a2 = env.baseId) !== null && _a2 !== void 0 ? _a2 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
26168
+ this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
25192
26169
  this.schemaPath = env.schemaPath;
25193
26170
  this.localRefs = env.localRefs;
25194
26171
  this.meta = env.meta;
@@ -25284,14 +26261,14 @@ var require_compile = __commonJS({
25284
26261
  }
25285
26262
  exports.compileSchema = compileSchema;
25286
26263
  function resolveRef(root, baseId, ref) {
25287
- var _a2;
26264
+ var _a3;
25288
26265
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
25289
26266
  const schOrFunc = root.refs[ref];
25290
26267
  if (schOrFunc)
25291
26268
  return schOrFunc;
25292
26269
  let _sch = resolve.call(this, root, ref);
25293
26270
  if (_sch === void 0) {
25294
- const schema = (_a2 = root.localRefs) === null || _a2 === void 0 ? void 0 : _a2[ref];
26271
+ const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
25295
26272
  const { schemaId } = this.opts;
25296
26273
  if (schema)
25297
26274
  _sch = new SchemaEnv({ schema, schemaId, root, baseId });
@@ -25360,8 +26337,8 @@ var require_compile = __commonJS({
25360
26337
  "definitions"
25361
26338
  ]);
25362
26339
  function getJsonPointer(parsedRef, { baseId, schema, root }) {
25363
- var _a2;
25364
- if (((_a2 = parsedRef.fragment) === null || _a2 === void 0 ? void 0 : _a2[0]) !== "/")
26340
+ var _a3;
26341
+ if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/")
25365
26342
  return;
25366
26343
  for (const part of parsedRef.fragment.slice(1).split("/")) {
25367
26344
  if (typeof schema === "boolean")
@@ -25532,8 +26509,8 @@ var require_utils = __commonJS({
25532
26509
  }
25533
26510
  return ind;
25534
26511
  }
25535
- function removeDotSegments(path22) {
25536
- let input = path22;
26512
+ function removeDotSegments(path25) {
26513
+ let input = path25;
25537
26514
  const output = [];
25538
26515
  let nextSlash = -1;
25539
26516
  let len = 0;
@@ -25733,8 +26710,8 @@ var require_schemes = __commonJS({
25733
26710
  wsComponent.secure = void 0;
25734
26711
  }
25735
26712
  if (wsComponent.resourceName) {
25736
- const [path22, query] = wsComponent.resourceName.split("?");
25737
- wsComponent.path = path22 && path22 !== "/" ? path22 : void 0;
26713
+ const [path25, query] = wsComponent.resourceName.split("?");
26714
+ wsComponent.path = path25 && path25 !== "/" ? path25 : void 0;
25738
26715
  wsComponent.query = query;
25739
26716
  wsComponent.resourceName = void 0;
25740
26717
  }
@@ -26227,11 +27204,11 @@ var require_core = __commonJS({
26227
27204
  };
26228
27205
  var MAX_EXPRESSION = 200;
26229
27206
  function requiredOptions(o) {
26230
- var _a2, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
27207
+ var _a3, _b2, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
26231
27208
  const s = o.strict;
26232
- const _optz = (_a2 = o.code) === null || _a2 === void 0 ? void 0 : _a2.optimize;
27209
+ const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize;
26233
27210
  const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
26234
- const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
27211
+ const regExp = (_c = (_b2 = o.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
26235
27212
  const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
26236
27213
  return {
26237
27214
  strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
@@ -26703,7 +27680,7 @@ var require_core = __commonJS({
26703
27680
  }
26704
27681
  }
26705
27682
  function addRule(keyword, definition, dataType) {
26706
- var _a2;
27683
+ var _a3;
26707
27684
  const post = definition === null || definition === void 0 ? void 0 : definition.post;
26708
27685
  if (dataType && post)
26709
27686
  throw new Error('keyword with "post" flag cannot have "type"');
@@ -26729,7 +27706,7 @@ var require_core = __commonJS({
26729
27706
  else
26730
27707
  ruleGroup.rules.push(rule);
26731
27708
  RULES.all[keyword] = rule;
26732
- (_a2 = definition.implements) === null || _a2 === void 0 ? void 0 : _a2.forEach((kwd) => this.addKeyword(kwd));
27709
+ (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
26733
27710
  }
26734
27711
  function addBeforeRule(ruleGroup, rule, before) {
26735
27712
  const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
@@ -26865,10 +27842,10 @@ var require_ref = __commonJS({
26865
27842
  gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
26866
27843
  }
26867
27844
  function addEvaluatedFrom(source) {
26868
- var _a2;
27845
+ var _a3;
26869
27846
  if (!it.opts.unevaluated)
26870
27847
  return;
26871
- const schEvaluated = (_a2 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a2 === void 0 ? void 0 : _a2.evaluated;
27848
+ const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated;
26872
27849
  if (it.props !== true) {
26873
27850
  if (schEvaluated && !schEvaluated.dynamicProps) {
26874
27851
  if (schEvaluated.props !== void 0) {
@@ -28547,7 +29524,7 @@ var require_discriminator = __commonJS({
28547
29524
  return _valid;
28548
29525
  }
28549
29526
  function getMapping() {
28550
- var _a2;
29527
+ var _a3;
28551
29528
  const oneOfMapping = {};
28552
29529
  const topRequired = hasRequired(parentSchema);
28553
29530
  let tagRequired = true;
@@ -28561,7 +29538,7 @@ var require_discriminator = __commonJS({
28561
29538
  if (sch === void 0)
28562
29539
  throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
28563
29540
  }
28564
- const propSch = (_a2 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a2 === void 0 ? void 0 : _a2[tagName];
29541
+ const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName];
28565
29542
  if (typeof propSch != "object") {
28566
29543
  throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
28567
29544
  }
@@ -29133,12 +30110,12 @@ var require_dist = __commonJS({
29133
30110
  throw new Error(`Unknown format "${name}"`);
29134
30111
  return f;
29135
30112
  };
29136
- function addFormats(ajv, list, fs19, exportName) {
29137
- var _a2;
29138
- var _b;
29139
- (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
30113
+ function addFormats(ajv, list, fs20, exportName) {
30114
+ var _a3;
30115
+ var _b2;
30116
+ (_a3 = (_b2 = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
29140
30117
  for (const f of list)
29141
- ajv.addFormat(f, fs19[f]);
30118
+ ajv.addFormat(f, fs20[f]);
29142
30119
  }
29143
30120
  module.exports = exports = formatsPlugin;
29144
30121
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -30279,6 +31256,102 @@ var init_login_runner = __esm({
30279
31256
  }
30280
31257
  });
30281
31258
 
31259
+ // src/mcp/download.js
31260
+ import fs17 from "node:fs/promises";
31261
+ import path18 from "node:path";
31262
+ async function reserveName(dir, stem) {
31263
+ for (let n = 0; ; n++) {
31264
+ const file2 = path18.join(dir, n === 0 ? `${stem}${ZIP}` : `${stem} (${n})${ZIP}`);
31265
+ try {
31266
+ await (await fs17.open(file2, "wx")).close();
31267
+ return file2;
31268
+ } catch (error2) {
31269
+ if (!isErrno(error2, "EEXIST") || n >= 999) throw error2;
31270
+ }
31271
+ }
31272
+ }
31273
+ async function saveZip(dir, fileName, bytes) {
31274
+ const base = fileName.toLowerCase().endsWith(ZIP) ? fileName.slice(0, -ZIP.length) : fileName;
31275
+ const stem = WINDOWS_DEVICE_NAME_RE.test(base) ? `${base}-canvas` : base;
31276
+ const tmp = path18.join(dir, tempName(`.${stem}${ZIP}`));
31277
+ let file2 = null;
31278
+ try {
31279
+ await fs17.mkdir(dir, { recursive: true });
31280
+ await fs17.writeFile(tmp, bytes, { flag: "wx" });
31281
+ file2 = await reserveName(dir, stem);
31282
+ await fs17.rename(tmp, file2);
31283
+ return file2;
31284
+ } catch (error2) {
31285
+ await Promise.all([fs17.rm(tmp, { force: true }), file2 ? fs17.rm(file2, { force: true }) : void 0]).catch(
31286
+ () => void 0
31287
+ );
31288
+ const reason = isErrnoLike(error2) ? error2.code : "the file could not be written";
31289
+ throw new CliError("CLI_DOWNLOAD_FAILED", `Could not save the download in the Downloads folder (${reason}).`);
31290
+ }
31291
+ }
31292
+ function isErrnoLike(error2) {
31293
+ return typeof error2 === "object" && error2 !== null && typeof /** @type {{ code?: unknown }} */
31294
+ error2.code === "string";
31295
+ }
31296
+ function fetchersOf(api) {
31297
+ return {
31298
+ fetchText: async (url2) => decoder.decode(await api.download(url2)),
31299
+ fetchBytes: async (url2) => {
31300
+ try {
31301
+ return await api.download(url2);
31302
+ } catch (error2) {
31303
+ if (refusedByCdn(error2)) return null;
31304
+ throw error2;
31305
+ }
31306
+ }
31307
+ };
31308
+ }
31309
+ function fetchFailure(error2) {
31310
+ const cause = error2.cause;
31311
+ if (cause instanceof CliError) {
31312
+ return new CliError(cause.code, `${error2.message}: ${cause.message}`, {
31313
+ status: cause.status,
31314
+ exit: cause.exit,
31315
+ details: cause.details
31316
+ });
31317
+ }
31318
+ return new CliError(
31319
+ "CLI_DOWNLOAD_FAILED",
31320
+ `${error2.message}: ${cause instanceof Error ? cause.message : String(cause)}`
31321
+ );
31322
+ }
31323
+ async function downloadCanvas(session, canvasId, dir) {
31324
+ const read2 = (await session.api.call({ method: "GET", path: `/design/canvases/${canvasId}` })).body;
31325
+ let built;
31326
+ try {
31327
+ built = await downloadCanvasZip(read2, fetchersOf(session.api));
31328
+ } catch (error2) {
31329
+ if (error2 instanceof CanvasDownloadFetchError) throw fetchFailure(error2);
31330
+ throw error2;
31331
+ }
31332
+ const file2 = await saveZip(dir, built.fileName, built.zip);
31333
+ return {
31334
+ canvas: canvasId,
31335
+ path: file2,
31336
+ designCount: built.designCount,
31337
+ imageCount: built.imageCount,
31338
+ missingImages: built.missingImages.length + built.unlistedImages.length
31339
+ };
31340
+ }
31341
+ var ZIP, decoder, refusedByCdn;
31342
+ var init_download = __esm({
31343
+ "src/mcp/download.js"() {
31344
+ "use strict";
31345
+ init_define_KOMBAI_TELEMETRY();
31346
+ init_contract();
31347
+ init_fsx();
31348
+ init_output();
31349
+ ZIP = ".zip";
31350
+ decoder = new TextDecoder();
31351
+ refusedByCdn = (error2) => error2 instanceof CliError && error2.code === "CLI_STORAGE_REFUSED" && typeof error2.status === "number" && error2.status >= 400 && error2.status < 500;
31352
+ }
31353
+ });
31354
+
30282
31355
  // src/mcp/tools.js
30283
31356
  function isVersionOf(uri, base) {
30284
31357
  const prefix = `${base}?v=`;
@@ -30343,6 +31416,45 @@ function toolDescriptors(resourceUri) {
30343
31416
  },
30344
31417
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
30345
31418
  _meta: { ui: { visibility: ["app"] } }
31419
+ },
31420
+ {
31421
+ name: RENAME_TOOL,
31422
+ description: "Kombai home: rename a canvas the signed-in person may edit, and answer the name the store kept. The view's own.",
31423
+ inputSchema: {
31424
+ type: "object",
31425
+ properties: {
31426
+ canvas: { type: "string", pattern: DESIGN_ID.canvas.source },
31427
+ name: { type: "string", minLength: 1, maxLength: DESIGN_LIMITS.nameMaxChars }
31428
+ },
31429
+ required: ["canvas", "name"],
31430
+ additionalProperties: false
31431
+ },
31432
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
31433
+ _meta: { ui: { visibility: ["app"] } }
31434
+ },
31435
+ {
31436
+ name: DELETE_TOOL,
31437
+ description: "Kombai home: delete a canvas the signed-in person owns, for everyone. The view's own.",
31438
+ inputSchema: {
31439
+ type: "object",
31440
+ properties: { canvas: { type: "string", pattern: DESIGN_ID.canvas.source } },
31441
+ required: ["canvas"],
31442
+ additionalProperties: false
31443
+ },
31444
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
31445
+ _meta: { ui: { visibility: ["app"] } }
31446
+ },
31447
+ {
31448
+ name: DOWNLOAD_TOOL,
31449
+ description: "Kombai home: save a canvas as a zip in this computer's Downloads folder, laid out to unzip into a project (.kombai/canvas/<name>.canvas and its images), and answer where it went; a guest's own canvas too. The view's own.",
31450
+ inputSchema: {
31451
+ type: "object",
31452
+ properties: { canvas: { type: "string", pattern: DESIGN_ID.canvas.source } },
31453
+ required: ["canvas"],
31454
+ additionalProperties: false
31455
+ },
31456
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
31457
+ _meta: { ui: { visibility: ["app"] } }
30346
31458
  }
30347
31459
  ];
30348
31460
  }
@@ -30474,6 +31586,39 @@ async function callCreate(ctx, args) {
30474
31586
  });
30475
31587
  return answer({ canvas: body.id, name: body.name, url: body.url, projectId });
30476
31588
  }
31589
+ function cardCanvasId(value) {
31590
+ if (typeof value !== "string" || !DESIGN_ID.canvas.test(value))
31591
+ throw badArgument("canvas must be a canvas id (cnv_\u2026).");
31592
+ return value;
31593
+ }
31594
+ async function callRename(ctx, args) {
31595
+ const canvasId = cardCanvasId(args.canvas);
31596
+ const name = typeof args.name === "string" ? args.name.trim() : "";
31597
+ if (!name || name.length > DESIGN_LIMITS.nameMaxChars) {
31598
+ throw badArgument(`name is required: 1 to ${DESIGN_LIMITS.nameMaxChars} characters.`);
31599
+ }
31600
+ const session = await openSession(ctx, { claim: false, deadline: new Deadline(MANAGE_DEADLINE_MS, ctx.now) });
31601
+ const { body } = await session.api.call({ method: "PATCH", path: `/design/canvases/${canvasId}`, body: { name } });
31602
+ return answer({ canvas: canvasId, name: typeof body?.name === "string" ? body.name : name });
31603
+ }
31604
+ async function callDelete(ctx, args) {
31605
+ const canvasId = cardCanvasId(args.canvas);
31606
+ const session = await openSession(ctx, { claim: false, deadline: new Deadline(MANAGE_DEADLINE_MS, ctx.now) });
31607
+ try {
31608
+ await deleteStoredCanvas(session.api, canvasId);
31609
+ } catch (error2) {
31610
+ if (error2 instanceof CliError && error2.code === "DESIGN_FORBIDDEN") {
31611
+ throw new CliError(error2.code, ONLY_OWNER_DELETES, { status: error2.status, details: error2.details });
31612
+ }
31613
+ throw error2;
31614
+ }
31615
+ return answer({ canvas: canvasId, deleted: true });
31616
+ }
31617
+ async function callDownload(ctx, args, dir) {
31618
+ const canvasId = cardCanvasId(args.canvas);
31619
+ const session = await openAnySession(ctx, { claim: false, deadline: new Deadline(DOWNLOAD_DEADLINE_MS, ctx.now) });
31620
+ return answer(await downloadCanvas(session, canvasId, dir));
31621
+ }
30477
31622
  async function canBeGuest(ctx) {
30478
31623
  const { env } = await currentEnv(ctx);
30479
31624
  return !holdsAccount(await readEntry(ctx.home, env));
@@ -30690,26 +31835,35 @@ function answer(structuredContent) {
30690
31835
  ), text: JSON.stringify(structuredContent) }]
30691
31836
  };
30692
31837
  }
30693
- var CANVAS_APP_TOOL, SESSION_TOOL, ACCOUNT_TOOL, CREATE_TOOL, MULTI_TEAM_NOT_SUPPORTED, RESOURCE_URI_BASE, versionedUri, SIGN_IN_MAX_WAIT_S, INSTRUCTIONS, read, badArgument, given;
31838
+ var CANVAS_APP_TOOL, SESSION_TOOL, ACCOUNT_TOOL, CREATE_TOOL, RENAME_TOOL, DELETE_TOOL, DOWNLOAD_TOOL, ONLY_OWNER_DELETES, DOWNLOAD_DEADLINE_MS, MANAGE_DEADLINE_MS, MULTI_TEAM_NOT_SUPPORTED, RESOURCE_URI_BASE, versionedUri, SIGN_IN_MAX_WAIT_S, INSTRUCTIONS, read, badArgument, given;
30694
31839
  var init_tools = __esm({
30695
31840
  "src/mcp/tools.js"() {
30696
31841
  "use strict";
30697
31842
  init_define_KOMBAI_TELEMETRY();
30698
31843
  init_kombai_icon();
30699
31844
  init_auth();
31845
+ init_canvas();
30700
31846
  init_api();
30701
31847
  init_contract();
31848
+ init_deadline();
30702
31849
  init_output();
30703
31850
  init_project();
30704
31851
  init_session();
30705
31852
  init_store();
30706
31853
  init_subscription();
30707
31854
  init_version();
31855
+ init_download();
30708
31856
  init_login_runner();
30709
31857
  CANVAS_APP_TOOL = "canvas_app";
30710
31858
  SESSION_TOOL = "canvas_app_session";
30711
31859
  ACCOUNT_TOOL = "canvas_app_account";
30712
31860
  CREATE_TOOL = "canvas_app_create";
31861
+ RENAME_TOOL = "canvas_app_rename";
31862
+ DELETE_TOOL = "canvas_app_delete";
31863
+ DOWNLOAD_TOOL = "canvas_app_download";
31864
+ ONLY_OWNER_DELETES = "Only the canvas's owner can delete it.";
31865
+ DOWNLOAD_DEADLINE_MS = 5e4;
31866
+ MANAGE_DEADLINE_MS = 5e4;
30713
31867
  MULTI_TEAM_NOT_SUPPORTED = "Creating a canvas from more than one team is not supported yet";
30714
31868
  RESOURCE_URI_BASE = "ui://kombai/cli-canvas-app";
30715
31869
  versionedUri = (base, version2) => `${base}?v=${encodeURIComponent(version2)}`;
@@ -30937,8 +32091,8 @@ var init_sign_in_card = __esm({
30937
32091
  });
30938
32092
 
30939
32093
  // src/mcp/cards.js
30940
- import fs17 from "node:fs/promises";
30941
- import path18 from "node:path";
32094
+ import fs18 from "node:fs/promises";
32095
+ import path19 from "node:path";
30942
32096
  import { fileURLToPath } from "node:url";
30943
32097
  function createCards(ctx, options) {
30944
32098
  const dir = options.dir ?? CARDS_DIR;
@@ -30946,7 +32100,7 @@ function createCards(ctx, options) {
30946
32100
  const script = (spec) => {
30947
32101
  let read2 = scripts.get(spec);
30948
32102
  if (!read2) {
30949
- read2 = fs17.readFile(path18.join(dir, spec.bundle), "utf8").catch(() => null);
32103
+ read2 = fs18.readFile(path19.join(dir, spec.bundle), "utf8").catch(() => null);
30950
32104
  scripts.set(spec, read2);
30951
32105
  }
30952
32106
  return read2;
@@ -31360,9 +32514,9 @@ var init_stdio3 = __esm({
31360
32514
 
31361
32515
  // src/mcp/view-html.js
31362
32516
  function viewHtml(version2, host, options = {}) {
31363
- return VIEW_HTML.replace("{{CLI_VERSION}}", version2).replaceAll("{{HOST_LABEL}}", host.label).replaceAll("{{HOST_EMBED}}", host.embed).replace("{{CLAIM_RETRY_MS}}", String(options.claimRetryMs ?? CLAIM_RETRY_MS)).replace("{{COVER_MS}}", String(options.coverMs ?? COVER_MS)).replace("{{RECHECK_MS}}", String(options.recheckMs ?? RECHECK_MS));
32517
+ return VIEW_HTML.replace("{{CLI_VERSION}}", version2).replaceAll("{{HOST_LABEL}}", host.label).replaceAll("{{HOST_EMBED}}", host.embed).replace("{{CLAIM_RETRY_MS}}", String(options.claimRetryMs ?? CLAIM_RETRY_MS)).replace("{{COVER_MS}}", String(options.coverMs ?? COVER_MS)).replace("{{RECHECK_MS}}", String(options.recheckMs ?? RECHECK_MS)).replace("{{MANAGE_WAIT_MS}}", String(options.manageWaitMs ?? MANAGE_WAIT_MS)).replace("{{DOWNLOAD_WAIT_MS}}", String(options.downloadWaitMs ?? DOWNLOAD_WAIT_MS));
31364
32518
  }
31365
- var VIEW_HTML, CLAIM_RETRY_MS, COVER_MS, RECHECK_MS;
32519
+ var VIEW_HTML, CLAIM_RETRY_MS, COVER_MS, RECHECK_MS, MANAGE_WAIT_MS, DOWNLOAD_WAIT_MS;
31366
32520
  var init_view_html = __esm({
31367
32521
  "src/mcp/view-html.js"() {
31368
32522
  "use strict";
@@ -31426,7 +32580,9 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31426
32580
  var HOST_LABEL = '{{HOST_LABEL}}', HOST_EMBED = '{{HOST_EMBED}}';
31427
32581
  var CLAIM_RETRY_MS = {{CLAIM_RETRY_MS}}, CLAIM_TRIES = 3;
31428
32582
  var COVER_MS = {{COVER_MS}}, RECHECK_MS = {{RECHECK_MS}};
32583
+ var MANAGE_WAIT_MS = {{MANAGE_WAIT_MS}}, DOWNLOAD_WAIT_MS = {{DOWNLOAD_WAIT_MS}};
31429
32584
  var SESSION_TOOL = 'canvas_app_session', ACCOUNT_TOOL = 'canvas_app_account', CREATE_TOOL = 'canvas_app_create';
32585
+ var RENAME_TOOL = 'canvas_app_rename', DELETE_TOOL = 'canvas_app_delete', DOWNLOAD_TOOL = 'canvas_app_download';
31430
32586
  // Every message from the page is a draft, whatever the page asked, while this and the page's ACTIONS_SENT_INTO_CHAT
31431
32587
  // are off (embed-bridge.ts says why that is a product decision now, not a wait for the frame fix).
31432
32588
  var SEND_ACTIONS = false;
@@ -31434,6 +32590,10 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31434
32590
  var RESULT_WAIT_MS = 2000, SIGN_IN_WAIT_S = 20;
31435
32591
  // The store's canvas-name limit (DESIGN_LIMITS.nameMaxChars): a longer create-canvas is a forged or broken message.
31436
32592
  var NAME_MAX_CHARS = 200;
32593
+ var CANVAS_ID = /^cnv_[0-9a-f]{12}$/;
32594
+ var STILL_OPENING = 'Kombai is still opening; try again in a moment.';
32595
+ var GUEST_CANNOT = 'Sign in to Kombai to rename or delete a canvas.';
32596
+ var BUSY = 'Kombai is still finishing the last one; try again in a moment.';
31437
32597
 
31438
32598
  var screen = document.getElementById('screen');
31439
32599
  var title = document.getElementById('title');
@@ -31513,6 +32673,8 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31513
32673
  var account = null;
31514
32674
  // A create-canvas is being answered: a second one waits for it to settle and is otherwise dropped.
31515
32675
  var creating = false;
32676
+ // The rename, delete and download being answered, by number (0: none): another of its kind meanwhile gets BUSY.
32677
+ var inFlight = { rename: 0, delete: 0, download: 0 }, manageCalls = 0;
31516
32678
  // True only once the home's document has loaded: until then the old page is still the frame's window.
31517
32679
  var framedHome = false;
31518
32680
  // The loaded home is the guest home; the guest's canvas.
@@ -31625,9 +32787,11 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31625
32787
  return { top: n(raw.top), right: n(raw.right), bottom: n(raw.bottom), left: n(raw.left) };
31626
32788
  }
31627
32789
  function hello() {
31628
- // Create, the account and the guest canvas go only to the loaded home (a design's script could read them).
32790
+ // Create, the account, the guest canvas, Rename, Delete and Download go only to the loaded home (a design's script
32791
+ // could read them); Rename and Delete not to the guest home, whose guest may only download.
31629
32792
  return {
31630
- kind: 'hello', theme: theme, canvases: true, creates: framedHome, insets: insets,
32793
+ kind: 'hello', theme: theme, canvases: true, creates: framedHome, manages: framedHome && !framedGuest,
32794
+ downloads: framedHome, insets: insets,
31631
32795
  account: framedHome && !framedGuest ? account : null,
31632
32796
  guest: framedHome && framedGuest ? { canvas: guestCanvas } : null,
31633
32797
  };
@@ -31661,6 +32825,54 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31661
32825
  postToFrame({ kind: 'create-failed', message: error.message, code: error.code || null });
31662
32826
  });
31663
32827
  }
32828
+ // A home card's Rename and Delete: the CLI makes the change with the key, since the home's own pass has no project
32829
+ // and the store refuses a write from such a pass; the page is told either way. One of each kind at a time.
32830
+ // In flight until it settles, or until the page's own wait runs out if Codex never answers; finish() is then false.
32831
+ function startCall(kind, waitMs) {
32832
+ var call = ++manageCalls;
32833
+ inFlight[kind] = call;
32834
+ var timer = setTimeout(function () { if (inFlight[kind] === call) inFlight[kind] = 0; }, waitMs);
32835
+ return function finish() {
32836
+ clearTimeout(timer);
32837
+ if (inFlight[kind] !== call) return false;
32838
+ inFlight[kind] = 0;
32839
+ return true;
32840
+ };
32841
+ }
32842
+ function renameCanvas(id, name) {
32843
+ var finish = startCall('rename', MANAGE_WAIT_MS);
32844
+ callTool(RENAME_TOOL, { canvas: id, name: name }).then(function (answer) {
32845
+ if (!finish()) return;
32846
+ postToFrame({ kind: 'canvas-renamed', canvasId: id, name: typeof answer.name === 'string' ? answer.name : name });
32847
+ }, function (error) {
32848
+ if (!finish()) return;
32849
+ postToFrame({ kind: 'rename-failed', canvasId: id, message: error.message, code: error.code || null });
32850
+ });
32851
+ }
32852
+ function deleteCanvas(id) {
32853
+ var finish = startCall('delete', MANAGE_WAIT_MS);
32854
+ callTool(DELETE_TOOL, { canvas: id }).then(function () {
32855
+ if (!finish()) return;
32856
+ postToFrame({ kind: 'canvas-deleted', canvasId: id });
32857
+ }, function (error) {
32858
+ if (!finish()) return;
32859
+ postToFrame({ kind: 'delete-failed', canvasId: id, message: error.message, code: error.code || null });
32860
+ });
32861
+ }
32862
+ // A home card's Download: Codex's frame cannot download, and the guest home holds no pass to read a canvas with, so
32863
+ // the CLI reads the canvas, builds its zip and writes it to the Downloads folder; the page is told where it went.
32864
+ function downloadCanvas(id) {
32865
+ var finish = startCall('download', DOWNLOAD_WAIT_MS);
32866
+ callTool(DOWNLOAD_TOOL, { canvas: id }).then(function (answer) {
32867
+ if (typeof answer.path !== 'string') throw new Error('Kombai did not say where the file went.');
32868
+ if (!finish()) return;
32869
+ var missing = typeof answer.missingImages === 'number' ? answer.missingImages : 0;
32870
+ postToFrame({ kind: 'download-saved', canvasId: id, path: answer.path, missingImages: missing });
32871
+ }).catch(function (error) {
32872
+ if (!finish()) return;
32873
+ postToFrame({ kind: 'download-failed', canvasId: id, message: error.message, code: error.code || null });
32874
+ });
32875
+ }
31664
32876
  function fromPage(m) {
31665
32877
  if (!m || m.kombai !== EMBED || m.v !== PROTOCOL || typeof m.kind !== 'string') return;
31666
32878
  if (m.kind === 'ready') { postToFrame(hello()); return; }
@@ -31686,7 +32898,7 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31686
32898
  }
31687
32899
  // A card on /canvases: that canvas's own ticket, then its page. Only a canvas id is taken, so a forged message
31688
32900
  // can open nothing but a canvas, which the ticket route then judges.
31689
- if (m.kind === 'open-canvas' && typeof m.canvas === 'string' && /^cnv_[0-9a-f]{12}$/.test(m.canvas)) {
32901
+ if (m.kind === 'open-canvas' && typeof m.canvas === 'string' && CANVAS_ID.test(m.canvas)) {
31690
32902
  canvas = m.canvas;
31691
32903
  node = null;
31692
32904
  open();
@@ -31705,12 +32917,31 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31705
32917
  if (m.kind === 'create-canvas') {
31706
32918
  if (creating || typeof m.name !== 'string' || !m.name.trim() || m.name.length > NAME_MAX_CHARS) return;
31707
32919
  if (!framedHome) {
31708
- postToFrame({ kind: 'create-failed', message: 'Kombai is still opening; try again in a moment.' });
32920
+ postToFrame({ kind: 'create-failed', message: STILL_OPENING });
31709
32921
  return;
31710
32922
  }
31711
32923
  createCanvas(m.name.trim());
31712
32924
  return;
31713
32925
  }
32926
+ // Rename, Delete and Download: as Create, a canvas id (and a name) only, one of each kind at a time; one before
32927
+ // the load, a Rename or Delete from the guest home, or one while another of its kind is answered gets a failure,
32928
+ // so the page's menu does not wait for good.
32929
+ if (m.kind === 'rename-canvas' || m.kind === 'delete-canvas' || m.kind === 'download-canvas') {
32930
+ var kind = m.kind.split('-')[0];
32931
+ var busy = inFlight[kind] !== 0;
32932
+ if (typeof m.canvasId !== 'string' || !CANVAS_ID.test(m.canvasId)) return;
32933
+ if (kind === 'rename' && (typeof m.name !== 'string' || !m.name.trim() || m.name.length > NAME_MAX_CHARS)) return;
32934
+ var refused = !framedHome ? STILL_OPENING
32935
+ : framedGuest && kind !== 'download' ? GUEST_CANNOT : busy ? BUSY : null;
32936
+ if (refused) {
32937
+ postToFrame({ kind: kind + '-failed', canvasId: m.canvasId, message: refused, code: null });
32938
+ return;
32939
+ }
32940
+ if (kind === 'rename') renameCanvas(m.canvasId, m.name.trim());
32941
+ else if (kind === 'delete') deleteCanvas(m.canvasId);
32942
+ else downloadCanvas(m.canvasId);
32943
+ return;
32944
+ }
31714
32945
  if (m.kind === 'open-link' && typeof m.url === 'string' && /^https:\/\//i.test(m.url)) offerLink(m.url);
31715
32946
  }
31716
32947
 
@@ -31964,11 +33195,14 @@ html.dark #cover{background:rgba(30,30,30,.6)}
31964
33195
  CLAIM_RETRY_MS = 3e3;
31965
33196
  COVER_MS = 1e4;
31966
33197
  RECHECK_MS = 2e4;
33198
+ MANAGE_WAIT_MS = 6e4;
33199
+ DOWNLOAD_WAIT_MS = 12e4;
31967
33200
  }
31968
33201
  });
31969
33202
 
31970
33203
  // src/mcp/server.js
31971
33204
  import os2 from "node:os";
33205
+ import path20 from "node:path";
31972
33206
  function createMcpServer(ctx, options = {}) {
31973
33207
  const place = {
31974
33208
  cwd: ctx.cwd,
@@ -31989,6 +33223,7 @@ function createMcpServer(ctx, options = {}) {
31989
33223
  const login2 = createLoginRunner(ctx);
31990
33224
  const callSession = createSessionTool(ctx, { login: login2 });
31991
33225
  const cards = createCards(ctx, { dir: options.cardsDir, login: login2 });
33226
+ const downloadsDir = path20.join(place.osHome, "Downloads");
31992
33227
  const resourceMeta = async () => {
31993
33228
  const { hosts } = await currentEnv(ctx);
31994
33229
  return {
@@ -32036,6 +33271,9 @@ function createMcpServer(ctx, options = {}) {
32036
33271
  if (host && name === SESSION_TOOL) return await callSession(args, host);
32037
33272
  if (host && name === ACCOUNT_TOOL) return await callAccount(ctx);
32038
33273
  if (host && name === CREATE_TOOL) return await callCreate(ctx, args);
33274
+ if (host && name === RENAME_TOOL) return await callRename(ctx, args);
33275
+ if (host && name === DELETE_TOOL) return await callDelete(ctx, args);
33276
+ if (host && name === DOWNLOAD_TOOL) return await callDownload(ctx, args, downloadsDir);
32039
33277
  const card = await cards.call(set2, name, args);
32040
33278
  if (card) return card;
32041
33279
  return toolError(new CliError("CLI_UNKNOWN_TOOL", `${name} is not a tool of this server for this client.`));
@@ -32188,7 +33426,7 @@ var init_drawings = __esm({
32188
33426
  var faq_default;
32189
33427
  var init_faq = __esm({
32190
33428
  "src/skill/faq.md"() {
32191
- faq_default = "# Questions about Kombai\n\nAnswer the user's question from this text, briefly and in your own words. To answer, run only commands that\nchange nothing (`kombai whoami`, `kombai credits`, `kombai canvas list`). If the answer is not here, say so and\npoint them to support@kombai.com; don't guess. For design work, run `kombai skill` and follow it.\n\n## What Kombai is\n\n- **What it does.** Kombai is an AI design engineer. The coding agent runs the Kombai CLI: Kombai's taste agent\n writes design directions grounded in the user's brief and repo, and the agent builds each design as HTML on a\n hosted Kombai canvas, where the user compares, edits and refines the designs in the browser.\n- **Which agents.** Claude Code, Codex and Cursor have Kombai plugins; any agent with a terminal can run the CLI.\n Where the agent shows MCP views (the Codex app, the Claude desktop app's Code tab), the canvas or Kombai's\n cards can show beside the chat; elsewhere the canvas opens in the browser.\n- **The Kombai desktop app** is not needed: the CLI designs on a hosted canvas whether or not it is installed.\n- **Requirements.** Node.js 20 or later, and a Kombai account or guest mode. Thumbnails need a Chromium browser\n (Chrome, Edge, Brave, Arc or Chromium); without one, `kombai browser install` downloads a headless Chromium of\n about 100 MB, after asking.\n\n## Account and credits\n\n- **Without an account.** `kombai guest` gives one canvas, with no taste runs, repo images, design systems or\n sharing. The guest canvas ends on the date `kombai whoami` shows; signing in keeps it.\n- **Signing in.** `kombai login` shows a match code and opens a Kombai page in the browser: approve there only\n if the codes match. `kombai whoami` shows who is signed in. `kombai logout` signs this machine out;\n `kombai logout --everywhere` also signs out every other key, the Kombai app and the website.\n- **Credits.** Taste runs spend Kombai credits; `kombai credits` shows what is left, the plan and when it refills.\n On a team plan they are the team's shared pool. With none left, its next is the plans page. The designs\n themselves are written by the user's own coding agent, on that agent's usage.\n- **Organizations.** With several, `kombai config org <id>` sets which one owns new canvases and design systems.\n\n## Designs and data\n\n- **Where designs live.** On hosted canvases in the user's Kombai account. `kombai canvas list` lists this\n repo's, `kombai canvas list --all` every one, and `kombai canvas open --canvas <id>` opens one in the browser.\n- **Editing.** The user can edit text, styles and layout on the canvas, or ask for a change from it: the canvas\n gives them a request to paste into this chat.\n- **Into code.** Ask the agent to build a design in this project: it writes it in the repo's own framework,\n components and styles, with the design as the reference.\n- **Design systems** are .ds files in the Kombai account and need no canvas; `kombai ds list` lists them.\n- **Sharing.** A new canvas is private. `kombai canvas share --canvas <id> --on` lets anyone with the link view it\n and teammates edit it; `--off` turns that off. Only the canvas's owner can.\n- **What Kombai receives.** The brief the agent writes for a taste run, each design's HTML, the repo images a\n design uses, files the agent uploads, design systems it pushes, and the thumbnails rendered on this machine.\n The rest of the repo is not uploaded.\n- **What stays here.** The sign-in key and the working copies of canvases, under ~/.kombai/cli.\n- **Usage data.** The CLI sends Kombai an event for each command (which ran, how it ended, how long it took) and\n reports unexpected errors. `DO_NOT_TRACK=1` turns both off.\n- **Deleting.** `kombai canvas delete --canvas <id>` and `kombai ds delete <slug>` delete for everyone. Deleting\n ~/.kombai removes what is stored on this machine. To close the account, email support@kombai.com.\n\n## Setup and problems\n\n- **Permissions.** Kombai needs network access and writes ~/.kombai, so an agent with a sandbox asks to run it\n outside.\n- **Updates.** The plugins run the CLI through npx, which fetches the newest release itself; a global install\n updates with npm. The plugin updates through the agent's own plugin manager.\n- **Reporting a problem.** Email support@kombai.com with the command, the JSON line it printed and the version\n `kombai --version` prints.\n";
33429
+ faq_default = "# Questions about Kombai\n\nAnswer the user's question from this text, briefly and in your own words. To answer, run only commands that\nchange nothing (`kombai whoami`, `kombai credits`, `kombai canvas list`). If the answer is not here, say so and\npoint them to support@kombai.com; don't guess. For design work, run `kombai skill` and follow it.\n\n## What Kombai is\n\n- **What it does.** Kombai is an AI design engineer. The coding agent runs the Kombai CLI: Kombai's taste agent\n writes design directions grounded in the user's brief and repo, and the agent builds each design as HTML on a\n hosted Kombai canvas, where the user compares, edits and refines the designs in the browser.\n- **Which agents.** Claude Code, Codex and Cursor have Kombai plugins; any agent with a terminal can run the CLI.\n Where the agent shows MCP views (the Codex app, the Claude desktop app's Code tab), the canvas or Kombai's\n cards can show beside the chat; elsewhere the canvas opens in the browser.\n- **The Kombai desktop app** is not needed: the CLI designs on a hosted canvas whether or not it is installed.\n- **Requirements.** Node.js 20 or later, and a Kombai account or guest mode. Thumbnails need a Chromium browser\n (Chrome, Edge, Brave, Arc or Chromium); without one, `kombai browser install` downloads a headless Chromium of\n about 100 MB, after asking.\n\n## Account and credits\n\n- **Without an account.** `kombai guest` gives one canvas, with no taste runs, repo images, design systems or\n sharing. The guest canvas ends on the date `kombai whoami` shows; signing in keeps it.\n- **Signing in.** `kombai login` shows a match code and opens a Kombai page in the browser: approve there only\n if the codes match. `kombai whoami` shows who is signed in. `kombai logout` signs this machine out;\n `kombai logout --everywhere` also signs out every other key, the Kombai app and the website.\n- **Credits.** Taste runs spend Kombai credits; `kombai credits` shows what is left, the plan and when it refills.\n On a team plan they are the team's shared pool. With none left, its next is the plans page. The designs\n themselves are written by the user's own coding agent, on that agent's usage.\n- **Organizations.** With several, `kombai config org <id>` sets which one owns new canvases and design systems.\n\n## Designs and data\n\n- **Where designs live.** On hosted canvases in the user's Kombai account. `kombai canvas list` lists this\n repo's, `kombai canvas list --all` every one, and `kombai canvas open --canvas <id>` opens one in the browser.\n- **Editing.** The user can edit text, styles and layout on the canvas, or ask for a change from it: the canvas\n gives them a request to paste into this chat.\n- **Into code.** Ask the agent to build a design in this project: it writes it in the repo's own framework,\n components and styles, with the design as the reference.\n- **Design systems** are .ds files in the Kombai account and need no canvas; `kombai ds list` lists them.\n- **Sharing.** A new canvas is private. `kombai canvas share --canvas <id> --on` lets anyone with the link view it\n and teammates edit it; `--off` turns that off. Only the canvas's owner can.\n- **What Kombai receives.** The brief the agent writes for a taste run, each design's HTML, the repo images a\n design uses, files the agent uploads, design systems it pushes, and the thumbnails rendered on this machine.\n The rest of the repo is not uploaded.\n- **What stays here.** The sign-in key and the working copies of canvases, under ~/.kombai/cli.\n- **Usage data.** The CLI sends Kombai an event for each command (which ran, how it ended, how long it took) and\n reports unexpected errors. `DO_NOT_TRACK=1` turns both off.\n- **Deleting.** `kombai canvas delete --canvas <id>` and `kombai ds delete <slug>` delete for everyone. Deleting\n ~/.kombai removes what is stored on this machine. To close the account, email support@kombai.com.\n\n## Setup and problems\n\n- **Permissions.** Kombai needs network access and writes ~/.kombai, so an agent with a sandbox asks to run it\n outside.\n- **The desktop app's skills.** The first Kombai command on a machine removes the skills the Kombai desktop app\n wrote into the agents' skills folders (`design-with-kombai`, `kombai-faq`, `kombai-status` and the rest), which\n drive the app instead of the CLI. Only the app's own copies go; other skills, the user's own included, stay. An\n agent session that was already open lists them until it restarts.\n- **Updates.** The plugins run the CLI through npx, which fetches the newest release itself; a global install\n updates with npm. The plugin updates through the agent's own plugin manager.\n- **Reporting a problem.** Email support@kombai.com with the command, the JSON line it printed and the version\n `kombai --version` prints.\n";
32192
33430
  }
32193
33431
  });
32194
33432
 
@@ -32314,8 +33552,8 @@ var init_mcp = __esm({
32314
33552
  });
32315
33553
 
32316
33554
  // src/commands/node.js
32317
- import fs18 from "node:fs/promises";
32318
- import path19 from "node:path";
33555
+ import fs19 from "node:fs/promises";
33556
+ import path21 from "node:path";
32319
33557
  async function placeText(cc) {
32320
33558
  try {
32321
33559
  const read2 = (await cc.session.api.call({ method: "GET", path: `/design/canvases/${cc.canvasId}` })).body;
@@ -32357,10 +33595,10 @@ function rectFrom(value) {
32357
33595
  return { x, y, w, h };
32358
33596
  }
32359
33597
  async function readDrawingFile(ctx, given2) {
32360
- const file2 = path19.resolve(ctx.cwd, given2);
33598
+ const file2 = path21.resolve(ctx.cwd, given2);
32361
33599
  let bytes;
32362
33600
  try {
32363
- bytes = new Uint8Array(await fs18.readFile(file2));
33601
+ bytes = new Uint8Array(await fs19.readFile(file2));
32364
33602
  } catch (error2) {
32365
33603
  if (isErrno(error2, "ENOENT"))
32366
33604
  throw new CliError("CLI_FILE_MISSING", `${file2} does not exist.`, { details: { path: file2 } });
@@ -32615,7 +33853,7 @@ async function pushDrawing(ctx, cc, projectId, nodeId, entry, saved) {
32615
33853
  if (!saved && sent === entry.files.content) {
32616
33854
  return { nodeId, status: "unchanged", version: entry.version, images: { uploaded: 0, stored: 0 } };
32617
33855
  }
32618
- const before = parseStored(await fs18.readFile(baseFile(paths, nodeId, "content")).catch(() => null));
33856
+ const before = parseStored(await fs19.readFile(baseFile(paths, nodeId, "content")).catch(() => null));
32619
33857
  const images = await storeDrawingPicture(cc, projectId, drawing, file2, nodeId, before?.src);
32620
33858
  const body = {
32621
33859
  ifVersion: saved?.version ?? entry.version,
@@ -32692,7 +33930,7 @@ async function storeDrawingPicture(cc, projectId, drawing, file2, nodeId, stored
32692
33930
  }
32693
33931
  throw error2;
32694
33932
  }
32695
- if (image.sha256 !== path19.posix.basename(src).split(".")[0]) {
33933
+ if (image.sha256 !== path21.posix.basename(src).split(".")[0]) {
32696
33934
  throw badDrawing(
32697
33935
  file2,
32698
33936
  nodeId,
@@ -32814,14 +34052,14 @@ async function explainGone(ctx, cc, nodeId, error2) {
32814
34052
  }
32815
34053
  async function saveConflict2(paths, canvasId, nodeId, stored, files) {
32816
34054
  await removeRemotes(paths, nodeId);
32817
- const dir = path19.join(paths.remote, `${nodeId}@v${stored.version}`);
32818
- await fs18.mkdir(dir, { recursive: true });
32819
- if (files.html) await writeFileAtomic(path19.join(dir, "node.html"), files.html, { mode: 420 });
32820
- if (files.overrides) await writeFileAtomic(path19.join(dir, "node.overrides.json"), files.overrides, { mode: 420 });
32821
- if (files.content) await writeFileAtomic(path19.join(dir, "node.content.json"), files.content, { mode: 420 });
32822
- await writeJsonAtomic(path19.join(dir, "images.json"), stored.images ?? [], { mode: 420 });
34055
+ const dir = path21.join(paths.remote, `${nodeId}@v${stored.version}`);
34056
+ await fs19.mkdir(dir, { recursive: true });
34057
+ if (files.html) await writeFileAtomic(path21.join(dir, "node.html"), files.html, { mode: 420 });
34058
+ if (files.overrides) await writeFileAtomic(path21.join(dir, "node.overrides.json"), files.overrides, { mode: 420 });
34059
+ if (files.content) await writeFileAtomic(path21.join(dir, "node.content.json"), files.content, { mode: 420 });
34060
+ await writeJsonAtomic(path21.join(dir, "images.json"), stored.images ?? [], { mode: 420 });
32823
34061
  await writeJsonAtomic(
32824
- path19.join(dir, "node.json"),
34062
+ path21.join(dir, "node.json"),
32825
34063
  { version: stored.version, state: stored.state, modifiedBy: stored.modifiedBy, node: stored.node },
32826
34064
  { mode: 420 }
32827
34065
  );
@@ -32844,16 +34082,16 @@ async function saveConflict2(paths, canvasId, nodeId, stored, files) {
32844
34082
  );
32845
34083
  }
32846
34084
  async function latestRemote2(paths, nodeId) {
32847
- const names = await fs18.readdir(paths.remote).catch(() => (
34085
+ const names = await fs19.readdir(paths.remote).catch(() => (
32848
34086
  /** @type {string[]} */
32849
34087
  []
32850
34088
  ));
32851
34089
  const versions = names.map((name) => name.startsWith(`${nodeId}@v`) ? Number(name.slice(nodeId.length + 2)) : NaN).filter(Number.isInteger).sort((a, b) => b - a);
32852
34090
  if (!versions.length) return null;
32853
- const dir = path19.join(paths.remote, `${nodeId}@v${versions[0]}`);
34091
+ const dir = path21.join(paths.remote, `${nodeId}@v${versions[0]}`);
32854
34092
  const saved = (
32855
34093
  /** @type {{ version?: number, node?: unknown } | undefined} */
32856
- await readJson(path19.join(dir, "node.json"))
34094
+ await readJson(path21.join(dir, "node.json"))
32857
34095
  );
32858
34096
  const node = saved?.node && typeof saved.node === "object" ? (
32859
34097
  /** @type {Record<string, unknown>} */
@@ -32875,7 +34113,7 @@ async function readNode(cc, nodeId) {
32875
34113
  }
32876
34114
  async function readWorking(paths, nodeId, kind) {
32877
34115
  try {
32878
- return new Uint8Array(await fs18.readFile(workingFile(paths, nodeId, kind)));
34116
+ return new Uint8Array(await fs19.readFile(workingFile(paths, nodeId, kind)));
32879
34117
  } catch (error2) {
32880
34118
  if (isErrno(error2, "ENOENT")) return null;
32881
34119
  throw error2;
@@ -32883,7 +34121,7 @@ async function readWorking(paths, nodeId, kind) {
32883
34121
  }
32884
34122
  async function baseCopies2(paths, nodeId, entry) {
32885
34123
  const files = {};
32886
- for (const kind of KINDS) if (entry.files[kind]) files[kind] = await fs18.readFile(baseFile(paths, nodeId, kind));
34124
+ for (const kind of KINDS) if (entry.files[kind]) files[kind] = await fs19.readFile(baseFile(paths, nodeId, kind));
32887
34125
  return files;
32888
34126
  }
32889
34127
  var PUSH_TRIES, START_TRIES2, TEXT_SIZE, PLACEMENT_GAP, EMPTY_HTML, CONFLICT_MARKER, RECT_PROBLEM, DATA_KIDS_MODULE, STOPS_PUSH, nodeStart, nodePull, nodePush, nodeLock, nodeUnlock;
@@ -33018,11 +34256,11 @@ var init_node = __esm({
33018
34256
  return Object.keys(base.nodes).length === 0 && Object.keys(base.starts).length === 0;
33019
34257
  });
33020
34258
  if (fresh && unused && (error2.status === 404 || error2.status === 410)) {
33021
- const files = await fs18.readdir(paths.nodes).catch(() => (
34259
+ const files = await fs19.readdir(paths.nodes).catch(() => (
33022
34260
  /** @type {string[]} */
33023
34261
  []
33024
34262
  ));
33025
- if (!files.length) await fs18.rm(paths.dir, { recursive: true, force: true });
34263
+ if (!files.length) await fs19.rm(paths.dir, { recursive: true, force: true });
33026
34264
  }
33027
34265
  }
33028
34266
  throw await canvasGone(cc, error2);
@@ -33147,7 +34385,7 @@ var init_node = __esm({
33147
34385
  type,
33148
34386
  version: read2.version,
33149
34387
  state: read2.state,
33150
- file: info.file ? path19.join(paths.dir, info.file) : null,
34388
+ file: info.file ? path21.join(paths.dir, info.file) : null,
33151
34389
  url: nodeLink(cc, nodeId),
33152
34390
  overrides: files.overrides ? workingFile(paths, nodeId, "overrides") : null,
33153
34391
  images: read2.images ?? [],
@@ -33375,7 +34613,7 @@ var init_pngtiles = __esm({
33375
34613
 
33376
34614
  // src/commands/screenshot.js
33377
34615
  import { execFile as execFile2 } from "node:child_process";
33378
- import path20 from "node:path";
34616
+ import path22 from "node:path";
33379
34617
  async function writeTiles(ctx, dir, nodeId, version2, png, screenshotFile) {
33380
34618
  const tiles = png ? pngTiles(png, TILE_HEIGHT) : null;
33381
34619
  if (!tiles) {
@@ -33386,8 +34624,8 @@ async function writeTiles(ctx, dir, nodeId, version2, png, screenshotFile) {
33386
34624
  });
33387
34625
  return [screenshotFile];
33388
34626
  }
33389
- if (tiles.length === 1) return [path20.join(dir, `${nodeId}@v${version2}.png`)];
33390
- const files = tiles.map((_, i) => path20.join(dir, `${nodeId}@v${version2}.tile-${i + 1}.png`));
34627
+ if (tiles.length === 1) return [path22.join(dir, `${nodeId}@v${version2}.png`)];
34628
+ const files = tiles.map((_, i) => path22.join(dir, `${nodeId}@v${version2}.tile-${i + 1}.png`));
33391
34629
  await Promise.all(files.map((file2, i) => writeFileAtomic(file2, tiles[i], { mode: 420 })));
33392
34630
  return files;
33393
34631
  }
@@ -33483,7 +34721,7 @@ var init_screenshot = __esm({
33483
34721
  if (named2 && flags.canvas === void 0) {
33484
34722
  throw new CliError("CLI_BAD_FLAG", "--node needs --canvas.", { next: "kombai screenshot fill --help" });
33485
34723
  }
33486
- const browserFlag = flags.browser === void 0 ? void 0 : path20.resolve(ctx.cwd, String(flags.browser));
34724
+ const browserFlag = flags.browser === void 0 ? void 0 : path22.resolve(ctx.cwd, String(flags.browser));
33487
34725
  if (browserFlag) {
33488
34726
  await checkNamedBrowser(
33489
34727
  browserFlag,
@@ -33691,14 +34929,14 @@ var init_screenshot = __esm({
33691
34929
  if (shot.state === "ok" && shot.screenshot) {
33692
34930
  const dir = canvasPaths(cc.work, canvasId).screenshots;
33693
34931
  await ensureDir(dir);
33694
- const screenshotFile = path20.join(dir, `${nodeId}@v${read2.version}.jpg`);
34932
+ const screenshotFile = path22.join(dir, `${nodeId}@v${read2.version}.jpg`);
33695
34933
  await writeFileAtomic(screenshotFile, await cc.session.api.download(shot.screenshot, deadline), {
33696
34934
  mode: 420
33697
34935
  });
33698
34936
  let screenshotPngFile = null;
33699
34937
  let png = null;
33700
34938
  if (shot.screenshotPng) {
33701
- screenshotPngFile = path20.join(dir, `${nodeId}@v${read2.version}.png`);
34939
+ screenshotPngFile = path22.join(dir, `${nodeId}@v${read2.version}.png`);
33702
34940
  png = await cc.session.api.download(shot.screenshotPng, deadline);
33703
34941
  await writeFileAtomic(screenshotPngFile, png, { mode: 420 });
33704
34942
  }
@@ -33761,7 +34999,7 @@ var init_screenshot = __esm({
33761
34999
  );
33762
35000
  }
33763
35001
  ctx.stderr.write(
33764
- `Download chrome-headless-shell ${PINNED_BUILD} (about 100 MB) into ${path20.join(ctx.home, "browser")}? [y/N] `
35002
+ `Download chrome-headless-shell ${PINNED_BUILD} (about 100 MB) into ${path22.join(ctx.home, "browser")}? [y/N] `
33765
35003
  );
33766
35004
  if (!/^y(es)?$/i.test(await readLine())) throw new CliError("CLI_CANCELLED", "Nothing was downloaded.");
33767
35005
  }
@@ -33771,7 +35009,7 @@ var init_screenshot = __esm({
33771
35009
  /** @type {typeof import('../render/install-entry.js')} */
33772
35010
  await import(INSTALL_MODULE)
33773
35011
  );
33774
- const executable = await installHeadlessShell(path20.join(ctx.home, "browser"), PINNED_BUILD);
35012
+ const executable = await installHeadlessShell(path22.join(ctx.home, "browser"), PINNED_BUILD);
33775
35013
  const answer2 = await askVersion(executable, 3e4);
33776
35014
  if (!answer2.version) {
33777
35015
  throw new CliError(
@@ -33789,7 +35027,7 @@ var init_screenshot = __esm({
33789
35027
  summary: "Save the path of a Chromium browser the search missed, after checking that it answers --version as Chromium. Clears a launch-failed skip.",
33790
35028
  args: [{ name: "path", required: true }],
33791
35029
  async run(ctx, { args }) {
33792
- const browserPath = path20.resolve(ctx.cwd, args[0]);
35030
+ const browserPath = path22.resolve(ctx.cwd, args[0]);
33793
35031
  await checkNamedBrowser(browserPath, "Give the path of a Chromium browser's program.");
33794
35032
  const version2 = (ctx.platform === "win32" ? await fileVersion(browserPath) : null) ?? (await askVersion(browserPath)).version;
33795
35033
  if (!version2) {
@@ -33865,6 +35103,93 @@ var init_commands = __esm({
33865
35103
  }
33866
35104
  });
33867
35105
 
35106
+ // src/lib/app-skills.js
35107
+ import { access, readdir, rm } from "node:fs/promises";
35108
+ import path23 from "node:path";
35109
+ function appSkillDirsOf(home, env) {
35110
+ const dirs = [
35111
+ path23.join(home, ".claude", "skills"),
35112
+ path23.join(home, ".agents", "skills"),
35113
+ path23.join(home, ".cursor", "skills"),
35114
+ path23.join(home, ".copilot", "skills"),
35115
+ path23.join(home, ".gemini", "skills"),
35116
+ path23.join(home, ".gemini", "config", "skills")
35117
+ ];
35118
+ if (env.CLAUDE_CONFIG_DIR) dirs.push(path23.join(path23.resolve(env.CLAUDE_CONFIG_DIR), "skills"));
35119
+ return [...new Set(dirs)];
35120
+ }
35121
+ async function removeAppSkillsOnce(ctx) {
35122
+ if (ctx.appSkillDirs.length === 0) return;
35123
+ const record2 = storePaths(ctx.home).appSkillsRemoved;
35124
+ try {
35125
+ await access(record2);
35126
+ return;
35127
+ } catch {
35128
+ }
35129
+ if (!await removeAppSkills(ctx.appSkillDirs)) return;
35130
+ try {
35131
+ await ensureDir(ctx.home);
35132
+ await writeFileAtomic(record2, `${new Date(ctx.now()).toISOString()}
35133
+ `);
35134
+ } catch {
35135
+ }
35136
+ }
35137
+ async function removeAppSkills(dirs) {
35138
+ const done = await Promise.all(
35139
+ dirs.map(async (dir) => {
35140
+ let names;
35141
+ try {
35142
+ names = await readdir(dir);
35143
+ } catch (error2) {
35144
+ return isAbsent(error2);
35145
+ }
35146
+ const removed = await Promise.all(
35147
+ names.filter((name) => APP_SKILL_NAMES.has(name)).map((name) => removeIfApps(path23.join(dir, name)))
35148
+ );
35149
+ return removed.every(Boolean);
35150
+ })
35151
+ );
35152
+ return done.every(Boolean);
35153
+ }
35154
+ async function removeIfApps(folder) {
35155
+ try {
35156
+ await access(path23.join(folder, APP_MARKER));
35157
+ } catch (error2) {
35158
+ return isAbsent(error2);
35159
+ }
35160
+ return rm(folder, { recursive: true, force: true }).then(
35161
+ () => true,
35162
+ () => false
35163
+ );
35164
+ }
35165
+ function isAbsent(error2) {
35166
+ return isErrno(error2, "ENOENT") || isErrno(error2, "ENOTDIR");
35167
+ }
35168
+ var APP_SKILL_NAMES, APP_MARKER;
35169
+ var init_app_skills = __esm({
35170
+ "src/lib/app-skills.js"() {
35171
+ "use strict";
35172
+ init_define_KOMBAI_TELEMETRY();
35173
+ init_fsx();
35174
+ init_store();
35175
+ APP_SKILL_NAMES = /* @__PURE__ */ new Set([
35176
+ "code-kombai-design",
35177
+ "code-with-kombai",
35178
+ "describe-kombai-canvas",
35179
+ "design-with-kombai",
35180
+ "detect-design-system-with-kombai",
35181
+ "improve-ui-with-kombai",
35182
+ "kombai-faq",
35183
+ "kombai-status",
35184
+ "report-to-kombai",
35185
+ "review-ui-with-kombai",
35186
+ "diagnose-kombai",
35187
+ "open-in-kombai"
35188
+ ]);
35189
+ APP_MARKER = ".kombai-skill";
35190
+ }
35191
+ });
35192
+
33868
35193
  // src/lib/args.js
33869
35194
  function parseArgv(argv, commands) {
33870
35195
  const pretty = argv.includes("--pretty");
@@ -34280,14 +35605,14 @@ var init_telemetry = __esm({
34280
35605
  // src/lib/context.js
34281
35606
  import { randomUUID as randomUUID4 } from "node:crypto";
34282
35607
  import os4 from "node:os";
34283
- import path21 from "node:path";
35608
+ import path24 from "node:path";
34284
35609
  function createContext(overrides = {}) {
34285
35610
  const platform2 = overrides.platform ?? process.platform;
34286
35611
  const stdout = overrides.stdout ?? process.stdout;
34287
35612
  const ctx = {
34288
35613
  stdout,
34289
35614
  stderr: process.stderr,
34290
- home: path21.join(os4.homedir(), ".kombai", "cli"),
35615
+ home: path24.join(os4.homedir(), ".kombai", "cli"),
34291
35616
  cwd: process.cwd(),
34292
35617
  fetch: globalThis.fetch,
34293
35618
  now: Date.now,
@@ -34309,6 +35634,7 @@ function createContext(overrides = {}) {
34309
35634
  sandbox: sandboxOf(process.env),
34310
35635
  claudeDesktop: process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop",
34311
35636
  changeSent: false,
35637
+ appSkillDirs: appSkillDirsOf(os4.homedir(), process.env),
34312
35638
  ...overrides
34313
35639
  };
34314
35640
  return ctx;
@@ -34317,6 +35643,7 @@ var init_context = __esm({
34317
35643
  "src/lib/context.js"() {
34318
35644
  "use strict";
34319
35645
  init_define_KOMBAI_TELEMETRY();
35646
+ init_app_skills();
34320
35647
  init_deadline();
34321
35648
  init_open();
34322
35649
  init_output();
@@ -34333,10 +35660,12 @@ __export(cli_exports, {
34333
35660
  });
34334
35661
  async function run(argv, overrides = {}) {
34335
35662
  const ctx = createContext(overrides);
35663
+ const appSkills = removeAppSkillsOnce(ctx);
34336
35664
  ctx.pretty = argv.includes("--pretty");
34337
35665
  const started = ctx.now();
34338
35666
  const ran = { command: null, help: false, wasGuest: await guestBefore(ctx) };
34339
35667
  const exit = await execute(ctx, argv, ran);
35668
+ await appSkills;
34340
35669
  await sendTelemetry(ctx, { ...ran, exit, ms: ctx.now() - started });
34341
35670
  return exit;
34342
35671
  }
@@ -34424,6 +35753,7 @@ var init_cli = __esm({
34424
35753
  init_define_KOMBAI_TELEMETRY();
34425
35754
  init_commands();
34426
35755
  init_skill();
35756
+ init_app_skills();
34427
35757
  init_args();
34428
35758
  init_context();
34429
35759
  init_output();