skillmkt 0.1.1 → 0.1.3

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.
@@ -1,9 +1,11 @@
1
- // conflicts — 队列列表;pending>0 exit3;--json
1
+ // conflicts — 队列列表;pending>0 exit3;--json;TTY 下 pending 时接管 Web
2
2
  import { loadConflicts } from '../lib/conflicts.js';
3
+ import { maybeHandoff } from '../lib/daemon.js';
3
4
  import { table } from '../lib/render.js';
4
5
 
5
6
  export async function run(ctx) {
6
7
  const all = loadConflicts(ctx.hub);
8
+ if (!ctx.flags.json && all.some((c) => c.status === 'pending') && await maybeHandoff(ctx, '/#conflicts')) return 0;
7
9
  const pending = all.filter((c) => c.status === 'pending');
8
10
  if (ctx.flags.json) { console.log(JSON.stringify(all, null, 2)); return pending.length ? 3 : 0; }
9
11
  if (!all.length) { console.log('no conflicts recorded — run: skillmkt merge <a> <b>'); return 0; }
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import { ensureHub, writeConfig, readConfig } from '../lib/hub.js';
4
4
  import { probeEndpoints, chat } from '../lib/llm.js';
5
+ import { ensureDaemon, openURL } from '../lib/daemon.js';
5
6
  import { choose, confirm } from '../lib/prompt.js';
6
7
  import { ok, warn, fail, info } from '../lib/render.js';
7
8
 
@@ -21,10 +22,19 @@ export async function run(ctx) {
21
22
 
22
23
  const raw = readConfig(ctx.hub)._raw;
23
24
  raw.ui = { ...(raw.ui || {}), enabled: mode === 'web' ? 'always' : 'auto' };
25
+ writeConfig(ctx.hub, raw); // ui 偏好先落盘(web 页内继续改其余键)
24
26
 
25
27
  if (mode === 'web') {
26
- // M5 daemon 就绪前:标记偏好,走终端向导完成本次
27
- warn('Web 初始化依赖 daemon(M5 提供)——本次先用终端向导完成,偏好已记录');
28
+ // daemon 就绪:setup 页完成探测+选模型+harness 勾选,全部经 /api/config 落盘
29
+ try {
30
+ const d = await ensureDaemon(ctx);
31
+ const url = openURL(d, '/#setup');
32
+ ok(`Web 初始化已打开: ${url}`);
33
+ info('setup 页内:探测端点 → 选模型 → 勾 harness → 保存(写入 config.yml)');
34
+ return 0;
35
+ } catch (e) {
36
+ warn(`daemon 不可用(${e.message.slice(0, 60)})——回退终端向导`);
37
+ }
28
38
  }
29
39
 
30
40
  // LLM 端点探测(只在用户进入配置步骤时探测——铁律)
@@ -6,10 +6,13 @@ import crypto from 'node:crypto';
6
6
  import { daemonFile, readDaemon } from '../lib/daemon.js';
7
7
  import { loadConflicts } from '../lib/conflicts.js';
8
8
  import { loadDecisions, decide } from '../lib/decide.js';
9
- import { readLibrary, readLock } from '../lib/hub.js';
9
+ import { readLibrary, readLock, readConfig, writeConfig, registerSkill, updateLock } from '../lib/hub.js';
10
10
  import { readUpstream } from '../lib/state.js';
11
11
  import { readYAML } from '../../pipeline/lib/util.js';
12
12
  import { scanAll } from '../lib/scanner.js';
13
+ import { probeEndpoints, chat } from '../lib/llm.js';
14
+ import { projectSkill, targetDirFor } from '../lib/project.js';
15
+ import { treeHash } from '../lib/package.js';
13
16
  import { ok, info, fail } from '../lib/render.js';
14
17
 
15
18
  const PUB = path.join(new URL('.', import.meta.url).pathname, '../public');
@@ -42,7 +45,10 @@ export async function run(ctx) {
42
45
  'GET /api/state': () => state(),
43
46
  'GET /api/conflicts': () => loadConflicts(ctx.hub),
44
47
  'GET /api/decisions': () => loadDecisions(ctx.hub),
48
+ 'GET /api/config': () => readConfig(ctx.hub)._raw,
49
+ 'GET /api/probe': async () => probeEndpoints(), // init 用:探测 LLM 端点
45
50
  };
51
+ const body = (req) => new Promise((r) => { let b = ''; req.on('data', (c) => b += c); req.on('end', () => r(b || '{}')); });
46
52
 
47
53
  const server = http.createServer(async (req, res) => {
48
54
  lastActive = Date.now();
@@ -60,21 +66,57 @@ export async function run(ctx) {
60
66
  if (u.pathname.startsWith('/api/')) {
61
67
  if (!authed) { res.writeHead(401, { 'content-type': 'application/json' }); return res.end('{"error":"unauthorized"}'); }
62
68
  res.setHeader('content-type', 'application/json');
63
- if (req.method === 'POST' && u.pathname === '/api/decide') {
64
- const body = JSON.parse(await new Promise((r) => { let b = ''; req.on('data', (c) => b += c); req.on('end', () => r(b || '{}')); }));
65
- const c = loadConflicts(ctx.hub).find((x) => x.id === body.id);
66
- if (!c) { res.writeHead(404); return res.end('{"error":"not found"}'); }
69
+ if (req.method === 'POST') {
70
+ const b = JSON.parse(await body(req));
67
71
  try {
68
- decide(ctx.hub, c, { resolution: body.resolution, custom: body.custom || null, reason: body.reason || 'web decision', by: 'web-ui' });
69
- c.status = 'resolved';
70
- const { writeConflict } = await import('../lib/conflicts.js');
71
- writeConflict(ctx.hub, c);
72
- emit('decide', { id: c.id });
73
- return res.end('{"ok":true}');
72
+ if (u.pathname === '/api/decide') {
73
+ const c = loadConflicts(ctx.hub).find((x) => x.id === b.id);
74
+ if (!c) { res.writeHead(404); return res.end('{"error":"not found"}'); }
75
+ decide(ctx.hub, c, { resolution: b.resolution, custom: b.custom || null, reason: b.reason || 'web decision', by: 'web-ui' });
76
+ c.status = 'resolved';
77
+ const { writeConflict } = await import('../lib/conflicts.js');
78
+ writeConflict(ctx.hub, c);
79
+ emit('decide', { id: c.id });
80
+ return res.end('{"ok":true}');
81
+ }
82
+ if (u.pathname === '/api/config') { // init:合并写 config
83
+ const raw = readConfig(ctx.hub)._raw;
84
+ if (b.llm !== undefined) raw.llm = b.llm;
85
+ if (b.ui !== undefined) raw.ui = b.ui;
86
+ if (b.default_targets !== undefined) raw.default_targets = b.default_targets;
87
+ if (b.policy) raw.policy = b.policy;
88
+ writeConfig(ctx.hub, raw);
89
+ emit('config', {});
90
+ return res.end('{"ok":true}');
91
+ }
92
+ if (u.pathname === '/api/llm-smoke') { // init 冒烟
93
+ const key = b.api_key?.startsWith('env:') ? process.env[b.api_key.slice(4)] ?? '' : b.api_key || '';
94
+ const r = await chat({ base_url: b.base_url, model: b.model, api_key: key, timeout_ms: 15000 }, { user: 'Reply with exactly: OK', maxTokens: 8 });
95
+ return res.end(JSON.stringify({ ok: true, reply: r.trim().slice(0, 80) }));
96
+ }
97
+ if (u.pathname === '/api/targets') { // web 改投影目标
98
+ const name = b.name, targets = b.targets || [];
99
+ const lib = readLibrary(ctx.hub);
100
+ const s = lib.skills?.[name];
101
+ if (!s) { res.writeHead(404); return res.end('{"error":"not found"}'); }
102
+ const dest = path.join(ctx.hub, 'skills', name);
103
+ const lockTargets = {};
104
+ for (const t of targets) {
105
+ const dir = targetDirFor(ctx, t, name);
106
+ if (!dir) continue;
107
+ const r = projectSkill(dest, name, dir, { mode: 'copy' });
108
+ lockTargets[t] = { hash: r.hash, projected_at: new Date().toISOString(), mode: 'copy' };
109
+ }
110
+ registerSkill(ctx.hub, name, { ...s, targets });
111
+ updateLock(ctx.hub, name, treeHash(dest), lockTargets);
112
+ emit('targets', { name });
113
+ return res.end('{"ok":true}');
114
+ }
74
115
  } catch (e) { res.writeHead(400); return res.end(JSON.stringify({ error: e.message })); }
116
+ res.writeHead(404); return res.end('{"error":"not found"}');
75
117
  }
76
118
  const h = routes[`${req.method} ${u.pathname}`];
77
- if (h) return res.end(JSON.stringify(h()));
119
+ if (h) return res.end(JSON.stringify(await h()));
78
120
  res.writeHead(404); return res.end('{"error":"not found"}');
79
121
  }
80
122
  // 静态:public/ + evidence 文件(冲突截图)
@@ -5,12 +5,15 @@ import { readConfig, writeConfig, expandHome } from '../lib/hub.js';
5
5
  import { projectSkill } from '../lib/project.js';
6
6
  import { updateLock } from '../lib/hub.js';
7
7
  import { readSkillDir } from '../lib/package.js';
8
+ import { maybeHandoff } from '../lib/daemon.js';
8
9
  import fs from 'node:fs';
9
10
 
10
11
  export async function run(ctx) {
11
12
  const [sub, ...rest] = ctx.args;
12
13
  const flags = ctx.flags.raw;
13
14
 
15
+ if ((!sub || sub === 'list') && !ctx.flags.json && await maybeHandoff(ctx, '/#skills')) return 0;
16
+
14
17
  if (!sub || sub === 'list') {
15
18
  const rows = ctx.harnesses.map((h) => ({
16
19
  id: h.id, state: h.state,
@@ -5,7 +5,12 @@ const el = (h) => { const d = document.createElement('div'); d.innerHTML = h; re
5
5
  const esc = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
6
6
  let S = null, tab = 'skills';
7
7
 
8
- async function refresh() { S = await api('/state'); render(); }
8
+ async function refresh() {
9
+ try { S = await api('/state'); }
10
+ catch (e) { document.getElementById('app').innerHTML = `<p class="pill bad">/api/state failed: ${esc(e.message)} — daemon 挂了?skillmkt serve --stop 后重开</p>`; return; }
11
+ if (S?.error) { document.getElementById('app').innerHTML = `<p class="pill bad">${esc(S.error)} — URL 里的 token 过期了,重跑 skillmkt serve 拿新链接</p>`; return; }
12
+ render();
13
+ }
9
14
  document.querySelectorAll('.tab').forEach((t) => t.onclick = () => { document.querySelectorAll('.tab').forEach((x) => x.classList.remove('on')); t.classList.add('on'); tab = t.dataset.t; render(); });
10
15
  const es = new EventSource(`/api/events?token=${T}`);
11
16
  es.addEventListener('decide', () => refresh());
@@ -14,14 +19,32 @@ es.onerror = () => document.getElementById('live').textContent = '○offline';
14
19
 
15
20
  const pill = (v) => `<span class="pill ${v === 'clean' || v === 'installed' || v === 'active' ? 'ok' : v === 'malicious' || v === 'pending' ? 'bad' : 'warn'}">${esc(v)}</span>`;
16
21
 
17
- function render() {
22
+ async function render() {
18
23
  const app = document.getElementById('app');
19
24
  if (!S) return;
20
25
  if (tab === 'skills') {
21
26
  const skills = Object.entries(S.library.skills || {});
22
27
  app.innerHTML = `<h3>installed (${skills.length})</h3>` + (skills.map(([n, s]) => `
23
28
  <div class="card"><div class="row"><b>${esc(n)}</b><span class="mut">${esc(s.version || '-')}</span><span class="mut">${esc(s.source?.registry || '')}</span>${pill(s.audit || 'clean')}
24
- <span class="mut" style="margin-left:auto">${(s.targets || []).join(', ') || 'no targets'}</span></div></div>`).join('') || '<p class="mut">none</p>');
29
+ <span class="mut" style="margin-left:auto">${(s.targets || []).join(', ') || 'no targets'}</span>
30
+ <button data-tg="${esc(n)}">targets</button></div>
31
+ <div class="tgbox" data-box="${esc(n)}" style="display:none;margin-top:6px"></div></div>`).join('') || '<p class="mut">none</p>');
32
+ // targets 编辑:勾选 harness → POST /api/targets 重投影
33
+ app.querySelectorAll('[data-tg]').forEach((b) => b.onclick = () => {
34
+ const box = app.querySelector(`[data-box="${b.dataset.tg}"]`);
35
+ if (box.style.display === 'block') { box.style.display = 'none'; return; }
36
+ const s = S.library.skills[b.dataset.tg];
37
+ box.style.display = 'block';
38
+ box.innerHTML = (S.harnesses || []).filter((x) => x.state === 'installed' && !x.detectOnly).map((x) =>
39
+ `<label class="row" style="display:block"><input type="checkbox" data-th="${esc(x.id)}" ${(s.targets || []).includes(x.id) ? 'checked' : ''}> ${esc(x.id)} <span class="mut">${esc(x.primaryDir || '')}</span></label>`).join('')
40
+ + `<div class="row" style="margin-top:6px"><button class="tgo">应用</button><span class="tout mut"></span></div>`;
41
+ box.querySelector('.tgo').onclick = async () => {
42
+ const ts = [...box.querySelectorAll('[data-th]:checked')].map((x) => x.dataset.th);
43
+ const r = await api('/targets', { method: 'POST', body: JSON.stringify({ name: b.dataset.tg, targets: ts }) });
44
+ box.querySelector('.tout').textContent = r.ok ? ' ✓' : ` ✗ ${r.error}`;
45
+ refresh();
46
+ };
47
+ });
25
48
  app.innerHTML += `<h3>harnesses</h3>` + (S.harnesses || []).map((h) => `<div class="card row"><b>${esc(h.id)}</b>${pill(h.status)}<span class="mut">${esc(h.primaryDir || h.dirs?.[0] || '')}</span></div>`).join('');
26
49
  const up = S.upstream.skills || {};
27
50
  if (Object.keys(up).length) app.innerHTML += `<h3>upstream</h3>` + Object.entries(up).map(([n, u]) => `<div class="card row"><b>${esc(n)}</b>${u.outdated ? pill('outdated') : pill('clean')}<span class="mut">${esc(String(u.ref || '').slice(0, 8))}</span></div>`).join('');
@@ -37,15 +60,31 @@ function render() {
37
60
  <div class="ev-imgs"></div>
38
61
  ${c.status === 'pending' ? `<div class="row" style="margin-top:8px">
39
62
  <button data-r="keep-a">keep A</button><button data-r="keep-b">keep B</button>
40
- <button data-r="merge">merge…</button><button data-r="dismissed">误报</button></div>` : ''}</div>`);
63
+ <button data-r="merge">merge…</button><button data-r="dismissed">误报</button></div>
64
+ <div class="editbox" style="display:none;margin-top:8px">
65
+ <textarea rows="3" class="mtext"></textarea>
66
+ <input class="reason" placeholder="reason(必填)">
67
+ <div class="row" style="margin-top:6px"><button class="go">提交合并</button><button class="cancel">取消</button></div></div>` : ''}</div>`);
41
68
  if (c.evidence_files) card.querySelector('.ev-imgs').innerHTML = c.evidence_files.filter((f) => f.endsWith('.png')).map((f) => `<img class="ev" src="/evidence/${c.id}/${f}?token=${T}">`).join('');
42
- card.querySelectorAll('button').forEach((b) => b.onclick = async () => {
43
- let custom = null;
44
- if (b.dataset.r === 'merge') { custom = prompt('合并文本:', `${c.sides[0].text} + ${c.sides[1].text}`); if (!custom) return; }
45
- const reason = prompt('reason:', '') || 'web decision';
46
- await api('/decide', { method: 'POST', body: JSON.stringify({ id: c.id, resolution: b.dataset.r, custom, reason }) });
69
+ const post = async (resolution, custom) => {
70
+ let reason = card.querySelector('.reason')?.value;
71
+ if (!reason) reason = prompt('reason(必填):', '') || '';
72
+ if (!reason.trim()) return alert('reason 必填');
73
+ await api('/decide', { method: 'POST', body: JSON.stringify({ id: c.id, resolution, custom, reason }) });
47
74
  refresh();
75
+ };
76
+ card.querySelectorAll('button[data-r]').forEach((b) => b.onclick = async () => {
77
+ if (b.dataset.r === 'merge') {
78
+ const box = card.querySelector('.editbox');
79
+ box.style.display = 'block';
80
+ box.querySelector('.mtext').value = `${c.sides[0].text}\n—— + ——\n${c.sides[1].text}`;
81
+ box.querySelector('.mtext').focus();
82
+ return;
83
+ }
84
+ post(b.dataset.r, null);
48
85
  });
86
+ card.querySelector('.editbox .go')?.addEventListener('click', () => post('merge', card.querySelector('.mtext').value.trim()));
87
+ card.querySelector('.editbox .cancel')?.addEventListener('click', () => { card.querySelector('.editbox').style.display = 'none'; });
49
88
  app.appendChild(card);
50
89
  }
51
90
  if (!cs.length) app.innerHTML += '<p class="mut">no conflicts — run skillmkt merge &lt;a&gt; &lt;b&gt;</p>';
@@ -55,9 +94,38 @@ function render() {
55
94
  }
56
95
  if (tab === 'setup') {
57
96
  const h = S.harnesses || [];
58
- app.innerHTML = `<h3>setup</h3><div class="card">hub: <code>${esc(S.hub)}</code></div>
59
- ${h.map((x) => `<div class="card row"><b>${esc(x.id)}</b>${pill(x.status)}<span class="mut">${esc(x.primaryDir || '')}</span></div>`).join('')}
60
- <p class="mut">CLI 是主操作面;本面板用于可视裁决与矩阵审阅。token 只在本地 daemon 生命周期内有效。</p>`;
97
+ const cfg = await api('/config');
98
+ const installed = h.filter((x) => x.state === 'installed' && !x.detectOnly).map((x) => x.id);
99
+ const sel = new Set(cfg.default_targets?.length ? cfg.default_targets : installed);
100
+ app.innerHTML = `<h3>setup / init</h3><div class="card">hub: <code>${esc(S.hub)}</code></div>
101
+ <div class="card"><h3>LLM 端点</h3>
102
+ <div class="row"><button id="probe">探测本地端点</button><span id="probe-out" class="mut">${cfg.llm?.model ? `当前: ${esc(cfg.llm.model)} @ ${esc(cfg.llm.base_url)}` : '未配置'}</span></div>
103
+ <div id="eps"></div>
104
+ <div class="row" style="margin-top:8px"><input id="murl" placeholder="base_url(手动,如 http://localhost:8001/v1)" value="${esc(cfg.llm?.base_url || '')}"></div>
105
+ <div class="row"><input id="mmodel" placeholder="model id" value="${esc(cfg.llm?.model || '')}"></div>
106
+ <div class="row"><input id="mkey" placeholder="api_key(env:VAR 引用,不存真值;留空=无 key)" value="${esc(cfg.llm?.api_key || '')}"></div>
107
+ <div class="row"><button id="smoke">冒烟测试</button><span id="smoke-out" class="mut"></span></div></div>
108
+ <div class="card"><h3>默认投影目标</h3>
109
+ ${h.map((x) => `<label class="row" style="display:block"><input type="checkbox" data-h="${esc(x.id)}" ${sel.has(x.id) ? 'checked' : ''} ${x.state !== 'installed' ? 'disabled' : ''}> <b>${esc(x.id)}</b> ${pill(x.state || x.status)} <span class="mut">${esc(x.primaryDir || '')}</span></label>`).join('')}</div>
110
+ <div class="card"><button id="save">保存配置</button><span id="save-out" class="mut"></span></div>`;
111
+ app.querySelector('#probe').onclick = async () => {
112
+ app.querySelector('#probe-out').textContent = 'probing…';
113
+ const eps = await api('/probe');
114
+ app.querySelector('#eps').innerHTML = eps.flatMap((e) => e.models.slice(0, 6).map((m) => `<div class="row" style="cursor:pointer" data-b="${esc(e.base_url)}" data-m="${esc(m)}">· ${esc(e.name)}:${e.port} — ${esc(m)}</div>`)).join('') || '<p class="mut">未发现(8001/11434/1234/8000/8080/1337/5000)</p>';
115
+ app.querySelector('#probe-out').textContent = `${eps.length} 个端点`;
116
+ app.querySelectorAll('#eps [data-b]').forEach((d) => d.onclick = () => { app.querySelector('#murl').value = d.dataset.b; app.querySelector('#mmodel').value = d.dataset.m; });
117
+ };
118
+ app.querySelector('#smoke').onclick = async () => {
119
+ app.querySelector('#smoke-out').textContent = '…';
120
+ const r = await api('/llm-smoke', { method: 'POST', body: JSON.stringify({ base_url: app.querySelector('#murl').value, model: app.querySelector('#mmodel').value, api_key: app.querySelector('#mkey').value }) });
121
+ app.querySelector('#smoke-out').textContent = r.ok ? `✓ ${r.reply}` : `✗ ${r.error}`;
122
+ };
123
+ app.querySelector('#save').onclick = async () => {
124
+ const targets = [...app.querySelectorAll('[data-h]:checked')].map((x) => x.dataset.h);
125
+ const r = await api('/config', { method: 'POST', body: JSON.stringify({ llm: { base_url: app.querySelector('#murl').value || null, model: app.querySelector('#mmodel').value || null, api_key: app.querySelector('#mkey').value || undefined, concurrency: 2, timeout_ms: 60000 }, default_targets: targets }) });
126
+ app.querySelector('#save-out').textContent = r.ok ? ' ✓ 已写入 config.yml' : ` ✗ ${r.error}`;
127
+ refresh();
128
+ };
61
129
  }
62
130
  }
63
131
  refresh();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skillmkt",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Local-first agent skill manager: install, audit, merge, distribute.",
6
6
  "license": "MIT",