File size: 15,277 Bytes
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
031fd6d
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12880e4
 
 
 
 
 
 
 
 
 
 
 
36277c7
 
 
 
 
 
 
 
 
 
 
 
0fc6e34
 
 
 
 
 
 
 
 
 
 
30b24ad
 
 
 
 
 
 
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fc6e34
36277c7
12880e4
0fc6e34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fc6e34
2b46b80
 
 
 
0fc6e34
 
 
 
 
 
 
 
 
 
 
2b46b80
 
0fc6e34
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30b24ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
 
36277c7
 
 
12880e4
 
 
 
 
 
 
 
36277c7
 
12880e4
36277c7
 
 
 
 
 
 
 
12880e4
36277c7
12880e4
36277c7
 
12880e4
36277c7
 
 
 
 
 
 
12880e4
36277c7
 
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/**
 * @local/agentlens — Client half.
 *
 * Two surfaces:
 *  1. A compact "体检" chip in the composer tool row
 *     (`conversation.input.left` list slot — rendered right after the
 *     permission control 完全访问 and the plan seat). Clicking it scans the
 *     current project and shows the agent-config summary in a small popover.
 *  2. An "AgentLens 迁移" section in Settings (`settings.section` slot) with
 *     a path picker, a scan shortcut, and one-click rule migration between
 *     agent formats (claude / cursor / codex / windsurf / copilot).
 *
 * All data flows through the host's local HTTP routes (/agentlens/*), which
 * shell out to the AgentLens CLI. Nothing leaves the machine.
 */
window.__ModuleLoader__.load({
  id: '@local/agentlens',
  factory(require) {
    const React = require('react');
    const h = React.createElement;
    const { useCallback, useEffect, useRef, useState } = React;

    const STYLE_ID = 'agentlens-client-style';
    const STYLE_TEXT = `
.agentlens-chip{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 10px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.06);color:inherit;font:inherit;font-size:12px;line-height:1;cursor:pointer;white-space:nowrap;transition:background .15s ease,border-color .15s ease}
.agentlens-chip:hover{background:rgba(255,255,255,.12);border-color:rgba(255,255,255,.24)}
.agentlens-chip:disabled{opacity:.5;cursor:default}
.agentlens-pop{position:absolute;bottom:calc(100% + 8px);left:0;z-index:60;width:min(560px,80vw);max-height:50vh;overflow:auto;padding:12px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.16);background:rgba(24,27,34,.98);color:#e8eaf0;font:12px/1.55 ui-monospace,Menlo,Consolas,monospace;white-space:pre-wrap;box-shadow:0 12px 40px rgba(0,0,0,.45)}
.agentlens-pop-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;font-family:-apple-system,'PingFang SC',sans-serif;font-weight:600}
.agentlens-pop-close{border:0;background:transparent;color:#9aa3b2;cursor:pointer;font-size:14px;padding:2px 6px;border-radius:6px}
.agentlens-pop-close:hover{background:rgba(255,255,255,.1);color:#fff}
.agentlens-anchor{position:relative;display:inline-flex}
.agentlens-panel{display:grid;gap:14px;max-width:720px}
.agentlens-panel h3{margin:0;font-size:15px}
.agentlens-panel .row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
.agentlens-panel input,.agentlens-panel select{padding:6px 9px;border-radius:8px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.06);color:inherit;font:inherit;font-size:13px}
.agentlens-panel input[type=text]{flex:1 1 260px}
.agentlens-panel button{padding:6px 14px;border-radius:8px;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.08);color:inherit;font:inherit;font-size:13px;cursor:pointer}
.agentlens-panel button:hover{background:rgba(255,255,255,.14)}
.agentlens-panel button:disabled{opacity:.5;cursor:default}
.agentlens-out{margin:0;padding:10px 12px;border-radius:10px;background:rgba(0,0,0,.35);border:1px solid rgba(255,255,255,.1);font:12px/1.55 ui-monospace,Menlo,Consolas,monospace;white-space:pre-wrap;max-height:320px;overflow:auto}
.agentlens-hint{margin:0;font-size:12px;opacity:.65}
`;

    const AGENTS = ['claude', 'cursor', 'codex', 'windsurf', 'copilot', 'dsh', 'workbuddy', 'zcode', 'mimo'];

    function rememberedPath() {
      try {
        return localStorage.getItem('agentlens.path') || '';
      } catch {
        return '';
      }
    }

    function rememberPath(value) {
      try {
        if (value) localStorage.setItem('agentlens.path', value);
        else localStorage.removeItem('agentlens.path');
      } catch {
        /* ignore */
      }
    }

    async function callScan(path) {
      const query = path ? `?path=${encodeURIComponent(path)}` : '';
      const r = await fetch(`/agentlens/scan${query}`, { credentials: 'same-origin' });
      const d = await r.json();
      if (!r.ok || d.ok === false) throw new Error(d.error || `HTTP ${r.status}`);
      return String(d.text || '');
    }

    async function callImport(target, out) {
      const r = await fetch('/agentlens/import', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ target, out }),
      });
      const d = await r.json();
      if (!r.ok || d.ok === false) throw new Error(d.error || `HTTP ${r.status}`);
      return String(d.text || '');
    }

    async function callExport(out) {
      const r = await fetch('/agentlens/export', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ out }),
      });
      const d = await r.json();
      if (!r.ok || d.ok === false) throw new Error(d.error || `HTTP ${r.status}`);
      return String(d.text || '');
    }

    async function fetchWorkspaces() {
      try {
        const r = await fetch('/agentlens/workspaces', { credentials: 'same-origin' });
        const d = await r.json();
        if (r.ok && d.ok !== false && Array.isArray(d.workspaces)) return d.workspaces;
      } catch {
        /* ignore */
      }
      return [];
    }

    async function callInstall() {
      const r = await fetch('/agentlens/install', { method: 'POST', credentials: 'same-origin' });
      const d = await r.json();
      if (!r.ok || d.ok === false) throw new Error(d.error || `HTTP ${r.status}`);
      return String(d.text || '');
    }

    async function callMigrate(path, from, to) {
      const r = await fetch('/agentlens/migrate', {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ path, from, to }),
      });
      const d = await r.json();
      if (!r.ok || d.ok === false) throw new Error(d.error || `HTTP ${r.status}`);
      return String(d.text || '');
    }

    // ------------------------------------------------------------ scan chip

    function ScanChip() {
      const [busy, setBusy] = useState(false);
      const [open, setOpen] = useState(false);
      const [text, setText] = useState('');
      const [error, setError] = useState('');

      const run = useCallback(async () => {
        setBusy(true);
        setError('');
        setText('');
        try {
          const result = await callScan(rememberedPath());
          setText(result);
          setOpen(true);
        } catch (err) {
          setError(String((err && err.message) || err));
          setOpen(true);
        } finally {
          setBusy(false);
        }
      }, []);

      return h(
        'span',
        { className: 'agentlens-anchor' },
        h(
          'button',
          {
            type: 'button',
            className: 'agentlens-chip',
            title: '扫描当前项目的 AI Agent 配置(agentlens)',
            disabled: busy,
            onClick: run,
          },
          h('span', null, '🩺'),
          h('span', null, busy ? '扫描中…' : '体检')
        ),
        open
          ? h(
              'div',
              { className: 'agentlens-pop' },
              h(
                'div',
                { className: 'agentlens-pop-head' },
                h('span', null, 'AgentLens 扫描结果'),
                h(
                  'button',
                  {
                    type: 'button',
                    className: 'agentlens-pop-close',
                    onClick: () => setOpen(false),
                    title: '关闭',
                  },
                  '✕'
                )
              ),
              error ? `扫描失败:${error}` : text
            )
          : null
      );
    }

    // ------------------------------------------------------ settings panel

    function MigratePanel() {
      const [path, setPath] = useState(rememberedPath());
      const [workspaces, setWorkspaces] = useState([]);
      const [exportOut, setExportOut] = useState('');
      const [importTarget, setImportTarget] = useState('codex');

      useEffect(() => {
        let alive = true;
        fetchWorkspaces().then((list) => {
          if (!alive) return;
          setWorkspaces(list);
          setPath((current) => {
            if (current) return current;
            const first = list[0] || '';
            if (first) rememberPath(first);
            return first;
          });
        });
        return () => {
          alive = false;
        };
      }, []);
      const [from, setFrom] = useState('claude');
      const [to, setTo] = useState('cursor');
      const [busy, setBusy] = useState('');
      const [out, setOut] = useState('');
      const [error, setError] = useState('');

      const savePath = useCallback((value) => {
        setPath(value);
        rememberPath(value);
      }, []);

      const doScan = useCallback(async () => {
        setBusy('scan');
        setError('');
        try {
          setOut(await callScan(path));
        } catch (err) {
          setError(String((err && err.message) || err));
          setOut('');
        } finally {
          setBusy('');
        }
      }, [path]);

      const doMigrate = useCallback(async () => {
        setBusy('migrate');
        setError('');
        try {
          setOut(await callMigrate(path, from, to));
        } catch (err) {
          setError(String((err && err.message) || err));
        } finally {
          setBusy('');
        }
      }, [path, from, to]);

      return h(
        'div',
        { className: 'agentlens-panel' },
        h('h3', null, 'AgentLens 迁移'),
        h(
          'p',
          { className: 'agentlens-hint' },
          '把项目里的规则文件(CLAUDE.md / AGENTS.md / .cursor/rules 等)在 9 个 Agent 之间一键迁移。先选择你的项目目录,再选源/目标 Agent。所有操作都在本机完成。'
        ),
        h(
          'div',
          { className: 'row' },
          workspaces.length > 0
            ? h('select', {
                value: workspaces.includes(path) ? path : '',
                onChange: (e) => {
                  if (e.target.value) savePath(e.target.value);
                },
                title: '从 DSH 最近打开的项目中选择',
              },
                h('option', { value: '' }, '选择项目目录…'),
                workspaces.map((w) => h('option', { key: w, value: w }, w)))
            : null,
          h('input', {
            type: 'text',
            placeholder: '或手动输入项目路径,例如 ~/你的项目',
            value: path,
            onChange: (e) => savePath(e.target.value),
          }),
          h(
            'button',
            { type: 'button', disabled: busy !== '', onClick: doScan },
            busy === 'scan' ? '扫描中…' : '扫描'
          )
        ),
        h(
          'div',
          { className: 'row' },
          h('span', { style: { opacity: 0.75 } }, '迁移规则:'),
          h(
            'select',
            { value: from, onChange: (e) => setFrom(e.target.value) },
            AGENTS.map((a) => h('option', { key: a, value: a }, a))
          ),
          h('span', { style: { opacity: 0.75 } }, '→'),
          h(
            'select',
            { value: to, onChange: (e) => setTo(e.target.value) },
            AGENTS.map((a) => h('option', { key: a, value: a }, a))
          ),
          h(
            'button',
            { type: 'button', disabled: busy !== '' || from === to, onClick: doMigrate },
            busy === 'migrate' ? '迁移中…' : '开始迁移'
          ),
          h(
            'button',
            {
              type: 'button',
              disabled: busy !== '',
              title: '把 AgentLens 接入本机所有检测到的 AI 工具(相当于跑一次 agentlens install)',
              onClick: async () => {
                setBusy('install');
                setError('');
                try {
                  setOut(await callInstall());
                } catch (err) {
                  setError(String((err && err.message) || err));
                } finally {
                  setBusy('');
                }
              },
            },
            busy === 'install' ? '接入中…' : '一键接入所有 App'
          )
        ),
        h(
          'div',
          { className: 'row' },
          h('span', { style: { opacity: 0.75 } }, '完整搬家到:'),
          h(
            'select',
            { value: importTarget, onChange: (e) => setImportTarget(e.target.value) },
            [['codex', 'Codex'], ['claude', 'Claude Code'], ['zcode', 'ZCode'], ['workbuddy', 'WorkBuddy'], ['mimo', 'MiMo Desktop']].map(
              ([value, label]) => h('option', { key: value, value }, label)
            )
          ),
          h('input', {
            type: 'text',
            placeholder: '资料目录(留空 = ~/<目标>-import)',
            value: exportOut,
            onChange: (e) => setExportOut(e.target.value),
          }),
          h(
            'button',
            {
              type: 'button',
              disabled: busy !== '',
              title: '把 DSH 全部资料(人物设定 + 文件资料 + 对话记录)一键导入目标 Agent 并写进它的全局配置',
              onClick: async () => {
                setBusy('import');
                setError('');
                try {
                  setOut(await callImport(importTarget, exportOut.trim()));
                } catch (err) {
                  setError(String((err && err.message) || err));
                } finally {
                  setBusy('');
                }
              },
            },
            busy === 'import' ? '导入中…' : '一键导入'
          )
        ),
        error ? h('p', { className: 'agentlens-hint', style: { color: '#ff8a80' } }, `出错了:${error}`) : null,
        out ? h('pre', { className: 'agentlens-out' }, out) : null
      );
    }

    // ----------------------------------------------------------------- apply

    return {
      inject: ['slots'],
      apply(ctx) {
        if (typeof document !== 'undefined' && !document.getElementById(STYLE_ID)) {
          const tag = document.createElement('style');
          tag.id = STYLE_ID;
          tag.textContent = STYLE_TEXT;
          document.head.appendChild(tag);
        }

        // Composer tool row: the permission seat (完全访问) is a `single` slot,
        // so the nearest injectable list slot rendered right after it is
        // `conversation.input.left`. No explicit order → appended after any
        // existing items (偏移一位 by design).
        ctx.slots.inject('conversation.input.left', () =>
          ctx.slots.register({ name: 'conversation.input.left' }, () => h(ScanChip))
        );

        // Settings page section for migration.
        ctx.slots.inject('settings.section', () =>
          ctx.slots.register(
            { name: 'settings.section', id: 'agentlens', order: 43, label: () => 'AgentLens 迁移' },
            MigratePanel
          )
        );
      },
    };
  },
});