@evandu/super-pi 0.1.323 → 0.1.324

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 (39) hide show
  1. package/agents/super-pi-managed-model/index.ts +8 -1
  2. package/dist/.super-pi-check-inputs.json +2 -2
  3. package/dist/client/.super-pi-client-sources.json +16 -11
  4. package/dist/client/assets/{CodeMirrorEditor-Di528QwW.js → CodeMirrorEditor-eVHUQY8Y.js} +1 -1
  5. package/dist/client/assets/{GitDiffEditor-CkuipKc9.js → GitDiffEditor-Cebgkg-9.js} +1 -1
  6. package/dist/client/assets/index-A2acEU1u.css +1 -0
  7. package/dist/client/assets/index-D9r6d2wH.js +363 -0
  8. package/dist/client/index.html +2 -2
  9. package/dist/server/application/group-chat-service.js +54 -4
  10. package/dist/server/application/provider-service.d.ts +2 -0
  11. package/dist/server/application/provider-service.js +28 -0
  12. package/dist/server/application/run-service.d.ts +2 -0
  13. package/dist/server/application/run-service.js +14 -2
  14. package/dist/server/group-primary-executor.js +9 -1
  15. package/dist/server/http-server.js +2 -2
  16. package/dist/server/managed-http.js +87 -18
  17. package/dist/server/managed-model-adapter.d.ts +8 -0
  18. package/dist/server/managed-model-adapter.js +46 -2
  19. package/dist/server/managed-model-gateway.d.ts +38 -0
  20. package/dist/server/managed-model-gateway.js +24 -3
  21. package/dist/server/managed-servers.d.ts +1 -0
  22. package/dist/server/managed-servers.js +15 -8
  23. package/dist/server/runtime.d.ts +1 -0
  24. package/dist/server/shared-model-catalog.d.ts +8 -0
  25. package/dist/server/shared-model-catalog.js +45 -0
  26. package/dist/server/store.d.ts +11 -1
  27. package/dist/server/store.js +85 -1
  28. package/dist/server/types.d.ts +9 -0
  29. package/dist/server/ws-server.d.ts +2 -2
  30. package/dist/server/ws-server.js +19 -5
  31. package/dist/shared/group-chat.d.ts +2 -0
  32. package/dist/shared/managed-servers.d.ts +1 -0
  33. package/dist/shared/model-configuration.d.ts +12 -0
  34. package/dist/shared/model-configuration.js +3 -0
  35. package/dist/shared/request-timing.d.ts +8 -0
  36. package/dist/shared/request-timing.js +1 -0
  37. package/package.json +1 -1
  38. package/dist/client/assets/index-CjV5_OmA.css +0 -1
  39. package/dist/client/assets/index-DLXLkcyw.js +0 -363
@@ -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-DLXLkcyw.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-D9r6d2wH.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-CjV5_OmA.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-A2acEU1u.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
17
17
 
@@ -1,4 +1,4 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import { open, readFile, realpath, writeFile } from "node:fs/promises";
3
3
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  import { createGitWorktree } from "../git.js";
@@ -45,6 +45,8 @@ function resolveQuestion(room, reply, answer, answerMessageId) {
45
45
  const topic = room.messages.find(post => post.role === "user" && post.id === reply.topicId);
46
46
  if (topic?.status === "interrupted" || topic?.status === "failed" || (answerMessageId && topic?.status === "completed")) {
47
47
  topic.status = "queued";
48
+ if (topic.role === "user" && topic.requestTiming)
49
+ topic.requestTiming = { startedAt: topic.requestTiming.startedAt };
48
50
  delete topic.error;
49
51
  }
50
52
  }
@@ -277,6 +279,8 @@ export class GroupChatService {
277
279
  for (const post of room.messages)
278
280
  if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
279
281
  post.status = "interrupted";
282
+ if (post.role === "user" && post.requestTiming)
283
+ post.requestTiming.outcome = "interrupted";
280
284
  post.error = "服务重启,本次发言已中断。";
281
285
  const trace = room.executions?.[post.id];
282
286
  if (trace && room.executions)
@@ -363,7 +367,34 @@ export class GroupChatService {
363
367
  }
364
368
  const rsi = room.rsi ?? defaultGroupRsi();
365
369
  const executionBusy = this.runtime.groupMembersBusy?.(workspaceId, id) ?? false;
366
- return { ...room, rsi: { ...rsi, pending: rsi.enabled && room.messages.length > 0 && rsi.sourceKey !== rsiSourceKey(room) }, activity: groupActivity(room, executionBusy), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}:${executionBusy}` };
370
+ const executionsByTopic = new Map();
371
+ for (const post of room.messages)
372
+ if (post.role === "assistant" && post.status === "completed" && post.executionConversationId && post.executionRequestId) {
373
+ const timing = this.store.requestTiming?.(post.executionConversationId, post.executionRequestId);
374
+ if (!timing)
375
+ continue;
376
+ const executions = executionsByTopic.get(post.topicId) ?? [];
377
+ executions.push(timing);
378
+ executionsByTopic.set(post.topicId, executions);
379
+ }
380
+ const timingChanges = [];
381
+ for (const post of room.messages) {
382
+ if (post.role !== "user" || post.requestTiming?.outcome !== "completed")
383
+ continue;
384
+ const executions = executionsByTopic.get(post.id);
385
+ if (!executions?.length)
386
+ continue;
387
+ const timing = post.requestTiming;
388
+ const latest = executions.reduce((value, item) => item.endedAt && item.endedAt > value ? item.endedAt : value, timing.endedAt ?? "");
389
+ const ended = executions.every(item => item.outcome);
390
+ const interrupted = executions.some(item => item.outcome === "interrupted");
391
+ const failed = executions.some(item => item.outcome !== "completed");
392
+ timing.endedAt = ended && !interrupted ? latest : undefined;
393
+ timing.outcome = !ended ? undefined : interrupted ? "interrupted" : failed ? "incomplete" : "completed";
394
+ timingChanges.push([post.id, timing.endedAt, timing.outcome]);
395
+ }
396
+ const timingRevision = timingChanges.length ? createHash("sha256").update(JSON.stringify(timingChanges)).digest("hex").slice(0, 16) : "";
397
+ return { ...room, rsi: { ...rsi, pending: rsi.enabled && room.messages.length > 0 && rsi.sourceKey !== rsiSourceKey(room) }, activity: groupActivity(room, executionBusy), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}:${executionBusy}${timingRevision ? `:${timingRevision}` : ""}` };
367
398
  }
368
399
  execution(workspaceId, id, postId) {
369
400
  const room = this.find(this.rooms, workspaceId, id);
@@ -632,7 +663,7 @@ export class GroupChatService {
632
663
  }
633
664
  if (!memberIds.length && parent?.role === "assistant" && room.members.some(member => member.id === parent.memberId))
634
665
  memberIds.push(parent.memberId);
635
- room.messages.push({ id: randomUUID(), role: "user", clientId, content, files, images, memberIds, replyTo: parent?.id, createdAt: timestamp(), status: "queued" });
666
+ room.messages.push({ id: randomUUID(), role: "user", clientId, content, files, images, memberIds, replyTo: parent?.id, createdAt: timestamp(), status: "queued", requestTiming: {} });
636
667
  room.updatedAt = timestamp();
637
668
  room.revision += 1;
638
669
  });
@@ -668,6 +699,8 @@ export class GroupChatService {
668
699
  for (const post of posts) {
669
700
  post.content = this.live.get(post.id) ?? post.content;
670
701
  post.status = "cancelled";
702
+ if (post.role === "user" && post.requestTiming)
703
+ Object.assign(post.requestTiming, { endedAt: timestamp(), outcome: "stopped" });
671
704
  if (post.role === "assistant") {
672
705
  this.saveExecution(room, post.id, true);
673
706
  if (post.humanQuestion && !post.humanQuestion.answer)
@@ -707,6 +740,8 @@ export class GroupChatService {
707
740
  if (next?.status !== "queued")
708
741
  return;
709
742
  next.status = "running";
743
+ if (next.requestTiming)
744
+ next.requestTiming.startedAt ??= timestamp();
710
745
  current.revision += 1;
711
746
  return next;
712
747
  });
@@ -1441,8 +1476,11 @@ export class GroupChatService {
1441
1476
  current.messages.push(this.moderatorPost(message, notice, hostName));
1442
1477
  }
1443
1478
  const handled = decision.action === "clarify" || !decision.hasNewRequest;
1444
- if (handled)
1479
+ if (handled) {
1445
1480
  message.status = "completed";
1481
+ if (message.requestTiming)
1482
+ Object.assign(message.requestTiming, { endedAt: timestamp(), outcome: "completed" });
1483
+ }
1446
1484
  current.revision += 1;
1447
1485
  current.updatedAt = timestamp();
1448
1486
  return { ids, handled };
@@ -1693,6 +1731,14 @@ export class GroupChatService {
1693
1731
  this.find(rooms, started.workspaceId, roomId).revision++;
1694
1732
  } }),
1695
1733
  userToolContext: reply.requirementsOnly ? undefined : { id: reply.id, workspaceId: started.workspaceId },
1734
+ onRequest: reply.requirementsOnly ? undefined : id => this.edit(rooms => {
1735
+ const room = this.find(rooms, started.workspaceId, roomId);
1736
+ const post = room.messages.find(item => item.id === reply.id);
1737
+ if (post?.role === "assistant") {
1738
+ post.executionRequestId = id;
1739
+ room.revision++;
1740
+ }
1741
+ }),
1696
1742
  memberSession: reply.requirementsOnly ? undefined : { workspaceId: started.workspaceId, roomId, memberId: reply.memberId, context: this.context(started, topic) },
1697
1743
  prompt: `会议身份:${member?.name ?? agent.name}。${member?.worktreePath ? "你在独立工作树工作;报告分支和产物供后续审查整合。" : ""}\n${prompt}`, cwd: member?.worktreePath,
1698
1744
  agent: executionAgent, model: member?.model ?? (agent.model && { ...agent.model, label: agent.model.modelId }), signal: memberSignal, timeoutMs: 15 * 60_000,
@@ -1740,6 +1786,10 @@ export class GroupChatService {
1740
1786
  if (post?.status !== "running")
1741
1787
  return;
1742
1788
  post.status = signal.aborted ? this.closing ? "interrupted" : "cancelled" : error ? "failed" : "completed";
1789
+ if (post.role === "user" && post.requestTiming) {
1790
+ const at = timestamp();
1791
+ Object.assign(post.requestTiming, { responseEndedAt: at, endedAt: at, outcome: post.status === "cancelled" ? "stopped" : post.status });
1792
+ }
1743
1793
  if (content !== undefined)
1744
1794
  post.content = content.slice(0, MAX_CONTENT);
1745
1795
  post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
@@ -51,6 +51,8 @@ export declare class ProviderService {
51
51
  set(input: unknown): Promise<PublicProvider[]>;
52
52
  remove(providerId: string): Promise<PublicProvider[]>;
53
53
  removeModel(providerId: string, modelId: string): Promise<PublicProvider[]>;
54
+ refreshConfiguration(): Promise<void>;
55
+ setSharedCatalogKey(providerId: string, key: string): Promise<void>;
54
56
  private readonly oauthJobs;
55
57
  constructor(registry: ProviderRegistry, runtime: AgentRuntime, broadcaster: EventBroadcaster, catalogService: CatalogService, store: Store, discoverModels?: typeof discoverPiProviderModels);
56
58
  /**
@@ -6,6 +6,9 @@ import { thinkingLevelsEndpoint } from "../../shared/thinking-levels.js";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { ModelDiscovery } from "../model-discovery.js";
8
8
  import { discoverPiProviderModels } from "../pi-session.js";
9
+ import { activeSharedCatalog } from "../managed-model-adapter.js";
10
+ import { sharedProviderModels } from "../shared-model-catalog.js";
11
+ import { piAuthPath } from "../providers.js";
9
12
  /**
10
13
  * THE PROVIDERS A PERSON ADDED, as a service.
11
14
  *
@@ -88,6 +91,22 @@ export class ProviderService {
88
91
  async set(input) { return this.mutate(() => this.setNow(input)); }
89
92
  async remove(providerId) { return this.mutate(() => this.removeNow(providerId)); }
90
93
  async removeModel(providerId, modelId) { return this.mutate(() => this.removeModelNow(providerId, modelId)); }
94
+ async refreshConfiguration() { return this.mutate(() => this.afterChange([], false)); }
95
+ async setSharedCatalogKey(providerId, key) {
96
+ return this.mutate(async () => {
97
+ const url = new URL("./core/auth-storage.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href;
98
+ const { AuthStorage } = await import(url);
99
+ const storage = AuthStorage.create(piAuthPath(this.registry.agentDir));
100
+ await storage.modify(providerId, async (previous) => {
101
+ if (previous?.type === "oauth")
102
+ throw new Error("请在内置供应商登录中管理此授权。");
103
+ if (!key)
104
+ return undefined;
105
+ return { type: "api_key", key, ...(previous?.env ? { env: previous.env } : {}) };
106
+ });
107
+ await this.afterChange([], false);
108
+ });
109
+ }
91
110
  oauthJobs = new Map();
92
111
  constructor(registry, runtime, broadcaster, catalogService, store, discoverModels = discoverPiProviderModels) {
93
112
  this.registry = registry;
@@ -175,6 +194,15 @@ export class ProviderService {
175
194
  provider.builtin = true;
176
195
  byId.set(info.id, provider);
177
196
  }
197
+ for (const [id, models] of sharedProviderModels(await activeSharedCatalog())) {
198
+ const previous = byId.get(id);
199
+ byId.set(id, {
200
+ ...previous, id, name: previous?.name ?? id, hasKey: previous?.hasKey ?? false,
201
+ baseUrl: models[0].baseUrl, api: models[0].api,
202
+ models: models.map(model => ({ id: model.id, name: model.name, reasoning: model.reasoning,
203
+ imageInput: model.input.includes("image"), contextWindow: model.contextWindow, maxTokens: model.maxTokens })),
204
+ });
205
+ }
178
206
  return [...byId.values()];
179
207
  }
180
208
  oauthSnapshot() {
@@ -421,6 +421,8 @@ export declare class RunService {
421
421
  mode?: MessageDeliveryMode;
422
422
  onAccepted?: (messageId: string) => void;
423
423
  images?: MessageImage[];
424
+ trackRequestTiming?: boolean;
425
+ timingRequestIds?: string[];
424
426
  }): Promise<void>;
425
427
  acknowledgeAcceptedSend(conversationId: string, clientId: string | undefined): Promise<boolean>;
426
428
  enqueueAndRun(conversationId: string, content: string, images?: MessageImage[], attachments?: Message["attachments"], clientId?: string, mode?: MessageDeliveryMode, onAccepted?: () => void): Promise<void>;
@@ -1181,6 +1181,7 @@ export class RunService {
1181
1181
  let assistant = assistantMessage;
1182
1182
  let currentUserMessageId = userMessageId;
1183
1183
  let closedOwnScope = false;
1184
+ let outcome = "completed";
1184
1185
  let toolCalls = [];
1185
1186
  let pendingTools = Promise.resolve();
1186
1187
  // A TURN MOVES FROM `waiting` TO `running` ONCE THE MODEL HAS PRODUCED ANY SIGNAL: a text delta
@@ -1660,6 +1661,7 @@ export class RunService {
1660
1661
  return toolCalls;
1661
1662
  if (!ownsScope())
1662
1663
  return toolCalls;
1664
+ await this.store.finishRequestReply(conversation.id, previous.id, currentUserMessageId, "completed");
1663
1665
  if (this.memory) {
1664
1666
  const checkpointed = this.store.conversation(conversation.id);
1665
1667
  if (checkpointed)
@@ -1829,6 +1831,10 @@ export class RunService {
1829
1831
  scheduleCheckpoint();
1830
1832
  }
1831
1833
  }
1834
+ catch (error) {
1835
+ outcome = isLengthExceededError(error) ? "incomplete" : "failed";
1836
+ throw error;
1837
+ }
1832
1838
  finally {
1833
1839
  scope.accepting = false;
1834
1840
  traceScope("draining");
@@ -1851,6 +1857,9 @@ export class RunService {
1851
1857
  enqueueTools("unfinished tool calls", () => this.store.clearPreparingToolCalls(conversation.id, assistant.id, stranded));
1852
1858
  }
1853
1859
  await pendingTools;
1860
+ if (ownsScope()) {
1861
+ await this.store.finishRequestReply(conversation.id, assistant.id, currentUserMessageId, controller.signal.aborted ? "stopped" : outcome);
1862
+ }
1854
1863
  // The positions are facts ABOUT THIS TURN and stop being true when it ends, so they go with it.
1855
1864
  // A dispatch whose POST arrives after this line gets no anchor and renders where it always did -
1856
1865
  // which is the honest outcome, because by then the call that asked for it may no longer be on screen.
@@ -2004,7 +2013,10 @@ export class RunService {
2004
2013
  }
2005
2014
  let message;
2006
2015
  try {
2007
- message = await this.store.addAgentMessage(conversationId, trimmed, { images: options?.images, ...(queueOnly ? { delivery: "waiting" } : {}) });
2016
+ message = await this.store.addAgentMessage(conversationId, trimmed, {
2017
+ images: options?.images, ...(queueOnly ? { delivery: "waiting" } : {}),
2018
+ requestTiming: options?.trackRequestTiming ? {} : undefined, timingRequestIds: options?.timingRequestIds,
2019
+ });
2008
2020
  }
2009
2021
  catch (error) {
2010
2022
  if (reservedController)
@@ -2328,7 +2340,7 @@ export class RunService {
2328
2340
  }
2329
2341
  this.lengthContinuations.set(conversationId, used + 1);
2330
2342
  try {
2331
- await this.enqueueAndRunAsAgent(conversationId, buildLengthContinuationPrompt(assistant));
2343
+ await this.enqueueAndRunAsAgent(conversationId, buildLengthContinuationPrompt(assistant), { timingRequestIds: assistant?.timingRequestIds });
2332
2344
  return;
2333
2345
  }
2334
2346
  catch (error) {
@@ -69,7 +69,15 @@ export function groupPrimaryExecutor(store, runs, uploadsDir) {
69
69
  const stored = await saveUpload(uploadsDir, id, "会议图片", image.mimeType, image.data);
70
70
  return { id: stored.id, name: stored.name, mimeType: stored.mimeType, bytes: stored.bytes };
71
71
  }));
72
- await runs.enqueueAndRunAsAgent(id, fresh ? `${input.prompt}\n会议完整公开上下文:\n${JSON.stringify(scope.context)}` : input.prompt, { images });
72
+ let recorded;
73
+ await runs.enqueueAndRunAsAgent(id, fresh ? `${input.prompt}\n会议完整公开上下文:\n${JSON.stringify(scope.context)}` : input.prompt, {
74
+ images, trackRequestTiming: Boolean(input.onRequest),
75
+ onAccepted(messageId) {
76
+ recorded = Promise.resolve(input.onRequest?.(messageId));
77
+ void recorded.catch(() => undefined);
78
+ },
79
+ });
80
+ await recorded;
73
81
  observe();
74
82
  input.signal?.throwIfAborted();
75
83
  const current = store.conversation(id);
@@ -1,7 +1,7 @@
1
1
  import { handleManagedHttp } from "./managed-http.js";
2
2
  import { handleRsiHttp } from "./rsi-http.js";
3
3
  import { remoteModelRelay } from "./managed-model-relay.js";
4
- import { readManagedModelConfig } from "./managed-model-adapter.js";
4
+ import { modelConfigurationMode, readManagedModelConfig } from "./managed-model-adapter.js";
5
5
  import { ReadReceipts } from "./read-receipts.js";
6
6
  import { createReadStream, existsSync } from "node:fs";
7
7
  import { matchPathMentions } from "../shared/file-mentions.js";
@@ -2004,7 +2004,7 @@ export function createHttpServer(options) {
2004
2004
  if (url.pathname === "/api/health") {
2005
2005
  const version = checkDiskVersion(rootDir);
2006
2006
  response.writeHead(200, { "content-type": "application/json; charset=utf-8" })
2007
- .end(JSON.stringify({ status: "ok", service: "super-pi", manager: Boolean(context.managedServers), managed: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), modelRelay: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), ...version }));
2007
+ .end(JSON.stringify({ status: "ok", service: "super-pi", manager: Boolean(context.managedServers), managed: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), modelRelay: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), modelMode: await modelConfigurationMode(), ...version }));
2008
2008
  return;
2009
2009
  }
2010
2010
  /**
@@ -2,15 +2,91 @@ import { isBrowserAuthorized } from "./browser-access.js";
2
2
  import { isLoopbackAddress } from "./http-server.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { rename, writeFile, rm } from "node:fs/promises";
5
- import { readManagedModelConfig } from "./managed-model-adapter.js";
5
+ import { modelConfigurationMode, modelConfigurationModePath, readManagedModelConfig } from "./managed-model-adapter.js";
6
+ import { isModelConfigurationMode } from "../shared/model-configuration.js";
7
+ import { sharedCatalogModels, sharedProviderModels, validSharedProviderId } from "./shared-model-catalog.js";
8
+ async function writeAtomic(path, content) {
9
+ const temp = path + "." + randomUUID() + ".tmp";
10
+ try {
11
+ await writeFile(temp, content, { mode: 0o600 });
12
+ await rename(temp, path);
13
+ }
14
+ finally {
15
+ await rm(temp, { force: true });
16
+ }
17
+ }
6
18
  /** A model-channel token is deliberately never accepted by these management routes. */
7
19
  export async function handleManagedHttp(context, request, response, url) {
8
20
  const route = url.pathname === "/api/managed-servers";
9
21
  const proxy = /^\/managed\/([a-f0-9-]+)(\/.*)$/.exec(url.pathname);
10
22
  const syncCatalog = url.pathname === "/api/managed-model/catalog";
11
- if (!route && !proxy && !syncCatalog && url.pathname !== "/api/managed-model/reload")
23
+ const modeRoute = url.pathname === "/api/managed-model/mode";
24
+ if (!route && !proxy && !syncCatalog && !modeRoute && url.pathname !== "/api/managed-model/reload")
12
25
  return false;
13
26
  const json = (status, value) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(value)); };
27
+ if (modeRoute) {
28
+ const path = modelConfigurationModePath();
29
+ const status = async () => {
30
+ const config = await readManagedModelConfig();
31
+ return { paired: Boolean(path), mode: await modelConfigurationMode(), syncedAt: config?.sharedCatalogAt, skippedModels: config?.sharedCatalogSkipped,
32
+ providers: [...sharedProviderModels(config?.sharedModels ?? [])].map(([id, models]) => ({ id, modelCount: models.length })) };
33
+ };
34
+ if (!path) {
35
+ json(request.method === "GET" ? 200 : 409, request.method === "GET" ? await status() : { error: "该服务器尚未和入口配对,使用独立配置。" });
36
+ return true;
37
+ }
38
+ if (!isBrowserAuthorized(request) && (!isLoopbackAddress(request.socket.remoteAddress) || (request.headers.origin && request.headers.origin !== url.origin))) {
39
+ json(403, { error: "需要远端服务的管理授权" });
40
+ return true;
41
+ }
42
+ if (request.method === "GET") {
43
+ json(200, await status());
44
+ return true;
45
+ }
46
+ if (request.method !== "PATCH") {
47
+ json(405, { error: "仅支持 GET/PATCH" });
48
+ return true;
49
+ }
50
+ try {
51
+ let raw = "";
52
+ for await (const chunk of request) {
53
+ raw += chunk;
54
+ if (raw.length > 16384) {
55
+ json(413, { error: "请求过大" });
56
+ return true;
57
+ }
58
+ }
59
+ const body = JSON.parse(raw);
60
+ const current = await status();
61
+ if (body.action === "setKey") {
62
+ if (current.mode !== "shared-catalog" || !validSharedProviderId(body.provider) || !current.providers.some(item => item.id === body.provider) ||
63
+ typeof body.key !== "string" || body.key.length > 8192) {
64
+ json(400, { error: "远端供应商或 API Key 无效" });
65
+ return true;
66
+ }
67
+ await context.providerService.setSharedCatalogKey(body.provider, body.key.trim());
68
+ }
69
+ else {
70
+ if (!isModelConfigurationMode(body.mode)) {
71
+ json(400, { error: "请选择有效的模型配置模式" });
72
+ return true;
73
+ }
74
+ if (body.mode === "shared-catalog" && !current.syncedAt) {
75
+ json(409, { error: "入口还未同步模型目录。请同步后重试,并确认入口和远端均已更新。" });
76
+ return true;
77
+ }
78
+ if (body.mode !== current.mode) {
79
+ await writeAtomic(path, body.mode);
80
+ await context.providerService.refreshConfiguration();
81
+ }
82
+ }
83
+ json(200, await status());
84
+ }
85
+ catch (error) {
86
+ json(400, { error: error instanceof SyntaxError ? "模型配置请求无效" : "模型配置操作失败,请重新读取当前配置后重试。" });
87
+ }
88
+ return true;
89
+ }
14
90
  if (syncCatalog || url.pathname === "/api/managed-model/reload") {
15
91
  if (!process.env.SUPER_PI_MANAGED_CONFIG) {
16
92
  json(404, { error: "当前服务未由本地入口托管" });
@@ -41,23 +117,16 @@ export async function handleManagedHttp(context, request, response, url) {
41
117
  json(400, { error: "模型目录无效" });
42
118
  return true;
43
119
  }
44
- const path = process.env.SUPER_PI_MANAGED_CONFIG;
45
- const temp = path + "." + randomUUID() + ".tmp";
46
- try {
47
- await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, entryIntegrations: catalog.entryIntegrations, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
48
- await rename(temp, path);
49
- process.env.SUPER_PI_WEB_ENABLED = catalog.entryIntegrations?.web === true ? "1" : "0";
50
- }
51
- finally {
52
- await rm(temp, { force: true });
53
- }
120
+ const sharedModels = Array.isArray(catalog.sharedModels) ? sharedCatalogModels(catalog.sharedModels) : undefined;
121
+ const omittedAtEntry = Number.isSafeInteger(catalog.sharedCatalogSkipped) && catalog.sharedCatalogSkipped > 0 ? catalog.sharedCatalogSkipped : 0;
122
+ const shared = sharedModels
123
+ ? { sharedModels, sharedCatalogAt: new Date().toISOString(), sharedCatalogSkipped: omittedAtEntry + catalog.sharedModels.length - sharedModels.length } : {};
124
+ const endpoint = `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke`;
125
+ await writeAtomic(process.env.SUPER_PI_MANAGED_CONFIG, JSON.stringify({ ...config, ...shared, models: catalog.models, defaultModel: catalog.defaultModel, entryIntegrations: catalog.entryIntegrations, endpoint }));
126
+ process.env.SUPER_PI_WEB_ENABLED = catalog.entryIntegrations?.web === true ? "1" : "0";
54
127
  }
55
- context.runtime.invalidateCatalog?.();
56
- context.runtime.bumpModelEpoch?.();
57
- await context.catalogService.broadcastAllCatalog();
58
- for (const conversation of context.store.snapshot().conversations)
59
- if (!conversation.archivedAt)
60
- await context.catalogService.broadcastCatalog(conversation.model, conversation.id);
128
+ if (await modelConfigurationMode() !== "independent")
129
+ await context.providerService.refreshConfiguration();
61
130
  json(200, { ok: true });
62
131
  return true;
63
132
  }
@@ -1,4 +1,6 @@
1
1
  import type { Model } from "@earendil-works/pi-ai";
2
+ import { type ModelConfigurationMode } from "../shared/model-configuration.js";
3
+ import { type SharedCatalogModel } from "./shared-model-catalog.js";
2
4
  export interface ManagedModelConfig {
3
5
  entryIntegrations?: {
4
6
  web: boolean;
@@ -7,11 +9,17 @@ export interface ManagedModelConfig {
7
9
  endpoint: string;
8
10
  token: string;
9
11
  models: Model<string>[];
12
+ sharedModels?: SharedCatalogModel[];
13
+ sharedCatalogAt?: string;
14
+ sharedCatalogSkipped?: number;
10
15
  defaultModel?: {
11
16
  provider: string;
12
17
  modelId: string;
13
18
  };
14
19
  }
20
+ export declare function modelConfigurationModePath(): string | undefined;
21
+ export declare function modelConfigurationMode(): Promise<ModelConfigurationMode>;
22
+ export declare function activeSharedCatalog(): Promise<SharedCatalogModel[]>;
15
23
  export declare function readManagedModelConfig(): Promise<ManagedModelConfig | undefined>;
16
24
  /** Both embedded sessions and isolated Pi processes register the same transport-only providers. */
17
25
  export declare function managedProviderDefinitions(config: ManagedModelConfig): Promise<{
@@ -2,8 +2,34 @@ import { readFile } from "node:fs/promises";
2
2
  import { Agent } from "undici";
3
3
  import { MODEL_OPTION_KEYS, MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId } from "./managed-model-flow.js";
4
4
  import { MODEL_STREAM_PROTOCOL, ModelWireDecoder } from "./managed-model-wire.js";
5
+ import { isModelConfigurationMode } from "../shared/model-configuration.js";
6
+ import { sharedProviderModels } from "./shared-model-catalog.js";
5
7
  // This authenticated channel is restricted to loopback, independently of provider/global proxies.
6
8
  const modelChannelDispatcher = new Agent();
9
+ export function modelConfigurationModePath() {
10
+ return process.env.SUPER_PI_MANAGED_CONFIG && `${process.env.SUPER_PI_MANAGED_CONFIG}.mode`;
11
+ }
12
+ export async function modelConfigurationMode() {
13
+ const path = modelConfigurationModePath();
14
+ if (!path)
15
+ return "independent";
16
+ try {
17
+ const mode = (await readFile(path, "utf8")).trim();
18
+ if (!isModelConfigurationMode(mode))
19
+ throw new Error("远端模型配置模式无效");
20
+ return mode;
21
+ }
22
+ catch (error) {
23
+ if (error.code === "ENOENT")
24
+ return "unified";
25
+ throw error;
26
+ }
27
+ }
28
+ export async function activeSharedCatalog() {
29
+ if (await modelConfigurationMode() !== "shared-catalog")
30
+ return [];
31
+ return (await readManagedModelConfig())?.sharedModels ?? [];
32
+ }
7
33
  export async function readManagedModelConfig() {
8
34
  const path = process.env.SUPER_PI_MANAGED_CONFIG;
9
35
  if (!path)
@@ -147,11 +173,29 @@ export async function managedProviderDefinitions(config) {
147
173
  }));
148
174
  }
149
175
  export async function installManagedModels(runtime) {
176
+ const mode = await modelConfigurationMode();
177
+ if (mode === "independent")
178
+ return;
150
179
  const config = await readManagedModelConfig();
151
180
  if (!config)
152
181
  return;
153
182
  const target = runtime;
154
- for (const definition of await managedProviderDefinitions(config))
155
- target.registerNativeProvider(definition.provider);
183
+ if (mode === "unified") {
184
+ for (const definition of await managedProviderDefinitions(config))
185
+ target.registerNativeProvider(definition.provider);
186
+ }
187
+ else {
188
+ for (const [provider, definitions] of sharedProviderModels(config.sharedModels ?? []))
189
+ target.registerProvider(provider, { models: definitions });
190
+ }
191
+ const models = mode === "unified" ? config.models : config.sharedModels ?? [];
192
+ const allowed = new Set(models.map(model => JSON.stringify([model.provider, model.id])));
193
+ const includes = (provider, id) => allowed.has(JSON.stringify([provider, id]));
194
+ const getAvailable = target.getAvailable?.bind(target);
195
+ if (getAvailable)
196
+ target.getAvailable = async (...args) => (await getAvailable(...args)).filter(model => includes(model.provider, model.id));
197
+ const getModel = target.getModel?.bind(target);
198
+ if (getModel)
199
+ target.getModel = (provider, model) => includes(provider, model) ? getModel(provider, model) : undefined;
156
200
  await target.refresh?.();
157
201
  }
@@ -2,6 +2,7 @@ import type { IncomingMessage, ServerResponse } from "node:http";
2
2
  import type { Context, Model, SimpleStreamOptions } from "@earendil-works/pi-ai";
3
3
  type Runtime = {
4
4
  getAvailable(): Promise<Model<string>[]>;
5
+ getModels?(): readonly Model<string>[];
5
6
  getModel(provider: string, id: string): Model<string> | undefined;
6
7
  streamSimple(model: Model<string>, context: Context, options?: SimpleStreamOptions): AsyncIterable<unknown>;
7
8
  };
@@ -16,6 +17,43 @@ export declare class ManagedModelGateway {
16
17
  writeTimeoutMs?: number;
17
18
  });
18
19
  private runtime;
20
+ catalogBundle(force?: boolean): Promise<{
21
+ models: {
22
+ id: string;
23
+ provider: string;
24
+ name: string;
25
+ api: string;
26
+ reasoning: boolean;
27
+ input: ("image" | "text")[];
28
+ cost: {
29
+ input: number;
30
+ output: number;
31
+ cacheRead: number;
32
+ cacheWrite: number;
33
+ tiers?: {
34
+ input: number;
35
+ output: number;
36
+ cacheRead: number;
37
+ cacheWrite: number;
38
+ inputTokensAbove: number;
39
+ }[] | undefined;
40
+ };
41
+ contextWindow: number;
42
+ maxTokens: number;
43
+ thinkingLevelMap: {
44
+ off?: string | null | undefined;
45
+ minimal?: string | null | undefined;
46
+ low?: string | null | undefined;
47
+ medium?: string | null | undefined;
48
+ high?: string | null | undefined;
49
+ xhigh?: string | null | undefined;
50
+ max?: string | null | undefined;
51
+ } | undefined;
52
+ baseUrl: string;
53
+ }[];
54
+ sharedModels: import("./shared-model-catalog.js").SharedCatalogModel[];
55
+ sharedCatalogSkipped: number;
56
+ }>;
19
57
  catalog(force?: boolean): Promise<{
20
58
  id: string;
21
59
  provider: string;
@@ -1,8 +1,10 @@
1
1
  import { DEFAULT_MODEL_IDLE_MS, MODEL_OPTION_KEYS, MODEL_REQUEST_HEADER, ModelFlowTrace, modelRequestId, nextModelEvent, writeModelChunk } from "./managed-model-flow.js";
2
2
  import { MODEL_STREAM_PROTOCOL, ModelWireEncoder } from "./managed-model-wire.js";
3
3
  import { describeThrown } from "./failure-text.js";
4
- import { piAgentDir, piAuthPath, piModelsPath } from "./providers.js";
4
+ import { piAgentDir, piAuthPath, piModelsPath, stripJsonComments } from "./providers.js";
5
5
  import { installProviderProxy } from "./provider-proxy.js";
6
+ import { sharedCatalogModels } from "./shared-model-catalog.js";
7
+ import { readFile } from "node:fs/promises";
6
8
  /** Credentials remain in the manager's normal Pi auth store, including OAuth refresh ownership. */
7
9
  export class ManagedModelGateway {
8
10
  factory;
@@ -27,9 +29,28 @@ export class ManagedModelGateway {
27
29
  this.cached = { runtime, createdAt: Date.now() };
28
30
  return runtime;
29
31
  }
30
- async catalog(force = false) {
32
+ async catalogBundle(force = false) {
31
33
  const runtime = await this.runtime(force);
32
- 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: "" }));
34
+ const available = await runtime.getAvailable();
35
+ const merged = new Map(available.map(model => [JSON.stringify([model.provider, model.id]), model]));
36
+ if (!this.factory && runtime.getModels) {
37
+ const definitions = await readFile(piModelsPath(), "utf8").then(text => JSON.parse(stripJsonComments(text))).catch(() => undefined);
38
+ const configured = new Set(Object.entries(definitions?.providers ?? {}).flatMap(([provider, config]) => Array.isArray(config?.models) ? config.models.map(model => JSON.stringify([provider, model?.id])) : []));
39
+ for (const model of runtime.getModels()) {
40
+ const key = JSON.stringify([model.provider, model.id]);
41
+ if (configured.has(key) && !merged.has(key))
42
+ merged.set(key, model);
43
+ }
44
+ }
45
+ const sharedModels = sharedCatalogModels([...merged.values()]);
46
+ return {
47
+ models: available.map(({ id, provider, name, api, reasoning, input, cost, contextWindow, maxTokens, thinkingLevelMap }) => ({ id, provider, name, api, reasoning, input, cost, contextWindow, maxTokens, thinkingLevelMap, baseUrl: "" })),
48
+ sharedModels,
49
+ sharedCatalogSkipped: merged.size - sharedModels.length,
50
+ };
51
+ }
52
+ async catalog(force = false) {
53
+ return (await this.catalogBundle(force)).models;
33
54
  }
34
55
  async handle(request, response) {
35
56
  if (request.method !== "POST") {
@@ -68,6 +68,7 @@ export declare class ManagedServers {
68
68
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
69
69
  service: "unknown" | "offline" | "online";
70
70
  modelChannel: "offline" | "online";
71
+ modelMode?: import("../shared/model-configuration.js").ModelConfigurationMode;
71
72
  modelTransport?: "direct";
72
73
  modelChannelPaused?: boolean;
73
74
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";