@evandu/super-pi 0.1.258 → 0.1.260
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.md +42 -0
- package/agents/super-pi-managed-model/index.ts +9 -0
- package/bin/npm-prefix.js +1 -1
- package/bin/super-pi.js +4 -3
- package/desktop/icon.png +0 -0
- package/desktop/launch.cjs +14 -0
- package/desktop/login-item.cjs +7 -0
- package/desktop/main.cjs +104 -0
- package/desktop/preload.cjs +9 -0
- package/desktop/runtime.cjs +107 -0
- package/dist/client/.super-pi-client-sources.json +33 -28
- package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
- package/dist/client/assets/{GitDiffEditor-BOtWl74Z.js → GitDiffEditor-FQBfGxOY.js} +3 -3
- package/dist/client/assets/index-Cn7hdrDw.js +350 -0
- package/dist/client/assets/{index-JchFQmlF.css → index-UfzqdECL.css} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/browser-access.d.ts +34 -0
- package/dist/server/browser-access.js +89 -0
- package/dist/server/command-handler.d.ts +1 -1
- package/dist/server/command-handler.js +3 -3
- package/dist/server/http-server.js +90 -36
- package/dist/server/index.js +9 -0
- package/dist/server/managed-http-tunnel.d.ts +6 -0
- package/dist/server/managed-http-tunnel.js +85 -0
- package/dist/server/managed-http.d.ts +4 -0
- package/dist/server/managed-http.js +85 -0
- package/dist/server/managed-model-adapter.d.ts +17 -0
- package/dist/server/managed-model-adapter.js +75 -0
- package/dist/server/managed-model-gateway.d.ts +49 -0
- package/dist/server/managed-model-gateway.js +73 -0
- package/dist/server/managed-servers.d.ts +55 -0
- package/dist/server/managed-servers.js +396 -0
- package/dist/server/managed-ssh.d.ts +26 -0
- package/dist/server/managed-ssh.js +73 -0
- package/dist/server/manager-vault.d.ts +11 -0
- package/dist/server/manager-vault.js +67 -0
- package/dist/server/provider-proxy.js +2 -0
- package/dist/server/remote-bootstrap.d.ts +17 -0
- package/dist/server/remote-bootstrap.js +119 -0
- package/dist/server/runtime.js +2 -2
- package/dist/server/server-context.d.ts +2 -0
- package/dist/server/terminal.d.ts +2 -2
- package/dist/server/terminal.js +6 -6
- package/dist/server/update.d.ts +1 -0
- package/dist/server/update.js +13 -2
- package/dist/server/ws-server.d.ts +5 -0
- package/dist/server/ws-server.js +29 -4
- package/dist/shared/managed-servers.d.ts +36 -0
- package/dist/shared/managed-servers.js +1 -0
- package/package.json +23 -4
- package/scripts/pack-server.mjs +44 -0
- package/dist/client/assets/CodeMirrorEditor-CyVU-MC_.js +0 -2
- package/dist/client/assets/index-Ba79LA0t.js +0 -349
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { request as httpRequest, Agent } from "node:http";
|
|
2
|
+
import { sshForward } from "./managed-ssh.js";
|
|
3
|
+
function headers(input, port, key) {
|
|
4
|
+
const next = { ...input, host: `127.0.0.1:${port}`, authorization: `Bearer ${key}` };
|
|
5
|
+
delete next.cookie;
|
|
6
|
+
// Only an upstream owner credential travels through the private SSH channel.
|
|
7
|
+
delete next["sec-websocket-protocol"];
|
|
8
|
+
return next;
|
|
9
|
+
}
|
|
10
|
+
function agentFor(client, port) {
|
|
11
|
+
const agent = new Agent({ keepAlive: false });
|
|
12
|
+
agent.createConnection = ((_options, callback) => {
|
|
13
|
+
void sshForward(client, port).then(channel => {
|
|
14
|
+
const socket = channel;
|
|
15
|
+
for (const method of ["setKeepAlive", "setNoDelay", "setTimeout", "ref", "unref"])
|
|
16
|
+
socket[method] = () => channel;
|
|
17
|
+
socket.destroySoon = channel.destroy.bind(channel);
|
|
18
|
+
callback(null, channel);
|
|
19
|
+
}, error => callback(error));
|
|
20
|
+
return undefined;
|
|
21
|
+
});
|
|
22
|
+
return agent;
|
|
23
|
+
}
|
|
24
|
+
export async function tunnelJson(client, port, path, key, method = "GET") {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const agent = agentFor(client, port);
|
|
27
|
+
const request = httpRequest({ hostname: "127.0.0.1", port, path, method, agent, headers: { authorization: `Bearer ${key}` } }, response => {
|
|
28
|
+
let text = "";
|
|
29
|
+
response.setEncoding("utf8");
|
|
30
|
+
response.on("data", chunk => { text += chunk; if (text.length > 8 * 1024 * 1024)
|
|
31
|
+
request.destroy(); });
|
|
32
|
+
response.once("end", () => { agent.destroy(); try {
|
|
33
|
+
if ((response.statusCode ?? 500) >= 400)
|
|
34
|
+
throw new Error();
|
|
35
|
+
resolve(JSON.parse(text));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
reject(new Error(`远端服务未返回有效状态(${response.statusCode})`));
|
|
39
|
+
} });
|
|
40
|
+
});
|
|
41
|
+
const timeout = setTimeout(() => request.destroy(new Error("远端服务响应超时")), 12_000);
|
|
42
|
+
request.once("close", () => clearTimeout(timeout));
|
|
43
|
+
request.once("error", () => { agent.destroy(); reject(new Error("SSH 已连接,但远端 Super Pi 服务不可达")); });
|
|
44
|
+
request.end();
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
export function proxyThroughSsh(client, port, key, path, request, response, basePath = "") {
|
|
48
|
+
const agent = agentFor(client, port);
|
|
49
|
+
const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: headers(request.headers, port, key), agent }, result => {
|
|
50
|
+
const outgoing = { ...result.headers };
|
|
51
|
+
delete outgoing["set-cookie"];
|
|
52
|
+
// The trusted artifact wrapper uses an origin-root URL; keep its inner frame on this backend.
|
|
53
|
+
if (basePath && path.startsWith("/api/message-artifact?") && new URL(path, "http://localhost").searchParams.has("frame") && String(outgoing["content-type"]).startsWith("text/html")) {
|
|
54
|
+
delete outgoing["content-length"];
|
|
55
|
+
let html = "";
|
|
56
|
+
result.setEncoding("utf8");
|
|
57
|
+
result.on("data", chunk => { html += chunk; if (html.length > 1024 * 1024)
|
|
58
|
+
result.destroy(); });
|
|
59
|
+
result.once("end", () => { response.writeHead(result.statusCode ?? 502, outgoing).end(html.replaceAll('src="/api/message-artifact', `src="${basePath}/api/message-artifact`)); agent.destroy(); });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
response.writeHead(result.statusCode ?? 502, outgoing);
|
|
63
|
+
result.pipe(response);
|
|
64
|
+
result.once("end", () => agent.destroy());
|
|
65
|
+
});
|
|
66
|
+
upstream.once("error", () => { agent.destroy(); if (!response.headersSent)
|
|
67
|
+
response.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 隧道暂不可用,正在恢复连接" }));
|
|
68
|
+
else
|
|
69
|
+
response.destroy(); });
|
|
70
|
+
response.once("close", () => { upstream.destroy(); agent.destroy(); });
|
|
71
|
+
request.pipe(upstream);
|
|
72
|
+
}
|
|
73
|
+
export async function proxyWebSocketThroughSsh(client, port, key, path, request, socket, head) {
|
|
74
|
+
const channel = await sshForward(client, port);
|
|
75
|
+
const outgoing = headers(request.headers, port, key);
|
|
76
|
+
channel.write(`GET ${path} HTTP/1.1\r\n${Object.entries(outgoing).filter(([, value]) => value !== undefined).map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(", ") : value}`).join("\r\n")}\r\n\r\n`);
|
|
77
|
+
if (head.length)
|
|
78
|
+
channel.write(head);
|
|
79
|
+
channel.pipe(socket);
|
|
80
|
+
socket.pipe(channel);
|
|
81
|
+
socket.once("close", () => channel.close());
|
|
82
|
+
channel.once("close", () => socket.destroy());
|
|
83
|
+
channel.once("error", () => socket.destroy());
|
|
84
|
+
socket.once("error", () => channel.close());
|
|
85
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { ServerContext } from "./server-context.js";
|
|
3
|
+
/** A model-channel token is deliberately never accepted by these management routes. */
|
|
4
|
+
export declare function handleManagedHttp(context: ServerContext, request: IncomingMessage, response: ServerResponse, url: URL): Promise<boolean>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { isBrowserAuthorized } from "./browser-access.js";
|
|
2
|
+
import { isLoopbackAddress } from "./http-server.js";
|
|
3
|
+
/** A model-channel token is deliberately never accepted by these management routes. */
|
|
4
|
+
export async function handleManagedHttp(context, request, response, url) {
|
|
5
|
+
const route = url.pathname === "/api/managed-servers";
|
|
6
|
+
const proxy = /^\/managed\/([a-f0-9-]+)(\/.*)$/.exec(url.pathname);
|
|
7
|
+
if (!route && !proxy && url.pathname !== "/api/managed-model/reload")
|
|
8
|
+
return false;
|
|
9
|
+
const json = (status, value) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(value)); };
|
|
10
|
+
if (url.pathname === "/api/managed-model/reload") {
|
|
11
|
+
if (!process.env.SUPER_PI_MANAGED_CONFIG) {
|
|
12
|
+
json(404, { error: "当前服务未由本地入口托管" });
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
if (!isBrowserAuthorized(request) || request.method !== "POST") {
|
|
16
|
+
json(403, { error: "需要托管服务的管理授权" });
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
context.runtime.invalidateCatalog?.();
|
|
20
|
+
context.runtime.bumpModelEpoch?.();
|
|
21
|
+
await context.catalogService.broadcastAllCatalog();
|
|
22
|
+
for (const conversation of context.store.snapshot().conversations)
|
|
23
|
+
if (!conversation.archivedAt)
|
|
24
|
+
await context.catalogService.broadcastCatalog(conversation.model, conversation.id);
|
|
25
|
+
json(200, { ok: true });
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
if (!context.managedServers) {
|
|
29
|
+
json(404, { available: false, error: "此纯服务安装不提供 SSH 管理,请在完整包的本地入口中配置" });
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (!isBrowserAuthorized(request) && (!isLoopbackAddress(request.socket.remoteAddress) || (request.headers.origin && request.headers.origin !== url.origin))) {
|
|
33
|
+
json(403, { error: "SSH 托管设置仅允许本地入口或已授权的管理浏览器访问" });
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
if (proxy) {
|
|
37
|
+
const path = proxy[2] + url.search;
|
|
38
|
+
if (!path.startsWith("/api/") && !path.startsWith("/tools/")) {
|
|
39
|
+
json(404, { error: "不支持的托管资源路径" });
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
context.managedServers.proxy(proxy[1], path, request, response);
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
const status = () => ({ available: true, profiles: context.managedServers.list(), connections: context.managedServers.connectionProfiles(), modelSource: "entry" });
|
|
46
|
+
if (request.method === "GET") {
|
|
47
|
+
json(200, status());
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
if (request.method !== "POST") {
|
|
51
|
+
json(405, { error: "仅支持 GET/POST" });
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
let text = "";
|
|
55
|
+
for await (const chunk of request) {
|
|
56
|
+
text += chunk;
|
|
57
|
+
if (text.length > 1024 * 1024) {
|
|
58
|
+
json(413, { error: "SSH 配置过大" });
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
const body = JSON.parse(text);
|
|
64
|
+
if (body.action === "save") {
|
|
65
|
+
await context.managedServers.save(body.profile);
|
|
66
|
+
}
|
|
67
|
+
else if (body.action === "trust")
|
|
68
|
+
await context.managedServers.trust(body.id, body.fingerprint);
|
|
69
|
+
else if (body.action === "syncAll") {
|
|
70
|
+
for (const profile of context.managedServers.list())
|
|
71
|
+
if (profile.enabled && profile.service === "online")
|
|
72
|
+
await context.managedServers.action(profile.id, "sync");
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
if (typeof body.id !== "string")
|
|
76
|
+
throw new Error("请选择服务器");
|
|
77
|
+
await context.managedServers.action(body.id, body.action);
|
|
78
|
+
}
|
|
79
|
+
json(200, status());
|
|
80
|
+
}
|
|
81
|
+
catch (cause) {
|
|
82
|
+
json(400, { ...status(), error: cause instanceof Error ? cause.message : "服务器托管操作失败" });
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
export interface ManagedModelConfig {
|
|
3
|
+
endpoint: string;
|
|
4
|
+
token: string;
|
|
5
|
+
models: Model<string>[];
|
|
6
|
+
defaultModel?: {
|
|
7
|
+
provider: string;
|
|
8
|
+
modelId: string;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export declare function readManagedModelConfig(): Promise<ManagedModelConfig | undefined>;
|
|
12
|
+
/** Both embedded sessions and isolated Pi processes register the same transport-only providers. */
|
|
13
|
+
export declare function managedProviderDefinitions(config: ManagedModelConfig): Promise<{
|
|
14
|
+
id: string;
|
|
15
|
+
provider: import("@earendil-works/pi-ai").Provider<string>;
|
|
16
|
+
}[]>;
|
|
17
|
+
export declare function installManagedModels(runtime: unknown): Promise<void>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
export async function readManagedModelConfig() {
|
|
3
|
+
const path = process.env.SUPER_PI_MANAGED_CONFIG;
|
|
4
|
+
if (!path)
|
|
5
|
+
return;
|
|
6
|
+
const config = JSON.parse(await readFile(path, "utf8"));
|
|
7
|
+
const url = new URL(config.endpoint);
|
|
8
|
+
if (url.hostname !== "127.0.0.1" || url.protocol !== "http:" || !config.token || !Array.isArray(config.models))
|
|
9
|
+
throw new Error("托管模型通道配置无效");
|
|
10
|
+
return config;
|
|
11
|
+
}
|
|
12
|
+
/** Both embedded sessions and isolated Pi processes register the same transport-only providers. */
|
|
13
|
+
export async function managedProviderDefinitions(config) {
|
|
14
|
+
const { createAssistantMessageEventStream, createProvider } = await import("@earendil-works/pi-ai");
|
|
15
|
+
const forward = (model, context, options) => {
|
|
16
|
+
const stream = createAssistantMessageEventStream();
|
|
17
|
+
void (async () => {
|
|
18
|
+
try {
|
|
19
|
+
const latest = await readManagedModelConfig() ?? config;
|
|
20
|
+
const { signal, ...rest } = options ?? {};
|
|
21
|
+
const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) => ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets"].includes(key) && typeof value !== "function"));
|
|
22
|
+
const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json" }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions }) });
|
|
23
|
+
if (!response.ok || !response.body)
|
|
24
|
+
throw new Error(`本地模型通道不可用(${response.status}),请检查管理电脑和 SSH 连接`);
|
|
25
|
+
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
26
|
+
let pending = "", settled = false;
|
|
27
|
+
for (;;) {
|
|
28
|
+
const { done, value } = await reader.read();
|
|
29
|
+
pending += decoder.decode(value, { stream: !done });
|
|
30
|
+
let end;
|
|
31
|
+
while ((end = pending.indexOf("\n")) >= 0) {
|
|
32
|
+
const line = pending.slice(0, end);
|
|
33
|
+
pending = pending.slice(end + 1);
|
|
34
|
+
if (!line)
|
|
35
|
+
continue;
|
|
36
|
+
const event = JSON.parse(line);
|
|
37
|
+
stream.push(event);
|
|
38
|
+
if (event.type === "done" || event.type === "error")
|
|
39
|
+
settled = true;
|
|
40
|
+
}
|
|
41
|
+
if (pending.length > 64 * 1024 * 1024)
|
|
42
|
+
throw new Error("模型通道事件过大");
|
|
43
|
+
if (done) {
|
|
44
|
+
if (!settled)
|
|
45
|
+
throw new Error("模型通道在回复完成前断开,请重连后重试");
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch (cause) {
|
|
51
|
+
const error = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: options?.signal?.aborted ? "aborted" : "error", errorMessage: cause instanceof Error ? cause.message : "模型通道失败", timestamp: Date.now() };
|
|
52
|
+
stream.push({ type: "error", reason: error.stopReason, error });
|
|
53
|
+
}
|
|
54
|
+
})();
|
|
55
|
+
return stream;
|
|
56
|
+
};
|
|
57
|
+
return [...new Set(config.models.map(model => model.provider))].map(provider => ({
|
|
58
|
+
id: provider,
|
|
59
|
+
provider: createProvider({
|
|
60
|
+
id: provider, name: `${provider} · 本地管理`,
|
|
61
|
+
auth: { apiKey: { name: "本地模型通道", resolve: async () => ({ auth: {} }) } },
|
|
62
|
+
models: config.models.filter(model => model.provider === provider).map(model => ({ ...model, baseUrl: config.endpoint, headers: undefined })),
|
|
63
|
+
api: { stream: forward, streamSimple: forward },
|
|
64
|
+
}),
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
export async function installManagedModels(runtime) {
|
|
68
|
+
const config = await readManagedModelConfig();
|
|
69
|
+
if (!config)
|
|
70
|
+
return;
|
|
71
|
+
const target = runtime;
|
|
72
|
+
for (const definition of await managedProviderDefinitions(config))
|
|
73
|
+
target.registerNativeProvider(definition.provider);
|
|
74
|
+
await target.refresh?.();
|
|
75
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
|
|
3
|
+
type Runtime = {
|
|
4
|
+
getAvailable(): Promise<Model<string>[]>;
|
|
5
|
+
getModel(provider: string, id: string): Model<string> | undefined;
|
|
6
|
+
streamSimple(model: Model<string>, context: Context, options?: SimpleStreamOptions): AsyncIterable<unknown>;
|
|
7
|
+
};
|
|
8
|
+
/** Credentials remain in the manager's normal Pi auth store, including OAuth refresh ownership. */
|
|
9
|
+
export declare class ManagedModelGateway {
|
|
10
|
+
private readonly factory?;
|
|
11
|
+
private cached?;
|
|
12
|
+
constructor(factory?: (() => Promise<Runtime>) | undefined);
|
|
13
|
+
private runtime;
|
|
14
|
+
catalog(force?: boolean): Promise<{
|
|
15
|
+
id: string;
|
|
16
|
+
provider: string;
|
|
17
|
+
name: string;
|
|
18
|
+
api: string;
|
|
19
|
+
reasoning: boolean;
|
|
20
|
+
input: ("image" | "text")[];
|
|
21
|
+
cost: {
|
|
22
|
+
input: number;
|
|
23
|
+
output: number;
|
|
24
|
+
cacheRead: number;
|
|
25
|
+
cacheWrite: number;
|
|
26
|
+
tiers?: {
|
|
27
|
+
input: number;
|
|
28
|
+
output: number;
|
|
29
|
+
cacheRead: number;
|
|
30
|
+
cacheWrite: number;
|
|
31
|
+
inputTokensAbove: number;
|
|
32
|
+
}[] | undefined;
|
|
33
|
+
};
|
|
34
|
+
contextWindow: number;
|
|
35
|
+
maxTokens: number;
|
|
36
|
+
thinkingLevelMap: {
|
|
37
|
+
off?: string | null | undefined;
|
|
38
|
+
minimal?: string | null | undefined;
|
|
39
|
+
low?: string | null | undefined;
|
|
40
|
+
medium?: string | null | undefined;
|
|
41
|
+
high?: string | null | undefined;
|
|
42
|
+
xhigh?: string | null | undefined;
|
|
43
|
+
max?: string | null | undefined;
|
|
44
|
+
} | undefined;
|
|
45
|
+
baseUrl: string;
|
|
46
|
+
}[]>;
|
|
47
|
+
handle(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
export {};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { piAgentDir, piAuthPath, piModelsPath } from "./providers.js";
|
|
2
|
+
import { installProviderProxy } from "./provider-proxy.js";
|
|
3
|
+
/** Credentials remain in the manager's normal Pi auth store, including OAuth refresh ownership. */
|
|
4
|
+
export class ManagedModelGateway {
|
|
5
|
+
factory;
|
|
6
|
+
cached;
|
|
7
|
+
constructor(factory) {
|
|
8
|
+
this.factory = factory;
|
|
9
|
+
}
|
|
10
|
+
async runtime(force = false) {
|
|
11
|
+
if (!force && this.cached && Date.now() - this.cached.createdAt < 30_000)
|
|
12
|
+
return this.cached.runtime;
|
|
13
|
+
let runtime;
|
|
14
|
+
if (this.factory)
|
|
15
|
+
runtime = await this.factory();
|
|
16
|
+
else {
|
|
17
|
+
const { ModelRuntime } = await import("@earendil-works/pi-coding-agent");
|
|
18
|
+
const native = await ModelRuntime.create({ authPath: piAuthPath(), modelsPath: piModelsPath() });
|
|
19
|
+
await installProviderProxy(native, piAgentDir());
|
|
20
|
+
runtime = native;
|
|
21
|
+
}
|
|
22
|
+
this.cached = { runtime, createdAt: Date.now() };
|
|
23
|
+
return runtime;
|
|
24
|
+
}
|
|
25
|
+
async catalog(force = false) {
|
|
26
|
+
const runtime = await this.runtime(force);
|
|
27
|
+
return (await runtime.getAvailable()).map(({ id, provider, name, api, reasoning, input, cost, contextWindow, maxTokens, thinkingLevelMap }) => ({ id, provider, name, api, reasoning, input, cost, contextWindow, maxTokens, thinkingLevelMap, baseUrl: "" }));
|
|
28
|
+
}
|
|
29
|
+
async handle(request, response) {
|
|
30
|
+
if (request.method !== "POST") {
|
|
31
|
+
response.writeHead(405).end();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const abort = new AbortController();
|
|
35
|
+
response.once("close", () => { if (!response.writableEnded)
|
|
36
|
+
abort.abort(); });
|
|
37
|
+
try {
|
|
38
|
+
const chunks = [];
|
|
39
|
+
let size = 0;
|
|
40
|
+
for await (const part of request) {
|
|
41
|
+
size += part.length;
|
|
42
|
+
if (size > 32 * 1024 * 1024)
|
|
43
|
+
throw new Error("模型请求超过大小限制");
|
|
44
|
+
chunks.push(part);
|
|
45
|
+
}
|
|
46
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
47
|
+
if (!body.context || typeof body.provider !== "string" || typeof body.modelId !== "string")
|
|
48
|
+
throw new Error("模型请求缺少上下文或模型标识");
|
|
49
|
+
const runtime = await this.runtime();
|
|
50
|
+
const model = (await runtime.getAvailable()).find(model => model.provider === body.provider && model.id === body.modelId);
|
|
51
|
+
if (!model) {
|
|
52
|
+
response.writeHead(404).end("本地没有配置这个模型");
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const allowed = ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets"];
|
|
56
|
+
const options = Object.fromEntries(Object.entries(body.options ?? {}).filter(([key]) => allowed.includes(key)));
|
|
57
|
+
response.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-store", "x-accel-buffering": "no" });
|
|
58
|
+
for await (const event of runtime.streamSimple(model, body.context, { ...options, signal: abort.signal })) {
|
|
59
|
+
if (abort.signal.aborted)
|
|
60
|
+
break;
|
|
61
|
+
if (!response.write(`${JSON.stringify(event)}\n`))
|
|
62
|
+
await new Promise(resolve => { response.once("drain", resolve); response.once("close", resolve); });
|
|
63
|
+
}
|
|
64
|
+
response.end();
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
if (!response.headersSent)
|
|
68
|
+
response.writeHead(502).end("本地模型调用失败,请检查本地模型配置和登录状态");
|
|
69
|
+
else
|
|
70
|
+
response.destroy();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import type { Duplex } from "node:stream";
|
|
3
|
+
import type { Client } from "ssh2";
|
|
4
|
+
import type { ManagedServerInput, ManagedServerProfile } from "../shared/managed-servers.js";
|
|
5
|
+
export declare class ManagedServers {
|
|
6
|
+
private readonly directory;
|
|
7
|
+
private readonly packageRoot;
|
|
8
|
+
private readonly defaultModel;
|
|
9
|
+
private readonly records;
|
|
10
|
+
private readonly clients;
|
|
11
|
+
private readonly secrets;
|
|
12
|
+
private readonly connecting;
|
|
13
|
+
private readonly jobs;
|
|
14
|
+
private readonly recoveries;
|
|
15
|
+
private readonly vault;
|
|
16
|
+
private readonly gateway;
|
|
17
|
+
private gatewayServer?;
|
|
18
|
+
private gatewayPort;
|
|
19
|
+
private timer?;
|
|
20
|
+
private stopped;
|
|
21
|
+
private persistence;
|
|
22
|
+
private artifact?;
|
|
23
|
+
constructor(directory: string, packageRoot: string, defaultModel: () => {
|
|
24
|
+
provider: string;
|
|
25
|
+
modelId: string;
|
|
26
|
+
} | undefined);
|
|
27
|
+
initialize(): Promise<void>;
|
|
28
|
+
list(): ManagedServerProfile[];
|
|
29
|
+
private persist;
|
|
30
|
+
private entry;
|
|
31
|
+
save(input: ManagedServerInput): Promise<ManagedServerProfile>;
|
|
32
|
+
trust(id: string, fingerprint: string): Promise<ManagedServerProfile>;
|
|
33
|
+
connect(id: string): Promise<Client>;
|
|
34
|
+
private reverseModelChannel;
|
|
35
|
+
syncModels(id: string, force?: boolean): Promise<void>;
|
|
36
|
+
private health;
|
|
37
|
+
private ensureService;
|
|
38
|
+
private progress;
|
|
39
|
+
deploy(id: string): ManagedServerProfile;
|
|
40
|
+
action(id: string, action: string): Promise<ManagedServerProfile | undefined>;
|
|
41
|
+
private maintain;
|
|
42
|
+
connectionProfiles(): {
|
|
43
|
+
id: string;
|
|
44
|
+
managedId: string;
|
|
45
|
+
managed: boolean;
|
|
46
|
+
name: string;
|
|
47
|
+
url: string;
|
|
48
|
+
enabled: boolean;
|
|
49
|
+
identity: string | undefined;
|
|
50
|
+
revision: number;
|
|
51
|
+
}[];
|
|
52
|
+
proxy(id: string, path: string, request: IncomingMessage, response: ServerResponse): void;
|
|
53
|
+
upgrade(id: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
|
|
54
|
+
close(): Promise<void>;
|
|
55
|
+
}
|