@evandu/super-pi 0.1.288 → 0.1.290

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.
Files changed (42) hide show
  1. package/desktop/main.cjs +14 -2
  2. package/desktop/notification-routing.cjs +45 -0
  3. package/desktop/notifications.cjs +1 -1
  4. package/desktop/pet-preload.cjs +11 -0
  5. package/desktop/pet-renderer.js +34 -0
  6. package/desktop/pet.cjs +77 -0
  7. package/desktop/pet.css +26 -0
  8. package/desktop/pet.html +32 -0
  9. package/desktop/preload.cjs +4 -1
  10. package/dist/client/.super-pi-client-sources.json +15 -14
  11. package/dist/client/assets/{CodeMirrorEditor-CWtrW4l8.js → CodeMirrorEditor-CC6Mf3yd.js} +1 -1
  12. package/dist/client/assets/{GitDiffEditor-as0g7l10.js → GitDiffEditor-AhSKDGru.js} +1 -1
  13. package/dist/client/assets/index-D-sud3i3.js +350 -0
  14. package/dist/client/assets/index-dkbN-Swt.css +1 -0
  15. package/dist/client/index.html +2 -2
  16. package/dist/server/application/catalog-service.js +1 -0
  17. package/dist/server/application/run-service.d.ts +1 -0
  18. package/dist/server/application/run-service.js +26 -1
  19. package/dist/server/command-handler.js +35 -0
  20. package/dist/server/managed-model-adapter.js +101 -30
  21. package/dist/server/managed-model-flow.d.ts +20 -0
  22. package/dist/server/managed-model-flow.js +94 -0
  23. package/dist/server/managed-model-gateway.d.ts +6 -1
  24. package/dist/server/managed-model-gateway.js +95 -13
  25. package/dist/server/managed-model-relay.d.ts +1 -0
  26. package/dist/server/managed-model-relay.js +63 -11
  27. package/dist/server/managed-model-wire.d.ts +20 -0
  28. package/dist/server/managed-model-wire.js +82 -0
  29. package/dist/server/pi-session-pool.d.ts +1 -0
  30. package/dist/server/pi-session-pool.js +1 -0
  31. package/dist/server/pi-session.d.ts +8 -0
  32. package/dist/server/pi-session.js +19 -1
  33. package/dist/server/runtime.d.ts +2 -0
  34. package/dist/server/runtime.js +13 -0
  35. package/dist/server/turn-failure.js +1 -1
  36. package/dist/server/types.d.ts +3 -0
  37. package/dist/shared/slash-commands.d.ts +7 -0
  38. package/dist/shared/slash-commands.js +18 -0
  39. package/package.json +3 -1
  40. package/dist/.super-pi-check-inputs.json +0 -4
  41. package/dist/client/assets/index-CA58HvxO.css +0 -1
  42. package/dist/client/assets/index-CtgkiwLi.js +0 -350
@@ -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-CtgkiwLi.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-D-sud3i3.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-CA58HvxO.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-dkbN-Swt.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -63,6 +63,7 @@ export class CatalogService {
63
63
  * Immediately re-reads agent definitions from disk and broadcasts catalogs.
64
64
  */
65
65
  async rescan() {
66
+ this.promptCatalogs.clear();
66
67
  await Promise.all([
67
68
  this.broadcastAgents(),
68
69
  this.broadcastSubagents(),
@@ -270,6 +270,7 @@ export declare class RunService {
270
270
  conversation: Conversation;
271
271
  cwd: string;
272
272
  }>;
273
+ reloadConversation(conversationId: string): Promise<void>;
273
274
  compactContext(conversationId: string): Promise<void>;
274
275
  cancelCompaction(conversationId: string): Promise<void>;
275
276
  /**
@@ -761,6 +761,31 @@ export class RunService {
761
761
  const { conversation, workspace } = this.turnContext(conversationId);
762
762
  return { conversation, cwd: await resolveSessionCwd(workspace.path, conversation.cwd) };
763
763
  }
764
+ async reloadConversation(conversationId) {
765
+ const { conversation, workspace } = this.turnContext(conversationId);
766
+ this.assertHistoryAvailable(conversationId);
767
+ if (conversation.archivedAt || workspace.closedAt)
768
+ throw new Error("请先恢复会话并打开工作区,再重新加载资源。");
769
+ if (this.activeRuns.has(conversationId) || this.interruptTargets.has(conversationId))
770
+ throw new Error("当前会话正在执行,请结束或停止任务后再重新加载资源。");
771
+ if (!this.runtime.reloadConversation)
772
+ throw new Error("当前运行时不支持资源重载,请升级此服务器。");
773
+ const controller = new AbortController();
774
+ this.claimRunSlot(conversationId, controller, true);
775
+ try {
776
+ const cwd = await resolveSessionCwd(workspace.path, conversation.cwd);
777
+ const file = await this.runtime.reloadConversation(conversation, cwd);
778
+ if (file)
779
+ await this.store.setConversationPiSessionFile(conversationId, file);
780
+ }
781
+ finally {
782
+ this.releaseRunSlot(conversationId, controller);
783
+ this.broadcaster.broadcastState();
784
+ const next = this.store.listWaitingMessages(conversationId).find(message => message.delivery === "waiting");
785
+ if (next)
786
+ setImmediate(() => { void this.processWaitingMessage(conversationId, next.id, { ifIdle: true }).catch(error => console.warn("Super Pi queued message after reload:", describeThrownWithStack(error))); });
787
+ }
788
+ }
764
789
  async compactContext(conversationId) {
765
790
  const { conversation, workspace } = this.turnContext(conversationId);
766
791
  this.assertHistoryAvailable(conversationId);
@@ -2051,7 +2076,7 @@ export class RunService {
2051
2076
  return this.enqueueMessage(conversationId, note, { source: "session-reminder" });
2052
2077
  }
2053
2078
  async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source, accepted }) {
2054
- const deliveryMode = parseMessageDeliveryMode(mode);
2079
+ const deliveryMode = this.maintenanceRuns.has(conversationId) ? "queue" : parseMessageDeliveryMode(mode);
2055
2080
  this.assertHistoryAvailable(conversationId);
2056
2081
  this.memory?.cancel(conversationId);
2057
2082
  if (source || !isLengthContinuation(content)) {
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { join } from "node:path";
3
3
  import { KNOWN_APIS } from "./providers.js";
4
4
  import { CHILD_SESSION_LOCK_REASON } from "../shared/child-session-lock.js";
5
+ import { parseBuiltinSlashCommand, builtinSlashHint } from "../shared/slash-commands.js";
5
6
  import { claimUpdateSlot, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
6
7
  /**
7
8
  * Routes client commands to appropriate application services and converts results or errors.
@@ -277,6 +278,15 @@ export class CommandHandler {
277
278
  await this.runService.cancelCompaction(command.conversationId);
278
279
  return;
279
280
  }
281
+ if (command.type === "conversation.reload") {
282
+ if (this.conversationService.isReverting(command.conversationId))
283
+ throw new Error("正在回退会话,稍后再重新加载资源。");
284
+ await this.runService.reloadConversation(command.conversationId);
285
+ await this.catalogService.rescan();
286
+ const { conversation } = await this.runService.dispatchContext(command.conversationId);
287
+ await this.catalogService.broadcastPromptCatalog(conversation.workspaceId);
288
+ return;
289
+ }
280
290
  if (command.type === "conversation.thinking") {
281
291
  await this.conversationService.setThinking(command.conversationId, command.level);
282
292
  return;
@@ -315,6 +325,31 @@ export class CommandHandler {
315
325
  if (this.conversationService.isReverting(command.conversationId)) {
316
326
  throw new Error("正在撤回上一条消息,Pi 的历史还没截断完成,请等撤回结束后再发送。");
317
327
  }
328
+ const slash = parseBuiltinSlashCommand(command.content);
329
+ if (slash) {
330
+ if (slash.args || command.images?.length || command.attachments?.length)
331
+ throw new Error(`/${slash.id} 请单独执行,不要附加正文或附件。`);
332
+ if (slash.id === "reload" || slash.id === "compact" || slash.id === "stop") {
333
+ await this.handleCommand({ type: slash.id === "reload" ? "conversation.reload" : slash.id === "compact" ? "conversation.compact" : "run.stop", conversationId: command.conversationId }, sendToSocket, remoteAddress, browserAuthorized);
334
+ }
335
+ else if (slash.id === "new" || slash.id === "clear") {
336
+ const { conversation } = await this.runService.dispatchContext(command.conversationId);
337
+ const result = await this.conversationService.createConversation(conversation.workspaceId, undefined, conversation.cwd);
338
+ accepted();
339
+ return result;
340
+ }
341
+ else if (slash.id === "fork") {
342
+ const result = await this.conversationService.forkConversation(command.conversationId);
343
+ if (!result.ok)
344
+ throw new Error(result.message);
345
+ accepted();
346
+ return result.forkedId;
347
+ }
348
+ else
349
+ throw new Error(`此命令需要工作台交互。${builtinSlashHint(command.content)}`);
350
+ accepted();
351
+ return;
352
+ }
318
353
  // `attachments` was dropped here while the send path grew it, so a message carrying a skill
319
354
  // attachment lost it on arrival - the browser drew the attachment, the transcript never had it, and
320
355
  // the model was handed the bare prompt. Forwarded now because this is the one line that carries
@@ -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]) => ["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 }) }).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
- throw new Error("本地模型通道未连接。请确认入口电脑的 Super Pi 服务正在运行,并查看该服务器的模型通道状态。", { cause });
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
- throw new Error(`模型通道未能完成请求(HTTP ${response.status}),请查看入口电脑的模型通道状态和供应商配置。`);
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 = "", settled = false;
31
- for (;;) {
32
- const { done, value } = await reader.read().catch(cause => {
33
- if (signal?.aborted)
34
- throw cause;
35
- throw new Error("模型通道在回复完成前断开,请重连后重试", { cause });
36
- });
37
- pending += decoder.decode(value, { stream: !done });
38
- let end;
39
- while ((end = pending.indexOf("\n")) >= 0) {
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
- if (done) {
52
- if (!settled)
53
- throw new Error("模型通道在回复完成前断开,请重连后重试");
54
- break;
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 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() };
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
- response.once("close", () => { if (!response.writableEnded)
36
- abort.abort(); });
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
- const model = (await runtime.getAvailable()).find(model => model.provider === body.provider && model.id === body.modelId);
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 allowed = ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets"];
56
- const options = Object.fromEntries(Object.entries(body.options ?? {}).filter(([key]) => allowed.includes(key)));
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
- for await (const event of runtime.streamSimple(model, body.context, { ...options, signal: abort.signal })) {
59
- if (abort.signal.aborted)
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
- if (!response.write(`${JSON.stringify(event)}\n`))
62
- await new Promise(resolve => { response.once("drain", resolve); response.once("close", resolve); });
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.destroy();
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
  }
@@ -3,6 +3,7 @@ import { WebSocket } from "ws";
3
3
  export declare class ModelRelay {
4
4
  private socket?;
5
5
  private requests;
6
+ private traces;
6
7
  private waiting;
7
8
  close(): void;
8
9
  attach(socket: WebSocket): void;