cladogram 0.5.2 → 0.5.4

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 (51) hide show
  1. package/README.md +30 -2
  2. package/bin/clado.js +55 -3
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +26 -0
  6. package/package.json +8 -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 +146 -0
  13. package/plugins/directory/style.css +48 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +46 -0
  16. package/skills/clado/SKILL.md +31 -17
  17. package/src/html/app-css.js +11 -42
  18. package/src/html/canvas-chain.js +5 -6
  19. package/src/html/canvas-focus.js +3 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +37 -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 +176 -0
  26. package/src/html/plugin-ui.js +45 -0
  27. package/src/html/runtime-api.js +47 -0
  28. package/src/html/runtime.js +15 -12
  29. package/src/server/agent.js +222 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +72 -11
  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 +3 -6
  36. package/src/server/assets/library.html +2 -12
  37. package/src/server/assets/library.js +280 -44
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +5 -2
  40. package/src/server/mcp.js +44 -19
  41. package/src/server/plugin-capabilities.js +172 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +157 -12
  45. package/src/skill/targets.js +1 -1
  46. package/src/util/update.js +58 -0
  47. package/src/vendor/html-to-image.min.js +24 -0
  48. package/src/workspace/content.js +3 -2
  49. package/src/workspace/service.js +81 -21
  50. package/src/workspace/tree.js +38 -0
  51. package/src/server/assets/tree.js +0 -26
@@ -0,0 +1,176 @@
1
+ :root {
2
+ --clado-ui-text: #191919;
3
+ --clado-ui-muted: #565656;
4
+ --clado-ui-accent: #252525;
5
+ --clado-ui-surface: rgb(252 252 252 / .04);
6
+ --clado-ui-panel-surface: rgb(250 250 250 / .13);
7
+ --clado-ui-well: rgb(231 231 231 / .46);
8
+ --clado-ui-solid: #f8f8f8;
9
+ --clado-ui-edge: #17171724;
10
+ --clado-ui-active: #e9e9e9;
11
+ --clado-ui-highlight: rgb(255 255 255 / .34);
12
+ --clado-ui-rim: rgb(93 93 93 / .08);
13
+ --clado-ui-shadow: 0 3px 12px rgb(21 21 21 / .10), 0 1px 3px rgb(21 21 21 / .06);
14
+ --clado-ui-glass-outline: rgb(100 100 100 / .17);
15
+ --clado-ui-glass-shadow: 0 5px 22px rgb(21 21 21 / .09);
16
+ --clado-ui-control-blur: 14px;
17
+ --clado-ui-panel-blur: 18px;
18
+ --clado-ui-radius: 16px;
19
+ --clado-ui-gap: 8px;
20
+ }
21
+ :root[data-theme="dark"] {
22
+ color-scheme: dark;
23
+ --clado-ui-text: #f3f3f3;
24
+ --clado-ui-muted: #b4b4b4;
25
+ --clado-ui-accent: #ededed;
26
+ --clado-ui-surface: rgb(33 33 33 / .38);
27
+ --clado-ui-panel-surface: rgb(30 30 30 / .68);
28
+ --clado-ui-well: rgb(128 128 128 / .16);
29
+ --clado-ui-solid: #292929;
30
+ --clado-ui-edge: #ffffff2a;
31
+ --clado-ui-active: #424242;
32
+ --clado-ui-highlight: #ffffff23;
33
+ --clado-ui-rim: #ffffff23;
34
+ --clado-ui-shadow: 0 8px 26px #0005, 0 2px 6px #0003;
35
+ --clado-ui-glass-outline: rgb(180 180 180 / .23);
36
+ --clado-ui-glass-shadow: 0 6px 24px #0005;
37
+ --clado-ui-control-blur: 14px;
38
+ --clado-ui-panel-blur: 30px;
39
+ }
40
+ .clado-plugin-slot {
41
+ position: fixed;
42
+ display: flex;
43
+ gap: var(--clado-ui-gap);
44
+ z-index: 18;
45
+ font: 13px/1.35 system-ui, sans-serif;
46
+ pointer-events: none;
47
+ }
48
+ .clado-plugin-slot[hidden], .clado-plugin-slot [hidden] { display: none !important; }
49
+ .clado-plugin-slot > * { pointer-events: auto; }
50
+ .clado-plugin-slot[data-slot="top-left"] { top: 14px; left: 16px; max-width: calc(100vw - 250px); flex-direction: column; align-items: start; }
51
+ .clado-plugin-slot[data-slot="top-right"] { top: 14px; right: 16px; flex-direction: column; align-items: end; }
52
+ .clado-plugin-slot[data-slot="bottom-left"] { bottom: 16px; left: 16px; align-items: end; }
53
+ .clado-plugin-slot[data-slot="bottom-right"] { bottom: 16px; right: 16px; flex-direction: column-reverse; align-items: end; }
54
+ :where(.clado-ui-glass) {
55
+ position: relative;
56
+ z-index: 0;
57
+ }
58
+ .clado-ui-glass {
59
+ --clado-ui-glass-fill: var(--clado-ui-surface);
60
+ --clado-ui-glass-blur: var(--clado-ui-control-blur);
61
+ --clado-ui-glass-feather: 3px;
62
+ color: var(--clado-ui-text);
63
+ background: var(--clado-ui-solid);
64
+ border: 1px solid var(--clado-ui-edge);
65
+ border-radius: var(--clado-ui-radius);
66
+ box-shadow: var(--clado-ui-shadow);
67
+ }
68
+ .clado-ui-glass.clado-ui-glass-panel {
69
+ --clado-ui-glass-fill: var(--clado-ui-panel-surface);
70
+ --clado-ui-glass-blur: var(--clado-ui-panel-blur);
71
+ --clado-ui-glass-feather: 5px;
72
+ }
73
+ .clado-ui-button {
74
+ appearance: none;
75
+ border: 1px solid transparent;
76
+ background: transparent;
77
+ color: var(--clado-ui-muted);
78
+ border-radius: 10px;
79
+ font: inherit;
80
+ line-height: 1.15;
81
+ min-height: 32px;
82
+ padding: 5px 10px;
83
+ cursor: pointer;
84
+ white-space: nowrap;
85
+ }
86
+ .clado-ui-button:where(:hover:not(:disabled), [aria-pressed="true"], [aria-expanded="true"], [aria-current="page"], .clado-ui-button-primary) {
87
+ color: var(--clado-ui-accent);
88
+ background: var(--clado-ui-active);
89
+ }
90
+ .clado-ui-button:focus-visible { outline: 2px solid var(--clado-ui-accent); outline-offset: 2px; }
91
+ .clado-ui-button:disabled { opacity: .5; cursor: default; }
92
+ .clado-ui-dialog {
93
+ color-scheme: light;
94
+ --clado-ui-text: #191919;
95
+ --clado-ui-muted: #565656;
96
+ --clado-ui-accent: #252525;
97
+ --clado-ui-edge: #17171724;
98
+ --clado-ui-active: #e9e9e9;
99
+ --ink: var(--clado-ui-text);
100
+ --muted: var(--clado-ui-muted);
101
+ --line: #e3e3e3;
102
+ color: var(--clado-ui-text);
103
+ background: #fff;
104
+ border: 1px solid #e3e3e3;
105
+ border-radius: var(--clado-ui-radius);
106
+ box-shadow: 0 10px 36px rgb(21 21 21 / .14);
107
+ }
108
+ .clado-ui-dialog::backdrop { background: transparent; }
109
+ .clado-ui-glass.clado-ui-button {
110
+ background-color: var(--clado-ui-solid);
111
+ border-color: var(--clado-ui-edge);
112
+ }
113
+ .clado-ui-glass.clado-ui-button:where(:hover:not(:disabled), [aria-expanded="true"], [aria-pressed="true"], [aria-current="page"], .clado-ui-button-primary) {
114
+ background-color: var(--clado-ui-active);
115
+ }
116
+ @supports (backdrop-filter: blur(1px)) {
117
+ @media (prefers-reduced-transparency: no-preference) {
118
+ .clado-ui-glass {
119
+ background: transparent;
120
+ border-color: var(--clado-ui-glass-outline);
121
+ box-shadow: var(--clado-ui-glass-shadow);
122
+ }
123
+ .clado-ui-glass::before {
124
+ content: "";
125
+ position: absolute;
126
+ z-index: -1;
127
+ inset: 0;
128
+ border-radius: inherit;
129
+ pointer-events: none;
130
+ background: var(--clado-ui-glass-fill);
131
+ backdrop-filter: blur(var(--clado-ui-glass-blur)) saturate(145%);
132
+ /* Retain enough blur at the edge to keep text behind the glass indistinct. */
133
+ mask-image:
134
+ linear-gradient(to right, rgb(0 0 0 / .95), #000 var(--clado-ui-glass-feather), #000 calc(100% - var(--clado-ui-glass-feather)), rgb(0 0 0 / .95)),
135
+ linear-gradient(to bottom, rgb(0 0 0 / .95), #000 var(--clado-ui-glass-feather), #000 calc(100% - var(--clado-ui-glass-feather)), rgb(0 0 0 / .95));
136
+ mask-composite: intersect;
137
+ }
138
+ .clado-ui-button, .clado-ui-glass.clado-ui-button {
139
+ --clado-ui-button-tint: 4%;
140
+ --clado-ui-button-outline: color-mix(in srgb, var(--clado-ui-edge) 36%, transparent);
141
+ background: color-mix(in srgb, var(--clado-ui-accent) var(--clado-ui-button-tint), transparent) padding-box;
142
+ border-color: var(--clado-ui-button-outline);
143
+ }
144
+ .clado-ui-button:hover:where(:not(:disabled)) {
145
+ --clado-ui-button-tint: 8%;
146
+ }
147
+ .clado-ui-button:is([aria-expanded="true"], [aria-pressed="true"], [aria-current="page"], .clado-ui-button-primary) {
148
+ --clado-ui-button-tint: 12%;
149
+ --clado-ui-button-outline: color-mix(in srgb, var(--clado-ui-accent) 16%, transparent);
150
+ }
151
+ .clado-ui-glass.clado-ui-button {
152
+ border-color: var(--clado-ui-glass-outline);
153
+ }
154
+ @supports (mask-composite: exclude) {
155
+ /* Keep the highlights on a thin rim so a white canvas does not become a white fill. */
156
+ .clado-ui-glass::after {
157
+ content: "";
158
+ position: absolute;
159
+ z-index: 1;
160
+ inset: -1px;
161
+ padding: 1px;
162
+ border-radius: inherit;
163
+ pointer-events: none;
164
+ background: linear-gradient(146deg, var(--clado-ui-highlight), transparent 32% 58%, var(--clado-ui-rim));
165
+ mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
166
+ mask-composite: exclude;
167
+ }
168
+ }
169
+ }
170
+ }
171
+ @media (max-width: 460px) {
172
+ .clado-plugin-slot[data-slot="top-left"] { top: 10px; left: 10px; max-width: calc(100vw - 207px); }
173
+ .clado-plugin-slot[data-slot="top-right"] { top: 10px; right: 10px; }
174
+ .clado-plugin-slot[data-slot="bottom-left"] { bottom: 10px; left: 10px; }
175
+ .clado-plugin-slot[data-slot="bottom-right"] { bottom: 10px; right: 10px; }
176
+ }
@@ -0,0 +1,45 @@
1
+ (() => {
2
+ function createHost(bridge, isEnabled = () => true) {
3
+ const slots = new Map();
4
+ let hidden = false;
5
+ return {
6
+ capabilities(pluginId, mountId) {
7
+ if (!bridge || !isEnabled(pluginId)) return undefined;
8
+ const identity = { pluginId, mountId };
9
+ return {
10
+ provide: invoke => bridge.provide(identity, invoke),
11
+ list: query => bridge.list(identity, query),
12
+ call: (to, input) => bridge.call(identity, to, input),
13
+ };
14
+ },
15
+ mount(slot, element, pluginId) {
16
+ if (!isEnabled(pluginId)) return () => {};
17
+ if (!slots.has(slot)) {
18
+ const region = document.createElement('div');
19
+ region.className = 'clado-plugin-slot';
20
+ region.dataset.slot = slot;
21
+ region.hidden = hidden;
22
+ slots.set(slot, region);
23
+ document.body.append(region);
24
+ }
25
+ const region = slots.get(slot);
26
+ element.dataset.pluginId = pluginId;
27
+ region.append(element);
28
+ return () => {
29
+ element.remove();
30
+ if (!region.childElementCount) {
31
+ region.remove();
32
+ slots.delete(slot);
33
+ }
34
+ };
35
+ },
36
+ setHidden(next) {
37
+ if (hidden === next) return;
38
+ hidden = next;
39
+ for (const slot of slots.values()) slot.hidden = hidden;
40
+ },
41
+ };
42
+ }
43
+
44
+ window.CladoPluginUI = { createHost };
45
+ })();
@@ -3,7 +3,54 @@
3
3
  setMode: setMode, setTheme: setTheme, clearFocus: clearLit,
4
4
  focusPath: focusPath,
5
5
  isChainOpen: canvasChainIsOpen,
6
+ isLensOpen: function () { return $('#lens').classList.contains('open'); },
7
+ isFocused: function () { return !!canvasFocusId; },
6
8
  contentPath: function (id) { var r = canvasRecords[id]; return r ? r.fullPath : null; },
9
+ selectionPath: function (target) { var r = canvasRecordForTarget(target); return r && r.titlePath || null; },
10
+ hasSelectionPath: function (path) {
11
+ var count = 0;
12
+ for (var record of Object.values(canvasRecords)) if (record.titlePath.length === path.length && path.every(function (part, i) { return part === record.titlePath[i]; })) count++;
13
+ return count === 1;
14
+ },
15
+ readPluginContext: function (fields, selectedPaths, page) {
16
+ var result = {}, mode = document.body.dataset.mode;
17
+ if (fields.includes('document')) {
18
+ result.document = { title: DOC.title, mode: mode, theme: document.documentElement.dataset.theme };
19
+ }
20
+ if (fields.includes('viewport')) {
21
+ var view = $(mode === 'doc' ? '#doc' : '#stage');
22
+ var bounds = view.getBoundingClientRect();
23
+ result.viewport = { width: bounds.width, height: bounds.height, scale: mode === 'doc' ? 1 : scale };
24
+ }
25
+ if (fields.includes('selection')) {
26
+ var byPath = new Map((selectedPaths.length ? Object.values(canvasRecords) : []).map(function (record) {
27
+ return [JSON.stringify(record.titlePath), record];
28
+ }));
29
+ function selectedContent(record) {
30
+ return { nodePath: record.titlePath, markdown: record.markdown,
31
+ children: record.kids.map(function (id) { return selectedContent(canvasRecords[id]); }) };
32
+ }
33
+ result.selection = selectedPaths.map(function (path) { return byPath.get(JSON.stringify(path)); })
34
+ .filter(Boolean).map(selectedContent);
35
+ }
36
+ if (fields.includes('graph')) {
37
+ var records = Object.values(canvasRecords);
38
+ var rows = records.map(function (record) {
39
+ return { kind: 'node', nodePath: record.titlePath,
40
+ parent: record.parent ? canvasRecords[record.parent].titlePath : null };
41
+ });
42
+ records.forEach(function (record) {
43
+ (canvasOut[record.id] || []).forEach(function (target) {
44
+ rows.push({ kind: 'link', from: record.titlePath, to: canvasRecords[target].titlePath });
45
+ });
46
+ });
47
+ result.graph = {
48
+ items: rows.slice(page.offset, page.offset + page.limit),
49
+ nextOffset: page.offset + page.limit < rows.length ? page.offset + page.limit : null
50
+ };
51
+ }
52
+ return result;
53
+ },
7
54
  focusTitle: function (title) {
8
55
  var r = Object.values(canvasRecords).find(function (r) { return r.title === title || r.fullPath === title; });
9
56
  if (!r) return;
@@ -1328,10 +1328,18 @@
1328
1328
  });
1329
1329
  $$('img', inn).forEach(function (i) { i.style.maxWidth = 'none'; });
1330
1330
  $('#lensLabel').textContent = label || '图';
1331
- $('#lens').classList.add('open');
1331
+ if (!$('#lens').classList.contains('open')) {
1332
+ $('#lens').classList.add('open');
1333
+ document.dispatchEvent(new CustomEvent('clado:lens-open'));
1334
+ }
1332
1335
  requestAnimationFrame(lensFit);
1333
1336
  }
1334
- function closeLens() { $('#lens').classList.remove('open'); $('#lensInner').innerHTML = ''; }
1337
+ function closeLens() {
1338
+ if (!$('#lens').classList.contains('open')) return;
1339
+ $('#lens').classList.remove('open');
1340
+ $('#lensInner').innerHTML = '';
1341
+ document.dispatchEvent(new CustomEvent('clado:lens-close'));
1342
+ }
1335
1343
 
1336
1344
  function flash(id) {
1337
1345
  var el = render.card[id];
@@ -1464,14 +1472,13 @@
1464
1472
 
1465
1473
  function setTheme(t, save) {
1466
1474
  document.documentElement.dataset.theme = t;
1467
- $('#theme').textContent = t === 'light' ? '☾︎' : '☀︎';
1468
1475
  if (save !== false) { try { localStorage.setItem('clado-theme', t); } catch (e) {} }
1469
1476
  renderMermaid(true).then(afterMedia);
1477
+ document.dispatchEvent(new CustomEvent('clado:view-state'));
1470
1478
  }
1471
1479
 
1472
1480
  function setMode(m) {
1473
1481
  document.body.dataset.mode = m;
1474
- $$('#modes button').forEach(function (b) { b.classList.toggle('on', b.dataset.mode === m); });
1475
1482
  if (m === 'cards') {
1476
1483
  requestAnimationFrame(function () {
1477
1484
  applyVisibility();
@@ -1493,6 +1500,7 @@
1493
1500
  } else {
1494
1501
  renderMermaid().then(function () { canvasPlaceMediaJumps($('#article')); });
1495
1502
  }
1503
+ document.dispatchEvent(new CustomEvent('clado:view-state'));
1496
1504
  }
1497
1505
 
1498
1506
  (function build() {
@@ -1515,9 +1523,10 @@
1515
1523
  // 主题三级兜底:本机上次切过的 > 编译时写进 <html data-theme> 的 > light。
1516
1524
  // 中间那一级就是 `--theme=dark` 生效的地方 —— 少了它,那个旗标收下来也没人看。
1517
1525
  var t = document.documentElement.dataset.theme || 'light';
1518
- try { t = localStorage.getItem('clado-theme') || t; } catch (e) {}
1526
+ if (!window.__CLADO_WORKSPACE_CHROME__ && !window.__CLADO_CHAIN__) {
1527
+ try { t = localStorage.getItem('clado-theme') || t; } catch (e) {}
1528
+ }
1519
1529
  document.documentElement.dataset.theme = t;
1520
- $('#theme').textContent = t === 'light' ? '☾︎' : '☀︎';
1521
1530
 
1522
1531
  fit();
1523
1532
  applyVisibility(); // 淡出收起来的卡、给端口上灰/蓝,顺带把线画了(此时 scale 已经对了)
@@ -1556,11 +1565,5 @@
1556
1565
  DOC.cards.forEach(function (c) { ro.observe(render.card[c.id]); });
1557
1566
  }
1558
1567
 
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
1568
  })();
1566
1569
  })();
@@ -0,0 +1,222 @@
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, ...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: 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) {
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) {
165
+ if (sessions.size >= 8) throw new DocumentError('Agent 会话过多,请关闭不用的页面后再试。', 429);
166
+ session = { key: input.session };
167
+ sessions.set(input.session, session);
168
+ }
169
+ session.running = true;
170
+ session.cancelled = false;
171
+ clearTimeout(session.idle);
172
+ res.writeHead(200, {
173
+ 'content-type': 'application/x-ndjson; charset=utf-8',
174
+ 'cache-control': 'no-store, no-transform',
175
+ 'x-content-type-options': 'nosniff',
176
+ });
177
+ const emit = event => {
178
+ if (!res.destroyed && !res.writableEnded) res.write(JSON.stringify(event) + '\n');
179
+ };
180
+ session.emit = emit;
181
+ const abort = new Promise((_, reject) => { session.fail = reject; });
182
+ const onDisconnect = () => { if (!res.writableEnded) close(session); };
183
+ res.on('close', onDisconnect);
184
+ const timer = setTimeout(() => close(session, new Error('Agent 响应超时。')), turnMs);
185
+ const run = async () => {
186
+ if (!session.agent) await connect(session);
187
+ if (session.cancelled || sessions.get(session.key) !== session) return { stopReason: 'cancelled' };
188
+ emit({ type: 'status', text: '正在生成' });
189
+ const prompt = promptBlocks(workspace, input);
190
+ if (!session.started && session.hasMcp) {
191
+ prompt.unshift({ type: 'text', text: '你正在 Clado 对话面板。普通问题直接回答。用户明确要求修改画布时,使用已连接的 ' + mcpName() + ' MCP,传用户消息中的 workspace 绝对路径。文档和节点操作通过 MCP,保持修改范围小。用户要求在画布上打开另一个文件时,用 clado_capabilities 查找并调用 clado.directory/directory.open,并传用户上下文中的 viewId。用户要求查看整图或检查布局时,用 clado_screenshot 并传同一个 viewId。' });
192
+ session.started = true;
193
+ }
194
+ return session.agent.rpc.request('session/prompt', { sessionId: session.id, prompt });
195
+ };
196
+ try {
197
+ emit({ type: 'status', text: session.agent ? '正在发送' : '正在连接 Agent' });
198
+ const result = await Promise.race([run(), abort]);
199
+ emit({ type: 'done', reason: session.cancelled ? 'cancelled' : result.stopReason });
200
+ } catch (error) {
201
+ if (session.cancelled) emit({ type: 'done', reason: 'cancelled' });
202
+ else {
203
+ const message = String(error.message || 'Agent 执行失败。').slice(0, 1200);
204
+ emit({ type: 'error', text: message });
205
+ }
206
+ close(session, error);
207
+ } finally {
208
+ clearTimeout(timer);
209
+ clearTimeout(session.stopTimer);
210
+ session.stopTimer = undefined;
211
+ session.running = false;
212
+ session.emit = session.fail = undefined;
213
+ res.off('close', onDisconnect);
214
+ res.end();
215
+ if (sessions.get(session.key) === session) {
216
+ session.idle = setTimeout(() => close(session), idleMs);
217
+ session.idle.unref();
218
+ }
219
+ }
220
+ }
221
+ return { handle, close: () => { for (const session of sessions.values()) close(session); } };
222
+ }
@@ -0,0 +1,111 @@
1
+ (() => {
2
+ const bootstrap = new URLSearchParams(location.hash.slice(1));
3
+ const ticket = bootstrap.get('ticket');
4
+ const mountId = bootstrap.get('mount');
5
+ const host = parent;
6
+ const pending = new Map();
7
+ let handlers = new Map();
8
+ const encoder = new TextEncoder();
9
+ let port, nextId = 0, maxMessageBytes = 262144;
10
+ function applyTheme(theme) {
11
+ if (theme === 'light' || theme === 'dark') document.documentElement.dataset.theme = theme;
12
+ }
13
+ applyTheme(bootstrap.get('theme'));
14
+
15
+ function request(method, params) {
16
+ const id = String(++nextId);
17
+ const message = JSON.stringify({ jsonrpc: '2.0', id, method, params });
18
+ if (encoder.encode(message).length > maxMessageBytes) return Promise.reject(new Error('插件请求超出大小限制。'));
19
+ const timeout = method === 'clado.call' && params.to?.capability === 'canvas.capture' ? 45000 : 12000;
20
+ return new Promise((resolve, reject) => {
21
+ const timer = setTimeout(() => {
22
+ pending.delete(id);
23
+ reject(Object.assign(new Error('Clado 插件请求超时。'), { code: -32006 }));
24
+ }, timeout);
25
+ pending.set(id, { resolve, reject, timer });
26
+ port.postMessage(message);
27
+ });
28
+ }
29
+ async function invoke(id, call) {
30
+ const key = call.to.capability + '@' + call.to.major;
31
+ let payload;
32
+ try {
33
+ const handler = handlers.get(key);
34
+ if (!handler) throw new Error('这个挂载未实现能力 ' + key);
35
+ payload = { result: await handler(call.input, { from: call.from, to: call.to, scope: call.scope }) };
36
+ } catch (error) {
37
+ payload = { error: { code: -32000, message: String(error?.message || '插件执行失败。').slice(0, 500) } };
38
+ }
39
+ try {
40
+ const reply = JSON.stringify({ jsonrpc: '2.0', id, ...payload });
41
+ if (encoder.encode(reply).length > maxMessageBytes) throw new Error();
42
+ port.postMessage(reply);
43
+ } catch {
44
+ port.postMessage(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32009, message: '能力响应无法序列化或超出大小限制。' } }));
45
+ }
46
+ }
47
+ function connect() {
48
+ return new Promise((resolve, reject) => {
49
+ if (host === window || !ticket || !mountId) {
50
+ reject(new Error('需要从 Clado 工作区的插件插槽启动。'));
51
+ return;
52
+ }
53
+ const hostOrigin = location.origin;
54
+ const timer = setTimeout(() => {
55
+ removeEventListener('message', receive);
56
+ reject(new Error('Clado 插件连接超时。'));
57
+ }, 5000);
58
+ function receive(event) {
59
+ if (event.source !== host || event.origin !== hostOrigin || event.data?.type !== 'clado-plugin:port' ||
60
+ event.data.ticket !== ticket || event.ports.length !== 1) return;
61
+ removeEventListener('message', receive);
62
+ clearTimeout(timer);
63
+ port = event.ports[0];
64
+ port.onmessage = ({ data }) => {
65
+ const { id, error, result, method, params } = JSON.parse(data);
66
+ if (method === 'clado.ui.theme') { applyTheme(params?.theme); return; }
67
+ if (method === 'clado.invoke') { void invoke(id, params); return; }
68
+ const waiter = pending.get(id);
69
+ if (!waiter) return;
70
+ clearTimeout(waiter.timer);
71
+ pending.delete(id);
72
+ if (error) waiter.reject(Object.assign(new Error(error.message), { code: error.code, data: error.data }));
73
+ else waiter.resolve(result);
74
+ };
75
+ resolve();
76
+ }
77
+ addEventListener('message', receive);
78
+ host.postMessage({ type: 'clado-plugin:connect', ticket }, hostOrigin);
79
+ });
80
+ }
81
+ const ready = (async () => {
82
+ await connect();
83
+ const { protocol, instanceId, scope, grants, limits, settings = {} } = await request('clado.hello', { protocols: ['1.0'], entrypoint: 'ui', ticket });
84
+ maxMessageBytes = limits.maxMessageBytes;
85
+ await request('clado.register', { entrypoint: 'ui', capabilities: [], events: [], mounts: [mountId] });
86
+ return {
87
+ protocol, instanceId, mountId, grants, scope, settings,
88
+ async getContext(fields, page = {}) {
89
+ const { output } = await request('clado.call', {
90
+ to: { pluginId: 'clado.host', capability: 'canvas.context.get', major: 1 },
91
+ scope, input: { ...page, fields },
92
+ });
93
+ return output;
94
+ },
95
+ async provide(capabilities) {
96
+ if (handlers.size) throw new Error('当前挂载已注册能力。');
97
+ const entries = Object.entries(capabilities);
98
+ if (!entries.length || entries.some(([, handler]) => typeof handler !== 'function')) throw new Error('每个能力都需要一个处理函数。');
99
+ handlers = new Map(entries);
100
+ try { return await request('clado.capabilities.register', { capabilities: [...handlers.keys()], scope }); }
101
+ catch (error) { handlers.clear(); throw error; }
102
+ },
103
+ async listCapabilities(query = {}) {
104
+ const { views } = await request('clado.capabilities.list', { query, scope });
105
+ return views[0]?.capabilities || [];
106
+ },
107
+ call(to, input) { return request('clado.call', { to, scope, input }); },
108
+ };
109
+ })();
110
+ window.CladoPlugin = { ready };
111
+ })();