@evandu/super-pi 0.1.280 → 0.1.281
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/dist/client/.super-pi-client-sources.json +9 -7
- package/dist/client/assets/{CodeMirrorEditor-D-UuYizz.js → CodeMirrorEditor-xxJP_tVy.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-Bt1n2la-.js → GitDiffEditor-X8eCsha9.js} +1 -1
- package/dist/client/assets/index-DaKloC7K.css +1 -0
- package/dist/client/assets/{index-rWE1xu-t.js → index-sWsdT0fC.js} +24 -24
- package/dist/client/index.html +2 -2
- package/dist/server/application/provider-service.d.ts +27 -11
- package/dist/server/application/provider-service.js +78 -10
- package/dist/server/application/rsi-service.d.ts +2 -0
- package/dist/server/application/rsi-service.js +78 -10
- package/dist/server/http-server.js +23 -0
- package/dist/server/index.js +4 -0
- package/dist/server/model-discovery.d.ts +44 -0
- package/dist/server/model-discovery.js +139 -0
- package/dist/server/pi-session.d.ts +25 -2
- package/dist/server/pi-session.js +30 -1
- package/dist/server/provider-proxy.d.ts +2 -0
- package/dist/server/provider-proxy.js +1 -1
- package/dist/server/providers.d.ts +6 -0
- package/dist/server/providers.js +76 -10
- package/dist/server/runtime.d.ts +2 -0
- package/dist/server/runtime.js +1 -0
- package/dist/shared/group-chat.d.ts +2 -0
- package/dist/shared/model-discovery.d.ts +15 -0
- package/dist/shared/model-discovery.js +1 -0
- package/dist/shared/tab-layout.d.ts +12 -0
- package/dist/shared/tab-layout.js +28 -0
- package/package.json +5 -1
- package/dist/client/assets/index-B5TLGyEw.css +0 -1
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
/** Server-owned discovery; network work never runs in a picker read or on a model turn. */
|
|
5
|
+
export class ModelDiscovery {
|
|
6
|
+
path;
|
|
7
|
+
hooks;
|
|
8
|
+
intervalMs;
|
|
9
|
+
saved = { states: {}, excluded: {} };
|
|
10
|
+
loaded;
|
|
11
|
+
writes = Promise.resolve();
|
|
12
|
+
pending;
|
|
13
|
+
timer;
|
|
14
|
+
wake;
|
|
15
|
+
controller;
|
|
16
|
+
closed = false;
|
|
17
|
+
started = false;
|
|
18
|
+
constructor(path, hooks, intervalMs = 4 * 60 * 60_000) {
|
|
19
|
+
this.path = path;
|
|
20
|
+
this.hooks = hooks;
|
|
21
|
+
this.intervalMs = intervalMs;
|
|
22
|
+
}
|
|
23
|
+
load() {
|
|
24
|
+
return this.loaded ??= (async () => {
|
|
25
|
+
try {
|
|
26
|
+
const raw = JSON.parse(await readFile(this.path, "utf8"));
|
|
27
|
+
if (!raw?.states || typeof raw.states !== "object" || Array.isArray(raw.states)
|
|
28
|
+
|| !raw?.excluded || typeof raw.excluded !== "object" || Array.isArray(raw.excluded)
|
|
29
|
+
|| !Object.values(raw.states).every((value) => value && typeof value.providerId === "string" && ["checking", "ready", "failed", "unsupported"].includes(value.state))
|
|
30
|
+
|| !Object.values(raw.excluded).every(value => Array.isArray(value) && value.every(id => typeof id === "string")))
|
|
31
|
+
throw new Error("Invalid discovery state");
|
|
32
|
+
this.saved = raw;
|
|
33
|
+
for (const state of Object.values(this.saved.states))
|
|
34
|
+
if (state.state === "checking") {
|
|
35
|
+
state.state = "failed";
|
|
36
|
+
state.detail = "上次检查被服务重启中断,稍后自动重试。";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error.code !== "ENOENT") {
|
|
41
|
+
this.loaded = undefined;
|
|
42
|
+
throw new Error("模型发现缓存无法读取;为保护已删除模型记录,暂不自动导入。");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
})();
|
|
46
|
+
}
|
|
47
|
+
save() {
|
|
48
|
+
const task = this.writes.catch(() => undefined).then(async () => {
|
|
49
|
+
await mkdir(dirname(this.path), { recursive: true });
|
|
50
|
+
const temporary = `${this.path}.${randomUUID()}.tmp`;
|
|
51
|
+
await writeFile(temporary, JSON.stringify(this.saved), { mode: 0o600 });
|
|
52
|
+
await rename(temporary, this.path);
|
|
53
|
+
});
|
|
54
|
+
this.writes = task;
|
|
55
|
+
return task;
|
|
56
|
+
}
|
|
57
|
+
async snapshot() {
|
|
58
|
+
await this.load();
|
|
59
|
+
const targets = await this.hooks.targets();
|
|
60
|
+
return { intervalHours: this.intervalMs / 3_600_000, automatic: this.started && !this.closed, running: Boolean(this.pending), providers: targets.map(target => structuredClone({ ...(this.saved.states[target.scope] ?? { providerId: target.id, state: "ready", added: 0, detail: "等待后台首次检查。" }), name: target.name })) };
|
|
61
|
+
}
|
|
62
|
+
async exclude(scope, modelId) {
|
|
63
|
+
await this.load();
|
|
64
|
+
this.saved.excluded[scope] = [...new Set([...(this.saved.excluded[scope] ?? []), modelId])];
|
|
65
|
+
await this.save();
|
|
66
|
+
}
|
|
67
|
+
async include(scope, modelIds) {
|
|
68
|
+
await this.load();
|
|
69
|
+
if (!this.saved.excluded[scope]?.some(id => modelIds.includes(id)))
|
|
70
|
+
return;
|
|
71
|
+
this.saved.excluded[scope] = this.saved.excluded[scope].filter(id => !modelIds.includes(id));
|
|
72
|
+
await this.save();
|
|
73
|
+
}
|
|
74
|
+
start() {
|
|
75
|
+
if (this.closed)
|
|
76
|
+
return;
|
|
77
|
+
this.started = true;
|
|
78
|
+
this.request(false);
|
|
79
|
+
this.timer ??= setInterval(() => { void this.refresh().catch(() => undefined); }, 60_000);
|
|
80
|
+
this.timer.unref();
|
|
81
|
+
}
|
|
82
|
+
request(force = true) {
|
|
83
|
+
if (this.closed || !this.started)
|
|
84
|
+
return;
|
|
85
|
+
clearTimeout(this.wake);
|
|
86
|
+
this.wake = setTimeout(() => { void this.refresh(force).catch(() => undefined); }, 2000);
|
|
87
|
+
this.wake.unref();
|
|
88
|
+
}
|
|
89
|
+
refresh(force = false) {
|
|
90
|
+
if (this.closed)
|
|
91
|
+
return Promise.resolve();
|
|
92
|
+
if (this.pending)
|
|
93
|
+
return this.pending;
|
|
94
|
+
this.controller = new AbortController();
|
|
95
|
+
return this.pending = this.run(force, this.controller.signal).finally(() => { this.pending = undefined; this.controller = undefined; });
|
|
96
|
+
}
|
|
97
|
+
async run(force, signal) {
|
|
98
|
+
await this.load();
|
|
99
|
+
for (const target of await this.hooks.targets()) {
|
|
100
|
+
if (signal.aborted)
|
|
101
|
+
break;
|
|
102
|
+
const previous = this.saved.states[target.scope];
|
|
103
|
+
const retryMs = previous?.state === "failed" ? 15 * 60_000 : this.intervalMs;
|
|
104
|
+
if (!force && previous?.checkedAt && Date.now() - Date.parse(previous.checkedAt) < retryMs)
|
|
105
|
+
continue;
|
|
106
|
+
const state = { providerId: target.id, name: target.name, state: "checking", added: 0, ...(previous?.succeededAt ? { succeededAt: previous.succeededAt } : {}) };
|
|
107
|
+
this.saved.states[target.scope] = state;
|
|
108
|
+
try {
|
|
109
|
+
const models = await this.hooks.discover(target, AbortSignal.any([signal, AbortSignal.timeout(30_000)]), force);
|
|
110
|
+
if (signal.aborted)
|
|
111
|
+
break;
|
|
112
|
+
const excluded = new Set(this.saved.excluded[target.scope] ?? []);
|
|
113
|
+
const added = await this.hooks.apply(target, models.filter(model => !excluded.has(model.id)));
|
|
114
|
+
if (added === undefined) {
|
|
115
|
+
delete this.saved.states[target.scope];
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (added > 0 || target.builtin)
|
|
119
|
+
await this.hooks.changed();
|
|
120
|
+
Object.assign(state, { state: "ready", checkedAt: new Date().toISOString(), succeededAt: new Date().toISOString(), added, detail: added ? `发现 ${added} 个新模型,已加入列表。` : "检查完成,模型列表已是最新。" });
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (signal.aborted)
|
|
124
|
+
break;
|
|
125
|
+
const unsupported = error.code === "DISCOVERY_UNSUPPORTED";
|
|
126
|
+
Object.assign(state, { state: unsupported ? "unsupported" : "failed", checkedAt: new Date().toISOString(), detail: unsupported ? "此接口未提供可用的模型枚举;继续使用已有模型。" : "检查失败,已保留已有模型;请检查供应商凭据、网络或代理,稍后自动重试。" });
|
|
127
|
+
}
|
|
128
|
+
await this.save();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
async close() {
|
|
132
|
+
this.closed = true;
|
|
133
|
+
clearInterval(this.timer);
|
|
134
|
+
clearTimeout(this.wake);
|
|
135
|
+
this.controller?.abort();
|
|
136
|
+
await this.pending?.catch(() => undefined);
|
|
137
|
+
await this.writes.catch(() => undefined);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* the transcript on disk while the live session still holds the old context in memory, and nothing in Pi
|
|
24
24
|
* would notice the difference.
|
|
25
25
|
*/
|
|
26
|
+
import type { DiscoveredModel } from "./types.js";
|
|
26
27
|
import type { PiImageContent } from "./types.js";
|
|
27
28
|
import type { PiCacheWarmingMode } from "../shared/pi-cache-warming.js";
|
|
28
29
|
/**
|
|
@@ -85,8 +86,16 @@ interface PiSdk {
|
|
|
85
86
|
ModelRuntime: {
|
|
86
87
|
create(options?: Record<string, unknown>): Promise<{
|
|
87
88
|
getModel?: (provider: string, modelId: string) => unknown;
|
|
88
|
-
getAvailable?: () => Promise<unknown[]>;
|
|
89
|
+
getAvailable?: (providerId?: string) => Promise<unknown[]>;
|
|
89
90
|
getModels?: () => unknown[];
|
|
91
|
+
getAuth?: (provider: string, options?: {
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
}) => Promise<{
|
|
94
|
+
auth: {
|
|
95
|
+
apiKey?: string;
|
|
96
|
+
headers?: Record<string, string>;
|
|
97
|
+
};
|
|
98
|
+
} | undefined>;
|
|
90
99
|
/**
|
|
91
100
|
* Pi's own verdict on its model configuration - the schema error that empties every picker
|
|
92
101
|
* when one entry in `models.json` is refused.
|
|
@@ -114,7 +123,10 @@ interface PiSdk {
|
|
|
114
123
|
agentName?: string;
|
|
115
124
|
}) => Promise<unknown>;
|
|
116
125
|
logout?: (providerId: string) => Promise<void>;
|
|
117
|
-
refresh?: () => Promise<
|
|
126
|
+
refresh?: (options?: Record<string, unknown>) => Promise<{
|
|
127
|
+
aborted: boolean;
|
|
128
|
+
errors: Map<string, Error>;
|
|
129
|
+
}>;
|
|
118
130
|
}>;
|
|
119
131
|
};
|
|
120
132
|
AuthStorage?: {
|
|
@@ -148,6 +160,17 @@ interface PiSdk {
|
|
|
148
160
|
* module and returns, and the caller decides what to do with a failure.
|
|
149
161
|
*/
|
|
150
162
|
export declare function warmPiSdk(): Promise<boolean>;
|
|
163
|
+
/** Refresh catalogs without changing credentials, defaults, or any running session. */
|
|
164
|
+
export declare function discoverPiProviderModels(input: {
|
|
165
|
+
id: string;
|
|
166
|
+
builtin: boolean;
|
|
167
|
+
baseUrl: string;
|
|
168
|
+
api: string;
|
|
169
|
+
agentDir: string;
|
|
170
|
+
signal: AbortSignal;
|
|
171
|
+
force: boolean;
|
|
172
|
+
catalogBaseUrl?: string;
|
|
173
|
+
}): Promise<DiscoveredModel[]>;
|
|
151
174
|
export declare function piCacheWarmingMode(mode?: PiCacheWarmingMode): Promise<PiCacheWarmingMode>;
|
|
152
175
|
/**
|
|
153
176
|
* A model catalog read from Pi's SDK, with NO PROCESS.
|
|
@@ -28,7 +28,8 @@ import { open, readdir } from "node:fs/promises";
|
|
|
28
28
|
import { StringDecoder } from "node:string_decoder";
|
|
29
29
|
import { dirname, join, resolve } from "node:path";
|
|
30
30
|
import { createModelResolver } from "./model-context-window.js";
|
|
31
|
-
import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
|
|
31
|
+
import { installProviderProxy, proxyCredentialStore, readProviderProxyEnv, withAuthProxy } from "./provider-proxy.js";
|
|
32
|
+
import { fetchRemoteModels, KNOWN_APIS } from "./providers.js";
|
|
32
33
|
import { SOURCE_LINK_GUIDANCE } from "../shared/message-source-link.js";
|
|
33
34
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
34
35
|
import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, readNativeToolSettings } from "./native-tool-settings.js";
|
|
@@ -56,6 +57,34 @@ export async function warmPiSdk() {
|
|
|
56
57
|
return false;
|
|
57
58
|
}
|
|
58
59
|
}
|
|
60
|
+
/** Refresh catalogs without changing credentials, defaults, or any running session. */
|
|
61
|
+
export async function discoverPiProviderModels(input) {
|
|
62
|
+
const sdk = await loadSdk();
|
|
63
|
+
const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(input.agentDir, "auth.json"))) : undefined;
|
|
64
|
+
const runtime = await sdk.ModelRuntime.create({ credentials, authPath: join(input.agentDir, "auth.json"), modelsPath: join(input.agentDir, "models.json"), refreshOnCreate: false, signal: input.signal, ...(input.catalogBaseUrl ? { catalogBaseUrl: input.catalogBaseUrl } : {}) });
|
|
65
|
+
await installProviderProxy(runtime, input.agentDir);
|
|
66
|
+
const proxyEnv = await readProviderProxyEnv(input.agentDir, input.id);
|
|
67
|
+
if (input.builtin) {
|
|
68
|
+
if (!runtime.refresh)
|
|
69
|
+
throw new Error("当前 Pi SDK 不支持目录刷新。");
|
|
70
|
+
const result = await withAuthProxy(proxyEnv, () => runtime.refresh({ providers: [input.id], allowNetwork: true, force: input.force, signal: input.signal }), input.id);
|
|
71
|
+
if (result.aborted)
|
|
72
|
+
throw new Error("模型目录刷新超时。");
|
|
73
|
+
if (result.errors.has(input.id))
|
|
74
|
+
throw result.errors.get(input.id);
|
|
75
|
+
const available = await runtime.getAvailable?.(input.id) ?? runtime.getModels?.() ?? [];
|
|
76
|
+
return available.flatMap((item) => {
|
|
77
|
+
const model = item;
|
|
78
|
+
if (model.provider !== input.id || !KNOWN_APIS.includes(model.api))
|
|
79
|
+
return [];
|
|
80
|
+
return [{ id: model.id, name: model.name ?? model.id, reasoning: model.reasoning === true, imageInput: model.input?.includes("image") === true, contextWindow: model.contextWindow, maxTokens: model.maxTokens, ...(model.thinkingLevelMap ? { thinkingLevelMap: model.thinkingLevelMap } : {}) }];
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const auth = await runtime.getAuth?.(input.id, { signal: input.signal });
|
|
84
|
+
const models = await fetchRemoteModels({ baseUrl: input.baseUrl, api: input.api, apiKey: auth?.auth.apiKey, headers: auth?.auth.headers, proxyEnv, signal: input.signal });
|
|
85
|
+
// /models may also enumerate embeddings, speech, moderation and image-generation endpoints.
|
|
86
|
+
return models.filter(model => !/(?:embedding|embed-|whisper|tts-|dall-e|moderation|transcrib|^rerank|^bge-|^text-embedding)/i.test(model.id));
|
|
87
|
+
}
|
|
59
88
|
let sdkPromise;
|
|
60
89
|
let sdkFailure;
|
|
61
90
|
export async function piCacheWarmingMode(mode) {
|
|
@@ -11,6 +11,8 @@ export declare function readProviderProxyEnv(agentDir: string, providerId?: stri
|
|
|
11
11
|
type Env = Record<string, string | undefined>;
|
|
12
12
|
/** Apply scoped proxy values without changing the server's process environment. */
|
|
13
13
|
export declare function providerProxyFetch(env: Env | undefined, baseFetch?: typeof fetch): typeof fetch | undefined;
|
|
14
|
+
/** OAuth adapters call global fetch. Route only the current async auth operation through its proxy. */
|
|
15
|
+
export declare function withAuthProxy<T>(env: Env | undefined, operation: () => Promise<T>, providerId?: string): Promise<T>;
|
|
14
16
|
/** Keep Pi's own cross-process credential lock, and preserve scoped env on OAuth rotation/login. */
|
|
15
17
|
export declare function proxyCredentialStore<T extends object>(store: T): T;
|
|
16
18
|
/** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
|
|
@@ -91,7 +91,7 @@ const authFetchScope = new AsyncLocalStorage();
|
|
|
91
91
|
let scopedFetch;
|
|
92
92
|
let baseAuthFetch;
|
|
93
93
|
/** OAuth adapters call global fetch. Route only the current async auth operation through its proxy. */
|
|
94
|
-
async function withAuthProxy(env, operation, providerId) {
|
|
94
|
+
export async function withAuthProxy(env, operation, providerId) {
|
|
95
95
|
const active = authFetchScope.getStore();
|
|
96
96
|
env = mergeEnv(env, providerId && active?.providerId === providerId ? active.env : undefined);
|
|
97
97
|
if (!Object.keys(env).some(key => /^(http_proxy|https_proxy|all_proxy|no_proxy)$/i.test(key))) {
|
|
@@ -186,6 +186,8 @@ export declare class ProviderRegistry {
|
|
|
186
186
|
* accident - it has to be given one.
|
|
187
187
|
*/
|
|
188
188
|
constructor(dataDir: string, piDir?: string);
|
|
189
|
+
get discoveryPath(): string;
|
|
190
|
+
get agentDir(): string;
|
|
189
191
|
private networkQueue;
|
|
190
192
|
private sharedNetworkRecord;
|
|
191
193
|
sharedNetwork(known: ReadonlyArray<{
|
|
@@ -286,6 +288,8 @@ export declare class ProviderRegistry {
|
|
|
286
288
|
* Full visual editor semantics: any provider in models.json is editable and removable.
|
|
287
289
|
*/
|
|
288
290
|
applyToPi(previous: ProviderDefinition[], next: ProviderDefinition[]): Promise<void>;
|
|
291
|
+
/** Append discovery results without normalizing any existing model or touching auth.json. */
|
|
292
|
+
appendDiscovered(provider: ProviderDefinition, models: DiscoveredModel[]): Promise<() => Promise<void>>;
|
|
289
293
|
/**
|
|
290
294
|
* Writes the keys into Pi's `auth.json`.
|
|
291
295
|
*/
|
|
@@ -306,6 +310,8 @@ export declare function validateProvider(input: unknown): ProviderDefinition;
|
|
|
306
310
|
*/
|
|
307
311
|
export declare function fetchRemoteModels(input: {
|
|
308
312
|
baseUrl: string;
|
|
313
|
+
signal?: AbortSignal;
|
|
314
|
+
headers?: Record<string, string>;
|
|
309
315
|
proxyEnv?: Record<string, string>;
|
|
310
316
|
apiKey?: string;
|
|
311
317
|
api?: string;
|
package/dist/server/providers.js
CHANGED
|
@@ -283,6 +283,8 @@ export class ProviderRegistry {
|
|
|
283
283
|
this.dataDir = dataDir;
|
|
284
284
|
this.piDir = piDir;
|
|
285
285
|
}
|
|
286
|
+
get discoveryPath() { return join(this.dataDir, "model-discovery.json"); }
|
|
287
|
+
get agentDir() { return this.piDir; }
|
|
286
288
|
networkQueue = Promise.resolve();
|
|
287
289
|
async sharedNetworkRecord(known) {
|
|
288
290
|
const saved = await readSharedProviderProxy(this.piDir);
|
|
@@ -671,6 +673,23 @@ export class ProviderRegistry {
|
|
|
671
673
|
await writeJsonAtomic(modelsPath, { ...existing, providers: mergedProviders });
|
|
672
674
|
await this.applyKeysToPi(previous, next);
|
|
673
675
|
}
|
|
676
|
+
/** Append discovery results without normalizing any existing model or touching auth.json. */
|
|
677
|
+
async appendDiscovered(provider, models) {
|
|
678
|
+
const path = piModelsPath(this.piDir);
|
|
679
|
+
const existing = await readJsonFile(path);
|
|
680
|
+
const entry = existing?.providers?.[provider.id];
|
|
681
|
+
if (!entry || typeof entry !== "object")
|
|
682
|
+
throw new Error("供应商配置已改变,放弃本次自动导入。");
|
|
683
|
+
const additions = toPiProvider({ ...provider, models }).models;
|
|
684
|
+
const updated = { ...entry, models: [...(Array.isArray(entry.models) ? entry.models : []), ...additions] };
|
|
685
|
+
await writeJsonAtomic(path, { ...existing, providers: { ...existing?.providers, [provider.id]: updated } });
|
|
686
|
+
return async () => {
|
|
687
|
+
const current = await readJsonFile(path);
|
|
688
|
+
if (JSON.stringify(current.providers?.[provider.id]) !== JSON.stringify(updated))
|
|
689
|
+
throw new Error("模型配置已被外部修改,拒绝覆盖。");
|
|
690
|
+
await writeJsonAtomic(path, { ...current, providers: { ...current.providers, [provider.id]: entry } });
|
|
691
|
+
};
|
|
692
|
+
}
|
|
674
693
|
/**
|
|
675
694
|
* Writes the keys into Pi's `auth.json`.
|
|
676
695
|
*/
|
|
@@ -851,18 +870,31 @@ export async function fetchRemoteModels(input) {
|
|
|
851
870
|
const cleanBase = rawBase.replace(/\/+$/, "");
|
|
852
871
|
const headers = {
|
|
853
872
|
accept: "application/json",
|
|
873
|
+
...input.headers,
|
|
854
874
|
};
|
|
855
875
|
if (input.apiKey && input.apiKey.trim()) {
|
|
856
876
|
headers.authorization = `Bearer ${input.apiKey.trim()}`;
|
|
877
|
+
if (input.api === "anthropic-messages") {
|
|
878
|
+
headers["x-api-key"] = input.apiKey.trim();
|
|
879
|
+
headers["anthropic-version"] ??= "2023-06-01";
|
|
880
|
+
delete headers.authorization;
|
|
881
|
+
}
|
|
882
|
+
else if (input.api === "google-generative-ai") {
|
|
883
|
+
headers["x-goog-api-key"] = input.apiKey.trim();
|
|
884
|
+
delete headers.authorization;
|
|
885
|
+
}
|
|
857
886
|
}
|
|
858
887
|
const isOllama = input.api === "ollama" || cleanBase.includes(":11434");
|
|
859
888
|
const candidates = [];
|
|
860
889
|
if (isOllama) {
|
|
861
890
|
candidates.push(`${cleanBase}/api/tags`, `${cleanBase}/v1/models`, `${cleanBase}/models`);
|
|
862
891
|
}
|
|
863
|
-
else if (
|
|
892
|
+
else if (/\/(v1|v1beta|v1alpha)$/.test(cleanBase)) {
|
|
864
893
|
candidates.push(`${cleanBase}/models`);
|
|
865
894
|
}
|
|
895
|
+
else if (input.api === "google-generative-ai") {
|
|
896
|
+
candidates.push(`${cleanBase}/v1beta/models`);
|
|
897
|
+
}
|
|
866
898
|
else {
|
|
867
899
|
candidates.push(`${cleanBase}/v1/models`, `${cleanBase}/models`);
|
|
868
900
|
}
|
|
@@ -878,7 +910,9 @@ export async function fetchRemoteModels(input) {
|
|
|
878
910
|
try {
|
|
879
911
|
const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(candidate, {
|
|
880
912
|
headers,
|
|
881
|
-
|
|
913
|
+
// Fetch only strips standard Authorization on cross-origin redirects, not vendor key headers.
|
|
914
|
+
redirect: input.api === "anthropic-messages" || input.api === "google-generative-ai" ? "error" : "follow",
|
|
915
|
+
signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000),
|
|
882
916
|
});
|
|
883
917
|
if (!response.ok) {
|
|
884
918
|
lastError = `HTTP ${response.status} ${response.statusText}`;
|
|
@@ -903,9 +937,32 @@ export async function fetchRemoteModels(input) {
|
|
|
903
937
|
const cause = lastCause instanceof Error
|
|
904
938
|
? (lastCause.cause instanceof Error ? lastCause.cause.message : lastCause.cause instanceof Object && lastCause.cause !== null ? String(lastCause.cause.code ?? "") : undefined)
|
|
905
939
|
: undefined;
|
|
906
|
-
|
|
940
|
+
const error = new Error(`无法从远程服务获取模型列表 (${lastError || "请求超时或无法连接"}${cause ? `:${cause}` : ""})`);
|
|
941
|
+
if (/HTTP (404|405|501)/.test(lastError))
|
|
942
|
+
Object.assign(error, { code: "DISCOVERY_UNSUPPORTED" });
|
|
943
|
+
throw error;
|
|
907
944
|
}
|
|
908
|
-
|
|
945
|
+
// Follow only same-origin continuation URLs that we construct; never forward keys to payload URLs.
|
|
946
|
+
const first = payload;
|
|
947
|
+
const combined = Array.isArray(payload) ? [...payload] : [...(first.data ?? first.models ?? [])];
|
|
948
|
+
let page = first;
|
|
949
|
+
const seenPages = new Set();
|
|
950
|
+
for (let index = 1; page.has_more || page.nextPageToken; index++) {
|
|
951
|
+
if (index >= 100 || combined.length >= 20_000)
|
|
952
|
+
throw new Error("模型目录分页超过安全上限,请缩小供应商范围。");
|
|
953
|
+
const token = page.nextPageToken ?? page.last_id;
|
|
954
|
+
if (!token || seenPages.has(token))
|
|
955
|
+
throw new Error("供应商模型分页无效,已保留原目录。");
|
|
956
|
+
seenPages.add(token);
|
|
957
|
+
const next = new URL(answeredUrl);
|
|
958
|
+
next.searchParams.set(page.nextPageToken ? "pageToken" : "after", token);
|
|
959
|
+
const response = await (providerProxyFetch(input.proxyEnv) ?? fetch)(next, { headers, redirect: "error", signal: input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000) });
|
|
960
|
+
if (!response.ok)
|
|
961
|
+
throw new Error("供应商模型分页读取失败,已保留原目录。");
|
|
962
|
+
page = await response.json();
|
|
963
|
+
combined.push(...(page.data ?? page.models ?? []));
|
|
964
|
+
}
|
|
965
|
+
return parseRemoteModels(combined, { baseUrl: answeredUrl, api: input.api });
|
|
909
966
|
}
|
|
910
967
|
/**
|
|
911
968
|
* THE ANSWER, READ.
|
|
@@ -941,7 +998,11 @@ export function parseRemoteModels(payload, context) {
|
|
|
941
998
|
if (!item || typeof item !== "object")
|
|
942
999
|
continue;
|
|
943
1000
|
const rec = item;
|
|
944
|
-
|
|
1001
|
+
if (Array.isArray(rec.supportedGenerationMethods) && !rec.supportedGenerationMethods.includes("generateContent"))
|
|
1002
|
+
continue;
|
|
1003
|
+
let id = typeof rec.id === "string" ? rec.id.trim() : typeof rec.name === "string" ? rec.name.trim() : typeof rec.model === "string" ? rec.model.trim() : "";
|
|
1004
|
+
if (context?.api === "google-generative-ai")
|
|
1005
|
+
id = id.replace(/^models\//, "");
|
|
945
1006
|
if (!id || seen.has(id))
|
|
946
1007
|
continue;
|
|
947
1008
|
seen.add(id);
|
|
@@ -960,24 +1021,29 @@ export function parseRemoteModels(payload, context) {
|
|
|
960
1021
|
const reasoning = typeof rec.reasoning === "boolean"
|
|
961
1022
|
? rec.reasoning
|
|
962
1023
|
: (Boolean(thinkingLevelMap) || /r1|reason|o1|o3|thinking|qwq|deepseek-r1/i.test(lower));
|
|
963
|
-
const imageInput =
|
|
1024
|
+
const imageInput = typeof rec.imageInput === "boolean" ? rec.imageInput
|
|
1025
|
+
: Array.isArray(rec.input) ? rec.input.includes("image")
|
|
1026
|
+
: /vision|vl|4o|gemini|claude-3|flash|pixtral/i.test(lower);
|
|
964
1027
|
// THE CATALOGUE IS ASKED BEFORE THE DEFAULT IS GUESSED. A model the provider did not describe
|
|
965
1028
|
// used to fall straight to the placeholder 128000/16384, and that stamp was later read back as
|
|
966
1029
|
// if a person had chosen it - which is how MiniMax-M3 (a 1,000,000-token model) came to believe
|
|
967
1030
|
// it had 128,000. Only a model with NO catalogue entry takes the default.
|
|
968
1031
|
const catalogue = storeWindowFor(readModelStore(piAgentDir()), id);
|
|
969
|
-
const
|
|
970
|
-
|
|
1032
|
+
const reportedWindow = rec.context_window ?? rec.contextWindow ?? rec.context_length ?? rec.inputTokenLimit;
|
|
1033
|
+
const contextWindow = typeof reportedWindow === "number" && Number.isFinite(reportedWindow) && reportedWindow > 0
|
|
1034
|
+
? reportedWindow
|
|
971
1035
|
: catalogue?.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
|
|
972
1036
|
// THE CATALOGUE OUTRANKS THE REASONING GUESS, AND THE ORDER IS THE WHOLE POINT. A reasoning
|
|
973
1037
|
// model used to be stamped with 32768 BEFORE the catalogue was consulted, so a model whose
|
|
974
1038
|
// provider publishes a bigger answer limit got a smaller one - the same hole as the window
|
|
975
1039
|
// one number over, with the same consequence: the limit Super Pi invented is the limit the
|
|
976
1040
|
// session runs on. The guess is what is left when nobody knows better.
|
|
977
|
-
const
|
|
1041
|
+
const reportedOutput = rec.max_output_tokens ?? rec.maxTokens ?? rec.outputTokenLimit;
|
|
1042
|
+
const maxTokens = typeof reportedOutput === "number" && Number.isFinite(reportedOutput) && reportedOutput > 0 ? reportedOutput
|
|
1043
|
+
: catalogue?.maxTokens ?? (reasoning ? GUESSED_MAX_TOKENS : DEFAULT_MAX_TOKENS);
|
|
978
1044
|
discovered.push({
|
|
979
1045
|
id,
|
|
980
|
-
name: id,
|
|
1046
|
+
name: typeof rec.display_name === "string" ? rec.display_name : typeof rec.displayName === "string" ? rec.displayName : id,
|
|
981
1047
|
reasoning,
|
|
982
1048
|
imageInput,
|
|
983
1049
|
contextWindow,
|
package/dist/server/runtime.d.ts
CHANGED
|
@@ -393,6 +393,7 @@ export interface AgentRuntime {
|
|
|
393
393
|
* selected model silently clamps away.
|
|
394
394
|
*/
|
|
395
395
|
catalog(selection?: ModelSelection): Promise<ModelCatalog>;
|
|
396
|
+
readonly supportsModelDiscovery?: boolean;
|
|
396
397
|
oauthProviders?(): Promise<{
|
|
397
398
|
id: string;
|
|
398
399
|
name: string;
|
|
@@ -1304,6 +1305,7 @@ export declare class PiRpcRuntime implements AgentRuntime {
|
|
|
1304
1305
|
loginLabel?: string;
|
|
1305
1306
|
authenticated: boolean;
|
|
1306
1307
|
}[]>;
|
|
1308
|
+
get supportsModelDiscovery(): boolean;
|
|
1307
1309
|
loginOAuth(providerId: string, interaction: {
|
|
1308
1310
|
signal: AbortSignal;
|
|
1309
1311
|
prompt(prompt: any): Promise<string>;
|
package/dist/server/runtime.js
CHANGED
|
@@ -2976,6 +2976,7 @@ export class PiRpcRuntime {
|
|
|
2976
2976
|
this.sdkCatalogPromise = undefined;
|
|
2977
2977
|
}
|
|
2978
2978
|
async oauthProviders() { return (await this.sdkCatalog())?.oauthProviders() ?? []; }
|
|
2979
|
+
get supportsModelDiscovery() { return this.pi.explicit !== true && this.sessionMode !== "oneshot"; }
|
|
2979
2980
|
async loginOAuth(providerId, interaction) {
|
|
2980
2981
|
const catalog = await this.sdkCatalog();
|
|
2981
2982
|
if (!catalog)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type ModelDiscoveryStatus = {
|
|
2
|
+
providerId: string;
|
|
3
|
+
name: string;
|
|
4
|
+
state: "checking" | "ready" | "failed" | "unsupported";
|
|
5
|
+
checkedAt?: string;
|
|
6
|
+
succeededAt?: string;
|
|
7
|
+
added: number;
|
|
8
|
+
detail?: string;
|
|
9
|
+
};
|
|
10
|
+
export type ModelDiscoverySnapshot = {
|
|
11
|
+
intervalHours: number;
|
|
12
|
+
automatic: boolean;
|
|
13
|
+
running: boolean;
|
|
14
|
+
providers: ModelDiscoveryStatus[];
|
|
15
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type ContentTabRow = {
|
|
2
|
+
ids: string[];
|
|
3
|
+
width: number;
|
|
4
|
+
};
|
|
5
|
+
/** Keep short tabs compact; move long single-line titles to another row before truncating. */
|
|
6
|
+
export declare function contentTabRows(tabs: readonly {
|
|
7
|
+
id: string;
|
|
8
|
+
width: number;
|
|
9
|
+
}[], container: number, min: number, max: number, fallback: {
|
|
10
|
+
perRow: number;
|
|
11
|
+
width: number;
|
|
12
|
+
}): ContentTabRow[];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Keep short tabs compact; move long single-line titles to another row before truncating. */
|
|
2
|
+
export function contentTabRows(tabs, container, min, max, fallback) {
|
|
3
|
+
const available = Number.isFinite(container) && container > 0 ? container : min;
|
|
4
|
+
const normalized = tabs.map(tab => ({ id: tab.id, width: Math.min(available, Math.max(Math.min(min, available), Number.isFinite(tab.width) ? tab.width : min)) }));
|
|
5
|
+
if (normalized.every(tab => tab.width <= fallback.width)) {
|
|
6
|
+
const rows = [];
|
|
7
|
+
for (let index = 0; index < tabs.length; index += Math.max(1, fallback.perRow))
|
|
8
|
+
rows.push({ ids: tabs.slice(index, index + Math.max(1, fallback.perRow)).map(tab => tab.id), width: Math.min(available, fallback.width) });
|
|
9
|
+
return rows;
|
|
10
|
+
}
|
|
11
|
+
const result = [];
|
|
12
|
+
let row = [], preferred = 0;
|
|
13
|
+
const finish = () => {
|
|
14
|
+
if (!row.length)
|
|
15
|
+
return;
|
|
16
|
+
result.push({ ids: row.map(tab => tab.id), width: Math.min(available / row.length, Math.max(max, preferred)) });
|
|
17
|
+
row = [];
|
|
18
|
+
preferred = 0;
|
|
19
|
+
};
|
|
20
|
+
for (const tab of normalized) {
|
|
21
|
+
if (row.length && Math.max(preferred, tab.width) * (row.length + 1) > available + 0.1)
|
|
22
|
+
finish();
|
|
23
|
+
row.push(tab);
|
|
24
|
+
preferred = Math.max(preferred, tab.width);
|
|
25
|
+
}
|
|
26
|
+
finish();
|
|
27
|
+
return result;
|
|
28
|
+
}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"superPi": {
|
|
4
4
|
"managedDirectListener": true
|
|
5
5
|
},
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.281",
|
|
7
7
|
"description": "Web control plane and companion for Pi",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"type": "module",
|
|
@@ -54,6 +54,8 @@
|
|
|
54
54
|
"pack:server": "npm run build && node scripts/pack-server.mjs"
|
|
55
55
|
},
|
|
56
56
|
"check:logic": [
|
|
57
|
+
"scripts/model-discovery.test.mjs",
|
|
58
|
+
"scripts/tab-content-layout.test.mjs",
|
|
57
59
|
"scripts/rsi-capability-loop.test.mjs",
|
|
58
60
|
"scripts/desktop-window-state.test.mjs",
|
|
59
61
|
"scripts/remote-listener.test.mjs",
|
|
@@ -329,6 +331,8 @@
|
|
|
329
331
|
"scripts/session-reminder-pmo-rights.test.mjs"
|
|
330
332
|
],
|
|
331
333
|
"check:browser": [
|
|
334
|
+
"scripts/model-discovery-browser.test.mjs",
|
|
335
|
+
"scripts/tab-content-browser.test.mjs",
|
|
332
336
|
"scripts/rsi-session-browser.test.mjs",
|
|
333
337
|
"scripts/message-source-links-browser.test.mjs",
|
|
334
338
|
"scripts/settings-number-drafts-browser.test.mjs",
|