cladogram 0.5.3 → 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 (46) hide show
  1. package/README.md +19 -0
  2. package/bin/clado.js +13 -2
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +7 -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 +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 +4 -0
  17. package/src/html/app-css.js +9 -40
  18. package/src/html/canvas-chain.js +5 -6
  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 +176 -0
  26. package/src/html/plugin-ui.js +45 -0
  27. package/src/html/runtime-api.js +41 -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 +12 -9
  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 +227 -44
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +5 -2
  40. package/src/server/mcp.js +29 -6
  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 +127 -11
  45. package/src/vendor/html-to-image.min.js +24 -0
  46. package/src/server/assets/tree.js +0 -26
@@ -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
+ })();
@@ -4,9 +4,6 @@
4
4
  let designKey = '', cardsInitialized = false, deferredDisplay = null, deferredDesign = null;
5
5
  const chainOpen = () => !!runtime.isChainOpen?.();
6
6
  const post = (type, detail = {}) => parent.postMessage({ type: 'clado-library:' + type, file, ...detail }, '*');
7
- const labels = { mindmap: '脑图', cards: '卡片', doc: '文档' };
8
- const modes = document.querySelector('#modes');
9
- ['mindmap','cards','doc'].forEach(mode => { const button = modes.querySelector('[data-mode="' + mode + '"]'); button.textContent = labels[mode]; modes.append(button); });
10
7
  document.addEventListener('pointerdown', () => post('dismiss-directory'), true);
11
8
  document.addEventListener('keydown', event => { if (event.key === 'Escape') post('dismiss-directory'); });
12
9
  if (!window.__CLADO_OFFLINE__ && window.__CLADO_FILE_VERSION__) {
@@ -115,8 +112,14 @@
115
112
  let targetFile; try { targetFile = decodeURIComponent(target.pathname.slice('/documents/'.length)); } catch { return; }
116
113
  post('open', { target: targetFile, anchor: parts.slice(1).join('#') });
117
114
  }, true);
118
- modes.addEventListener('click', async event => { if (!event.target.closest('button')) return; await settle(); post('mode', { mode: document.body.dataset.mode }); });
119
- document.querySelector('#theme').addEventListener('click', () => post('theme', { theme: document.documentElement.dataset.theme }));
115
+ document.addEventListener('clado:view-state', () => post('view-state'));
116
+ document.addEventListener('clado:lens-open', () => post('lens-modal', { value: true }));
117
+ document.addEventListener('clado:lens-close', () => post('lens-modal', { value: false }));
118
+ async function setMode(mode) {
119
+ if (chainOpen()) return;
120
+ runtime.setMode(mode);
121
+ await settle();
122
+ }
120
123
  function setDesign(design) {
121
124
  if (chainOpen()) { deferredDesign=design;return; }
122
125
  const key = JSON.stringify(design); if (key === designKey) return; designKey = key;
@@ -137,16 +140,16 @@
137
140
  if(event.source!==parent || event.data?.type!=='clado-workspace:display')return;
138
141
  if (runtime.isChainOpen?.()) { deferredDisplay=event.data;return; }
139
142
  const {mode,theme,anchor}=event.data;
140
- if(['doc','cards','mindmap'].includes(mode))runtime.setMode(mode);
143
+ if(['doc','cards','mindmap'].includes(mode)) runtime.setMode(mode);
141
144
  if(['light','dark'].includes(theme))runtime.setTheme(theme,false);
142
145
  await settle();
143
146
  if(anchor) { let title=anchor;try{title=decodeURIComponent(anchor);}catch{}runtime.focusTitle(title); }
144
- post('mode',{mode:document.body.dataset.mode});
147
+ post('view-state');
145
148
  });
146
- window.CladoPrototype = { setDesign, isChainOpen: chainOpen, fit: () => { if(!chainOpen())runtime.refresh(); }, closeLens: runtime.closeLens, captureView: runtime.captureView, restoreView: runtime.restoreView };
149
+ window.CladoPrototype = { setDesign, setMode, isChainOpen: chainOpen, fit: () => { if(!chainOpen())runtime.refresh(); }, closeLens: runtime.closeLens, captureView: runtime.captureView, restoreView: runtime.restoreView };
147
150
  let resizeTimer; addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { if (!chainOpen() && document.body.dataset.mode !== 'doc') runtime.refresh(); }, 120); });
148
151
  const ready = () => post('ready', { mode: document.body.dataset.mode, version: window.__CLADO_FILE_VERSION__ });
149
- settle().then(() => {
152
+ window.CladoPrototype.whenReady = settle().then(() => {
150
153
  let anchor; try { anchor = decodeURIComponent(window.__CLADO_ANCHOR__ || params.get('anchor') || ''); } catch { anchor = ''; }
151
154
  ready();
152
155
  if (anchor) requestAnimationFrame(() => requestAnimationFrame(() => runtime.focusTitle(anchor)));
@@ -0,0 +1,84 @@
1
+ (() => {
2
+ window.CladoCapabilityBridge = () => {
3
+ const viewId = crypto.randomUUID();
4
+ const endpoint = '/library/plugin-bridge?viewId=' + encodeURIComponent(viewId);
5
+ const handlers = new Map();
6
+ const keyOf = ({ pluginId, mountId }) => JSON.stringify([pluginId, mountId]);
7
+ let stream, connected = false;
8
+
9
+ async function send(message, captureId) {
10
+ const response = await fetch(captureId ? endpoint + '&captureId=' + encodeURIComponent(captureId) : endpoint, {
11
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message),
12
+ });
13
+ const result = await response.json();
14
+ if (!response.ok) throw Object.assign(new Error(result.error), { data: result.details });
15
+ return result;
16
+ }
17
+
18
+ async function run(call) {
19
+ const handler = handlers.get(keyOf(call.to))?.invoke;
20
+ let response;
21
+ try {
22
+ if (!handler) throw Object.assign(new Error('插件能力已断开。'), { kind: 'NO_PROVIDER' });
23
+ response = { action: 'result', callId: call.id, output: await handler(call) };
24
+ } catch (cause) {
25
+ response = {
26
+ action: 'error', callId: call.id, kind: cause.kind || 'PROVIDER_ERROR',
27
+ message: String(cause.message || '插件执行失败。').slice(0, 500),
28
+ };
29
+ }
30
+ const captureId = response.action === 'result' && call.to.pluginId === 'clado.host' && call.to.capability === 'canvas.capture'
31
+ ? call.id : undefined;
32
+ try { await send(response, captureId); }
33
+ catch {
34
+ await send({ action: 'error', callId: call.id, kind: 'PROVIDER_ERROR', message: '插件响应无法传回服务。' }).catch(() => {});
35
+ }
36
+ }
37
+
38
+ function connect() {
39
+ stream = new EventSource(endpoint);
40
+ stream.addEventListener('ready', () => {
41
+ connected = true;
42
+ for (const { registration, active } of handlers.values()) {
43
+ if (active) send(registration).catch(error => console.warn('Clado 能力注册失败', error));
44
+ }
45
+ });
46
+ stream.addEventListener('call', event => { void run(JSON.parse(event.data)); });
47
+ stream.addEventListener('error', () => { connected = false; });
48
+ }
49
+ connect();
50
+ addEventListener('pagehide', () => { connected = false; stream.close(); });
51
+ addEventListener('pageshow', event => { if (event.persisted) connect(); });
52
+
53
+ return {
54
+ viewId,
55
+ async provide(identity, invoke) {
56
+ const registration = { action: 'register', ...identity };
57
+ const key = keyOf(identity);
58
+ const entry = { registration, invoke, active: false };
59
+ handlers.set(key, entry);
60
+ try {
61
+ const result = connected ? await send(registration) : await new Promise((resolve, reject) => {
62
+ const pendingStream = stream;
63
+ const timeout = setTimeout(() => {
64
+ pendingStream.removeEventListener('ready', onReady);
65
+ reject(new Error('插件服务连接超时。'));
66
+ }, 5000);
67
+ function onReady() {
68
+ clearTimeout(timeout);
69
+ send(registration).then(resolve, reject);
70
+ }
71
+ pendingStream.addEventListener('ready', onReady, { once: true });
72
+ });
73
+ entry.active = true;
74
+ return result;
75
+ } catch (error) {
76
+ if (handlers.get(key) === entry) handlers.delete(key);
77
+ throw error;
78
+ }
79
+ },
80
+ list(identity, query = {}) { return send({ action: 'list', ...identity, query }); },
81
+ call(identity, to, input) { return send({ action: 'call', ...identity, to, input }); },
82
+ };
83
+ };
84
+ })();
@@ -0,0 +1,39 @@
1
+ .clado-plugin-window {
2
+ min-width: 0;
3
+ border-radius: 12px;
4
+ }
5
+ .clado-plugin-frame {
6
+ display: block;
7
+ border: 0;
8
+ border-radius: inherit;
9
+ }
10
+ .clado-plugin-slot[data-slot="topbar"] {
11
+ top: 68px;
12
+ left: 50%;
13
+ transform: translateX(-50%);
14
+ max-width: 26vw;
15
+ overflow: auto hidden;
16
+ scrollbar-width: none;
17
+ }
18
+ .clado-plugin-slot[data-slot="topbar"] .clado-plugin-window { flex: 0 0 116px; height: 44px; }
19
+ .clado-plugin-slot[data-slot="top-left"] .clado-plugin-window,
20
+ .clado-plugin-slot[data-slot="top-right"] .clado-plugin-window,
21
+ .clado-plugin-slot[data-slot="bottom-right"] .clado-plugin-window { flex: 0 0 44px; height: 44px; width: 84px; }
22
+ .clado-plugin-slot[data-slot="bottombar"] {
23
+ bottom: 16px;
24
+ left: 50%;
25
+ max-width: min(56vw, calc(100vw - 158px));
26
+ transform: translateX(-50%);
27
+ overflow: auto hidden;
28
+ }
29
+ .clado-plugin-slot[data-slot="bottombar"] .clado-plugin-window { flex: 0 0 160px; height: 44px; }
30
+ .clado-plugin-slot[data-slot="sidebar"],
31
+ .clado-plugin-slot[data-slot="canvas-overlay"] { flex-direction: column; overflow: auto; max-height: 40vh; right: 16px; }
32
+ .clado-plugin-slot[data-slot="sidebar"] { top: 72px; width: min(220px, 24vw); }
33
+ .clado-plugin-slot[data-slot="canvas-overlay"] { bottom: 16px; width: min(220px, 22vw); }
34
+ .clado-plugin-slot[data-slot="sidebar"] .clado-plugin-window,
35
+ .clado-plugin-slot[data-slot="canvas-overlay"] .clado-plugin-window { width: 100%; height: 145px; flex: none; }
36
+ .clado-plugin-slot[data-slot="bottom-left"] .clado-plugin-window { width: 148px; height: 42px; }
37
+ @media (max-width: 640px) {
38
+ .clado-plugin-slot[data-slot="topbar"] { top: 64px; max-width: 52vw; }
39
+ }