pi-model-manager 0.3.6 → 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 +17 -6
- package/README.md +17 -6
- package/atomic-write.ts +4 -1
- package/builtin-model-catalog.ts +17 -15
- package/configuration-lock.ts +65 -3
- package/configuration-persistence.ts +4 -4
- package/i18n.ts +1 -0
- package/local-proxy-service.ts +48 -15
- package/models-json-sync.ts +3 -10
- package/package.json +85 -83
- package/presets/builtin-client-headers.ts +3 -3
- package/presets/providers.ts +6 -2
- package/proper-lockfile.d.ts +18 -0
- package/provider-transport.ts +2 -1
- package/runtime-base-url.ts +10 -5
- package/state-document.ts +20 -3
- package/state-store.ts +20 -2
- package/tui/dashboard.ts +29 -12
- package/tui/editor-model.ts +75 -10
- package/tui/editor-provider.ts +12 -7
- package/tui/header-profiles-panel.ts +27 -6
- package/tui/model-list-fetch.ts +6 -1
- package/tui/persistent-menu.ts +11 -1
package/README.en.md
CHANGED
|
@@ -4,7 +4,7 @@ English · [简体中文](./README.md)
|
|
|
4
4
|
|
|
5
5
|
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
|
-
[](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 返回
|
|
@@ -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
|
[](https://github.com/earendil-works/pi)
|
|
6
6
|
[](./LICENSE)
|
|
7
|
-
[](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 返回
|
|
@@ -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) {
|
package/builtin-model-catalog.ts
CHANGED
|
@@ -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
|
|
44
|
-
let builtinProviderIdsPromise: Promise<ReadonlySet<string>> | undefined;
|
|
48
|
+
let builtinCatalogPromise: Promise<BuiltinCatalog> | undefined;
|
|
45
49
|
|
|
46
|
-
function
|
|
47
|
-
|
|
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
|
|
65
|
+
return builtinCatalogPromise;
|
|
60
66
|
}
|
|
61
67
|
|
|
62
|
-
export function getBuiltinProviderIds(): Promise<ReadonlySet<string>> {
|
|
63
|
-
|
|
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
|
|
85
|
+
const firstModel = (await getBuiltinCatalog()).models.find(
|
|
84
86
|
(model) => model.provider === providerId,
|
|
85
87
|
);
|
|
86
88
|
if (!firstModel) return undefined;
|
package/configuration-lock.ts
CHANGED
|
@@ -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
|
|
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),
|
|
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
|
@@ -269,6 +269,7 @@ const ENGLISH_MESSAGES = {
|
|
|
269
269
|
|
|
270
270
|
"{successMessage},但以下接入未能刷新,已保留上一版 runtime:\n- {warnings}": "{successMessage}, but the following providers could not be refreshed and retain their previous runtime:\n- {warnings}",
|
|
271
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.",
|
|
272
273
|
"已删除请求头 {profileId}": "Deleted header profile {profileId}",
|
|
273
274
|
"代理地址无效:{url}": "Invalid proxy URL: {url}",
|
|
274
275
|
"代理地址目前只支持 http:// 或 https:// 代理": "Only http:// or https:// proxies are currently supported",
|
package/local-proxy-service.ts
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
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
|
-
|
|
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/${
|
|
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)}${
|
|
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
|
},
|
package/models-json-sync.ts
CHANGED
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
ModelRuntime,
|
|
12
12
|
type ExtensionCommandContext,
|
|
13
13
|
} from "@earendil-works/pi-coding-agent";
|
|
14
|
-
import
|
|
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
|
-
|
|
282
|
-
|
|
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;
|
package/package.json
CHANGED
|
@@ -1,83 +1,85 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "pi-model-manager",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./index.ts",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts"
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
"
|
|
17
|
-
"state-
|
|
18
|
-
"state-
|
|
19
|
-
"state-
|
|
20
|
-
"
|
|
21
|
-
"openai-
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"models-json-
|
|
26
|
-
"
|
|
27
|
-
"provider-
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
"pi",
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
"
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
"@earendil-works/pi-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
"
|
|
81
|
-
"
|
|
82
|
-
|
|
83
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-model-manager",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "A TUI model and provider manager for Pi with native models.json persistence, request-header profiles, proxy routing, and protocol compatibility.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "node --experimental-strip-types --import ./tests/register-test-loader.mjs --test --test-reporter=spec tests/*.test.ts",
|
|
9
|
+
"test:runtime": "node --experimental-strip-types --import ./tests/register-runtime-loader.mjs --test --test-reporter=spec tests/*-wire.test.ts"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"NOTICE",
|
|
13
|
+
"README.en.md",
|
|
14
|
+
"index.ts",
|
|
15
|
+
"i18n.ts",
|
|
16
|
+
"ui-language-settings.ts",
|
|
17
|
+
"state-store.ts",
|
|
18
|
+
"state-metadata-store.ts",
|
|
19
|
+
"state-cache.ts",
|
|
20
|
+
"state-document.ts",
|
|
21
|
+
"openai-responses-payload.ts",
|
|
22
|
+
"openai-service-tier.ts",
|
|
23
|
+
"claude-code-compat.ts",
|
|
24
|
+
"builtin-model-catalog.ts",
|
|
25
|
+
"models-json-manager.ts",
|
|
26
|
+
"models-json-sync.ts",
|
|
27
|
+
"provider-registrar.ts",
|
|
28
|
+
"provider-transport.ts",
|
|
29
|
+
"local-proxy-service.ts",
|
|
30
|
+
"request-pipeline.ts",
|
|
31
|
+
"model-mutations.ts",
|
|
32
|
+
"header-profile-mutations.ts",
|
|
33
|
+
"rescue.ts",
|
|
34
|
+
"atomic-write.ts",
|
|
35
|
+
"proper-lockfile.d.ts",
|
|
36
|
+
"common.ts",
|
|
37
|
+
"config-value-reference.ts",
|
|
38
|
+
"configuration-persistence.ts",
|
|
39
|
+
"configuration-lock.ts",
|
|
40
|
+
"file-snapshot.ts",
|
|
41
|
+
"sensitive-redaction.ts",
|
|
42
|
+
"compat-settings.ts",
|
|
43
|
+
"runtime-base-url.ts",
|
|
44
|
+
"types.ts",
|
|
45
|
+
"tui/",
|
|
46
|
+
"presets/"
|
|
47
|
+
],
|
|
48
|
+
"keywords": [
|
|
49
|
+
"pi-package",
|
|
50
|
+
"pi-extension",
|
|
51
|
+
"pi",
|
|
52
|
+
"model-manager",
|
|
53
|
+
"provider-manager",
|
|
54
|
+
"models-json",
|
|
55
|
+
"client-headers",
|
|
56
|
+
"openai",
|
|
57
|
+
"anthropic"
|
|
58
|
+
],
|
|
59
|
+
"author": "Qihuanxishini",
|
|
60
|
+
"license": "AGPL-3.0-only",
|
|
61
|
+
"repository": {
|
|
62
|
+
"type": "git",
|
|
63
|
+
"url": "git+https://github.com/Qihuanxishini/pi-model-manager.git"
|
|
64
|
+
},
|
|
65
|
+
"homepage": "https://github.com/Qihuanxishini/pi-model-manager#readme",
|
|
66
|
+
"bugs": {
|
|
67
|
+
"url": "https://github.com/Qihuanxishini/pi-model-manager/issues"
|
|
68
|
+
},
|
|
69
|
+
"pi": {
|
|
70
|
+
"extensions": [
|
|
71
|
+
"./index.ts"
|
|
72
|
+
]
|
|
73
|
+
},
|
|
74
|
+
"peerDependencies": {
|
|
75
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
76
|
+
"@earendil-works/pi-ai": "*",
|
|
77
|
+
"@earendil-works/pi-tui": "*"
|
|
78
|
+
},
|
|
79
|
+
"dependencies": {
|
|
80
|
+
"http-proxy-agent": "^9.1.0",
|
|
81
|
+
"https-proxy-agent": "^9.1.0",
|
|
82
|
+
"minimatch": "^10.2.6",
|
|
83
|
+
"proper-lockfile": "^4.1.2"
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -4,12 +4,12 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
|
4
4
|
"anthropic-beta": "claude-code-20250219,context-1m-2025-08-07,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,per-turn-control-2026-07-01,mid-conversation-tool-changes-2026-07-01,effort-2025-11-24",
|
|
5
5
|
"anthropic-dangerous-direct-browser-access": "true",
|
|
6
6
|
"anthropic-version": "2023-06-01",
|
|
7
|
-
"user-agent": "claude-cli/2.1.
|
|
7
|
+
"user-agent": "claude-cli/2.1.296 (external, sdk-cli)",
|
|
8
8
|
"x-app": "cli",
|
|
9
9
|
"x-stainless-arch": "x64",
|
|
10
10
|
"x-stainless-lang": "js",
|
|
11
11
|
"x-stainless-os": "Windows",
|
|
12
|
-
"x-stainless-package-version": "0.
|
|
12
|
+
"x-stainless-package-version": "0.128.0",
|
|
13
13
|
"x-stainless-retry-count": "0",
|
|
14
14
|
"x-stainless-runtime": "node",
|
|
15
15
|
"x-stainless-runtime-version": "v26.3.0",
|
|
@@ -18,6 +18,6 @@ export const CLAUDE_CODE_CLIENT_HEADERS: Record<string, string> = {
|
|
|
18
18
|
|
|
19
19
|
export const CODEX_CLI_CLIENT_HEADERS: Record<string, string> = {
|
|
20
20
|
"originator": "codex-tui",
|
|
21
|
-
"user-agent": "codex-tui/0.
|
|
21
|
+
"user-agent": "codex-tui/0.162.1 (Windows 10.0.26300; x86_64) WindowsTerminal (codex-tui; 0.162.1)",
|
|
22
22
|
"x-codex-beta-features": "remote_compaction_v2",
|
|
23
23
|
};
|
package/presets/providers.ts
CHANGED
|
@@ -66,7 +66,7 @@ const PROVIDER_PRESETS: ProviderPreset[] = [
|
|
|
66
66
|
apiKey: "$GEMINI_API_KEY",
|
|
67
67
|
authHeader: false,
|
|
68
68
|
contextWindow: 1048576,
|
|
69
|
-
maxTokens:
|
|
69
|
+
maxTokens: 64000,
|
|
70
70
|
inputKinds: ["text", "image"],
|
|
71
71
|
defaultReasoning: true,
|
|
72
72
|
},
|
|
@@ -105,6 +105,10 @@ export function switchProviderDraftApiPreset(draft: ProviderDraft, nextApi: ApiK
|
|
|
105
105
|
}
|
|
106
106
|
// [喵喵喵]: 版本路径规则随协议而变(OpenAI 要 /v1、Anthropic 不要),
|
|
107
107
|
// 保留的自定义地址必须按新协议重新归一化,否则切完协议就指向错误端点。
|
|
108
|
-
|
|
108
|
+
try {
|
|
109
|
+
draft.baseUrl = replaceBaseUrl ? nextPreset.baseUrl : resolveRuntimeBaseUrl(nextApi, draft.baseUrl);
|
|
110
|
+
} catch {
|
|
111
|
+
draft.baseUrl = nextPreset.baseUrl;
|
|
112
|
+
}
|
|
109
113
|
if (replaceApiKey) draft.apiKey = nextPreset.apiKey;
|
|
110
114
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// proper-lockfile 4.x 不自带类型声明;这里仅为本仓库实际用到的 API 提供最小签名。
|
|
2
|
+
declare module "proper-lockfile" {
|
|
3
|
+
export interface LockOptions {
|
|
4
|
+
realpath?: boolean | null;
|
|
5
|
+
retries?: number | { retries: number; factor: number; minTimeout: number; maxTimeout: number };
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function lock(path: string, options?: LockOptions): Promise<() => Promise<void>>;
|
|
9
|
+
export function unlock(path: string, options?: LockOptions): Promise<void>;
|
|
10
|
+
export function check(path: string, options?: LockOptions): Promise<boolean>;
|
|
11
|
+
|
|
12
|
+
const properLockfile: {
|
|
13
|
+
lock: typeof lock;
|
|
14
|
+
unlock: typeof unlock;
|
|
15
|
+
check: typeof check;
|
|
16
|
+
};
|
|
17
|
+
export default properLockfile;
|
|
18
|
+
}
|
package/provider-transport.ts
CHANGED
|
@@ -154,7 +154,8 @@ export function createProviderTransport(runtime: ModelRuntime, native: Provider,
|
|
|
154
154
|
} else {
|
|
155
155
|
const route = await openTemporaryLocalProxyRoute(native.id, request.url, proxyUrl);
|
|
156
156
|
try {
|
|
157
|
-
|
|
157
|
+
// [喵喵喵]: 经由本地代理转发时强制禁止自动跟随重定向,防止客户端绕过代理直连上游
|
|
158
|
+
response = await fetchImpl(new Request(route.url, new Request(request, { redirect: "manual" })));
|
|
158
159
|
} finally {
|
|
159
160
|
// [喵喵喵]: 收到响应头时转发端已经取得路由;删除查找项不会中断已建立的 SSE 流。
|
|
160
161
|
route.close();
|
package/runtime-base-url.ts
CHANGED
|
@@ -57,9 +57,14 @@ export function fromNativeBaseUrl(
|
|
|
57
57
|
legacyNormalization = false,
|
|
58
58
|
): string {
|
|
59
59
|
if (api !== "anthropic-messages" || anthropicApiRoot) return baseUrl;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
60
|
+
try {
|
|
61
|
+
const url = new URL(baseUrl.trim());
|
|
62
|
+
trimPath(url);
|
|
63
|
+
// [喵喵喵]: 旧版插件在注册前剥去末尾 /v1;读取旧配置必须先复现该行为再显式补回版本路径。
|
|
64
|
+
if (legacyNormalization && url.pathname.toLowerCase().endsWith("/v1")) url.pathname = url.pathname.slice(0, -3) || "/";
|
|
65
|
+
return appendUrlPath(formatUrl(url), "v1");
|
|
66
|
+
} catch {
|
|
67
|
+
// [喵喵喵]: 受控简化 — 解析失败的 Base URL 原样返回交由上层校验拦截;边界:非交互调用方(如状态读回)拿不到提示;升级:出现排查诉求时为读回路径接入统一的告警通道
|
|
68
|
+
return baseUrl;
|
|
69
|
+
}
|
|
65
70
|
}
|
package/state-document.ts
CHANGED
|
@@ -428,7 +428,8 @@ export function buildModelFromDraft(
|
|
|
428
428
|
next.openAIServiceTier = "priority";
|
|
429
429
|
}
|
|
430
430
|
|
|
431
|
-
|
|
431
|
+
// [喵喵喵]: 仅在启用推理时维护 Adaptive 思考协议;关闭推理时彻底清理兼容标记,避免误剥离协议头
|
|
432
|
+
if (effectiveApi === "anthropic-messages" && draft.reasoningMode === "enabled" && draft.anthropicThinkingProtocol) {
|
|
432
433
|
const existingOverride = existing?.compat?.forceAdaptiveThinking;
|
|
433
434
|
const providerForcesAdaptiveThinking = providerCompat?.forceAdaptiveThinking === true;
|
|
434
435
|
if (draft.anthropicThinkingProtocol === "adaptive") {
|
|
@@ -439,6 +440,11 @@ export function buildModelFromDraft(
|
|
|
439
440
|
} else {
|
|
440
441
|
delete compat.forceAdaptiveThinking;
|
|
441
442
|
}
|
|
443
|
+
} else if (effectiveApi === "anthropic-messages" && draft.reasoningMode !== "enabled" && providerCompat?.forceAdaptiveThinking === true) {
|
|
444
|
+
// [喵喵喵]: 关闭推理但接入级强制 adaptive 时显式写 false 覆盖继承值,否则合并后仍会注入 beta 请求头
|
|
445
|
+
compat.forceAdaptiveThinking = false;
|
|
446
|
+
} else {
|
|
447
|
+
delete compat.forceAdaptiveThinking;
|
|
442
448
|
}
|
|
443
449
|
|
|
444
450
|
if (Object.keys(compat).length > 0) next.compat = compat;
|
|
@@ -448,9 +454,20 @@ export function buildModelFromDraft(
|
|
|
448
454
|
|
|
449
455
|
// ========== 请求头 ==========
|
|
450
456
|
|
|
451
|
-
export function createRequestHeaderProfileDraft(): RequestHeaderProfileDraft {
|
|
457
|
+
export function createRequestHeaderProfileDraft(existingIds?: Iterable<string>): RequestHeaderProfileDraft {
|
|
458
|
+
let profileId = "custom-headers";
|
|
459
|
+
if (existingIds) {
|
|
460
|
+
const set = new Set(existingIds);
|
|
461
|
+
if (set.has(profileId)) {
|
|
462
|
+
let counter = 1;
|
|
463
|
+
while (set.has(`custom-headers-${counter}`)) {
|
|
464
|
+
counter += 1;
|
|
465
|
+
}
|
|
466
|
+
profileId = `custom-headers-${counter}`;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
452
469
|
return {
|
|
453
|
-
profileId
|
|
470
|
+
profileId,
|
|
454
471
|
profileName: t("自定义请求头"),
|
|
455
472
|
headers: {},
|
|
456
473
|
selectedIndex: 0,
|
package/state-store.ts
CHANGED
|
@@ -103,12 +103,29 @@ function resolveProviderCustomHeaders(
|
|
|
103
103
|
return providerMetadata?.customClientHeaders ?? {};
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
function stripProviderInheritedHeaders(
|
|
107
|
+
modelHeaders: Record<string, string> | undefined,
|
|
108
|
+
providerHeaders: Record<string, string> | undefined,
|
|
109
|
+
): Record<string, string> | undefined {
|
|
110
|
+
if (!modelHeaders || !providerHeaders) return modelHeaders;
|
|
111
|
+
const result = cloneStringRecord(modelHeaders);
|
|
112
|
+
for (const [pName, pValue] of Object.entries(providerHeaders)) {
|
|
113
|
+
for (const [mName, mValue] of Object.entries(result)) {
|
|
114
|
+
if (mName.toLowerCase() === pName.toLowerCase() && mValue === pValue) {
|
|
115
|
+
delete result[mName];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return hasStringRecordEntries(result) ? result : undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
106
122
|
function buildStoredModelFromModelsJson(
|
|
107
123
|
providerId: string,
|
|
108
124
|
providerApi: ApiKind,
|
|
109
125
|
providerBaseUrl: string,
|
|
110
126
|
providerNativeBaseUrl: string,
|
|
111
127
|
providerCompat: CompatSettings | undefined,
|
|
128
|
+
providerHeaders: Record<string, string> | undefined,
|
|
112
129
|
managed: boolean,
|
|
113
130
|
clientHeaderProfile: StoredProvider["clientHeaderProfile"],
|
|
114
131
|
customClientHeaders: Record<string, string>,
|
|
@@ -130,14 +147,14 @@ function buildStoredModelFromModelsJson(
|
|
|
130
147
|
)
|
|
131
148
|
: undefined;
|
|
132
149
|
const nativeHeaders = managed
|
|
133
|
-
? stripManagedClientHeaders(model.headers, profileHeaders)
|
|
150
|
+
? stripProviderInheritedHeaders(stripManagedClientHeaders(model.headers, profileHeaders), providerHeaders)
|
|
134
151
|
: cloneStringRecord(model.headers);
|
|
135
152
|
const stored: StoredModel = {
|
|
136
153
|
id: model.id,
|
|
137
154
|
reasoning: model.reasoning ?? false,
|
|
138
155
|
input: readModelInput(model),
|
|
139
156
|
contextWindow: model.contextWindow && model.contextWindow > 0 ? model.contextWindow : 128000,
|
|
140
|
-
maxTokens: model.maxTokens && model.maxTokens > 0 ? model.maxTokens :
|
|
157
|
+
maxTokens: model.maxTokens && model.maxTokens > 0 ? model.maxTokens : 16000,
|
|
141
158
|
cost: readModelCost(model),
|
|
142
159
|
};
|
|
143
160
|
if (explicitApi && explicitApi !== providerApi) stored.api = explicitApi;
|
|
@@ -199,6 +216,7 @@ async function buildStoredProviderFromModelsJson(
|
|
|
199
216
|
baseUrl,
|
|
200
217
|
nativeBaseUrl,
|
|
201
218
|
providerCompat,
|
|
219
|
+
entry.headers,
|
|
202
220
|
managed,
|
|
203
221
|
clientHeaderProfile,
|
|
204
222
|
customClientHeaders,
|
package/tui/dashboard.ts
CHANGED
|
@@ -248,9 +248,13 @@ async function editStoredModel(
|
|
|
248
248
|
return false;
|
|
249
249
|
}
|
|
250
250
|
const draft = createModelDraftFromStoredModel(providerId, provider, model);
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
251
|
+
// [喵喵喵]: 保存失败时保留草稿继续编辑,防止用户修改的 contextWindow/maxTokens 等配置丢失
|
|
252
|
+
while (true) {
|
|
253
|
+
const outcome = await editModel(ctx, draft, t("编辑模型 {fullId}", { fullId: getModelFullId(providerId, modelId) }), requestHeaderProfiles, clientHeaderCaptures);
|
|
254
|
+
if (outcome.action !== "save") return false;
|
|
255
|
+
const saved = await saveModelDraft(pi, ctx, outcome.draft, modelId);
|
|
256
|
+
if (saved) return true;
|
|
257
|
+
}
|
|
254
258
|
}
|
|
255
259
|
|
|
256
260
|
async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext, providerId: string): Promise<boolean> {
|
|
@@ -301,16 +305,26 @@ async function showProviderMenu(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
301
305
|
if (action.type === "shortcut") {
|
|
302
306
|
if (action.shortcut === "add-model") {
|
|
303
307
|
const draft = createModelDraftForStoredProvider(providerId, currentProvider);
|
|
304
|
-
|
|
305
|
-
|
|
308
|
+
// [喵喵喵]: 新增模型校验或保存失败时保留草稿
|
|
309
|
+
while (true) {
|
|
310
|
+
const outcome = await editModel(ctx, draft, t("添加模型到 {providerId}", { providerId }), state.requestHeaderProfiles, state.clientHeaderCaptures);
|
|
311
|
+
if (outcome.action !== "save") break;
|
|
312
|
+
const saved = await saveModelDraft(pi, ctx, outcome.draft, undefined);
|
|
313
|
+
if (saved) break;
|
|
314
|
+
}
|
|
306
315
|
continue;
|
|
307
316
|
}
|
|
308
317
|
if (action.shortcut === "edit-provider") {
|
|
309
318
|
const draft = createProviderDraftFromStored(providerId, currentProvider);
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
await
|
|
313
|
-
if (outcome.
|
|
319
|
+
// [喵喵喵]: 编辑接入保存失败或重命名冲突时保留草稿,不退回主面板
|
|
320
|
+
while (true) {
|
|
321
|
+
const outcome = await editProvider(ctx, draft, t("编辑接入 {providerId}", { providerId }), state.requestHeaderProfiles);
|
|
322
|
+
if (outcome.action !== "save") break;
|
|
323
|
+
const saved = await saveProviderDraft(pi, ctx, outcome.draft, providerId);
|
|
324
|
+
if (saved) {
|
|
325
|
+
if (outcome.draft.providerId !== providerId) return true;
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
314
328
|
}
|
|
315
329
|
continue;
|
|
316
330
|
}
|
|
@@ -351,9 +365,12 @@ async function createProviderAndModel(pi: ExtensionAPI, ctx: ExtensionCommandCon
|
|
|
351
365
|
const stored = stagedState.providers[providerOutcome.draft.providerId]!;
|
|
352
366
|
ctx.ui.notify(t("请继续添加第一个模型;取消模型编辑则不会创建该接入。"), "info");
|
|
353
367
|
const modelDraft = createModelDraftForStoredProvider(providerOutcome.draft.providerId, stored);
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
368
|
+
while (true) {
|
|
369
|
+
const modelOutcome = await editModel(ctx, modelDraft, t("添加模型到 {providerId}", { providerId: providerOutcome.draft.providerId }), stagedState.requestHeaderProfiles, stagedState.clientHeaderCaptures);
|
|
370
|
+
if (modelOutcome.action !== "save") return false;
|
|
371
|
+
const saved = await saveNewProviderAndModelDraft(pi, ctx, providerOutcome.draft, modelOutcome.draft);
|
|
372
|
+
if (saved) return true;
|
|
373
|
+
}
|
|
357
374
|
}
|
|
358
375
|
}
|
|
359
376
|
|
package/tui/editor-model.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { t } from "../i18n.ts";
|
|
|
11
11
|
import type { AnthropicThinkingProtocol, BuiltInClientHeaderProfileId, ModelDraft, ModelListFetchOutcome, ReasoningMode, StoredClientHeaderCapture, StoredRequestHeaderProfile } from "../types.ts";
|
|
12
12
|
import { fetchModelIds } from "./model-list-fetch.ts";
|
|
13
13
|
import { pickModelIdFromList } from "./model-picker.ts";
|
|
14
|
-
import { showOptionPicker, showPersistentFormMenu, padLabel, type MenuCursor } from "./persistent-menu.ts";
|
|
14
|
+
import { showOptionPicker, showPersistentFormMenu, padLabel, markAdjustableValue, type MenuCursor, type HorizontalDirection } from "./persistent-menu.ts";
|
|
15
15
|
import {
|
|
16
16
|
describeVisionInput,
|
|
17
17
|
formatApiShort,
|
|
@@ -54,8 +54,65 @@ function getIntegerFieldLabel(field: "contextWindow" | "maxTokens"): string {
|
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
|
|
57
|
-
//
|
|
58
|
-
|
|
57
|
+
// [喵喵喵]: 上下文窗口常用十进制档位 (128k ~ 500k)
|
|
58
|
+
export const CONTEXT_WINDOW_PRESETS: readonly number[] = [
|
|
59
|
+
128_000,
|
|
60
|
+
200_000,
|
|
61
|
+
256_000,
|
|
62
|
+
272_000,
|
|
63
|
+
300_000,
|
|
64
|
+
400_000,
|
|
65
|
+
500_000,
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
// [喵喵喵]: 输出上限与上下文统一十进制档位 (16k ~ 128k);宁小勿大——写小仅封顶略低,写超真实上限会被 API 直接拒绝
|
|
69
|
+
export const MAX_TOKENS_PRESETS: readonly number[] = [
|
|
70
|
+
16_000,
|
|
71
|
+
32_000,
|
|
72
|
+
64_000,
|
|
73
|
+
128_000,
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
export function cycleNumericPreset(
|
|
77
|
+
current: number,
|
|
78
|
+
presets: readonly number[],
|
|
79
|
+
direction: HorizontalDirection,
|
|
80
|
+
): number {
|
|
81
|
+
if (presets.length === 0) return current;
|
|
82
|
+
if (direction === "left") {
|
|
83
|
+
for (let i = presets.length - 1; i >= 0; i--) {
|
|
84
|
+
if (presets[i] < current) return presets[i];
|
|
85
|
+
}
|
|
86
|
+
return presets[0];
|
|
87
|
+
}
|
|
88
|
+
for (let i = 0; i < presets.length; i++) {
|
|
89
|
+
if (presets[i] > current) return presets[i];
|
|
90
|
+
}
|
|
91
|
+
return presets[presets.length - 1];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function parsePositiveIntegerWithUnit(rawInput: string): number | undefined {
|
|
95
|
+
const trimmed = rawInput.trim();
|
|
96
|
+
if (!trimmed) return undefined;
|
|
97
|
+
|
|
98
|
+
const match = /^([0-9]+(?:\.[0-9]+)?)\s*([kmKM])?$/i.exec(trimmed);
|
|
99
|
+
if (!match) return undefined;
|
|
100
|
+
|
|
101
|
+
const num = Number.parseFloat(match[1]);
|
|
102
|
+
if (!Number.isFinite(num) || num <= 0) return undefined;
|
|
103
|
+
|
|
104
|
+
const unit = match[2]?.toLowerCase();
|
|
105
|
+
if (unit === "m") return Math.round(num * 1_000_000);
|
|
106
|
+
if (unit === "k") return Math.round(num * 1_000);
|
|
107
|
+
|
|
108
|
+
// 纯数字无单位时,若数值小于 1000(如输入 64、128、200),按习惯视作千倍处理
|
|
109
|
+
if (num < 1000) return Math.round(num * 1_000);
|
|
110
|
+
|
|
111
|
+
return Math.round(num);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 开关字段在两个方向上取反;数值字段按 direction 在预设间步进。
|
|
115
|
+
function applyHorizontalToggle(draft: ModelDraft, fieldId: string, direction: HorizontalDirection): boolean {
|
|
59
116
|
if (fieldId === "visionInput") {
|
|
60
117
|
draft.inputKinds = supportsVisionInput(draft.inputKinds) ? ["text"] : ["text", "image"];
|
|
61
118
|
return true;
|
|
@@ -72,6 +129,14 @@ function applyHorizontalToggle(draft: ModelDraft, fieldId: string): boolean {
|
|
|
72
129
|
draft.openAIServiceTier = draft.openAIServiceTier === "priority" ? undefined : "priority";
|
|
73
130
|
return true;
|
|
74
131
|
}
|
|
132
|
+
if (fieldId === "contextWindow") {
|
|
133
|
+
draft.contextWindow = cycleNumericPreset(draft.contextWindow, CONTEXT_WINDOW_PRESETS, direction);
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
if (fieldId === "maxTokens") {
|
|
137
|
+
draft.maxTokens = cycleNumericPreset(draft.maxTokens, MAX_TOKENS_PRESETS, direction);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
75
140
|
return false;
|
|
76
141
|
}
|
|
77
142
|
|
|
@@ -95,8 +160,8 @@ function buildRows(draft: ModelDraft): FieldRow[] {
|
|
|
95
160
|
rows.push({ id: "openAIServiceTier", label: "Fast mode", value: describeOpenAIServiceTier(draft), adjustable: true });
|
|
96
161
|
}
|
|
97
162
|
rows.push(
|
|
98
|
-
{ id: "contextWindow", label: t("上下文窗口"), value: String(draft.contextWindow) },
|
|
99
|
-
{ id: "maxTokens", label: t("最大输出"), value: String(draft.maxTokens) },
|
|
163
|
+
{ id: "contextWindow", label: t("上下文窗口"), value: String(draft.contextWindow), adjustable: true },
|
|
164
|
+
{ id: "maxTokens", label: t("最大输出"), value: String(draft.maxTokens), adjustable: true },
|
|
100
165
|
);
|
|
101
166
|
return rows;
|
|
102
167
|
}
|
|
@@ -172,8 +237,8 @@ async function editIntField(ctx: ExtensionCommandContext, draft: ModelDraft, fie
|
|
|
172
237
|
if (value === undefined) return;
|
|
173
238
|
const trimmed = value.trim();
|
|
174
239
|
if (!trimmed) return;
|
|
175
|
-
const parsed =
|
|
176
|
-
if (
|
|
240
|
+
const parsed = parsePositiveIntegerWithUnit(trimmed);
|
|
241
|
+
if (parsed === undefined || parsed <= 0) {
|
|
177
242
|
ctx.ui.notify(t("{label} 必须是正整数", { label }), "warning");
|
|
178
243
|
return;
|
|
179
244
|
}
|
|
@@ -279,7 +344,7 @@ export async function editModel(
|
|
|
279
344
|
// [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
|
|
280
345
|
const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
|
|
281
346
|
id: row.id,
|
|
282
|
-
label: `${padLabel(row.label, 16)}${row.value}`,
|
|
347
|
+
label: `${padLabel(row.label, 16)}${row.adjustable ? markAdjustableValue(row.value) : row.value}`,
|
|
283
348
|
adjustable: row.adjustable,
|
|
284
349
|
}));
|
|
285
350
|
const rows = buildRows(draft);
|
|
@@ -295,8 +360,8 @@ export async function editModel(
|
|
|
295
360
|
t("接入 {providerId} · API {api}", { providerId: draft.providerId, api: formatApiShort(draft.api) }),
|
|
296
361
|
t("Ctrl+S 保存并启用模型;不切换当前会话模型"),
|
|
297
362
|
],
|
|
298
|
-
onAdjust: (id) => {
|
|
299
|
-
if (!applyHorizontalToggle(draft, id)) return undefined;
|
|
363
|
+
onAdjust: (id, direction) => {
|
|
364
|
+
if (!applyHorizontalToggle(draft, id, direction)) return undefined;
|
|
300
365
|
return toMenuRows(buildRows(draft));
|
|
301
366
|
},
|
|
302
367
|
hints: [
|
package/tui/editor-provider.ts
CHANGED
|
@@ -8,13 +8,13 @@ import { hasStringRecordEntries } from "../common.ts";
|
|
|
8
8
|
import { t } from "../i18n.ts";
|
|
9
9
|
import { switchProviderDraftApiPreset } from "../presets/providers.ts";
|
|
10
10
|
import { redactUrlForDisplay } from "../sensitive-redaction.ts";
|
|
11
|
-
import { resolveRuntimeBaseUrl } from "../runtime-base-url.ts";
|
|
11
|
+
import { resolveRuntimeBaseUrl, validateRequestBaseUrl } from "../runtime-base-url.ts";
|
|
12
12
|
import {
|
|
13
13
|
DEFAULT_PROVIDER_HTTP_PROXY_URL,
|
|
14
14
|
type OpenAIChatCompatibilityMode,
|
|
15
15
|
type OpenAIResponsesStreamCompletionMode,
|
|
16
16
|
} from "../types.ts";
|
|
17
|
-
import { showOptionPicker, showPersistentFormMenu, padLabel, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
|
|
17
|
+
import { showOptionPicker, showPersistentFormMenu, padLabel, markAdjustableValue, type HorizontalDirection, type MenuCursor } from "./persistent-menu.ts";
|
|
18
18
|
import {
|
|
19
19
|
describeProfile,
|
|
20
20
|
formatApiShort,
|
|
@@ -95,7 +95,7 @@ function buildRows(
|
|
|
95
95
|
{ id: "api", label: t("API 协议"), value: draft.api },
|
|
96
96
|
{ id: "providerId", label: t("接入 ID(必填)"), value: draft.providerId || t("<必填>") },
|
|
97
97
|
{ id: "providerName", label: t("名称"), value: draft.providerName || t("<空>") },
|
|
98
|
-
{ id: "baseUrl", label: "Base URL", value: draft.baseUrl },
|
|
98
|
+
{ id: "baseUrl", label: "Base URL", value: redactUrlForDisplay(draft.baseUrl) },
|
|
99
99
|
];
|
|
100
100
|
if (draft.api === "openai-completions") {
|
|
101
101
|
rows.push({
|
|
@@ -270,9 +270,14 @@ async function editField(
|
|
|
270
270
|
if (value === undefined) return;
|
|
271
271
|
const trimmed = value.trim();
|
|
272
272
|
if (!trimmed) return;
|
|
273
|
-
// [喵喵喵]:
|
|
274
|
-
|
|
275
|
-
|
|
273
|
+
// [喵喵喵]: 当场校验并归一化成 SDK 可直接使用的根地址;若输入有误通过通知友好提示,避免未捕获异常导致 TUI 闪退丢失草稿
|
|
274
|
+
try {
|
|
275
|
+
validateRequestBaseUrl(trimmed);
|
|
276
|
+
draft.baseUrl = resolveRuntimeBaseUrl(draft.api, trimmed);
|
|
277
|
+
} catch (error) {
|
|
278
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
279
|
+
ctx.ui.notify(t("Base URL 格式错误:{error}", { error: message }), "warning");
|
|
280
|
+
}
|
|
276
281
|
}
|
|
277
282
|
|
|
278
283
|
export type ProviderEditOutcome =
|
|
@@ -290,7 +295,7 @@ export async function editProvider(
|
|
|
290
295
|
// [喵喵喵]: 字段行的排版在开关切换后要原样重建,抽成函数避免两处写法飘移。
|
|
291
296
|
const toMenuRows = (fieldRows: FieldRow[]) => fieldRows.map((row) => ({
|
|
292
297
|
id: row.id,
|
|
293
|
-
label: `${padLabel(row.label, 16)}${row.value}`,
|
|
298
|
+
label: `${padLabel(row.label, 16)}${row.adjustable ? markAdjustableValue(row.value) : row.value}`,
|
|
294
299
|
adjustable: row.adjustable,
|
|
295
300
|
}));
|
|
296
301
|
const rows = buildRows(draft, requestHeaderProfiles);
|
|
@@ -270,11 +270,21 @@ async function saveProfile(
|
|
|
270
270
|
}
|
|
271
271
|
try {
|
|
272
272
|
await saveRequestHeaderProfileConfiguration(pi, ctx, state, draft, oldProfileId);
|
|
273
|
-
return true;
|
|
274
273
|
} catch (error) {
|
|
275
274
|
ctx.ui.notify(t("保存失败:{error}", { error: formatUnknownError(error) }), "error");
|
|
276
275
|
return false;
|
|
277
276
|
}
|
|
277
|
+
// [喵喵喵]: 保存后重新计数——重命名场景下引用已改指向新 ID,用保存前状态会误判 (issue #1);
|
|
278
|
+
// 提示属于锦上添花,读取失败不能反向误导成保存失败
|
|
279
|
+
try {
|
|
280
|
+
const savedState = await readState();
|
|
281
|
+
if (countModelsUsingRequestHeaderProfile(savedState, draft.profileId.trim()) === 0) {
|
|
282
|
+
ctx.ui.notify(t("请求头 {profileId} 尚未被任何接入使用;在接入编辑器的「请求头」行选择后才会生效。", { profileId: draft.profileId.trim() }), "info");
|
|
283
|
+
}
|
|
284
|
+
} catch {
|
|
285
|
+
// 计数提示失败时静默跳过,保存结果不受影响
|
|
286
|
+
}
|
|
287
|
+
return true;
|
|
278
288
|
}
|
|
279
289
|
|
|
280
290
|
async function deleteProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext, profileId: string): Promise<boolean> {
|
|
@@ -309,9 +319,14 @@ async function editStoredProfile(pi: ExtensionAPI, ctx: ExtensionCommandContext,
|
|
|
309
319
|
ctx.ui.notify(t("请求头不存在:{profileId}", { profileId }), "warning");
|
|
310
320
|
return true;
|
|
311
321
|
}
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
322
|
+
const draft = createRequestHeaderProfileDraftFromStored(profileId, profile);
|
|
323
|
+
// [喵喵喵]: 保存失败时保留当前草稿重试,防止用户输入的头信息与名称被强制退出丢弃
|
|
324
|
+
while (true) {
|
|
325
|
+
const outcome = await editProfile(ctx, draft, t("编辑请求头 {profileId}", { profileId }));
|
|
326
|
+
if (outcome.action !== "save") return false;
|
|
327
|
+
const saved = await saveProfile(pi, ctx, outcome.draft, profileId);
|
|
328
|
+
if (saved) return true;
|
|
329
|
+
}
|
|
315
330
|
}
|
|
316
331
|
|
|
317
332
|
type HeaderProfileShortcut = "new-profile" | "delete-profile";
|
|
@@ -367,8 +382,14 @@ export async function runHeaderProfilesPanel(pi: ExtensionAPI, ctx: ExtensionCom
|
|
|
367
382
|
if (action.type === "cancel") return;
|
|
368
383
|
if (action.type === "shortcut") {
|
|
369
384
|
if (action.shortcut === "new-profile") {
|
|
370
|
-
const
|
|
371
|
-
|
|
385
|
+
const draft = createRequestHeaderProfileDraft(profileIds);
|
|
386
|
+
// [喵喵喵]: 新建保存失败时保留已输入的草稿继续编辑
|
|
387
|
+
while (true) {
|
|
388
|
+
const outcome = await editProfile(ctx, draft, t("新建请求头"));
|
|
389
|
+
if (outcome.action !== "save") break;
|
|
390
|
+
const saved = await saveProfile(pi, ctx, outcome.draft, undefined);
|
|
391
|
+
if (saved) break;
|
|
392
|
+
}
|
|
372
393
|
continue;
|
|
373
394
|
}
|
|
374
395
|
const selectedProfileId = rows[cursor.index]?.profileId;
|
package/tui/model-list-fetch.ts
CHANGED
|
@@ -140,7 +140,12 @@ async function requestModelIds(
|
|
|
140
140
|
temporaryProxyRoute = proxyConfig
|
|
141
141
|
? await openProxyRouteWithSignal(proxyConfig, url, signal)
|
|
142
142
|
: undefined;
|
|
143
|
-
|
|
143
|
+
// [喵喵喵]: 经由本地代理时强制禁止自动跟随 3xx 重定向,防止直连上游泄露 IP
|
|
144
|
+
const response = await fetch(temporaryProxyRoute?.url ?? url, {
|
|
145
|
+
headers,
|
|
146
|
+
signal,
|
|
147
|
+
redirect: temporaryProxyRoute ? "manual" : "follow",
|
|
148
|
+
});
|
|
144
149
|
const text = await readBoundedResponseText(response, signal);
|
|
145
150
|
if (!response.ok) {
|
|
146
151
|
const reason = response.status === 401 || response.status === 403 ? t("认证失败,请检查 API key 和认证头")
|
package/tui/persistent-menu.ts
CHANGED
|
@@ -79,6 +79,11 @@ export function padLabel(label: string, columns: number): string {
|
|
|
79
79
|
return padToVisibleWidth(label, columns);
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
// [喵喵喵]: 可左右键切换的行值两侧加滑块标记,让能力直接可见
|
|
83
|
+
export function markAdjustableValue(value: string): string {
|
|
84
|
+
return `← ${value} →`;
|
|
85
|
+
}
|
|
86
|
+
|
|
82
87
|
function getSearchText(row: MenuRow): string {
|
|
83
88
|
return (row.searchText ?? `${row.id}\n${row.label}`).toLocaleLowerCase();
|
|
84
89
|
}
|
|
@@ -196,7 +201,12 @@ function createPersistentMenu<TAction extends MenuAction | FormMenuAction | Shor
|
|
|
196
201
|
|
|
197
202
|
const syncCursor = (activeRows: MenuRow[]): void => {
|
|
198
203
|
const row = activeRows[selectedIndex];
|
|
199
|
-
if (row)
|
|
204
|
+
if (row) {
|
|
205
|
+
cursor.index = currentRows.indexOf(row);
|
|
206
|
+
} else {
|
|
207
|
+
// [喵喵喵]: 过滤为空时重置光标为 -1,防止外层快捷键取到陈旧索引误操作隐藏条目
|
|
208
|
+
cursor.index = -1;
|
|
209
|
+
}
|
|
200
210
|
};
|
|
201
211
|
|
|
202
212
|
const requestRender = (): void => {
|