cladogram 0.5.5-beta.7 → 0.5.5-beta.8
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/bin/clado.js +33 -10
- package/docs/release.md +6 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +569 -40
- package/plugins/agent/style.css +152 -10
- package/plugins/brand/index.js +13 -1
- package/plugins/directory/index.js +18 -1
- package/src/agent/providers/index.js +197 -14
- package/src/agent/sessions.js +2 -0
- package/src/html/plugin-ui.css +95 -2
- package/src/server/agent.js +243 -26
- package/src/server/assets/library.js +235 -2
- package/src/server/plugin-settings.js +28 -2
- package/src/server/workspace-hub.js +223 -0
- package/src/server/workspace.js +101 -11
|
@@ -93,6 +93,7 @@
|
|
|
93
93
|
return result;
|
|
94
94
|
},
|
|
95
95
|
} : null,
|
|
96
|
+
openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openWorkspacePicker() : null,
|
|
96
97
|
setTheme: theme => {
|
|
97
98
|
if (modalLocked()) return;
|
|
98
99
|
try { localStorage.setItem('clado-theme', theme); } catch {}
|
|
@@ -121,6 +122,8 @@
|
|
|
121
122
|
openFromCapability,
|
|
122
123
|
workspaceUrl,
|
|
123
124
|
switchWorkspace: id => { location.href = workspaceUrl(id); },
|
|
125
|
+
openWorkspacePicker: config.canSwitchWorkspace && !offline ? () => openWorkspacePicker() : null,
|
|
126
|
+
createCanvas: config.canSwitchWorkspace && !offline ? () => createCanvasFlow() : null,
|
|
124
127
|
refresh: () => scan(true),
|
|
125
128
|
back: () => {
|
|
126
129
|
if (modalLocked()) return;
|
|
@@ -143,6 +146,236 @@
|
|
|
143
146
|
}
|
|
144
147
|
const selectionTab = config.selection ? crypto.randomUUID() : null;
|
|
145
148
|
let aiSelection = null, selectionRequest = Promise.resolve(), pageHidden = false;
|
|
149
|
+
|
|
150
|
+
// ============ 本机工作区中心(选择/浏览/新建工作区 + 新项目首屏启动台) ============
|
|
151
|
+
let wsPickerOverlay = null;
|
|
152
|
+
async function createCanvasFlow(defaultTitle = '') {
|
|
153
|
+
if (!config.canSwitchWorkspace || offline) return;
|
|
154
|
+
const title = defaultTitle || window.prompt('输入新画布标题:', '系统架构概览');
|
|
155
|
+
if (!title || !title.trim()) return;
|
|
156
|
+
try {
|
|
157
|
+
const res = await fetch(withWorkspace('/library/fs-workspaces'), {
|
|
158
|
+
method: 'POST',
|
|
159
|
+
headers: { 'content-type': 'application/json' },
|
|
160
|
+
body: JSON.stringify({ action: 'create_canvas', title: title.trim() }),
|
|
161
|
+
});
|
|
162
|
+
const data = await res.json();
|
|
163
|
+
if (!res.ok) throw new Error(data.error || '创建画布失败');
|
|
164
|
+
pendingOpen = data.file;
|
|
165
|
+
await scan(true);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
directory.showMessage('新建画布失败', err.message || '请稍后重试');
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function applyWorkspaceSwitch(targetPath, { createIfMissing = false, initStarterCanvas = false } = {}) {
|
|
172
|
+
if (!targetPath || !targetPath.trim()) return;
|
|
173
|
+
const res = await fetch('/library/fs-workspaces', {
|
|
174
|
+
method: 'POST',
|
|
175
|
+
headers: { 'content-type': 'application/json' },
|
|
176
|
+
body: JSON.stringify({
|
|
177
|
+
action: 'select',
|
|
178
|
+
path: targetPath.trim(),
|
|
179
|
+
createIfMissing,
|
|
180
|
+
initStarterCanvas,
|
|
181
|
+
}),
|
|
182
|
+
});
|
|
183
|
+
const data = await res.json();
|
|
184
|
+
if (!res.ok) throw new Error(data.error || '切换工作区失败');
|
|
185
|
+
try { sessionStorage.removeItem(storageKey); } catch {}
|
|
186
|
+
location.href = '/';
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function ensureWorkspacePicker() {
|
|
190
|
+
if (wsPickerOverlay || !document.body) return wsPickerOverlay;
|
|
191
|
+
wsPickerOverlay = document.createElement('div');
|
|
192
|
+
wsPickerOverlay.id = 'clado-workspace-picker';
|
|
193
|
+
wsPickerOverlay.className = 'clado-market-overlay';
|
|
194
|
+
wsPickerOverlay.innerHTML = `
|
|
195
|
+
<div class="clado-market-sheet" style="max-width:500px;">
|
|
196
|
+
<div class="clado-market-well" style="padding:12px 14px;display:flex;align-items:center;justify-content:space-between;gap:8px;">
|
|
197
|
+
<div>
|
|
198
|
+
<strong style="font-size:15px;">选择或新建工作区</strong>
|
|
199
|
+
<div data-ws-cur style="font-size:11px;color:var(--clado-ui-muted);margin-top:2px;"></div>
|
|
200
|
+
</div>
|
|
201
|
+
<button type="button" class="clado-market-tab active" data-ws-close style="padding:5px 11px;">关闭</button>
|
|
202
|
+
</div>
|
|
203
|
+
|
|
204
|
+
<div class="clado-market-well" data-ws-recents-wrap style="padding:11px 12px;display:none;flex-direction:column;gap:5px;">
|
|
205
|
+
<div style="font-size:11px;font-weight:650;color:var(--clado-ui-muted);">最近打开的项目</div>
|
|
206
|
+
<div data-ws-recents style="display:flex;flex-direction:column;gap:3px;"></div>
|
|
207
|
+
</div>
|
|
208
|
+
|
|
209
|
+
<div class="clado-market-well" style="padding:11px 12px;display:flex;flex-direction:column;gap:8px;">
|
|
210
|
+
<div style="display:flex;align-items:center;justify-content:space-between;gap:6px;">
|
|
211
|
+
<span style="font-size:11.5px;font-weight:650;color:var(--clado-ui-muted);">浏览本机目录</span>
|
|
212
|
+
<div style="display:flex;gap:4px;">
|
|
213
|
+
<button type="button" class="clado-market-tab active" data-ws-up style="font-size:11px;padding:3px 8px;">↑ 上级</button>
|
|
214
|
+
<button type="button" class="clado-market-tab active" data-ws-home style="font-size:11px;padding:3px 8px;">⌂ 主目录</button>
|
|
215
|
+
</div>
|
|
216
|
+
</div>
|
|
217
|
+
<div data-ws-browse-list style="max-height:190px;overflow-y:auto;display:flex;flex-direction:column;gap:2px;"></div>
|
|
218
|
+
</div>
|
|
219
|
+
|
|
220
|
+
<div class="clado-market-well" style="padding:12px;display:flex;flex-direction:column;gap:8px;">
|
|
221
|
+
<div style="font-size:11.5px;color:var(--clado-ui-muted);">目标工作区路径(回车浏览目录,或直接输入新目录路径自动创建)</div>
|
|
222
|
+
<div style="display:flex;gap:6px;">
|
|
223
|
+
<input type="text" data-ws-input style="flex:1;height:35px;padding:0 11px;border-radius:10px;border:1px solid var(--clado-ui-well-border);background:var(--clado-ui-well);color:var(--clado-ui-text);font:inherit;font-size:12.5px;outline:none;" placeholder="/path/to/your-project" />
|
|
224
|
+
<button type="button" class="clado-market-tab active" data-ws-go style="height:35px;padding:0 11px;font-size:12px;">浏览</button>
|
|
225
|
+
</div>
|
|
226
|
+
<div data-ws-err style="font-size:11.5px;color:#e11d48;display:none;"></div>
|
|
227
|
+
<div style="display:flex;gap:8px;flex-wrap:wrap;">
|
|
228
|
+
<button type="button" class="clado-market-tab active" data-ws-open style="flex:1;height:35px;font-size:12.5px;">打开此目录</button>
|
|
229
|
+
<button type="button" data-ws-init style="flex:1.2;height:35px;border:0;border-radius:10px;background:var(--clado-ui-brand);color:#fff;font:inherit;font-size:12.5px;font-weight:600;cursor:pointer;">在此新建工作区并建首张画布</button>
|
|
230
|
+
</div>
|
|
231
|
+
</div>
|
|
232
|
+
</div>`;
|
|
233
|
+
document.body.append(wsPickerOverlay);
|
|
234
|
+
|
|
235
|
+
let parentDir = '';
|
|
236
|
+
let homeDir = '';
|
|
237
|
+
const curEl = wsPickerOverlay.querySelector('[data-ws-cur]');
|
|
238
|
+
const recentsWrap = wsPickerOverlay.querySelector('[data-ws-recents-wrap]');
|
|
239
|
+
const recentsList = wsPickerOverlay.querySelector('[data-ws-recents]');
|
|
240
|
+
const browseList = wsPickerOverlay.querySelector('[data-ws-browse-list]');
|
|
241
|
+
const pathInput = wsPickerOverlay.querySelector('[data-ws-input]');
|
|
242
|
+
const errEl = wsPickerOverlay.querySelector('[data-ws-err]');
|
|
243
|
+
|
|
244
|
+
const showErr = msg => {
|
|
245
|
+
errEl.textContent = msg || '';
|
|
246
|
+
errEl.style.display = msg ? 'block' : 'none';
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const loadDir = async (dir = '') => {
|
|
250
|
+
showErr('');
|
|
251
|
+
try {
|
|
252
|
+
const qs = dir ? '?dir=' + encodeURIComponent(dir) : '';
|
|
253
|
+
const res = await fetch('/library/fs-workspaces' + qs, { cache: 'no-store' });
|
|
254
|
+
const data = await res.json();
|
|
255
|
+
if (!res.ok) throw new Error(data.error || '读取目录失败');
|
|
256
|
+
parentDir = data.parentDir || '';
|
|
257
|
+
homeDir = data.homeDir || '';
|
|
258
|
+
curEl.textContent = data.hubMode ? '请选择一个项目目录开始协作' : `当前:${data.currentWorkspace}`;
|
|
259
|
+
pathInput.value = data.currentDir || data.currentWorkspace || '';
|
|
260
|
+
|
|
261
|
+
const recents = Array.isArray(data.recentWorkspaces) ? data.recentWorkspaces : [];
|
|
262
|
+
if (recents.length) {
|
|
263
|
+
recentsWrap.style.display = 'flex';
|
|
264
|
+
recentsList.replaceChildren();
|
|
265
|
+
for (const r of recents.slice(0, 5)) {
|
|
266
|
+
const row = document.createElement('button');
|
|
267
|
+
row.type = 'button';
|
|
268
|
+
row.className = 'clado-folder-row';
|
|
269
|
+
row.innerHTML = `<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><strong>${r.name}</strong> <small style="color:var(--clado-ui-muted);">${r.path}</small></span><span style="font-size:11px;color:var(--clado-ui-brand);flex:none;">${r.documents ?? 0} 画布</span>`;
|
|
270
|
+
row.onclick = () => applyWorkspaceSwitch(r.path, { createIfMissing: false }).catch(e => showErr(e.message));
|
|
271
|
+
recentsList.append(row);
|
|
272
|
+
}
|
|
273
|
+
} else {
|
|
274
|
+
recentsWrap.style.display = 'none';
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
browseList.replaceChildren();
|
|
278
|
+
const entries = Array.isArray(data.entries) ? data.entries : [];
|
|
279
|
+
if (!entries.length) {
|
|
280
|
+
const empty = document.createElement('div');
|
|
281
|
+
empty.style.cssText = 'padding:12px;text-align:center;color:var(--clado-ui-muted);font-size:12px;';
|
|
282
|
+
empty.textContent = '当前文件夹下暂无子目录,可直接打开此目录或下方输入新子目录名新建。';
|
|
283
|
+
browseList.append(empty);
|
|
284
|
+
} else {
|
|
285
|
+
for (const item of entries) {
|
|
286
|
+
const row = document.createElement('button');
|
|
287
|
+
row.type = 'button';
|
|
288
|
+
row.className = 'clado-folder-row';
|
|
289
|
+
row.dataset.folderPath = item.path;
|
|
290
|
+
const badges = [
|
|
291
|
+
item.hasClado ? '<span style="color:#059669;font-weight:600;">Clado</span>' : '',
|
|
292
|
+
item.isGit ? '<span style="color:var(--clado-ui-muted);">Git</span>' : '',
|
|
293
|
+
item.mdCount ? `<span>${item.mdCount} md</span>` : '',
|
|
294
|
+
].filter(Boolean).join(' · ');
|
|
295
|
+
row.innerHTML = `<span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">📁 ${item.name}</span><small style="color:var(--clado-ui-subtle);flex:none;">${badges || '进入 ›'}</small>`;
|
|
296
|
+
row.onclick = () => loadDir(item.path);
|
|
297
|
+
browseList.append(row);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
} catch (err) {
|
|
301
|
+
showErr(err.message || '读取目录失败');
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
wsPickerOverlay.addEventListener('click', ev => {
|
|
306
|
+
if (ev.target === wsPickerOverlay || ev.target.closest('[data-ws-close]')) {
|
|
307
|
+
wsPickerOverlay.classList.remove('show');
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
pathInput.addEventListener('keydown', ev => {
|
|
311
|
+
if (ev.key === 'Enter') {
|
|
312
|
+
ev.preventDefault();
|
|
313
|
+
if (pathInput.value.trim()) loadDir(pathInput.value.trim());
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
wsPickerOverlay.querySelector('[data-ws-go]').onclick = () => {
|
|
317
|
+
if (pathInput.value.trim()) loadDir(pathInput.value.trim());
|
|
318
|
+
};
|
|
319
|
+
wsPickerOverlay.querySelector('[data-ws-up]').onclick = () => { if (parentDir) loadDir(parentDir); };
|
|
320
|
+
wsPickerOverlay.querySelector('[data-ws-home]').onclick = () => { if (homeDir) loadDir(homeDir); };
|
|
321
|
+
wsPickerOverlay.querySelector('[data-ws-open]').onclick = () => {
|
|
322
|
+
applyWorkspaceSwitch(pathInput.value, { createIfMissing: true, initStarterCanvas: false }).catch(e => showErr(e.message));
|
|
323
|
+
};
|
|
324
|
+
wsPickerOverlay.querySelector('[data-ws-init]').onclick = () => {
|
|
325
|
+
applyWorkspaceSwitch(pathInput.value, { createIfMissing: true, initStarterCanvas: true }).catch(e => showErr(e.message));
|
|
326
|
+
};
|
|
327
|
+
wsPickerOverlay._loadDir = loadDir;
|
|
328
|
+
return wsPickerOverlay;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function openWorkspacePicker(initialDir = '') {
|
|
332
|
+
if (!config.canSwitchWorkspace || offline || !document.body) return;
|
|
333
|
+
const modal = ensureWorkspacePicker();
|
|
334
|
+
if (!modal) return;
|
|
335
|
+
modal.classList.add('show');
|
|
336
|
+
modal._loadDir(initialDir);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (config.canSwitchWorkspace && !offline && document.body) {
|
|
340
|
+
window.addEventListener('clado:open-workspace-picker', () => openWorkspacePicker());
|
|
341
|
+
const emptyEl = $('#emptyState');
|
|
342
|
+
if (emptyEl) {
|
|
343
|
+
const wsTitle = config.hubMode ? '欢迎使用 Clado · 请先选择工作区' : `当前工作区:${config.workspaceName || '未命名项目'}`;
|
|
344
|
+
const wsSub = config.hubMode
|
|
345
|
+
? '选择一个已有代码仓库或新建空白工作区,配置好模型供应商即可开始与多角色分身协作设计。'
|
|
346
|
+
: `路径:${config.workspacePath || '.'} · 当前目录尚无画布文档,你可以一键新建首张画布或直接在右下角向 Agent 提问。`;
|
|
347
|
+
emptyEl.style.padding = '0';
|
|
348
|
+
emptyEl.innerHTML = `
|
|
349
|
+
<div class="clado-launchpad-wrap">
|
|
350
|
+
<div class="clado-launchpad-card">
|
|
351
|
+
<div>
|
|
352
|
+
<div style="font-size:16px;font-weight:700;color:var(--clado-ui-text);">${wsTitle}</div>
|
|
353
|
+
<div style="font-size:12px;line-height:1.55;color:var(--clado-ui-muted);margin-top:5px;">${wsSub}</div>
|
|
354
|
+
</div>
|
|
355
|
+
<div class="clado-launchpad-actions">
|
|
356
|
+
<button type="button" class="clado-launchpad-btn primary" data-lp-pick>
|
|
357
|
+
<span><strong>📂 选择或切换本机工作区</strong><br/><small style="color:var(--clado-ui-muted);">浏览电脑目录、打开已有仓库或新建项目</small></span>
|
|
358
|
+
<span style="color:var(--clado-ui-brand);font-weight:700;">›</span>
|
|
359
|
+
</button>
|
|
360
|
+
<button type="button" class="clado-launchpad-btn" data-lp-new-canvas>
|
|
361
|
+
<span><strong>✨ 在当前工作区新建首张画布</strong><br/><small style="color:var(--clado-ui-muted);">立即创建初始架构画布进入三视图协作</small></span>
|
|
362
|
+
<span style="opacity:.5;">+</span>
|
|
363
|
+
</button>
|
|
364
|
+
<button type="button" class="clado-launchpad-btn" data-lp-llm>
|
|
365
|
+
<span><strong>⚙ 配置供应商与主力模型</strong><br/><small style="color:var(--clado-ui-muted);">支持 OpenAI / Anthropic / DeepSeek / OpenRouter / Ollama</small></span>
|
|
366
|
+
<span style="opacity:.5;">›</span>
|
|
367
|
+
</button>
|
|
368
|
+
</div>
|
|
369
|
+
</div>
|
|
370
|
+
</div>`;
|
|
371
|
+
emptyEl.querySelector('[data-lp-pick]').onclick = () => openWorkspacePicker();
|
|
372
|
+
emptyEl.querySelector('[data-lp-new-canvas]').onclick = () => createCanvasFlow('系统架构概览');
|
|
373
|
+
emptyEl.querySelector('[data-lp-llm]').onclick = () => window.dispatchEvent(new CustomEvent('clado:open-llm-settings'));
|
|
374
|
+
}
|
|
375
|
+
if (config.hubMode) {
|
|
376
|
+
setTimeout(() => openWorkspacePicker(), 60);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
146
379
|
const liveObjectsEnabled = Boolean(config.selection && !offline && document.body);
|
|
147
380
|
let canvasObjectsList = [];
|
|
148
381
|
const objectSelection = new Map();
|
|
@@ -543,7 +776,7 @@
|
|
|
543
776
|
if (!container) {
|
|
544
777
|
container = document.createElement('div');
|
|
545
778
|
container.className = 'empty-workspaces';
|
|
546
|
-
$('#emptyState').append(container);
|
|
779
|
+
($('#emptyState .clado-launchpad-card') || $('#emptyState')).append(container);
|
|
547
780
|
}
|
|
548
781
|
container.replaceChildren();
|
|
549
782
|
const title = document.createElement('div');
|
|
@@ -682,7 +915,7 @@
|
|
|
682
915
|
else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
|
|
683
916
|
else { $('#updateError').hidden = true; if (force || doc.version !== version) { open(selected, version ? '' : pendingAnchor, { update: true }); } else { flushPendingTouch(); status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); } }
|
|
684
917
|
}
|
|
685
|
-
} catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
|
|
918
|
+
} catch { if (pageHidden) return; status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
|
|
686
919
|
finally {
|
|
687
920
|
busy = false;
|
|
688
921
|
if (pendingRescan) { pendingRescan = false; scan(true); }
|
|
@@ -17,10 +17,28 @@ const specs = {
|
|
|
17
17
|
'clado.agent': {
|
|
18
18
|
name: { type: 'string', minLength: 1, maxLength: 80 },
|
|
19
19
|
mode: { enum: ['auto', 'builtin', 'acp'] },
|
|
20
|
-
|
|
20
|
+
providerId: { type: 'string', minLength: 1, maxLength: 64 },
|
|
21
|
+
provider: { enum: ['auto', 'openai', 'anthropic', 'custom'] },
|
|
21
22
|
baseUrl: { type: 'string', minLength: 1, maxLength: 512 },
|
|
22
23
|
apiKey: { type: 'string', maxLength: 512 },
|
|
23
24
|
model: { type: 'string', minLength: 1, maxLength: 128 },
|
|
25
|
+
providers: {
|
|
26
|
+
type: 'object',
|
|
27
|
+
maxProperties: 24,
|
|
28
|
+
additionalProperties: {
|
|
29
|
+
type: 'object',
|
|
30
|
+
additionalProperties: false,
|
|
31
|
+
properties: {
|
|
32
|
+
label: { type: 'string', maxLength: 80 },
|
|
33
|
+
protocol: { enum: ['openai', 'anthropic'] },
|
|
34
|
+
baseUrl: { type: 'string', maxLength: 512 },
|
|
35
|
+
apiKey: { type: 'string', maxLength: 512 },
|
|
36
|
+
model: { type: 'string', maxLength: 128 },
|
|
37
|
+
enabled: { type: 'boolean' },
|
|
38
|
+
models: { type: 'array', maxItems: 80, items: { type: 'string', maxLength: 128 } },
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
},
|
|
24
42
|
persona: { enum: ['architect', 'coder', 'qa', 'auditor', 'custom'] },
|
|
25
43
|
personaPrompt: { type: 'string', maxLength: 4000 },
|
|
26
44
|
command: { type: 'string', minLength: 1, maxLength: 2048, pattern: '^.+' },
|
|
@@ -51,7 +69,15 @@ const specs = {
|
|
|
51
69
|
const defaults = {
|
|
52
70
|
'clado.brand': { showScreenshot: true },
|
|
53
71
|
'clado.directory': { showFilename: true },
|
|
54
|
-
'clado.agent': {
|
|
72
|
+
'clado.agent': {
|
|
73
|
+
name: 'Clado',
|
|
74
|
+
mode: 'builtin',
|
|
75
|
+
providerId: 'openai',
|
|
76
|
+
command: process.env.CLADO_ZCODE_ACP_PATH || 'zcode-acp-server',
|
|
77
|
+
args: [],
|
|
78
|
+
env: {},
|
|
79
|
+
placeholder: '写下一个想法…',
|
|
80
|
+
},
|
|
55
81
|
};
|
|
56
82
|
const fileName = 'plugin-settings.json';
|
|
57
83
|
const maxBytes = 1024 * 1024;
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本机工作区中心(Workspace Hub):
|
|
3
|
+
* - 最近打开工作区持久化(~/.clado/recent-workspaces.json)
|
|
4
|
+
* - 本机目录安全浏览(供网页端选择/切换/新建项目目录)
|
|
5
|
+
* - 浏览器端一键新建初始画布文档(告别“必须先用外部客户端建文档”的死胡同)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
11
|
+
import { DocumentError, scanDirectory, workspacePath } from '../workspace/documents.js';
|
|
12
|
+
import { contextFor, initialize } from '../workspace/storage.js';
|
|
13
|
+
import { userTemplatePaths } from '../skill/templates.js';
|
|
14
|
+
|
|
15
|
+
const MAX_RECENTS = 16;
|
|
16
|
+
|
|
17
|
+
function recentsFilePath() {
|
|
18
|
+
const dir = userTemplatePaths().state;
|
|
19
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
20
|
+
return join(dir, 'recent-workspaces.json');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function countMarkdownInWorkspace(wsDir) {
|
|
24
|
+
try {
|
|
25
|
+
const cladoDoc = join(wsDir, '.clado', 'doc');
|
|
26
|
+
if (existsSync(cladoDoc) && lstatSync(cladoDoc).isDirectory()) {
|
|
27
|
+
return scanDirectory(cladoDoc).documents.length;
|
|
28
|
+
}
|
|
29
|
+
return scanDirectory(wsDir).documents.length;
|
|
30
|
+
} catch {
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readRecentWorkspaces() {
|
|
36
|
+
const file = recentsFilePath();
|
|
37
|
+
if (!existsSync(file)) return [];
|
|
38
|
+
try {
|
|
39
|
+
const raw = JSON.parse(readFileSync(file, 'utf8'));
|
|
40
|
+
if (!Array.isArray(raw)) return [];
|
|
41
|
+
const out = [];
|
|
42
|
+
for (const item of raw) {
|
|
43
|
+
if (!item || typeof item.path !== 'string') continue;
|
|
44
|
+
const p = resolve(item.path);
|
|
45
|
+
try {
|
|
46
|
+
if (!existsSync(p) || !statSync(p).isDirectory()) continue;
|
|
47
|
+
out.push({
|
|
48
|
+
path: p,
|
|
49
|
+
name: basename(p) || p,
|
|
50
|
+
hasClado: existsSync(join(p, '.clado')),
|
|
51
|
+
isGit: existsSync(join(p, '.git')),
|
|
52
|
+
documents: countMarkdownInWorkspace(p),
|
|
53
|
+
lastOpenedAt: item.lastOpenedAt || new Date().toISOString(),
|
|
54
|
+
});
|
|
55
|
+
} catch {}
|
|
56
|
+
}
|
|
57
|
+
return out.slice(0, MAX_RECENTS);
|
|
58
|
+
} catch {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function recordRecentWorkspace(wsPath) {
|
|
64
|
+
if (!wsPath) return [];
|
|
65
|
+
const clean = resolve(wsPath);
|
|
66
|
+
const existing = readRecentWorkspaces().filter(item => item.path !== clean);
|
|
67
|
+
const next = [
|
|
68
|
+
{
|
|
69
|
+
path: clean,
|
|
70
|
+
name: basename(clean) || clean,
|
|
71
|
+
lastOpenedAt: new Date().toISOString(),
|
|
72
|
+
},
|
|
73
|
+
...existing,
|
|
74
|
+
].slice(0, MAX_RECENTS);
|
|
75
|
+
try {
|
|
76
|
+
writeFileSync(recentsFilePath(), JSON.stringify(next, null, 2) + '\n', { mode: 0o600 });
|
|
77
|
+
} catch {}
|
|
78
|
+
return readRecentWorkspaces();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function browseLocalFolders(dirInput = '') {
|
|
82
|
+
const home = homedir();
|
|
83
|
+
const target = dirInput ? resolve(String(dirInput)) : home;
|
|
84
|
+
if (!existsSync(target)) {
|
|
85
|
+
throw new DocumentError(`目录不存在:${target}`, 404);
|
|
86
|
+
}
|
|
87
|
+
const st = statSync(target);
|
|
88
|
+
const currentDir = st.isDirectory() ? target : dirname(target);
|
|
89
|
+
const parent = dirname(currentDir);
|
|
90
|
+
const parentDir = parent !== currentDir ? parent : '';
|
|
91
|
+
|
|
92
|
+
const entries = [];
|
|
93
|
+
let rawEntries = [];
|
|
94
|
+
try {
|
|
95
|
+
rawEntries = readdirSync(currentDir, { withFileTypes: true });
|
|
96
|
+
} catch {
|
|
97
|
+
throw new DocumentError(`无权读取目录:${currentDir}`, 403);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
for (const entry of rawEntries) {
|
|
101
|
+
if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist' || entry.name === '$RECYCLE.BIN') {
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const full = join(currentDir, entry.name);
|
|
105
|
+
try {
|
|
106
|
+
const info = lstatSync(full);
|
|
107
|
+
if (!info.isDirectory() || info.isSymbolicLink()) continue;
|
|
108
|
+
let mdCount = 0;
|
|
109
|
+
const hasClado = existsSync(join(full, '.clado'));
|
|
110
|
+
const isGit = existsSync(join(full, '.git'));
|
|
111
|
+
if (hasClado && existsSync(join(full, '.clado', 'doc'))) {
|
|
112
|
+
try {
|
|
113
|
+
mdCount = readdirSync(join(full, '.clado', 'doc')).filter(n => /\.mdc?$/i.test(n)).length;
|
|
114
|
+
} catch {}
|
|
115
|
+
} else {
|
|
116
|
+
try {
|
|
117
|
+
mdCount = readdirSync(full).filter(n => /\.mdc?$/i.test(n) && !/^readme\.md$/i.test(n)).length;
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
entries.push({
|
|
121
|
+
name: entry.name,
|
|
122
|
+
path: full,
|
|
123
|
+
hasClado,
|
|
124
|
+
isGit,
|
|
125
|
+
mdCount,
|
|
126
|
+
});
|
|
127
|
+
} catch {}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
entries.sort((a, b) => {
|
|
131
|
+
const scoreA = (a.hasClado ? 4 : 0) + (a.isGit ? 2 : 0) + (a.mdCount > 0 ? 1 : 0);
|
|
132
|
+
const scoreB = (b.hasClado ? 4 : 0) + (b.isGit ? 2 : 0) + (b.mdCount > 0 ? 1 : 0);
|
|
133
|
+
if (scoreA !== scoreB) return scoreB - scoreA;
|
|
134
|
+
return a.name.localeCompare(b.name, 'zh-CN');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
currentDir,
|
|
139
|
+
parentDir,
|
|
140
|
+
homeDir: home,
|
|
141
|
+
hasClado: existsSync(join(currentDir, '.clado')),
|
|
142
|
+
isGit: existsSync(join(currentDir, '.git')),
|
|
143
|
+
entries: entries.slice(0, 120),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function resolveWorkspaceSelection(targetPath, { createIfMissing = false, project = true } = {}) {
|
|
148
|
+
if (!targetPath || typeof targetPath !== 'string') {
|
|
149
|
+
throw new DocumentError('请提供有效的工作区目录路径。', 400);
|
|
150
|
+
}
|
|
151
|
+
const clean = resolve(targetPath.trim());
|
|
152
|
+
if (!existsSync(clean)) {
|
|
153
|
+
if (!createIfMissing) throw new DocumentError(`目录不存在:${clean}(可勾选新建目录)`, 404);
|
|
154
|
+
mkdirSync(clean, { recursive: true });
|
|
155
|
+
}
|
|
156
|
+
const st = statSync(clean);
|
|
157
|
+
if (!st.isDirectory()) throw new DocumentError('工作区路径必须是文件夹。', 400);
|
|
158
|
+
|
|
159
|
+
let workspace = clean;
|
|
160
|
+
let root = clean;
|
|
161
|
+
if (basename(clean) === 'doc' && basename(dirname(clean)) === '.clado') {
|
|
162
|
+
workspace = dirname(dirname(clean));
|
|
163
|
+
root = clean;
|
|
164
|
+
} else if (
|
|
165
|
+
project
|
|
166
|
+
|| existsSync(join(clean, '.clado/workspace.json'))
|
|
167
|
+
|| existsSync(join(clean, 'package.json'))
|
|
168
|
+
|| existsSync(join(clean, '.git'))
|
|
169
|
+
|| !scanDirectory(clean).documents.some(d => !/^readme\.md$/i.test(d.file))
|
|
170
|
+
) {
|
|
171
|
+
const ctx = contextFor(clean, clean);
|
|
172
|
+
workspace = clean;
|
|
173
|
+
root = ctx.documents;
|
|
174
|
+
}
|
|
175
|
+
const rootCtx = contextFor(workspace, workspace, root);
|
|
176
|
+
initialize(rootCtx);
|
|
177
|
+
return { workspace, root, rootCtx };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function createStarterCanvas(docRoot, { title = '系统架构概览', file = '' } = {}) {
|
|
181
|
+
const cleanTitle = String(title || '系统架构概览').trim().slice(0, 80) || '系统架构概览';
|
|
182
|
+
const slug = String(file || '')
|
|
183
|
+
.trim()
|
|
184
|
+
.replace(/\.mdc?$/i, '')
|
|
185
|
+
.replace(/[\\/:*?"<>|]/g, '-')
|
|
186
|
+
.slice(0, 64);
|
|
187
|
+
|
|
188
|
+
let fileName = (slug || 'overview') + '.md';
|
|
189
|
+
if (!file && existsSync(join(docRoot, fileName))) {
|
|
190
|
+
let idx = 2;
|
|
191
|
+
while (existsSync(join(docRoot, `canvas-${idx}.md`)) && idx < 99) idx++;
|
|
192
|
+
fileName = `canvas-${idx}.md`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const fullPath = workspacePath(docRoot, fileName, true);
|
|
196
|
+
if (existsSync(fullPath)) {
|
|
197
|
+
throw new DocumentError(`画布文件已存在:${fileName}`, 409);
|
|
198
|
+
}
|
|
199
|
+
if (!existsSync(dirname(fullPath))) mkdirSync(dirname(fullPath), { recursive: true });
|
|
200
|
+
|
|
201
|
+
const body = [
|
|
202
|
+
`# ${cleanTitle}`,
|
|
203
|
+
'',
|
|
204
|
+
'在此梳理核心模块职责、接口契约与关键状态流转 [#核心入口|blue](#entry-contract),下游衔接 [协作与演进边界](#协作与演进边界)。',
|
|
205
|
+
'',
|
|
206
|
+
'## 核心入口契约 {#entry-contract}',
|
|
207
|
+
'',
|
|
208
|
+
'- 明确输入校验、幂等边界与状态推进条件',
|
|
209
|
+
'- 可在右下角直接让 Clado Agent 扫描当前代码库自动补全卡片',
|
|
210
|
+
'',
|
|
211
|
+
'# 协作与演进边界',
|
|
212
|
+
'',
|
|
213
|
+
'记录模块间调用约定、异常兜底与待确认事项。',
|
|
214
|
+
'',
|
|
215
|
+
'## 待办与验收点',
|
|
216
|
+
'',
|
|
217
|
+
'- 选中任意卡片或长按贴上便签,一键发给当前分身深化设计',
|
|
218
|
+
'',
|
|
219
|
+
].join('\n');
|
|
220
|
+
|
|
221
|
+
writeFileSync(fullPath, body, 'utf8');
|
|
222
|
+
return { file: fileName, title: cleanTitle };
|
|
223
|
+
}
|