cladogram 0.5.3 → 0.5.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +25 -6
  2. package/bin/clado.js +17 -6
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +14 -0
  6. package/package.json +7 -1
  7. package/plugins/agent/index.js +181 -0
  8. package/plugins/agent/style.css +105 -0
  9. package/plugins/brand/index.js +262 -0
  10. package/plugins/brand/style.css +162 -0
  11. package/plugins/directory/capabilities.json +27 -0
  12. package/plugins/directory/index.js +201 -0
  13. package/plugins/directory/style.css +59 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +66 -0
  16. package/skills/clado/SKILL.md +19 -15
  17. package/src/html/app-css.js +69 -47
  18. package/src/html/canvas-chain.js +7 -7
  19. package/src/html/canvas-focus.js +2 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +5 -9
  22. package/src/html/canvas-ui.js +35 -27
  23. package/src/html/page.js +11 -37
  24. package/src/html/plugin-assets.js +33 -0
  25. package/src/html/plugin-ui.css +188 -0
  26. package/src/html/plugin-ui.js +51 -0
  27. package/src/html/runtime-api.js +41 -0
  28. package/src/html/runtime.js +164 -87
  29. package/src/server/agent.js +223 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +14 -10
  32. package/src/server/assets/library-plugin-bridge.js +84 -0
  33. package/src/server/assets/library-plugins.css +39 -0
  34. package/src/server/assets/library-plugins.js +200 -0
  35. package/src/server/assets/library.css +8 -6
  36. package/src/server/assets/library.html +3 -13
  37. package/src/server/assets/library.js +280 -47
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +6 -3
  40. package/src/server/mcp.js +40 -17
  41. package/src/server/plugin-capabilities.js +188 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +222 -29
  45. package/src/skill/install.js +1 -1
  46. package/src/skill/targets.js +3 -3
  47. package/src/util/update.js +3 -2
  48. package/src/vendor/html-to-image.min.js +24 -0
  49. package/src/workspace/service.js +21 -13
  50. package/src/workspace/storage.js +88 -20
  51. package/templates/business-flow.mdc +1 -1
  52. package/templates/call-chain.mdc +1 -1
  53. package/templates/data-design.mdc +1 -1
  54. package/src/server/assets/tree.js +0 -26
@@ -529,35 +529,59 @@
529
529
  DOC.cards.forEach(function (c) { if (!indeg[c.id]) sink(c.id); });
530
530
  // 一个根都没有(整张图全是环)时,随便挑一张起头,剩下的照样能排开
531
531
  DOC.cards.forEach(function (c) { if (!walked[c.id]) sink(c.id); });
532
- var kids = {}, focused = typeof canvasVisibleCards !== 'undefined' && canvasVisibleCards;
532
+ var kids = {}, incoming = {}, focused = typeof canvasVisibleCards !== 'undefined' && canvasVisibleCards;
533
533
  DOC.edges.forEach(function (e) {
534
534
  if (!seen[e[0]] || !seen[e[1]] || (!focused && !openEdge[edgeKey(e[0], e[1])])) return;
535
- (kids[e[0]] = kids[e[0]] || []).push(e[1]);
536
- });
537
- /*
538
- * ★ 同一列里的上下顺序,按**边出现的先后**排,不按卡片在文档里的先后。
539
- * 原来直接 `vis.forEach` 走卡片顺序:`订单明细表` 那一段写在文档最前面,
540
- * 它就先被塞进第 2 列、排在最上面 —— 可它明明是从「明细」那一节连出去的,
541
- * 应该排在 `用户表`、`商品表` 后面。用户看到的「订单明细表跑到最上面去了」
542
- * 就是这个。改成先按 DOC.edges 的顺序收,剩下的(没有入边的根)再补。
543
- */
544
- var cols = {}, inCol = {};
545
- DOC.edges.forEach(function (e) {
546
- if (!seen[e[0]] || !seen[e[1]] || (!focused && !openEdge[edgeKey(e[0], e[1])]) || inCol[e[1]]) return;
547
- inCol[e[1]] = 1;
548
- (cols[depth[e[1]]] = cols[depth[e[1]]] || []).push(e[1]);
535
+ var list = kids[e[0]] || (kids[e[0]] = []);
536
+ if (list.indexOf(e[1]) < 0) list.push(e[1]);
537
+ if (depth[e[0]] < depth[e[1]]) {
538
+ var parents = incoming[e[1]] || (incoming[e[1]] = []);
539
+ if (parents.indexOf(e[0]) < 0) parents.push(e[0]);
540
+ }
549
541
  });
550
- vis.forEach(function (id) {
551
- if (inCol[id]) return;
542
+ // 按列自左向右排定列内初始顺序:遵循左侧已排好父卡的上下顺序及父卡内首次引用顺序,避免深层列上下颠倒。
543
+ var cols = {}, docIndex = {};
544
+ vis.forEach(function (id, index) {
545
+ docIndex[id] = index;
552
546
  (cols[depth[id]] = cols[depth[id]] || []).push(id);
553
547
  });
554
- pos = {};
555
548
  var keys = Object.keys(cols).map(Number).sort(function (a, b) { return a - b; });
549
+ var colRank = {};
550
+ keys.forEach(function (d, ki) {
551
+ if (ki > 0) {
552
+ var meta = {};
553
+ cols[d].forEach(function (id) {
554
+ var parents = (incoming[id] || []).filter(function (p) { return p in colRank; });
555
+ if (parents.length) {
556
+ var sum = 0, minRank = Infinity, minRef = Infinity;
557
+ parents.forEach(function (p) {
558
+ sum += colRank[p];
559
+ if (colRank[p] < minRank) {
560
+ minRank = colRank[p];
561
+ minRef = (kids[p] || []).indexOf(id);
562
+ }
563
+ });
564
+ meta[id] = { hasParent: 1, avg: sum / parents.length, minRank: minRank, minRef: minRef < 0 ? 1e9 : minRef };
565
+ } else {
566
+ meta[id] = { hasParent: 0, avg: 1e9, minRank: 1e9, minRef: 1e9 };
567
+ }
568
+ });
569
+ cols[d].sort(function (a, b) {
570
+ var ma = meta[a], mb = meta[b];
571
+ if (ma.hasParent !== mb.hasParent) return mb.hasParent - ma.hasParent;
572
+ if (ma.avg !== mb.avg) return ma.avg - mb.avg;
573
+ if (ma.minRank !== mb.minRank) return ma.minRank - mb.minRank;
574
+ if (ma.minRef !== mb.minRef) return ma.minRef - mb.minRef;
575
+ return docIndex[a] - docIndex[b];
576
+ });
577
+ }
578
+ cols[d].forEach(function (id, idx) { colRank[id] = idx; });
579
+ });
580
+ pos = {};
556
581
  /*
557
582
  * ★ 每一列的 x 得按**左边那一列最宽的那张卡**让位。
558
583
  * 卡片会被 Mermaid 图撑宽(最宽到 1500px),原来写死 `PAD + d * (W + COL)` ——
559
- * 一张被撑到 1200 的卡就直接压在右边那一列的卡身上了。这就是「缩放的时候
560
- * 卡片会重叠」的来源(不是只算了一层,是压根没算宽度)。
584
+ * 一张被撑到 1200 的卡就直接压在右边那一列的卡身上了。
561
585
  */
562
586
  var colX = {}, cx = PAD, naturalY = {};
563
587
  keys.forEach(function (d) {
@@ -566,50 +590,83 @@
566
590
  cols[d].forEach(function (id) { wmax = Math.max(wmax, render.card[id].offsetWidth || W); });
567
591
  cx += wmax + COL;
568
592
  });
593
+ // 统一按左上角蓝色竖条中心(y + 47px)对齐:
594
+ // 因为每张卡的蓝色竖条距离卡片顶部都是固定偏移,父卡蓝条对齐子卡蓝条中点即 parent.y = (minChildY + maxChildY) / 2。
595
+ // 无子卡的同列兄弟不再写死到 PAD,而是就近紧贴相邻已定位兄弟,避免长分支把上方叶卡甩飞。
569
596
  keys.slice().reverse().forEach(function (d) {
570
597
  var col = cols[d].map(function (id) {
571
598
  var h = render.card[id].offsetHeight;
572
- var ks = kids[id] || [], top = Infinity, bot = -Infinity;
599
+ var ks = kids[id] || [], topY = Infinity, botY = -Infinity;
573
600
  ks.forEach(function (q) {
574
- if (!pos[q]) return;
575
- top = Math.min(top, pos[q].y);
576
- bot = Math.max(bot, pos[q].y + render.card[q].offsetHeight);
601
+ if (!pos[q] || depth[q] <= d) return;
602
+ topY = Math.min(topY, pos[q].y);
603
+ botY = Math.max(botY, pos[q].y);
577
604
  });
578
- var want = isFinite(top) ? (top + bot) / 2 - h / 2 : PAD;
579
- naturalY[id] = want;
580
- return { id: id, h: h, want: want };
605
+ var hasWant = isFinite(topY);
606
+ var want = hasWant ? (topY + botY) / 2 : null;
607
+ if (hasWant) naturalY[id] = want;
608
+ return { id: id, h: h, hasWant: hasWant, want: want, y: 0 };
581
609
  });
582
- // 后代的位置只影响纵向对齐。同一父卡的子卡始终按正文首次引用的顺序排列。
583
- var prev = null;
610
+ var firstAnchored = col.findIndex(function (it) { return it.hasWant; });
611
+ if (firstAnchored < 0) {
612
+ var cursor = PAD;
613
+ col.forEach(function (it) {
614
+ it.y = cursor;
615
+ cursor += it.h + ROW;
616
+ });
617
+ } else {
618
+ // 先为有子卡的节点从上到下分配不重叠位置(为中间夹着的无子卡兄弟预留足够高度),
619
+ // 再把首段无子卡兄弟贴紧在首个有子卡节点上方、中间与尾段无子卡兄弟紧贴在上方兄弟下方。
620
+ var prevAnchor = -1;
621
+ for (var i = 0; i < col.length; i++) {
622
+ if (!col[i].hasWant) continue;
623
+ var y = col[i].want;
624
+ if (prevAnchor >= 0) {
625
+ var minY = col[prevAnchor].y + col[prevAnchor].h + ROW;
626
+ for (var m = prevAnchor + 1; m < i; m++) minY += col[m].h + ROW;
627
+ if (y < minY) y = minY;
628
+ }
629
+ col[i].y = y;
630
+ if (prevAnchor >= 0) {
631
+ var cur = col[prevAnchor].y + col[prevAnchor].h + ROW;
632
+ for (var m2 = prevAnchor + 1; m2 < i; m2++) {
633
+ col[m2].y = cur;
634
+ cur += col[m2].h + ROW;
635
+ }
636
+ }
637
+ prevAnchor = i;
638
+ }
639
+ // 首段无子卡节点向上紧贴首个已定位兄弟,不再飞到顶部 PAD。
640
+ for (var k = firstAnchored - 1; k >= 0; k--) {
641
+ col[k].y = col[k + 1].y - col[k].h - ROW;
642
+ }
643
+ // 尾段无子卡节点向下紧贴最后一个已定位兄弟。
644
+ for (var t = prevAnchor + 1; t < col.length; t++) {
645
+ col[t].y = col[t - 1].y + col[t - 1].h + ROW;
646
+ }
647
+ }
584
648
  col.forEach(function (it) {
585
- // 先不夹到 PAD:父亲比儿子们高一大截时「居中」是要往负数走的,
586
- // 夹住就退化成「跟第一个儿子齐平」——正好是这次要修的那个毛病。
587
- // 越界统一留到最后整体下移。
588
- var y = it.want;
589
- if (prev && y < prev.y + prev.h + ROW) y = prev.y + prev.h + ROW;
590
- pos[it.id] = { x: colX[d], y: y };
591
- prev = { y: y, h: it.h };
649
+ pos[it.id] = { x: colX[d], y: it.y };
592
650
  });
593
651
  });
594
- // 左列卡片互相让位后的位移要传给右列分支;共享子卡取所有父卡位移的平均值。
652
+ // 左列卡片互相让位后的位移传给右列分支,保序且用同列等距分组消解碰撞。
595
653
  if (!anchor || !prevPos) {
596
- var incoming = {};
597
- Object.keys(kids).forEach(function (parent) {
598
- kids[parent].forEach(function (child) {
599
- if (depth[parent] < depth[child]) (incoming[child] || (incoming[child] = [])).push(parent);
600
- });
601
- });
602
654
  keys.slice(1).forEach(function (d) {
603
- var parentY = {}, desiredY = {};
604
- cols[d].forEach(function (id) {
655
+ var parentY = {}, desiredY = {}, colOrder = {};
656
+ cols[d].forEach(function (id, idx) {
657
+ colOrder[id] = idx;
605
658
  var parents = incoming[id] || [];
606
659
  parentY[id] = parents.length ? parents.reduce(function (sum, parent) { return sum + pos[parent].y; }, 0) / parents.length : pos[id].y;
607
- var shift = parents.length ? parents.reduce(function (sum, parent) { return sum + pos[parent].y - naturalY[parent]; }, 0) / parents.length : 0;
660
+ var shifted = parents.filter(function (parent) { return naturalY[parent] !== undefined; });
661
+ var shift = shifted.length ? shifted.reduce(function (sum, parent) { return sum + (pos[parent].y - naturalY[parent]); }, 0) / shifted.length : 0;
608
662
  desiredY[id] = pos[id].y + shift;
609
663
  });
610
- // 同列先按父卡顺序分组。同组保留引用顺序,相撞时把间距分摊给两边。
664
+ var ordered = cols[d].slice().sort(function (a, b) {
665
+ if (parentY[a] !== parentY[b]) return parentY[a] - parentY[b];
666
+ return colOrder[a] - colOrder[b];
667
+ });
611
668
  var groups = [], offset = 0;
612
- cols[d].slice().sort(function (a, b) { return parentY[a] - parentY[b]; }).forEach(function (id) {
669
+ ordered.forEach(function (id) {
613
670
  groups.push({ cards: [{ id: id, offset: offset }], y: desiredY[id] - offset });
614
671
  offset += render.card[id].offsetHeight + ROW;
615
672
  while (groups.length > 1 && groups[groups.length - 2].y > groups[groups.length - 1].y) {
@@ -625,9 +682,8 @@
625
682
  }
626
683
  /*
627
684
  * ★ 收起 / 展开只动「被点的那张 + 它的**所有后代**」,别的卡一个像素都不挪。
628
- * 做法:先照常全局摆一遍,然后把不在 moved 里的卡片 y 换回快照里的旧值,
629
- * 最后按列把 moved 的卡片往下推开,避开这些钉住的卡。
630
- * (用户的原话:「除了当前节点以及它自己的儿子,其他的节点位置都不动」。)
685
+ * 避让同列固定卡时尊重父卡上下顺序:上方父卡的子卡优先往上让位,下方父卡的子卡优先往下让位,
686
+ * 避免上面的子卡被推到下面调用卡片的下方错位。
631
687
  */
632
688
  var moved = null;
633
689
  if (anchor && prevPos) {
@@ -639,7 +695,7 @@
639
695
  moved[walkId] = 1;
640
696
  (kids[walkId] || []).forEach(function (q) { stack.push(q); });
641
697
  }
642
- // 钉回父卡时整支一起平移,保留可见孩子围绕父卡的居中关系。
698
+ // 钉回父卡时整支一起平移,保留可见孩子围绕父卡蓝条的对齐关系。
643
699
  if (pos[anchor] && prevPos[anchor]) {
644
700
  var dx = prevPos[anchor].x - pos[anchor].x, dy = prevPos[anchor].y - pos[anchor].y;
645
701
  Object.keys(moved).forEach(function (id) {
@@ -650,23 +706,25 @@
650
706
  if (pos[c.id] && !moved[c.id] && prevPos[c.id]) pos[c.id].y = prevPos[c.id].y;
651
707
  if (pos[c.id] && !moved[c.id] && prevPos[c.id]) pos[c.id].x = prevPos[c.id].x;
652
708
  });
653
- /*
654
- * ★ 被点的这张**自己也不许动**。用户原话:「我点的这个标题的这个卡片,它能不动吗?」
655
- * 它虽然在 moved 里(要跟着走一遍好收放后代),但位置得钉死在原地 ——
656
- * 手指点哪儿,那张卡就待在哪儿,只有它右边那一串后代会重摆。
657
- */
658
709
  if (pos[anchor] && prevPos[anchor]) pos[anchor].y = prevPos[anchor].y;
710
+ var anchorY = pos[anchor] ? pos[anchor].y : 0;
659
711
  keys.forEach(function (d) {
660
- var moving = [], pinned = [], blocked = [];
712
+ var moving = [], pinned = [], blocked = [], collidingParents = [];
661
713
  cols[d].forEach(function (id) {
662
714
  if (CARD_PLACEMENTS[id]) pos[id] = Object.assign({}, CARD_PLACEMENTS[id]);
663
715
  (moved[id] && id !== anchor && !CARD_PLACEMENTS[id] ? moving : pinned).push(id);
664
716
  });
665
- // 整组让开固定卡,保持孩子间距;选择离父卡最近的上下空位。
717
+ if (!moving.length) return;
666
718
  moving.forEach(function (id) {
667
719
  pinned.forEach(function (fixed) {
668
- blocked.push({ lo: pos[fixed].y - ROW - pos[id].y - render.card[id].offsetHeight,
669
- hi: pos[fixed].y + render.card[fixed].offsetHeight + ROW - pos[id].y });
720
+ var lo = pos[fixed].y - ROW - pos[id].y - render.card[id].offsetHeight;
721
+ var hi = pos[fixed].y + render.card[fixed].offsetHeight + ROW - pos[id].y;
722
+ blocked.push({ lo: lo, hi: hi });
723
+ if (lo < 0 && hi > 0) {
724
+ var fp = (incoming[fixed] || []).filter(function (p) { return pos[p]; });
725
+ var py = fp.length ? fp.reduce(function (s, p) { return s + pos[p].y; }, 0) / fp.length : pos[fixed].y;
726
+ collidingParents.push(py);
727
+ }
670
728
  });
671
729
  });
672
730
  blocked.sort(function (a, b) { return a.lo - b.lo; });
@@ -677,11 +735,31 @@
677
735
  else intervals.push(range);
678
736
  });
679
737
  var shift = 0;
738
+ var avgPinnedParentY = collidingParents.length
739
+ ? collidingParents.reduce(function (s, y) { return s + y; }, 0) / collidingParents.length
740
+ : null;
680
741
  intervals.forEach(function (range) {
681
- if (range.lo < 0 && range.hi > 0) shift = Math.abs(range.lo) < Math.abs(range.hi) ? range.lo : range.hi;
742
+ if (range.lo < 0 && range.hi > 0) {
743
+ if (avgPinnedParentY !== null && Math.abs(anchorY - avgPinnedParentY) > 1) {
744
+ shift = anchorY < avgPinnedParentY ? range.lo : range.hi;
745
+ } else {
746
+ shift = Math.abs(range.lo) < Math.abs(range.hi) ? range.lo : range.hi;
747
+ }
748
+ }
682
749
  });
683
- // 无限画布允许负坐标,不能把上半组逐张夹到PAD而破坏居中。
684
- moving.forEach(function (id) { pos[id].y += shift; });
750
+ if (shift) {
751
+ // 同列移动组连同其后续列子孙一起平移,保持整支对齐不撕裂。
752
+ var sub = {}, q = moving.slice();
753
+ while (q.length) {
754
+ var cur = q.pop();
755
+ if (sub[cur]) continue;
756
+ sub[cur] = 1;
757
+ (kids[cur] || []).forEach(function (child) {
758
+ if (moved[child] && !CARD_PLACEMENTS[child] && depth[child] > d) q.push(child);
759
+ });
760
+ }
761
+ Object.keys(sub).forEach(function (id) { if (pos[id]) pos[id].y += shift; });
762
+ }
685
763
  });
686
764
  } else {
687
765
  // 整体下移,保证最上面那张卡正好落在 PAD 上(相对关系一个没动)
@@ -690,14 +768,6 @@
690
768
  var shift = isFinite(minY) ? PAD - minY : 0;
691
769
  DOC.cards.forEach(function (c) { if (pos[c.id]) pos[c.id].y += shift; });
692
770
  }
693
- /*
694
- * ★ 最后兜一次底:上面两个分支(整体摆 / 只动那一支)都是**摆的时候**量高度的,
695
- * 而卡片的高度会被异步的东西改(mermaid 渲染、字体加载、图片解码)。
696
- * 实测就是这么重叠的:摆的时候「库存服务」只有 151 高,之后长到 240,
697
- * 同一列下面的「通知服务」就被压住了。
698
- * 这里按**当前实测高度**把每一列从上往下再扫一遍,谁压住谁就往下推。
699
- * 只往下推、不往上提,也不改 x —— 列位置和镜头都不受影响。
700
- */
701
771
  keys.forEach(function (d) {
702
772
  var col = cols[d].map(function (id) { return { id: id, h: render.card[id].offsetHeight }; });
703
773
  col.sort(function (a, b) { return pos[a.id].y - pos[b.id].y; });
@@ -705,8 +775,6 @@
705
775
  col.forEach(function (it) {
706
776
  var y = pos[it.id].y;
707
777
  if (prev && y < prev.y + prev.h + ROW) y = prev.y + prev.h + ROW;
708
- // ★ 只推「这一支」里的卡。钉住的卡一个像素都不许动 ——
709
- // 用户报的「每次点标题,父节点就往下挪一点」就是这里把它推走的。
710
778
  if ((!moved || moved[it.id]) && it.id !== anchor) pos[it.id].y = y;
711
779
  prev = { y: pos[it.id].y, h: it.h };
712
780
  });
@@ -1316,10 +1384,13 @@
1316
1384
  lx = (st.width - w * ls) / 2; ly = (st.height - h * ls) / 2;
1317
1385
  lensApply();
1318
1386
  }
1387
+ var lensSeq = 0;
1319
1388
  function openLens(html, label, kind) {
1389
+ lensSeq++;
1320
1390
  var inn = $('#lensInner');
1321
1391
  inn.innerHTML = kind ? '<div class="markdown-body">' + html + '</div>' : html;
1322
- if (kind) inn.dataset.cap = kind === 'code' ? '2.2' : '3'; else delete inn.dataset.cap;
1392
+ if (kind) { inn.dataset.cap = kind === 'code' ? '2.2' : '3'; inn.dataset.kind = kind; }
1393
+ else { delete inn.dataset.cap; delete inn.dataset.kind; }
1323
1394
  $$('svg', inn).forEach(function (s) {
1324
1395
  var vb = s.viewBox && s.viewBox.baseVal;
1325
1396
  s.removeAttribute('width'); s.removeAttribute('height');
@@ -1328,10 +1399,21 @@
1328
1399
  });
1329
1400
  $$('img', inn).forEach(function (i) { i.style.maxWidth = 'none'; });
1330
1401
  $('#lensLabel').textContent = label || '图';
1331
- $('#lens').classList.add('open');
1402
+ if (!$('#lens').classList.contains('open')) {
1403
+ $('#lens').classList.add('open');
1404
+ document.dispatchEvent(new CustomEvent('clado:lens-open'));
1405
+ }
1332
1406
  requestAnimationFrame(lensFit);
1333
1407
  }
1334
- function closeLens() { $('#lens').classList.remove('open'); $('#lensInner').innerHTML = ''; }
1408
+ function closeLens() {
1409
+ if (!$('#lens').classList.contains('open')) return;
1410
+ var seq = ++lensSeq;
1411
+ $('#lens').classList.remove('open');
1412
+ document.dispatchEvent(new CustomEvent('clado:lens-close'));
1413
+ setTimeout(function () {
1414
+ if (seq === lensSeq && !$('#lens').classList.contains('open')) $('#lensInner').innerHTML = '';
1415
+ }, 180);
1416
+ }
1335
1417
 
1336
1418
  function flash(id) {
1337
1419
  var el = render.card[id];
@@ -1464,14 +1546,13 @@
1464
1546
 
1465
1547
  function setTheme(t, save) {
1466
1548
  document.documentElement.dataset.theme = t;
1467
- $('#theme').textContent = t === 'light' ? '☾︎' : '☀︎';
1468
1549
  if (save !== false) { try { localStorage.setItem('clado-theme', t); } catch (e) {} }
1469
1550
  renderMermaid(true).then(afterMedia);
1551
+ document.dispatchEvent(new CustomEvent('clado:view-state'));
1470
1552
  }
1471
1553
 
1472
1554
  function setMode(m) {
1473
1555
  document.body.dataset.mode = m;
1474
- $$('#modes button').forEach(function (b) { b.classList.toggle('on', b.dataset.mode === m); });
1475
1556
  if (m === 'cards') {
1476
1557
  requestAnimationFrame(function () {
1477
1558
  applyVisibility();
@@ -1493,6 +1574,7 @@
1493
1574
  } else {
1494
1575
  renderMermaid().then(function () { canvasPlaceMediaJumps($('#article')); });
1495
1576
  }
1577
+ document.dispatchEvent(new CustomEvent('clado:view-state'));
1496
1578
  }
1497
1579
 
1498
1580
  (function build() {
@@ -1515,9 +1597,10 @@
1515
1597
  // 主题三级兜底:本机上次切过的 > 编译时写进 <html data-theme> 的 > light。
1516
1598
  // 中间那一级就是 `--theme=dark` 生效的地方 —— 少了它,那个旗标收下来也没人看。
1517
1599
  var t = document.documentElement.dataset.theme || 'light';
1518
- try { t = localStorage.getItem('clado-theme') || t; } catch (e) {}
1600
+ if (!window.__CLADO_WORKSPACE_CHROME__ && !window.__CLADO_CHAIN__) {
1601
+ try { t = localStorage.getItem('clado-theme') || t; } catch (e) {}
1602
+ }
1519
1603
  document.documentElement.dataset.theme = t;
1520
- $('#theme').textContent = t === 'light' ? '☾︎' : '☀︎';
1521
1604
 
1522
1605
  fit();
1523
1606
  applyVisibility(); // 淡出收起来的卡、给端口上灰/蓝,顺带把线画了(此时 scale 已经对了)
@@ -1556,11 +1639,5 @@
1556
1639
  DOC.cards.forEach(function (c) { ro.observe(render.card[c.id]); });
1557
1640
  }
1558
1641
 
1559
- $$('#modes button').forEach(function (b) {
1560
- b.addEventListener('click', function () { setMode(b.dataset.mode); });
1561
- });
1562
- $('#theme').addEventListener('click', function () {
1563
- setTheme(document.documentElement.dataset.theme === 'light' ? 'dark' : 'light');
1564
- });
1565
1642
  })();
1566
1643
  })();
@@ -0,0 +1,223 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { Readable, Writable } from 'node:stream';
3
+ import { client, ndJsonStream, PROTOCOL_VERSION } from '@agentclientprotocol/sdk';
4
+ import { z } from 'zod/v4';
5
+ import { VERSION } from '../util/version.js';
6
+ import { DocumentError } from '../workspace/documents.js';
7
+
8
+ const idleMs = 15 * 60_000;
9
+ const turnMs = 5 * 60_000;
10
+ const sessionId = z.uuid();
11
+ const requestSchema = z.discriminatedUnion('action', [
12
+ z.strictObject({
13
+ action: z.literal('prompt'), session: sessionId, text: z.string().trim().min(1).max(12_000),
14
+ viewId: z.uuid().optional(),
15
+ canvas: z.strictObject({
16
+ file: z.string().min(1).max(1500),
17
+ revision: z.string().regex(/^[a-f0-9]{64}$/),
18
+ selection: z.array(z.array(z.string().min(1).max(500)).min(1).max(6)).max(200),
19
+ }).optional(),
20
+ }),
21
+ z.strictObject({ action: z.enum(['cancel', 'close']), session: sessionId }),
22
+ ]);
23
+
24
+ async function readRequest(req) {
25
+ const chunks = [];
26
+ let bytes = 0;
27
+ for await (const chunk of req) {
28
+ bytes += chunk.length;
29
+ if (bytes > 96 * 1024) throw new DocumentError('发送内容过长。', 413);
30
+ chunks.push(chunk);
31
+ }
32
+ const parsed = requestSchema.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
33
+ if (!parsed.success) throw new DocumentError('Agent 请求参数不合法。', 400);
34
+ return parsed.data;
35
+ }
36
+
37
+ function promptBlocks(workspace, input) {
38
+ const context = {
39
+ workspace,
40
+ ...(input.viewId && { viewId: input.viewId }),
41
+ ...(input.canvas && { file: input.canvas.file, revision: input.canvas.revision, selection: input.canvas.selection }),
42
+ };
43
+ return [
44
+ { type: 'text', text: '以下是 Clado 在用户发送时记录的工作区、标签页和画布选区。workspace、viewId 和 file 是工具参数,selection 是按点选顺序排列的标题路径。' },
45
+ { type: 'text', text: JSON.stringify(context) },
46
+ { type: 'text', text: '用户指令:\n' + input.text },
47
+ ];
48
+ }
49
+
50
+ function startAgent({ workspace, command, args, env, mcpName, emit, closed }) {
51
+ const proc = spawn(command, args, {
52
+ cwd: workspace,
53
+ stdio: ['pipe', 'pipe', 'pipe'],
54
+ windowsHide: true,
55
+ env: { ...process.env, ...env },
56
+ });
57
+ proc.stderr.resume();
58
+ const cladoCalls = new Map();
59
+ proc.on('error', cause => {
60
+ const message = cause.code === 'ENOENT'
61
+ ? '找不到 ACP 启动命令。请安装适配器或在「灵感」插件设置里填写其路径。'
62
+ : '无法启动 ACP 进程。';
63
+ closed(new Error(message));
64
+ });
65
+ proc.on('exit', code => closed(new Error('ACP 进程已退出' + (code ? '(退出码 ' + code + ')' : '') + '。请检查启动命令和登录状态。')));
66
+ const connection = client()
67
+ .onRequest('session/request_permission', ({ params }) => {
68
+ // The send action enables canvas operations on this serve instance.
69
+ // Match the adapter's correlated tool call, never its display text alone.
70
+ const option = params.options.find(option => option.kind === 'allow_once');
71
+ if (option && params._meta?.is_mcp_tool_approval === true &&
72
+ cladoCalls.get(params.toolCall.toolCallId) === params.sessionId) {
73
+ return { outcome: { outcome: 'selected', optionId: option.optionId } };
74
+ }
75
+ emit({ type: 'status', text: '已拒绝额外的本机执行权限' });
76
+ return { outcome: { outcome: 'cancelled' } };
77
+ })
78
+ .onNotification('session/update', ({ params }) => {
79
+ const update = params.update;
80
+ const kind = update.sessionUpdate;
81
+ if (kind === 'agent_message_chunk' && update.content?.type === 'text') {
82
+ emit({ type: 'text', text: update.content.text });
83
+ } else if (kind === 'tool_call' || kind === 'tool_call_update') {
84
+ const title = update.title?.slice(0, 160);
85
+ if (kind === 'tool_call' && title?.startsWith('mcp.' + mcpName + '.clado_')) {
86
+ cladoCalls.set(update.toolCallId, params.sessionId);
87
+ }
88
+ if (update.status === 'completed' || update.status === 'failed') cladoCalls.delete(update.toolCallId);
89
+ emit({ type: 'tool', id: update.toolCallId, title, status: update.status });
90
+ }
91
+ })
92
+ .connect(ndJsonStream(Writable.toWeb(proc.stdin), Readable.toWeb(proc.stdout)));
93
+ connection.closed.then(() => closed(new Error('ACP 已断开。请检查适配器或重新发送。')));
94
+ return {
95
+ rpc: connection.agent,
96
+ dispose() {
97
+ connection.close();
98
+ proc.stdin.destroy();
99
+ if (proc.exitCode === null && proc.signalCode === null) proc.kill();
100
+ },
101
+ };
102
+ }
103
+
104
+ export function createAgentHandler({
105
+ workspace, mcpUrl,
106
+ command = process.env.CLADO_CODEX_ACP_PATH || 'codex-acp',
107
+ args = [],
108
+ resolveLaunch = () => ({ command, args, env: { INITIAL_AGENT_MODE: 'read-only' } }),
109
+ }) {
110
+ const sessions = new Map();
111
+ const mcpName = () => 'clado_canvas_' + new URL(mcpUrl()).port;
112
+ function close(session, error) {
113
+ if (sessions.get(session.key) !== session) return;
114
+ sessions.delete(session.key);
115
+ clearTimeout(session.idle);
116
+ session.fail?.(error || new Error('Agent 会话已关闭。'));
117
+ session.agent?.dispose();
118
+ }
119
+
120
+ async function connect(session) {
121
+ session.agent = startAgent({
122
+ workspace: session.workspace, ...resolveLaunch(), mcpName: mcpName(), emit: event => session.emit?.(event),
123
+ closed: error => close(session, error),
124
+ });
125
+ const { rpc } = session.agent;
126
+ const init = await rpc.request('initialize', {
127
+ protocolVersion: PROTOCOL_VERSION,
128
+ clientInfo: { name: 'clado', title: 'Clado', version: VERSION },
129
+ clientCapabilities: {},
130
+ });
131
+ if (init.protocolVersion !== PROTOCOL_VERSION) throw new Error('当前适配器不支持 Clado 的 ACP 协议版本。');
132
+ session.hasMcp = !!init.agentCapabilities?.mcpCapabilities?.http;
133
+ const result = await rpc.request('session/new', {
134
+ cwd: session.workspace,
135
+ mcpServers: session.hasMcp ? [{ name: mcpName(), type: 'http', url: mcpUrl(), headers: [] }] : [],
136
+ });
137
+ session.id = result.sessionId;
138
+ }
139
+
140
+ async function handle(req, res, targetWorkspace = workspace) {
141
+ const host = req.headers.host || '';
142
+ if (req.method !== 'POST') throw new DocumentError('Agent 只接受 POST 请求。', 405);
143
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) ||
144
+ req.headers.origin !== 'http://' + host ||
145
+ req.headers['content-type']?.split(';')[0] !== 'application/json') {
146
+ throw new DocumentError('Agent 只接受本机同源页面请求。', 403);
147
+ }
148
+ const input = await readRequest(req);
149
+ let session = sessions.get(input.session);
150
+ if (input.action !== 'prompt') {
151
+ if (input.action === 'close') {
152
+ close(session || { key: input.session });
153
+ } else if (session?.running) {
154
+ session.cancelled = true;
155
+ if (session.id) {
156
+ session.agent.rpc.notify('session/cancel', { sessionId: session.id }).catch(error => close(session, error));
157
+ session.stopTimer ||= setTimeout(() => close(session, new Error('Agent 停止超时,会话已关闭。')), 5000);
158
+ } else close(session, new Error('已停止连接。'));
159
+ }
160
+ res.writeHead(204).end();
161
+ return;
162
+ }
163
+ if (session?.running) throw new DocumentError('当前会话还有一条消息在执行。', 409);
164
+ if (session && session.workspace !== targetWorkspace) throw new DocumentError('会话已绑定到另一个工作区,请开启新对话。', 409);
165
+ if (!session) {
166
+ if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
167
+ session = { key: input.session, workspace: targetWorkspace };
168
+ sessions.set(input.session, session);
169
+ }
170
+ session.running = true;
171
+ session.cancelled = false;
172
+ clearTimeout(session.idle);
173
+ res.writeHead(200, {
174
+ 'content-type': 'application/x-ndjson; charset=utf-8',
175
+ 'cache-control': 'no-store, no-transform',
176
+ 'x-content-type-options': 'nosniff',
177
+ });
178
+ const emit = event => {
179
+ if (!res.destroyed && !res.writableEnded) res.write(JSON.stringify(event) + '\n');
180
+ };
181
+ session.emit = emit;
182
+ const abort = new Promise((_, reject) => { session.fail = reject; });
183
+ const onDisconnect = () => { if (!res.writableEnded) close(session); };
184
+ res.on('close', onDisconnect);
185
+ const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
186
+ const run = async () => {
187
+ if (!session.agent) await connect(session);
188
+ if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
189
+ emit({ type: 'status', text: '正在生成' });
190
+ const prompt = promptBlocks(session.workspace, input);
191
+ if (!session.started && session.hasMcp) {
192
+ prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
193
+ session.started = true;
194
+ }
195
+ return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
196
+ };
197
+ try {
198
+ emit({ type: 'status', text: session.agent ? '正在发送' : '正在连接 Agent' });
199
+ const result = await Promise.race([run(), abort]);
200
+ emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
201
+ } catch (error) {
202
+ if (session.cancelled) emit({ type: 'done', reason: 'cancelled' });
203
+ else {
204
+ const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
205
+ emit({ type: 'error', text: message });
206
+ }
207
+ close(session, error);
208
+ } finally {
209
+ clearTimeout(timer);
210
+ clearTimeout(session.stopTimer);
211
+ session.stopTimer = undefined;
212
+ session.running = false;
213
+ session.emit = session.fail = undefined;
214
+ res.off('close', onDisconnect);
215
+ res.end();
216
+ if (sessions.get(session.key) === session) {
217
+ session.idle = setTimeout(() => close(session), idleMs);
218
+ session.idle.unref();
219
+ }
220
+ }
221
+ }
222
+ return { handle, close: () => { for (const session of sessions.values()) close(session); } };
223
+ }