pi-model-manager 0.3.4 → 0.3.6
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 +28 -9
- package/README.md +28 -9
- package/atomic-write.ts +2 -2
- package/configuration-persistence.ts +32 -1
- package/i18n.ts +25 -1
- package/index.ts +9 -2
- package/local-proxy-service.ts +3 -2
- package/models-json-sync.ts +30 -3
- package/openai-responses-payload.ts +6 -8
- package/package.json +4 -2
- package/presets/builtin-client-headers.ts +3 -3
- package/presets/client-headers.ts +10 -13
- package/presets/providers.ts +1 -1
- package/provider-registrar.ts +36 -117
- package/provider-transport.ts +178 -0
- package/request-pipeline.ts +22 -17
- package/runtime-base-url.ts +45 -65
- package/state-document.ts +32 -10
- package/state-metadata-store.ts +43 -7
- package/state-store.ts +24 -4
- package/tui/editor-provider.ts +57 -1
- package/tui/model-list-fetch.ts +22 -70
- package/types.ts +5 -0
package/provider-registrar.ts
CHANGED
|
@@ -1,99 +1,50 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
// StoredProvider → pi 的 ProviderConfig → pi.registerProvider 的统一桥梁。
|
|
4
|
-
//
|
|
5
|
-
// 设计要点:
|
|
6
|
-
// - factory 阶段只注册无需本地 server 的 catalog 配置;session_start 再激活代理 transport。
|
|
7
|
-
// - reconcileProvider 是保存后的完整 runtime 同步入口,统一处理 register/unregister 与回滚。
|
|
8
|
-
// - getClientHeadersForProfile 在这里调,把客户端请求头 profile 翻译成模型级 headers。
|
|
1
|
+
// 将配置交给 Pi 构造原生 Provider,插件仅包装其请求传输。
|
|
9
2
|
|
|
10
|
-
import type
|
|
3
|
+
import { ModelRuntime, type ExtensionAPI, type ProviderConfig } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { Provider } from "@earendil-works/pi-ai";
|
|
11
5
|
import { isBuiltinProviderId } from "./builtin-model-catalog.ts";
|
|
12
6
|
import { mergeCompatSettings } from "./compat-settings.ts";
|
|
13
7
|
import { formatUnknownError } from "./common.ts";
|
|
14
8
|
import { t } from "./i18n.ts";
|
|
15
|
-
import {
|
|
16
|
-
getLocalProxyBaseUrl,
|
|
17
|
-
getProviderHttpProxyUrl,
|
|
18
|
-
isProviderHttpProxyEnabled,
|
|
19
|
-
removeProviderLocalProxyRoutes,
|
|
20
|
-
restoreProviderLocalProxyRoutes,
|
|
21
|
-
snapshotProviderLocalProxyRoutes,
|
|
22
|
-
type ProviderProxyRoute,
|
|
23
|
-
} from "./local-proxy-service.ts";
|
|
9
|
+
import { removeProviderLocalProxyRoutes } from "./local-proxy-service.ts";
|
|
24
10
|
import { getClientHeadersForProfile, mergeModelRequestHeaders } from "./presets/client-headers.ts";
|
|
11
|
+
import { createProviderTransport } from "./provider-transport.ts";
|
|
25
12
|
import { resolveRuntimeBaseUrl } from "./runtime-base-url.ts";
|
|
26
13
|
import type { ApiKind, BuiltInClientHeaderProfileId, StateDocument, StoredClientHeaderCapture, StoredModel, StoredProvider, StoredRequestHeaderProfile } from "./types.ts";
|
|
27
14
|
|
|
28
|
-
// pi 的 ProviderConfig 类型从 d.ts 拿;这里用结构兼容 + as any 避免拉太多内部类型。
|
|
29
|
-
// 关键字段:name / baseUrl / apiKey / api / authHeader / models
|
|
30
|
-
type ProviderConfig = Parameters<ExtensionAPI["registerProvider"]>[1];
|
|
31
15
|
type ProviderModelConfig = NonNullable<ProviderConfig["models"]>[number];
|
|
32
|
-
|
|
33
|
-
const
|
|
16
|
+
const REGISTERED_PROVIDER_CONFIGS = new Map<string, Provider>();
|
|
17
|
+
const emptyCredentialStore = {
|
|
18
|
+
async read() { return undefined; },
|
|
19
|
+
async list() { return []; },
|
|
20
|
+
async modify() { return undefined; },
|
|
21
|
+
async delete() {},
|
|
22
|
+
};
|
|
34
23
|
|
|
35
24
|
function buildProviderConfig(
|
|
36
25
|
provider: StoredProvider,
|
|
37
26
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile> = {},
|
|
38
27
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>> = {},
|
|
39
|
-
): ProviderConfig {
|
|
40
|
-
const runtimeBaseUrl = resolveRuntimeBaseUrl(provider.api, provider.baseUrl);
|
|
41
|
-
return buildProviderConfigWithBaseUrl(provider, runtimeBaseUrl, requestHeaderProfiles, clientHeaderCaptures);
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function buildProviderConfigWithBaseUrl(
|
|
45
|
-
provider: StoredProvider,
|
|
46
|
-
runtimeBaseUrl: string,
|
|
47
|
-
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
48
|
-
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
49
|
-
modelRuntimeBaseUrls: ReadonlyMap<string, string> = new Map(),
|
|
50
28
|
): ProviderConfig {
|
|
51
29
|
const apiKey = provider.apiKey?.trim();
|
|
52
30
|
return {
|
|
53
31
|
name: provider.name,
|
|
54
|
-
baseUrl:
|
|
32
|
+
baseUrl: resolveRuntimeBaseUrl(provider.api, provider.baseUrl),
|
|
55
33
|
...(apiKey ? { apiKey } : {}),
|
|
56
34
|
api: provider.api,
|
|
57
|
-
headers: provider.headers,
|
|
35
|
+
headers: mergeModelRequestHeaders(undefined, provider.headers),
|
|
58
36
|
authHeader: provider.authHeader,
|
|
59
|
-
models: provider.models.map((model) => buildModelConfig(
|
|
60
|
-
provider,
|
|
61
|
-
model,
|
|
62
|
-
requestHeaderProfiles,
|
|
63
|
-
clientHeaderCaptures,
|
|
64
|
-
modelRuntimeBaseUrls.get(model.id),
|
|
65
|
-
)),
|
|
37
|
+
models: provider.models.map((model) => buildModelConfig(provider, model, requestHeaderProfiles, clientHeaderCaptures)),
|
|
66
38
|
};
|
|
67
39
|
}
|
|
68
40
|
|
|
69
|
-
async function
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
)
|
|
75
|
-
|
|
76
|
-
removeProviderLocalProxyRoutes(providerId);
|
|
77
|
-
if (!isProviderHttpProxyEnabled(provider)) {
|
|
78
|
-
return buildProviderConfigWithBaseUrl(provider, upstreamRuntimeBaseUrl, requestHeaderProfiles, clientHeaderCaptures);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
const proxyUrl = getProviderHttpProxyUrl(provider);
|
|
82
|
-
const runtimeBaseUrl = await getLocalProxyBaseUrl(providerId, upstreamRuntimeBaseUrl, proxyUrl);
|
|
83
|
-
const modelRuntimeBaseUrls = new Map<string, string>();
|
|
84
|
-
for (const model of provider.models) {
|
|
85
|
-
const upstreamModelBaseUrl = resolveModelRuntimeBaseUrl(provider, model);
|
|
86
|
-
if (!upstreamModelBaseUrl) continue;
|
|
87
|
-
const routeId = `${providerId}/model/${model.id}`;
|
|
88
|
-
modelRuntimeBaseUrls.set(model.id, await getLocalProxyBaseUrl(routeId, upstreamModelBaseUrl, proxyUrl));
|
|
89
|
-
}
|
|
90
|
-
return buildProviderConfigWithBaseUrl(
|
|
91
|
-
provider,
|
|
92
|
-
runtimeBaseUrl,
|
|
93
|
-
requestHeaderProfiles,
|
|
94
|
-
clientHeaderCaptures,
|
|
95
|
-
modelRuntimeBaseUrls,
|
|
96
|
-
);
|
|
41
|
+
async function buildNativeProvider(providerId: string, provider: StoredProvider, config: ProviderConfig): Promise<Provider> {
|
|
42
|
+
// [喵喵喵]: 复用 Pi 的认证解析与多协议分派;临时 runtime 不读取用户认证或模型文件,也不刷新网络目录。
|
|
43
|
+
const runtime = await ModelRuntime.create({ credentials: emptyCredentialStore, modelsPath: null, allowModelNetwork: false, refreshOnCreate: false });
|
|
44
|
+
runtime.registerProvider(providerId, config);
|
|
45
|
+
const native = runtime.getProvider(providerId);
|
|
46
|
+
if (!native) throw new Error(t("无法构建接入:{providerId}", { providerId }));
|
|
47
|
+
return createProviderTransport(runtime, native, provider);
|
|
97
48
|
}
|
|
98
49
|
|
|
99
50
|
function asManagedApi(value: string | undefined, fallback: ApiKind): ApiKind {
|
|
@@ -126,7 +77,10 @@ export function buildModelRequestHeaders(
|
|
|
126
77
|
clientHeaderCaptures,
|
|
127
78
|
effectiveCompat,
|
|
128
79
|
);
|
|
129
|
-
|
|
80
|
+
const explicitHeaders = mergeModelRequestHeaders(provider.headers, model.headers);
|
|
81
|
+
return provider.clientHeaderProfile === "custom"
|
|
82
|
+
? mergeModelRequestHeaders(explicitHeaders, profileHeaders)
|
|
83
|
+
: mergeModelRequestHeaders(profileHeaders, explicitHeaders);
|
|
130
84
|
}
|
|
131
85
|
|
|
132
86
|
function buildModelConfig(
|
|
@@ -134,13 +88,12 @@ function buildModelConfig(
|
|
|
134
88
|
model: StoredModel,
|
|
135
89
|
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
136
90
|
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
137
|
-
runtimeBaseUrl?: string,
|
|
138
91
|
): ProviderModelConfig {
|
|
139
92
|
return {
|
|
140
93
|
id: model.id,
|
|
141
94
|
name: model.name ?? model.id,
|
|
142
95
|
api: model.api as ProviderModelConfig["api"],
|
|
143
|
-
baseUrl:
|
|
96
|
+
baseUrl: resolveModelRuntimeBaseUrl(provider, model),
|
|
144
97
|
reasoning: model.reasoning,
|
|
145
98
|
thinkingLevelMap: model.thinkingLevelMap,
|
|
146
99
|
input: model.input,
|
|
@@ -175,21 +128,19 @@ async function canRegisterManagedProvider(providerId: string, provider: StoredPr
|
|
|
175
128
|
function replaceManagedProviderConfig(
|
|
176
129
|
pi: ExtensionAPI,
|
|
177
130
|
providerId: string,
|
|
178
|
-
nextConfig:
|
|
179
|
-
previousRoutes: ReadonlyMap<string, ProviderProxyRoute>,
|
|
131
|
+
nextConfig: Provider,
|
|
180
132
|
): void {
|
|
181
133
|
const previousConfig = REGISTERED_PROVIDER_CONFIGS.get(providerId);
|
|
182
134
|
try {
|
|
183
135
|
if (previousConfig) pi.unregisterProvider(providerId);
|
|
184
|
-
pi.registerProvider(
|
|
136
|
+
pi.registerProvider(nextConfig);
|
|
185
137
|
REGISTERED_PROVIDER_CONFIGS.set(providerId, nextConfig);
|
|
186
138
|
} catch (error) {
|
|
187
|
-
restoreProviderLocalProxyRoutes(providerId, previousRoutes);
|
|
188
139
|
let rollbackError: unknown;
|
|
189
140
|
try {
|
|
190
141
|
if (previousConfig) {
|
|
191
142
|
pi.unregisterProvider(providerId);
|
|
192
|
-
pi.registerProvider(
|
|
143
|
+
pi.registerProvider(previousConfig);
|
|
193
144
|
REGISTERED_PROVIDER_CONFIGS.set(providerId, previousConfig);
|
|
194
145
|
} else {
|
|
195
146
|
REGISTERED_PROVIDER_CONFIGS.delete(providerId);
|
|
@@ -220,46 +171,14 @@ export async function reconcileProvider(
|
|
|
220
171
|
return;
|
|
221
172
|
}
|
|
222
173
|
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
nextConfig = await buildRuntimeProviderConfig(providerId, provider, requestHeaderProfiles, clientHeaderCaptures);
|
|
227
|
-
} catch (error) {
|
|
228
|
-
restoreProviderLocalProxyRoutes(providerId, previousRoutes);
|
|
229
|
-
throw error;
|
|
230
|
-
}
|
|
231
|
-
replaceManagedProviderConfig(pi, providerId, nextConfig, previousRoutes);
|
|
174
|
+
const config = buildProviderConfig(provider, requestHeaderProfiles, clientHeaderCaptures);
|
|
175
|
+
const native = await buildNativeProvider(providerId, provider, config);
|
|
176
|
+
replaceManagedProviderConfig(pi, providerId, native);
|
|
232
177
|
}
|
|
233
178
|
|
|
234
|
-
async function reconcileProviderCatalog(
|
|
235
|
-
pi: ExtensionAPI,
|
|
236
|
-
providerId: string,
|
|
237
|
-
provider: StoredProvider,
|
|
238
|
-
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
239
|
-
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
240
|
-
): Promise<void> {
|
|
241
|
-
if (!(await canRegisterManagedProvider(providerId, provider))) {
|
|
242
|
-
unregisterManagedProvider(pi, providerId);
|
|
243
|
-
return;
|
|
244
|
-
}
|
|
245
|
-
const previousRoutes = snapshotProviderLocalProxyRoutes(providerId);
|
|
246
|
-
removeProviderLocalProxyRoutes(providerId);
|
|
247
|
-
const nextConfig = buildProviderConfig(provider, requestHeaderProfiles, clientHeaderCaptures);
|
|
248
|
-
replaceManagedProviderConfig(pi, providerId, nextConfig, previousRoutes);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
type StateProviderReconciler = (
|
|
252
|
-
pi: ExtensionAPI,
|
|
253
|
-
providerId: string,
|
|
254
|
-
provider: StoredProvider,
|
|
255
|
-
requestHeaderProfiles: Record<string, StoredRequestHeaderProfile>,
|
|
256
|
-
clientHeaderCaptures: Partial<Record<BuiltInClientHeaderProfileId, StoredClientHeaderCapture>>,
|
|
257
|
-
) => Promise<void>;
|
|
258
|
-
|
|
259
179
|
async function reconcileAllFromState(
|
|
260
180
|
pi: ExtensionAPI,
|
|
261
181
|
document: StateDocument,
|
|
262
|
-
reconcile: StateProviderReconciler,
|
|
263
182
|
): Promise<string[]> {
|
|
264
183
|
const warnings: string[] = [];
|
|
265
184
|
const activeProviderIds = new Set(
|
|
@@ -270,7 +189,7 @@ async function reconcileAllFromState(
|
|
|
270
189
|
}
|
|
271
190
|
for (const [providerId, provider] of Object.entries(document.providers)) {
|
|
272
191
|
try {
|
|
273
|
-
await
|
|
192
|
+
await reconcileProvider(pi, providerId, provider, document.requestHeaderProfiles, document.clientHeaderCaptures);
|
|
274
193
|
} catch (error) {
|
|
275
194
|
warnings.push(`${providerId}: ${formatUnknownError(error)}`);
|
|
276
195
|
}
|
|
@@ -280,10 +199,10 @@ async function reconcileAllFromState(
|
|
|
280
199
|
|
|
281
200
|
/** factory 阶段仅注册模型 catalog,不启动长生命周期本地代理。 */
|
|
282
201
|
export async function registerCatalogFromState(pi: ExtensionAPI, document: StateDocument): Promise<string[]> {
|
|
283
|
-
return reconcileAllFromState(pi, document
|
|
202
|
+
return reconcileAllFromState(pi, document);
|
|
284
203
|
}
|
|
285
204
|
|
|
286
205
|
/** session_start 激活当前 state 的完整 provider transport。 */
|
|
287
206
|
export async function registerAllFromState(pi: ExtensionAPI, document: StateDocument): Promise<string[]> {
|
|
288
|
-
return reconcileAllFromState(pi, document
|
|
207
|
+
return reconcileAllFromState(pi, document);
|
|
289
208
|
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// 在 Pi 已构造请求后选择传输路线;协议判断始终使用真实网关地址。
|
|
2
|
+
|
|
3
|
+
import { lazyStream, type Provider } from "@earendil-works/pi-ai";
|
|
4
|
+
import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { mergeModelRequestHeaders } from "./presets/client-headers.ts";
|
|
6
|
+
import { t } from "./i18n.ts";
|
|
7
|
+
import { getProviderHttpProxyUrl, openTemporaryLocalProxyRoute } from "./local-proxy-service.ts";
|
|
8
|
+
import { appendUrlPath, resolveRuntimeBaseUrl, validateRequestBaseUrl } from "./runtime-base-url.ts";
|
|
9
|
+
import type { ApiKind, StoredProvider } from "./types.ts";
|
|
10
|
+
|
|
11
|
+
const RESPONSES_TERMINAL_EVENTS = new Set([
|
|
12
|
+
"response.completed",
|
|
13
|
+
"response.incomplete",
|
|
14
|
+
"response.failed",
|
|
15
|
+
"error",
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
function findSseFrameBoundary(buffer: Uint8Array): number {
|
|
19
|
+
for (let index = 0; index < buffer.length; index += 1) {
|
|
20
|
+
if (buffer[index] === 10 && buffer[index + 1] === 10) return index + 2;
|
|
21
|
+
if (buffer[index] === 13 && buffer[index + 1] === 13) return index + 2;
|
|
22
|
+
if (buffer[index] === 13 && buffer[index + 1] === 10 && buffer[index + 2] === 13 && buffer[index + 3] === 10) return index + 4;
|
|
23
|
+
}
|
|
24
|
+
return -1;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isResponsesTerminalFrame(frame: Uint8Array): boolean {
|
|
28
|
+
const text = new TextDecoder().decode(frame);
|
|
29
|
+
let eventType: string | undefined;
|
|
30
|
+
const dataLines: string[] = [];
|
|
31
|
+
for (const line of text.split(/\r?\n|\r/)) {
|
|
32
|
+
if (line.startsWith("event:")) eventType = line.slice("event:".length).trim();
|
|
33
|
+
if (line.startsWith("data:")) dataLines.push(line.slice("data:".length).trimStart());
|
|
34
|
+
}
|
|
35
|
+
if (eventType && RESPONSES_TERMINAL_EVENTS.has(eventType)) return true;
|
|
36
|
+
const data = dataLines.join("\n").trim();
|
|
37
|
+
if (!data || data === "[DONE]") return false;
|
|
38
|
+
try {
|
|
39
|
+
const parsed = JSON.parse(data) as { type?: unknown };
|
|
40
|
+
return typeof parsed.type === "string" && RESPONSES_TERMINAL_EVENTS.has(parsed.type);
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function appendBytes(left: Uint8Array, right: Uint8Array): Uint8Array {
|
|
47
|
+
const combined = new Uint8Array(left.length + right.length);
|
|
48
|
+
combined.set(left);
|
|
49
|
+
combined.set(right, left.length);
|
|
50
|
+
return combined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function wrapResponsesTerminalStream(response: Response): Response {
|
|
54
|
+
if (!response.body || !response.ok) return response;
|
|
55
|
+
const reader = response.body.getReader();
|
|
56
|
+
let buffer = new Uint8Array();
|
|
57
|
+
let terminal = false;
|
|
58
|
+
const body = new ReadableStream<Uint8Array>({
|
|
59
|
+
async pull(controller) {
|
|
60
|
+
while (!terminal) {
|
|
61
|
+
const boundary = findSseFrameBoundary(buffer);
|
|
62
|
+
if (boundary >= 0) {
|
|
63
|
+
const frame = buffer.slice(0, boundary);
|
|
64
|
+
buffer = buffer.slice(boundary);
|
|
65
|
+
terminal = isResponsesTerminalFrame(frame);
|
|
66
|
+
controller.enqueue(frame);
|
|
67
|
+
if (terminal) {
|
|
68
|
+
controller.close();
|
|
69
|
+
await reader.cancel().catch(() => {});
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const next = await reader.read();
|
|
74
|
+
if (next.done) {
|
|
75
|
+
if (buffer.length > 0) controller.enqueue(buffer);
|
|
76
|
+
controller.close();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
buffer = appendBytes(buffer, next.value);
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
cancel(reason) {
|
|
83
|
+
return reader.cancel(reason);
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
return new Response(body, {
|
|
87
|
+
status: response.status,
|
|
88
|
+
statusText: response.statusText,
|
|
89
|
+
headers: response.headers,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function createProviderTransport(runtime: ModelRuntime, native: Provider, provider: StoredProvider): Provider {
|
|
94
|
+
const endpoints = new Map(provider.models.map((model) => {
|
|
95
|
+
const api = model.api ?? provider.api;
|
|
96
|
+
const baseUrl = resolveRuntimeBaseUrl(api as ApiKind, model.baseUrl ?? provider.baseUrl);
|
|
97
|
+
return [model.id, { api, baseUrl }];
|
|
98
|
+
}));
|
|
99
|
+
const proxyUrl = provider.httpProxyEnabled ? getProviderHttpProxyUrl(provider) : undefined;
|
|
100
|
+
|
|
101
|
+
const wrap = (stream: Provider["streamSimple"]): Provider["streamSimple"] => (model, context, options) => lazyStream(model, async () => {
|
|
102
|
+
const endpoint = endpoints.get(model.id);
|
|
103
|
+
if (!endpoint || endpoint.api !== model.api) throw new Error(t("请求模型不属于当前接入配置:{modelId}", { modelId: model.id }));
|
|
104
|
+
validateRequestBaseUrl(endpoint.baseUrl);
|
|
105
|
+
// [喵喵喵]: Pi 的模型级请求头解析属于 ModelRuntime,不包含在 getProvider() 返回值里;使用已解析的 key 只补齐本接入的显式配置。
|
|
106
|
+
const resolved = await runtime.getAuth(model, { apiKey: options?.apiKey, env: options?.env, signal: options?.signal });
|
|
107
|
+
if (!resolved) throw new Error(t("请求认证解析失败"));
|
|
108
|
+
options = { ...options, headers: mergeModelRequestHeaders(options?.headers, resolved.auth.headers) };
|
|
109
|
+
// [喵喵喵]: models.json 会叠加在动态 provider 之上;还原用户侧 API 根地址,不能让原生持久化形式参与路径拼接。
|
|
110
|
+
const upstreamModel = { ...model, baseUrl: endpoint.baseUrl };
|
|
111
|
+
if (model.api === "google-generative-ai") {
|
|
112
|
+
// [喵喵喵]: Google 适配器先按精确键拼入默认 User-Agent,再构造 Headers;使用该拼写才能覆盖而不是合并成两个值。
|
|
113
|
+
if (options.headers?.["user-agent"] !== undefined) {
|
|
114
|
+
const { "user-agent": userAgent, ...headers } = options.headers;
|
|
115
|
+
options = { ...options, headers: { ...headers, "User-Agent": userAgent } };
|
|
116
|
+
}
|
|
117
|
+
if (!proxyUrl) return stream(upstreamModel, context, options);
|
|
118
|
+
const route = await openTemporaryLocalProxyRoute(native.id, endpoint.baseUrl, proxyUrl);
|
|
119
|
+
try {
|
|
120
|
+
// [喵喵喵]: Google 不支持请求级 fetch,只有发送副本使用本地地址;其模型能力判断基于模型 ID。
|
|
121
|
+
const result = stream({ ...upstreamModel, baseUrl: route.url }, context, options);
|
|
122
|
+
void result.result().then(() => route.close(), () => route.close());
|
|
123
|
+
return result;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
route.close();
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (model.api !== "openai-completions" && model.api !== "openai-responses" && model.api !== "anthropic-messages") {
|
|
130
|
+
if (proxyUrl) throw new Error(t("该协议尚不支持接入级代理:{api}", { api: model.api }));
|
|
131
|
+
return stream(upstreamModel, context, options);
|
|
132
|
+
}
|
|
133
|
+
if (!proxyUrl
|
|
134
|
+
&& model.api !== "anthropic-messages"
|
|
135
|
+
&& !(model.api === "openai-responses" && provider.openAIResponsesStreamCompletionMode === "terminal-event")) {
|
|
136
|
+
return stream(upstreamModel, context, options);
|
|
137
|
+
}
|
|
138
|
+
const fetchImpl = options?.fetch ?? globalThis.fetch;
|
|
139
|
+
const transportFetch: typeof fetch = async (input, init) => {
|
|
140
|
+
let request = new Request(input, init);
|
|
141
|
+
if (model.api === "anthropic-messages") {
|
|
142
|
+
const url = new URL(request.url);
|
|
143
|
+
const sdkEndpoint = new URL(appendUrlPath(endpoint.baseUrl, "v1", "messages"));
|
|
144
|
+
if (url.origin !== sdkEndpoint.origin || url.pathname !== sdkEndpoint.pathname) {
|
|
145
|
+
throw new Error(t("Anthropic 请求路径与当前适配契约不符"));
|
|
146
|
+
}
|
|
147
|
+
// [喵喵喵]: 仅替换 SDK 明确追加的端点路径,保留 beta 等请求参数,不对 URL 做全局 /v1 替换。
|
|
148
|
+
url.pathname = new URL(appendUrlPath(endpoint.baseUrl, "messages")).pathname;
|
|
149
|
+
request = new Request(url, request);
|
|
150
|
+
}
|
|
151
|
+
let response: Response;
|
|
152
|
+
if (!proxyUrl) {
|
|
153
|
+
response = await fetchImpl(request);
|
|
154
|
+
} else {
|
|
155
|
+
const route = await openTemporaryLocalProxyRoute(native.id, request.url, proxyUrl);
|
|
156
|
+
try {
|
|
157
|
+
response = await fetchImpl(new Request(route.url, request));
|
|
158
|
+
} finally {
|
|
159
|
+
// [喵喵喵]: 收到响应头时转发端已经取得路由;删除查找项不会中断已建立的 SSE 流。
|
|
160
|
+
route.close();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (model.api === "openai-responses"
|
|
164
|
+
&& provider.openAIResponsesStreamCompletionMode === "terminal-event") {
|
|
165
|
+
// [喵喵喵]: 某些中转已发出正式终态事件却保持连接;完整转交该 frame 后即可按协议结束本地流。
|
|
166
|
+
return wrapResponsesTerminalStream(response);
|
|
167
|
+
}
|
|
168
|
+
return response;
|
|
169
|
+
};
|
|
170
|
+
return stream(upstreamModel, context, { ...options, fetch: transportFetch });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
...native,
|
|
175
|
+
stream: wrap(native.stream.bind(native)) as Provider["stream"],
|
|
176
|
+
streamSimple: wrap(native.streamSimple.bind(native)),
|
|
177
|
+
};
|
|
178
|
+
}
|
package/request-pipeline.ts
CHANGED
|
@@ -12,45 +12,37 @@ import { injectOpenAIServiceTier } from "./openai-service-tier.ts";
|
|
|
12
12
|
import { readCachedState } from "./state-cache.ts";
|
|
13
13
|
import type { StateDocument } from "./types.ts";
|
|
14
14
|
|
|
15
|
-
type StateLoader = () => Promise<StateDocument>;
|
|
16
15
|
|
|
17
16
|
type RequestTransform = {
|
|
18
17
|
id: string;
|
|
19
18
|
warning: MessageKey;
|
|
20
|
-
run(payload: unknown, ctx: ExtensionContext,
|
|
19
|
+
run(payload: unknown, ctx: ExtensionContext, state: StateDocument): unknown | undefined;
|
|
21
20
|
};
|
|
22
21
|
|
|
23
|
-
function createRequestStateLoader(): StateLoader {
|
|
24
|
-
let statePromise: Promise<StateDocument> | undefined;
|
|
25
|
-
return () => {
|
|
26
|
-
statePromise ??= readCachedState();
|
|
27
|
-
return statePromise;
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
22
|
|
|
31
23
|
const REQUEST_TRANSFORMS: RequestTransform[] = [
|
|
32
24
|
{
|
|
33
25
|
id: "claude-code-metadata",
|
|
34
26
|
warning: "ClaudeCode metadata 注入失败,本次请求仅使用请求头",
|
|
35
|
-
|
|
27
|
+
run(payload, ctx, state) {
|
|
36
28
|
if (!ctx.model || ctx.model.api !== "anthropic-messages") return undefined;
|
|
37
|
-
return injectClaudeCodeMetadata(payload, ctx.model,
|
|
29
|
+
return injectClaudeCodeMetadata(payload, ctx.model, state);
|
|
38
30
|
},
|
|
39
31
|
},
|
|
40
32
|
{
|
|
41
33
|
id: "openai-responses-instructions",
|
|
42
34
|
warning: "OpenAI Responses instructions 标准化失败,本次请求使用原始 payload",
|
|
43
|
-
|
|
35
|
+
run(payload, ctx, state) {
|
|
44
36
|
if (!ctx.model || ctx.model.api !== "openai-responses") return undefined;
|
|
45
|
-
return normalizeManagedOpenAIResponsesPayload(payload, ctx.model,
|
|
37
|
+
return normalizeManagedOpenAIResponsesPayload(payload, ctx.model, state);
|
|
46
38
|
},
|
|
47
39
|
},
|
|
48
40
|
{
|
|
49
41
|
id: "openai-service-tier",
|
|
50
42
|
warning: "Fast mode 状态读取失败,本次请求未注入 service_tier",
|
|
51
|
-
|
|
43
|
+
run(payload, ctx, state) {
|
|
52
44
|
if (!ctx.model || ctx.model.api !== "openai-responses") return undefined;
|
|
53
|
-
return injectOpenAIServiceTier(payload, ctx.model,
|
|
45
|
+
return injectOpenAIServiceTier(payload, ctx.model, state);
|
|
54
46
|
},
|
|
55
47
|
},
|
|
56
48
|
];
|
|
@@ -66,11 +58,24 @@ export function createRequestPipeline(): RequestPipeline {
|
|
|
66
58
|
async transform(initialPayload, ctx) {
|
|
67
59
|
let payload = initialPayload;
|
|
68
60
|
let changed = false;
|
|
69
|
-
|
|
61
|
+
if (!ctx.model || (ctx.model.api !== "anthropic-messages" && ctx.model.api !== "openai-responses")) return undefined;
|
|
62
|
+
let state: StateDocument;
|
|
63
|
+
try {
|
|
64
|
+
state = await readCachedState();
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (ctx.hasUI && !notifiedTransformErrors.has("state")) {
|
|
67
|
+
notifiedTransformErrors.add("state");
|
|
68
|
+
ctx.ui.notify(`[pi-model-manager] ${t("请求配置读取失败,本次使用原始 payload")}: ${formatUnknownError(error)}`, "warning");
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
const provider = state.providers[ctx.model.provider];
|
|
73
|
+
const storedModel = provider?.models.find((model) => model.id === ctx.model!.id);
|
|
74
|
+
if (!provider?.managed || !storedModel || (storedModel.api ?? provider.api) !== ctx.model.api) return undefined;
|
|
70
75
|
|
|
71
76
|
for (const transform of REQUEST_TRANSFORMS) {
|
|
72
77
|
try {
|
|
73
|
-
const nextPayload = await transform.run(payload, ctx,
|
|
78
|
+
const nextPayload = await transform.run(payload, ctx, state);
|
|
74
79
|
if (nextPayload !== undefined) {
|
|
75
80
|
payload = nextPayload;
|
|
76
81
|
changed = true;
|
package/runtime-base-url.ts
CHANGED
|
@@ -1,85 +1,65 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 用户侧 API 根地址与 Pi 原生 Anthropic SDK 地址之间的转换。
|
|
2
2
|
|
|
3
|
+
import { t } from "./i18n.ts";
|
|
3
4
|
import type { ApiKind } from "./types.ts";
|
|
4
5
|
|
|
5
|
-
function
|
|
6
|
-
return
|
|
6
|
+
function formatUrl(url: URL): string {
|
|
7
|
+
return url.toString().replace(/^(https?:\/\/[^/?#]+)\/(?=$|[?#])/i, "$1");
|
|
7
8
|
}
|
|
8
9
|
|
|
9
|
-
function
|
|
10
|
-
|
|
11
|
-
return new URL(baseUrl.trim());
|
|
12
|
-
} catch {
|
|
13
|
-
return undefined;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function trimPathTrailingSlashes(pathname: string): string {
|
|
18
|
-
const trimmed = pathname.replace(/\/+$/, "");
|
|
19
|
-
return trimmed || "/";
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function hasRootPath(url: URL): boolean {
|
|
23
|
-
return trimPathTrailingSlashes(url.pathname) === "/";
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function appendPathSegments(url: URL, segments: string[]): string {
|
|
27
|
-
const basePath = trimPathTrailingSlashes(url.pathname);
|
|
28
|
-
const suffix = segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
|
|
29
|
-
url.pathname = `${basePath === "/" ? "" : basePath}/${suffix}` || "/";
|
|
30
|
-
return url.toString();
|
|
10
|
+
function trimPath(url: URL): void {
|
|
11
|
+
url.pathname = url.pathname.replace(/\/+$/, "") || "/";
|
|
31
12
|
}
|
|
32
13
|
|
|
33
14
|
export function appendUrlPath(baseUrl: string, ...segments: string[]): string {
|
|
34
|
-
const
|
|
35
|
-
|
|
15
|
+
const url = new URL(baseUrl.trim());
|
|
16
|
+
const prefix = url.pathname.replace(/\/+$/, "");
|
|
36
17
|
const suffix = segments.map((segment) => segment.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
|
|
37
|
-
|
|
18
|
+
url.pathname = `${prefix}/${suffix}`;
|
|
19
|
+
return formatUrl(url);
|
|
38
20
|
}
|
|
39
21
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const path = trimPathTrailingSlashes(parsed.pathname);
|
|
47
|
-
if (path.toLowerCase().endsWith("/v1")) {
|
|
48
|
-
parsed.pathname = path.slice(0, -3) || "/";
|
|
49
|
-
} else {
|
|
50
|
-
parsed.pathname = path;
|
|
22
|
+
/** 校验发生在编辑/注册/发现边界,不允许 SDK 把端点拼进查询参数或 fragment。 */
|
|
23
|
+
export function validateRequestBaseUrl(baseUrl: string): void {
|
|
24
|
+
const url = new URL(baseUrl.trim());
|
|
25
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(t("Base URL 必须使用 http 或 https"));
|
|
26
|
+
if (baseUrl.includes("?") || baseUrl.includes("#")) {
|
|
27
|
+
throw new Error(t("Base URL 不支持查询参数(?)或片段(#);请填写 API 根地址"));
|
|
51
28
|
}
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function appendV1ForRootUrl(baseUrl: string): string {
|
|
56
|
-
const parsed = parseBaseUrl(baseUrl);
|
|
57
|
-
if (!parsed) return trimTrailingSlashes(baseUrl);
|
|
58
|
-
if (hasRootPath(parsed)) return appendPathSegments(parsed, ["v1"]);
|
|
59
|
-
parsed.pathname = trimPathTrailingSlashes(parsed.pathname);
|
|
60
|
-
return parsed.toString();
|
|
29
|
+
if (url.username || url.password) throw new Error(t("Base URL 不支持内嵌认证;请使用 API key 或请求头配置"));
|
|
61
30
|
}
|
|
62
31
|
|
|
63
|
-
function
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
32
|
+
export function resolveRuntimeBaseUrl(api: ApiKind, baseUrl: string): string {
|
|
33
|
+
const url = new URL(baseUrl.trim());
|
|
34
|
+
trimPath(url);
|
|
35
|
+
if (url.pathname === "/") {
|
|
36
|
+
if (api === "openai-completions" || api === "openai-responses" || api === "anthropic-messages") url.pathname = "/v1";
|
|
37
|
+
else if (api === "google-generative-ai" && url.hostname === "generativelanguage.googleapis.com") url.pathname = "/v1beta";
|
|
69
38
|
}
|
|
70
|
-
|
|
71
|
-
return parsed.toString();
|
|
39
|
+
return formatUrl(url);
|
|
72
40
|
}
|
|
73
41
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
42
|
+
/** 标准 Anthropic 根地址存成 SDK 原生形式,自定义版本路径由私有元数据标识。 */
|
|
43
|
+
export function toNativeBaseUrl(api: string, baseUrl: string): { baseUrl: string; anthropicApiRoot?: true } {
|
|
44
|
+
if (api !== "anthropic-messages") return { baseUrl };
|
|
45
|
+
const url = new URL(resolveRuntimeBaseUrl(api, baseUrl));
|
|
46
|
+
if (url.pathname.endsWith("/v1")) {
|
|
47
|
+
url.pathname = url.pathname.slice(0, -3) || "/";
|
|
48
|
+
return { baseUrl: formatUrl(url) };
|
|
49
|
+
}
|
|
50
|
+
return { baseUrl: formatUrl(url), anthropicApiRoot: true };
|
|
78
51
|
}
|
|
79
52
|
|
|
80
|
-
export function
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
53
|
+
export function fromNativeBaseUrl(
|
|
54
|
+
api: string,
|
|
55
|
+
baseUrl: string,
|
|
56
|
+
anthropicApiRoot = false,
|
|
57
|
+
legacyNormalization = false,
|
|
58
|
+
): string {
|
|
59
|
+
if (api !== "anthropic-messages" || anthropicApiRoot) return baseUrl;
|
|
60
|
+
const url = new URL(baseUrl.trim());
|
|
61
|
+
trimPath(url);
|
|
62
|
+
// [喵喵喵]: 旧版插件在注册前剥去末尾 /v1;读取旧配置必须先复现该行为再显式补回版本路径。
|
|
63
|
+
if (legacyNormalization && url.pathname.toLowerCase().endsWith("/v1")) url.pathname = url.pathname.slice(0, -3) || "/";
|
|
64
|
+
return appendUrlPath(formatUrl(url), "v1");
|
|
85
65
|
}
|