skillmkt 0.2.4 → 0.2.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.
@@ -47,7 +47,7 @@ export async function run(ctx) {
47
47
 
48
48
  // LLM 端点探测(只在用户进入配置步骤时探测——铁律)
49
49
  info('探测本地 LLM 服务…');
50
- const found = await probeEndpoints();
50
+ const found = await probeEndpoints(400, { extraBases: [ctx.config.llm?.base_url] });
51
51
  let base_url = null, model = null;
52
52
 
53
53
  if (found.length) {
@@ -69,7 +69,7 @@ export async function run(ctx) {
69
69
  ({ base_url, model } = sel.v);
70
70
  }
71
71
  } else {
72
- info('未发现本地 LLM 服务(8001/11434/1234/8000/8080/1337/5000)');
72
+ info('未发现本地 LLM 服务(已扫本机所有监听端口)');
73
73
  info('→ 手动:skillmkt config set llm.base_url http://host:port/v1');
74
74
  }
75
75
 
@@ -10,7 +10,7 @@ import { readLibrary, readLock, readConfig, writeConfig, registerSkill, updateLo
10
10
  import { readUpstream } from '../lib/state.js';
11
11
  import { readYAML } from '../../pipeline/lib/util.js';
12
12
  import { detectHarnesses } from '../lib/scanner.js';
13
- import { probeEndpoints, chat } from '../lib/llm.js';
13
+ import { probeEndpoints, chat, upsertEnvFile, resolveKeyRef } from '../lib/llm.js';
14
14
  import { projectSkill, unproject, targetDirFor } from '../lib/project.js';
15
15
  import { treeHash } from '../lib/package.js';
16
16
  import { ok, info } from '../lib/render.js';
@@ -45,7 +45,7 @@ export async function startServer(ctx, { quiet = false, port = 0 } = {}) {
45
45
  'GET /api/conflicts': () => loadConflicts(ctx.hub),
46
46
  'GET /api/decisions': () => loadDecisions(ctx.hub),
47
47
  'GET /api/config': () => readConfig(ctx.hub)._raw,
48
- 'GET /api/probe': async () => probeEndpoints(), // init 用:探测 LLM 端点
48
+ 'GET /api/probe': async () => probeEndpoints(400, { extraBases: [readConfig(ctx.hub).llm?.base_url] }),
49
49
  };
50
50
  const body = (req) => new Promise((r) => { let b = ''; req.on('data', (c) => b += c); req.on('end', () => r(b || '{}')); });
51
51
 
@@ -85,16 +85,24 @@ export async function startServer(ctx, { quiet = false, port = 0 } = {}) {
85
85
  }
86
86
  if (u.pathname === '/api/config') { // init:合并写 config
87
87
  const raw = readConfig(ctx.hub)._raw;
88
- if (b.llm !== undefined) raw.llm = b.llm;
88
+ let keyEnv = false;
89
+ if (b.llm !== undefined) {
90
+ if (b.llm.api_key && !String(b.llm.api_key).startsWith('env:')) {
91
+ upsertEnvFile(path.join(ctx.hub, '.env'), 'SKILLMKT_LLM_KEY', b.llm.api_key);
92
+ b.llm.api_key = 'env:SKILLMKT_LLM_KEY'; // config.yml 只留引用
93
+ keyEnv = true;
94
+ }
95
+ raw.llm = b.llm;
96
+ }
89
97
  if (b.ui !== undefined) raw.ui = b.ui;
90
98
  if (b.default_targets !== undefined) raw.default_targets = b.default_targets;
91
99
  if (b.policy) raw.policy = b.policy;
92
100
  writeConfig(ctx.hub, raw);
93
101
  emit('config', {});
94
- return res.end('{"ok":true}');
102
+ return res.end(JSON.stringify({ ok: true, key_env: keyEnv }));
95
103
  }
96
104
  if (u.pathname === '/api/llm-smoke') { // init 冒烟
97
- const key = b.api_key?.startsWith('env:') ? process.env[b.api_key.slice(4)] ?? '' : b.api_key || '';
105
+ const key = resolveKeyRef(b.api_key, ctx); // env: 引用走 hub/.env 等解析链
98
106
  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 });
99
107
  return res.end(JSON.stringify({ ok: true, reply: r.trim().slice(0, 80) }));
100
108
  }
package/client/lib/llm.js CHANGED
@@ -2,11 +2,12 @@
2
2
  // 批次6 补:chatJSON 真调用、probeEndpoints、端口探测。铁律:非 init/config 零探测。
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import { execFileSync } from 'node:child_process';
5
6
 
6
- function loadDotEnv(cwd) {
7
+ function loadDotEnv(file) {
7
8
  try {
8
9
  const out = {};
9
- for (const line of fs.readFileSync(path.join(cwd, '.env'), 'utf8').split('\n')) {
10
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
10
11
  const m = line.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)\s*$/);
11
12
  if (m && !line.trim().startsWith('#')) out[m[1]] = m[2].replace(/^["']|["']$/g, '');
12
13
  }
@@ -14,9 +15,34 @@ function loadDotEnv(cwd) {
14
15
  } catch { return {}; }
15
16
  }
16
17
 
18
+ // upsert KEY=value 到 env 文件(600 权限)——web 保存明文密钥时落到 hub/.env,config.yml 只留 env: 引用
19
+ export function upsertEnvFile(file, key, value) {
20
+ let lines = [];
21
+ try { lines = fs.readFileSync(file, 'utf8').split('\n'); } catch { /* 新文件 */ }
22
+ const idx = lines.findIndex((l) => l.startsWith(`${key}=`));
23
+ const entry = `${key}=${value}`;
24
+ if (idx >= 0) lines[idx] = entry; else lines.push(entry);
25
+ fs.mkdirSync(path.dirname(file), { recursive: true });
26
+ fs.writeFileSync(file, lines.filter(Boolean).join('\n') + '\n', { mode: 0o600 });
27
+ try { fs.chmodSync(file, 0o600); } catch { /* windows 无 mode */ }
28
+ }
29
+
30
+ // "env:VAR" → 真值(hub/.env + cwd/.env + 环境变量);裸值原样返回
31
+ export function resolveKeyRef(keyRef, ctx) {
32
+ if (!keyRef?.startsWith('env:')) return keyRef || '';
33
+ const v = keyRef.slice(4);
34
+ const env = {
35
+ ...(ctx?.hub ? loadDotEnv(path.join(ctx.hub, '.env')) : {}),
36
+ ...loadDotEnv(path.join(ctx?.cwd ?? '.', '.env')),
37
+ ...process.env,
38
+ };
39
+ return env[v] ?? '';
40
+ }
41
+
17
42
  export function resolveLLM(ctx) {
18
43
  if (ctx.flags.noLlm) return null;
19
- const env = { ...loadDotEnv(ctx.cwd), ...process.env };
44
+ // 解析链:hub/.env < cwd/.env < 真环境变量(后者覆盖前者)
45
+ const env = { ...(ctx.hub ? loadDotEnv(path.join(ctx.hub, '.env')) : {}), ...loadDotEnv(path.join(ctx.cwd, '.env')), ...process.env };
20
46
  const cfg = ctx.config.llm || {};
21
47
  const base = ctx.flags.baseUrl || env.SKILLMKT_LLM_BASE_URL || env.OMLX_BASE_URL || cfg.base_url;
22
48
  const model = ctx.flags.model || env.SKILLMKT_LLM_MODEL || env.OMLX_MODEL || cfg.model;
@@ -57,6 +83,21 @@ export async function chat(llm, { system = '', user, maxTokens = 64, temperature
57
83
 
58
84
  export const LLM_PROBES = [8001, 11434, 1234, 8000, 8080, 1337, 5000];
59
85
 
86
+ // 本机所有 LISTEN 端口(lsof)——模型服务换任意端口都能被扫到;拿不到就只用固定列表
87
+ function listeningPorts() {
88
+ try {
89
+ const out = execFileSync('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN'], { encoding: 'utf8', timeout: 4000 });
90
+ const ports = new Set();
91
+ for (const line of out.split('\n')) {
92
+ const m = line.match(/(?:127\.0\.0\.1|localhost|\*|\[?::1\]?):(\d+)/i);
93
+ if (m) ports.add(+m[1]);
94
+ }
95
+ return [...ports];
96
+ } catch { return []; }
97
+ }
98
+
99
+ const portOf = (base) => { try { return +(new URL(base).port || 0) || null; } catch { return null; } };
100
+
60
101
  // 识别服务实现——有特征端点才冠名,认不出如实标"OpenAI 兼容服务"(oMLX 跑在 1234 时不该叫 LM Studio)
61
102
  async function identifyImpl(port, timeoutMs) {
62
103
  const get = async (p) => {
@@ -70,11 +111,16 @@ async function identifyImpl(port, timeoutMs) {
70
111
  return 'OpenAI 兼容服务';
71
112
  }
72
113
 
73
- // 仅 init/config 使用——并发扫端口。/v1/models 通了即收录;
114
+ // 仅 init/config 使用——候选端口 = 常见端口 ∪ 本机全部监听端口 ∪ env/config 已知 base_url 端口,
115
+ // 并发试 /v1/models。响应里 data 不是数组则不算 LLM 端点(防止 dev server 等返回 200 被误收录);
74
116
  // 401/403 时用已知环境 key 重试,仍不通则标 needs_key 保留(别静默漏掉 oMLX 这类要 key 的本地服务)
75
- export async function probeEndpoints(timeoutMs = 400) {
117
+ export async function probeEndpoints(timeoutMs = 400, { extraBases = [] } = {}) {
118
+ const candidates = new Set(LLM_PROBES);
119
+ for (const p of listeningPorts()) candidates.add(p);
120
+ for (const v of ['SKILLMKT_LLM_BASE_URL', 'OMLX_BASE_URL']) { const p = portOf(process.env[v]); if (p) candidates.add(p); }
121
+ for (const b of extraBases) { const p = portOf(b); if (p) candidates.add(p); }
76
122
  const envKeys = ['SKILLMKT_LLM_API_KEY', 'OMLX_API_KEY'].map((v) => process.env[v]).filter(Boolean);
77
- const results = await Promise.allSettled(LLM_PROBES.map(async (port) => {
123
+ const results = await Promise.allSettled([...candidates].map(async (port) => {
78
124
  const base = `http://localhost:${port}/v1`;
79
125
  const tryModels = async (key) => {
80
126
  const ctrl = new AbortController();
@@ -91,10 +137,17 @@ export async function probeEndpoints(timeoutMs = 400) {
91
137
  if (res.status === 401 || res.status === 403) {
92
138
  for (const k of envKeys) { res = await tryModels(k); if (res?.ok) break; }
93
139
  }
140
+ if (!res.ok) {
141
+ // 只有 OpenAI 风格错误体({"error":{...}})才算"要 key 的 LLM 端点"——普通鉴权服务不误报
142
+ const err = await res.json().catch(() => null);
143
+ if (!err?.error) return null;
144
+ const name = await identifyImpl(port, timeoutMs);
145
+ return { name, port, base_url: base, models: [], needs_key: true };
146
+ }
147
+ const data = await res.json().catch(() => null);
148
+ if (!Array.isArray(data?.data)) return null; // 200 但不是 OpenAI models 响应 → 非 LLM 端点
94
149
  const name = await identifyImpl(port, timeoutMs);
95
- if (!res.ok) return { name, port, base_url: base, models: [], needs_key: true };
96
- const data = await res.json();
97
- return { name, port, base_url: base, models: (data.data || []).map((m) => m.id) };
150
+ return { name, port, base_url: base, models: data.data.map((m) => m.id) };
98
151
  }));
99
152
  return results.map((r) => r.value).filter(Boolean);
100
153
  }
@@ -151,7 +151,7 @@ async function render() {
151
151
  <label class="field">模型名称</label><input type="text" id="mmodel" list="model-opts" placeholder="可输入关键字搜索,扫描后自动列出发现的模型" value="${esc(cfg.llm?.model || '')}">
152
152
  <datalist id="model-opts"></datalist>
153
153
  <label class="field">访问密钥</label><input type="text" id="mkey" value="${esc(cfg.llm?.api_key || '')}">
154
- <p class="mut">可填 <code>env:变量名</code> 引用环境变量,密钥真值不会写进配置文件;本机服务一般留空即可。</p>
154
+ <p class="mut">本机服务一般留空。填了明文密钥会存到 <code>~/.skillmkt/.env</code>(仅本人可读),配置文件里只留引用——不会以明文落进 config.yml。</p>
155
155
  <div class="row"><button id="smoke">测试连接</button><span id="smoke-out" class="mut"></span></div></div>
156
156
  <div class="card"><h3>第 2 步 · skill 默认安装位置</h3>
157
157
  <p class="mut">勾选的 AI 工具会在你安装新 skill 时自动收到一份副本。已勾过的话保存即生效。</p>
@@ -170,7 +170,7 @@ async function render() {
170
170
  app.querySelector('#eps').innerHTML = eps.map((e) => e.needs_key
171
171
  ? `<div class="ep" data-b="${esc(e.base_url)}">${esc(e.name)}:${e.port} — <span class="mut">需要密钥(点这行填地址,再填密钥、测试连接)</span></div>`
172
172
  : `<div class="ep" data-b="${esc(e.base_url)}">${esc(e.name)}:${e.port} — ${e.models.length} 个模型(在下方「模型名称」下拉框里搜索)</div>`).join('')
173
- || '<p class="mut" style="margin-top:8px">没扫到——请确认模型服务已启动(会检查 8001 / 11434 / 1234 / 8000 / 8080 / 1337 / 5000 端口)</p>';
173
+ || '<p class="mut" style="margin-top:8px">没扫到——已尝试本机所有监听端口。确认模型服务已启动,或直接把服务地址填到下面</p>';
174
174
  app.querySelector('#probe-out').textContent = `发现 ${eps.length} 个服务、${modelMap.size} 个模型`;
175
175
  app.querySelectorAll('#eps [data-b]').forEach((d) => d.onclick = () => {
176
176
  app.querySelectorAll('#eps .ep').forEach((x) => x.classList.remove('sel'));
@@ -193,7 +193,7 @@ async function render() {
193
193
  app.querySelector('#save').onclick = async () => {
194
194
  const targets = [...app.querySelectorAll('[data-h]:checked')].map((x) => x.dataset.h);
195
195
  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 }) });
196
- app.querySelector('#save-out').textContent = r.ok ? '已保存到 config.yml' : `保存失败:${r.error}`;
196
+ app.querySelector('#save-out').textContent = r.ok ? `已保存到 config.yml${r.key_env ? ',密钥存入 .env' : ''}` : `保存失败:${r.error}`;
197
197
  refresh();
198
198
  };
199
199
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skillmkt",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "description": "Local-first agent skill manager: install, audit, merge, distribute.",
6
6
  "license": "MIT",