pi-model-setting 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +207 -2
- package/index.ts +3 -0
- package/package.json +42 -4
- package/src/context-window.ts +42 -0
- package/src/extension.ts +144 -0
- package/src/selector.ts +172 -0
- package/src/service-tier.ts +13 -0
- package/src/settings.ts +134 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DavidEasden
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,208 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-model-setting
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A standalone extension for **Pi 1.7.0**. It does not modify Pi's source code, `models.json`, or authentication configuration.
|
|
4
|
+
|
|
5
|
+
- `/service_tier`: choose `default`, `fast`, or `ultrafast` for models where `provider === "openai"`.
|
|
6
|
+
- `/context_window`: set the context window of the current physical chat model for any provider.
|
|
7
|
+
- All command descriptions, selectors, results, and error messages are in English.
|
|
8
|
+
- Settings are stored per `provider/modelId` and never shared between models.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Requires Pi 1.7.0. The package ships the TypeScript source that Pi loads directly, so there is no build step and no `dist/` directory to wait for.
|
|
13
|
+
|
|
14
|
+
### From Git
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pi install git:github.com/DavidEasden/pi-model-setting
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
That tracks the repository's default branch. Pin an explicit ref when you want a fixed version; Pi reconciles the checkout to that ref and does not move it on update:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pi install git:github.com/DavidEasden/pi-model-setting@main
|
|
24
|
+
pi install git:github.com/DavidEasden/pi-model-setting@<tag-or-commit>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
An HTTPS repository URL is treated as a Git source as well:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pi install https://github.com/DavidEasden/pi-model-setting
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Git packages are cloned under `~/.pi/agent/git/<host>/<owner>/<repo>`, and Pi installs their declared dependencies on installation. This package only declares `@earendil-works/*` as peer dependencies, which Pi supplies itself, so nothing needs to be installed by hand.
|
|
34
|
+
|
|
35
|
+
### From npm
|
|
36
|
+
|
|
37
|
+
Available once the package has been published to the npm registry:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pi install npm:pi-model-setting
|
|
41
|
+
pi install npm:pi-model-setting@0.1.0
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
An exact version is pinned and not checked for updates.
|
|
45
|
+
|
|
46
|
+
### From a local checkout
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pi install .
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
A local package is loaded from the resolved path without being copied; run the command from the project directory, or pass an absolute path instead. The declaration is stored as a path relative to the settings file that contains it, so prefer a Git or npm source for an install that should survive moving the checkout.
|
|
53
|
+
|
|
54
|
+
### Try it without changing your settings
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pi -e git:github.com/DavidEasden/pi-model-setting
|
|
58
|
+
pi -e ./index.ts
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`-e` leaves the installed package list untouched and caches Git sources under `~/.pi/agent/tmp/extensions/`, re-checking them on every start and `/reload`.
|
|
62
|
+
|
|
63
|
+
### Manage the installation
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pi list # show installed packages
|
|
67
|
+
pi update --extensions # reinstall packages and reconcile their refs
|
|
68
|
+
pi update git:github.com/DavidEasden/pi-model-setting # update this package only
|
|
69
|
+
pi remove git:github.com/DavidEasden/pi-model-setting
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Add `--local` (`-l`) to write the declaration to `.pi/settings.json` instead of personal settings; project packages load only after project trust is granted.
|
|
73
|
+
|
|
74
|
+
After installing, restart Pi or run `/reload` in an existing session. Do not add both `index.ts` and the whole package at the same time, since the first loads one extension file and the second loads the package.
|
|
75
|
+
|
|
76
|
+
Development and testing require Node.js 22.19 or newer.
|
|
77
|
+
|
|
78
|
+
## Commands and interaction
|
|
79
|
+
|
|
80
|
+
Type a command on its own to open a searchable list:
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
/service_tier
|
|
84
|
+
/context_window
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
| Command | Options |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `/service_tier` | `default`, `fast`, `ultrafast` |
|
|
90
|
+
| `/context_window` | `Model default`, `512k`, `1m`, `Custom…` |
|
|
91
|
+
|
|
92
|
+
- Arrow keys move the cursor; typing filters the list. The current value is marked with `✓`.
|
|
93
|
+
- **Enter**: apply to the current session and persist the choice in the session branch.
|
|
94
|
+
- **Ctrl+S**: apply, and also save it as the default for the current model in new sessions.
|
|
95
|
+
- **Esc**: cancel without committing a selection.
|
|
96
|
+
- Saved defaults are labelled `Saved default`.
|
|
97
|
+
- `Custom…` accepts integers plus `k` / `m` suffixes. Pressing Ctrl+S on that item saves the entered value as the default.
|
|
98
|
+
- Navigation, confirm, and cancel use the keybindings Pi injects; Ctrl+S is specific to this selector.
|
|
99
|
+
|
|
100
|
+
You can also apply a value directly to the current session:
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
/service_tier default
|
|
104
|
+
/service_tier fast
|
|
105
|
+
/service_tier ultrafast
|
|
106
|
+
/context_window 512k
|
|
107
|
+
/context_window 1m
|
|
108
|
+
/context_window 750000
|
|
109
|
+
/context_window auto
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
There are no `/tier` or `/ctx` aliases. To save a default, use Ctrl+S in the list rather than an extra long form command.
|
|
113
|
+
|
|
114
|
+
The no-argument list is TUI-only. RPC can use the commands with arguments; print / JSON modes can apply arguments too, but Pi does not show UI notifications in those modes. The commands refuse changes while a model request, compaction, or another operation is in progress.
|
|
115
|
+
|
|
116
|
+
## What the context window means
|
|
117
|
+
|
|
118
|
+
`512k = 512,000` and `1m = 1,000,000`, using decimal units.
|
|
119
|
+
|
|
120
|
+
`Model default` dynamically reads `contextWindow` from the current model registry. It includes the original model configuration but excludes any override applied by this extension. Choosing it is equivalent to `/context_window auto`:
|
|
121
|
+
|
|
122
|
+
- removes the extension's override and follows the model configuration;
|
|
123
|
+
- saving writes `null`, **not a snapshot of the length at that moment**;
|
|
124
|
+
- re-syncs on model switch, reload, opening the command, or entering a request boundary;
|
|
125
|
+
- if external code refreshes only the registry without emitting events, the sync happens at the next such boundary — the model registry is not polled.
|
|
126
|
+
|
|
127
|
+
The change applies to the active model's metadata, so Pi's context usage display and automatic compaction decisions use the new value. It does not change `maxTokens`, the thinking level, or model selection, and it never puts a context-length field into HTTP requests.
|
|
128
|
+
|
|
129
|
+
Explicit values must be positive safe integers and greater than the effective compaction reserve for the current model. Validation follows Pi's own order: `compaction.modelOverrides["provider/modelId"].reserveTokens` → global `compaction.reserveTokens` → `16,384`. The check is kept even when automatic compaction is currently disabled. If a stored value is no longer valid while restoring, an error is reported and that override is not applied.
|
|
130
|
+
|
|
131
|
+
**This is only a local context budget; it does not give the server a larger context capability.** Set it according to the real backend limit. A smaller value also does not delete history immediately; the next normal compaction check decides whether to compact.
|
|
132
|
+
|
|
133
|
+
Limits for virtual routed models depend on the final physical model, so you cannot change the context of `pi-virtual` directly; switch to the physical model you want to configure first. Image generation and classification models are not chat models and are out of scope.
|
|
134
|
+
|
|
135
|
+
## Service tier boundaries
|
|
136
|
+
|
|
137
|
+
Only models whose provider is exactly `openai`, using the `openai-responses` or `openai-completions` API, are supported. The field is not injected into Anthropic, Google, `openai-codex`, or any other custom provider.
|
|
138
|
+
|
|
139
|
+
The request body `service_tier` is set through the public `before_provider_request` hook:
|
|
140
|
+
|
|
141
|
+
- sends `default` when no other value is selected;
|
|
142
|
+
- sends `fast` and `ultrafast` verbatim, without mapping them to `priority` or any other value;
|
|
143
|
+
- leaves all other request fields unchanged;
|
|
144
|
+
- keeps the original error if the backend rejects the tier, with no silent downgrade.
|
|
145
|
+
|
|
146
|
+
**Whether a tier is available, its pricing, and its limits are decided by the backend.** This extension does not promise that official OpenAI or any compatible endpoint accepts `ultrafast`, and it does not adjust Pi's cost accounting.
|
|
147
|
+
|
|
148
|
+
In Pi 1.7.0 that hook receives only the payload, with no physical model argument. The extension verifies the current provider/API and the model ID inside the payload, so it does not force a tier onto virtual routing or onto a different model request redirected by another extension. It covers normal session requests; Pi's built-in compaction summaries, branch summaries, and standalone requests issued directly by other extensions are not guaranteed to pass through this hook.
|
|
149
|
+
|
|
150
|
+
## Storage and recovery
|
|
151
|
+
|
|
152
|
+
Model defaults are stored in:
|
|
153
|
+
|
|
154
|
+
```text
|
|
155
|
+
~/.pi/agent/pi-model-setting.json
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
When `--agent-dir` or `PI_CODING_AGENT_DIR` is used, the file follows the corresponding directory.
|
|
159
|
+
|
|
160
|
+
Example:
|
|
161
|
+
|
|
162
|
+
```json
|
|
163
|
+
{
|
|
164
|
+
"version": 1,
|
|
165
|
+
"models": {
|
|
166
|
+
"openai/gpt-5.5": {
|
|
167
|
+
"service_tier": "fast",
|
|
168
|
+
"contextWindow": null
|
|
169
|
+
},
|
|
170
|
+
"anthropic/claude-sonnet-4-5": {
|
|
171
|
+
"contextWindow": 1000000
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Precedence is resolved per field:
|
|
178
|
+
|
|
179
|
+
1. a value explicitly selected in the current session branch;
|
|
180
|
+
2. the saved default for that model;
|
|
181
|
+
3. the context window falls back to the model's original configuration, and the service tier falls back to `default`.
|
|
182
|
+
|
|
183
|
+
Session values are stored with `pi.appendEntry("pi-model-setting", ...)` and never enter the model context. Restoring a session, reloading, deriving sessions, and tree navigation rebuild the settings from the current branch and ignore selections from abandoned branches. A `--no-session` session keeps session values in process memory only.
|
|
184
|
+
|
|
185
|
+
The context override on the original object is reverted when the model switches, the extension shuts down, or the extension reloads. If another extension has already rewritten that field, a stale value is not forced back. Ordinary CLI runs use a separate runtime per session; SDK hosts should not share one mutable Model object across concurrent sessions.
|
|
186
|
+
|
|
187
|
+
Saving uses a file lock, a re-read-and-merge while holding the lock, then a temporary file and an atomic replace. A corrupt configuration, unknown version, or held lock produces an error: the original file is left untouched and the selection is not applied. A concurrent save that hits the lock may retry later; if a process was killed while holding the lock, clean up `pi-model-setting.json.lock` in the same directory only after confirming that no other Pi is saving.
|
|
188
|
+
|
|
189
|
+
## Development and verification
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
npm install
|
|
193
|
+
npm run check
|
|
194
|
+
npm test
|
|
195
|
+
npm pack --dry-run
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
To publish a new version, bump `version` in `package.json`, then run `npm login` once and `npm publish`. The published tarball contains `index.ts`, `src/`, the README, the LICENSE, and package metadata only.
|
|
199
|
+
|
|
200
|
+
The tests cover:
|
|
201
|
+
|
|
202
|
+
- number parsing, configuration validation, branch restoration, atomic saves, and lock contention;
|
|
203
|
+
- per-model isolation, dynamic original values, reversion, and registry object refresh;
|
|
204
|
+
- selector search, cancel, Enter / Ctrl+S, custom input, remapped keybindings, and narrow screens;
|
|
205
|
+
- the real Pi 1.7.0 SDK, verifying usage display, the automatic compaction threshold, reload, tree navigation, new-session defaults, and uninstall;
|
|
206
|
+
- a local HTTP fake server verifying the actual Responses / Chat Completions request bodies, without contacting a real model service.
|
|
207
|
+
|
|
208
|
+
The runtime uses the source entry point. The published manifest contains only `index.ts`, `src/`, the README, the LICENSE, and package metadata — no `resource/` reference source, session data, or test dependencies.
|
package/index.ts
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-model-setting",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "为 Pi 提供按模型保存的服务档位和上下文长度设置",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/DavidEasden/pi-model-setting.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": [
|
|
12
|
+
"pi-package"
|
|
13
|
+
],
|
|
14
|
+
"files": [
|
|
15
|
+
"index.ts",
|
|
16
|
+
"src",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"pi": {
|
|
20
|
+
"extensions": [
|
|
21
|
+
"./index.ts"
|
|
22
|
+
]
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "tsx --test tests/*.test.ts",
|
|
26
|
+
"check": "tsc --noEmit"
|
|
27
|
+
},
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=22.19.0"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@earendil-works/pi-ai": "*",
|
|
33
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
34
|
+
"@earendil-works/pi-tui": "*"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
38
|
+
"@earendil-works/pi-coding-agent": "1.7.0",
|
|
39
|
+
"@earendil-works/pi-tui": "1.7.0",
|
|
40
|
+
"@types/node": "^22.0.0",
|
|
41
|
+
"tsx": "^4.20.0",
|
|
42
|
+
"typescript": "^5.7.0"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ContextWindow } from "./settings.ts";
|
|
3
|
+
|
|
4
|
+
export function modelKey(model: Pick<Model<string>, "provider" | "id">): string {
|
|
5
|
+
return `${model.provider}/${model.id}`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function validateContextWindow(value: ContextWindow, reserveTokens: number): void {
|
|
9
|
+
if (value !== null && (!Number.isSafeInteger(value) || value <= reserveTokens)) {
|
|
10
|
+
throw new Error(`Context window must be greater than the compaction reserve (${reserveTokens.toLocaleString("en-US")} tokens).`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class ContextWindowOverride {
|
|
15
|
+
private patched = new Map<Model<string>, { original: number; applied: number }>();
|
|
16
|
+
|
|
17
|
+
original(model: Model<string>): number {
|
|
18
|
+
const patch = this.patched.get(model);
|
|
19
|
+
return patch && model.contextWindow === patch.applied ? patch.original : model.contextWindow;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
restore(): void {
|
|
23
|
+
for (const [model, patch] of this.patched) {
|
|
24
|
+
// 其他扩展已改变同一字段时,不用旧快照覆盖它的新值。
|
|
25
|
+
if (model.contextWindow === patch.applied) model.contextWindow = patch.original;
|
|
26
|
+
}
|
|
27
|
+
this.patched.clear();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
apply(model: Model<string> | undefined, registered: Model<string> | undefined, value: ContextWindow | undefined): number | undefined {
|
|
31
|
+
const baseline = registered ? this.original(registered) : model ? this.original(model) : undefined;
|
|
32
|
+
this.restore();
|
|
33
|
+
if (!model || baseline === undefined) return;
|
|
34
|
+
// 注册表刷新可能换了对象;旧活动对象也应跟随新的原始配置。
|
|
35
|
+
model.contextWindow = baseline;
|
|
36
|
+
if (value !== undefined && value !== null) {
|
|
37
|
+
this.patched.set(model, { original: baseline, applied: value });
|
|
38
|
+
model.contextWindow = value;
|
|
39
|
+
}
|
|
40
|
+
return baseline;
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/extension.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { getAgentDir, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { ContextWindowOverride, modelKey, validateContextWindow } from "./context-window.ts";
|
|
4
|
+
import { applyServiceTier, supportsServiceTier } from "./service-tier.ts";
|
|
5
|
+
import { contextChoices, showSelector, tierChoices } from "./selector.ts";
|
|
6
|
+
import {
|
|
7
|
+
ENTRY_TYPE, SettingsStore, effectiveSettings, emptySettings, isServiceTier,
|
|
8
|
+
parseContextWindow, restoreSettings, settingsFor, updateSettings,
|
|
9
|
+
type ModelSettings,
|
|
10
|
+
} from "./settings.ts";
|
|
11
|
+
|
|
12
|
+
export function createSettingsExtension(options: { settingsPath?: string } = {}) {
|
|
13
|
+
return (pi: ExtensionAPI): void => {
|
|
14
|
+
const store = new SettingsStore(options.settingsPath ?? join(getAgentDir(), "pi-model-setting.json"));
|
|
15
|
+
const override = new ContextWindowOverride();
|
|
16
|
+
let defaults = emptySettings();
|
|
17
|
+
let session = emptySettings();
|
|
18
|
+
|
|
19
|
+
const reserveTokens = (ctx: ExtensionContext) => {
|
|
20
|
+
const compaction = pi.getSettings().compaction;
|
|
21
|
+
const ordinary = compaction?.reserveTokens;
|
|
22
|
+
const perModel = ctx.model ? compaction?.modelOverrides?.[modelKey(ctx.model)]?.reserveTokens : undefined;
|
|
23
|
+
for (const value of [ordinary, perModel]) {
|
|
24
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
|
|
25
|
+
throw new Error("Compaction reserveTokens must be a non-negative safe integer.");
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return perModel ?? ordinary ?? 16384;
|
|
29
|
+
};
|
|
30
|
+
const reportError = (ctx: ExtensionContext, error: unknown) => {
|
|
31
|
+
ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
|
|
32
|
+
};
|
|
33
|
+
const currentSettings = (ctx: ExtensionContext) => ctx.model
|
|
34
|
+
? effectiveSettings(defaults, session, modelKey(ctx.model)) : {};
|
|
35
|
+
|
|
36
|
+
function sync(ctx: ExtensionContext): number | undefined {
|
|
37
|
+
const model = ctx.model;
|
|
38
|
+
let value = currentSettings(ctx).contextWindow;
|
|
39
|
+
try {
|
|
40
|
+
if (value !== undefined) validateContextWindow(value, reserveTokens(ctx));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
reportError(ctx, error);
|
|
43
|
+
value = undefined;
|
|
44
|
+
}
|
|
45
|
+
return override.apply(model, model && ctx.modelRegistry.find(model.provider, model.id), value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function restore(ctx: ExtensionContext): void {
|
|
49
|
+
override.restore();
|
|
50
|
+
try { defaults = store.read(); }
|
|
51
|
+
catch (error) { defaults = emptySettings(); reportError(ctx, error); }
|
|
52
|
+
session = restoreSettings(ctx.sessionManager.getBranch());
|
|
53
|
+
sync(ctx);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function command(kind: "tier" | "context", args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
57
|
+
try {
|
|
58
|
+
if (!ctx.isIdle()) throw new Error("Wait for the current operation to finish before changing model settings.");
|
|
59
|
+
const model = ctx.model;
|
|
60
|
+
if (!model) throw new Error("No model is selected.");
|
|
61
|
+
if (kind === "tier" && !supportsServiceTier(model)) {
|
|
62
|
+
throw new Error("/service_tier requires provider openai with the Responses or Chat Completions API.");
|
|
63
|
+
}
|
|
64
|
+
if (kind === "context" && model.api === "pi-virtual") {
|
|
65
|
+
throw new Error("Select a physical model to change its context window; virtual models use routed model limits.");
|
|
66
|
+
}
|
|
67
|
+
defaults = store.read();
|
|
68
|
+
const baseline = sync(ctx) ?? model.contextWindow;
|
|
69
|
+
const key = modelKey(model);
|
|
70
|
+
const current = currentSettings(ctx);
|
|
71
|
+
const saved = settingsFor(defaults, key);
|
|
72
|
+
let value: string | number | null = args.trim();
|
|
73
|
+
let save = false;
|
|
74
|
+
if (!value) {
|
|
75
|
+
if (ctx.mode !== "tui") throw new Error("The selector requires TUI mode. Supply a value as a command argument.");
|
|
76
|
+
const tier = current.service_tier ?? "default";
|
|
77
|
+
const window = current.contextWindow ?? null;
|
|
78
|
+
const selection = await showSelector(ctx, kind === "tier" ? {
|
|
79
|
+
title: "Service Tier", model: key, items: tierChoices(tier, saved.service_tier), current: tier,
|
|
80
|
+
} : {
|
|
81
|
+
title: "Context Window", model: key, items: contextChoices(window, baseline, saved.contextWindow),
|
|
82
|
+
current: window === null ? "auto" : window === 512_000 ? "512k" : window === 1_000_000 ? "1m" : "custom",
|
|
83
|
+
customValue: window ?? undefined,
|
|
84
|
+
validateCustom: (value) => validateContextWindow(value, reserveTokens(ctx)),
|
|
85
|
+
});
|
|
86
|
+
if (!selection) return;
|
|
87
|
+
value = selection.value;
|
|
88
|
+
save = selection.save;
|
|
89
|
+
}
|
|
90
|
+
if (!ctx.isIdle() || !ctx.model || modelKey(ctx.model) !== key) {
|
|
91
|
+
throw new Error("The active model or operation changed. Run the command again.");
|
|
92
|
+
}
|
|
93
|
+
let patch: ModelSettings;
|
|
94
|
+
let label: string;
|
|
95
|
+
if (kind === "tier") {
|
|
96
|
+
if (!isServiceTier(value)) throw new Error("Service tier must be default, fast or ultrafast.");
|
|
97
|
+
patch = { service_tier: value };
|
|
98
|
+
label = `service_tier=${value}`;
|
|
99
|
+
} else {
|
|
100
|
+
const window = typeof value === "string" ? parseContextWindow(value) : value;
|
|
101
|
+
validateContextWindow(window, reserveTokens(ctx));
|
|
102
|
+
patch = { contextWindow: window };
|
|
103
|
+
const liveBaseline = sync(ctx) ?? baseline;
|
|
104
|
+
label = window === null ? `contextWindow=Model default (${liveBaseline.toLocaleString("en-US")})`
|
|
105
|
+
: `contextWindow=${window.toLocaleString("en-US")}`;
|
|
106
|
+
}
|
|
107
|
+
// 先保存,再应用;文件写入失败时不把本次选择误报为已生效。
|
|
108
|
+
if (save) defaults = store.save(key, patch);
|
|
109
|
+
const next = updateSettings(session, key, patch);
|
|
110
|
+
pi.appendEntry(ENTRY_TYPE, next);
|
|
111
|
+
session = next;
|
|
112
|
+
sync(ctx);
|
|
113
|
+
ctx.ui.notify(`${save ? "Saved default" : "Applied"}: ${key} · ${label} (${save ? "This model" : "This session"})`, "info");
|
|
114
|
+
} catch (error) {
|
|
115
|
+
reportError(ctx, error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function completions(values: string[], prefix: string) {
|
|
120
|
+
const items = values.filter((value) => value.startsWith(prefix)).map((value) => ({ value, label: value }));
|
|
121
|
+
return items.length ? items : null;
|
|
122
|
+
}
|
|
123
|
+
pi.registerCommand("service_tier", {
|
|
124
|
+
description: "Set the OpenAI service tier",
|
|
125
|
+
getArgumentCompletions: (prefix) => completions(["default", "fast", "ultrafast"], prefix),
|
|
126
|
+
handler: (args, ctx) => command("tier", args, ctx),
|
|
127
|
+
});
|
|
128
|
+
pi.registerCommand("context_window", {
|
|
129
|
+
description: "Set the current model context window",
|
|
130
|
+
getArgumentCompletions: (prefix) => completions(["auto", "512k", "1m"], prefix),
|
|
131
|
+
handler: (args, ctx) => command("context", args, ctx),
|
|
132
|
+
});
|
|
133
|
+
pi.on("session_start", (_event, ctx) => restore(ctx));
|
|
134
|
+
pi.on("session_tree", (_event, ctx) => restore(ctx));
|
|
135
|
+
pi.on("model_select", (_event, ctx) => { sync(ctx); });
|
|
136
|
+
// input 早于发送前的压缩检查;其余边界兼顾扩展发起的请求和模型刷新。
|
|
137
|
+
pi.on("input", (_event, ctx) => { sync(ctx); });
|
|
138
|
+
pi.on("before_agent_start", (_event, ctx) => { sync(ctx); });
|
|
139
|
+
pi.on("turn_start", (_event, ctx) => { sync(ctx); });
|
|
140
|
+
pi.on("before_provider_request", (event, ctx) =>
|
|
141
|
+
applyServiceTier(event.payload, ctx.model, currentSettings(ctx).service_tier ?? "default"));
|
|
142
|
+
pi.on("session_shutdown", () => { override.restore(); });
|
|
143
|
+
};
|
|
144
|
+
}
|
package/src/selector.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { ExtensionCommandContext, Theme } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Input, matchesKey, SelectList, truncateToWidth, type Component, type Focusable, type KeybindingsManager, type SelectItem } from "@earendil-works/pi-tui";
|
|
3
|
+
import { parseContextWindow, SERVICE_TIERS, type ContextWindow, type ServiceTier } from "./settings.ts";
|
|
4
|
+
|
|
5
|
+
export interface Choice extends SelectItem {}
|
|
6
|
+
export interface Selection {
|
|
7
|
+
value: string | ContextWindow;
|
|
8
|
+
save: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface SelectorOptions {
|
|
11
|
+
title: string;
|
|
12
|
+
model: string;
|
|
13
|
+
items: Choice[];
|
|
14
|
+
current: string;
|
|
15
|
+
customValue?: number;
|
|
16
|
+
validateCustom?: (value: ContextWindow) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const tokens = (value: number) => `${value.toLocaleString("en-US")} tokens`;
|
|
20
|
+
|
|
21
|
+
export function tierChoices(current: ServiceTier, saved?: ServiceTier): Choice[] {
|
|
22
|
+
return SERVICE_TIERS.map((value) => ({
|
|
23
|
+
value,
|
|
24
|
+
label: `${current === value ? "✓ " : " "}${value}`,
|
|
25
|
+
description: saved === value ? "Saved default" : undefined,
|
|
26
|
+
}));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function contextChoices(current: ContextWindow, baseline: number, saved?: ContextWindow): Choice[] {
|
|
30
|
+
const custom = current !== null && current !== 512_000 && current !== 1_000_000;
|
|
31
|
+
return [
|
|
32
|
+
{ value: "auto", label: `${current === null ? "✓ " : " "}Model default`, description: tokens(baseline) },
|
|
33
|
+
{ value: "512k", label: `${current === 512_000 ? "✓ " : " "}512k`, description: tokens(512_000) },
|
|
34
|
+
{ value: "1m", label: `${current === 1_000_000 ? "✓ " : " "}1m`, description: tokens(1_000_000) },
|
|
35
|
+
{ value: "custom", label: `${custom ? "✓ " : " "}Custom…`, description: custom ? tokens(current) : undefined },
|
|
36
|
+
].map((item) => {
|
|
37
|
+
const isSaved = saved !== undefined && (item.value === "custom"
|
|
38
|
+
? saved !== null && saved !== 512_000 && saved !== 1_000_000
|
|
39
|
+
: parseContextWindow(item.value) === saved);
|
|
40
|
+
return { ...item, description: [item.description, isSaved ? `Saved default${item.value === "custom" ? ` (${tokens(saved as number)})` : ""}` : undefined].filter(Boolean).join(" · ") };
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class SettingsSelector implements Component, Focusable {
|
|
45
|
+
readonly capturesViewportInput = true;
|
|
46
|
+
private input: Input;
|
|
47
|
+
private list: SelectList;
|
|
48
|
+
private filtered: Choice[];
|
|
49
|
+
private custom = false;
|
|
50
|
+
private saveOnSubmit = false;
|
|
51
|
+
private error?: string;
|
|
52
|
+
|
|
53
|
+
constructor(
|
|
54
|
+
private options: SelectorOptions,
|
|
55
|
+
private theme: Theme,
|
|
56
|
+
private keys: KeybindingsManager,
|
|
57
|
+
private done: (value: Selection | undefined) => void,
|
|
58
|
+
private requestRender: () => void,
|
|
59
|
+
) {
|
|
60
|
+
this.input = this.createInput("Filter options");
|
|
61
|
+
this.filtered = options.items;
|
|
62
|
+
this.list = this.createList();
|
|
63
|
+
this.list.setSelectedIndex(Math.max(0, this.filtered.findIndex((item) => item.value === options.current)));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
get focused(): boolean { return this.input.focused; }
|
|
67
|
+
set focused(value: boolean) { this.input.focused = value; }
|
|
68
|
+
|
|
69
|
+
private createInput(placeholder: string): Input {
|
|
70
|
+
return new Input({ prompt: "› ", placeholder, placeholderStyle: (text) => this.theme.fg("dim", text) });
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private createList(): SelectList {
|
|
74
|
+
return new SelectList(this.filtered, 4, {
|
|
75
|
+
selectedPrefix: (text) => this.theme.fg("accent", text),
|
|
76
|
+
selectedText: (text) => this.theme.fg("accent", text),
|
|
77
|
+
description: (text) => this.theme.fg("muted", text),
|
|
78
|
+
scrollInfo: (text) => this.theme.fg("dim", text),
|
|
79
|
+
noMatch: (text) => this.theme.fg("warning", text),
|
|
80
|
+
}, { minPrimaryColumnWidth: 20, maxPrimaryColumnWidth: 24 });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
private submit(save: boolean): void {
|
|
84
|
+
if (this.custom) {
|
|
85
|
+
try {
|
|
86
|
+
const value = parseContextWindow(this.input.getValue());
|
|
87
|
+
this.options.validateCustom?.(value);
|
|
88
|
+
this.done({ value, save: save || this.saveOnSubmit });
|
|
89
|
+
} catch (error) {
|
|
90
|
+
this.error = error instanceof Error ? error.message : String(error);
|
|
91
|
+
}
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
const item = this.list.getSelectedItem();
|
|
95
|
+
if (!item) return;
|
|
96
|
+
if (item.value !== "custom") {
|
|
97
|
+
this.done({ value: item.value, save });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
this.custom = true;
|
|
101
|
+
this.saveOnSubmit = save;
|
|
102
|
+
const focused = this.focused;
|
|
103
|
+
this.input = this.createInput("512000, 512k, 1m or auto");
|
|
104
|
+
this.input.focused = focused;
|
|
105
|
+
if (this.options.customValue !== undefined) {
|
|
106
|
+
this.input.setValue(String(this.options.customValue));
|
|
107
|
+
this.input.handleInput("\x05");
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
handleInput(data: string): void {
|
|
112
|
+
if (this.keys.matches(data, "tui.select.cancel")) {
|
|
113
|
+
this.done(undefined);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (matchesKey(data, "ctrl+s")) this.submit(true);
|
|
117
|
+
else if (this.keys.matches(data, "tui.select.confirm")) this.submit(false);
|
|
118
|
+
else if (!this.custom && (
|
|
119
|
+
this.keys.matches(data, "tui.select.up") || this.keys.matches(data, "tui.select.down") ||
|
|
120
|
+
this.keys.matches(data, "tui.select.pageUp") || this.keys.matches(data, "tui.select.pageDown")
|
|
121
|
+
)) {
|
|
122
|
+
const index = this.filtered.findIndex((item) => item.value === this.list.getSelectedItem()?.value);
|
|
123
|
+
const direction = this.keys.matches(data, "tui.select.up") || this.keys.matches(data, "tui.select.pageUp") ? -1 : 1;
|
|
124
|
+
if (this.filtered.length) this.list.setSelectedIndex((index + direction + this.filtered.length) % this.filtered.length);
|
|
125
|
+
} else {
|
|
126
|
+
const previous = this.input.getValue();
|
|
127
|
+
this.input.handleInput(data);
|
|
128
|
+
if (previous !== this.input.getValue()) {
|
|
129
|
+
this.error = undefined;
|
|
130
|
+
if (!this.custom) {
|
|
131
|
+
const filter = this.input.getValue().trim().toLowerCase();
|
|
132
|
+
this.filtered = this.options.items.filter((item) =>
|
|
133
|
+
`${item.value} ${item.label} ${item.description ?? ""}`.toLowerCase().includes(filter));
|
|
134
|
+
this.list = this.createList();
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
this.requestRender();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
render(width: number): string[] {
|
|
142
|
+
const keys = (id: Parameters<KeybindingsManager["getKeys"]>[0]) => this.keys.getKeys(id).join("/");
|
|
143
|
+
const hint = [
|
|
144
|
+
!this.custom ? `${keys("tui.select.up")}/${keys("tui.select.down")} Navigate` : undefined,
|
|
145
|
+
`${keys("tui.select.confirm")} ${this.saveOnSubmit ? "Save default" : "Apply"}`,
|
|
146
|
+
"Ctrl+S Save default",
|
|
147
|
+
`${keys("tui.select.cancel")} Cancel`,
|
|
148
|
+
].filter(Boolean).join(" · ");
|
|
149
|
+
return [
|
|
150
|
+
this.theme.fg("accent", this.theme.bold(this.custom ? "Custom Context Window" : this.options.title)),
|
|
151
|
+
this.theme.fg("muted", this.options.model),
|
|
152
|
+
"",
|
|
153
|
+
...this.input.render(Math.max(4, width)),
|
|
154
|
+
"",
|
|
155
|
+
...(!this.custom ? this.filtered.length ? this.list.render(Math.max(4, width)) : [this.theme.fg("warning", "No matching options")] : []),
|
|
156
|
+
...(this.error ? [this.theme.fg("error", this.error)] : []),
|
|
157
|
+
"",
|
|
158
|
+
this.theme.fg("dim", hint),
|
|
159
|
+
].map((line) => truncateToWidth(line, Math.max(1, width)));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
invalidate(): void {
|
|
163
|
+
this.input.invalidate();
|
|
164
|
+
this.list.invalidate();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function showSelector(ctx: ExtensionCommandContext, options: SelectorOptions): Promise<Selection | undefined> {
|
|
169
|
+
return ctx.ui.custom<Selection | undefined>((tui, theme, keys, done) =>
|
|
170
|
+
new SettingsSelector(options, theme, keys, done, () => tui.requestRender()),
|
|
171
|
+
{ blocked: { kind: "question", message: options.title } });
|
|
172
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import { isRecord, type ServiceTier } from "./settings.ts";
|
|
3
|
+
|
|
4
|
+
export function supportsServiceTier(model: Model<string>): boolean {
|
|
5
|
+
return model.provider === "openai" && (model.api === "openai-responses" || model.api === "openai-completions");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function applyServiceTier(payload: unknown, model: Model<string> | undefined, tier: ServiceTier | undefined): unknown {
|
|
9
|
+
if (!model || !tier || !supportsServiceTier(model) || !isRecord(payload)) return undefined;
|
|
10
|
+
// Pi 1.7.0 的请求事件没有物理模型字段;不把当前选择的档位注入不同模型请求。
|
|
11
|
+
if (payload.model !== model.id) return undefined;
|
|
12
|
+
return { ...payload, service_tier: tier };
|
|
13
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
export const SERVICE_TIERS = ["default", "fast", "ultrafast"] as const;
|
|
6
|
+
export type ServiceTier = (typeof SERVICE_TIERS)[number];
|
|
7
|
+
export type ContextWindow = number | null;
|
|
8
|
+
export interface ModelSettings {
|
|
9
|
+
service_tier?: ServiceTier;
|
|
10
|
+
contextWindow?: ContextWindow;
|
|
11
|
+
}
|
|
12
|
+
export interface SettingsData {
|
|
13
|
+
version: 1;
|
|
14
|
+
models: Record<string, ModelSettings>;
|
|
15
|
+
}
|
|
16
|
+
export const ENTRY_TYPE = "pi-model-setting";
|
|
17
|
+
|
|
18
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
19
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isServiceTier(value: unknown): value is ServiceTier {
|
|
23
|
+
return SERVICE_TIERS.some((tier) => tier === value);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function isContextWindow(value: unknown): value is ContextWindow {
|
|
27
|
+
return value === null || (typeof value === "number" && Number.isSafeInteger(value) && value > 0);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function parseContextWindow(input: string): ContextWindow {
|
|
31
|
+
const value = input.trim().toLowerCase();
|
|
32
|
+
if (value === "auto") return null;
|
|
33
|
+
const match = /^(\d+)(?:\.(\d+))?([km])?$/.exec(value);
|
|
34
|
+
if (!match || value.length > 100) {
|
|
35
|
+
throw new Error("Enter a positive token count, such as 512000, 512k or 1m, or auto.");
|
|
36
|
+
}
|
|
37
|
+
const fraction = match[2] ?? "";
|
|
38
|
+
const denominator = 10n ** BigInt(fraction.length);
|
|
39
|
+
const scale = match[3] === "m" ? 1_000_000n : match[3] === "k" ? 1_000n : 1n;
|
|
40
|
+
const numerator = BigInt(match[1] + fraction) * scale;
|
|
41
|
+
const tokens = numerator / denominator;
|
|
42
|
+
if (numerator % denominator !== 0n || tokens <= 0n || tokens > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
43
|
+
throw new Error("Context window must be a positive safe integer number of tokens.");
|
|
44
|
+
}
|
|
45
|
+
return Number(tokens);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function decodeSettings(value: unknown): SettingsData {
|
|
49
|
+
if (!isRecord(value) || value.version !== 1 || !isRecord(value.models)) {
|
|
50
|
+
throw new Error("Invalid settings file: expected version 1 and a models object.");
|
|
51
|
+
}
|
|
52
|
+
for (const [key, settings] of Object.entries(value.models)) {
|
|
53
|
+
if (!isRecord(settings) ||
|
|
54
|
+
(settings.service_tier !== undefined && !isServiceTier(settings.service_tier)) ||
|
|
55
|
+
(settings.contextWindow !== undefined && !isContextWindow(settings.contextWindow))) {
|
|
56
|
+
throw new Error(`Invalid model settings: ${key}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return value as unknown as SettingsData;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function emptySettings(): SettingsData {
|
|
63
|
+
return { version: 1, models: {} };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function settingsFor(data: SettingsData, key: string): ModelSettings {
|
|
67
|
+
return Object.hasOwn(data.models, key) ? data.models[key] : {};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function effectiveSettings(defaults: SettingsData, session: SettingsData, key: string): ModelSettings {
|
|
71
|
+
return { ...settingsFor(defaults, key), ...settingsFor(session, key) };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function updateSettings(data: SettingsData, key: string, patch: ModelSettings): SettingsData {
|
|
75
|
+
return { ...data, models: { ...data.models, [key]: { ...settingsFor(data, key), ...patch } } };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function restoreSettings(entries: readonly { type: string; customType?: string; data?: unknown }[]): SettingsData {
|
|
79
|
+
let settings = emptySettings();
|
|
80
|
+
for (const entry of entries) {
|
|
81
|
+
if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
|
|
82
|
+
try {
|
|
83
|
+
settings = decodeSettings(entry.data);
|
|
84
|
+
} catch {
|
|
85
|
+
// 损坏或未来版本的条目不能覆盖当前分支最后一个有效快照。
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return settings;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export class SettingsStore {
|
|
92
|
+
constructor(readonly path: string) {}
|
|
93
|
+
|
|
94
|
+
read(): SettingsData {
|
|
95
|
+
try {
|
|
96
|
+
return decodeSettings(JSON.parse(readFileSync(this.path, "utf8")));
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return emptySettings();
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
save(key: string, patch: ModelSettings): SettingsData {
|
|
104
|
+
mkdirSync(dirname(this.path), { recursive: true });
|
|
105
|
+
const lockPath = `${this.path}.lock`;
|
|
106
|
+
let lock: number;
|
|
107
|
+
try {
|
|
108
|
+
lock = openSync(lockPath, "wx", 0o600);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if ((error as NodeJS.ErrnoException).code === "EEXIST") {
|
|
111
|
+
throw new Error("Settings are being saved by another process. Try again.");
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
const temporary = `${this.path}.${randomUUID()}.tmp`;
|
|
116
|
+
try {
|
|
117
|
+
// 持锁后重读,合并其他进程写入的不同模型或字段。
|
|
118
|
+
const next = updateSettings(this.read(), key, patch);
|
|
119
|
+
decodeSettings(next);
|
|
120
|
+
writeFileSync(temporary, JSON.stringify(next, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
|
121
|
+
renameSync(temporary, this.path);
|
|
122
|
+
return next;
|
|
123
|
+
} finally {
|
|
124
|
+
try {
|
|
125
|
+
unlinkSync(temporary);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
128
|
+
} finally {
|
|
129
|
+
closeSync(lock);
|
|
130
|
+
unlinkSync(lockPath);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|