pi-web-ui 0.112.0 → 0.113.1

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +1 -7
  3. package/README.zh-CN.md +1 -7
  4. package/README.zh-TW.md +1 -7
  5. package/bin/pi-web-ui.mjs +423 -50
  6. package/dist/gh-comment-781.md +5 -0
  7. package/dist/server/agent-service-daemon.js +29 -4
  8. package/dist/server/agent-service.js +222 -36
  9. package/dist/server/canvas/canvas-agent-tool.js +2 -0
  10. package/dist/server/canvas/canvas-orchestrator.js +40 -1
  11. package/dist/server/canvas/pstack-skills-data.js +498 -0
  12. package/dist/server/control-socket.js +6 -2
  13. package/dist/server/dispatch-domain-handlers.js +36 -11
  14. package/dist/server/dsh/dsh-agent-service.js +52 -4
  15. package/dist/server/durable/durable-driver.js +37 -98
  16. package/dist/server/durable/durable-event-projector.js +253 -0
  17. package/dist/server/engine-probe.js +35 -11
  18. package/dist/server/files-service.js +72 -8
  19. package/dist/server/index.js +74 -50
  20. package/dist/server/model-admin.js +185 -63
  21. package/dist/server/plugins.js +10 -6
  22. package/dist/server/remote-ssh-service.js +110 -12
  23. package/dist/server/serialize.js +1 -1
  24. package/dist/server/settings-service.js +36 -48
  25. package/dist/server/setup-page.js +632 -0
  26. package/dist/server/skill-discovery.js +361 -59
  27. package/dist/server/skill-maintenance.js +231 -0
  28. package/dist/server/skill-tool.js +32 -3
  29. package/dist/server/soft-cap.js +29 -7
  30. package/dist/server/subagents.js +246 -31
  31. package/dist/server/tool-host-factories.js +2 -0
  32. package/dist/server/tool-manager.js +106 -28
  33. package/dist/server/universal/drivers/claude-code.js +96 -4
  34. package/dist/server/universal/universal-session.js +19 -0
  35. package/dist/server/webui-context.js +6 -6
  36. package/dist/test-artifact.md +9 -0
  37. package/dist/test-preview-modal.md +11 -0
  38. package/dist/test-report.html +20 -0
  39. package/package.json +1 -1
  40. package/plugin-sdk/index.d.ts +17 -3
  41. package/plugins/catalog.json +10 -0
  42. package/web/dist/assets/{TerminalPanel-Dqr1dK28.js → TerminalPanel-Ci55JtJL.js} +2 -2
  43. package/web/dist/assets/index-ByiO9f-N.js +2008 -0
  44. package/web/dist/assets/index-ycGLh4a4.css +1 -0
  45. package/web/dist/index.html +2 -2
  46. package/web/dist/sw.js +1 -1
  47. package/web/dist/assets/index-Dh8BX-lP.js +0 -720
  48. package/web/dist/assets/index-DqrC1I_a.css +0 -1
@@ -129,6 +129,12 @@ export function mergeProviderConfigEntry(prevEntry, config, models) {
129
129
  merged.maxTokens = Number(model.maxTokens);
130
130
  else
131
131
  delete merged.maxTokens;
132
+ // thinkingLevelMap:表单带了就覆盖,没带(undefined)= 保留磁盘上的手写映射,
133
+ // 与 api/baseUrl/cost/compat 同语义。注意不能 `else delete`——那会把用户在
134
+ // models.json 里手写的 xhigh/max 映射抹掉,档位又会退回 off…high。
135
+ const thinkingLevelMap = sanitizeThinkingLevelMap(model.thinkingLevelMap);
136
+ if (thinkingLevelMap)
137
+ merged.thinkingLevelMap = thinkingLevelMap;
132
138
  return merged;
133
139
  });
134
140
  const mergedEntry = { ...prevEntry };
@@ -193,11 +199,173 @@ export function detectReasoningCapability(id, rawMeta) {
193
199
  ];
194
200
  return REASONING_PATTERNS.some((pattern) => pattern.test(lower));
195
201
  }
202
+ // ---------------------------------------------------------------------------
203
+ // 思考档位(models.json 的模型级 thinkingLevelMap)
204
+ // ---------------------------------------------------------------------------
205
+ /** pi-ai 的思考档位,同时也是 `thinkingLevelMap` 认识的全部键(顺序 = 下拉顺序)。 */
206
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
207
+ /** pi-ai 默认开放给「推理模型」的档位(没有 thinkingLevelMap 时就是这个集合)。 */
208
+ const DEFAULT_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
209
+ /** 网关/推理端点常见的档位字面值 → pi 档位(查表前先归一化,见 normalizeLevelToken)。 */
210
+ const THINKING_LEVEL_ALIASES = {
211
+ off: "off",
212
+ none: "off",
213
+ no: "off",
214
+ "none-thinking": "off",
215
+ nothink: "off",
216
+ "no-think": "off",
217
+ disabled: "off",
218
+ disable: "off",
219
+ minimal: "minimal",
220
+ min: "minimal",
221
+ minimum: "minimal",
222
+ low: "low",
223
+ medium: "medium",
224
+ med: "medium",
225
+ mid: "medium",
226
+ middle: "medium",
227
+ high: "high",
228
+ xhigh: "xhigh",
229
+ "x-high": "xhigh",
230
+ "extra-high": "xhigh",
231
+ "very-high": "xhigh",
232
+ max: "max",
233
+ maximum: "max",
234
+ ultra: "max",
235
+ };
236
+ /** `/v1/models` 条目里可能携带推理档位的字段名(各家字段拼写不一)。 */
237
+ const THINKING_LEVEL_META_KEYS = [
238
+ "reasoning_levels",
239
+ "reasoningLevels",
240
+ "supported_reasoning_levels",
241
+ "supportedReasoningLevels",
242
+ "thinking_levels",
243
+ "supported_thinking_levels",
244
+ "supportedThinkingLevels",
245
+ ];
246
+ function normalizeLevelToken(token) {
247
+ return token
248
+ .trim()
249
+ .toLowerCase()
250
+ .replace(/[\s_]+/g, "-");
251
+ }
252
+ /** 档位元数据可能是数组、对象数组(`.effort`)、字典或逗号串——统一摊平成字面值列表。 */
253
+ function collectLevelTokens(value, out, depth = 0) {
254
+ if (depth > 2 || value === null || value === undefined)
255
+ return;
256
+ if (typeof value === "string") {
257
+ for (const part of value.split(/[,;|]/))
258
+ if (part.trim())
259
+ out.push(part);
260
+ return;
261
+ }
262
+ if (Array.isArray(value)) {
263
+ for (const item of value) {
264
+ if (typeof item === "string") {
265
+ out.push(item);
266
+ continue;
267
+ }
268
+ if (item && typeof item === "object") {
269
+ const row = item;
270
+ for (const key of ["effort", "level", "name", "id", "value", "type"]) {
271
+ if (typeof row[key] === "string") {
272
+ out.push(row[key]);
273
+ break;
274
+ }
275
+ }
276
+ }
277
+ }
278
+ return;
279
+ }
280
+ if (typeof value === "object") {
281
+ const row = value;
282
+ // 形如 { levels: [...] } / { supported: [...] } 的包裹
283
+ for (const key of ["levels", "values", "supported"]) {
284
+ if (key in row) {
285
+ collectLevelTokens(row[key], out, depth + 1);
286
+ return;
287
+ }
288
+ }
289
+ // 形如 { low: true, high: {…} } 的字典(false/null 表示不支持)
290
+ for (const [key, val] of Object.entries(row)) {
291
+ if (val === false || val === null || val === undefined)
292
+ continue;
293
+ out.push(key);
294
+ }
295
+ }
296
+ }
297
+ /** 从网关 `/models` 条目的推理档位元数据推导 pi-ai 的模型级 `thinkingLevelMap`。
298
+ *
299
+ * 背景:pi-ai 的 `getSupportedThinkingLevels()` 只有在模型带 `thinkingLevelMap`
300
+ * 且 `xhigh` / `max` 有显式映射时才开放这两档(见 pi-ai dist/models.js),否则
301
+ * 自定义服务商(vLLM / 聚合网关)永远只能选到 `off`…`high`。网关自己在
302
+ * `reasoning_levels` / `supported_reasoning_levels[].effort` 里报了能力,这里就
303
+ * 把它翻译成 pi 的映射:报了的档位映射成网关字面值,没报的显式写 `null`(= 不支持)。
304
+ *
305
+ * 两条保守规则:
306
+ * - `off` 永不隐藏(不写 `null`):关掉思考总是合法的,而且多数网关也没有
307
+ * `none` / `off` 这个字面值;只有在网关明确报了这类字面值时才映射过去。
308
+ * - 推导结果与 pi 默认能力(`off` + `minimal/low/medium/high`)完全一致时不返回
309
+ * 任何映射,避免每次刷新都把 models.json 无谓改写一遍。
310
+ *
311
+ * 纯函数,单测见 tests/unit/model-admin-thinking-levels.test.ts。
312
+ */
313
+ export function buildThinkingLevelMapFromMeta(raw) {
314
+ const meta = raw ?? {};
315
+ const tokens = [];
316
+ for (const key of THINKING_LEVEL_META_KEYS) {
317
+ if (key in meta)
318
+ collectLevelTokens(meta[key], tokens);
319
+ }
320
+ if (tokens.length === 0)
321
+ return undefined;
322
+ const advertised = new Map();
323
+ for (const token of tokens) {
324
+ const level = THINKING_LEVEL_ALIASES[normalizeLevelToken(token)];
325
+ if (level && !advertised.has(level))
326
+ advertised.set(level, token.trim());
327
+ }
328
+ // 只报了「关思考」类字面值 = 这模型压根不推理,别当成档位元数据。
329
+ if (![...advertised.keys()].some((level) => level !== "off"))
330
+ return undefined;
331
+ const map = {};
332
+ for (const level of THINKING_LEVELS) {
333
+ if (level === "off") {
334
+ const offLiteral = advertised.get("off");
335
+ if (offLiteral)
336
+ map.off = offLiteral;
337
+ continue;
338
+ }
339
+ map[level] = advertised.get(level) ?? null;
340
+ }
341
+ const enabled = THINKING_LEVELS.filter((level) => map[level] !== null);
342
+ const sameAsDefault = enabled.length === DEFAULT_THINKING_LEVELS.length &&
343
+ enabled.every((level, i) => level === DEFAULT_THINKING_LEVELS[i]);
344
+ if (sameAsDefault && map.off === undefined)
345
+ return undefined;
346
+ return map;
347
+ }
348
+ /** 只保留 pi 认识的 7 个档位键,值归一化成「非空字符串」或 `null`。
349
+ * models.json 的模型 schema 只列这 7 个键,未知键写进去既无意义也可能被拒。 */
350
+ export function sanitizeThinkingLevelMap(value) {
351
+ if (!value || typeof value !== "object" || Array.isArray(value))
352
+ return undefined;
353
+ const src = value;
354
+ const out = {};
355
+ for (const level of THINKING_LEVELS) {
356
+ const raw = src[level];
357
+ if (raw === null)
358
+ out[level] = null;
359
+ else if (typeof raw === "string" && raw.trim())
360
+ out[level] = raw.trim();
361
+ }
362
+ return Object.keys(out).length > 0 ? out : undefined;
363
+ }
196
364
  /** Best-effort extraction of model metadata from an OpenAI-compatible
197
365
  * /models `data[]` item. Most endpoints only return `{ id }` — the extra
198
366
  * fields (context_window / max_model_len / modalities / supports_vision /
199
- * reasoning / display_name) come from vLLM and other extended
200
- * implementations, and are filled into the form when present. */
367
+ * reasoning / display_name / 推理档位) come from vLLM, 聚合网关 and other
368
+ * extended implementations, and are filled into the form when present. */
201
369
  function parseOpenAiModel(m) {
202
370
  const r = (m ?? {});
203
371
  const id = typeof r.id === "string" ? r.id : "";
@@ -210,13 +378,17 @@ function parseOpenAiModel(m) {
210
378
  strArrMeta(r.input)?.includes("image") === true;
211
379
  // 名字与元数据兜底:端点未提供 reasoning 时通过通用推理模型特征推断。
212
380
  // 只增不减:取消勾选靠手填(编辑页/刷新合并都只补缺)。
213
- const reasoning = detectReasoningCapability(id, r);
381
+ // 网关自报推理档位同样是「这是推理模型」的铁证(如聚合网关的 glm-5.3,
382
+ // 名字认不出来,但 reasoning_levels 报了 low/high/max)。
383
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
384
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
214
385
  const contextWindow = numMeta(r.context_window) ?? numMeta(r.context_length) ?? numMeta(r.max_model_len) ?? numMeta(r.max_context_length);
215
386
  const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
216
387
  return {
217
388
  id,
218
389
  ...(name ? { name } : {}),
219
390
  ...(reasoning ? { reasoning: true } : {}),
391
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
220
392
  ...(vision ? { input: ["text", "image"] } : {}),
221
393
  ...(contextWindow ? { contextWindow } : {}),
222
394
  ...(maxTokens ? { maxTokens } : {}),
@@ -231,11 +403,13 @@ function parseGoogleModel(m) {
231
403
  const id = rawName.replace(/^models\//, "");
232
404
  const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
233
405
  // 与 OpenAI 形状同口径的推断兜底(见 detectReasoningCapability)。
234
- const reasoning = detectReasoningCapability(id, r);
406
+ const thinkingLevelMap = buildThinkingLevelMapFromMeta(r);
407
+ const reasoning = detectReasoningCapability(id, r) || thinkingLevelMap !== undefined;
235
408
  return {
236
409
  id,
237
410
  ...(displayName && displayName !== id ? { name: displayName } : {}),
238
411
  ...(reasoning ? { reasoning: true } : {}),
412
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
239
413
  ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
240
414
  ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
241
415
  };
@@ -1270,6 +1444,9 @@ export class ModelAdminService {
1270
1444
  input: Array.isArray(m.input) ? m.input : undefined,
1271
1445
  contextWindow: m.contextWindow,
1272
1446
  maxTokens: m.maxTokens,
1447
+ // 思考档位映射必须下发:前端模型行拿不到它就会在保存往返里丢掉,
1448
+ // 编辑页也无法展示网关自报的 xhigh/max 能力。
1449
+ thinkingLevelMap: sanitizeThinkingLevelMap(m.thinkingLevelMap),
1273
1450
  }))
1274
1451
  : [];
1275
1452
  return {
@@ -1312,65 +1489,8 @@ export class ModelAdminService {
1312
1489
  }
1313
1490
  this.host.flushSnapshot();
1314
1491
  }
1315
- /** Numeric metadata value (NaN/string "unknown" → undefined). */
1316
- static numMeta(v) {
1317
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
1318
- }
1319
- static boolMeta(v) {
1320
- return typeof v === "boolean" ? v : undefined;
1321
- }
1322
- static strArrMeta(v) {
1323
- return Array.isArray(v) ? v.filter((x) => typeof x === "string") : undefined;
1324
- }
1325
- /** Best-effort extraction of model metadata from an OpenAI-compatible
1326
- * /models `data[]` item. Most endpoints only return `{ id }` — the extra
1327
- * fields (context_window / max_model_len / modalities / supports_vision /
1328
- * reasoning / display_name) come from vLLM and other extended
1329
- * implementations, and are filled into the form when present. */
1330
- static parseOpenAiModel(m) {
1331
- const r = (m ?? {});
1332
- const id = typeof r.id === "string" ? r.id : "";
1333
- const name = (typeof r.name === "string" && r.name.trim() ? r.name : undefined) ??
1334
- (typeof r.display_name === "string" && r.display_name.trim() ? r.display_name : undefined);
1335
- const modalities = strArrMeta(r.modalities) ?? strArrMeta(r.input_modalities);
1336
- const vision = modalities?.includes("image") === true ||
1337
- boolMeta(r.supports_vision) === true ||
1338
- boolMeta(r.vision) === true ||
1339
- strArrMeta(r.input)?.includes("image") === true;
1340
- // 名字与元数据兜底:端点未提供 reasoning 时通过通用推理模型特征推断。
1341
- const reasoning = detectReasoningCapability(id, r);
1342
- const contextWindow = numMeta(r.context_window) ??
1343
- numMeta(r.context_length) ??
1344
- numMeta(r.max_model_len) ??
1345
- numMeta(r.max_context_length);
1346
- const maxTokens = numMeta(r.max_tokens) ?? numMeta(r.max_output_tokens) ?? numMeta(r.max_completion_tokens);
1347
- return {
1348
- id,
1349
- ...(name ? { name } : {}),
1350
- ...(reasoning ? { reasoning: true } : {}),
1351
- ...(vision ? { input: ["text", "image"] } : {}),
1352
- ...(contextWindow ? { contextWindow } : {}),
1353
- ...(maxTokens ? { maxTokens } : {}),
1354
- };
1355
- }
1356
- /** google-generative-ai /models shape:
1357
- * { models: [{ name: "models/gemini-flash", displayName, inputTokenLimit,
1358
- * outputTokenLimit, supportedGenerationMethods }] } */
1359
- static parseGoogleModel(m) {
1360
- const r = (m ?? {});
1361
- const rawName = typeof r.name === "string" ? r.name : "";
1362
- const id = rawName.replace(/^models\//, "");
1363
- const displayName = typeof r.displayName === "string" ? r.displayName : undefined;
1364
- // 与 OpenAI 形状同口径的推断兜底(见 detectReasoningCapability)。
1365
- const reasoning = detectReasoningCapability(id, r);
1366
- return {
1367
- id,
1368
- ...(displayName && displayName !== id ? { name: displayName } : {}),
1369
- ...(reasoning ? { reasoning: true } : {}),
1370
- ...(numMeta(r.inputTokenLimit) ? { contextWindow: numMeta(r.inputTokenLimit) } : {}),
1371
- ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
1372
- };
1373
- }
1492
+ // 模型元数据解析(numMeta/boolMeta/strArrMeta/parseOpenAiModel/parseGoogleModel)
1493
+ // 单源在模块级:这几份曾是静态方法里的死副本,改一处漏一处(#771 白改一遍)。
1374
1494
  /** Probe a custom provider's OpenAI-compatible /models endpoint (server-side
1375
1495
  * because the baseUrl is often a LAN/loopback host the browser can't reach
1376
1496
  * cross-origin) and return the advertised models. reqId is echoed back
@@ -1726,10 +1846,12 @@ export class ModelAdminService {
1726
1846
  * toModelRow itself only trims); absent values keep being inherited
1727
1847
  * from sibling models at compose time. */
1728
1848
  static toModelRow(m) {
1849
+ const thinkingLevelMap = sanitizeThinkingLevelMap(m.thinkingLevelMap);
1729
1850
  return {
1730
1851
  id: m.id.trim(),
1731
1852
  ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1732
1853
  ...(m.reasoning ? { reasoning: true } : {}),
1854
+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),
1733
1855
  ...(m.input?.length ? { input: m.input } : {}),
1734
1856
  ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1735
1857
  ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
@@ -1693,7 +1693,7 @@ export class PluginManager {
1693
1693
  streamingHandlers = new Set();
1694
1694
  /** 插件间总线订阅:topic → 处理器集合(host.events.on 注册;反激活时清理该插件全部订阅)。 */
1695
1695
  busHandlers = new Map();
1696
- /** host.chatWait 的 run_end 等待者(emitRunEvent 里按 conversationId 唤醒)。 */
1696
+ /** host.chatWait 的 run_end 等待者(emitRunEvent 里按 runId / conversationId 唤醒)。 */
1697
1697
  chatWaiters = [];
1698
1698
  /** 激活期插件的能力门控快照(activate 开头写入、落盘 loaded 或失败即删):
1699
1699
  * canUse 在 host 对象可用之前(loaded.set 之前)也要能判定。 */
@@ -1761,11 +1761,13 @@ export class PluginManager {
1761
1761
  return true;
1762
1762
  return legacy(fam);
1763
1763
  }
1764
- /** host.chatWait 等待指定对话的 run_end(默认 120s 超时由调用方钳制后传入)。 */
1765
- waitRunEnd(conversationId, timeoutMs) {
1764
+ /** host.chatWait 等待指定对话的 run_end(默认 120s 超时由调用方钳制后传入)。
1765
+ * runId 优先:过户换持有方 / 撞 id 改名后 conversationId 已经对不上了。 */
1766
+ waitRunEnd(conversationId, timeoutMs, runId) {
1766
1767
  return new Promise((resolve) => {
1767
1768
  const entry = {
1768
1769
  conversationId,
1770
+ ...(runId ? { runId } : {}),
1769
1771
  done: (ended) => {
1770
1772
  clearTimeout(timer);
1771
1773
  const i = this.chatWaiters.indexOf(entry);
@@ -1830,9 +1832,11 @@ export class PluginManager {
1830
1832
  * 与 emitToolEvent 同级;订阅者崩了只记日志,不影响主流程)。
1831
1833
  * run_end 顺带唤醒 host.chatWait 的等待者(按 conversationId 匹配)。 */
1832
1834
  emitRunEvent(ev) {
1833
- if (ev.type === "run_end" && ev.conversationId) {
1835
+ if (ev.type === "run_end" && (ev.conversationId || ev.runId)) {
1834
1836
  for (const w of this.chatWaiters) {
1835
- if (w.conversationId !== ev.conversationId)
1837
+ const byRun = Boolean(ev.runId && w.runId && ev.runId === w.runId);
1838
+ const byConv = Boolean(ev.conversationId) && w.conversationId === ev.conversationId && !w.runId;
1839
+ if (!byRun && !byConv)
1836
1840
  continue;
1837
1841
  try {
1838
1842
  w.done(true);
@@ -3213,7 +3217,7 @@ export class PluginManager {
3213
3217
  return { ok: false, error: "无头调用未返回 conversationId" };
3214
3218
  // 默认 120s 超时;上下钳制防 100ms 误杀与无限等待。
3215
3219
  const timeoutMs = Math.max(1000, Math.min(Number(opts?.timeoutMs ?? 120_000) || 120_000, 600_000));
3216
- const ended = await self.waitRunEnd(cid, timeoutMs);
3220
+ const ended = await self.waitRunEnd(cid, timeoutMs, sent?.runId);
3217
3221
  if (!ended)
3218
3222
  return { ok: false, conversationId: cid, error: `等待运行结束超时(约${Math.round(timeoutMs / 1000)}s)` };
3219
3223
  return { ok: true, conversationId: cid };
@@ -387,6 +387,9 @@ export class RemoteSshService {
387
387
  }
388
388
  }
389
389
  get profilesFilePath() {
390
+ return path.join(this.dataDir, "global-hosts.json");
391
+ }
392
+ get legacyProfilesFilePath() {
390
393
  return path.join(this.dataDir, "ssh-profiles.json");
391
394
  }
392
395
  async loadProfilesData() {
@@ -398,6 +401,16 @@ export class RemoteSshService {
398
401
  return parsed;
399
402
  }
400
403
  }
404
+ else if (existsSync(this.legacyProfilesFilePath)) {
405
+ const content = await fs.readFile(this.legacyProfilesFilePath, "utf8");
406
+ const parsed = JSON.parse(content);
407
+ if (parsed && parsed.version === 1 && typeof parsed.profiles === "object") {
408
+ // 迁移到新的 global-hosts.json
409
+ await fs.mkdir(this.dataDir, { recursive: true });
410
+ await fs.writeFile(this.profilesFilePath, JSON.stringify(parsed, null, 2), "utf8");
411
+ return parsed;
412
+ }
413
+ }
401
414
  }
402
415
  catch { }
403
416
  return { version: 1, profiles: {} };
@@ -405,7 +418,10 @@ export class RemoteSshService {
405
418
  async saveProfilesData(data) {
406
419
  try {
407
420
  await fs.mkdir(this.dataDir, { recursive: true });
408
- await fs.writeFile(this.profilesFilePath, JSON.stringify(data, null, 2), "utf8");
421
+ const json = JSON.stringify(data, null, 2);
422
+ await fs.writeFile(this.profilesFilePath, json, "utf8");
423
+ // 同时保持旧文件同步(防止外部或旧调用方异常)
424
+ await fs.writeFile(this.legacyProfilesFilePath, json, "utf8").catch(() => { });
409
425
  }
410
426
  catch (err) {
411
427
  console.error("[remote-ssh] 无法保存 profiles 文件:", err);
@@ -423,9 +439,41 @@ export class RemoteSshService {
423
439
  authType: p.authType,
424
440
  privateKeyPath: p.privateKeyPath,
425
441
  lastConnected: p.lastConnected,
442
+ remotePath: p.remotePath,
443
+ description: p.description,
426
444
  }))
427
445
  .sort((a, b) => (b.lastConnected ?? 0) - (a.lastConnected ?? 0));
428
446
  }
447
+ /** 获取解密后的 profile 凭据(仅供受信任的服务端内部模块使用) */
448
+ async getDecryptedProfile(name) {
449
+ const data = await this.loadProfilesData();
450
+ const p = data.profiles[name];
451
+ if (!p)
452
+ return null;
453
+ let password;
454
+ let passphrase;
455
+ if (p.authType === "password" && p.encryptedPassword) {
456
+ password = await this.unseal(p.encryptedPassword);
457
+ }
458
+ else if (p.authType === "key" && p.encryptedPassphrase) {
459
+ passphrase = await this.unseal(p.encryptedPassphrase);
460
+ }
461
+ return {
462
+ profile: {
463
+ name: p.name,
464
+ host: p.host,
465
+ port: p.port,
466
+ username: p.username,
467
+ authType: p.authType,
468
+ privateKeyPath: p.privateKeyPath,
469
+ lastConnected: p.lastConnected,
470
+ remotePath: p.remotePath,
471
+ description: p.description,
472
+ },
473
+ password,
474
+ passphrase,
475
+ };
476
+ }
429
477
  /** 删除一个已保存的 profile */
430
478
  async deleteProfile(name) {
431
479
  const data = await this.loadProfilesData();
@@ -435,7 +483,7 @@ export class RemoteSshService {
435
483
  }
436
484
  }
437
485
  /** 记录或更新一个 profile */
438
- async saveProfile(name, params) {
486
+ async saveProfile(name, params, meta) {
439
487
  const data = await this.loadProfilesData();
440
488
  const existing = data.profiles[name];
441
489
  const auth = params.auth;
@@ -447,6 +495,8 @@ export class RemoteSshService {
447
495
  authType: auth.type,
448
496
  privateKeyPath: auth.type === "key" ? auth.privateKeyPath : undefined,
449
497
  lastConnected: Date.now(),
498
+ remotePath: meta?.remotePath ?? existing?.remotePath,
499
+ description: meta?.description ?? existing?.description,
450
500
  };
451
501
  if (auth.type === "password") {
452
502
  if (auth.password) {
@@ -689,18 +739,30 @@ export class RemoteSshService {
689
739
  async probe(params) {
690
740
  let client;
691
741
  let hydrated;
692
- try {
693
- const res = await this.createClient(params);
694
- client = res.client;
695
- hydrated = res.hydrated;
742
+ let conn;
743
+ const port = params.port ?? 22;
744
+ const hostKey = `${params.username}@${params.host}:${port}`;
745
+ const existingId = this.hostConnections.get(hostKey);
746
+ const existingConn = existingId ? this.connections.get(existingId) : undefined;
747
+ if (existingConn && existingConn.alive) {
748
+ conn = existingConn;
749
+ client = existingConn.client;
750
+ hydrated = existingConn.params;
696
751
  }
697
- catch (err) {
698
- return {
699
- ok: false,
700
- error: err.message || String(err),
701
- };
752
+ else {
753
+ try {
754
+ const res = await this.createClient(params);
755
+ client = res.client;
756
+ hydrated = res.hydrated;
757
+ conn = this.registerConnection(client, hydrated);
758
+ }
759
+ catch (err) {
760
+ return {
761
+ ok: false,
762
+ error: err.message || String(err),
763
+ };
764
+ }
702
765
  }
703
- const conn = this.registerConnection(client, hydrated);
704
766
  // 无论是否显式勾选,连接成功都持久化凭据以便打开远程工作区后能够跨请求/跨重启自动重连
705
767
  if (params.saveProfile !== false) {
706
768
  const pName = params.profileName?.trim() || `${hydrated.username}@${hydrated.host}`;
@@ -713,6 +775,8 @@ uname -m
713
775
  uname -n
714
776
  echo "$USER"
715
777
  echo "$HOME"
778
+ (nproc 2>/dev/null || grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo "1")
779
+ (awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || free -m 2>/dev/null | awk '/Mem:/ {print $2}' || sysctl -n hw.memsize 2>/dev/null | awk '{print int($1/1024/1024)}' || echo "0")
716
780
  echo "===GIT==="
717
781
  which git 2>/dev/null && git --version 2>/dev/null || echo "NONE"
718
782
  echo "===NODE==="
@@ -767,6 +831,8 @@ done
767
831
  const hostname = sysLines[2] || "";
768
832
  const user = sysLines[3] || "";
769
833
  const homeDir = sysLines[4] || "/";
834
+ const cores = parseInt(sysLines[5] || "1", 10) || 1;
835
+ const totalMemMb = parseInt(sysLines[6] || "0", 10) || 0;
770
836
  const gitLines = (sections["GIT"] || []).filter(Boolean);
771
837
  const gitInstalled = gitLines.length > 0 && gitLines[0] !== "NONE";
772
838
  const gitVersion = gitInstalled ? gitLines.join(" ") : undefined;
@@ -793,6 +859,8 @@ done
793
859
  hostname,
794
860
  user,
795
861
  homeDir,
862
+ cores,
863
+ totalMemMb,
796
864
  },
797
865
  tools: {
798
866
  git: { installed: gitInstalled, version: gitVersion },
@@ -1428,6 +1496,36 @@ fi
1428
1496
  };
1429
1497
  return virtualPty;
1430
1498
  }
1499
+ /**
1500
+ * 为目标主机打开交互式 PTY Shell 通道(返回底层 ClientChannel 流与连接)
1501
+ */
1502
+ async openShell(target, options = {}) {
1503
+ const port = target.port ?? 22;
1504
+ const conn = await this.getOrConnectHost(target.host, port, target.username);
1505
+ return new Promise((resolve, reject) => {
1506
+ conn.client.shell({
1507
+ term: options.term ?? "xterm-256color",
1508
+ cols: Math.max(2, Math.floor(options.cols ?? 80)),
1509
+ rows: Math.max(2, Math.floor(options.rows ?? 24)),
1510
+ }, (err, stream) => {
1511
+ if (err)
1512
+ return reject(err);
1513
+ if (target.remotePath && target.remotePath !== "~") {
1514
+ stream.write(`cd ${shellQuotePosix(target.remotePath)} && clear\r`);
1515
+ }
1516
+ resolve({
1517
+ stream,
1518
+ conn,
1519
+ close: () => {
1520
+ try {
1521
+ stream.close();
1522
+ }
1523
+ catch { }
1524
+ },
1525
+ });
1526
+ });
1527
+ });
1528
+ }
1431
1529
  }
1432
1530
  /**
1433
1531
  * 通过 SFTP 流式响应远程工作区文件的 HTTP 下载与媒体/HTML 预览请求(/api/file 与 /api/preview)。
@@ -3,7 +3,7 @@ import { saveAttachmentSync } from "./attachment-store.js";
3
3
  import { stripMarkers } from "./markers/index.js";
4
4
  export const TEXT_CAP = 200_000;
5
5
  export const TOOL_OUTPUT_CAP = 100_000;
6
- export const ARGS_CAP = 20_000;
6
+ export const ARGS_CAP = 200_000;
7
7
  /**
8
8
  * toolResult 里单张图片进快照的上限(dataUrl 字符数 ≈ 1.5MB 二进制)。
9
9
  * 视口/元素截图随便过;超大整页截图回落成占位文本(模型侧不受影响 —— 图它