pi-web-ui 0.87.2 → 0.89.0

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 (35) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/bin/pi-web-ui.mjs +463 -0
  3. package/dist/server/agent-service.js +419 -45
  4. package/dist/server/attachments.js +39 -0
  5. package/dist/server/client-state.js +22 -0
  6. package/dist/server/conversation-read-tool.js +325 -0
  7. package/dist/server/dsh/dsh-agent-service.js +32 -3
  8. package/dist/server/files-service.js +103 -0
  9. package/dist/server/host-metrics.js +59 -0
  10. package/dist/server/index.js +381 -8
  11. package/dist/server/model-admin.js +285 -36
  12. package/dist/server/plugin-facilities.js +115 -2
  13. package/dist/server/plugin-llm.js +129 -0
  14. package/dist/server/plugin-permissions.js +176 -0
  15. package/dist/server/plugin-schedule.js +211 -0
  16. package/dist/server/plugins.js +1005 -68
  17. package/dist/server/scheduler-tasks.js +405 -0
  18. package/dist/server/settings-service.js +8 -1
  19. package/dist/server/terminals.js +14 -1
  20. package/dist/server/tool-manager.js +6 -1
  21. package/dist/server/update-check.js +249 -19
  22. package/extensions/webui.ts +9 -2
  23. package/package.json +4 -2
  24. package/plugin-sdk/README.md +127 -0
  25. package/plugin-sdk/index.d.ts +454 -0
  26. package/plugin-sdk/index.mjs +545 -0
  27. package/plugin-sdk/package.json +9 -0
  28. package/plugins/catalog.json +11 -2
  29. package/web/dist/assets/TerminalPanel-BOUmN3uu.js +6 -0
  30. package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
  31. package/web/dist/assets/index-3XU67qMh.js +376 -0
  32. package/web/dist/assets/index-B-gdvWtW.css +10 -0
  33. package/web/dist/index.html +2 -3
  34. package/web/dist/assets/index-CYuoen3I.js +0 -374
  35. package/web/dist/assets/index-F86qWlJy.css +0 -41
@@ -12,9 +12,58 @@
12
12
  * UI 文案直接中文(服务端 notice 约定)。apiKey/headers 绝不下发浏览器。
13
13
  */
14
14
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
- import { join } from "node:path";
15
+ import { dirname, join } from "node:path";
16
16
  import { pick } from "./i18n.js";
17
17
  import { ProviderOAuthFlowManager } from "./provider-oauth-flow.js";
18
+ /** Drop provisional overlay rows once the official catalog lists the same id.
19
+ *
20
+ * Background: a hand-appended row SHADOWS the official row at compose time
21
+ * (applyModelsJson rebuilds the entry from the definition, so official
22
+ * name/vision/contextWindow/etc. are lost and only api/baseUrl are
23
+ * inherited). While pi.dev doesn't list the id the shadow is the whole
24
+ * point; once it does, the shadow becomes stale metadata. `official` maps
25
+ * provider → model id → the official row's api (undefined when unknown).
26
+ * A row graduates when the official catalog lists its id AND the row
27
+ * carries no deliberate routing of its own: no baseUrl, and either no api
28
+ * or the same api the official row uses. A row with its own baseUrl or a
29
+ * differing api is a customization, not a provisional — it stays. When an
30
+ * entry's models become empty and it carries no other keys, the whole entry
31
+ * is removed so it also leaves the "custom providers" list; entries with
32
+ * other keys (baseUrl/apiKey/headers/…) are kept. Mutates `providers` in
33
+ * place and returns what was graduated. Pure + unit-tested. */
34
+ export function graduateOverlayModels(providers, official) {
35
+ const graduated = [];
36
+ for (const [pid, entry] of Object.entries(providers)) {
37
+ if (!entry || typeof entry !== "object" || !Array.isArray(entry.models))
38
+ continue;
39
+ const officialModels = official[pid];
40
+ if (!officialModels || Object.keys(officialModels).length === 0)
41
+ continue;
42
+ const kept = [];
43
+ for (const row of entry.models) {
44
+ const r = (row ?? {});
45
+ const id = typeof r.id === "string" ? r.id.trim() : "";
46
+ const listed = id !== "" && Object.hasOwn(officialModels, id);
47
+ const officialApi = listed ? officialModels[id] : undefined;
48
+ const rowApi = typeof r.api === "string" && r.api.trim() ? r.api.trim() : undefined;
49
+ const provisional = listed && r.baseUrl == null && (rowApi === undefined || (officialApi !== undefined && rowApi === officialApi));
50
+ if (provisional) {
51
+ graduated.push({ providerId: pid, modelId: id });
52
+ continue;
53
+ }
54
+ kept.push(row);
55
+ }
56
+ if (kept.length === entry.models.length)
57
+ continue;
58
+ if (kept.length === 0 && Object.keys(entry).every((k) => k === "models")) {
59
+ delete providers[pid];
60
+ }
61
+ else {
62
+ entry.models = kept;
63
+ }
64
+ }
65
+ return graduated;
66
+ }
18
67
  /** Strip // and /* *\/ comments without touching string literals (URLs contain //). */
19
68
  function stripJsonComments(src) {
20
69
  let out = "";
@@ -1256,6 +1305,239 @@ export class ModelAdminService {
1256
1305
  return done(false, { error: err.message });
1257
1306
  }
1258
1307
  }
1308
+ /** Force-refresh BUILT-IN providers' official pi.dev catalogs, bypassing
1309
+ * the SDK's 4h freshness window (`force: true`). Without force, refresh
1310
+ * inside the window is a silent no-op against models-store.json — which
1311
+ * is why a newly-published cheap model can sit on pi.dev for hours while
1312
+ * the picker still shows the old list. Afterwards the picker + provider
1313
+ * status are repushed. Per-provider fetch failures don't fail the whole
1314
+ * run (those providers keep their cached catalog) but are surfaced in
1315
+ * the result + a warning notice. */
1316
+ async refreshBuiltinModels(reqId) {
1317
+ const done = (ok, error) => this.host.emit({ type: "refresh_builtin_result", reqId, ok, ...(error ? { error } : {}) });
1318
+ try {
1319
+ const mr = this.host.modelRuntime();
1320
+ const res = await mr.refresh({
1321
+ allowNetwork: true,
1322
+ force: true,
1323
+ signal: AbortSignal.timeout(90_000),
1324
+ });
1325
+ // Provisional overlay rows (append_builtin_model) shadow the official
1326
+ // row once pi.dev lists the id — graduate them so official
1327
+ // name/vision/limits take over. Only rows without their own
1328
+ // api/baseUrl are provisional; deliberate customizations stay.
1329
+ const graduated = this.graduateProvisionalOverlays();
1330
+ if (graduated.length > 0) {
1331
+ await mr.refresh();
1332
+ }
1333
+ this.host.invalidatePiConfig();
1334
+ await this.host.pushModels();
1335
+ await this.listProviders();
1336
+ const failures = [...res.errors.entries()].map(([pid, err]) => `${pid} (${err.message})`);
1337
+ if (failures.length > 0) {
1338
+ const detail = failures.join("; ");
1339
+ this.host.emit({
1340
+ type: "notice",
1341
+ level: "warning",
1342
+ text: `⚠️ 官方模型目录已强制刷新,但 ${failures.length} 个供应商拉取失败(沿用缓存):${detail}`,
1343
+ textEn: `⚠️ Official model catalogs force-refreshed, but ${failures.length} provider(s) failed (cached catalog kept): ${detail}`,
1344
+ });
1345
+ return done(true, detail);
1346
+ }
1347
+ this.host.emit({
1348
+ type: "notice",
1349
+ level: "info",
1350
+ text: "🔄 已强制刷新官方模型目录(绕过 4 小时缓存),模型下拉已更新",
1351
+ textEn: "🔄 Official model catalogs force-refreshed (4h cache bypassed); the model picker is up to date",
1352
+ });
1353
+ if (graduated.length > 0) {
1354
+ const names = graduated.map((g) => `${g.providerId}/${g.modelId}`).join("、");
1355
+ this.host.emit({
1356
+ type: "notice",
1357
+ level: "info",
1358
+ text: `🎓 ${names} 官方已收录,手工条目已移除并转用官方配置`,
1359
+ textEn: `${names} graduated to the official catalog; provisional rows removed`,
1360
+ });
1361
+ }
1362
+ return done(true);
1363
+ }
1364
+ catch (err) {
1365
+ this.host.emit({
1366
+ type: "notice",
1367
+ level: "error",
1368
+ text: `强制刷新官方模型目录失败:${err.message}`,
1369
+ textEn: `Failed to force-refresh official model catalogs: ${err.message}`,
1370
+ });
1371
+ return done(false, err.message);
1372
+ }
1373
+ finally {
1374
+ this.host.flushSnapshot();
1375
+ }
1376
+ }
1377
+ /** Graduate provisional overlay rows against the freshly force-refreshed
1378
+ * official catalog (models-store.json next to models.json). Persists the
1379
+ * pruned models.json only when something actually graduated; a missing
1380
+ * or unparsable store is a silent no-op (never fail the refresh). */
1381
+ graduateProvisionalOverlays() {
1382
+ let official = {};
1383
+ try {
1384
+ const storePath = join(dirname(this.modelsConfigPath()), "models-store.json");
1385
+ const stored = JSON.parse(readFileSync(storePath, "utf8"));
1386
+ for (const [pid, entry] of Object.entries(stored ?? {})) {
1387
+ if (!Array.isArray(entry?.models))
1388
+ continue;
1389
+ const byId = {};
1390
+ for (const m of entry.models) {
1391
+ if (typeof m?.id !== "string" || !m.id.trim())
1392
+ continue;
1393
+ byId[m.id.trim()] = typeof m.api === "string" ? m.api : undefined;
1394
+ }
1395
+ official[pid] = byId;
1396
+ }
1397
+ }
1398
+ catch {
1399
+ return [];
1400
+ }
1401
+ const { providers } = this.readModelsConfig();
1402
+ const graduated = graduateOverlayModels(providers, official);
1403
+ if (graduated.length === 0)
1404
+ return graduated;
1405
+ try {
1406
+ writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1407
+ }
1408
+ catch {
1409
+ return [];
1410
+ }
1411
+ return graduated;
1412
+ }
1413
+ /** Normalize one UI-submitted model row into models.json shape (same rules
1414
+ * as save_model_config: blank optionals dropped, numbers coerced).
1415
+ * Per-model api/baseUrl overrides pass through (validated by callers —
1416
+ * toModelRow itself only trims); absent values keep being inherited
1417
+ * from sibling models at compose time. */
1418
+ static toModelRow(m) {
1419
+ return {
1420
+ id: m.id.trim(),
1421
+ ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1422
+ ...(m.reasoning ? { reasoning: true } : {}),
1423
+ ...(m.input?.length ? { input: m.input } : {}),
1424
+ ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1425
+ ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
1426
+ ...(m.api?.trim() ? { api: m.api.trim() } : {}),
1427
+ ...(m.baseUrl?.trim() ? { baseUrl: m.baseUrl.trim() } : {}),
1428
+ };
1429
+ }
1430
+ /** Known per-model api types (same list as the custom-provider form). */
1431
+ static MODEL_APIS = new Set([
1432
+ "openai-completions",
1433
+ "openai-responses",
1434
+ "anthropic-messages",
1435
+ "google-generative-ai",
1436
+ ]);
1437
+ /** Write models.json and hot-reload the model runtime (shared tail of
1438
+ * save_model_config / append_builtin_model). Reuses the provider
1439
+ * credential already in auth.json for the runtime, then repushes the
1440
+ * config list + the picker. Callers emit their own notice. */
1441
+ async writeModelsConfigAndReload(providers, pid) {
1442
+ mkdirSync(this.host.agentDir, { recursive: true });
1443
+ writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1444
+ // Allow a models.json entry to reuse the provider credential already
1445
+ // stored in auth.json. Seed the shared runtime too, because older pi-ai
1446
+ // versions did not always fall back to stored credentials for a
1447
+ // newly-created custom provider. Never copy the secret into models.json.
1448
+ try {
1449
+ const auth = JSON.parse(readFileSync(join(this.host.agentDir, "auth.json"), "utf8"));
1450
+ const credential = auth[pid];
1451
+ if (credential &&
1452
+ typeof credential === "object" &&
1453
+ "key" in credential &&
1454
+ typeof credential.key === "string" &&
1455
+ credential.key.trim()) {
1456
+ await this.host.modelRuntime().setRuntimeApiKey(pid, credential.key);
1457
+ }
1458
+ }
1459
+ catch {
1460
+ // auth.json is optional; models.json can still use its own apiKey.
1461
+ }
1462
+ await this.host.modelRuntime().refresh();
1463
+ this.host.invalidatePiConfig();
1464
+ await this.listModelsConfig();
1465
+ await this.host.pushModels();
1466
+ }
1467
+ /** Append ONE model to a BUILT-IN provider's models.json overlay entry
1468
+ * (append_builtin_result). Pure overlay: when the provider has no entry
1469
+ * yet, a `{ models: [row] }` entry is created — no baseUrl/api — so
1470
+ * api/baseUrl keep being inherited from the provider's own models at
1471
+ * compose time and later official catalog refreshes never drop the row.
1472
+ * Existing entry fields are left byte-for-byte alone (append-only, even
1473
+ * safer than save_model_config's merge). Duplicate id is an idempotent
1474
+ * no-op (info notice, ok:true). The row shows up under "custom
1475
+ * providers" (same id) for edit/remove. */
1476
+ async appendBuiltinModel(providerId, model, reqId) {
1477
+ const done = (ok, error) => this.host.emit({ type: "append_builtin_result", reqId, ok, ...(error ? { error } : {}) });
1478
+ const pid = providerId.trim();
1479
+ const mid = model?.id?.trim() ?? "";
1480
+ const fail = (text, textEn) => {
1481
+ this.host.emit({ type: "notice", level: "error", text, textEn });
1482
+ return done(false, text);
1483
+ };
1484
+ try {
1485
+ if (!pid)
1486
+ return fail("请填写服务商 ID", "Enter a provider ID");
1487
+ if (!mid)
1488
+ return fail("请填写模型 ID", "Enter a model ID");
1489
+ const api = model?.api?.trim() ? model.api.trim() : undefined;
1490
+ if (api && !ModelAdminService.MODEL_APIS.has(api)) {
1491
+ return fail(`接口类型无效:${api}(仅支持 ${[...ModelAdminService.MODEL_APIS].join(" / ")},留空则自动继承)`, `Invalid api type: ${api} (supported: ${[...ModelAdminService.MODEL_APIS].join(" / ")}; leave blank to inherit)`);
1492
+ }
1493
+ const baseUrl = model?.baseUrl?.trim() ? model.baseUrl.trim() : undefined;
1494
+ if (baseUrl) {
1495
+ let url;
1496
+ try {
1497
+ url = new URL(baseUrl);
1498
+ }
1499
+ catch {
1500
+ url = undefined;
1501
+ }
1502
+ if (!url || (url.protocol !== "http:" && url.protocol !== "https:")) {
1503
+ return fail(`接口地址无效:${baseUrl}(仅支持 http/https,留空则自动继承)`, `Invalid baseUrl: ${baseUrl} (http/https only; leave blank to inherit)`);
1504
+ }
1505
+ }
1506
+ if (!this.host.modelRuntime().getProvider(pid)) {
1507
+ return fail(`供应商 ${pid} 不存在`, `Provider ${pid} does not exist`);
1508
+ }
1509
+ const { providers } = this.readModelsConfig();
1510
+ const prev = providers[pid];
1511
+ const prevModels = Array.isArray(prev?.models) ? [...prev.models] : [];
1512
+ if (prevModels.some((m) => typeof m?.id === "string" && m.id.trim() === mid)) {
1513
+ this.host.emit({
1514
+ type: "notice",
1515
+ level: "info",
1516
+ text: `${pid} 已有模型 ${mid},无需重复添加`,
1517
+ textEn: `${pid} already has model ${mid}; nothing to add`,
1518
+ });
1519
+ return done(true);
1520
+ }
1521
+ // 手填行只带用户给的字段(通常只有 id,也许有名),api/baseUrl
1522
+ // 由 compose 时从同供应商现有模型继承——这正是纯 overlay 能工作的原因。
1523
+ const row = ModelAdminService.toModelRow({ ...model, id: mid });
1524
+ providers[pid] = { ...prev, models: [...prevModels, row] };
1525
+ await this.writeModelsConfigAndReload(providers, pid);
1526
+ this.host.emit({
1527
+ type: "notice",
1528
+ level: "info",
1529
+ text: `✅ 已给 ${pid} 添加模型 ${mid},模型下拉已更新(该条目同时列在「自定义服务商」下,可编辑/删除)`,
1530
+ textEn: `✅ Added model ${mid} to ${pid}; the picker is updated (the entry is also listed under custom providers for edit/remove)`,
1531
+ });
1532
+ return done(true);
1533
+ }
1534
+ catch (err) {
1535
+ return fail(`添加模型失败:${err.message}`, `Failed to add model: ${err.message}`);
1536
+ }
1537
+ finally {
1538
+ this.host.flushSnapshot();
1539
+ }
1540
+ }
1259
1541
  /** Upsert one provider into models.json and hot-reload the model runtime. */
1260
1542
  async saveModelConfig(providerId, config) {
1261
1543
  const pid = providerId.trim();
@@ -1268,16 +1550,7 @@ export class ModelAdminService {
1268
1550
  });
1269
1551
  return;
1270
1552
  }
1271
- const models = (config.models ?? [])
1272
- .filter((m) => m.id && m.id.trim())
1273
- .map((m) => ({
1274
- id: m.id.trim(),
1275
- ...(m.name?.trim() ? { name: m.name.trim() } : {}),
1276
- ...(m.reasoning ? { reasoning: true } : {}),
1277
- ...(m.input?.length ? { input: m.input } : {}),
1278
- ...(m.contextWindow ? { contextWindow: Number(m.contextWindow) } : {}),
1279
- ...(m.maxTokens ? { maxTokens: Number(m.maxTokens) } : {}),
1280
- }));
1553
+ const models = (config.models ?? []).filter((m) => m.id && m.id.trim()).map((m) => ModelAdminService.toModelRow(m));
1281
1554
  if (models.length === 0) {
1282
1555
  this.host.emit({
1283
1556
  type: "notice",
@@ -1292,31 +1565,7 @@ export class ModelAdminService {
1292
1565
  // 合并而不是重建:UI 认识之外的字段(provider 级 headers、模型级 api/
1293
1566
  // baseUrl/cost/compat/thinkingLevelMap)必须原样保留,见 mergeProviderConfigEntry。
1294
1567
  providers[pid] = mergeProviderConfigEntry(providers[pid], config, models);
1295
- mkdirSync(this.host.agentDir, { recursive: true });
1296
- writeFileSync(this.modelsConfigPath(), JSON.stringify({ providers }, null, 2) + "\n");
1297
- // Allow a custom models.json entry to reuse the provider credential
1298
- // already stored in auth.json. Seed the shared runtime too, because
1299
- // older pi-ai versions did not always fall back to stored credentials
1300
- // for a newly-created custom provider. Never copy the secret into
1301
- // models.json.
1302
- try {
1303
- const auth = JSON.parse(readFileSync(join(this.host.agentDir, "auth.json"), "utf8"));
1304
- const credential = auth[pid];
1305
- if (credential &&
1306
- typeof credential === "object" &&
1307
- "key" in credential &&
1308
- typeof credential.key === "string" &&
1309
- credential.key.trim()) {
1310
- await this.host.modelRuntime().setRuntimeApiKey(pid, credential.key);
1311
- }
1312
- }
1313
- catch {
1314
- // auth.json is optional; models.json can still use its own apiKey.
1315
- }
1316
- await this.host.modelRuntime().refresh();
1317
- this.host.invalidatePiConfig();
1318
- await this.listModelsConfig();
1319
- await this.host.pushModels();
1568
+ await this.writeModelsConfigAndReload(providers, pid);
1320
1569
  this.host.emit({
1321
1570
  type: "notice",
1322
1571
  level: "info",
@@ -17,8 +17,8 @@
17
17
  */
18
18
  import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
19
19
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
20
- import { readFile as fspReadFile, readdir as fspReaddir, rm as fspRm, mkdir as fspMkdir, writeFile as fspWriteFile, } from "node:fs/promises";
21
- import { dirname, join, resolve } from "node:path";
20
+ import { readFile as fspReadFile, readdir as fspReaddir, rm as fspRm, mkdir as fspMkdir, writeFile as fspWriteFile, appendFile as fspAppendFile, stat as fspStat, } from "node:fs/promises";
21
+ import { dirname, join, relative, resolve } from "node:path";
22
22
  import { createRequire } from "node:module";
23
23
  import { spawnSync } from "node:child_process";
24
24
  /** tmp+rename 原子写(错误由调用方隔离——插件设施的 IO 一律尽力而为)。 */
@@ -140,9 +140,19 @@ export class PluginSecrets {
140
140
  }
141
141
  return k;
142
142
  }
143
+ /** 同一密文文件的跨实例共享缓存(按绝对路径):设置面板的保存与插件运行时的
144
+ * 读取走的是两个实例(savePluginSettings 现场 new,host 闭包里一个),实例级缓存
145
+ * 会让“刚保存完立刻 getSettings”读到旧值。共享后同进程内永远一致;文件被删
146
+ * (卸载插件)时重置,避免重装同 id 读到旧机密。 */
147
+ static shared = new Map();
143
148
  load() {
144
149
  if (this.store)
145
150
  return this.store;
151
+ const hit = PluginSecrets.shared.get(this.file);
152
+ if (hit && existsSync(this.file)) {
153
+ this.store = hit;
154
+ return hit;
155
+ }
146
156
  try {
147
157
  const parsed = JSON.parse(readFileSync(this.file, "utf8"));
148
158
  this.store =
@@ -151,6 +161,7 @@ export class PluginSecrets {
151
161
  catch {
152
162
  this.store = { v: 1, items: {} };
153
163
  }
164
+ PluginSecrets.shared.set(this.file, this.store);
154
165
  return this.store;
155
166
  }
156
167
  set(name, value) {
@@ -268,6 +279,43 @@ export function ensurePluginDeps(pluginDir, specs, onProgress) {
268
279
  depInstallLocks.set(lockKey, p);
269
280
  return p;
270
281
  }
282
+ /** 深度/条数护栏:glob 递归遍历与结果都封顶,防大仓库扫爆内存。 */
283
+ const GLOB_MAX_WALK = 2000;
284
+ const GLOB_MAX_RESULTS = 500;
285
+ /** 极简 glob 转 RegExp:只支持 `*`(单段任意)/`?`(单字符)/`**`(跨段任意)。
286
+ * 纯函数,单测覆盖。 */
287
+ export function globToRegExp(pattern) {
288
+ const src = String(pattern ?? "")
289
+ .trim()
290
+ .replace(/\\/g, "/");
291
+ let re = "";
292
+ for (let i = 0; i < src.length; i++) {
293
+ const c = src[i];
294
+ if (c === "*") {
295
+ if (src[i + 1] === "*") {
296
+ // `**`:跨段;`/**/` 整体可省(根下也命中)。
297
+ if (src[i + 2] === "/") {
298
+ re += "(?:.*/)?";
299
+ i += 2;
300
+ }
301
+ else {
302
+ re += ".*";
303
+ i += 1;
304
+ }
305
+ }
306
+ else {
307
+ re += "[^/]*";
308
+ }
309
+ }
310
+ else if (c === "?") {
311
+ re += "[^/]";
312
+ }
313
+ else {
314
+ re += c.replace(/[.+^${}()|[\]\\]/, (m) => `\\${m}`);
315
+ }
316
+ }
317
+ return new RegExp(`^${re}$`);
318
+ }
271
319
  export class WorkspaceFS {
272
320
  root;
273
321
  /** root 是活值 getter(返回当前工作区绝对路径),跟随 set_cwd。 */
@@ -311,6 +359,71 @@ export class WorkspaceFS {
311
359
  await fspMkdir(dirname(target), { recursive: true });
312
360
  await fspWriteFile(target, data);
313
361
  }
362
+ /** 追加写文件(日志/队列场景;父目录自动补;越界拒绝与 write 同口径)。 */
363
+ async append(relPath, data) {
364
+ const target = this.abs(relPath);
365
+ await fspMkdir(dirname(target), { recursive: true });
366
+ await fspAppendFile(target, data);
367
+ }
368
+ /** 建目录(递归;已存在幂等成功;越界拒绝与 write 同口径)。 */
369
+ async mkdir(relDir) {
370
+ await fspMkdir(this.abs(relDir), { recursive: true });
371
+ }
372
+ /** 文件元信息(size/mtime 供同步/缓存判断;不存在抛错)。 */
373
+ async stat(relPath) {
374
+ const target = this.abs(relPath);
375
+ const st = await fspStat(target);
376
+ const base = target
377
+ .replace(/[/\\]+$/, "")
378
+ .split("/")
379
+ .pop() ?? String(relPath);
380
+ return {
381
+ name: base,
382
+ type: st.isDirectory() ? "dir" : "file",
383
+ size: st.isDirectory() ? 0 : st.size,
384
+ mtime: Number(st.mtimeMs) || 0,
385
+ };
386
+ }
387
+ /** 极简 glob 搜索(星号匹配如 `*.json`、双星匹配如 `foo/bar.md` 的父目录任意层):
388
+ * 相对路径(`/` 分隔)按 pattern 过滤。walk 与结果双封顶,目录本身也参与
389
+ * 匹配(`docs*` 能命中目录)。只返回相对路径字符串,调用方再 read/stat。 */
390
+ async glob(pattern, relDir = "") {
391
+ const pat = String(pattern ?? "")
392
+ .trim()
393
+ .replace(/\\/g, "/");
394
+ if (!pat)
395
+ throw new Error("glob: pattern 为空");
396
+ const re = globToRegExp(pat);
397
+ const base = this.abs(relDir);
398
+ const out = [];
399
+ const stack = [base];
400
+ let walked = 0;
401
+ while (stack.length && walked < GLOB_MAX_WALK && out.length < GLOB_MAX_RESULTS) {
402
+ const dir = stack.pop();
403
+ let ents;
404
+ try {
405
+ ents = await fspReaddir(dir, { withFileTypes: true });
406
+ }
407
+ catch {
408
+ continue; // 无权限/中途删除:跳过该分支,不整单失败
409
+ }
410
+ for (const e of ents) {
411
+ if (walked++ >= GLOB_MAX_WALK || out.length >= GLOB_MAX_RESULTS)
412
+ break;
413
+ const abs = join(dir, e.name);
414
+ const rel = relative(base, abs).replace(/\\/g, "/");
415
+ if (e.isDirectory()) {
416
+ if (re.test(rel) || re.test(`${rel}/`))
417
+ out.push(rel);
418
+ stack.push(abs);
419
+ }
420
+ else if (re.test(rel)) {
421
+ out.push(rel);
422
+ }
423
+ }
424
+ }
425
+ return out;
426
+ }
314
427
  /** 删除文件/目录(递归;只允许删工作区内的路径)。 */
315
428
  async remove(relPath) {
316
429
  await fspRm(this.abs(relPath), { recursive: true, force: false });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 插件直调模型(host.llm.complete 的底层):一次性的孤立无工具会话。
3
+ *
4
+ * 与审查循环的 reviewer 同一条 SDK 链路(createAgentSessionServices +
5
+ * ModelRuntime.create + createAgentSessionFromServices + prompt +
6
+ * getLastAssistantText + dispose),区别:
7
+ * - `noTools: true` + skills 全剥:纯补全,无副作用、可预测花费;
8
+ * - 调用方(agent-service.completeForPlugins)只给 cwd/agentDir/回落模型,
9
+ * 并发与预算门在本文件内收敛。
10
+ *
11
+ * 约束(fail-closed,一律结构化返回、绝不抛错):
12
+ * - 输入封顶:prompt ≤ 8000 字、system ≤ 4000 字;
13
+ * - 输出截断:maxChars 缺省 8000、上限 32000;
14
+ * - 超时:缺省 90s、范围 5s–5min,超时即 dispose 掉会话;
15
+ * - 并发:全局最多 4 路在飞,超了直接回 {ok:false}(插件侧重试,不排队——
16
+ * 排队会把插件的 await 变成不定等待,调用方超时兜底更难写)。
17
+ */
18
+ import { join } from "node:path";
19
+ import { createAgentSessionFromServices, createAgentSessionServices, ModelRuntime, SessionManager, } from "@earendil-works/pi-coding-agent";
20
+ import { parseModelSpec } from "./attachments.js";
21
+ const MAX_PROMPT_CHARS = 8000;
22
+ const MAX_SYSTEM_CHARS = 4000;
23
+ const DEFAULT_MAX_CHARS = 8000;
24
+ const MAX_MAX_CHARS = 32000;
25
+ const DEFAULT_TIMEOUT_MS = 90_000;
26
+ const MIN_TIMEOUT_MS = 5_000;
27
+ const MAX_TIMEOUT_MS = 300_000;
28
+ const MAX_INFLIGHT = 4;
29
+ let inflight = 0;
30
+ /** 当前在飞的孤立调用数(单测/诊断用)。 */
31
+ export function llmInflight() {
32
+ return inflight;
33
+ }
34
+ function fail(error) {
35
+ return { ok: false, error };
36
+ }
37
+ export async function completeWithIsolatedSession(env, req) {
38
+ const prompt = String(req?.prompt ?? "");
39
+ if (!prompt.trim())
40
+ return fail("llm.complete: prompt 为空");
41
+ if (prompt.length > MAX_PROMPT_CHARS)
42
+ return fail(`llm.complete: prompt 超长(${prompt.length} > ${MAX_PROMPT_CHARS} 字),请裁剪后重发`);
43
+ const system = String(req?.system ?? "");
44
+ if (system.length > MAX_SYSTEM_CHARS)
45
+ return fail(`llm.complete: system 超长(${system.length} > ${MAX_SYSTEM_CHARS} 字),请裁剪后重发`);
46
+ if (inflight >= MAX_INFLIGHT)
47
+ return fail(`llm.complete: 并发已满(${MAX_INFLIGHT} 路在飞),请稍后重试`);
48
+ const maxChars = Math.min(Math.max(Number(req?.maxChars ?? DEFAULT_MAX_CHARS) || DEFAULT_MAX_CHARS, 1), MAX_MAX_CHARS);
49
+ const timeoutMs = Math.min(Math.max(Number(req?.timeoutMs ?? DEFAULT_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
50
+ inflight += 1;
51
+ try {
52
+ const run = (async () => {
53
+ let dispose;
54
+ try {
55
+ const services = await createAgentSessionServices({
56
+ cwd: env.cwd,
57
+ agentDir: env.agentDir,
58
+ // 技能全剥:纯补全不需要技能上下文(省 token,结果可预测)。
59
+ resourceLoaderOptions: {
60
+ skillsOverride: (res) => ({ ...res, skills: [] }),
61
+ },
62
+ modelRuntime: await ModelRuntime.create({
63
+ authPath: join(env.agentDir, "auth.json"),
64
+ modelsPath: join(env.agentDir, "models.json"),
65
+ }),
66
+ });
67
+ // 模型:显式指定 > 主会话回落 > 会话默认(与 reviewer 同优先级)。
68
+ let model;
69
+ let modelName = "default";
70
+ const spec = parseModelSpec(req?.model);
71
+ if (spec) {
72
+ model = services.modelRuntime.getModel(spec.provider, spec.id);
73
+ if (!model)
74
+ return fail(`llm.complete: 找不到模型 ${spec.spec}`);
75
+ modelName = spec.spec;
76
+ }
77
+ if (!model && env.fallbackModel) {
78
+ model = services.modelRuntime.getModel(env.fallbackModel.provider, env.fallbackModel.id);
79
+ if (model)
80
+ modelName = `${env.fallbackModel.provider}/${env.fallbackModel.id}`;
81
+ }
82
+ const srv = await createAgentSessionFromServices({
83
+ services,
84
+ sessionManager: SessionManager.inMemory(env.cwd),
85
+ ...(model ? { model } : {}),
86
+ // 全部工具关闭("all"):纯补全,无副作用(SDK 的 noTools 是 "builtin"|"all" 枚举)。
87
+ noTools: "all",
88
+ });
89
+ dispose = () => {
90
+ try {
91
+ srv.session.dispose();
92
+ }
93
+ catch {
94
+ /* dispose 尽力而为 */
95
+ }
96
+ };
97
+ const text = system.trim() ? `系统指令:${system.trim()}\n\n---\n\n任务:${prompt}` : prompt;
98
+ await srv.session.prompt(text, { expandPromptTemplates: false });
99
+ const raw = srv.session.getLastAssistantText() ?? "";
100
+ let usage;
101
+ try {
102
+ const stats = srv.session.getSessionStats();
103
+ usage = { input: stats.tokens.input, output: stats.tokens.output };
104
+ }
105
+ catch {
106
+ /* usage 尽力而为 */
107
+ }
108
+ return { ok: true, text: raw.slice(0, maxChars), model: modelName, ...(usage ? { usage } : {}) };
109
+ }
110
+ finally {
111
+ // 会话回收跟 run 走:超时竞速输了 run 还在飞,run 落定才 dispose,不留孤儿。
112
+ try {
113
+ dispose?.();
114
+ }
115
+ catch {
116
+ /* dispose 尽力而为 */
117
+ }
118
+ }
119
+ })();
120
+ const timer = new Promise((resolve) => setTimeout(() => resolve(fail(`llm.complete: 超时(约${Math.round(timeoutMs / 1000)}s)`)), timeoutMs));
121
+ return await Promise.race([run, timer]);
122
+ }
123
+ catch (err) {
124
+ return fail(`llm.complete: ${err.message}`);
125
+ }
126
+ finally {
127
+ inflight -= 1;
128
+ }
129
+ }