pi-web-ui 0.111.0 → 0.113.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 (88) hide show
  1. package/CHANGELOG.md +92 -2
  2. package/bin/frp-manager.mjs +9 -2
  3. package/bin/pi-web-ui.mjs +325 -45
  4. package/dist/server/agent-service-daemon.js +29 -4
  5. package/dist/server/agent-service.js +1527 -510
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/canvas/canvas-agent-tool.js +8 -0
  11. package/dist/server/canvas/canvas-orchestrator.js +128 -22
  12. package/dist/server/canvas/pstack-skills-data.js +498 -0
  13. package/dist/server/client-state.js +28 -0
  14. package/dist/server/delegate-mode.js +6 -3
  15. package/dist/server/delegate-task.js +18 -3
  16. package/dist/server/dispatch-domain-handlers.js +39 -11
  17. package/dist/server/dsh/dsh-agent-service.js +294 -15
  18. package/dist/server/dsh/dsh-serialize.js +1 -1
  19. package/dist/server/durable/durable-driver.js +112 -107
  20. package/dist/server/durable/durable-event-projector.js +253 -0
  21. package/dist/server/durable/durable-loader.js +1 -14
  22. package/dist/server/durable/durable-models.js +107 -0
  23. package/dist/server/durable/index.js +0 -4
  24. package/dist/server/engine-probe.js +111 -48
  25. package/dist/server/eval-tool.js +28 -3
  26. package/dist/server/goal-service.js +7 -0
  27. package/dist/server/index.js +371 -57
  28. package/dist/server/json-utils.js +57 -0
  29. package/dist/server/marker-service.js +8 -0
  30. package/dist/server/message-window.js +43 -10
  31. package/dist/server/model-admin.js +247 -163
  32. package/dist/server/model-resolver.js +66 -44
  33. package/dist/server/plan-manager.js +3 -6
  34. package/dist/server/plugin-api-catalog.js +1 -0
  35. package/dist/server/plugin-assets.js +238 -0
  36. package/dist/server/plugin-facilities.js +22 -0
  37. package/dist/server/plugin-ui-slots.js +1 -0
  38. package/dist/server/plugins.js +209 -11
  39. package/dist/server/preset-fields.js +25 -1
  40. package/dist/server/preset-share.js +5 -2
  41. package/dist/server/prompt-assembler.js +2 -1
  42. package/dist/server/prompt-composer.js +18 -8
  43. package/dist/server/protocol-version.js +1 -1
  44. package/dist/server/queue-utils.js +156 -0
  45. package/dist/server/remote-ssh-service.js +110 -12
  46. package/dist/server/sdk-builtin-extensions.js +85 -0
  47. package/dist/server/serialize.js +1 -1
  48. package/dist/server/server-config.js +66 -0
  49. package/dist/server/session-parser.js +49 -13
  50. package/dist/server/session-search.js +4 -3
  51. package/dist/server/settings-service.js +74 -53
  52. package/dist/server/setup-page.js +632 -0
  53. package/dist/server/skill-discovery.js +361 -59
  54. package/dist/server/skill-maintenance.js +231 -0
  55. package/dist/server/skill-tool.js +32 -3
  56. package/dist/server/soft-cap.js +30 -6
  57. package/dist/server/subagent-helpers.js +22 -1
  58. package/dist/server/subagent-notify.js +93 -0
  59. package/dist/server/subagent-security-gate.js +282 -0
  60. package/dist/server/subagent-templates.js +8 -0
  61. package/dist/server/subagents.js +390 -48
  62. package/dist/server/terminals.js +196 -8
  63. package/dist/server/text-quote.js +61 -0
  64. package/dist/server/tool-approval.js +63 -4
  65. package/dist/server/tool-guards.js +208 -0
  66. package/dist/server/tool-host-factories.js +48 -10
  67. package/dist/server/tool-manager.js +106 -28
  68. package/dist/server/tool-overrides.js +21 -11
  69. package/dist/server/universal/driver-base.js +8 -0
  70. package/dist/server/universal/drivers/claude-code.js +116 -7
  71. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  72. package/dist/server/universal/index.js +0 -1
  73. package/dist/server/universal/universal-session.js +106 -10
  74. package/dist/server/worktree-service.js +189 -1
  75. package/docs/dsh-engine.md +1 -5
  76. package/package.json +1 -1
  77. package/plugin-sdk/client-utils.mjs +192 -5
  78. package/plugin-sdk/index.d.ts +63 -1
  79. package/plugin-sdk/index.mjs +94 -0
  80. package/plugin-sdk/package.json +5 -1
  81. package/plugins/catalog.json +21 -0
  82. package/web/dist/assets/{TerminalPanel-BiUNySMA.js → TerminalPanel-3wojLfLk.js} +2 -2
  83. package/web/dist/assets/index-A8YXwnpZ.js +2008 -0
  84. package/web/dist/assets/index-BwL7qBh6.css +1 -0
  85. package/web/dist/index.html +11 -2
  86. package/web/dist/sw.js +1 -1
  87. package/web/dist/assets/index-B0ajS__T.js +0 -697
  88. package/web/dist/assets/index-BHik5WGG.css +0 -1
@@ -32,3 +32,159 @@ export function removeQueuedByIndexOrText(list, text, index) {
32
32
  }
33
33
  return removeFirstOccurrence(list, text);
34
34
  }
35
+ let queueSeq = 0;
36
+ export function generateQueueId() {
37
+ return `q-${Date.now().toString(36)}-${(++queueSeq).toString(36)}`;
38
+ }
39
+ export function createQueuedEntry(text, opts) {
40
+ return {
41
+ id: opts?.id || generateQueueId(),
42
+ text,
43
+ images: opts?.images,
44
+ attachments: opts?.attachments,
45
+ createdAt: opts?.createdAt ?? Date.now(),
46
+ };
47
+ }
48
+ /**
49
+ * 跨端/跨引擎统一剔除排队条目:
50
+ * 1. 优先按 `query.id` 绝对精准匹配(免疫并发下标漂移与同文本覆盖);
51
+ * 2. 其次按 `query.index`(需校验文本相符);
52
+ * 3. 兜底按 `query.text` 匹配首处项(兼容旧客户端)。
53
+ */
54
+ export function removeQueuedEntry(list, query) {
55
+ if (query.id) {
56
+ const idx = list.findIndex((e) => e.id === query.id);
57
+ if (idx >= 0) {
58
+ return [...list.slice(0, idx), ...list.slice(idx + 1)];
59
+ }
60
+ }
61
+ if (typeof query.index === "number" &&
62
+ Number.isInteger(query.index) &&
63
+ query.index >= 0 &&
64
+ query.index < list.length &&
65
+ (!query.text || list[query.index]?.text === query.text)) {
66
+ return [...list.slice(0, query.index), ...list.slice(query.index + 1)];
67
+ }
68
+ if (query.text !== undefined) {
69
+ const idx = list.findIndex((e) => e.text === query.text);
70
+ if (idx >= 0) {
71
+ return [...list.slice(0, idx), ...list.slice(idx + 1)];
72
+ }
73
+ }
74
+ return [...list];
75
+ }
76
+ /**
77
+ * 按气泡下标移除一个排队条目(兼容历史调用签名)。
78
+ */
79
+ export function removeQueuedEntryByIndexOrText(list, text, index) {
80
+ return removeQueuedEntry(list, { text, index });
81
+ }
82
+ /**
83
+ * 入队 prompt 抛错时的快速回滚:从末尾向前查找第一个匹配文本的条目并弹出(issue #718)。
84
+ */
85
+ export function rollbackQueuedEntry(list, text) {
86
+ for (let i = list.length - 1; i >= 0; i--) {
87
+ if (list[i]?.text === text) {
88
+ return [...list.slice(0, i), ...list.slice(i + 1)];
89
+ }
90
+ }
91
+ return [...list];
92
+ }
93
+ /**
94
+ * 将本地条目列表与 SDK 权威的 `newTexts` 队列文本对账(issue #718)。
95
+ * 遵循 SDK 先进先出(FIFO)头部出队机制,优先保留尾部幸存者的完整条目元数据;
96
+ * 保证对账后返回的条目数量与顺序与 `newTexts` 严格一致。
97
+ */
98
+ export function reconcileQueuedEntries(currentEntries, newTexts) {
99
+ if (!newTexts || newTexts.length === 0) {
100
+ return [];
101
+ }
102
+ if (!currentEntries || currentEntries.length === 0) {
103
+ return newTexts.map((text) => createQueuedEntry(text));
104
+ }
105
+ // 1. 长度一致且文本逐项吻合
106
+ if (currentEntries.length === newTexts.length) {
107
+ let allMatch = true;
108
+ for (let i = 0; i < newTexts.length; i++) {
109
+ if (currentEntries[i]?.text !== newTexts[i]) {
110
+ allMatch = false;
111
+ break;
112
+ }
113
+ }
114
+ if (allMatch) {
115
+ return [...currentEntries];
116
+ }
117
+ }
118
+ // 2. 队列缩短(常见场景:SDK 头部 FIFO 出队消费一条或多条消息)
119
+ if (currentEntries.length > newTexts.length) {
120
+ const dropCount = currentEntries.length - newTexts.length;
121
+ const headDropped = currentEntries.slice(dropCount);
122
+ let matchesTail = true;
123
+ for (let i = 0; i < newTexts.length; i++) {
124
+ if (headDropped[i]?.text !== newTexts[i]) {
125
+ matchesTail = false;
126
+ break;
127
+ }
128
+ }
129
+ if (matchesTail) {
130
+ return headDropped;
131
+ }
132
+ }
133
+ // 3. 队列增长(常见场景:前缀保持,尾部追加)
134
+ if (currentEntries.length < newTexts.length) {
135
+ let prefixMatch = true;
136
+ for (let i = 0; i < currentEntries.length; i++) {
137
+ if (currentEntries[i]?.text !== newTexts[i]) {
138
+ prefixMatch = false;
139
+ break;
140
+ }
141
+ }
142
+ if (prefixMatch) {
143
+ const res = [...currentEntries];
144
+ for (let i = currentEntries.length; i < newTexts.length; i++) {
145
+ res.push(createQueuedEntry(newTexts[i]));
146
+ }
147
+ return res;
148
+ }
149
+ }
150
+ // 4. 容错通用对齐(例如中间删除或非对齐位移):
151
+ // 倒序优先匹配尾部幸存条目(排队为追加写入,尾部条目存活概率更高)
152
+ const available = currentEntries.map((e, idx) => ({ ...e, idx, used: false }));
153
+ const result = new Array(newTexts.length);
154
+ for (let i = newTexts.length - 1; i >= 0; i--) {
155
+ const targetText = newTexts[i];
156
+ let foundIdx = -1;
157
+ for (let j = available.length - 1; j >= 0; j--) {
158
+ if (!available[j].used && available[j].text === targetText) {
159
+ foundIdx = j;
160
+ break;
161
+ }
162
+ }
163
+ if (foundIdx !== -1) {
164
+ available[foundIdx].used = true;
165
+ const matched = available[foundIdx];
166
+ result[i] = {
167
+ id: matched.id,
168
+ text: targetText,
169
+ images: matched.images,
170
+ attachments: matched.attachments,
171
+ createdAt: matched.createdAt,
172
+ };
173
+ }
174
+ else {
175
+ result[i] = createQueuedEntry(targetText);
176
+ }
177
+ }
178
+ return result;
179
+ }
180
+ export function toQueuedPromptItems(entries) {
181
+ return entries.map((e) => ({
182
+ id: e.id,
183
+ text: e.text,
184
+ attachments: e.attachments,
185
+ createdAt: e.createdAt,
186
+ }));
187
+ }
188
+ export function toQueuedPromptTexts(entries) {
189
+ return entries.map((e) => e.text);
190
+ }
@@ -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)。
@@ -0,0 +1,85 @@
1
+ /**
2
+ * sdk-builtin-extensions.ts — 动态装配与筛选 @earendil-works/pi-coding-agent SDK 内置扩展。
3
+ *
4
+ * 职责:
5
+ * 1. 继承 SDK 原生内置扩展(如 builtin:llama.cpp、builtin:codemode、builtin:tool-search);
6
+ * 2. 精准隔离 SDK 内置 MCP 扩展(pi-web-ui 统一使用专属 McpBridge 管理,防止 MCP 进程双重派生);
7
+ * 3. 严格保留 builtin: true 与 replaceable 等元数据,确保 SDK DefaultResourceLoader 正确建立
8
+ * builtin:<name> 字典索引(解决 Issue #755:GUI 无法发现和使用 llama.cpp 本地模型的问题);
9
+ * 4. 遵循与 resolve-global-sdk / patch-remote-catalog 相同的事实源,兼容全局 SDK 与自带副本。
10
+ */
11
+ import { existsSync } from "node:fs";
12
+ import { dirname, join } from "node:path";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import { createCodemodeExtension, createToolSearchExtension } from "@earendil-works/pi-coding-agent";
15
+ let cachedEntries = null;
16
+ /**
17
+ * 解析当前生效 SDK 的 extensions/index.js 文件绝对路径。
18
+ */
19
+ export function resolveSdkExtensionsIndexPath() {
20
+ try {
21
+ const entry = fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent"));
22
+ const candidate = join(dirname(entry), "extensions", "index.js");
23
+ if (existsSync(candidate))
24
+ return candidate;
25
+ }
26
+ catch {
27
+ /* ignore resolve failure */
28
+ }
29
+ return null;
30
+ }
31
+ /**
32
+ * 获取经过宿主门禁过滤后的 SDK 内置扩展工厂列表(带内存缓存)。
33
+ * - 包含:llama.cpp、codemode、tool-search(以及未来 SDK 官方新增的提供商扩展)
34
+ * - 剔除:mcp(由 WebUI 独立 McpBridge 接管)
35
+ */
36
+ export async function getSdkBuiltinExtensionFactories() {
37
+ if (cachedEntries)
38
+ return cachedEntries;
39
+ const factories = [];
40
+ const indexPath = resolveSdkExtensionsIndexPath();
41
+ if (indexPath) {
42
+ try {
43
+ const mod = (await import(pathToFileURL(indexPath).href));
44
+ if (Array.isArray(mod.builtInExtensions)) {
45
+ for (const ext of mod.builtInExtensions) {
46
+ // 严格屏蔽 SDK 内置 mcp:避免与宿主 McpBridge 重复连接和拉起 stdio 进程
47
+ if (ext.name === "mcp")
48
+ continue;
49
+ factories.push({
50
+ name: ext.name,
51
+ factory: ext.factory,
52
+ builtin: ext.builtin ?? true,
53
+ replaceable: ext.replaceable ?? false,
54
+ hidden: true,
55
+ });
56
+ }
57
+ }
58
+ }
59
+ catch {
60
+ /* dynamic load failed, fall back below */
61
+ }
62
+ }
63
+ // 兜底回退:若未成功加载任何工厂,保证核心基础设施扩展可用
64
+ if (factories.length === 0) {
65
+ factories.push({
66
+ name: "codemode",
67
+ hidden: true,
68
+ replaceable: true,
69
+ builtin: true,
70
+ factory: createCodemodeExtension(),
71
+ }, {
72
+ name: "tool-search",
73
+ hidden: true,
74
+ replaceable: true,
75
+ builtin: true,
76
+ factory: createToolSearchExtension(),
77
+ });
78
+ }
79
+ cachedEntries = factories;
80
+ return factories;
81
+ }
82
+ /**
83
+ * 宿主层需禁用的 SDK 内置扩展名称清单(双保险,传给 disabledBuiltinExtensions)。
84
+ */
85
+ export const SDK_DISABLED_BUILTIN_EXTENSIONS = ["mcp"];
@@ -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
  * 视口/元素截图随便过;超大整页截图回落成占位文本(模型侧不受影响 —— 图它
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 本地配置页的持久化后端。
3
+ *
4
+ * `GET /setup` 与 `/api/setup/*` 只允许回环地址访问(见 isLoopbackAddress),
5
+ * 因此忘记 token 也能进——这正是它的存在意义。配置落在
6
+ * `<dataDir>/server-config.json`,优先级:命令行旗标 > 环境变量 > 本文件 > 默认值。
7
+ * 改 host/port/allowlist 需要重启服务生效;token 支持热旋转(index.ts 里 AUTH_TOKEN 是 let)。
8
+ */
9
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ const FILE_NAME = "server-config.json";
12
+ const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
13
+ export function configFilePath(dataDir) {
14
+ return join(dataDir, FILE_NAME);
15
+ }
16
+ export function loadServerFileConfig(dataDir) {
17
+ try {
18
+ const raw = readFileSync(configFilePath(dataDir), "utf8");
19
+ const parsed = JSON.parse(raw);
20
+ const out = {};
21
+ if (typeof parsed.port === "number" && Number.isInteger(parsed.port))
22
+ out.port = parsed.port;
23
+ if (typeof parsed.host === "string" && parsed.host.trim())
24
+ out.host = parsed.host.trim();
25
+ if (typeof parsed.token === "string")
26
+ out.token = parsed.token;
27
+ if (typeof parsed.allowHosts === "string")
28
+ out.allowHosts = parsed.allowHosts;
29
+ if (Array.isArray(parsed.allowHosts))
30
+ out.allowHosts = parsed.allowHosts.filter((s) => typeof s === "string").join(",");
31
+ if (typeof parsed.allowOrigins === "string")
32
+ out.allowOrigins = parsed.allowOrigins;
33
+ if (Array.isArray(parsed.allowOrigins))
34
+ out.allowOrigins = parsed.allowOrigins.filter((s) => typeof s === "string").join(",");
35
+ return out;
36
+ }
37
+ catch {
38
+ return {};
39
+ }
40
+ }
41
+ export function saveServerFileConfig(dataDir, cfg) {
42
+ mkdirSync(dataDir, { recursive: true });
43
+ writeFileSync(configFilePath(dataDir), `${JSON.stringify(cfg, null, "\t")}\n`, "utf8");
44
+ }
45
+ /** 回环判定:IPv4 127/8、IPv6 ::1(含 IPv4 映射)都算本地。 */
46
+ export function isLoopbackAddress(remoteAddress) {
47
+ if (!remoteAddress)
48
+ return false;
49
+ const ip = remoteAddress.trim().toLowerCase();
50
+ if (LOOPBACK.has(ip))
51
+ return true;
52
+ if (ip === "127.0.0.1" || ip.startsWith("127."))
53
+ return true;
54
+ // ::ffff:127.x.x.x 映射形
55
+ if (ip.startsWith("::ffff:127."))
56
+ return true;
57
+ return false;
58
+ }
59
+ /** token 强度小建议(不硬拦,只提示):空=不清/不设,短于 8 字符警告。 */
60
+ export function tokenWarning(token) {
61
+ if (!token)
62
+ return "";
63
+ if (token.length < 8)
64
+ return "口令短于 8 字符,局域网暴露时建议更长。";
65
+ return "";
66
+ }
@@ -7,8 +7,9 @@
7
7
  *
8
8
  * 从 agent-service.ts 抽出为独立模块。
9
9
  */
10
+ import { existsSync } from "node:fs";
10
11
  import * as fsPromises from "node:fs/promises";
11
- import { join, resolve } from "node:path";
12
+ import { basename, join, resolve } from "node:path";
12
13
  import { SessionManager } from "@earendil-works/pi-coding-agent";
13
14
  import { normalizePathKey } from "./client-state.js";
14
15
  import { MAX_SEARCH_TEXT_CHARS, readCwdFromSessionHeader, piSessionsRoot } from "./session-search.js";
@@ -347,29 +348,64 @@ export async function findMostRecentSessionFileFast(sessionDir, targetCwd) {
347
348
  return undefined;
348
349
  }
349
350
  let jsonlFiles = dirEntries.filter((f) => f.endsWith(".jsonl"));
350
- if (jsonlFiles.length === 0) {
351
+ const candidateFiles = new Map();
352
+ if (jsonlFiles.length > 0) {
353
+ for (const f of jsonlFiles) {
354
+ const fp = join(targetDir, f);
355
+ candidateFiles.set(normalizePathKey(fp), fp);
356
+ }
357
+ }
358
+ else {
351
359
  // 如果 targetDir 下没有 .jsonl 文件,可能是工作区根目录(sessionBaseDir),尝试解析物理存储目录
352
360
  try {
353
- const extra = piSessionsRoot();
354
- const resolvedStorageDir = extra ? resolve(extra) : SessionManager.create(targetDir).getSessionDir();
355
- if (resolvedStorageDir && resolvedStorageDir !== targetDir) {
361
+ const projectDir = SessionManager.create(targetDir).getSessionDir();
362
+ if (existsSync(projectDir)) {
356
363
  try {
357
- const storageEntries = await fsPromises.readdir(resolvedStorageDir);
358
- const storageJsonl = storageEntries.filter((f) => f.endsWith(".jsonl"));
359
- if (storageJsonl.length > 0) {
360
- targetDir = resolvedStorageDir;
361
- jsonlFiles = storageJsonl;
364
+ const entries = await fsPromises.readdir(projectDir);
365
+ for (const f of entries) {
366
+ if (f.endsWith(".jsonl")) {
367
+ const fp = join(projectDir, f);
368
+ candidateFiles.set(normalizePathKey(fp), fp);
369
+ }
362
370
  }
363
371
  }
364
372
  catch { }
365
373
  }
374
+ const extra = piSessionsRoot();
375
+ if (extra) {
376
+ const resolvedExtra = resolve(extra);
377
+ if (existsSync(resolvedExtra)) {
378
+ try {
379
+ const entries = await fsPromises.readdir(resolvedExtra);
380
+ for (const f of entries) {
381
+ if (f.endsWith(".jsonl")) {
382
+ const fp = join(resolvedExtra, f);
383
+ candidateFiles.set(normalizePathKey(fp), fp);
384
+ }
385
+ }
386
+ }
387
+ catch { }
388
+ const extraSubdir = join(resolvedExtra, basename(projectDir));
389
+ if (normalizePathKey(extraSubdir) !== normalizePathKey(projectDir) && existsSync(extraSubdir)) {
390
+ try {
391
+ const subEntries = await fsPromises.readdir(extraSubdir);
392
+ for (const f of subEntries) {
393
+ if (f.endsWith(".jsonl")) {
394
+ const fp = join(extraSubdir, f);
395
+ candidateFiles.set(normalizePathKey(fp), fp);
396
+ }
397
+ }
398
+ }
399
+ catch { }
400
+ }
401
+ }
402
+ }
366
403
  }
367
404
  catch { }
368
405
  }
369
- if (jsonlFiles.length === 0)
406
+ if (candidateFiles.size === 0)
370
407
  return undefined;
371
- const stats = await Promise.all(jsonlFiles.map(async (f) => {
372
- const fp = join(targetDir, f);
408
+ const stats = await Promise.all(Array.from(candidateFiles.values()).map(async (fp) => {
373
409
  try {
374
410
  const st = await fsPromises.stat(fp);
375
411
  return { path: fp, mtime: st.mtimeMs };
@@ -124,11 +124,12 @@ export function piSessionsRoot() {
124
124
  * Shared by deleteSession/renameSession/switchSession so the open path cannot
125
125
  * escape the confinement the write paths already enforce. */
126
126
  export function isInsideSessionsDir(agentDir, targetPath) {
127
- const abs = resolve(targetPath);
128
- const roots = [resolve(agentDir, "sessions")];
127
+ const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
128
+ const abs = fold(resolve(targetPath));
129
+ const roots = [fold(resolve(agentDir, "sessions"))];
129
130
  const extra = piSessionsRoot();
130
131
  if (extra)
131
- roots.push(resolve(extra));
132
+ roots.push(fold(resolve(extra)));
132
133
  return roots.some((root) => abs.startsWith(root + sep));
133
134
  }
134
135
  /**