pi-web-ui 0.87.2 → 0.88.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.
@@ -0,0 +1,59 @@
1
+ import os from "node:os";
2
+ function calculateMemoryPercent(snapshot) {
3
+ const memoryUsed = Math.max(0, snapshot.memoryTotal - snapshot.memoryFree);
4
+ return snapshot.memoryTotal > 0 ? Math.max(0, Math.min(100, (memoryUsed / snapshot.memoryTotal) * 100)) : 0;
5
+ }
6
+ export function defaultReadSnapshot() {
7
+ const cpus = os.cpus();
8
+ let cpuIdle = 0;
9
+ let cpuTotal = 0;
10
+ for (const cpu of cpus) {
11
+ const times = cpu.times;
12
+ const total = (times.user ?? 0) + (times.nice ?? 0) + (times.sys ?? 0) + (times.idle ?? 0) + (times.irq ?? 0);
13
+ cpuIdle += times.idle ?? 0;
14
+ cpuTotal += total;
15
+ }
16
+ return {
17
+ cpuIdle,
18
+ cpuTotal,
19
+ memoryFree: os.freemem(),
20
+ memoryTotal: os.totalmem(),
21
+ };
22
+ }
23
+ export function calculateHostMetrics(previous, current) {
24
+ const totalDelta = current.cpuTotal - previous.cpuTotal;
25
+ const idleDelta = current.cpuIdle - previous.cpuIdle;
26
+ let cpuPercent = null;
27
+ if (totalDelta > 0) {
28
+ const rawPercent = (1 - idleDelta / totalDelta) * 100;
29
+ cpuPercent = Math.max(0, Math.min(100, rawPercent));
30
+ }
31
+ const memoryPercent = calculateMemoryPercent(current);
32
+ return {
33
+ cpuPercent,
34
+ memoryPercent,
35
+ };
36
+ }
37
+ export function createHostMetricsSampler(readSnapshot = defaultReadSnapshot) {
38
+ let previous = null;
39
+ try {
40
+ previous = readSnapshot();
41
+ }
42
+ catch {
43
+ // 初始基线读取异常时不击穿服务启动,待后续心跳重试
44
+ previous = null;
45
+ }
46
+ return () => {
47
+ const current = readSnapshot();
48
+ if (!previous) {
49
+ previous = current;
50
+ return {
51
+ cpuPercent: null,
52
+ memoryPercent: calculateMemoryPercent(current),
53
+ };
54
+ }
55
+ const metrics = calculateHostMetrics(previous, current);
56
+ previous = current;
57
+ return metrics;
58
+ };
59
+ }
@@ -45,6 +45,7 @@ import { PluginInstaller } from "./plugin-installer.js";
45
45
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
46
46
  import { McpBridge } from "./mcp-bridge.js";
47
47
  import { createMcpHotReload } from "./mcp-hot-reload.js";
48
+ import { createHostMetricsSampler } from "./host-metrics.js";
48
49
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
49
50
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
50
51
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -679,15 +680,27 @@ httpServer.on("upgrade", (req, socket, head) => {
679
680
  });
680
681
  });
681
682
  // Heartbeat: lets clients detect half-open connections (server killed without
682
- // closing sockets, sleep/wake, network partitions). Idle connections otherwise
683
- // carry no traffic and TCP keepalive defaults are far too slow (~2h).
683
+ // closing sockets, sleep/wake, network partitions). Also broadcasts lightweight
684
+ // server host metrics (CPU and memory usage) sampled every ~2s.
685
+ const HEARTBEAT_INTERVAL_MS = 2_000;
686
+ const sampleHostMetrics = createHostMetricsSampler();
684
687
  const heartbeatTimer = setInterval(() => {
685
- for (const ws of wss.clients) {
686
- if (ws.readyState === WebSocket.OPEN) {
687
- ws.send(JSON.stringify({ type: "heartbeat" }));
688
+ let message = { type: "heartbeat" };
689
+ try {
690
+ message = { type: "heartbeat", hostMetrics: sampleHostMetrics() };
691
+ }
692
+ catch {
693
+ // 继续发送普通心跳,下一轮重试采样。
694
+ }
695
+ if (wss.clients.size > 0) {
696
+ const payload = JSON.stringify(message);
697
+ for (const ws of wss.clients) {
698
+ if (ws.readyState === WebSocket.OPEN) {
699
+ ws.send(payload);
700
+ }
688
701
  }
689
702
  }
690
- }, 10_000);
703
+ }, HEARTBEAT_INTERVAL_MS);
691
704
  // 引擎分发:PI_WEB_ENGINE=dsh 时使用 DeepSeek Harness 引擎(server/dsh/),
692
705
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
693
706
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
@@ -754,6 +767,60 @@ pluginMgr.pathAccessRequester = (pluginId, dir, reason) => new Promise((resolve)
754
767
  });
755
768
  // 用户点了「允许」→ 授权表变了 → 立刻重推给所有在线客户端(设置面板「已授权目录」即时可见)。
756
769
  pluginMgr.onGrantsChanged = () => pushPluginGrants();
770
+ const pendingPermissionRequests = new Map();
771
+ /** 把能力授权表推给所有在线客户端(设置面板展示 + 撤销后刷新)。 */
772
+ function pushPluginPermissions() {
773
+ const payload = JSON.stringify({ type: "plugin_permissions", grants: pluginMgr.permGrants.list() });
774
+ for (const client of wss.clients) {
775
+ if (client.readyState === WebSocket.OPEN) {
776
+ try {
777
+ client.send(payload);
778
+ }
779
+ catch {
780
+ /* 死连接 */
781
+ }
782
+ }
783
+ }
784
+ }
785
+ pluginMgr.permissionRequester = (pluginId, req) => new Promise((resolve) => {
786
+ const id = randomUUID();
787
+ const resolved = JSON.stringify({ type: "plugin_permission_resolved", id });
788
+ const timer = setTimeout(() => {
789
+ pendingPermissionRequests.delete(id);
790
+ for (const client of wss.clients) {
791
+ if (client.readyState === WebSocket.OPEN) {
792
+ try {
793
+ client.send(resolved);
794
+ }
795
+ catch {
796
+ /* 死连接 */
797
+ }
798
+ }
799
+ }
800
+ resolve({ ok: false, remember: false });
801
+ }, 120_000);
802
+ pendingPermissionRequests.set(id, { resolve, timer });
803
+ const ask = JSON.stringify({
804
+ type: "plugin_permission_request",
805
+ id,
806
+ pluginId,
807
+ family: req.family,
808
+ ...(req.hosts ? { hosts: req.hosts } : {}),
809
+ ...(req.models ? { models: req.models } : {}),
810
+ ...(req.reason ? { reason: req.reason } : {}),
811
+ });
812
+ for (const client of wss.clients) {
813
+ if (client.readyState === WebSocket.OPEN) {
814
+ try {
815
+ client.send(ask);
816
+ }
817
+ catch {
818
+ /* 死连接 */
819
+ }
820
+ }
821
+ }
822
+ });
823
+ pluginMgr.onPermGrantsChanged = () => pushPluginPermissions();
757
824
  /** 广播通知条给全部在线客户端(全局事件,不属于某个 ClientSession —— 如 mcp.json 坏)。 */
758
825
  function pushNoticeToAll(level, text, textEn) {
759
826
  const payload = JSON.stringify({ type: "notice", level, text, textEn });
@@ -907,6 +974,19 @@ service.pluginStopBgTask = (taskId) => pluginMgr.stopPluginBgTask(taskId);
907
974
  return { ok: false, error: err.message };
908
975
  }
909
976
  };
977
+ // llmProvider:插件直调模型(孤立无工具的一次性补全,不建对话)。
978
+ // 标准 pi 引擎走 service.completeForPlugins;DSH/未知引擎回 {ok:false},绝不抛错。
979
+ pm.llmProvider = async (pluginId, req) => {
980
+ try {
981
+ const svc = service;
982
+ if (typeof svc.completeForPlugins !== "function")
983
+ return { ok: false, error: "当前引擎不支持 LLM 直调(仅标准 pi 引擎)" };
984
+ return await svc.completeForPlugins(pluginId, (req ?? {}));
985
+ }
986
+ catch (err) {
987
+ return { ok: false, error: err.message };
988
+ }
989
+ };
910
990
  }
911
991
  // 插件宿主工作区实时跟随当前项目:任意客户端 set_cwd 成功后同步给
912
992
  // PluginManager,编辑器等工作区跟随型插件随即切根(详见 plugins.ts notifyCwd)。
@@ -1492,6 +1572,29 @@ wss.on("connection", (ws) => {
1492
1572
  }
1493
1573
  break;
1494
1574
  }
1575
+ // -- 插件能力授权(host.requestPermission)-------------------------------
1576
+ case "plugin_permission_response": {
1577
+ const id = String(msg.id ?? "");
1578
+ const pending = pendingPermissionRequests.get(id);
1579
+ if (pending) {
1580
+ clearTimeout(pending.timer);
1581
+ pendingPermissionRequests.delete(id);
1582
+ // 先答复者胜:通知其它在线端收起同一条请求(与目录授权不同,这里要显式 resolved)。
1583
+ const resolved = JSON.stringify({ type: "plugin_permission_resolved", id });
1584
+ for (const client of wss.clients) {
1585
+ if (client.readyState === WebSocket.OPEN) {
1586
+ try {
1587
+ client.send(resolved);
1588
+ }
1589
+ catch {
1590
+ /* 死连接 */
1591
+ }
1592
+ }
1593
+ }
1594
+ pending.resolve({ ok: msg.ok === true, remember: msg.remember === true });
1595
+ }
1596
+ break;
1597
+ }
1495
1598
  case "plugin_dom_consent": {
1496
1599
  void pluginMgr
1497
1600
  .setDomConsent(msg.pluginId, msg.granted === true)
@@ -1514,6 +1617,18 @@ wss.on("connection", (ws) => {
1514
1617
  pushPluginGrants();
1515
1618
  break;
1516
1619
  }
1620
+ case "plugin_permission_revoke": {
1621
+ const family = msg.family === "net" || msg.family === "llm" ? msg.family : undefined;
1622
+ const removed = pluginMgr.permGrants.revoke(typeof msg.pluginId === "string" ? msg.pluginId : undefined, family, typeof msg.host === "string" || typeof msg.model === "string"
1623
+ ? {
1624
+ ...(typeof msg.host === "string" ? { host: msg.host } : {}),
1625
+ ...(typeof msg.model === "string" ? { model: msg.model } : {}),
1626
+ }
1627
+ : undefined);
1628
+ cs?.emitNotice("info", `已撤销 ${removed} 条能力授权`, `Revoked ${removed} permission grant(s)`);
1629
+ pushPluginPermissions();
1630
+ break;
1631
+ }
1517
1632
  // -- 插件市场目录同步(issue #148)--------------------------------------
1518
1633
  case "plugin_catalog_sync": {
1519
1634
  const syncLang = () => cs?.getLang() ?? "en";
@@ -1634,6 +1749,8 @@ wss.on("connection", (ws) => {
1634
1749
  pluginMgr.notifyAttach(cid);
1635
1750
  // 插件目录授权表(设置面板展示 + 可撤销)
1636
1751
  send({ type: "plugin_grants", grants: pluginMgr.grants.list() });
1752
+ // 插件能力授权表(设置面板展示 + 可撤销;session 授权带标记)
1753
+ send({ type: "plugin_permissions", grants: pluginMgr.permGrants.list() });
1637
1754
  // 插件命令可能在本客户端 attach 过程中才注册(首载竞态)——
1638
1755
  // 重推一次目录,保证选择器完整。
1639
1756
  service.applyPluginCommandCatalog();
@@ -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
+ }