@evandu/super-pi 0.1.322 → 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 (47) 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 +24 -19
  4. package/dist/client/assets/CodeMirrorEditor-eVHUQY8Y.js +2 -0
  5. package/dist/client/assets/GitDiffEditor-Cebgkg-9.js +31 -0
  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/file-review-threads.d.ts +5 -2
  15. package/dist/server/file-review-threads.js +83 -5
  16. package/dist/server/git.d.ts +7 -7
  17. package/dist/server/git.js +25 -8
  18. package/dist/server/group-primary-executor.js +9 -1
  19. package/dist/server/http-server.js +22 -10
  20. package/dist/server/managed-http.js +87 -18
  21. package/dist/server/managed-model-adapter.d.ts +8 -0
  22. package/dist/server/managed-model-adapter.js +46 -2
  23. package/dist/server/managed-model-gateway.d.ts +38 -0
  24. package/dist/server/managed-model-gateway.js +24 -3
  25. package/dist/server/managed-servers.d.ts +1 -0
  26. package/dist/server/managed-servers.js +15 -8
  27. package/dist/server/runtime.d.ts +1 -0
  28. package/dist/server/shared-model-catalog.d.ts +8 -0
  29. package/dist/server/shared-model-catalog.js +45 -0
  30. package/dist/server/store.d.ts +11 -1
  31. package/dist/server/store.js +85 -1
  32. package/dist/server/types.d.ts +9 -0
  33. package/dist/server/ws-server.d.ts +2 -2
  34. package/dist/server/ws-server.js +19 -5
  35. package/dist/shared/file-review.d.ts +39 -0
  36. package/dist/shared/file-review.js +14 -0
  37. package/dist/shared/group-chat.d.ts +2 -0
  38. package/dist/shared/managed-servers.d.ts +1 -0
  39. package/dist/shared/model-configuration.d.ts +12 -0
  40. package/dist/shared/model-configuration.js +3 -0
  41. package/dist/shared/request-timing.d.ts +8 -0
  42. package/dist/shared/request-timing.js +1 -0
  43. package/package.json +2 -1
  44. package/dist/client/assets/CodeMirrorEditor-BsMtOxUG.js +0 -2
  45. package/dist/client/assets/GitDiffEditor-L_OuYDQ2.js +0 -29
  46. package/dist/client/assets/index-Cvx8i65V.css +0 -1
  47. package/dist/client/assets/index-DeMK1efe.js +0 -358
@@ -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";
@@ -14,6 +14,7 @@ import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed
14
14
  import { installRemote, startRemote, stopRemote } from "./remote-bootstrap.js";
15
15
  import { discoverManagedInstallations, recoverySummary } from "./managed-recovery.js";
16
16
  import { isServiceListenHost } from "../shared/managed-servers.js";
17
+ import { isModelConfigurationMode } from "../shared/model-configuration.js";
17
18
  import { discoverExistingInstallation } from "./existing-service.js";
18
19
  import { publishedServerUpdate } from "./published-server-update.js";
19
20
  import { directJson, serviceOrigin, defaultServiceOrigin, probeServiceEndpoint, proxyThroughDirect, proxyWebSocketThroughDirect } from "./managed-http-direct.js";
@@ -417,7 +418,7 @@ export class ManagedServers {
417
418
  if (reload && entry.profile.modelTransport === "direct" && relay?.readyState !== WebSocket.OPEN)
418
419
  throw new Error("服务端口的模型通道正在连接,请稍后重试");
419
420
  if (reload && entry.installation && secret && relay?.readyState === WebSocket.OPEN && entry.profile.serviceUrl) {
420
- const body = JSON.stringify({ models: await this.gateway.catalog(force), defaultModel: this.defaultModel(), entryIntegrations: this.integrations?.available() });
421
+ const body = JSON.stringify({ ...await this.gateway.catalogBundle(force), defaultModel: this.defaultModel(), entryIntegrations: this.integrations?.available() });
421
422
  const hash = createHash("sha256").update(body).digest("hex");
422
423
  if (!force && this.syncedRelays.get(relay) === hash)
423
424
  return;
@@ -435,16 +436,19 @@ export class ManagedServers {
435
436
  const directBootstrap = !reload && entry.profile.modelTransport === "direct";
436
437
  if (!entry.installation || (!entry.reversePort && !directBootstrap) || !client || !secret)
437
438
  throw new Error("请先部署并连接此服务器");
438
- const models = await this.gateway.catalog(force);
439
+ const catalog = await this.gateway.catalogBundle(force);
439
440
  const endpoint = directBootstrap ? `http://127.0.0.1:${entry.profile.servicePort}/api/managed-model/invoke` : `http://127.0.0.1:${entry.reversePort}/model`;
440
- const content = JSON.stringify({ endpoint, token: secret.modelToken, models, defaultModel: this.defaultModel() });
441
- const hash = createHash("sha256").update(content).digest("hex");
442
- if (hash === entry.modelHash)
441
+ const config = { endpoint, token: secret.modelToken, ...catalog, defaultModel: this.defaultModel(), entryIntegrations: this.integrations?.available() };
442
+ const hash = createHash("sha256").update(JSON.stringify(config)).digest("hex");
443
+ if (!force && hash === entry.modelHash)
443
444
  return;
445
+ const content = JSON.stringify({ ...config, sharedCatalogAt: new Date().toISOString() });
444
446
  await sshWrite(client, posix.join(entry.installation.root, "models.json"), content);
445
- const defaultModel = this.defaultModel() ?? (models[0] ? { provider: models[0].provider, modelId: models[0].id } : undefined);
446
- if (defaultModel)
447
- await sshWrite(client, posix.join(entry.installation.root, "agent", "settings.json"), JSON.stringify({ defaultProvider: defaultModel.provider, defaultModel: defaultModel.modelId }));
447
+ const defaultModel = this.defaultModel() ?? (catalog.models[0] ? { provider: catalog.models[0].provider, modelId: catalog.models[0].id } : undefined);
448
+ const settingsPath = posix.join(entry.installation.root, "agent", "settings.json");
449
+ if (!reload && defaultModel && (await sshExec(client, `test -e ${sh(settingsPath)} && echo present || true`)).trim() !== "present") {
450
+ await sshWrite(client, settingsPath, JSON.stringify({ defaultProvider: defaultModel.provider, defaultModel: defaultModel.modelId }));
451
+ }
448
452
  if (reload)
449
453
  await this.serviceJson(entry, "/api/managed-model/reload", "POST");
450
454
  entry.modelHash = hash;
@@ -514,6 +518,8 @@ export class ManagedServers {
514
518
  profile.transport = "direct";
515
519
  profile.service = "online";
516
520
  delete profile.serviceError;
521
+ if (isModelConfigurationMode(health.modelMode))
522
+ profile.modelMode = health.modelMode;
517
523
  if (entry.installation && health.modelRelay === true && !this.stopped) {
518
524
  profile.modelTransport = "direct";
519
525
  delete profile.modelChannelPaused;
@@ -1019,6 +1025,7 @@ export class ManagedServers {
1019
1025
  else if (action === "sync") {
1020
1026
  try {
1021
1027
  await this.syncModels(id, true);
1028
+ delete entry.profile.modelError;
1022
1029
  }
1023
1030
  catch (error) {
1024
1031
  entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
@@ -277,6 +277,7 @@ export type GroupExecutionLifecycle = {
277
277
  export type IsolatedCompletionInput = {
278
278
  images?: import("./types.js").PiImageContent[];
279
279
  onConversation?(conversationId: string): Promise<void> | void;
280
+ onRequest?(messageId: string): Promise<void> | void;
280
281
  userToolContext?: {
281
282
  id: string;
282
283
  workspaceId: string;
@@ -0,0 +1,8 @@
1
+ import type { Model } from "@earendil-works/pi-ai";
2
+ export type SharedCatalogModel = Pick<Model<string>, "provider" | "id" | "name" | "api" | "baseUrl" | "reasoning" | "input" | "cost" | "contextWindow" | "maxTokens" | "thinkingLevelMap"> & {
3
+ compat?: Record<string, boolean | string>;
4
+ };
5
+ export declare const validSharedProviderId: (id: unknown) => id is string;
6
+ /** Project only model definitions. URLs with embedded authentication or query parameters stay local. */
7
+ export declare function sharedCatalogModels(models: readonly unknown[]): SharedCatalogModel[];
8
+ export declare function sharedProviderModels(models: readonly SharedCatalogModel[]): Map<string, Omit<SharedCatalogModel, "provider">[]>;
@@ -0,0 +1,45 @@
1
+ import { PI_THINKING_LEVELS } from "../shared/thinking-levels.js";
2
+ export const validSharedProviderId = (id) => typeof id === "string" && /^[a-z0-9_.-]{1,160}$/i.test(id) && !Object.hasOwn(Object.prototype, id) && id !== "prototype";
3
+ const compatibilityFlags = ["supportsDeveloperRole", "supportsReasoningEffort", "supportsStore", "supportsStrictMode", "requiresToolResultName", "requiresAssistantAfterToolResult", "requiresThinkingAsText", "supportsUsageInStreaming"];
4
+ const compatibilityChoices = {
5
+ maxTokensField: ["max_tokens", "max_completion_tokens"],
6
+ thinkingFormat: ["ant-ling", "baseten", "chat-template", "deepseek", "openai", "openrouter", "qwen", "qwen-chat-template", "string-thinking", "together", "zai"],
7
+ };
8
+ /** Project only model definitions. URLs with embedded authentication or query parameters stay local. */
9
+ export function sharedCatalogModels(models) {
10
+ return models.flatMap(value => {
11
+ const model = value;
12
+ if (!model || !validSharedProviderId(model.provider) || typeof model.id !== "string" || !model.id ||
13
+ typeof model.api !== "string" || typeof model.baseUrl !== "string" || typeof model.name !== "string")
14
+ return [];
15
+ try {
16
+ const url = new URL(model.baseUrl);
17
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
18
+ return [];
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ const number = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
24
+ const cost = { input: number(model.cost?.input), output: number(model.cost?.output), cacheRead: number(model.cost?.cacheRead), cacheWrite: number(model.cost?.cacheWrite) };
25
+ const thinkingLevelMap = Object.fromEntries(PI_THINKING_LEVELS.flatMap(level => {
26
+ const value = model.thinkingLevelMap?.[level];
27
+ return value === null || typeof value === "number" || (typeof value === "string" && /^[a-z0-9_-]{1,32}$/i.test(value)) ? [[level, value]] : [];
28
+ }));
29
+ const compat = model.compat && Object.fromEntries(Object.entries(model.compat).filter(([key, value]) => typeof value === "boolean" ? compatibilityFlags.includes(key) :
30
+ typeof value === "string" && Object.hasOwn(compatibilityChoices, key) && compatibilityChoices[key].includes(value)));
31
+ const input = Array.isArray(model.input) && model.input.includes("image") ? ["text", "image"] : ["text"];
32
+ return [{ provider: model.provider, id: model.id, name: model.name, api: model.api, baseUrl: model.baseUrl,
33
+ reasoning: model.reasoning === true, input, cost, contextWindow: number(model.contextWindow), maxTokens: number(model.maxTokens),
34
+ ...(Object.keys(thinkingLevelMap).length ? { thinkingLevelMap } : {}), ...(compat && Object.keys(compat).length ? { compat } : {}) }];
35
+ });
36
+ }
37
+ export function sharedProviderModels(models) {
38
+ const providers = new Map();
39
+ for (const { provider, ...model } of models) {
40
+ const group = providers.get(provider) ?? [];
41
+ group.push(model);
42
+ providers.set(provider, group);
43
+ }
44
+ return providers;
45
+ }
@@ -7,6 +7,7 @@ import type { WorkflowRun } from "./workflow.js";
7
7
  import type { AppState, BackgroundTaskSummary, Conversation, Message, MessageDelivery, MessageImage, ModelSelection, Project, SubagentRun, SubagentRunUpdate, TodoItem, ToolCallQuestion, ToolCallArg, ToolCallBlock, ToolResultSummary, Workspace } from "./types.js";
8
8
  import { type BackgroundCompletion } from "../shared/background-task.js";
9
9
  import type { TurnUsageReadout } from "./conversation-usage.js";
10
+ import type { RequestOutcome } from "../shared/request-timing.js";
10
11
  /** Mints the id a forked conversation will have, BEFORE its Pi transcript exists.
11
12
  *
12
13
  * Exported because the ordering demands it and no other arrangement provides it. Pi's copied file's header
@@ -499,7 +500,7 @@ export declare class Store {
499
500
  * `composePrompt` in the run service). So the instruction reaches the model the same way, and the
500
501
  * reader sees who spoke.
501
502
  */
502
- addAgentMessage(conversationId: string, content: string, options?: Pick<Message, "delivery" | "source" | "images">): Promise<Message>;
503
+ addAgentMessage(conversationId: string, content: string, options?: Pick<Message, "delivery" | "source" | "images" | "requestTiming" | "timingRequestIds">): Promise<Message>;
503
504
  addUserMessage(conversationId: string, content: string, images?: MessageImage[], attachments?: import("./types.js").MessageAttachments, options?: {
504
505
  clientId?: string;
505
506
  delivery?: Message["delivery"];
@@ -773,6 +774,15 @@ export declare class Store {
773
774
  private waitingMessages;
774
775
  private requireWaitingMessage;
775
776
  private persistMessages;
777
+ requestTiming(conversationId: string, messageId: string): {
778
+ startedAt?: string;
779
+ responseEndedAt?: string;
780
+ endedAt?: string;
781
+ outcome?: RequestOutcome;
782
+ } | undefined;
783
+ private linkRequestTiming;
784
+ private settleRequests;
785
+ finishRequestReply(conversationId: string, replyId: string, promptId: string, outcome: RequestOutcome): Promise<void>;
776
786
  /**
777
787
  * Claims one waiting message for delivery to the live Pi process: `waiting` becomes `sending`, and the
778
788
  * message STAYS WHERE IT IS - still on screen, still in the transcript, still at the same index.
@@ -624,6 +624,7 @@ function backgroundTaskMessage(conversation, task, outcome, content, deliver) {
624
624
  content,
625
625
  createdAt: finished.finishedAt,
626
626
  backgroundTask: anchored ? { ...finished, output: undefined } : finished,
627
+ ...(origin?.timingRequestIds?.length ? { timingRequestIds: origin.timingRequestIds } : {}),
627
628
  ...(deliver && !conversation.archivedAt ? { delivery: "waiting" } : {}),
628
629
  };
629
630
  conversation.messages.push(message);
@@ -759,6 +760,15 @@ export class Store {
759
760
  const orphanedTasks = reconcileBackgroundTasks(state);
760
761
  const interrupted = reconcileConversations(state);
761
762
  const requeued = reconcileWaitingMessages(state);
763
+ let interruptedTiming = false;
764
+ for (const conversation of state.conversations)
765
+ for (const message of conversation?.messages ?? []) {
766
+ const timing = message.requestTiming;
767
+ if (timing?.startedAt && !timing.outcome) {
768
+ timing.outcome = "interrupted";
769
+ interruptedTiming = true;
770
+ }
771
+ }
762
772
  const todos = reconcileTodos(state);
763
773
  // THE USAGE SWEEP. A run recorded before the conversation ledger existed has its money sitting in
764
774
  // the run record and nowhere else, so the ledger is brought up to date here - once, and only
@@ -768,7 +778,7 @@ export class Store {
768
778
  // Persisted here, in `open`, rather than left for the first unrelated write: a reconciled record that
769
779
  // is only rewritten by a later mutation would still read `running` to anything that opened the file
770
780
  // in the meantime, and would be reconciled a SECOND time on the next restart.
771
- if (defaulted || migratedProjects || orphaned.length || orphanedWorkflows.length || orphanedTasks.changed || interrupted.length || requeued.recovered.length || requeued.changed || todos.changed || foldedUsage) {
781
+ if (defaulted || migratedProjects || orphaned.length || orphanedWorkflows.length || orphanedTasks.changed || interrupted.length || interruptedTiming || requeued.recovered.length || requeued.changed || todos.changed || foldedUsage) {
772
782
  for (const run of orphaned)
773
783
  console.warn(`Super Pi: sub-agent run ${run.id} was still marked running when the last server stopped - it is now failed, because no child process survived it.`);
774
784
  for (const plan of orphanedWorkflows)
@@ -1987,6 +1997,10 @@ export class Store {
1987
1997
  message.images = structuredClone(options.images);
1988
1998
  if (options?.delivery)
1989
1999
  message.delivery = options.delivery;
2000
+ if (options?.requestTiming)
2001
+ message.requestTiming = {};
2002
+ if (options?.timingRequestIds?.length)
2003
+ message.timingRequestIds = [...options.timingRequestIds];
1990
2004
  conversation.messages.push(message);
1991
2005
  if (message.source === "session-reminder" && !message.delivery)
1992
2006
  await this.persistIncomingTurn(conversation, message);
@@ -2731,6 +2745,71 @@ export class Store {
2731
2745
  async persistMessages(conversation, acceptedSendId, metadata) {
2732
2746
  await this.persistTransaction({ kind: "conversation.messages", conversationId: conversation.id, messages: structuredClone(conversation.messages), updatedAt: conversation.updatedAt, ...(acceptedSendId ? { acceptedSendId } : {}), ...(metadata ? { metadata: structuredClone(metadata) } : {}) });
2733
2747
  }
2748
+ requestTiming(conversationId, messageId) {
2749
+ const timing = this.state.conversations.find(item => item.id === conversationId)?.messages.find(item => item.id === messageId)?.requestTiming;
2750
+ return timing && { ...timing };
2751
+ }
2752
+ linkRequestTiming(conversation, prompts, assistant) {
2753
+ const ids = new Set(prompts.flatMap(message => {
2754
+ if (message.role === "user" || message.requestTiming) {
2755
+ message.requestTiming ??= {};
2756
+ message.requestTiming.startedAt ??= assistant.createdAt;
2757
+ return [message.id];
2758
+ }
2759
+ return message.timingRequestIds ?? [];
2760
+ }));
2761
+ if (!ids.size)
2762
+ return;
2763
+ assistant.timingRequestIds = [...ids];
2764
+ for (const message of conversation.messages)
2765
+ if (ids.has(message.id) && message.requestTiming?.outcome === "incomplete") {
2766
+ delete message.requestTiming.endedAt;
2767
+ delete message.requestTiming.outcome;
2768
+ }
2769
+ }
2770
+ settleRequests(conversation, ids, outcome = "completed") {
2771
+ if (!ids.length)
2772
+ return;
2773
+ const requested = new Set(ids);
2774
+ const messagesById = new Map(conversation.messages.map(message => [message.id, message]));
2775
+ const pending = new Set();
2776
+ if (outcome === "completed") {
2777
+ for (const message of conversation.messages) {
2778
+ if (message.delivery || (message.role === "assistant" && !message.timingReplyEnded)) {
2779
+ for (const id of message.timingRequestIds ?? [])
2780
+ if (requested.has(id))
2781
+ pending.add(id);
2782
+ }
2783
+ }
2784
+ for (const task of this.state.backgroundTasks) {
2785
+ if (task.conversationId !== conversation.id || !task.originMessageId)
2786
+ continue;
2787
+ for (const id of messagesById.get(task.originMessageId)?.timingRequestIds ?? [])
2788
+ if (requested.has(id))
2789
+ pending.add(id);
2790
+ }
2791
+ }
2792
+ const endedAt = now();
2793
+ for (const id of requested) {
2794
+ const timing = messagesById.get(id)?.requestTiming;
2795
+ if (!timing?.responseEndedAt || timing.outcome || pending.has(id))
2796
+ continue;
2797
+ timing.endedAt = endedAt;
2798
+ timing.outcome = outcome;
2799
+ }
2800
+ }
2801
+ async finishRequestReply(conversationId, replyId, promptId, outcome) {
2802
+ const conversation = this.requireConversation(conversationId);
2803
+ const assistant = conversation.messages.find(message => message.id === replyId);
2804
+ if (!assistant?.timingRequestIds?.length || assistant.timingReplyEnded)
2805
+ return;
2806
+ assistant.timingReplyEnded = true;
2807
+ const prompt = conversation.messages.find(message => message.id === promptId);
2808
+ if (prompt?.requestTiming)
2809
+ prompt.requestTiming.responseEndedAt ??= now();
2810
+ this.settleRequests(conversation, assistant.timingRequestIds, outcome);
2811
+ await this.persistMessages(conversation);
2812
+ }
2734
2813
  /**
2735
2814
  * Claims one waiting message for delivery to the live Pi process: `waiting` becomes `sending`, and the
2736
2815
  * message STAYS WHERE IT IS - still on screen, still in the transcript, still at the same index.
@@ -2843,6 +2922,7 @@ export class Store {
2843
2922
  if (message.delivery === "sending")
2844
2923
  throw new Error("这条消息已经交给 Agent 了,取消不掉(Pi 没有撤回单条队列消息的能力)");
2845
2924
  const [removed] = conversation.messages.splice(index, 1);
2925
+ this.settleRequests(conversation, removed.timingRequestIds ?? []);
2846
2926
  await this.persistMessages(conversation);
2847
2927
  return structuredClone(removed);
2848
2928
  }
@@ -2942,6 +3022,7 @@ export class Store {
2942
3022
  conversation.messages.splice(deliveryIndex, 0, user);
2943
3023
  delete user.delivery;
2944
3024
  const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
3025
+ this.linkRequestTiming(conversation, [user], assistant);
2945
3026
  conversation.messages.splice(deliveryIndex + 1, 0, assistant);
2946
3027
  await this.persistMessages(conversation);
2947
3028
  return { user: structuredClone(user), assistant: structuredClone(assistant) };
@@ -2998,6 +3079,7 @@ export class Store {
2998
3079
  }
2999
3080
  conversation.messages.splice(deliveryIndex, 0, ...batch);
3000
3081
  const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
3082
+ this.linkRequestTiming(conversation, batch, assistant);
3001
3083
  conversation.messages.splice(deliveryIndex + batch.length, 0, assistant);
3002
3084
  const firstUser = conversation.messages.find((item) => item.role === "user");
3003
3085
  const autoTitle = firstUser?.content.trim()
@@ -3162,6 +3244,8 @@ export class Store {
3162
3244
  const conversation = this.state.conversations.find(item => item.id === task.conversationId);
3163
3245
  this.state.backgroundTasks = this.state.backgroundTasks.filter(item => item.id !== taskId);
3164
3246
  const message = conversation && backgroundTaskMessage(conversation, task, outcome, content, deliver);
3247
+ if (conversation && message && !message.delivery)
3248
+ this.settleRequests(conversation, message.timingRequestIds ?? []);
3165
3249
  if (message?.delivery === "waiting" && conversation) {
3166
3250
  const waiting = this.waitingMessages(conversation);
3167
3251
  const lastSending = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);