pi-model-manager 0.1.0 → 0.2.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,11 +4,11 @@ English · [简体中文](./README.md)
4
4
 
5
5
  [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.82.0-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.1.0-2f81f7.svg)](https://www.npmjs.com/package/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.2.0-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
 
11
- > The current stable version is `0.1.0` and requires Pi `>=0.82.0`.
11
+ > The current stable version is `0.2.0` and requires Pi `>=0.82.0`.
12
12
 
13
13
  ## Interface preview
14
14
 
@@ -45,7 +45,7 @@ A TUI model and provider manager for [Pi](https://github.com/earendil-works/pi).
45
45
  - Route each provider directly or through its own HTTP(S) proxy.
46
46
  - Use recommended, disabled, Claude Code, Codex, or custom client-header profiles.
47
47
  - Reference API keys as literals, `$ENV_VAR` / `${ENV_VAR}`, or Pi `!command` values.
48
- - Persist configuration atomically and re-register managed providers after saving.
48
+ - Persist configuration with a cross-process lock and recoverable two-file transactions, then re-register managed providers after saving.
49
49
 
50
50
  ## Installation
51
51
 
@@ -92,6 +92,7 @@ pi install npm:pi-model-manager
92
92
  | `n` | Create a provider and its first model |
93
93
  | `d` | Delete the selected provider |
94
94
  | `h` | Manage reusable header profiles |
95
+ | `/` | Search the current list |
95
96
  | `Esc` | Go back or exit |
96
97
 
97
98
  4. In an editor, use the arrow keys to select a field and press `Enter` to edit it. Toggle supported fields with `←` / `→`, then press `Ctrl+S` to save.
@@ -108,7 +109,7 @@ Each provider can define:
108
109
  - Provider-specific HTTP(S) proxy
109
110
  - One or more models
110
111
 
111
- When adding a model, the extension attempts to fetch the upstream model list with a 10-second timeout. You can still enter a model ID manually if discovery fails.
112
+ When adding a model, the extension attempts to fetch the upstream model list. The complete discovery flow, including authentication fallbacks, shares one 10-second limit and can be cancelled with `Esc`. You can still enter a model ID manually after failure or cancellation.
112
113
 
113
114
  Model capabilities include:
114
115
 
@@ -145,7 +146,9 @@ Custom profiles reject authentication-related sensitive headers. Put authenticat
145
146
  | `~/.pi/agent/models.json` | Native Pi provider and model definitions; the single source of truth for model configuration |
146
147
  | `~/.pi/agent/extensions/pi-model-manager/state.json` | Extension metadata such as header choices, custom profiles, proxy switches, and Fast mode |
147
148
 
148
- The extension preserves native `models.json` fields that are outside the TUI's editing scope whenever possible. Avoid modifying the same configuration file from multiple processes at once.
149
+ The extension generates client headers, proxy routes, and dynamic registrations only for explicitly managed providers. Ownership requires both a managed ID in `state.json` and a `piModelManager.managed` marker on the Provider node in `models.json`; this prevents a deleted Provider ID from silently taking ownership of an unrelated native Provider that later reuses the same ID. Native providers without this ownership evidence remain unmanaged: saving unrelated settings does not rewrite their existing headers or unknown native fields. Built-in Pi providers cannot be edited or deleted through this extension.
150
+
151
+ Plugin configuration writes are serialized with a cross-process lock, and `enabledModels` also honors Pi's `proper-lockfile` lock. An intent journal makes the `models.json` / `state.json` pair recoverable after interruption, and readers reject an in-progress half-written pair. External editors do not honor these locks, so content hashes are still checked before saving; an external change cancels the save instead of being overwritten.
149
152
 
150
153
  ## Secrets and security
151
154
 
@@ -203,4 +206,4 @@ Thanks to the [LINUX DO](https://linux.do/) community for discussion, sharing, a
203
206
 
204
207
  ## License
205
208
 
206
- Official releases from `v0.1.0` onward are licensed under the [GNU Affero General Public License v3.0 only](./LICENSE). Modified distributions must provide the corresponding source, remain under AGPL-3.0, and identify their changes; they must not represent themselves as official releases. See [NOTICE](./NOTICE).
209
+ This project is licensed under the [GNU Affero General Public License v3.0 only](./LICENSE). Modified distributions must provide the corresponding source, remain under AGPL-3.0, and identify their changes; they must not represent themselves as official releases. See [NOTICE](./NOTICE).
package/README.md CHANGED
@@ -4,11 +4,11 @@
4
4
 
5
5
  [![Pi](https://img.shields.io/badge/Pi-%3E%3D0.82.0-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.1.0-2f81f7.svg)](https://www.npmjs.com/package/pi-model-manager)
7
+ [![Version](https://img.shields.io/badge/version-0.2.0-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
 
11
- > 当前稳定版为 `0.1.0`,要求 Pi `>=0.82.0`。
11
+ > 当前稳定版为 `0.2.0`,要求 Pi `>=0.82.0`。
12
12
 
13
13
  ## 界面预览
14
14
 
@@ -45,7 +45,7 @@
45
45
  - 为每个接入单独配置直连或 HTTP(S) 代理。
46
46
  - 提供自动推荐、禁用、Claude Code、Codex 和自定义请求头模式。
47
47
  - API key 支持字面值、`$ENV_VAR` / `${ENV_VAR}` 和 Pi 的 `!command` 引用。
48
- - 原子写入配置,并在保存后重新注册受管理的 Provider,无需手工编辑多处分散状态。
48
+ - 使用跨进程锁与可恢复双文件事务持久化配置,并在保存后重新注册受管理的 Provider。
49
49
 
50
50
  ## 安装
51
51
 
@@ -92,6 +92,7 @@ pi install npm:pi-model-manager
92
92
  | `n` | 新建接入及其第一个模型 |
93
93
  | `d` | 删除所选接入 |
94
94
  | `h` | 管理可复用请求头 |
95
+ | `/` | 搜索当前列表 |
95
96
  | `Esc` | 返回或退出 |
96
97
 
97
98
  4. 在编辑器中使用方向键选择字段,按 `Enter` 编辑;支持切换的字段可用 `←` / `→` 调整;按 `Ctrl+S` 保存。
@@ -110,7 +111,7 @@ pi install npm:pi-model-manager
110
111
  - 接入级 HTTP(S) 代理
111
112
  - 一个或多个模型
112
113
 
113
- 新建模型时,扩展会尝试在 10 秒内从上游读取模型列表;失败后仍可手动输入模型 ID。
114
+ 新建模型时,扩展会尝试从上游读取模型列表;整次发现(包括认证回退)共用一个 10 秒上限,可按 `Esc` 手动取消。失败或取消后仍可手动输入模型 ID。
114
115
 
115
116
  ### 模型能力
116
117
 
@@ -149,7 +150,9 @@ pi install npm:pi-model-manager
149
150
  | `~/.pi/agent/models.json` | Pi 原生接入与模型定义;模型配置的唯一权威来源 |
150
151
  | `~/.pi/agent/extensions/pi-model-manager/state.json` | 请求头选择、自定义请求头、代理开关和 Fast mode 等扩展私有元数据 |
151
152
 
152
- 扩展会尽量保留 `models.json` 中不由 TUI 编辑的原生字段。不要同时让多个进程修改同一配置文件。
153
+ 扩展只会为明确受管理的 Provider 生成请求头、代理路由和动态注册配置。所有权由 `state.json` 的受管理 ID 与 `models.json` Provider 节点中的 `piModelManager.managed` 标记共同确认,防止已删除的 Provider ID 在日后被同名原生配置复用时遭到插件接管。没有这些所有权信息的原生 Provider 保持未管理,其已有 Header 和未知原生字段不会因保存其它配置而被改写;Pi 内置 Provider 不在本扩展中提供编辑或删除入口。
154
+
155
+ 插件自身的配置写入由跨进程锁串行化,`enabledModels` 还同时遵守 Pi 的 `proper-lockfile` 锁;`models.json` 与 `state.json` 通过事务意图文件在中断后恢复,读取方不会采用事务进行中的半完成组合。外部编辑器不受这些锁约束,因此保存前仍会校验内容签名;检测到外部修改时会取消保存而不是覆盖。
153
156
 
154
157
  ## 密钥与安全
155
158
 
@@ -207,4 +210,4 @@ npm pack --dry-run
207
210
 
208
211
  ## 许可证
209
212
 
210
- `v0.1.0` 及后续官方版本采用 [GNU Affero General Public License v3.0 only](./LICENSE)。分发修改版本时必须公开对应源码、继续使用 AGPL-3.0,并明确标注改动;修改版不得冒充官方发行。详见 [NOTICE](./NOTICE)。
213
+ 本项目采用 [GNU Affero General Public License v3.0 only](./LICENSE)。分发修改版本时必须公开对应源码、继续使用 AGPL-3.0,并明确标注改动;修改版不得冒充官方发行。详见 [NOTICE](./NOTICE)。
package/atomic-write.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  // Windows 友好的配置文件持久化写入。
2
2
  //
3
3
  // 目标文件可能被正在运行的 pi、编辑器、杀软或索引器短暂占用。
4
- // 直接 rename(tmp, target) 在 Windows 上会留下 tmp 且正式配置不变;这里统一
5
- // 处理重试、降级覆盖与失败时的可恢复临时文件提示。
4
+ // 直接 rename(tmp, target) 在 Windows 上可能因短暂占用失败;这里只进行有限重试,
5
+ // 不以非原子的 copy 覆盖冒充成功,最终失败时保留完整临时文件供恢复。
6
6
 
7
7
  import { randomUUID } from "node:crypto";
8
- import { copyFile, mkdir, rename, unlink, writeFile } from "node:fs/promises";
8
+ import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
9
9
  import { dirname } from "node:path";
10
10
 
11
11
  const REPLACE_RETRY_DELAYS_MS = [25, 50, 100, 200, 400, 800] as const;
@@ -53,35 +53,7 @@ async function renameWithRetry(sourcePath: string, targetPath: string): Promise<
53
53
  throw lastError;
54
54
  }
55
55
 
56
- async function copyOverTargetWithRetry(sourcePath: string, targetPath: string): Promise<void> {
57
- let lastError: unknown;
58
- for (let attempt = 0; attempt <= REPLACE_RETRY_DELAYS_MS.length; attempt += 1) {
59
- try {
60
- await copyFile(sourcePath, targetPath);
61
- await removeTempFile(sourcePath);
62
- return;
63
- } catch (error) {
64
- lastError = error;
65
- if (!isTransientReplaceError(error) || attempt === REPLACE_RETRY_DELAYS_MS.length) break;
66
- await sleep(REPLACE_RETRY_DELAYS_MS[attempt]!);
67
- }
68
- }
69
- throw lastError;
70
- }
71
56
 
72
- async function replaceTargetFile(sourcePath: string, targetPath: string): Promise<void> {
73
- try {
74
- await renameWithRetry(sourcePath, targetPath);
75
- } catch (renameError) {
76
- if (process.platform !== "win32" || !isTransientReplaceError(renameError)) throw renameError;
77
- // [喵喵喵]: Windows 上 rename 覆盖会被短暂文件锁拦截;重试后降级 copyFile,避免配置保存停留在 tmp (2026-06-21)
78
- try {
79
- await copyOverTargetWithRetry(sourcePath, targetPath);
80
- } catch (copyError) {
81
- throw new Error(`rename 失败:${formatError(renameError)};copy 覆盖也失败:${formatError(copyError)}`);
82
- }
83
- }
84
- }
85
57
 
86
58
  export async function atomicWriteText(targetPath: string, content: string): Promise<void> {
87
59
  await mkdir(dirname(targetPath), { recursive: true });
@@ -91,7 +63,7 @@ export async function atomicWriteText(targetPath: string, content: string): Prom
91
63
  try {
92
64
  await writeFile(tempPath, content, "utf8");
93
65
  tempHasCompleteContent = true;
94
- await replaceTargetFile(tempPath, targetPath);
66
+ await renameWithRetry(tempPath, targetPath);
95
67
  } catch (error) {
96
68
  if (!tempHasCompleteContent) await removeTempFile(tempPath);
97
69
  const recoveryNote = tempHasCompleteContent ? `;完整内容已保留在临时文件:${tempPath}` : "";
package/common.ts CHANGED
@@ -16,15 +16,6 @@ export function trimOrFallback(value: string | undefined, fallback: string): str
16
16
  return trimmed ? trimmed : fallback;
17
17
  }
18
18
 
19
- export function trimSingleLine(value: string): string {
20
- return value.replace(/[\r\n]+/g, " ").trim();
21
- }
22
-
23
- export function trimSingleLineOrFallback(value: string | undefined, fallback: string): string {
24
- const singleLine = value?.replace(/[\r\n]+/g, " ").trim();
25
- return singleLine ? singleLine : fallback;
26
- }
27
-
28
19
  export function formatUnknownError(error: unknown): string {
29
20
  return error instanceof Error ? error.message : String(error);
30
21
  }
@@ -56,11 +47,3 @@ export function stringifyJson(value: unknown): string {
56
47
  export function cloneJson<T>(value: T): T {
57
48
  return value === undefined ? value : JSON.parse(JSON.stringify(value));
58
49
  }
59
-
60
- export function slugifyName(name: string): string {
61
- return name
62
- .trim()
63
- .toLowerCase()
64
- .replace(/[^a-z0-9._-]+/g, "-")
65
- .replace(/^-+|-+$/g, "");
66
- }
@@ -0,0 +1,136 @@
1
+ // 跨 Pi 进程的配置 mutation 锁。只约束遵守本锁的插件写入,外部编辑器冲突另由内容签名检测。
2
+
3
+ import { hostname } from "node:os";
4
+ import { open, mkdir, readFile, stat, unlink, type FileHandle } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { randomUUID } from "node:crypto";
7
+ import { STATE_DIR } from "./state-metadata-store.ts";
8
+
9
+ interface ConfigurationLockRecord {
10
+ token: string;
11
+ pid: number;
12
+ hostname: string;
13
+ startedAt: string;
14
+ }
15
+
16
+ interface HeldConfigurationLock {
17
+ handle: FileHandle;
18
+ record: ConfigurationLockRecord;
19
+ }
20
+
21
+ const LOCK_PATH = join(STATE_DIR, "config.lock");
22
+ const LOCK_RETRY_DELAYS_MS = [50, 100, 200, 400, 800] as const;
23
+ const INVALID_LOCK_STALE_MS = 30_000;
24
+
25
+ function sleep(ms: number): Promise<void> {
26
+ return new Promise((resolve) => setTimeout(resolve, ms));
27
+ }
28
+
29
+ function getErrorCode(error: unknown): string | undefined {
30
+ return error instanceof Error && "code" in error
31
+ ? String((error as NodeJS.ErrnoException).code)
32
+ : undefined;
33
+ }
34
+
35
+ function parseLockRecord(source: string): ConfigurationLockRecord | undefined {
36
+ try {
37
+ const parsed = JSON.parse(source) as Partial<ConfigurationLockRecord>;
38
+ if (typeof parsed.token !== "string" || !parsed.token) return undefined;
39
+ if (!Number.isInteger(parsed.pid) || (parsed.pid ?? 0) <= 0) return undefined;
40
+ if (typeof parsed.hostname !== "string" || !parsed.hostname) return undefined;
41
+ if (typeof parsed.startedAt !== "string" || !parsed.startedAt) return undefined;
42
+ return parsed as ConfigurationLockRecord;
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ }
47
+
48
+ function isSameHostProcessRunning(record: ConfigurationLockRecord): boolean {
49
+ if (record.hostname !== hostname()) return true;
50
+ try {
51
+ process.kill(record.pid, 0);
52
+ return true;
53
+ } catch (error) {
54
+ return getErrorCode(error) !== "ESRCH";
55
+ }
56
+ }
57
+
58
+ async function removeInactiveLock(): Promise<boolean> {
59
+ let source: string;
60
+ try {
61
+ source = await readFile(LOCK_PATH, "utf8");
62
+ } catch (error) {
63
+ return getErrorCode(error) === "ENOENT";
64
+ }
65
+ const record = parseLockRecord(source);
66
+ if (record && isSameHostProcessRunning(record)) return false;
67
+ if (!record) {
68
+ try {
69
+ const lockStats = await stat(LOCK_PATH);
70
+ if (Date.now() - lockStats.mtimeMs < INVALID_LOCK_STALE_MS) return false;
71
+ } catch (error) {
72
+ return getErrorCode(error) === "ENOENT";
73
+ }
74
+ }
75
+ try {
76
+ await unlink(LOCK_PATH);
77
+ return true;
78
+ } catch (error) {
79
+ return getErrorCode(error) === "ENOENT";
80
+ }
81
+ }
82
+
83
+ async function acquireConfigurationLock(): Promise<HeldConfigurationLock> {
84
+ await mkdir(STATE_DIR, { recursive: true });
85
+ const record: ConfigurationLockRecord = {
86
+ token: randomUUID(),
87
+ pid: process.pid,
88
+ hostname: hostname(),
89
+ startedAt: new Date().toISOString(),
90
+ };
91
+
92
+ for (let attempt = 0; attempt <= LOCK_RETRY_DELAYS_MS.length; attempt += 1) {
93
+ try {
94
+ const handle = await open(LOCK_PATH, "wx");
95
+ try {
96
+ await handle.writeFile(`${JSON.stringify(record)}\n`, "utf8");
97
+ await handle.sync();
98
+ return { handle, record };
99
+ } catch (error) {
100
+ await handle.close().catch(() => undefined);
101
+ await unlink(LOCK_PATH).catch(() => undefined);
102
+ throw error;
103
+ }
104
+ } catch (error) {
105
+ if (getErrorCode(error) !== "EEXIST") throw error;
106
+ if (await removeInactiveLock()) continue;
107
+ if (attempt === LOCK_RETRY_DELAYS_MS.length) break;
108
+ await sleep(LOCK_RETRY_DELAYS_MS[attempt]!);
109
+ }
110
+ }
111
+ throw new Error(`另一个 Pi 进程正在保存模型配置;无法在限定时间内获取锁:${LOCK_PATH}`);
112
+ }
113
+
114
+ async function releaseConfigurationLock(lock: HeldConfigurationLock): Promise<void> {
115
+ await lock.handle.close();
116
+ let current: ConfigurationLockRecord | undefined;
117
+ try {
118
+ current = parseLockRecord(await readFile(LOCK_PATH, "utf8"));
119
+ } catch (error) {
120
+ if (getErrorCode(error) === "ENOENT") return;
121
+ throw error;
122
+ }
123
+ if (current?.token !== lock.record.token) {
124
+ throw new Error(`配置锁所有权在释放前发生变化,已保留锁文件供检查:${LOCK_PATH}`);
125
+ }
126
+ await unlink(LOCK_PATH);
127
+ }
128
+
129
+ export async function withConfigurationLock<T>(operation: () => Promise<T>): Promise<T> {
130
+ const lock = await acquireConfigurationLock();
131
+ try {
132
+ return await operation();
133
+ } finally {
134
+ await releaseConfigurationLock(lock);
135
+ }
136
+ }