pi-model-manager 0.3.5 → 0.4.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.
package/README.en.md CHANGED
@@ -4,7 +4,7 @@ English · [简体中文](./README.md)
4
4
 
5
5
  [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.85.1-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
- [![Version](https://img.shields.io/badge/version-0.3.5-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.3.7-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
8
8
 
9
9
  A TUI model and provider manager for [Pi](https://github.com/earendil-works/pi). It keeps Pi's native `models.json` as the single source of truth for model configuration while adding provider/model editing, client-header identities, proxy routing, and protocol compatibility controls.
10
10
 
@@ -89,11 +89,11 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
89
89
  模型 ID gpt-5.6-sol
90
90
  重新拉取 上游模型列表
91
91
  显示名称 默认 = 模型 ID
92
- ❯ 视觉支持 开启
93
- Thinking 开启
94
- Fast mode 关闭
95
- 上下文窗口 1050000
96
- 最大输出 128000
92
+ ❯ 视觉支持 ← 开启 →
93
+ Thinking ← 开启 →
94
+ Fast mode ← 关闭 →
95
+ 上下文窗口 ← 1050000 →
96
+ 最大输出 ← 128000 →
97
97
  请求头 跟随接入(Auto→Codex)
98
98
 
99
99
  ↑↓ 选择 ←→ 切换选项 Enter 编辑 Ctrl+S 保存并启用 Esc 返回
@@ -241,8 +241,8 @@ Model capabilities include:
241
241
 
242
242
  The current built-in values were derived from real client requests with authentication fields removed:
243
243
 
244
- - Claude Code `2.1.243`
245
- - Codex TUI `0.149.1`
244
+ - Claude Code `2.1.278`
245
+ - Codex TUI `0.155.1`
246
246
 
247
247
  These headers only help API gateways that require a recognized client identity; they do not replace an API key. The public repository and npm package contain **no request-capture tooling, user captures, authentication headers, or machine-local state**. Disable identity headers or create a custom profile if a built-in profile does not fit your endpoint.
248
248
 
@@ -304,6 +304,17 @@ pi -e .
304
304
 
305
305
  Pi loads the TypeScript entry point directly; no separate build step is required. Do not commit `state.json`, `bootstrap-meta.json`, `node_modules`, or request-capture data.
306
306
 
307
+ Tests have separate stub and real-host entry points. The current real-host verification baseline is Pi `0.99.0`:
308
+
309
+ ```bash
310
+ npm test
311
+ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm run test:runtime
312
+ ```
313
+
314
+ `npm test` uses test stubs and skips real-host cases. `test:runtime` runs only `tests/*-wire.test.ts`, covering the complete built-in provider guard and protocol transport. Set `PI_TEST_RUNTIME_ROOT` to the installed Pi package directory; use a `C:/...` path in Windows Git Bash. These tests use local responses and fake credentials without calling external model services.
315
+
316
+ Host-provided packages use `"*"` in `peerDependencies`; supported versions are listed in the compatibility table above. Runtime modules are supplied by Pi.
317
+
307
318
  Inspect the public package contents with:
308
319
 
309
320
  ```bash
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.85.1-6f42c1)](https://github.com/earendil-works/pi)
6
6
  [![License](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](./LICENSE)
7
- [![Version](https://img.shields.io/badge/version-0.3.5-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.3.7-2f81f7.svg)](https://github.com/Qihuanxishini/pi-model-manager)
8
8
 
9
9
  一个面向 [Pi](https://github.com/earendil-works/pi) 的 TUI 模型与接入管理扩展。它以 Pi 原生 `models.json` 为模型配置的唯一权威来源,并提供接入/模型编辑、请求头身份、代理路由和协议兼容配置。
10
10
 
@@ -89,11 +89,11 @@ Ctrl+S 保存并启用模型;不切换当前会话模型
89
89
  模型 ID gpt-5.6-sol
90
90
  重新拉取 上游模型列表
91
91
  显示名称 默认 = 模型 ID
92
- ❯ 视觉支持 开启
93
- Thinking 开启
94
- Fast mode 关闭
95
- 上下文窗口 1050000
96
- 最大输出 128000
92
+ ❯ 视觉支持 ← 开启 →
93
+ Thinking ← 开启 →
94
+ Fast mode ← 关闭 →
95
+ 上下文窗口 ← 1050000 →
96
+ 最大输出 ← 128000 →
97
97
  请求头 跟随接入(Auto→Codex)
98
98
 
99
99
  ↑↓ 选择 ←→ 切换选项 Enter 编辑 Ctrl+S 保存并启用 Esc 返回
@@ -245,8 +245,8 @@ Anthropic 标准端点在写入 `models.json` 时转换为 Pi 原生 SDK 所需
245
245
 
246
246
  当前内置值来自真实客户端请求并已移除认证信息:
247
247
 
248
- - Claude Code `2.1.243`
249
- - Codex TUI `0.149.1`
248
+ - Claude Code `2.1.278`
249
+ - Codex TUI `0.155.1`
250
250
 
251
251
  这些值只用于兼容需要识别客户端身份的 API 中转,不代替 API key。公开仓库和 npm 包**不包含请求捕获工具、用户抓包、认证头或本机状态**。如果内置值不适合你的服务,请关闭身份头或创建自定义请求头。
252
252
 
@@ -308,6 +308,17 @@ pi -e .
308
308
 
309
309
  扩展由 Pi 直接加载 TypeScript 入口,不需要单独构建步骤。开发时请勿提交 `state.json`、`bootstrap-meta.json`、`node_modules` 或任何请求捕获数据。
310
310
 
311
+ 测试分为替身测试和真实宿主测试,当前真实宿主验证基线为 Pi `0.99.0`:
312
+
313
+ ```bash
314
+ npm test
315
+ PI_TEST_RUNTIME_ROOT="/path/to/node_modules/@earendil-works/pi-coding-agent" npm run test:runtime
316
+ ```
317
+
318
+ `npm test` 使用测试替身,并跳过真实宿主用例;`test:runtime` 只运行 `tests/*-wire.test.ts`,包括完整内置接入目录保护与协议转发检查。`PI_TEST_RUNTIME_ROOT` 指向已安装的 Pi 包目录,Windows Git Bash 下使用 `C:/...` 形式。这些测试使用本地响应与虚拟凭据,不调用外部模型服务。
319
+
320
+ 宿主提供的包在 `peerDependencies` 中声明为 `"*"`,实际支持版本见上方兼容性表;运行时仍复用 Pi 提供的模块。
321
+
311
322
  验证公开包内容:
312
323
 
313
324
  ```bash
package/atomic-write.ts CHANGED
@@ -56,13 +56,16 @@ async function renameWithRetry(sourcePath: string, targetPath: string): Promise<
56
56
 
57
57
 
58
58
 
59
+ // [喵喵喵]: 含明文 API Key 的配置文件应显式传入 0o600;默认不强制 mode,避免波及 Pi 核心等共享配置文件的权限
60
+ export const SECURE_FILE_MODE = 0o600;
61
+
59
62
  export async function atomicWriteText(targetPath: string, content: string, mode?: number): Promise<void> {
60
63
  await mkdir(dirname(targetPath), { recursive: true });
61
64
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
62
65
  let tempHasCompleteContent = false;
63
66
 
64
67
  try {
65
- await writeFile(tempPath, content, { encoding: "utf8", mode });
68
+ await writeFile(tempPath, content, { encoding: "utf8", ...(mode === undefined ? {} : { mode }) });
66
69
  tempHasCompleteContent = true;
67
70
  await renameWithRetry(tempPath, targetPath);
68
71
  } catch (error) {
@@ -18,6 +18,11 @@ interface BuiltinCatalogModel {
18
18
  baseUrl: string;
19
19
  }
20
20
 
21
+ interface BuiltinCatalog {
22
+ models: readonly BuiltinCatalogModel[];
23
+ providerIds: ReadonlySet<string>;
24
+ }
25
+
21
26
  const SUPPORTED_API_KINDS = new Set<ApiKind>([
22
27
  "openai-completions",
23
28
  "openai-responses",
@@ -40,31 +45,28 @@ const emptyCredentialStore = {
40
45
  },
41
46
  };
42
47
 
43
- let builtinModelsPromise: Promise<readonly BuiltinCatalogModel[]> | undefined;
44
- let builtinProviderIdsPromise: Promise<ReadonlySet<string>> | undefined;
48
+ let builtinCatalogPromise: Promise<BuiltinCatalog> | undefined;
45
49
 
46
- function getBuiltinModels(): Promise<readonly BuiltinCatalogModel[]> {
47
- builtinModelsPromise ??= ModelRuntime.create({
50
+ function getBuiltinCatalog(): Promise<BuiltinCatalog> {
51
+ builtinCatalogPromise ??= ModelRuntime.create({
48
52
  credentials: emptyCredentialStore,
49
53
  modelsPath: null,
50
54
  allowModelNetwork: false,
51
- }).then((runtime) =>
52
- runtime.getModels().map((model) => ({
55
+ }).then((runtime) => ({
56
+ models: runtime.getModels().map((model) => ({
53
57
  provider: String(model.provider),
54
58
  api: String(model.api),
55
59
  baseUrl: model.baseUrl,
56
60
  })),
57
- );
61
+ // [喵喵喵]: 聊天目录不包含仅提供生图或分类器的接入;保护 ID 必须取完整接入目录。
62
+ providerIds: new Set(runtime.getProviders().map((provider) => provider.id)),
63
+ }));
58
64
 
59
- return builtinModelsPromise;
65
+ return builtinCatalogPromise;
60
66
  }
61
67
 
62
- export function getBuiltinProviderIds(): Promise<ReadonlySet<string>> {
63
- builtinProviderIdsPromise ??= getBuiltinModels().then(
64
- (models) => new Set(models.map((model) => model.provider)),
65
- );
66
-
67
- return builtinProviderIdsPromise;
68
+ export async function getBuiltinProviderIds(): Promise<ReadonlySet<string>> {
69
+ return (await getBuiltinCatalog()).providerIds;
68
70
  }
69
71
 
70
72
  export async function isBuiltinProviderId(providerId: string): Promise<boolean> {
@@ -80,7 +82,7 @@ function asSupportedApiKind(value: string | undefined): ApiKind | undefined {
80
82
  export async function getBuiltinProviderDefaults(
81
83
  providerId: string,
82
84
  ): Promise<BuiltinProviderDefaults | undefined> {
83
- const firstModel = (await getBuiltinModels()).find(
85
+ const firstModel = (await getBuiltinCatalog()).models.find(
84
86
  (model) => model.provider === providerId,
85
87
  );
86
88
  if (!firstModel) return undefined;
@@ -1,7 +1,7 @@
1
1
  // 跨 Pi 进程的配置 mutation 锁。只约束遵守本锁的插件写入,外部编辑器冲突另由内容签名检测。
2
2
 
3
3
  import { hostname } from "node:os";
4
- import { open, mkdir, readFile, stat, unlink, type FileHandle } from "node:fs/promises";
4
+ import { open, mkdir, readFile, readdir, stat, unlink, rename, link, type FileHandle } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { t } from "./i18n.ts";
@@ -22,6 +22,14 @@ interface HeldConfigurationLock {
22
22
  const LOCK_PATH = join(STATE_DIR, "config.lock");
23
23
  const LOCK_RETRY_DELAYS_MS = [50, 100, 200, 400, 800] as const;
24
24
  const INVALID_LOCK_STALE_MS = 30_000;
25
+ const STALE_LOCK_NAME_PREFIX = "config.lock.stale.";
26
+ // [喵喵喵]: 持有期上限需远大于任何合理单次事务耗时(本地文件 I/O),避免误抢活跃锁;仅作为 PID 复用死锁的兑底
27
+ const MAX_LOCK_HOLD_MS = 600_000;
28
+
29
+ function isLockExpired(record: ConfigurationLockRecord): boolean {
30
+ const started = Date.parse(record.startedAt);
31
+ return Number.isFinite(started) && Date.now() - started > MAX_LOCK_HOLD_MS;
32
+ }
25
33
 
26
34
  function sleep(ms: number): Promise<void> {
27
35
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -48,6 +56,8 @@ function parseLockRecord(source: string): ConfigurationLockRecord | undefined {
48
56
 
49
57
  function isSameHostProcessRunning(record: ConfigurationLockRecord): boolean {
50
58
  if (record.hostname !== hostname()) return true;
59
+ // [喵喵喵]: 超过最大持有期(10 分钟)视为僵死锁,防止 PID 被操作系统常驻后台进程复用导致永久死锁
60
+ if (isLockExpired(record)) return false;
51
61
  try {
52
62
  process.kill(record.pid, 0);
53
63
  return true;
@@ -73,16 +83,68 @@ async function removeInactiveLock(): Promise<boolean> {
73
83
  return getErrorCode(error) === "ENOENT";
74
84
  }
75
85
  }
86
+
87
+ // [喵喵喵]: 先原子重命名到临时路径再清理,防止 TOCTOU 竞态误删刚刚获取的新锁
88
+ const stalePath = `${LOCK_PATH}.stale.${randomUUID()}`;
76
89
  try {
77
- await unlink(LOCK_PATH);
78
- return true;
90
+ await rename(LOCK_PATH, stalePath);
79
91
  } catch (error) {
80
92
  return getErrorCode(error) === "ENOENT";
81
93
  }
94
+
95
+ try {
96
+ const movedSource = await readFile(stalePath, "utf8");
97
+ const movedRecord = parseLockRecord(movedSource);
98
+ // [喵喵喵]: token 不一致说明读取后锁文件已被活跃进程替换,必须放回且不得覆盖新锁
99
+ if (record && movedRecord?.token !== record.token) {
100
+ await restoreMovedLock(stalePath);
101
+ return false;
102
+ }
103
+ await unlink(stalePath);
104
+ return true;
105
+ } catch {
106
+ // [喵喵喵]: 校验阶段异常时不能销毁内容未知的锁文件,尽力放回并交由下次获取重试判定
107
+ await restoreMovedLock(stalePath);
108
+ return false;
109
+ }
110
+ }
111
+
112
+ // [喵喵喵]: 用 link 原子放回:目标已存在时以 EEXIST 失败,绝不覆盖他人在空窗期新建的锁
113
+ async function restoreMovedLock(stalePath: string): Promise<void> {
114
+ try {
115
+ await link(stalePath, LOCK_PATH);
116
+ } catch (error) {
117
+ if (getErrorCode(error) === "EEXIST") return;
118
+ throw error;
119
+ }
120
+ await unlink(stalePath).catch(() => undefined);
121
+ }
122
+
123
+ // [喵喵喵]: 清理历史进程崩溃遗留的 config.lock.stale.* 残留(正常生命周期仅存在微秒级)
124
+ async function sweepAbandonedStaleLocks(): Promise<void> {
125
+ let entries: string[];
126
+ try {
127
+ entries = await readdir(STATE_DIR);
128
+ } catch {
129
+ return;
130
+ }
131
+ await Promise.all(entries
132
+ .filter((name) => name.startsWith(STALE_LOCK_NAME_PREFIX))
133
+ .map(async (name) => {
134
+ const stalePath = join(STATE_DIR, name);
135
+ try {
136
+ const stats = await stat(stalePath);
137
+ if (Date.now() - stats.mtimeMs < INVALID_LOCK_STALE_MS) return;
138
+ await unlink(stalePath);
139
+ } catch {
140
+ // 并发清理或文件已消失时静默跳过
141
+ }
142
+ }));
82
143
  }
83
144
 
84
145
  async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
85
146
  await mkdir(STATE_DIR, { recursive: true });
147
+ await sweepAbandonedStaleLocks();
86
148
  const record: ConfigurationLockRecord = {
87
149
  token: randomUUID(),
88
150
  pid: process.pid,
@@ -8,7 +8,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
8
  type RegistryRefreshContext = Pick<ExtensionContext, "modelRegistry">;
9
9
  import { unlink } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
- import { atomicWriteText } from "./atomic-write.ts";
11
+ import { atomicWriteText, SECURE_FILE_MODE } from "./atomic-write.ts";
12
12
  import { formatUnknownError, isObjectRecord, stringifyJson } from "./common.ts";
13
13
  import { withConfigurationLock } from "./configuration-lock.ts";
14
14
  import { hashTextContent, readStableTextFileSnapshot } from "./file-snapshot.ts";
@@ -123,7 +123,7 @@ async function classifyTransition(path: string, transition: FileTransition): Pro
123
123
  }
124
124
 
125
125
  async function finishTransition(path: string, transition: FileTransition, status: "old" | "target"): Promise<void> {
126
- if (status === "old") await atomicWriteText(path, transition.targetSource);
126
+ if (status === "old") await atomicWriteText(path, transition.targetSource, SECURE_FILE_MODE);
127
127
  const completed = await readStableTextFileSnapshot(path);
128
128
  if (completed.contentHash !== transition.targetHash) {
129
129
  throw new Error(t("{path} 写入后内容签名不匹配;已保留 {transactionPath} 供恢复。", { path, transactionPath: TRANSACTION_PATH }));
@@ -184,7 +184,7 @@ async function writeConfigurationTransaction(
184
184
  if (metadataSnapshot.metadata.version < 5) {
185
185
  const backupPath = join(STATE_DIR, `base-url-v5-${hashTextContent(journal.modelsJson.oldHash + journal.metadataState.oldHash).slice(0, 16)}.json`);
186
186
  const backup = await readStableTextFileSnapshot(backupPath);
187
- if (backup.source === undefined) await atomicWriteText(backupPath, stringifyJson(journal), 0o600);
187
+ if (backup.source === undefined) await atomicWriteText(backupPath, stringifyJson(journal), SECURE_FILE_MODE);
188
188
  else {
189
189
  const saved = parseTransactionJournal(backup.source);
190
190
  if (saved.modelsJson.oldHash !== journal.modelsJson.oldHash || saved.metadataState.oldHash !== journal.metadataState.oldHash) {
@@ -192,7 +192,7 @@ async function writeConfigurationTransaction(
192
192
  }
193
193
  }
194
194
  }
195
- await atomicWriteText(TRANSACTION_PATH, stringifyJson(journal));
195
+ await atomicWriteText(TRANSACTION_PATH, stringifyJson(journal), SECURE_FILE_MODE);
196
196
 
197
197
  try {
198
198
  const modelsStatus = await classifyTransition(MODELS_JSON_PATH, journal.modelsJson);
package/i18n.ts CHANGED
@@ -96,6 +96,15 @@ const ENGLISH_MESSAGES = {
96
96
  "兼容 — 强制 system role,适合忽略 developer 的中转": "Compatible — force the system role for relays that ignore developer",
97
97
  "标准模式:保持 Pi 默认兼容判断。": "Standard mode: keep Pi's default compatibility detection.",
98
98
  "兼容模式:系统提示词强制使用 system role,适合忽略 developer 的中转。": "Compatibility mode: the system prompt always uses the system role for relays that ignore developer.",
99
+ "流结束兼容": "Stream completion",
100
+ "兼容 · 终态即结束": "Compatible · end on terminal event",
101
+ "标准 · 等待连接关闭": "Standard · wait for connection close",
102
+ "选择流结束兼容": "Select stream completion mode",
103
+ "标准 — 等待上游正常关闭连接": "Standard — wait for upstream to close the connection",
104
+ "兼容 — 收到正式终态事件后主动结束": "Compatible — finish after receiving a formal terminal event",
105
+ "兼容模式:正式终态事件已转交后主动结束,不等待上游关闭连接。": "Compatibility mode: finish after forwarding the formal terminal event without waiting for upstream to close.",
106
+ "标准模式:等待上游正常结束流。若回复完成后长期卡住,可启用兼容模式。": "Standard mode: wait for upstream to finish the stream normally. Enable compatibility mode if completed replies remain stuck.",
107
+ "未知 Responses 流结束模式:{value}": "Unknown Responses stream completion mode: {value}",
99
108
  "接入 ID 必填,且不能与已有或 pi 内置接入重复": "Provider ID is required and must not duplicate an existing or built-in Pi provider",
100
109
  "Ctrl+S 保存并同步 models.json;不切换当前会话模型": "Ctrl+S saves and syncs models.json without switching the current session model",
101
110
  "选择 API 协议": "Select API protocol",
@@ -260,6 +269,7 @@ const ENGLISH_MESSAGES = {
260
269
 
261
270
  "{successMessage},但以下接入未能刷新,已保留上一版 runtime:\n- {warnings}": "{successMessage}, but the following providers could not be refreshed and retain their previous runtime:\n- {warnings}",
262
271
  "已保存请求头 {profileId}": "Saved header profile {profileId}",
272
+ "请求头 {profileId} 尚未被任何接入使用;在接入编辑器的「请求头」行选择后才会生效。": "Header profile {profileId} is not used by any provider yet; select it in the provider editor's request-header row to take effect.",
263
273
  "已删除请求头 {profileId}": "Deleted header profile {profileId}",
264
274
  "代理地址无效:{url}": "Invalid proxy URL: {url}",
265
275
  "代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
@@ -4,6 +4,7 @@
4
4
  // 不修改 pi 本体:开启代理的接入点在运行时注册为 127.0.0.1 本地地址,
5
5
  // 本服务再通过用户配置的 HTTP/HTTPS 代理转发到真实上游。
6
6
 
7
+ import { randomUUID } from "node:crypto";
7
8
  import http, { type IncomingHttpHeaders, type IncomingMessage, type ServerResponse } from "node:http";
8
9
  import https from "node:https";
9
10
  import { HttpProxyAgent } from "http-proxy-agent";
@@ -28,7 +29,6 @@ let server: http.Server | undefined;
28
29
  let listenPromise: Promise<number> | undefined;
29
30
  let listenPort: number | undefined;
30
31
  let closingPromise: Promise<void> | undefined;
31
- let temporaryRouteSequence = 0;
32
32
 
33
33
  const HOP_BY_HOP_HEADERS = new Set([
34
34
  "connection",
@@ -93,9 +93,25 @@ function ensureSupportedProxyProtocol(proxy: URL): void {
93
93
  }
94
94
  }
95
95
 
96
- function pipeResponse(upstreamResponse: IncomingMessage, response: ServerResponse): void {
96
+ function pipeResponse(upstreamResponse: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
97
+ const statusCode = upstreamResponse.statusCode ?? 502;
98
+ // [喵喵喵]: 上游返回 3xx 重定向时,若重定向目标跨域,直接在代理层拦截,防止客户端在跟随重定向时泄露真实 IP
99
+ if (statusCode >= 300 && statusCode < 400 && upstreamResponse.headers.location) {
100
+ try {
101
+ const target = new URL(upstreamResponse.headers.location, route.upstreamOrigin);
102
+ if (target.origin !== route.upstreamOrigin) {
103
+ response.writeHead(502, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
104
+ response.end(t("代理安全拦截:上游返回了跨域重定向至 {target},已拒绝跟随", { target: target.origin }));
105
+ // [喵喵喵]: 拦截后主动销毁上游响应,避免未消费的 body 占用 socket 直到超时
106
+ upstreamResponse.destroy();
107
+ return;
108
+ }
109
+ } catch {
110
+ // 非法 location 则继续透传交由客户端处理
111
+ }
112
+ }
97
113
  const headers = stripHopByHopHeaders(upstreamResponse.headers);
98
- response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.statusMessage, headers);
114
+ response.writeHead(statusCode, upstreamResponse.statusMessage, headers);
99
115
  // 尽快把 SSE 响应头交给本地客户端,后续 body 由 Node 的 HTTP 栈处理 chunked/backpressure。
100
116
  response.flushHeaders();
101
117
  upstreamResponse.on("error", (error) => {
@@ -162,7 +178,7 @@ function writeUpstreamRequestError(response: ServerResponse, error: Error): void
162
178
  writeProxyError(response, error);
163
179
  }
164
180
 
165
- function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse): void {
181
+ function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
166
182
  ensureSupportedProxyProtocol(proxy);
167
183
  const headers = buildForwardRequestHeaders(target, request);
168
184
  const agent = new HttpProxyAgent(proxy);
@@ -173,7 +189,7 @@ function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, res
173
189
  path: `${target.pathname}${target.search}`,
174
190
  headers,
175
191
  agent,
176
- }, (upstreamResponse) => pipeResponse(upstreamResponse, response));
192
+ }, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
177
193
  upstreamRequest.once("close", () => agent.destroy());
178
194
  bindClientAbort(request, response, upstreamRequest);
179
195
  upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
@@ -182,7 +198,7 @@ function forwardPlainHttp(target: URL, proxy: URL, request: IncomingMessage, res
182
198
  upstreamRequest.once("socket", () => request.pipe(upstreamRequest));
183
199
  }
184
200
 
185
- function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse): void {
201
+ function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, response: ServerResponse, route: ProviderProxyRoute): void {
186
202
  ensureSupportedProxyProtocol(proxy);
187
203
  const headers = buildForwardRequestHeaders(target, request);
188
204
  const agent = new HttpsProxyAgent(proxy);
@@ -193,7 +209,7 @@ function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, respons
193
209
  path: `${target.pathname}${target.search}`,
194
210
  headers,
195
211
  agent,
196
- }, (upstreamResponse) => pipeResponse(upstreamResponse, response));
212
+ }, (upstreamResponse) => pipeResponse(upstreamResponse, response, route));
197
213
  upstreamRequest.once("close", () => agent.destroy());
198
214
  bindClientAbort(request, response, upstreamRequest);
199
215
  upstreamRequest.on("error", (error) => writeUpstreamRequestError(response, error));
@@ -202,13 +218,20 @@ function forwardHttps(target: URL, proxy: URL, request: IncomingMessage, respons
202
218
 
203
219
  function forwardRequest(route: ProviderProxyRoute, request: IncomingMessage, response: ServerResponse, routePath: string): void {
204
220
  const target = new URL(routePath, route.upstreamOrigin);
221
+ // [喵喵喵]: 强制校验解析后的 target.origin 严格等于受管的 upstreamOrigin,阻断 SSRF 任意上游转发
222
+ if (target.origin !== route.upstreamOrigin) {
223
+ throw new Error(t("拒绝转发:目标 Origin {actual} 与注册路由 {expected} 不一致", {
224
+ actual: target.origin,
225
+ expected: route.upstreamOrigin,
226
+ }));
227
+ }
205
228
  const proxy = new URL(route.proxyUrl);
206
229
  if (target.protocol === "http:") {
207
- forwardPlainHttp(target, proxy, request, response);
230
+ forwardPlainHttp(target, proxy, request, response, route);
208
231
  return;
209
232
  }
210
233
  if (target.protocol === "https:") {
211
- forwardHttps(target, proxy, request, response);
234
+ forwardHttps(target, proxy, request, response, route);
212
235
  return;
213
236
  }
214
237
  throw new Error(t("不支持的上游协议:{protocol}", { protocol: target.protocol }));
@@ -220,18 +243,27 @@ function handleRequest(request: IncomingMessage, response: ServerResponse): void
220
243
  const localUrl = new URL(request.url ?? "/", "http://127.0.0.1");
221
244
  const [, encodedProviderId, ...rest] = localUrl.pathname.split("/");
222
245
  if (!encodedProviderId) {
223
- response.writeHead(404);
246
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
224
247
  response.end("missing provider id");
225
248
  return;
226
249
  }
227
- const providerId = decodeURIComponent(encodedProviderId);
250
+ let providerId: string;
251
+ try {
252
+ providerId = decodeURIComponent(encodedProviderId);
253
+ } catch {
254
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
255
+ response.end("malformed provider id");
256
+ return;
257
+ }
228
258
  const route = ROUTES.get(providerId);
229
259
  if (!route) {
230
- response.writeHead(404);
260
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff" });
231
261
  response.end(`unknown provider: ${providerId}`);
232
262
  return;
233
263
  }
234
- const path = `/${rest.join("/")}${localUrl.search}`;
264
+ // [喵喵喵]: 清除多余连续斜杠,防止 //evil.com 协议相对路径逃逸
265
+ const normalizedRemaining = rest.join("/").replace(/^\/+/, "");
266
+ const path = `/${normalizedRemaining}${localUrl.search}`;
235
267
  await forwardRequest(route, request, response, path);
236
268
  } catch (error) {
237
269
  writeProxyError(response, error);
@@ -306,11 +338,12 @@ export async function openTemporaryLocalProxyRoute(
306
338
  const upstream = new URL(upstreamUrl);
307
339
  const proxy = parseHttpProxyUrl(proxyUrl);
308
340
  const port = await ensureServerForRoute();
309
- const routeId = `${providerId}/model-list/${++temporaryRouteSequence}`;
341
+ const routeId = `${providerId}/model-list/${randomUUID()}`;
310
342
  const route = { upstreamOrigin: upstream.origin, proxyUrl: proxy.toString() };
311
343
  ROUTES.set(routeId, route);
344
+ const basePath = trimTrailingSlashes(upstream.pathname || "");
312
345
  return {
313
- url: `http://127.0.0.1:${port}/${encodeURIComponent(routeId)}${upstream.pathname}${upstream.search}`,
346
+ url: `http://127.0.0.1:${port}/${encodeURIComponent(routeId)}${basePath}${upstream.search}`,
314
347
  close(): void {
315
348
  if (ROUTES.get(routeId) === route) ROUTES.delete(routeId);
316
349
  },
@@ -11,7 +11,7 @@ import {
11
11
  ModelRuntime,
12
12
  type ExtensionCommandContext,
13
13
  } from "@earendil-works/pi-coding-agent";
14
- import { createRequire } from "node:module";
14
+ import settingsFileLock from "proper-lockfile";
15
15
  import { join } from "node:path";
16
16
  import { minimatch } from "minimatch";
17
17
  import { atomicWriteText } from "./atomic-write.ts";
@@ -278,15 +278,8 @@ function removeEnabledProviderPatterns(patterns: string[], providerId: string):
278
278
  return patterns.filter((pattern) => !splitThinkingSuffix(pattern).base.toLowerCase().startsWith(providerPrefix));
279
279
  }
280
280
 
281
- interface SettingsFileLock {
282
- lock(path: string, options: {
283
- realpath: false;
284
- retries: { retries: number; factor: number; minTimeout: number; maxTimeout: number };
285
- }): Promise<() => Promise<void>>;
286
- }
287
-
288
- const require = createRequire(import.meta.url);
289
- const settingsFileLock = require("proper-lockfile") as SettingsFileLock;
281
+ // [喵喵喵]: Bun 编译版 Pi 下 createRequire 无法寻址 proper-lockfile 的传递依赖 graceful-fs,
282
+ // 必须走 ESM 导入让 Node/Bun 的 ESM 解析器接管 (issue #3)
290
283
 
291
284
  interface LockedSettingsUpdate {
292
285
  configured: boolean;