skillmkt 0.1.4 → 0.1.6

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.
@@ -2,7 +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
+ import { openURL, readDaemon } from '../lib/daemon.js';
6
6
  import { choose, confirm } from '../lib/prompt.js';
7
7
  import { ok, warn, fail, info } from '../lib/render.js';
8
8
 
@@ -25,15 +25,24 @@ export async function run(ctx) {
25
25
  writeConfig(ctx.hub, raw); // ui 偏好先落盘(web 页内继续改其余键)
26
26
 
27
27
  if (mode === 'web') {
28
- // daemon 就绪:setup 页完成探测+选模型+harness 勾选,全部经 /api/config 落盘
28
+ // 前台语义:本进程=服务器,开页后挂住流日志,Ctrl-C 连服务一起退
29
29
  try {
30
- const d = await ensureDaemon(ctx);
31
- const url = openURL(d, '/#setup');
30
+ const alive = (() => { const d = readDaemon(ctx.hub); return d && (() => { try { process.kill(d.pid, 0); return true; } catch { return false; } })() ? d : null; })();
31
+ if (alive) {
32
+ const url = openURL(alive, '/#setup');
33
+ ok(`Web 初始化已打开: ${url}(服务已在别的终端跑)`);
34
+ return 0;
35
+ }
36
+ const { startServer } = await import('./serve.js');
37
+ const srv = await startServer(ctx, { quiet: false });
38
+ const url = openURL({ port: srv.port, token: srv.token }, '/#setup');
32
39
  ok(`Web 初始化已打开: ${url}`);
33
- info('setup 页内:探测端点 → 选模型 → 勾 harness → 保存(写入 config.yml)');
40
+ info('setup 页内:扫描端点 → 选模型 → 勾 agent → 保存(写入 config.yml)');
41
+ info('服务前台运行中 — Ctrl-C 退出');
42
+ await new Promise(() => {});
34
43
  return 0;
35
44
  } catch (e) {
36
- warn(`daemon 不可用(${e.message.slice(0, 60)})——回退终端向导`);
45
+ warn(`服务起不来(${e.message.slice(0, 60)})——回退终端向导`);
37
46
  }
38
47
  }
39
48
 
@@ -6,7 +6,7 @@ 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, readConfig, writeConfig, registerSkill, updateLock } from '../lib/hub.js';
9
+ import { readLibrary, readLock, readConfig, writeConfig, registerSkill, updateLock, ensureHub } 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';
@@ -18,15 +18,10 @@ import { ok, info, fail } from '../lib/render.js';
18
18
  const PUB = path.join(new URL('.', import.meta.url).pathname, '../public');
19
19
  const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png', '.svg': 'image/svg+xml' };
20
20
 
21
- export async function run(ctx) {
21
+ // startServer — 可复用:serve 命令与 CLI 接管共用。返回 {port, token, server, emit, shutdown}
22
+ export async function startServer(ctx, { quiet = false, port = 0 } = {}) {
23
+ ensureHub(ctx.hub);
22
24
  const flags = ctx.flags.raw;
23
- if (flags.stop) {
24
- const d = readDaemon(ctx.hub);
25
- if (d) { try { process.kill(d.pid); } catch { /* dead */ } fs.rmSync(daemonFile(ctx.hub), { force: true }); ok('daemon stopped'); }
26
- else info('no daemon');
27
- return 0;
28
- }
29
-
30
25
  const token = crypto.randomBytes(16).toString('hex');
31
26
  const sse = new Set();
32
27
  const emit = (type, data) => { for (const res of sse) res.write(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`); };
@@ -34,7 +29,9 @@ export async function run(ctx) {
34
29
  const idleMs = (ctx.config.daemon?.idle_minutes ?? 30) * 60e3;
35
30
 
36
31
  const state = () => ({
37
- hub: ctx.hub, library: readLibrary(ctx.hub), lock: readLock(ctx.hub),
32
+ hub: ctx.hub,
33
+ initialized: (() => { const r = readConfig(ctx.hub)._raw; return !!(r.ui || r.llm || r.default_targets); })(),
34
+ library: readLibrary(ctx.hub), lock: readLock(ctx.hub),
38
35
  upstream: readUpstream(ctx.hub), conflicts: loadConflicts(ctx.hub),
39
36
  decisions: loadDecisions(ctx.hub), harnesses: ctx.harnesses,
40
37
  scans: fs.existsSync(path.join(ctx.hub, 'scans')) ? fs.readdirSync(path.join(ctx.hub, 'scans')).map((f) => readYAML(path.join(ctx.hub, 'scans', f))).filter(Boolean) : [],
@@ -50,7 +47,6 @@ export async function run(ctx) {
50
47
  };
51
48
  const body = (req) => new Promise((r) => { let b = ''; req.on('data', (c) => b += c); req.on('end', () => r(b || '{}')); });
52
49
 
53
- const quiet = !!flags.daemon;
54
50
  const server = http.createServer(async (req, res) => {
55
51
  lastActive = Date.now();
56
52
  const t0 = Date.now();
@@ -132,25 +128,40 @@ export async function run(ctx) {
132
128
  fs.createReadStream(file).pipe(res);
133
129
  });
134
130
 
135
- await new Promise((r) => server.listen(flags.port || 0, '127.0.0.1', r));
136
- const port = server.address().port;
137
- fs.writeFileSync(daemonFile(ctx.hub), JSON.stringify({ pid: process.pid, port, token, started: new Date().toISOString() }));
131
+ await new Promise((r) => server.listen(port, '127.0.0.1', r));
132
+ const realPort = server.address().port;
133
+ fs.writeFileSync(daemonFile(ctx.hub), JSON.stringify({ pid: process.pid, port: realPort, token, started: new Date().toISOString() }));
138
134
  const idle = setInterval(() => { if (Date.now() - lastActive > idleMs) { server.close(); process.exit(0); } }, 60e3);
139
135
  idle.unref();
140
136
 
141
- // 退出语义:SIGINT/SIGTERM/正常 close → 摘 daemon.json(前台模式主语义)
142
137
  const shutdown = () => {
143
- console.log('\nserve: shutting down…');
138
+ clearInterval(idle);
144
139
  fs.rmSync(daemonFile(ctx.hub), { force: true });
145
140
  server.close(() => process.exit(0));
146
141
  setTimeout(() => process.exit(0), 800).unref();
147
142
  };
148
143
  process.on('SIGINT', shutdown);
149
144
  process.on('SIGTERM', shutdown);
145
+ return { server, port: realPort, token, emit, shutdown };
146
+ }
150
147
 
151
- if (flags.daemon) { console.log(`daemon ready :${port}`); await new Promise(() => {}); }
152
- console.log(`serve: http://127.0.0.1:${port}?token=${token}`);
153
- console.log(` foreground — Ctrl-C 退出(idle ${ctx.config.daemon?.idle_minutes ?? 30}m 自退;分离模式见 --daemon)`);
148
+ export async function run(ctx) {
149
+ const flags = ctx.flags.raw;
150
+ if (flags.stop) {
151
+ const d = readDaemon(ctx.hub);
152
+ if (d) { try { process.kill(d.pid); } catch { /* dead */ } fs.rmSync(daemonFile(ctx.hub), { force: true }); ok('daemon stopped'); }
153
+ else info('no daemon');
154
+ return 0;
155
+ }
156
+ // 已有前台/分离实例在跑 → 不重复起,报地址
157
+ const existing = readDaemon(ctx.hub);
158
+ if (existing && existing.pid !== process.pid) {
159
+ try { process.kill(existing.pid, 0); info(`已在跑: http://127.0.0.1:${existing.port}/?token=${existing.token}(--stop 停掉)`); return 0; } catch { /* stale */ }
160
+ }
161
+ const d = await startServer(ctx, { quiet: !!flags.daemon, port: flags.port || 0 });
162
+ if (flags.daemon) { console.log(`daemon ready :${d.port}`); await new Promise(() => {}); }
163
+ console.log(`serve: http://127.0.0.1:${d.port}/?token=${d.token}`);
164
+ console.log(` 前台运行 — Ctrl-C 退出(idle ${ctx.config.daemon?.idle_minutes ?? 30}m 自退)`);
154
165
  await new Promise(() => {});
155
166
  return 0;
156
167
  }
@@ -29,19 +29,29 @@ export async function ensureDaemon(ctx) {
29
29
  }
30
30
 
31
31
  export function openURL(d, route = '/') {
32
- const url = `http://127.0.0.1:${d.port}${route}?token=${d.token}`;
32
+ // token 必须进 ?search(location.search 可读);#fragment 只带 tab 名
33
+ const frag = route.includes('#') ? `#${route.split('#')[1]}` : '';
34
+ const url = `http://127.0.0.1:${d.port}/?token=${d.token}${frag}`;
33
35
  try { execFileSync('open', [url]); } catch { /* linux: xdg-open */ try { execFileSync('xdg-open', [url]); } catch { /* noop */ } }
34
36
  return url;
35
37
  }
36
38
 
37
- // CLI 自动接管:TTY + 未禁 ui + daemon 可用 → 开浏览器返回 true;否则 false 走终端
39
+ // CLI 接管:有活 daemon→开页复用(返回 true 让调用方退出);
40
+ // 没有→当前进程前台起服务+开页+挂住流日志(Ctrl-C 连服务一起退,永不返回)
38
41
  export async function maybeHandoff(ctx, route = '/') {
39
42
  if (!process.stdout.isTTY || ctx.flags.raw.cli || ctx.flags.raw.noUi) return false;
40
43
  if (ctx.flags.raw.ui === false) return false;
44
+ const d = readDaemon(ctx.hub);
45
+ if (d && alive(d.pid)) {
46
+ console.log(`opened ${openURL(d, route)}(服务已在跑,Ctrl-C 那个终端的 serve 可停)`);
47
+ return true;
48
+ }
41
49
  try {
42
- const d = await ensureDaemon(ctx);
43
- const url = openURL(d, route);
44
- console.log(`opened ${url}`);
50
+ const { startServer } = await import('../commands/serve.js');
51
+ const srv = await startServer(ctx, { quiet: false });
52
+ console.log(`opened ${openURL({ port: srv.port, token: srv.token }, route)}`);
53
+ console.log(' 服务前台运行中 — 操作日志见下方,Ctrl-C 退出');
54
+ await new Promise(() => {}); // 挂住:本进程=服务器
45
55
  return true;
46
56
  } catch { return false; }
47
57
  }
@@ -3,12 +3,13 @@ const T = new URLSearchParams(location.search).get('token') || '';
3
3
  const api = async (p, opt) => (await fetch(`/api${p}${p.includes('?') ? '&' : '?'}token=${T}`, { headers: { authorization: `Bearer ${T}` }, ...opt })).json();
4
4
  const el = (h) => { const d = document.createElement('div'); d.innerHTML = h; return d.firstElementChild; };
5
5
  const esc = (s) => String(s ?? '').replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
6
- let S = null, tab = location.hash.slice(1) || 'skills';
6
+ let S = null, tab = location.hash.slice(1).split('?')[0] || 'skills';
7
7
 
8
8
  async function refresh() {
9
9
  try { S = await api('/state'); }
10
10
  catch (e) { document.getElementById('app').innerHTML = `<p class="pill bad">/api/state 请求失败:${esc(e.message)}——daemon 挂了?重跑 skillmkt serve</p>`; return; }
11
11
  if (S?.error) { document.getElementById('app').innerHTML = `<p class="pill bad">${esc(S.error)}——URL 里的 token 已失效,重跑 skillmkt serve 拿新链接</p>`; return; }
12
+ if (!location.hash && !S.initialized) { tab = 'setup'; location.hash = 'setup'; } // 未初始化→setup
12
13
  render();
13
14
  }
14
15
  const syncTabs = () => document.querySelectorAll('nav [data-t]').forEach((x) => x.classList.toggle('on', x.dataset.t === tab));
@@ -33,17 +34,17 @@ async function render() {
33
34
 
34
35
  if (tab === 'skills') {
35
36
  const skills = Object.entries(S.library.skills || {});
36
- app.innerHTML = `<h2>已受管 skills(${skills.length})</h2>` + (skills.map(([n, s]) => `
37
+ app.innerHTML = `<h2>已安装 skills(${skills.length})</h2>` + (skills.map(([n, s]) => `
37
38
  <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')}
38
- <span class="mut" style="margin-left:auto">${(s.targets || []).join('、') || '无目标'}</span>
39
- <button data-tg="${esc(n)}">编辑目标</button></div>
39
+ <span class="mut" style="margin-left:auto">装在:${(s.targets || []).join('、') || '无'}</span>
40
+ <button data-tg="${esc(n)}">安装位置</button></div>
40
41
  <div class="tgbox" data-box="${esc(n)}" style="display:none;margin-top:8px"></div></div>`).join('') || '<p class="mut">还没有受管 skill——skillmkt install &lt;ref&gt;</p>');
41
42
  app.querySelectorAll('[data-tg]').forEach((b) => b.onclick = () => {
42
43
  const box = app.querySelector(`[data-box="${b.dataset.tg}"]`);
43
44
  if (box.style.display === 'block') { box.style.display = 'none'; return; }
44
45
  const s = S.library.skills[b.dataset.tg];
45
46
  box.style.display = 'block';
46
- box.innerHTML = `<label class="field">投影到(勾选后立即复制过去)</label>` +
47
+ box.innerHTML = `<label class="field">装到这些 agent(勾选后立即复制生效)</label>` +
47
48
  (S.harnesses || []).filter((x) => x.state === 'installed' && !x.detectOnly).map((x) =>
48
49
  `<label class="row"><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('')
49
50
  + `<div class="row" style="margin-top:8px"><button class="primary tgo">应用目标</button><span class="tout mut"></span></div>`;
@@ -54,9 +55,9 @@ async function render() {
54
55
  refresh();
55
56
  };
56
57
  });
57
- app.innerHTML += `<h2>harness 探测</h2>` + (S.harnesses || []).map((h) => `<div class="card row"><b>${esc(h.id)}</b>${pill(h.state)}<span class="mut">${esc(h.primaryDir || h.dirs?.[0] || '')}</span></div>`).join('');
58
+ app.innerHTML += `<h2>检测到的 agent</h2>` + (S.harnesses || []).map((h) => `<div class="card row"><b>${esc(h.id)}</b>${pill(h.state)}<span class="mut">${esc(h.primaryDir || h.dirs?.[0] || '')}</span></div>`).join('');
58
59
  const up = S.upstream.skills || {};
59
- if (Object.keys(up).length) app.innerHTML += `<h2>上游状态</h2>` + 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('');
60
+ if (Object.keys(up).length) app.innerHTML += `<h2>可更新</h2>` + 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('');
60
61
  }
61
62
 
62
63
  if (tab === 'conflicts') {
@@ -116,17 +117,17 @@ async function render() {
116
117
  const sel = new Set(cfg.default_targets?.length ? cfg.default_targets : installed);
117
118
  app.innerHTML = `<h2>初始化与配置</h2>
118
119
  <div class="card"><b>LLM 端点</b><span class="mut" id="cur">${cfg.llm?.model ? `(当前:${esc(cfg.llm.model)} @ ${esc(cfg.llm.base_url)})` : '(未配置)'}</span>
119
- <div class="row" style="margin-top:8px"><button id="probe">探测本地端点</button><span id="probe-out" class="mut"></span></div>
120
+ <div class="row" style="margin-top:8px"><button id="probe">扫描本地 LLM 服务</button><span id="probe-out" class="mut"></span></div>
120
121
  <div id="eps"></div>
121
122
  <label class="field">base_url</label><input type="text" id="murl" value="${esc(cfg.llm?.base_url || '')}">
122
123
  <label class="field">model</label><input type="text" id="mmodel" value="${esc(cfg.llm?.model || '')}">
123
124
  <label class="field">api_key(env:VAR 引用,不存真值;留空=无 key)</label><input type="text" id="mkey" value="${esc(cfg.llm?.api_key || '')}">
124
- <div class="row" style="margin-top:8px"><button id="smoke">冒烟测试</button><span id="smoke-out" class="mut"></span></div></div>
125
- <div class="card"><b>默认投影目标</b><span class="mut">(新装 skill 默认投到这里)</span>
125
+ <div class="row" style="margin-top:8px"><button id="smoke">测试连接</button><span id="smoke-out" class="mut"></span></div></div>
126
+ <div class="card"><b>skill 装到哪些 agent</b><span class="mut">(勾选后,新装的 skill 会复制进这些 agent 的 skills 目录)</span>
126
127
  ${h.map((x) => `<label class="row"><input type="checkbox" data-h="${esc(x.id)}" ${sel.has(x.id) ? 'checked' : ''} ${x.state !== 'installed' ? 'disabled' : ''}> ${esc(x.id)} ${pill(x.state)} <span class="mut">${esc(x.primaryDir || '')}</span></label>`).join('')}</div>
127
128
  <div class="card"><button class="primary" id="save">保存配置</button><span id="save-out" class="mut"></span></div>`;
128
129
  app.querySelector('#probe').onclick = async () => {
129
- app.querySelector('#probe-out').textContent = '探测中…';
130
+ app.querySelector('#probe-out').textContent = '扫描中…';
130
131
  const eps = await api('/probe');
131
132
  app.querySelector('#eps').innerHTML = eps.flatMap((e) => e.models.slice(0, 6).map((m) => `<div class="ep" data-b="${esc(e.base_url)}" data-m="${esc(m)}">${esc(e.name)}:${e.port} — <code>${esc(m)}</code></div>`)).join('') || '<p class="mut">未发现(8001 / 11434 / 1234 / 8000 / 8080 / 1337 / 5000)</p>';
132
133
  app.querySelector('#probe-out').textContent = `${eps.length} 个端点`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skillmkt",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "type": "module",
5
5
  "description": "Local-first agent skill manager: install, audit, merge, distribute.",
6
6
  "license": "MIT",