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 +9 -6
- package/README.md +9 -6
- package/atomic-write.ts +4 -32
- package/common.ts +0 -17
- package/configuration-lock.ts +136 -0
- package/configuration-persistence.ts +281 -34
- package/file-snapshot.ts +76 -0
- package/header-profile-mutations.ts +29 -7
- package/index.ts +24 -10
- package/local-proxy-service.ts +93 -30
- package/model-mutations.ts +58 -32
- package/models-json-manager.ts +43 -79
- package/models-json-sync.ts +117 -93
- package/openai-responses-payload.ts +1 -1
- package/package.json +11 -5
- package/presets/client-headers.ts +2 -15
- package/presets/providers.ts +27 -4
- package/presets/thinking.ts +5 -13
- package/provider-registrar.ts +9 -2
- package/runtime-base-url.ts +55 -30
- package/sensitive-redaction.ts +46 -0
- package/state-cache.ts +2 -1
- package/state-document.ts +14 -14
- package/state-metadata-store.ts +65 -31
- package/state-store.ts +85 -31
- package/tui/dashboard.ts +19 -6
- package/tui/editor-model.ts +18 -4
- package/tui/editor-provider.ts +11 -10
- package/tui/header-profiles-panel.ts +58 -3
- package/tui/model-list-fetch.ts +136 -114
- package/tui/model-list-validation.ts +79 -0
- package/tui/persistent-menu.ts +96 -14
- package/tui/ui-helpers.ts +146 -96
- package/types.ts +7 -14
- package/models-json-mutations.ts +0 -90
- package/tui/models-json-panel.ts +0 -269
|
@@ -1,72 +1,319 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// 模型管理保存边界:锁内重读最新 models.json/state.json,目标化应用 mutation,
|
|
2
|
+
// 再以可恢复事务写入两个文件。registry 刷新在释放文件锁后执行。
|
|
3
3
|
|
|
4
4
|
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import {
|
|
5
|
+
import { unlink } from "node:fs/promises";
|
|
6
|
+
import { atomicWriteText } from "./atomic-write.ts";
|
|
7
|
+
import { formatUnknownError, isObjectRecord, stringifyJson } from "./common.ts";
|
|
8
|
+
import { withConfigurationLock } from "./configuration-lock.ts";
|
|
9
|
+
import { hashTextContent, readStableTextFileSnapshot } from "./file-snapshot.ts";
|
|
6
10
|
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
11
|
+
MODELS_JSON_PATH,
|
|
12
|
+
markManagedProvidersInDoc,
|
|
13
|
+
readModelsJsonSnapshot,
|
|
14
|
+
renameModelInDoc,
|
|
15
|
+
renameProviderInDoc,
|
|
16
|
+
type ModelsJsonDocument,
|
|
17
|
+
} from "./models-json-manager.ts";
|
|
18
|
+
import {
|
|
19
|
+
buildModelsDocumentWithSynchronizedModel,
|
|
20
|
+
buildModelsDocumentWithoutModel,
|
|
21
|
+
buildSynchronizedModelsDocument,
|
|
10
22
|
} from "./models-json-sync.ts";
|
|
11
23
|
import { invalidateStateCache } from "./state-cache.ts";
|
|
12
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
CONFIGURATION_TRANSACTION_PATH,
|
|
26
|
+
STATE_PATH,
|
|
27
|
+
readMetadataStateSnapshot,
|
|
28
|
+
serializeMetadataState,
|
|
29
|
+
} from "./state-metadata-store.ts";
|
|
30
|
+
import { buildStateDocumentFromSources } from "./state-store.ts";
|
|
13
31
|
import type { StateDocument } from "./types.ts";
|
|
14
32
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
33
|
+
interface PreparedConfigurationChange {
|
|
34
|
+
document: StateDocument;
|
|
35
|
+
changedProviderIds: string[];
|
|
36
|
+
removedProviderIds: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type PrepareConfigurationChange = (latest: StateDocument) => PreparedConfigurationChange;
|
|
40
|
+
|
|
41
|
+
interface FileTransition {
|
|
42
|
+
oldSource: string | null;
|
|
43
|
+
oldHash: string;
|
|
44
|
+
targetSource: string;
|
|
45
|
+
targetHash: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface ConfigurationTransactionJournal {
|
|
49
|
+
version: 1;
|
|
50
|
+
createdAt: string;
|
|
51
|
+
modelsJson: FileTransition;
|
|
52
|
+
metadataState: FileTransition;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const TRANSACTION_PATH = CONFIGURATION_TRANSACTION_PATH;
|
|
56
|
+
|
|
57
|
+
function getErrorCode(error: unknown): string | undefined {
|
|
58
|
+
return error instanceof Error && "code" in error
|
|
59
|
+
? String((error as NodeJS.ErrnoException).code)
|
|
60
|
+
: undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function createTransition(oldSource: string | undefined, targetSource: string): FileTransition {
|
|
64
|
+
return {
|
|
65
|
+
oldSource: oldSource ?? null,
|
|
66
|
+
oldHash: hashTextContent(oldSource),
|
|
67
|
+
targetSource,
|
|
68
|
+
targetHash: hashTextContent(targetSource),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readTransition(raw: unknown, path: string): FileTransition {
|
|
73
|
+
if (!isObjectRecord(raw)) throw new Error(`${path} 必须是对象`);
|
|
74
|
+
const oldSource = raw.oldSource;
|
|
75
|
+
const oldHash = raw.oldHash;
|
|
76
|
+
const targetSource = raw.targetSource;
|
|
77
|
+
const targetHash = raw.targetHash;
|
|
78
|
+
if (oldSource !== null && typeof oldSource !== "string") throw new Error(`${path}.oldSource 必须是字符串或 null`);
|
|
79
|
+
if (typeof oldHash !== "string" || typeof targetSource !== "string" || typeof targetHash !== "string") {
|
|
80
|
+
throw new Error(`${path} 缺少有效内容或签名`);
|
|
81
|
+
}
|
|
82
|
+
const normalizedOldSource = oldSource === null ? undefined : oldSource;
|
|
83
|
+
if (hashTextContent(normalizedOldSource) !== oldHash || hashTextContent(targetSource) !== targetHash) {
|
|
84
|
+
throw new Error(`${path} 内容签名校验失败`);
|
|
85
|
+
}
|
|
86
|
+
return { oldSource, oldHash, targetSource, targetHash };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function parseTransactionJournal(source: string): ConfigurationTransactionJournal {
|
|
90
|
+
const raw = JSON.parse(source);
|
|
91
|
+
if (!isObjectRecord(raw) || raw.version !== 1 || typeof raw.createdAt !== "string") {
|
|
92
|
+
throw new Error("事务意图文件格式无效");
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
version: 1,
|
|
96
|
+
createdAt: raw.createdAt,
|
|
97
|
+
modelsJson: readTransition(raw.modelsJson, "modelsJson"),
|
|
98
|
+
metadataState: readTransition(raw.metadataState, "metadataState"),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function removeTransactionJournal(): Promise<void> {
|
|
103
|
+
try {
|
|
104
|
+
await unlink(TRANSACTION_PATH);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (getErrorCode(error) !== "ENOENT") throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function classifyTransition(path: string, transition: FileTransition): Promise<"old" | "target"> {
|
|
111
|
+
const current = await readStableTextFileSnapshot(path);
|
|
112
|
+
if (current.contentHash === transition.targetHash) return "target";
|
|
113
|
+
if (current.contentHash === transition.oldHash) return "old";
|
|
114
|
+
throw new Error(`${path} 的当前内容既不是事务旧版本,也不是目标版本;已保留 ${TRANSACTION_PATH},不会覆盖外部修改。`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function finishTransition(path: string, transition: FileTransition, status: "old" | "target"): Promise<void> {
|
|
118
|
+
if (status === "old") await atomicWriteText(path, transition.targetSource);
|
|
119
|
+
const completed = await readStableTextFileSnapshot(path);
|
|
120
|
+
if (completed.contentHash !== transition.targetHash) {
|
|
121
|
+
throw new Error(`${path} 写入后内容签名不匹配;已保留 ${TRANSACTION_PATH} 供恢复。`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function recoverPendingConfigurationTransactionInsideLock(): Promise<boolean> {
|
|
126
|
+
const journalSnapshot = await readStableTextFileSnapshot(TRANSACTION_PATH);
|
|
127
|
+
if (journalSnapshot.source === undefined) return false;
|
|
128
|
+
let journal: ConfigurationTransactionJournal;
|
|
129
|
+
try {
|
|
130
|
+
journal = parseTransactionJournal(journalSnapshot.source);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
throw new Error(`无法解析未完成事务 ${TRANSACTION_PATH}:${formatUnknownError(error)}`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 先同时判定两端,任何一端存在外部修改时都不继续写另一端。
|
|
136
|
+
const [modelsStatus, metadataStatus] = await Promise.all([
|
|
137
|
+
classifyTransition(MODELS_JSON_PATH, journal.modelsJson),
|
|
138
|
+
classifyTransition(STATE_PATH, journal.metadataState),
|
|
139
|
+
]);
|
|
140
|
+
await finishTransition(MODELS_JSON_PATH, journal.modelsJson, modelsStatus);
|
|
141
|
+
await finishTransition(STATE_PATH, journal.metadataState, metadataStatus);
|
|
142
|
+
await removeTransactionJournal();
|
|
143
|
+
invalidateStateCache();
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function recoverPendingConfigurationTransaction(): Promise<boolean> {
|
|
148
|
+
return withConfigurationLock(recoverPendingConfigurationTransactionInsideLock);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function assertSnapshotStillCurrent(path: string, expectedHash: string): Promise<void> {
|
|
152
|
+
const current = await readStableTextFileSnapshot(path);
|
|
153
|
+
if (current.contentHash !== expectedHash) {
|
|
154
|
+
throw new Error(`${path} 已被其它进程或编辑器修改;已取消本次保存,请重新打开 /model-manager 后重试。`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function writeConfigurationTransaction(
|
|
159
|
+
modelsSnapshot: Awaited<ReturnType<typeof readModelsJsonSnapshot>>,
|
|
160
|
+
metadataSnapshot: Awaited<ReturnType<typeof readMetadataStateSnapshot>>,
|
|
161
|
+
modelsTarget: string,
|
|
162
|
+
nextState: StateDocument,
|
|
19
163
|
): Promise<void> {
|
|
164
|
+
const metadataTarget = serializeMetadataState(nextState);
|
|
165
|
+
const journal: ConfigurationTransactionJournal = {
|
|
166
|
+
version: 1,
|
|
167
|
+
createdAt: new Date().toISOString(),
|
|
168
|
+
modelsJson: createTransition(modelsSnapshot.source, modelsTarget),
|
|
169
|
+
metadataState: createTransition(metadataSnapshot.source, metadataTarget),
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
await Promise.all([
|
|
173
|
+
assertSnapshotStillCurrent(MODELS_JSON_PATH, modelsSnapshot.contentHash),
|
|
174
|
+
assertSnapshotStillCurrent(STATE_PATH, metadataSnapshot.contentHash),
|
|
175
|
+
]);
|
|
176
|
+
await atomicWriteText(TRANSACTION_PATH, stringifyJson(journal));
|
|
177
|
+
|
|
20
178
|
try {
|
|
21
|
-
await
|
|
22
|
-
|
|
179
|
+
const modelsStatus = await classifyTransition(MODELS_JSON_PATH, journal.modelsJson);
|
|
180
|
+
await finishTransition(MODELS_JSON_PATH, journal.modelsJson, modelsStatus);
|
|
181
|
+
const metadataStatus = await classifyTransition(STATE_PATH, journal.metadataState);
|
|
182
|
+
await finishTransition(STATE_PATH, journal.metadataState, metadataStatus);
|
|
183
|
+
await removeTransactionJournal();
|
|
23
184
|
} catch (error) {
|
|
24
|
-
throw new Error(
|
|
185
|
+
throw new Error(`配置事务未完成:${formatUnknownError(error)}。下次启动或保存会尝试恢复。`);
|
|
25
186
|
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
type ModelsDocumentMutation = (
|
|
190
|
+
source: ModelsJsonDocument,
|
|
191
|
+
change: PreparedConfigurationChange,
|
|
192
|
+
) => ModelsJsonDocument;
|
|
193
|
+
|
|
194
|
+
async function persistConfigurationInsideLock(
|
|
195
|
+
prepare: PrepareConfigurationChange,
|
|
196
|
+
mutateModels: ModelsDocumentMutation,
|
|
197
|
+
): Promise<StateDocument> {
|
|
198
|
+
await recoverPendingConfigurationTransactionInsideLock();
|
|
199
|
+
const [modelsSnapshot, metadataSnapshot] = await Promise.all([
|
|
200
|
+
readModelsJsonSnapshot(),
|
|
201
|
+
readMetadataStateSnapshot(),
|
|
202
|
+
]);
|
|
203
|
+
const latest = await buildStateDocumentFromSources(modelsSnapshot.document, metadataSnapshot);
|
|
204
|
+
const sourceWithOwnershipMarkers = metadataSnapshot.requirePluginManagedProviderMarker
|
|
205
|
+
? modelsSnapshot.document
|
|
206
|
+
: markManagedProvidersInDoc(modelsSnapshot.document, latest.managedProviderIds);
|
|
207
|
+
const sourceWithLegacyProviders = buildSynchronizedModelsDocument(
|
|
208
|
+
latest,
|
|
209
|
+
sourceWithOwnershipMarkers,
|
|
210
|
+
[],
|
|
211
|
+
Object.keys(metadataSnapshot.legacyProviders),
|
|
212
|
+
);
|
|
213
|
+
const change = prepare(latest);
|
|
214
|
+
const nextModels = mutateModels(sourceWithLegacyProviders, change);
|
|
215
|
+
const modelsTarget = nextModels === modelsSnapshot.document && modelsSnapshot.source !== undefined
|
|
216
|
+
? modelsSnapshot.source
|
|
217
|
+
: stringifyJson(nextModels);
|
|
218
|
+
await writeConfigurationTransaction(modelsSnapshot, metadataSnapshot, modelsTarget, change.document);
|
|
219
|
+
return change.document;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function refreshRegistryAfterPersistence(
|
|
223
|
+
ctx: ExtensionCommandContext,
|
|
224
|
+
persist: () => Promise<StateDocument>,
|
|
225
|
+
): Promise<StateDocument> {
|
|
226
|
+
let document: StateDocument;
|
|
26
227
|
try {
|
|
27
|
-
await
|
|
228
|
+
document = await withConfigurationLock(persist);
|
|
28
229
|
invalidateStateCache();
|
|
29
230
|
} catch (error) {
|
|
30
|
-
throw new Error(`models.json
|
|
231
|
+
throw new Error(`models.json/state.json 未完整保存:${formatUnknownError(error)}`);
|
|
31
232
|
}
|
|
32
233
|
try {
|
|
33
234
|
await ctx.modelRegistry.refresh();
|
|
34
235
|
} catch (error) {
|
|
35
236
|
throw new Error(`models.json/state.json 已写入,但当前会话 registry 重载失败:${formatUnknownError(error)}。可执行 /reload 重试。`);
|
|
36
237
|
}
|
|
238
|
+
return document;
|
|
37
239
|
}
|
|
38
240
|
|
|
39
241
|
export async function persistManagedConfiguration(
|
|
40
242
|
ctx: ExtensionCommandContext,
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
)
|
|
44
|
-
|
|
243
|
+
prepare: PrepareConfigurationChange,
|
|
244
|
+
): Promise<StateDocument> {
|
|
245
|
+
return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
|
|
246
|
+
prepare,
|
|
247
|
+
(source, change) => buildSynchronizedModelsDocument(
|
|
248
|
+
change.document,
|
|
249
|
+
source,
|
|
250
|
+
change.removedProviderIds,
|
|
251
|
+
change.changedProviderIds,
|
|
252
|
+
),
|
|
253
|
+
));
|
|
45
254
|
}
|
|
46
255
|
|
|
47
256
|
export async function persistProviderRenameConfiguration(
|
|
48
257
|
ctx: ExtensionCommandContext,
|
|
49
|
-
|
|
258
|
+
prepare: PrepareConfigurationChange,
|
|
50
259
|
oldProviderId: string,
|
|
51
260
|
newProviderId: string,
|
|
52
|
-
): Promise<
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
261
|
+
): Promise<StateDocument> {
|
|
262
|
+
return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
|
|
263
|
+
prepare,
|
|
264
|
+
(source, change) => buildSynchronizedModelsDocument(
|
|
265
|
+
change.document,
|
|
266
|
+
renameProviderInDoc(source, oldProviderId, newProviderId),
|
|
267
|
+
change.removedProviderIds,
|
|
268
|
+
change.changedProviderIds,
|
|
269
|
+
),
|
|
270
|
+
));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export async function persistModelConfiguration(
|
|
274
|
+
ctx: ExtensionCommandContext,
|
|
275
|
+
prepare: PrepareConfigurationChange,
|
|
276
|
+
providerId: string,
|
|
277
|
+
modelId: string,
|
|
278
|
+
): Promise<StateDocument> {
|
|
279
|
+
return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
|
|
280
|
+
prepare,
|
|
281
|
+
(source, change) => buildModelsDocumentWithSynchronizedModel(
|
|
282
|
+
change.document,
|
|
283
|
+
source,
|
|
284
|
+
providerId,
|
|
285
|
+
modelId,
|
|
286
|
+
),
|
|
287
|
+
));
|
|
58
288
|
}
|
|
59
289
|
|
|
60
290
|
export async function persistModelRenameConfiguration(
|
|
61
291
|
ctx: ExtensionCommandContext,
|
|
62
|
-
|
|
292
|
+
prepare: PrepareConfigurationChange,
|
|
63
293
|
providerId: string,
|
|
64
294
|
oldModelId: string,
|
|
65
295
|
newModelId: string,
|
|
66
|
-
): Promise<
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
296
|
+
): Promise<StateDocument> {
|
|
297
|
+
return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
|
|
298
|
+
prepare,
|
|
299
|
+
(source, change) => buildModelsDocumentWithSynchronizedModel(
|
|
300
|
+
change.document,
|
|
301
|
+
renameModelInDoc(source, providerId, oldModelId, newModelId),
|
|
302
|
+
providerId,
|
|
303
|
+
newModelId,
|
|
304
|
+
oldModelId,
|
|
305
|
+
),
|
|
306
|
+
));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function persistModelDeletionConfiguration(
|
|
310
|
+
ctx: ExtensionCommandContext,
|
|
311
|
+
prepare: PrepareConfigurationChange,
|
|
312
|
+
providerId: string,
|
|
313
|
+
modelId: string,
|
|
314
|
+
): Promise<StateDocument> {
|
|
315
|
+
return refreshRegistryAfterPersistence(ctx, () => persistConfigurationInsideLock(
|
|
316
|
+
prepare,
|
|
317
|
+
(source, change) => buildModelsDocumentWithoutModel(change.document, source, providerId, modelId),
|
|
318
|
+
));
|
|
72
319
|
}
|
package/file-snapshot.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 小型配置文件的稳定读取与强内容签名。
|
|
2
|
+
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFile, stat } from "node:fs/promises";
|
|
5
|
+
|
|
6
|
+
export interface FileSignature {
|
|
7
|
+
exists: boolean;
|
|
8
|
+
mtimeMs: number;
|
|
9
|
+
ctimeMs: number;
|
|
10
|
+
size: number;
|
|
11
|
+
ino: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface StableTextFileSnapshot {
|
|
15
|
+
source: string | undefined;
|
|
16
|
+
signature: FileSignature;
|
|
17
|
+
contentHash: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const MISSING_FILE_SIGNATURE: FileSignature = { exists: false, mtimeMs: 0, ctimeMs: 0, size: -1, ino: 0 };
|
|
21
|
+
|
|
22
|
+
function isNotFound(error: unknown): boolean {
|
|
23
|
+
return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function hashTextContent(source: string | undefined): string {
|
|
27
|
+
const hash = createHash("sha256");
|
|
28
|
+
hash.update(source === undefined ? "missing\0" : "present\0");
|
|
29
|
+
if (source !== undefined) hash.update(source);
|
|
30
|
+
return hash.digest("hex");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function readFileSignature(path: string): Promise<FileSignature> {
|
|
34
|
+
try {
|
|
35
|
+
const stats = await stat(path);
|
|
36
|
+
return { exists: true, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs, size: stats.size, ino: stats.ino };
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (isNotFound(error)) return MISSING_FILE_SIGNATURE;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function sameFileSignature(left: FileSignature, right: FileSignature): boolean {
|
|
44
|
+
return left.exists === right.exists
|
|
45
|
+
&& left.mtimeMs === right.mtimeMs
|
|
46
|
+
&& left.ctimeMs === right.ctimeMs
|
|
47
|
+
&& left.size === right.size
|
|
48
|
+
&& left.ino === right.ino;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 文件在读取窗口内变化时重试,避免把旧内容和新签名组合成同一个 snapshot。 */
|
|
52
|
+
export async function readStableTextFileSnapshot(path: string): Promise<StableTextFileSnapshot> {
|
|
53
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
54
|
+
const before = await readFileSignature(path);
|
|
55
|
+
if (!before.exists) {
|
|
56
|
+
const after = await readFileSignature(path);
|
|
57
|
+
if (sameFileSignature(before, after)) {
|
|
58
|
+
return { source: undefined, signature: after, contentHash: hashTextContent(undefined) };
|
|
59
|
+
}
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let source: string;
|
|
64
|
+
try {
|
|
65
|
+
source = await readFile(path, "utf8");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (isNotFound(error)) continue;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
const after = await readFileSignature(path);
|
|
71
|
+
if (sameFileSignature(before, after)) {
|
|
72
|
+
return { source, signature: after, contentHash: hashTextContent(source) };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
throw new Error(`${path} 在读取期间持续变化;请停止其它写入后重试。`);
|
|
76
|
+
}
|
|
@@ -6,7 +6,22 @@ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-c
|
|
|
6
6
|
import { persistManagedConfiguration } from "./configuration-persistence.ts";
|
|
7
7
|
import { registerAllFromState } from "./provider-registrar.ts";
|
|
8
8
|
import { deleteRequestHeaderProfileFromDocument, upsertRequestHeaderProfileInDocument } from "./state-document.ts";
|
|
9
|
-
import type { RequestHeaderProfileDraft, StateDocument } from "./types.ts";
|
|
9
|
+
import type { RequestHeaderProfileDraft, StateDocument, StoredProvider } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
function providerReferencesProfile(provider: StoredProvider, profileId: string): boolean {
|
|
12
|
+
return provider.requestHeaderProfileId === profileId
|
|
13
|
+
|| provider.models.some((model) => model.requestHeaderProfileId === profileId);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function findProfileProviderIds(
|
|
17
|
+
document: StateDocument,
|
|
18
|
+
profileIds: string[],
|
|
19
|
+
): string[] {
|
|
20
|
+
const ids = new Set(profileIds);
|
|
21
|
+
return Object.entries(document.providers)
|
|
22
|
+
.filter(([, provider]) => provider.managed && [...ids].some((profileId) => providerReferencesProfile(provider, profileId)))
|
|
23
|
+
.map(([providerId]) => providerId);
|
|
24
|
+
}
|
|
10
25
|
|
|
11
26
|
function notifyHeaderProfileRefresh(
|
|
12
27
|
ctx: ExtensionCommandContext,
|
|
@@ -23,12 +38,16 @@ function notifyHeaderProfileRefresh(
|
|
|
23
38
|
export async function saveRequestHeaderProfileConfiguration(
|
|
24
39
|
pi: ExtensionAPI,
|
|
25
40
|
ctx: ExtensionCommandContext,
|
|
26
|
-
|
|
41
|
+
_state: StateDocument,
|
|
27
42
|
draft: RequestHeaderProfileDraft,
|
|
28
43
|
oldProfileId: string | undefined,
|
|
29
44
|
): Promise<void> {
|
|
30
|
-
const
|
|
31
|
-
await persistManagedConfiguration(ctx,
|
|
45
|
+
const profileId = draft.profileId.trim();
|
|
46
|
+
const nextState = await persistManagedConfiguration(ctx, (latest) => ({
|
|
47
|
+
document: upsertRequestHeaderProfileInDocument(latest, oldProfileId, draft),
|
|
48
|
+
changedProviderIds: findProfileProviderIds(latest, [profileId, ...(oldProfileId ? [oldProfileId] : [])]),
|
|
49
|
+
removedProviderIds: [],
|
|
50
|
+
}));
|
|
32
51
|
const warnings = await registerAllFromState(pi, nextState);
|
|
33
52
|
notifyHeaderProfileRefresh(ctx, `已保存请求头 ${draft.profileId.trim()}`, warnings);
|
|
34
53
|
}
|
|
@@ -36,11 +55,14 @@ export async function saveRequestHeaderProfileConfiguration(
|
|
|
36
55
|
export async function deleteRequestHeaderProfileConfiguration(
|
|
37
56
|
pi: ExtensionAPI,
|
|
38
57
|
ctx: ExtensionCommandContext,
|
|
39
|
-
|
|
58
|
+
_state: StateDocument,
|
|
40
59
|
profileId: string,
|
|
41
60
|
): Promise<void> {
|
|
42
|
-
const nextState =
|
|
43
|
-
|
|
61
|
+
const nextState = await persistManagedConfiguration(ctx, (latest) => ({
|
|
62
|
+
document: deleteRequestHeaderProfileFromDocument(latest, profileId),
|
|
63
|
+
changedProviderIds: findProfileProviderIds(latest, [profileId]),
|
|
64
|
+
removedProviderIds: [],
|
|
65
|
+
}));
|
|
44
66
|
const warnings = await registerAllFromState(pi, nextState);
|
|
45
67
|
notifyHeaderProfileRefresh(ctx, `已删除请求头 ${profileId}`, warnings);
|
|
46
68
|
}
|
package/index.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|
|
11
11
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
import { formatUnknownError } from "./common.ts";
|
|
13
|
+
import { recoverPendingConfigurationTransaction } from "./configuration-persistence.ts";
|
|
13
14
|
import { resetClaudeCodeMetadataSession } from "./claude-code-compat.ts";
|
|
14
15
|
import { closeLocalProxyServer } from "./local-proxy-service.ts";
|
|
15
16
|
import { registerAllFromState, registerCatalogFromState } from "./provider-registrar.ts";
|
|
@@ -24,17 +25,25 @@ interface StartupSummary {
|
|
|
24
25
|
export default async function modelManagerExtension(pi: ExtensionAPI): Promise<void> {
|
|
25
26
|
const summary: StartupSummary = { startupErrors: [] };
|
|
26
27
|
|
|
27
|
-
|
|
28
|
+
let configurationBlocked = false;
|
|
28
29
|
try {
|
|
29
|
-
|
|
30
|
-
summary.startupErrors.push(`读取 models.json/state.json 失败:${formatUnknownError(error)}(本次启动仅使用内存空配置,不覆盖原文件)`);
|
|
31
|
-
return createEmptyState();
|
|
32
|
-
});
|
|
33
|
-
for (const warning of await registerCatalogFromState(pi, stateForStartup)) {
|
|
34
|
-
summary.startupErrors.push(`注册模型目录失败:${warning}`);
|
|
35
|
-
}
|
|
30
|
+
await recoverPendingConfigurationTransaction();
|
|
36
31
|
} catch (error) {
|
|
37
|
-
|
|
32
|
+
configurationBlocked = true;
|
|
33
|
+
summary.startupErrors.push(`恢复未完成配置事务失败:${formatUnknownError(error)}(为避免读取半完成配置,本次暂不注册模型)`);
|
|
34
|
+
}
|
|
35
|
+
if (!configurationBlocked) {
|
|
36
|
+
try {
|
|
37
|
+
const stateForStartup = await readState().catch((error) => {
|
|
38
|
+
summary.startupErrors.push(`读取 models.json/state.json 失败:${formatUnknownError(error)}(本次启动仅使用内存空配置,不覆盖原文件)`);
|
|
39
|
+
return createEmptyState();
|
|
40
|
+
});
|
|
41
|
+
for (const warning of await registerCatalogFromState(pi, stateForStartup)) {
|
|
42
|
+
summary.startupErrors.push(`注册模型目录失败:${warning}`);
|
|
43
|
+
}
|
|
44
|
+
} catch (error) {
|
|
45
|
+
summary.startupErrors.push(`读取/注册模型配置失败:${formatUnknownError(error)}`);
|
|
46
|
+
}
|
|
38
47
|
}
|
|
39
48
|
|
|
40
49
|
// ---- 2. session_start 激活 transport 并汇报 ----
|
|
@@ -44,12 +53,17 @@ export default async function modelManagerExtension(pi: ExtensionAPI): Promise<v
|
|
|
44
53
|
resetClaudeCodeMetadataSession();
|
|
45
54
|
const transportErrors: string[] = [];
|
|
46
55
|
try {
|
|
56
|
+
if (configurationBlocked) {
|
|
57
|
+
await recoverPendingConfigurationTransaction();
|
|
58
|
+
configurationBlocked = false;
|
|
59
|
+
}
|
|
47
60
|
const currentState = await readState();
|
|
48
61
|
for (const warning of await registerAllFromState(pi, currentState)) {
|
|
49
62
|
transportErrors.push(`激活模型接入失败:${warning}`);
|
|
50
63
|
}
|
|
51
64
|
} catch (error) {
|
|
52
|
-
|
|
65
|
+
configurationBlocked = true;
|
|
66
|
+
transportErrors.push(`恢复、读取或激活模型配置失败:${formatUnknownError(error)}`);
|
|
53
67
|
}
|
|
54
68
|
|
|
55
69
|
if (event.reason === "startup" && !notified) {
|