pi-web-ui 0.88.0 → 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.
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * All-source update check: pi-web-ui itself, the installed pi core
3
3
  * (@earendil-works/pi-coding-agent — probed via `pi --version`, with a
4
- * vendored-copy fallback), plus the DIRECT pi extensions declared in
5
- * <agentDir>/npm/package.json (fallback: raw node_modules walk).
4
+ * vendored-copy fallback), the DIRECT pi extensions declared in
5
+ * <agentDir>/npm/package.json (fallback: raw node_modules walk), plus the
6
+ * git-source extensions declared in global/project settings.json (issue #178).
6
7
  * Pure logic lives here so it can be unit-tested with an injected fetcher
7
8
  * (and an injected pi-core probe); ClientSession only wires it to the wire
8
9
  * protocol.
9
10
  */
11
+ import { execFile } from "node:child_process";
10
12
  import { readdirSync, readFileSync, realpathSync, existsSync } from "node:fs";
11
13
  import { delimiter, dirname, join } from "node:path";
14
+ import { promisify } from "node:util";
12
15
  import { pick } from "./i18n.js";
13
16
  const PI_CORE_PACKAGE = "@earendil-works/pi-coding-agent";
14
17
  /** npm 官方源;用户在 <agentDir>/npm/.npmrc 里配了镜像/私有源时会被覆盖(issue #151)。 */
@@ -155,6 +158,203 @@ function readLocalPackage(dir) {
155
158
  return null;
156
159
  }
157
160
  }
161
+ // -- git-source extensions (issue #178) --------------------------------------
162
+ // The panel historically enumerated only npm direct deps, so `git:` entries in
163
+ // settings.json never appeared. pi core updates both (`updateConfiguredSources`
164
+ // buckets npmCandidates/gitCandidates), keyed by normalized `git:host/path`.
165
+ const execFileAsync = promisify(execFile);
166
+ /** Matches pi core NETWORK_TIMEOUT_MS so slow forges degrade the same way. */
167
+ const GIT_TIMEOUT_MS = 10_000;
168
+ function hasUnsafeGitPart(value, allowSlash) {
169
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
170
+ return true;
171
+ if (!allowSlash && value.includes("/"))
172
+ return true;
173
+ if (value.split("/").includes(".."))
174
+ return true;
175
+ return false;
176
+ }
177
+ function normalizeGitRepo(host, path, ref) {
178
+ const cleanPath = path.replace(/\.git$/, "").replace(/^\/+|\/+$/g, "");
179
+ if (!host || !cleanPath || cleanPath.split("/").length < 2)
180
+ return null;
181
+ if (hasUnsafeGitPart(host, false) || hasUnsafeGitPart(cleanPath, true))
182
+ return null;
183
+ if (ref !== null && (ref === "" || ref.includes("\0")))
184
+ return null;
185
+ return {
186
+ host,
187
+ path: cleanPath,
188
+ ref,
189
+ shorthand: `${host}/${cleanPath}`,
190
+ identity: `git:${host}/${cleanPath}`,
191
+ };
192
+ }
193
+ /** Split `rest` (the part after the host) on the first `@` into path + ref. */
194
+ function splitGitRef(rest) {
195
+ const at = rest.indexOf("@");
196
+ if (at < 0)
197
+ return { path: rest, ref: null };
198
+ return { path: rest.slice(0, at), ref: rest.slice(at + 1) || null };
199
+ }
200
+ /**
201
+ * Parse a settings `packages` entry into a git source, or null when it is not
202
+ * one. Accepts the same shapes pi core does (`parseGitUrl`): `git:`-prefixed
203
+ * shorthand/URLs plus bare explicit protocol URLs. `npm:`/local entries yield
204
+ * null — they are handled by the npm enumeration, not here.
205
+ */
206
+ export function parseGitExtensionSource(entry) {
207
+ const trimmed = entry.trim();
208
+ if (!trimmed || trimmed.startsWith("npm:"))
209
+ return null;
210
+ const url = trimmed.startsWith("git:") ? trimmed.slice(4).trim() : trimmed;
211
+ if (!url)
212
+ return null;
213
+ // scp-like: git@host:owner/repo[.git][@ref]
214
+ const scp = url.match(/^git@([^:]+):(.+)$/);
215
+ if (scp) {
216
+ const { path, ref } = splitGitRef(scp[2]);
217
+ return normalizeGitRepo(scp[1], path, ref);
218
+ }
219
+ // Explicit protocol URLs (bare or git:-prefixed).
220
+ if (/^(https?|ssh|git):\/\//i.test(url)) {
221
+ let host;
222
+ let rest;
223
+ try {
224
+ const parsed = new URL(url);
225
+ host = parsed.hostname;
226
+ rest = parsed.pathname.replace(/^\/+/, "");
227
+ }
228
+ catch {
229
+ return null;
230
+ }
231
+ const { path, ref } = splitGitRef(rest);
232
+ return normalizeGitRepo(host, path, ref);
233
+ }
234
+ // Shorthand only with an explicit git: prefix (bare `a/b` is a local path).
235
+ if (!trimmed.startsWith("git:"))
236
+ return null;
237
+ const slash = url.indexOf("/");
238
+ if (slash < 0)
239
+ return null;
240
+ const host = url.slice(0, slash);
241
+ if (!host.includes(".") && host !== "localhost")
242
+ return null;
243
+ const { path, ref } = splitGitRef(url.slice(slash + 1));
244
+ return normalizeGitRepo(host, path, ref);
245
+ }
246
+ /**
247
+ * Total switch for the git-source check (issue #178 step 8). `0/false/no/off`
248
+ * disables it (large-monorepo escape hatch); unset or anything else enables.
249
+ */
250
+ export function isGitExtensionCheckEnabled(env = process.env) {
251
+ const v = (env.PI_WEB_GIT_EXTENSION_CHECK ?? "").trim().toLowerCase();
252
+ return v !== "0" && v !== "false" && v !== "no" && v !== "off";
253
+ }
254
+ function readSettingsPackagesFile(file) {
255
+ try {
256
+ const data = JSON.parse(readFileSync(file, "utf8"));
257
+ if (!data || typeof data !== "object" || !Array.isArray(data.packages))
258
+ return [];
259
+ return data.packages.filter((p) => typeof p === "string" || (p !== null && typeof p === "object"));
260
+ }
261
+ catch {
262
+ return [];
263
+ }
264
+ }
265
+ function readGitCloneNameVersion(installDir) {
266
+ try {
267
+ const pkg = JSON.parse(readFileSync(join(installDir, "package.json"), "utf8"));
268
+ if (!pkg.name || !pkg.version)
269
+ return null;
270
+ return { name: pkg.name, version: pkg.version };
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ }
276
+ /**
277
+ * Enumerate `git:` entries from global (<agentDir>/settings.json) plus project
278
+ * (<projectCwd>/.pi/settings.json) settings — the same two scopes pi core
279
+ * updates. Project wins on identity collision (mirrors core dedupePackages).
280
+ * Entries whose clone is missing are still listed (version `?`): checkAll
281
+ * reports them as per-item errors instead of silently dropping the row.
282
+ */
283
+ export function listGitExtensions(agentDir, projectCwd, env = process.env) {
284
+ if (!isGitExtensionCheckEnabled(env))
285
+ return [];
286
+ const scopes = [];
287
+ if (projectCwd)
288
+ scopes.push({ file: join(projectCwd, ".pi", "settings.json"), gitRoot: join(projectCwd, ".pi", "git") });
289
+ scopes.push({ file: join(agentDir, "settings.json"), gitRoot: join(agentDir, "git") });
290
+ const seen = new Set();
291
+ const out = [];
292
+ for (const { file, gitRoot } of scopes) {
293
+ for (const pkg of readSettingsPackagesFile(file)) {
294
+ const raw = typeof pkg === "string" ? pkg : typeof pkg.source === "string" ? pkg.source : null;
295
+ if (!raw)
296
+ continue;
297
+ const parsed = parseGitExtensionSource(raw);
298
+ if (!parsed || seen.has(parsed.identity))
299
+ continue;
300
+ seen.add(parsed.identity);
301
+ const installDir = join(gitRoot, parsed.host, ...parsed.path.split("/"));
302
+ const nv = readGitCloneNameVersion(installDir);
303
+ out.push({
304
+ name: nv?.name ?? parsed.shorthand,
305
+ version: nv?.version ?? "?",
306
+ kind: "git-extension",
307
+ source: parsed.shorthand,
308
+ installDir,
309
+ ref: parsed.ref,
310
+ });
311
+ }
312
+ }
313
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
314
+ }
315
+ /** Display form for git rows: `<version> (<short sha>)`, sha-only when the
316
+ * clone has no readable package.json version (issue #178 step 5). */
317
+ export function formatGitVersion(version, sha) {
318
+ const short = sha.slice(0, 7);
319
+ return version && version !== "?" ? `${version} (${short})` : short;
320
+ }
321
+ async function runGit(args, cwd) {
322
+ const { stdout } = await execFileAsync("git", args, {
323
+ cwd,
324
+ timeout: GIT_TIMEOUT_MS,
325
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
326
+ });
327
+ return stdout.trim();
328
+ }
329
+ /**
330
+ * Compare a clone's HEAD against its remote (lightweight: `ls-remote` fetches
331
+ * refs only, no objects). Upstream branch wins when configured, else origin
332
+ * HEAD — the same order pi core `getRemoteGitHead` uses.
333
+ */
334
+ export async function defaultCheckGitExtension(installDir) {
335
+ const localSha = await runGit(["rev-parse", "HEAD"], installDir);
336
+ if (!/^[0-9a-f]{40}$/i.test(localSha))
337
+ throw new Error(`Bad local HEAD: ${localSha.slice(0, 20)}`);
338
+ let remoteSha = null;
339
+ try {
340
+ const upstream = await runGit(["rev-parse", "--abbrev-ref", "@{upstream}"], installDir);
341
+ const branch = upstream.match(/^origin\/(.+)$/)?.[1];
342
+ if (branch) {
343
+ const out = await runGit(["ls-remote", "origin", `refs/heads/${branch}`], installDir);
344
+ remoteSha = out.match(/^([0-9a-f]{40})\s+/m)?.[1] ?? null;
345
+ }
346
+ }
347
+ catch {
348
+ /* no usable upstream — fall through to origin HEAD */
349
+ }
350
+ if (!remoteSha) {
351
+ const out = await runGit(["ls-remote", "origin", "HEAD"], installDir);
352
+ remoteSha = out.match(/^([0-9a-f]{40})\s+HEAD$/m)?.[1] ?? null;
353
+ }
354
+ if (!remoteSha)
355
+ throw new Error("Failed to determine remote HEAD");
356
+ return { localSha, remoteSha };
357
+ }
158
358
  /** How long a pi probe result stays hot (mirrors ClientSession.piCliProbe). */
159
359
  const PI_PROBE_TTL_MS = 10_000;
160
360
  let piCoreProbe = null;
@@ -236,13 +436,14 @@ function readVendoredPiCore(agentDir) {
236
436
  }
237
437
  }
238
438
  /**
239
- * Build the full local target list: webui + the pi core + installed packages.
439
+ * Build the full local target list: webui + the pi core + installed packages
440
+ * + git-source extensions (issue #178) from global and project settings.
240
441
  * The pi core version comes from the CLI probe (injectable for tests), falling
241
442
  * back to the vendored copy under <agentDir>/npm/node_modules. Packages
242
443
  * listing the core directly are filtered out so the pi-core row wins — never
243
444
  * two rows for the same package.
244
445
  */
245
- export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProbePiCore) {
446
+ export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProbePiCore, opts) {
246
447
  const targets = [{ name: "pi-web-ui", version: webuiVersion, kind: "webui" }];
247
448
  const coreVersion = probePiCore() ?? readVendoredPiCore(agentDir);
248
449
  if (coreVersion) {
@@ -253,6 +454,7 @@ export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProb
253
454
  });
254
455
  }
255
456
  targets.push(...listInstalledPackages(agentDir).filter((pkg) => pkg.name !== PI_CORE_PACKAGE));
457
+ targets.push(...listGitExtensions(agentDir, opts?.projectCwd));
256
458
  return targets;
257
459
  }
258
460
  /** Default fetcher (real network). Tests inject a fake. */
@@ -361,24 +563,61 @@ export async function fetchLatest(fetcher, name, registry = NPM_DEFAULT_REGISTRY
361
563
  };
362
564
  }
363
565
  /**
364
- * Check every target against the registry. One failed lookup degrades to an
365
- * error item (upToDate: false) without failing the rest. Results keep the
366
- * input order. Bounded concurrency (CONCURRENCY) keeps registry load polite.
566
+ * Check every target: npm kinds against the registry, git-extension kinds
567
+ * against their clone's remote (`ls-remote`, refs only). One failed lookup
568
+ * degrades to an error item (upToDate: false) without failing the rest.
569
+ * Results keep the input order. Bounded concurrency (CONCURRENCY) keeps
570
+ * registry/remote load polite. The git checker is injectable for tests.
367
571
  */
368
572
  export async function checkAll(targets, fetcher = defaultFetcher,
369
- /** 单项 registry 查询失败时的 error 文案语言(默认英文)。 */
573
+ /** 单项查询失败时的 error 文案语言(默认英文)。 */
370
574
  lang,
371
575
  /** 镜像/私有源配置(默认官方源;调用方经 resolveNpmRegistry 传入 .npmrc,issue #151)。 */
372
- registryConfig) {
576
+ registryConfig,
577
+ /** git 源远端比较(默认真 git;单测注入 fake,issue #178)。 */
578
+ gitCheck = defaultCheckGitExtension) {
373
579
  const l = lang?.() ?? "en";
374
580
  const registry = registryConfig?.registry ?? NPM_DEFAULT_REGISTRY;
375
581
  const authHeader = registryConfig?.authHeader ?? null;
582
+ const fail = (t, errMessage) => ({
583
+ name: t.name,
584
+ kind: t.kind,
585
+ current: t.version,
586
+ latest: null,
587
+ latestPublishedAt: null,
588
+ upToDate: false,
589
+ ...(t.source ? { source: t.source } : {}),
590
+ error: pick(l, `检查更新失败:${errMessage}`, `Failed to check for updates: ${errMessage}`, "updatecheck.check.failed", {
591
+ errMessage,
592
+ }),
593
+ });
376
594
  const results = Array.from({ length: targets.length });
377
595
  let cursor = 0;
378
596
  async function worker() {
379
597
  while (cursor < targets.length) {
380
598
  const i = cursor++;
381
599
  const t = targets[i];
600
+ if (t.kind === "git-extension") {
601
+ try {
602
+ if (!t.installDir)
603
+ throw new Error("missing install dir");
604
+ const { localSha, remoteSha } = await gitCheck(t.installDir);
605
+ const upToDate = localSha.trim() === remoteSha.trim();
606
+ results[i] = {
607
+ name: t.name,
608
+ kind: t.kind,
609
+ current: formatGitVersion(t.version, localSha),
610
+ latest: formatGitVersion(t.version, remoteSha),
611
+ latestPublishedAt: null,
612
+ upToDate,
613
+ ...(t.source ? { source: t.source } : {}),
614
+ };
615
+ }
616
+ catch (err) {
617
+ results[i] = fail(t, err.message);
618
+ }
619
+ continue;
620
+ }
382
621
  try {
383
622
  const { latest, latestPublishedAt } = await fetchLatest(fetcher, t.name, registry, authHeader);
384
623
  results[i] = {
@@ -391,16 +630,7 @@ registryConfig) {
391
630
  };
392
631
  }
393
632
  catch (err) {
394
- const errMessage = err.message;
395
- results[i] = {
396
- name: t.name,
397
- kind: t.kind,
398
- current: t.version,
399
- latest: null,
400
- latestPublishedAt: null,
401
- upToDate: false,
402
- error: pick(l, `检查更新失败:${errMessage}`, `Failed to check for updates: ${errMessage}`, "updatecheck.check.failed", { errMessage }),
403
- };
633
+ results[i] = fail(t, err.message);
404
634
  }
405
635
  }
406
636
  }
@@ -80,7 +80,8 @@ async function openBrowser(url: string): Promise<void> {
80
80
  platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
81
  // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
82
  // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
- spawn(cmd, rest, { stdio: "ignore", detached: true })
83
+ // Windows 下 detached 子进程会新建控制台闪窗;改为不 detached 并 windowsHide。
84
+ spawn(cmd, rest, { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true })
84
85
  .on("error", (err) => {
85
86
  if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
87
  console.warn(
@@ -163,7 +164,13 @@ export default function (pi: ExtensionAPI): void {
163
164
  PI_WEB_CWD: cwd,
164
165
  ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
166
  };
166
- const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
+ const proc = spawn(NODE, [SERVER_ENTRY], {
168
+ cwd,
169
+ env,
170
+ stdio: "ignore",
171
+ detached: process.platform !== "win32",
172
+ windowsHide: true,
173
+ });
167
174
  proc.unref();
168
175
  running.set(sid, { proc, port, cwd, url });
169
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.88.0",
3
+ "version": "0.89.0",
4
4
  "description": "Web chat interface for the pi coding agent, powered by the pi SDK (@earendil-works/pi-coding-agent) — one-command run, Docker/systemd/launchd deployable",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -88,6 +88,7 @@
88
88
  "@xterm/addon-fit": "^0.11.0",
89
89
  "@xterm/xterm": "^6.0.0",
90
90
  "compression": "^1.8.1",
91
+ "electron-updater": "^6.8.9",
91
92
  "express": "^4.21.2",
92
93
  "highlight.js": "^11.10.0",
93
94
  "katex": "^0.16.47",
@@ -115,9 +116,9 @@
115
116
  "@vitejs/plugin-react": "^4.3.4",
116
117
  "concurrently": "^9.1.0",
117
118
  "cross-env": "^10.1.0",
118
- "esbuild": "^0.25.12",
119
119
  "electron": "^44.0.0",
120
120
  "electron-builder": "^26.0.0",
121
+ "esbuild": "^0.25.12",
121
122
  "jsdom": "^26.1.0",
122
123
  "mermaid": "^11.17.2",
123
124
  "oxlint": "^1.81.0",
@@ -190,6 +190,8 @@ export interface PluginHost {
190
190
  path: string,
191
191
  handler: (req: unknown, res: unknown) => void,
192
192
  ): () => void;
193
+ /** 注册通用反向代理前缀(子路径去前缀透传到 127.0.0.1:port;要 "http" 能力;返回注销函数)。 */
194
+ registerProxy(prefix: string, target: number | { port: number; host?: string }): () => void;
193
195
  ui: PluginHostUi;
194
196
  llm: PluginHostLlm;
195
197
  storage: {
@@ -396,6 +398,8 @@ export interface MockHostControls {
396
398
  commands: Array<PluginCommandDef>;
397
399
  /** 已挂载的路由表(活数组,注销即摘除)。 */
398
400
  routes: Array<{ method: string; path: string; handler: (req: unknown, res: unknown) => void }>;
401
+ /** 已注册的代理前缀(活数组,注销即摘除)。 */
402
+ proxies: Array<{ prefix: string; target: number | { port: number; host?: string } }>;
399
403
  /** 已登记的定时任务(活数组 {spec, fn, opts};schedule() 不设真定时器,注销即摘除)。 */
400
404
  schedules: Array<{ spec: string | number; fn: () => void; opts?: PluginHostScheduleOptions }>;
401
405
  /** 依次触发全部已登记的定时回调(返回各回调返回值;抛错即 reject)。 */
@@ -262,6 +262,7 @@ export function createMockHost(overrides) {
262
262
  const agentToolStore = [];
263
263
  const commandStore = [];
264
264
  const routeStore = [];
265
+ const proxyStore = [];
265
266
  const scheduleStore = [];
266
267
  // 注册类:存定义体 + 返回只摘除本次注册的注销函数(与宿主同语义)。
267
268
  const remember = (store, entry) => {
@@ -365,6 +366,11 @@ export function createMockHost(overrides) {
365
366
  path: String(path ?? "/"),
366
367
  handler,
367
368
  }),
369
+ registerProxy: (prefix, target) =>
370
+ remember(proxyStore, {
371
+ prefix: String(prefix ?? "/"),
372
+ target: typeof target === "number" ? { port: target, host: "127.0.0.1" } : target,
373
+ }),
368
374
  fs: {
369
375
  list: async () => [],
370
376
  read: async () => new Uint8Array(0),
@@ -475,6 +481,9 @@ export function createMockHost(overrides) {
475
481
  get routes() {
476
482
  return routeStore;
477
483
  },
484
+ get proxies() {
485
+ return proxyStore;
486
+ },
478
487
  get schedules() {
479
488
  return scheduleStore;
480
489
  },
@@ -21,8 +21,8 @@
21
21
  "id": "vscode-editor",
22
22
  "name": "vscode-editor",
23
23
  "icon": "📝",
24
- "description": "类 VSCode 工作台:多根文件树 + CodeMirror 编辑器 + 底部终端 + Remote-SSH + SFTP 同步。",
25
- "descriptionEn": "VSCode-like workbench: multi-root file tree, CodeMirror editor, integrated terminal, Remote-SSH and SFTP sync.",
24
+ "description": "类 VSCode 工作台:多根文件树 + CodeMirror 编辑器 + 底部终端 + Remote-SSH + SFTP 同步;向 AI 注册 SFTP/SSH/远端文件工具,可自主传代码。",
25
+ "descriptionEn": "VSCode-like workbench: multi-root file tree, CodeMirror editor, integrated terminal, Remote-SSH and SFTP sync; registers SFTP/SSH/remote-file tools so the AI can deploy code itself.",
26
26
  "source": "xing-shuyin/pi-web-ui/plugins/vscode-editor",
27
27
  "homepage": "https://github.com/xing-shuyin/pi-web-ui/tree/main/plugins/vscode-editor"
28
28
  },
@@ -71,6 +71,15 @@
71
71
  "source": "xing-shuyin/pi-web-ui/plugins/voice-input",
72
72
  "homepage": "https://github.com/xing-shuyin/pi-web-ui/tree/main/plugins/voice-input"
73
73
  },
74
+ {
75
+ "id": "live-preview",
76
+ "name": "live-preview",
77
+ "icon": "🌐",
78
+ "description": "Live Server 式预览:/liveserver 看 HTML(含相对资源与自动刷新),/md 看 Markdown 渲染;真服务只绑回环地址,经宿主通用代理对外只露同源前缀。",
79
+ "descriptionEn": "Live-Server-style preview: HTML under /liveserver (relative assets + auto reload), rendered Markdown under /md. Loopback-only inner server exposed via host proxy prefixes.",
80
+ "source": "xing-shuyin/pi-web-ui/plugins/live-preview",
81
+ "homepage": "https://github.com/xing-shuyin/pi-web-ui/tree/main/plugins/live-preview"
82
+ },
74
83
  {
75
84
  "id": "image-toolkit",
76
85
  "name": "image-toolkit",
@@ -1,4 +1,4 @@
1
- import{a as i,j as n}from"./markdown-D3PKeHAZ.js";import{u as M,b as z,T as H,a as f,c as Z,F as ee,d as q,e as ne,f as G,g as te,r as se,h as ae,i as re,j as ie,k as le}from"./index-CQg5A74_.js";import{D as ce,o as oe}from"./xterm-B96xOxS9.js";import"./react-w24rH0km.js";function me(t){let c=null;return{clean:t.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(B,a)=>(c=Number(a),`\r
1
+ import{a as i,j as n}from"./markdown-D3PKeHAZ.js";import{u as M,b as z,T as H,a as f,c as Z,F as ee,d as q,e as ne,f as G,g as te,r as se,h as ae,i as re,j as ie,k as le}from"./index-3XU67qMh.js";import{D as ce,o as oe}from"./xterm-B96xOxS9.js";import"./react-w24rH0km.js";function me(t){let c=null;return{clean:t.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(B,a)=>(c=Number(a),`\r
2
2
  `)).replace(/\r?\n?\x1b\[90m\[(?:进程已退出,退出码 |Process exited with code )-?\d+\]\x1b\[0m\r?\n?/g,`\r
3
3
  `),exitCode:c}}function de({conversationId:t,terminalId:c,command:N,cwd:B,title:a,agentBash:w,active:u,running:x,exitCode:h,register:E}){const C=i.useRef(null),j=i.useRef(null),{locale:T}=M(),o=i.useRef(T);o.current=T;const v=N?JSON.stringify(N):"",F=i.useRef(x===!1);i.useEffect(()=>{const m=C.current;if(!m)return;const r=new ce({theme:z(),fontFamily:'"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace',fontSize:13,cursorBlink:!0,scrollback:8e3}),b=new oe;r.loadAddon(b),r.open(m),j.current={term:r,fit:b},u&&r.focus();const g=()=>{r.options.theme=z()};window.addEventListener(H,g),r.attachCustomKeyEventHandler(d=>{if(d.type!=="keydown")return!0;const D=d.key?.toLowerCase();if((d.ctrlKey||d.metaKey)&&D==="v")return!1;if(d.ctrlKey&&!d.shiftKey&&!d.altKey&&D==="c"&&r.hasSelection()){const _=r.textarea;return _&&(_.value=r.getSelection(),_.select()),!1}return!0});const $=E(t,c,{write:d=>r.write(me(d).clean),dispose:()=>r.dispose()}),A=()=>{try{b.fit(),f({type:"terminal_resize",terminalId:c,conversationId:t,cols:r.cols,rows:r.rows})}catch{}},I=requestAnimationFrame(()=>{try{b.fit()}catch{}F.current||(N?f({type:"run_command",terminalId:c,conversationId:t,command:N,cols:r.cols,rows:r.rows}):f({type:"terminal_create",terminalId:c,title:a,locale:o.current,agentBash:w,conversationId:t,cwd:B,cols:r.cols,rows:r.rows}))}),S=r.onData(d=>{f({type:"terminal_input",terminalId:c,conversationId:t,data:d})});let k=null;return typeof ResizeObserver<"u"&&(k=new ResizeObserver(()=>{m.offsetWidth>0&&m.offsetHeight>0&&A()}),k.observe(m)),()=>{cancelAnimationFrame(I),S.dispose(),window.removeEventListener(H,g),k?.disconnect(),$(),r.dispose(),j.current=null}},[t,c,v,E]),i.useEffect(()=>{if(!u)return;const m=requestAnimationFrame(()=>{const r=j.current;if(r){try{r.fit.fit(),f({type:"terminal_resize",terminalId:c,conversationId:t,cols:r.term.cols,rows:r.term.rows})}catch{}r.term.focus()}});return()=>cancelAnimationFrame(m)},[u]);const{t:R}=M(),p=i.useRef(void 0);return i.useEffect(()=>{if(x===p.current||(p.current=x,x!==!1))return;const m=j.current;m&&m.term.write(`\r
4
4
  \x1B[90m${R("exitBanner",{code:h??""})}\x1B[0m\r