@evandu/super-pi 0.1.289 → 0.1.291
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 +6 -5
- package/dist/client/assets/{CodeMirrorEditor-BQEK9QVa.js → CodeMirrorEditor-BItIClMY.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-jen_6W68.js → GitDiffEditor-CgWWgUsi.js} +1 -1
- package/dist/client/assets/index-C3aSjjM8.css +1 -0
- package/dist/client/assets/{index-C7o39I4j.js → index-Cwt3-oUx.js} +30 -30
- package/dist/client/index.html +2 -2
- package/dist/server/managed-http.js +1 -1
- package/dist/server/managed-model-adapter.js +101 -30
- package/dist/server/managed-model-flow.d.ts +20 -0
- package/dist/server/managed-model-flow.js +94 -0
- package/dist/server/managed-model-gateway.d.ts +6 -1
- package/dist/server/managed-model-gateway.js +95 -13
- package/dist/server/managed-model-relay.d.ts +1 -0
- package/dist/server/managed-model-relay.js +63 -11
- package/dist/server/managed-model-wire.d.ts +20 -0
- package/dist/server/managed-model-wire.js +82 -0
- package/dist/server/managed-recovery.d.ts +10 -0
- package/dist/server/managed-recovery.js +113 -0
- package/dist/server/managed-servers.d.ts +10 -2
- package/dist/server/managed-servers.js +116 -9
- package/dist/server/remote-bootstrap.d.ts +3 -0
- package/dist/server/remote-bootstrap.js +11 -1
- package/dist/server/turn-failure.js +1 -1
- package/dist/shared/managed-servers.d.ts +16 -0
- package/package.json +5 -1
- package/dist/.super-pi-check-inputs.json +0 -4
- package/dist/client/assets/index-dkbN-Swt.css +0 -1
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="alternate icon" href="/favicon.ico" />
|
|
9
9
|
<link rel="apple-touch-icon" href="/favicon.svg" />
|
|
10
10
|
<title>Super Pi</title>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-Cwt3-oUx.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-C3aSjjM8.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -133,7 +133,7 @@ export async function handleManagedHttp(context, request, response, url) {
|
|
|
133
133
|
else {
|
|
134
134
|
if (typeof body.id !== "string")
|
|
135
135
|
throw new Error("请选择服务器");
|
|
136
|
-
await context.managedServers.action(body.id, body.action);
|
|
136
|
+
await context.managedServers.action(body.id, body.action, body.instanceId);
|
|
137
137
|
}
|
|
138
138
|
json(200, status());
|
|
139
139
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { MODEL_OPTION_KEYS, MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId } from "./managed-model-flow.js";
|
|
3
|
+
import { MODEL_STREAM_PROTOCOL, ModelWireDecoder } from "./managed-model-wire.js";
|
|
2
4
|
export async function readManagedModelConfig() {
|
|
3
5
|
const path = process.env.SUPER_PI_MANAGED_CONFIG;
|
|
4
6
|
if (!path)
|
|
@@ -9,56 +11,125 @@ export async function readManagedModelConfig() {
|
|
|
9
11
|
throw new Error("托管模型通道配置无效");
|
|
10
12
|
return config;
|
|
11
13
|
}
|
|
14
|
+
function transportDetail(cause) {
|
|
15
|
+
const failure = cause;
|
|
16
|
+
const value = failure?.cause?.code ?? failure?.code;
|
|
17
|
+
const code = typeof value === "string" && /^[A-Z][A-Z0-9_]{1,60}$/.test(value) ? value : "";
|
|
18
|
+
return { code: code ? `(${code})` : "", timedOut: /TIMEOUT|TIMEDOUT/.test(code) };
|
|
19
|
+
}
|
|
20
|
+
function httpFailure(status) {
|
|
21
|
+
const label = `模型通道请求失败(HTTP ${status})`;
|
|
22
|
+
if (status === 401 || status === 403)
|
|
23
|
+
return `${label}:服务拒绝了通道鉴权。请在入口电脑的服务器连接中检查此服务器的配对配置。`;
|
|
24
|
+
if (status === 404)
|
|
25
|
+
return `${label}:未找到所选模型或通道接口。请同步模型配置;若仍失败,请检查两端 Super Pi 的版本。`;
|
|
26
|
+
if (status === 503)
|
|
27
|
+
return `${label}:通道尚未就绪或正在处理过多请求。请保持入口电脑的 Super Pi 服务运行,等待自动重连或当前请求结束后重试。`;
|
|
28
|
+
if (status === 429)
|
|
29
|
+
return `${label}:请求被限流。请稍后重试,或减少同时执行的模型请求。`;
|
|
30
|
+
if (status === 502)
|
|
31
|
+
return `${label}:入口转发请求失败,未提供详细原因。请检查入口电脑的服务运行状态和模型配置后重试。`;
|
|
32
|
+
return `${label}:未取得有效模型响应。请检查入口电脑的服务与模型配置后重试。`;
|
|
33
|
+
}
|
|
12
34
|
/** Both embedded sessions and isolated Pi processes register the same transport-only providers. */
|
|
13
35
|
export async function managedProviderDefinitions(config) {
|
|
14
36
|
const { createAssistantMessageEventStream, createProvider } = await import("@earendil-works/pi-ai");
|
|
15
37
|
const forward = (model, context, options) => {
|
|
16
38
|
const stream = createAssistantMessageEventStream();
|
|
17
39
|
void (async () => {
|
|
40
|
+
let partial;
|
|
41
|
+
const requestId = modelRequestId(), trace = new ModelFlowTrace(requestId, "remote-adapter");
|
|
42
|
+
const identified = (message) => message.includes("请求编号:") ? message : `${message} 请求编号:${requestId}`;
|
|
43
|
+
const wire = new ModelWireDecoder();
|
|
44
|
+
let endReason = "failed";
|
|
45
|
+
trace.record("request", 0, true);
|
|
18
46
|
try {
|
|
19
47
|
const latest = await readManagedModelConfig() ?? config;
|
|
20
48
|
const { signal, ...rest } = options ?? {};
|
|
21
|
-
const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) =>
|
|
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 }) }).catch(cause => {
|
|
49
|
+
const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) => MODEL_OPTION_KEYS.includes(key) && typeof value !== "function"));
|
|
50
|
+
const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json", [MODEL_REQUEST_HEADER]: requestId }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions, streamProtocol: MODEL_STREAM_PROTOCOL }) }).catch(cause => {
|
|
23
51
|
if (signal?.aborted)
|
|
24
52
|
throw cause;
|
|
25
|
-
|
|
53
|
+
const detail = transportDetail(cause);
|
|
54
|
+
throw new Error(`本地模型通道未连接:${detail.timedOut ? "等待入口响应超时" : "请求尚未收到入口响应"}${detail.code}。请确认入口电脑的 Super Pi 服务正在运行,并检查入口与远端的连接;恢复后重试。`, { cause });
|
|
26
55
|
});
|
|
27
|
-
if (!response.ok || !response.body)
|
|
28
|
-
|
|
56
|
+
if (!response.ok || !response.body) {
|
|
57
|
+
const body = await response.json().catch(() => undefined);
|
|
58
|
+
throw new Error(typeof body?.error === "string" ? body.error : httpFailure(response.status));
|
|
59
|
+
}
|
|
29
60
|
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
30
|
-
let pending = ""
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const line = pending.slice(0, end);
|
|
41
|
-
pending = pending.slice(end + 1);
|
|
42
|
-
if (!line)
|
|
43
|
-
continue;
|
|
44
|
-
const event = JSON.parse(line);
|
|
45
|
-
stream.push(event);
|
|
46
|
-
if (event.type === "done" || event.type === "error")
|
|
47
|
-
settled = true;
|
|
48
|
-
}
|
|
49
|
-
if (pending.length > 64 * 1024 * 1024)
|
|
61
|
+
let pending = "";
|
|
62
|
+
const retained = () => partial?.content.length ? "已保留收到的模型内容。" : "尚未收到可保留的模型内容。";
|
|
63
|
+
const disconnected = (cause) => {
|
|
64
|
+
const detail = transportDetail(cause);
|
|
65
|
+
return new Error(`模型通道在回复完成前断开:${detail.timedOut ? "读取回复超时" : "读取回复时连接中断"}${detail.code}。${retained()}具体断开原因未确认,请检查入口电脑的服务运行状态和入口与远端的连接,恢复后重试。`, { cause });
|
|
66
|
+
};
|
|
67
|
+
const consume = (line) => {
|
|
68
|
+
if (!line.trim())
|
|
69
|
+
return false;
|
|
70
|
+
if (line.length > 64 * 1024 * 1024)
|
|
50
71
|
throw new Error("模型通道事件过大");
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
72
|
+
let event;
|
|
73
|
+
try {
|
|
74
|
+
event = wire.decode(JSON.parse(line));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new Error(`模型通道返回了无法解析的事件。${retained()}请检查两端 Super Pi 的版本和模型兼容性后重试。`);
|
|
78
|
+
}
|
|
79
|
+
if ("partial" in event)
|
|
80
|
+
partial = event.partial;
|
|
81
|
+
if (event.type === "error" && event.reason !== "aborted" && typeof event.error?.errorMessage === "string"
|
|
82
|
+
&& !/^(入口模型|模型通道|本地模型通道)/.test(event.error.errorMessage)) {
|
|
83
|
+
event.error = { ...event.error, errorMessage: `入口模型调用失败(${model.provider}/${model.id}):${event.error.errorMessage}` };
|
|
84
|
+
}
|
|
85
|
+
if (event.type === "error" && event.reason !== "aborted")
|
|
86
|
+
event.error = { ...event.error, errorMessage: identified(event.error.errorMessage ?? "入口模型调用失败,未提供详细原因。") };
|
|
87
|
+
stream.push(event);
|
|
88
|
+
trace.record("session-event", Buffer.byteLength(line));
|
|
89
|
+
const terminal = event.type === "done" || event.type === "error";
|
|
90
|
+
if (terminal)
|
|
91
|
+
endReason = event.type;
|
|
92
|
+
return terminal;
|
|
93
|
+
};
|
|
94
|
+
try {
|
|
95
|
+
for (;;) {
|
|
96
|
+
const { done, value } = await reader.read().catch(cause => {
|
|
97
|
+
if (signal?.aborted)
|
|
98
|
+
throw cause;
|
|
99
|
+
throw disconnected(cause);
|
|
100
|
+
});
|
|
101
|
+
if (value)
|
|
102
|
+
trace.record("http-receive", value.byteLength);
|
|
103
|
+
pending += decoder.decode(value, { stream: !done });
|
|
104
|
+
let end;
|
|
105
|
+
while ((end = pending.indexOf("\n")) >= 0) {
|
|
106
|
+
const line = pending.slice(0, end);
|
|
107
|
+
pending = pending.slice(end + 1);
|
|
108
|
+
if (consume(line))
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (pending.length > 64 * 1024 * 1024)
|
|
112
|
+
throw new Error("模型通道事件过大");
|
|
113
|
+
if (done) {
|
|
114
|
+
if (consume(pending))
|
|
115
|
+
return;
|
|
116
|
+
throw new Error(`模型通道响应已结束,但没有收到完成标记。${retained()}无法确认本轮回复是否完整,请重试;若反复出现,请检查两端 Super Pi 的版本和模型兼容性。`);
|
|
117
|
+
}
|
|
55
118
|
}
|
|
56
119
|
}
|
|
120
|
+
finally {
|
|
121
|
+
void reader.cancel().catch(() => { });
|
|
122
|
+
reader.releaseLock();
|
|
123
|
+
}
|
|
57
124
|
}
|
|
58
125
|
catch (cause) {
|
|
59
|
-
const
|
|
126
|
+
const reason = cause instanceof Error ? cause.message : "模型通道失败";
|
|
127
|
+
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 } }, ...partial, stopReason: options?.signal?.aborted ? "aborted" : "error", errorMessage: options?.signal?.aborted ? reason : identified(reason), timestamp: partial?.timestamp ?? Date.now() };
|
|
60
128
|
stream.push({ type: "error", reason: error.stopReason, error });
|
|
61
129
|
}
|
|
130
|
+
finally {
|
|
131
|
+
trace.finish(options?.signal?.aborted ? "aborted" : endReason);
|
|
132
|
+
}
|
|
62
133
|
})();
|
|
63
134
|
return stream;
|
|
64
135
|
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
export declare const MODEL_REQUEST_HEADER = "x-super-pi-model-request-id";
|
|
3
|
+
export declare const DEFAULT_MODEL_IDLE_MS = 300000;
|
|
4
|
+
export declare const MODEL_OPTION_KEYS: string[];
|
|
5
|
+
export declare function modelRequestId(value?: unknown): string;
|
|
6
|
+
/** Deliberately accepts numeric measurements and fixed labels, never model payloads. */
|
|
7
|
+
export declare class ModelFlowTrace {
|
|
8
|
+
readonly requestId: string;
|
|
9
|
+
private readonly side;
|
|
10
|
+
private last;
|
|
11
|
+
private sequence;
|
|
12
|
+
private bytes;
|
|
13
|
+
constructor(requestId: string, side: string);
|
|
14
|
+
record(stage: string, bytes?: number, force?: boolean, reason?: string): void;
|
|
15
|
+
finish(reason: string): void;
|
|
16
|
+
}
|
|
17
|
+
/** A drained buffer can precede subscription to drain; recheck state as well as events. */
|
|
18
|
+
export declare function writeModelChunk(response: ServerResponse, chunk: string, signal: AbortSignal, timeoutMs?: number): Promise<void>;
|
|
19
|
+
/** Cancellation must settle even if an upstream iterator ignores AbortSignal. */
|
|
20
|
+
export declare function nextModelEvent<T>(iterator: AsyncIterator<T>, signal: AbortSignal): Promise<IteratorResult<T>>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
export const MODEL_REQUEST_HEADER = "x-super-pi-model-request-id";
|
|
3
|
+
export const DEFAULT_MODEL_IDLE_MS = 300_000;
|
|
4
|
+
export const MODEL_OPTION_KEYS = ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets", "timeoutMs", "websocketConnectTimeoutMs", "maxRetries", "maxRetryDelayMs", "transport"];
|
|
5
|
+
export function modelRequestId(value) {
|
|
6
|
+
return typeof value === "string" && /^[a-f0-9-]{36}$/i.test(value) ? value : randomUUID();
|
|
7
|
+
}
|
|
8
|
+
/** Deliberately accepts numeric measurements and fixed labels, never model payloads. */
|
|
9
|
+
export class ModelFlowTrace {
|
|
10
|
+
requestId;
|
|
11
|
+
side;
|
|
12
|
+
last = new Map();
|
|
13
|
+
sequence = new Map();
|
|
14
|
+
bytes = new Map();
|
|
15
|
+
constructor(requestId, side) {
|
|
16
|
+
this.requestId = requestId;
|
|
17
|
+
this.side = side;
|
|
18
|
+
}
|
|
19
|
+
record(stage, bytes = 0, force = false, reason) {
|
|
20
|
+
const seq = (this.sequence.get(stage) ?? 0) + 1;
|
|
21
|
+
const total = (this.bytes.get(stage) ?? 0) + bytes;
|
|
22
|
+
this.sequence.set(stage, seq);
|
|
23
|
+
this.bytes.set(stage, total);
|
|
24
|
+
const now = Date.now();
|
|
25
|
+
if (!force && now - (this.last.get(stage) ?? 0) < 5000)
|
|
26
|
+
return;
|
|
27
|
+
this.last.set(stage, now);
|
|
28
|
+
console.info("Super Pi model flow", JSON.stringify({ requestId: this.requestId, side: this.side, stage, seq, bytes: total, at: new Date(now).toISOString(), ...(reason ? { reason } : {}) }));
|
|
29
|
+
}
|
|
30
|
+
finish(reason) {
|
|
31
|
+
const at = new Date().toISOString();
|
|
32
|
+
for (const [stage, seq] of this.sequence) {
|
|
33
|
+
if (stage === "end")
|
|
34
|
+
continue;
|
|
35
|
+
console.info("Super Pi model flow", JSON.stringify({ requestId: this.requestId, side: this.side, stage: `${stage}-total`, seq, bytes: this.bytes.get(stage) ?? 0, at }));
|
|
36
|
+
}
|
|
37
|
+
this.record("end", 0, true, reason);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** A drained buffer can precede subscription to drain; recheck state as well as events. */
|
|
41
|
+
export async function writeModelChunk(response, chunk, signal, timeoutMs = 30_000) {
|
|
42
|
+
if (signal.aborted)
|
|
43
|
+
throw signal.reason ?? new Error("Model request aborted");
|
|
44
|
+
if (response.destroyed || response.writableEnded)
|
|
45
|
+
throw new Error("Model response closed");
|
|
46
|
+
if (response.write(chunk))
|
|
47
|
+
return;
|
|
48
|
+
await new Promise((resolve, reject) => {
|
|
49
|
+
let poll, timeout;
|
|
50
|
+
const finish = (error) => {
|
|
51
|
+
clearInterval(poll);
|
|
52
|
+
clearTimeout(timeout);
|
|
53
|
+
response.off("drain", drained);
|
|
54
|
+
response.off("close", closed);
|
|
55
|
+
response.off("error", failed);
|
|
56
|
+
signal.removeEventListener("abort", aborted);
|
|
57
|
+
if (error)
|
|
58
|
+
reject(error);
|
|
59
|
+
else
|
|
60
|
+
resolve();
|
|
61
|
+
};
|
|
62
|
+
const drained = () => finish();
|
|
63
|
+
const closed = () => finish(new Error("Model response closed while waiting for drain"));
|
|
64
|
+
const failed = (error) => finish(error);
|
|
65
|
+
const aborted = () => finish(signal.reason instanceof Error ? signal.reason : new Error("Model request aborted"));
|
|
66
|
+
const check = () => {
|
|
67
|
+
if (signal.aborted)
|
|
68
|
+
aborted();
|
|
69
|
+
else if (response.destroyed || response.writableEnded)
|
|
70
|
+
closed();
|
|
71
|
+
else if (response.writableLength === 0 || response.writableNeedDrain === false)
|
|
72
|
+
drained();
|
|
73
|
+
};
|
|
74
|
+
response.once("drain", drained);
|
|
75
|
+
response.once("close", closed);
|
|
76
|
+
response.once("error", failed);
|
|
77
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
78
|
+
poll = setInterval(check, 50);
|
|
79
|
+
timeout = setTimeout(() => finish(new Error("入口模型转发写入超时:下游持续未能接收数据,请检查入口与远端的连接后重试。")), timeoutMs);
|
|
80
|
+
check();
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** Cancellation must settle even if an upstream iterator ignores AbortSignal. */
|
|
84
|
+
export function nextModelEvent(iterator, signal) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
const aborted = () => { signal.removeEventListener("abort", aborted); reject(signal.reason ?? new Error("Model request aborted")); };
|
|
87
|
+
if (signal.aborted) {
|
|
88
|
+
aborted();
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
signal.addEventListener("abort", aborted, { once: true });
|
|
92
|
+
Promise.resolve().then(() => iterator.next()).then(value => { signal.removeEventListener("abort", aborted); resolve(value); }, error => { signal.removeEventListener("abort", aborted); reject(error); });
|
|
93
|
+
});
|
|
94
|
+
}
|
|
@@ -8,8 +8,13 @@ type Runtime = {
|
|
|
8
8
|
/** Credentials remain in the manager's normal Pi auth store, including OAuth refresh ownership. */
|
|
9
9
|
export declare class ManagedModelGateway {
|
|
10
10
|
private readonly factory?;
|
|
11
|
+
private readonly transport;
|
|
11
12
|
private cached?;
|
|
12
|
-
constructor(factory?: (() => Promise<Runtime>) | undefined
|
|
13
|
+
constructor(factory?: (() => Promise<Runtime>) | undefined, transport?: {
|
|
14
|
+
heartbeatMs?: number;
|
|
15
|
+
idleTimeoutMs?: number;
|
|
16
|
+
writeTimeoutMs?: number;
|
|
17
|
+
});
|
|
13
18
|
private runtime;
|
|
14
19
|
catalog(force?: boolean): Promise<{
|
|
15
20
|
id: string;
|
|
@@ -1,11 +1,16 @@
|
|
|
1
|
+
import { DEFAULT_MODEL_IDLE_MS, MODEL_OPTION_KEYS, MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId, nextModelEvent, writeModelChunk } from "./managed-model-flow.js";
|
|
2
|
+
import { MODEL_STREAM_PROTOCOL, ModelWireEncoder } from "./managed-model-wire.js";
|
|
3
|
+
import { describeThrown } from "./failure-text.js";
|
|
1
4
|
import { piAgentDir, piAuthPath, piModelsPath } from "./providers.js";
|
|
2
5
|
import { installProviderProxy } from "./provider-proxy.js";
|
|
3
6
|
/** Credentials remain in the manager's normal Pi auth store, including OAuth refresh ownership. */
|
|
4
7
|
export class ManagedModelGateway {
|
|
5
8
|
factory;
|
|
9
|
+
transport;
|
|
6
10
|
cached;
|
|
7
|
-
constructor(factory) {
|
|
11
|
+
constructor(factory, transport = {}) {
|
|
8
12
|
this.factory = factory;
|
|
13
|
+
this.transport = transport;
|
|
9
14
|
}
|
|
10
15
|
async runtime(force = false) {
|
|
11
16
|
if (!force && this.cached && Date.now() - this.cached.createdAt < 30_000)
|
|
@@ -32,8 +37,17 @@ export class ManagedModelGateway {
|
|
|
32
37
|
return;
|
|
33
38
|
}
|
|
34
39
|
const abort = new AbortController();
|
|
35
|
-
|
|
36
|
-
|
|
40
|
+
const requestId = modelRequestId(request.headers[MODEL_REQUEST_HEADER]);
|
|
41
|
+
const trace = new ModelFlowTrace(requestId, "entry-gateway");
|
|
42
|
+
response.setHeader(MODEL_REQUEST_HEADER, requestId);
|
|
43
|
+
trace.record("request", 0, true);
|
|
44
|
+
let heartbeat;
|
|
45
|
+
let idleTimer, idleExpired = false;
|
|
46
|
+
let iterator, stage = "prepare", endReason = "incomplete";
|
|
47
|
+
let model, partial, settled = false;
|
|
48
|
+
const onClose = () => { clearInterval(heartbeat); clearTimeout(idleTimer); if (!response.writableEnded)
|
|
49
|
+
abort.abort(); };
|
|
50
|
+
response.once("close", onClose);
|
|
37
51
|
try {
|
|
38
52
|
const chunks = [];
|
|
39
53
|
let size = 0;
|
|
@@ -47,27 +61,95 @@ export class ManagedModelGateway {
|
|
|
47
61
|
if (!body.context || typeof body.provider !== "string" || typeof body.modelId !== "string")
|
|
48
62
|
throw new Error("模型请求缺少上下文或模型标识");
|
|
49
63
|
const runtime = await this.runtime();
|
|
50
|
-
|
|
64
|
+
model = (await runtime.getAvailable()).find(model => model.provider === body.provider && model.id === body.modelId);
|
|
51
65
|
if (!model) {
|
|
66
|
+
endReason = "model-not-found";
|
|
52
67
|
response.writeHead(404).end("本地没有配置这个模型");
|
|
53
68
|
return;
|
|
54
69
|
}
|
|
55
|
-
const
|
|
56
|
-
const
|
|
70
|
+
const options = Object.fromEntries(Object.entries(body.options ?? {}).filter(([key]) => MODEL_OPTION_KEYS.includes(key)));
|
|
71
|
+
const timeoutMs = options.timeoutMs ?? this.transport.idleTimeoutMs ?? DEFAULT_MODEL_IDLE_MS;
|
|
72
|
+
if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0)
|
|
73
|
+
throw new Error("timeoutMs 必须是大于等于零的有限数字。");
|
|
74
|
+
options.timeoutMs = timeoutMs;
|
|
75
|
+
const armIdle = () => {
|
|
76
|
+
clearTimeout(idleTimer);
|
|
77
|
+
if (!timeoutMs)
|
|
78
|
+
return;
|
|
79
|
+
idleTimer = setTimeout(() => {
|
|
80
|
+
idleExpired = true;
|
|
81
|
+
abort.abort(new Error(`入口模型等待超时:连续 ${Math.ceil(timeoutMs / 1000)} 秒没有收到上游模型事件。模型通道连接仍在线也可能发生此情况;已保留收到的内容,请重试或更换模型。请求编号:${requestId}`));
|
|
82
|
+
}, timeoutMs);
|
|
83
|
+
};
|
|
84
|
+
const encoder = body.streamProtocol === MODEL_STREAM_PROTOCOL ? new ModelWireEncoder() : undefined;
|
|
57
85
|
response.writeHead(200, { "content-type": "application/x-ndjson", "cache-control": "no-store", "x-accel-buffering": "no" });
|
|
58
|
-
|
|
59
|
-
|
|
86
|
+
response.flushHeaders();
|
|
87
|
+
// WebSocket ping does not keep the loopback HTTP body alive while a model is silent.
|
|
88
|
+
heartbeat = setInterval(() => {
|
|
89
|
+
if (!response.destroyed && !response.writableEnded && response.writableLength === 0)
|
|
90
|
+
response.write("\n");
|
|
91
|
+
}, Math.max(10, this.transport.heartbeatMs ?? 15_000));
|
|
92
|
+
heartbeat.unref();
|
|
93
|
+
iterator = runtime.streamSimple(model, body.context, { ...options, signal: abort.signal,
|
|
94
|
+
onProviderStreamEvent: () => { trace.record("provider-event"); if (stage === "upstream-next")
|
|
95
|
+
armIdle(); },
|
|
96
|
+
})[Symbol.asyncIterator]();
|
|
97
|
+
for (;;) {
|
|
98
|
+
stage = "upstream-next";
|
|
99
|
+
armIdle();
|
|
100
|
+
const next = await nextModelEvent(iterator, abort.signal);
|
|
101
|
+
clearTimeout(idleTimer);
|
|
102
|
+
if (next.done)
|
|
60
103
|
break;
|
|
61
|
-
|
|
62
|
-
|
|
104
|
+
const event = next.value;
|
|
105
|
+
trace.record("upstream-event");
|
|
106
|
+
const value = event;
|
|
107
|
+
if (value.partial)
|
|
108
|
+
partial = value.partial;
|
|
109
|
+
const terminal = value.type === "done" || value.type === "error";
|
|
110
|
+
const line = `${JSON.stringify(encoder ? encoder.encode(event) : event)}\n`;
|
|
111
|
+
stage = "http-write";
|
|
112
|
+
trace.record("http-write-begin", Buffer.byteLength(line));
|
|
113
|
+
const waitStarted = Date.now();
|
|
114
|
+
await writeModelChunk(response, line, abort.signal, this.transport.writeTimeoutMs);
|
|
115
|
+
trace.record("http-write-complete", Buffer.byteLength(line), Date.now() - waitStarted > 1000);
|
|
116
|
+
if (terminal) {
|
|
117
|
+
settled = true;
|
|
118
|
+
endReason = `${value.type}-${["stop", "length", "toolUse", "deferred", "aborted", "error"].includes(value.reason ?? "") ? value.reason : "unknown"}`;
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
63
121
|
}
|
|
122
|
+
if (!settled && !abort.signal.aborted)
|
|
123
|
+
throw new Error("入口模型流未返回完成事件,请检查供应商连接后重试。");
|
|
64
124
|
response.end();
|
|
65
125
|
}
|
|
66
|
-
catch {
|
|
126
|
+
catch (cause) {
|
|
127
|
+
endReason = idleExpired ? "upstream-idle-timeout" : abort.signal.aborted ? "canceled" : `${stage}-failed`;
|
|
128
|
+
if ((abort.signal.aborted && !idleExpired) || response.destroyed || response.writableEnded)
|
|
129
|
+
return;
|
|
130
|
+
const reason = describeThrown(cause) || "未提供详细原因,请检查供应商配置和登录状态。";
|
|
131
|
+
const errorMessage = /^(入口模型|模型通道)/.test(reason) ? reason : model
|
|
132
|
+
? `入口模型调用失败(${model.provider}/${model.id}):${reason}`
|
|
133
|
+
: `入口模型准备失败:${reason}`;
|
|
67
134
|
if (!response.headersSent)
|
|
68
|
-
response.writeHead(502).end(
|
|
135
|
+
response.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: errorMessage }));
|
|
136
|
+
else if (model && !settled) {
|
|
137
|
+
const error = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id,
|
|
138
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
139
|
+
...partial, stopReason: "error", errorMessage, timestamp: partial?.timestamp ?? Date.now() };
|
|
140
|
+
response.end(`${JSON.stringify({ type: "error", reason: "error", error })}\n`);
|
|
141
|
+
}
|
|
69
142
|
else
|
|
70
|
-
response.
|
|
143
|
+
response.end();
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
clearInterval(heartbeat);
|
|
147
|
+
clearTimeout(idleTimer);
|
|
148
|
+
response.off("close", onClose);
|
|
149
|
+
if (!settled)
|
|
150
|
+
abort.abort();
|
|
151
|
+
void iterator?.return?.().catch(() => { });
|
|
152
|
+
trace.finish(endReason);
|
|
71
153
|
}
|
|
72
154
|
}
|
|
73
155
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { WebSocket } from "ws";
|
|
3
|
+
import { MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId } from "./managed-model-flow.js";
|
|
3
4
|
// Only model requests cross this connection. The destination and credential are
|
|
4
5
|
// selected by the manager and never taken from a remote request.
|
|
5
6
|
const maxRequest = 32 * 1024 * 1024;
|
|
@@ -7,6 +8,7 @@ const maxConcurrent = 32;
|
|
|
7
8
|
export class ModelRelay {
|
|
8
9
|
socket;
|
|
9
10
|
requests = new Map();
|
|
11
|
+
traces = new Map();
|
|
10
12
|
waiting = new Set();
|
|
11
13
|
close() {
|
|
12
14
|
this.socket?.terminate();
|
|
@@ -18,14 +20,20 @@ export class ModelRelay {
|
|
|
18
20
|
for (const response of this.requests.values())
|
|
19
21
|
response.destroy();
|
|
20
22
|
this.requests.clear();
|
|
23
|
+
for (const trace of this.traces.values())
|
|
24
|
+
trace.finish("channel-replaced");
|
|
25
|
+
this.traces.clear();
|
|
21
26
|
this.socket = socket;
|
|
22
27
|
for (const resume of this.waiting)
|
|
23
28
|
resume();
|
|
24
29
|
socket.on("error", () => socket.terminate());
|
|
25
|
-
socket.on("close",
|
|
30
|
+
socket.on("close", code => {
|
|
26
31
|
if (this.socket !== socket)
|
|
27
32
|
return;
|
|
28
33
|
this.socket = undefined;
|
|
34
|
+
for (const trace of this.traces.values())
|
|
35
|
+
trace.finish(`channel-closed-${code}`);
|
|
36
|
+
this.traces.clear();
|
|
29
37
|
for (const response of this.requests.values())
|
|
30
38
|
response.destroy();
|
|
31
39
|
this.requests.clear();
|
|
@@ -38,19 +46,34 @@ export class ModelRelay {
|
|
|
38
46
|
const response = this.requests.get(id);
|
|
39
47
|
if (!response)
|
|
40
48
|
return;
|
|
41
|
-
|
|
49
|
+
const trace = this.traces.get(id);
|
|
50
|
+
if (type === "start") {
|
|
42
51
|
response.writeHead(status, { "content-type": contentType === "application/json" ? contentType : "application/x-ndjson", "cache-control": "no-store" });
|
|
52
|
+
response.flushHeaders();
|
|
53
|
+
trace?.record("response-start", 0, true);
|
|
54
|
+
}
|
|
43
55
|
else if (type === "data") {
|
|
44
|
-
|
|
56
|
+
const chunk = Buffer.from(data, "base64");
|
|
57
|
+
trace?.record("ws-receive", chunk.length);
|
|
58
|
+
if (response.writableLength > maxRequest) {
|
|
59
|
+
trace?.finish("downstream-buffer-limit");
|
|
60
|
+
this.traces.delete(id);
|
|
45
61
|
response.destroy();
|
|
46
|
-
|
|
47
|
-
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
response.write(chunk);
|
|
65
|
+
trace?.record("http-write", chunk.length);
|
|
66
|
+
}
|
|
48
67
|
}
|
|
49
68
|
else if (type === "end") {
|
|
69
|
+
trace?.finish("http-end");
|
|
70
|
+
this.traces.delete(id);
|
|
50
71
|
this.requests.delete(id);
|
|
51
72
|
response.end();
|
|
52
73
|
}
|
|
53
74
|
else if (type === "error") {
|
|
75
|
+
trace?.finish("entry-forward-error");
|
|
76
|
+
this.traces.delete(id);
|
|
54
77
|
this.requests.delete(id);
|
|
55
78
|
if (response.headersSent)
|
|
56
79
|
response.destroy();
|
|
@@ -102,9 +125,17 @@ export class ModelRelay {
|
|
|
102
125
|
response.writeHead(503).end();
|
|
103
126
|
return;
|
|
104
127
|
}
|
|
105
|
-
|
|
128
|
+
let id = modelRequestId(request.headers[MODEL_REQUEST_HEADER]);
|
|
129
|
+
if (this.requests.has(id))
|
|
130
|
+
id = randomUUID();
|
|
131
|
+
const trace = new ModelFlowTrace(id, "remote-relay");
|
|
132
|
+
this.traces.set(id, trace);
|
|
133
|
+
response.setHeader(MODEL_REQUEST_HEADER, id);
|
|
134
|
+
trace.record("request", Buffer.concat(parts).length, true);
|
|
106
135
|
this.requests.set(id, response);
|
|
107
136
|
response.once("close", () => {
|
|
137
|
+
this.traces.get(id)?.finish("response-closed");
|
|
138
|
+
this.traces.delete(id);
|
|
108
139
|
if (this.requests.delete(id) && socket.readyState === WebSocket.OPEN)
|
|
109
140
|
socket.send(JSON.stringify({ type: "cancel", id }));
|
|
110
141
|
});
|
|
@@ -134,7 +165,20 @@ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
|
|
|
134
165
|
socket.on("error", () => socket.terminate());
|
|
135
166
|
socket.on("close", () => { clearInterval(heartbeat); for (const controller of active.values())
|
|
136
167
|
controller.abort(); });
|
|
137
|
-
const send = (value) => new Promise((resolve, reject) =>
|
|
168
|
+
const send = (value, signal) => new Promise((resolve, reject) => {
|
|
169
|
+
const finish = (error) => { clearTimeout(timer); signal?.removeEventListener("abort", aborted); if (error)
|
|
170
|
+
reject(error);
|
|
171
|
+
else
|
|
172
|
+
resolve(); };
|
|
173
|
+
const aborted = () => finish(new Error("Model relay request aborted"));
|
|
174
|
+
const timer = setTimeout(() => finish(new Error("Model relay WebSocket send timed out")), 30_000);
|
|
175
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
176
|
+
if (signal?.aborted) {
|
|
177
|
+
aborted();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
socket.send(JSON.stringify(value), error => finish(error));
|
|
181
|
+
});
|
|
138
182
|
socket.on("message", async (raw) => {
|
|
139
183
|
let message;
|
|
140
184
|
try {
|
|
@@ -158,25 +202,33 @@ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
|
|
|
158
202
|
return;
|
|
159
203
|
}
|
|
160
204
|
const controller = new AbortController();
|
|
205
|
+
const trace = new ModelFlowTrace(modelRequestId(id), "entry-relay");
|
|
206
|
+
trace.record("request", Buffer.byteLength(body, "base64"), true);
|
|
161
207
|
active.set(id, controller);
|
|
208
|
+
let endReason = "forward-error";
|
|
162
209
|
try {
|
|
163
|
-
const result = await fetch(`http://127.0.0.1:${gatewayPort}${path}`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
|
|
164
|
-
await send({ id, type: "start", status: result.status, contentType: result.headers.get("content-type") });
|
|
210
|
+
const result = await fetch(`http://127.0.0.1:${gatewayPort}${path}`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json", [MODEL_REQUEST_HEADER]: id }, body: Buffer.from(body, "base64"), signal: controller.signal });
|
|
211
|
+
await send({ id, type: "start", status: result.status, contentType: result.headers.get("content-type") }, controller.signal);
|
|
165
212
|
const reader = result.body?.getReader();
|
|
166
213
|
if (reader)
|
|
167
214
|
for (;;) {
|
|
168
215
|
const { value, done } = await reader.read();
|
|
169
216
|
if (done)
|
|
170
217
|
break;
|
|
171
|
-
|
|
218
|
+
trace.record("gateway-receive", value.byteLength);
|
|
219
|
+
trace.record("ws-send-begin", value.byteLength);
|
|
220
|
+
await send({ id, type: "data", data: Buffer.from(value).toString("base64") }, controller.signal);
|
|
221
|
+
trace.record("ws-send-complete", value.byteLength);
|
|
172
222
|
}
|
|
173
|
-
await send({ id, type: "end" });
|
|
223
|
+
await send({ id, type: "end" }, controller.signal);
|
|
224
|
+
endReason = "http-end";
|
|
174
225
|
}
|
|
175
226
|
catch {
|
|
176
227
|
if (socket.readyState === WebSocket.OPEN)
|
|
177
228
|
await send({ id, type: "error" }).catch(() => { });
|
|
178
229
|
}
|
|
179
230
|
finally {
|
|
231
|
+
trace.finish(controller.signal.aborted ? "aborted" : endReason);
|
|
180
232
|
controller.abort();
|
|
181
233
|
active.delete(id);
|
|
182
234
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { AssistantMessage, AssistantMessageEvent } from "@earendil-works/pi-ai";
|
|
2
|
+
export declare const MODEL_STREAM_PROTOCOL = "compact-v1";
|
|
3
|
+
type Block = AssistantMessage["content"][number];
|
|
4
|
+
type Frame = {
|
|
5
|
+
wire: 1;
|
|
6
|
+
event: Record<string, unknown>;
|
|
7
|
+
meta?: Omit<AssistantMessage, "content">;
|
|
8
|
+
block?: Block;
|
|
9
|
+
};
|
|
10
|
+
/** Pi partials are live mutable helpers. Reconstruct event-time content from deltas. */
|
|
11
|
+
export declare class ModelWireEncoder {
|
|
12
|
+
private previousMeta;
|
|
13
|
+
encode(event: AssistantMessageEvent): AssistantMessageEvent | Frame;
|
|
14
|
+
}
|
|
15
|
+
export declare class ModelWireDecoder {
|
|
16
|
+
private partial?;
|
|
17
|
+
private arguments;
|
|
18
|
+
decode(value: unknown): AssistantMessageEvent;
|
|
19
|
+
}
|
|
20
|
+
export {};
|