@evandu/super-pi 0.1.246 → 0.1.248

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.
@@ -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-Dx58PQcK.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-CVSDagOL.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-DGpbsE3E.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-NdrxLvOm.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -32,6 +32,7 @@ export declare class ProviderService {
32
32
  private readonly broadcaster;
33
33
  private readonly catalogService;
34
34
  private readonly store;
35
+ private readonly oauthJobs;
35
36
  constructor(registry: ProviderRegistry, runtime: AgentRuntime, broadcaster: EventBroadcaster, catalogService: CatalogService, store: Store);
36
37
  /**
37
38
  * Every provider Pi knows about, as the browser may see it: no keys, only the fact of one.
@@ -45,6 +46,27 @@ export declare class ProviderService {
45
46
  * because that provider is a built-in whose only configuration is a credential.
46
47
  */
47
48
  list(): Promise<PublicProvider[]>;
49
+ oauthSnapshot(): {
50
+ id: string;
51
+ providerId: string;
52
+ state: string;
53
+ event?: Record<string, unknown>;
54
+ prompt?: {
55
+ type: string;
56
+ message: string;
57
+ placeholder?: string;
58
+ options?: {
59
+ id: string;
60
+ label: string;
61
+ description?: string;
62
+ }[];
63
+ };
64
+ error?: string;
65
+ }[];
66
+ startOAuthLogin(providerId: unknown): Promise<string>;
67
+ answerOAuthPrompt(id: unknown, answer: unknown): void;
68
+ cancelOAuthLogin(id: unknown): void;
69
+ logoutOAuth(providerId: unknown): Promise<void>;
48
70
  /**
49
71
  * Turns a provider off, then makes every LIVE conversation stop pointing at the models it removed.
50
72
  *
@@ -3,6 +3,7 @@ import { readProviderProxyEnv } from "../provider-proxy.js";
3
3
  import { piAgentDir } from "../providers.js";
4
4
  import { hasStoredCredential } from "../provider-network.js";
5
5
  import { thinkingLevelsEndpoint } from "../../shared/thinking-levels.js";
6
+ import { randomUUID } from "node:crypto";
6
7
  /**
7
8
  * THE PROVIDERS A PERSON ADDED, as a service.
8
9
  *
@@ -31,6 +32,7 @@ export class ProviderService {
31
32
  broadcaster;
32
33
  catalogService;
33
34
  store;
35
+ oauthJobs = new Map();
34
36
  constructor(registry, runtime, broadcaster, catalogService, store) {
35
37
  this.registry = registry;
36
38
  this.runtime = runtime;
@@ -93,7 +95,102 @@ export class ProviderService {
93
95
  disabled: true,
94
96
  models: entry.models,
95
97
  }));
96
- return publicProviders([...configured, ...credentialOnly, ...offList]);
98
+ const base = publicProviders([...configured, ...credentialOnly, ...offList]);
99
+ const oauth = await this.runtime.oauthProviders?.() ?? [];
100
+ const byId = new Map(base.map((provider) => [provider.id, provider]));
101
+ for (const info of oauth) {
102
+ const provider = byId.get(info.id) ?? {
103
+ id: info.id, name: info.name, baseUrl: "", api: "", hasKey: info.authenticated,
104
+ builtin: true, models: [],
105
+ };
106
+ provider.name = info.name;
107
+ provider.authType = "oauth";
108
+ provider.oauthSubscription = info.isSubscription;
109
+ if (info.loginLabel)
110
+ provider.oauthLoginLabel = info.loginLabel;
111
+ provider.authenticated = info.authenticated;
112
+ provider.hasKey = info.authenticated;
113
+ provider.builtin = true;
114
+ byId.set(info.id, provider);
115
+ }
116
+ return [...byId.values()];
117
+ }
118
+ oauthSnapshot() {
119
+ return [...this.oauthJobs.values()].map(({ answer: _answer, abort: _abort, ...job }) => structuredClone(job));
120
+ }
121
+ async startOAuthLogin(providerId) {
122
+ if (typeof providerId !== "string" || !providerId)
123
+ throw new Error("请选择 Pi 内置的授权供应商。");
124
+ const provider = (await this.runtime.oauthProviders?.() ?? []).find((item) => item.id === providerId);
125
+ if (!provider)
126
+ throw new Error("Pi 当前版本不支持这个供应商的 OAuth 登录。");
127
+ for (const job of this.oauthJobs.values())
128
+ if (job.providerId === providerId && ["starting", "authorizing", "prompt"].includes(job.state))
129
+ this.cancelOAuthLogin(job.id);
130
+ if (this.oauthJobs.size >= 20) {
131
+ for (const [id, job] of this.oauthJobs)
132
+ if (!["starting", "authorizing", "prompt"].includes(job.state)) {
133
+ this.oauthJobs.delete(id);
134
+ break;
135
+ }
136
+ if (this.oauthJobs.size >= 20)
137
+ throw new Error("同时进行的 OAuth 登录过多,请先完成或取消一个登录。");
138
+ }
139
+ const job = { id: randomUUID(), providerId, state: "starting", abort: new AbortController() };
140
+ this.oauthJobs.set(job.id, job);
141
+ void (async () => {
142
+ try {
143
+ await this.runtime.loginOAuth(providerId, {
144
+ signal: job.abort.signal,
145
+ notify: (event) => { job.event = event && typeof event === "object" ? structuredClone(event) : undefined; job.state = event?.type === "auth_url" || event?.type === "device_code" ? "authorizing" : "starting"; },
146
+ prompt: (prompt) => new Promise((resolve, reject) => {
147
+ job.prompt = { type: String(prompt.type ?? "text"), message: String(prompt.message ?? "Pi 需要输入授权信息"),
148
+ ...(typeof prompt.placeholder === "string" ? { placeholder: prompt.placeholder } : {}),
149
+ ...(Array.isArray(prompt.options) ? { options: prompt.options.map((item) => ({ id: String(item.id), label: String(item.label), ...(item.description ? { description: String(item.description) } : {}) })) } : {}) };
150
+ job.state = "prompt";
151
+ const signal = prompt.signal ?? job.abort.signal;
152
+ const abort = () => { job.answer = undefined; job.prompt = undefined; reject(new Error("登录已取消。")); };
153
+ signal.addEventListener("abort", abort, { once: true });
154
+ job.answer = (value) => { signal.removeEventListener("abort", abort); job.prompt = undefined; job.answer = undefined; resolve(value); };
155
+ if (signal.aborted)
156
+ abort();
157
+ }),
158
+ });
159
+ job.state = "completed";
160
+ job.event = undefined;
161
+ await this.afterChange();
162
+ }
163
+ catch (error) {
164
+ job.state = job.abort.signal.aborted ? "cancelled" : "failed";
165
+ job.error = job.abort.signal.aborted ? "登录已取消。" : "Pi OAuth 登录失败,请重试并检查授权页面。";
166
+ job.prompt = undefined;
167
+ job.event = undefined;
168
+ }
169
+ })();
170
+ return job.id;
171
+ }
172
+ answerOAuthPrompt(id, answer) {
173
+ const job = this.oauthJobs.get(String(id));
174
+ if (!job || job.state !== "prompt" || !job.answer || typeof answer !== "string" || answer.length > 8192)
175
+ throw new Error("授权输入已过期,请重新登录。");
176
+ const submit = job.answer;
177
+ submit(answer);
178
+ }
179
+ cancelOAuthLogin(id) {
180
+ const job = this.oauthJobs.get(String(id));
181
+ if (!job || !["starting", "authorizing", "prompt"].includes(job.state))
182
+ return;
183
+ job.state = "cancelled";
184
+ job.abort.abort();
185
+ job.answer?.("");
186
+ job.answer = undefined;
187
+ job.prompt = undefined;
188
+ }
189
+ async logoutOAuth(providerId) {
190
+ if (typeof providerId !== "string" || !(await this.runtime.oauthProviders?.() ?? []).some((item) => item.id === providerId))
191
+ throw new Error("Pi 当前版本不支持这个供应商。");
192
+ await this.runtime.logoutOAuth?.(providerId);
193
+ await this.afterChange([{ provider: providerId }]);
97
194
  }
98
195
  /**
99
196
  * Turns a provider off, then makes every LIVE conversation stop pointing at the models it removed.
@@ -13,7 +13,7 @@ import { toWorkspaceRelative } from "../files.js";
13
13
  import { inScope, refreshWorkspaceIndex } from "../file-index.js";
14
14
  import { resolveSessionCwd } from "../session-cwd.js";
15
15
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
16
- import { BACKGROUND_LOG_LIMIT, subagentProgress } from "../../shared/background-task.js";
16
+ import { BACKGROUND_LOG_LIMIT, sanitizeBackgroundOutput, subagentProgress } from "../../shared/background-task.js";
17
17
  import { execFile } from "node:child_process";
18
18
  import { promisify } from "node:util";
19
19
  import { randomUUID } from "node:crypto";
@@ -332,7 +332,8 @@ export class RunService {
332
332
  const task = this.store.backgroundTask(sessionId);
333
333
  if (!task)
334
334
  return;
335
- const output = (stdout + stderr).slice(-BACKGROUND_LOG_LIMIT);
335
+ const rawOutput = stdout + stderr;
336
+ const output = sanitizeBackgroundOutput(rawOutput).slice(-BACKGROUND_LOG_LIMIT);
336
337
  const offset = completion?.offset ?? stdout.length + stderr.length;
337
338
  const status = completion?.status === "cancelled" || completion?.status === "interrupted"
338
339
  ? completion.status : exitCode === 0 && !completion?.signal ? "completed" : "failed";
@@ -341,7 +342,7 @@ export class RunService {
341
342
  : completion?.signal ? `进程收到信号 ${completion.signal}`
342
343
  : status === "failed" ? `Command exited with code ${exitCode}` : undefined;
343
344
  const settling = this.trackDetached(this.finishBackgroundResult(task, {
344
- status, output, outputOffset: offset, outputTruncated: offset > output.length,
345
+ status, output, outputOffset: offset, outputTruncated: offset > rawOutput.length,
345
346
  exitCode, signal: completion?.signal, reason,
346
347
  }, status === "completed" || status === "failed")).catch(error => {
347
348
  console.warn("Super Pi: could not record background command completion:", error);
@@ -47,4 +47,6 @@ export declare class WorkspaceService {
47
47
  * Updates workspace default settings (model, thinking level, default agent).
48
48
  */
49
49
  updateSettings(workspaceId: string, settings: WorkspaceSettingsUpdate): Promise<void>;
50
+ /** Validates once for every mounted workspace, then persists the shared defaults in one write. */
51
+ updateMountedWorkspaceSettings(settings: Pick<WorkspaceSettingsUpdate, "model" | "thinkingLevel">): Promise<number>;
50
52
  }
@@ -141,4 +141,46 @@ export class WorkspaceService {
141
141
  });
142
142
  this.broadcaster.broadcastState();
143
143
  }
144
+ /** Validates once for every mounted workspace, then persists the shared defaults in one write. */
145
+ async updateMountedWorkspaceSettings(settings) {
146
+ const workspaces = this.store.snapshot().workspaces.filter((item) => !item.closedAt);
147
+ if (!workspaces.length)
148
+ throw new Error("没有可更新的工作区。");
149
+ let selection;
150
+ if (settings.model) {
151
+ const available = await this.runtime.catalog();
152
+ const option = available.source === "pi"
153
+ ? available.models.find((model) => model.provider === settings.model?.provider && model.modelId === settings.model?.modelId)
154
+ : undefined;
155
+ if (available.source === "pi" && !option) {
156
+ throw this.catalogService.notOffered(`模型 ${settings.model.provider}/${settings.model.modelId}`, available);
157
+ }
158
+ selection = option
159
+ ? { provider: option.provider, modelId: option.modelId, label: option.label }
160
+ : { provider: settings.model.provider, modelId: settings.model.modelId, label: settings.model.modelId };
161
+ }
162
+ const thinkingLevel = settings.thinkingLevel ?? undefined;
163
+ if (thinkingLevel) {
164
+ if (!selection)
165
+ throw new Error("请先选择具体模型,再设置思考等级。");
166
+ const modelCatalog = await this.runtime.catalog(selection);
167
+ if (modelCatalog.source === "pi" && !modelCatalog.levels.includes(thinkingLevel)) {
168
+ throw this.catalogService.notOffered(`思考等级 ${thinkingLevel}`, modelCatalog);
169
+ }
170
+ }
171
+ if (selection) {
172
+ for (const workspace of workspaces) {
173
+ try {
174
+ assertModelAllowed(this.store.snapshot().modelFilterRules, workspace, selection);
175
+ }
176
+ catch (error) {
177
+ const detail = error instanceof Error ? error.message : String(error);
178
+ throw new Error(`无法批量修改:工作区「${workspace.name}」不允许该模型。${detail}`);
179
+ }
180
+ }
181
+ }
182
+ const updated = await this.store.setMountedWorkspaceDefaults({ model: selection, thinkingLevel });
183
+ this.broadcaster.broadcastState();
184
+ return updated;
185
+ }
144
186
  }
@@ -176,6 +176,13 @@ export class CommandHandler {
176
176
  });
177
177
  return;
178
178
  }
179
+ if (command.type === "workspaces.settings.bulk") {
180
+ await this.workspaceService.updateMountedWorkspaceSettings({
181
+ model: command.model,
182
+ thinkingLevel: command.thinkingLevel,
183
+ });
184
+ return;
185
+ }
179
186
  if (command.type === "conversation.create") {
180
187
  return await this.conversationService.createConversation(command.workspaceId, undefined, command.cwd);
181
188
  }
@@ -1010,6 +1010,51 @@ export function createHttpServer(options) {
1010
1010
  }
1011
1011
  return;
1012
1012
  }
1013
+ if (url.pathname === "/api/providers/oauth") {
1014
+ const remote = request.socket.remoteAddress;
1015
+ const origin = request.headers.origin;
1016
+ const fetchSite = request.headers["sec-fetch-site"];
1017
+ if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1018
+ json(403, { error: "供应商授权只允许本机或局域网的同源请求。" });
1019
+ return;
1020
+ }
1021
+ try {
1022
+ if (request.method === "GET") {
1023
+ json(200, { jobs: context.providerService.oauthSnapshot() });
1024
+ return;
1025
+ }
1026
+ if (request.method !== "POST") {
1027
+ json(405, { error: "供应商授权仅支持 GET / POST" });
1028
+ return;
1029
+ }
1030
+ const asked = await readRequestText(request, 16384);
1031
+ if (asked.tooLarge) {
1032
+ json(413, { error: "授权请求过大" });
1033
+ return;
1034
+ }
1035
+ const body = JSON.parse(asked.text || "{}");
1036
+ switch (body.action) {
1037
+ case "login":
1038
+ await context.providerService.startOAuthLogin(body.providerId);
1039
+ break;
1040
+ case "answer":
1041
+ context.providerService.answerOAuthPrompt(body.id, body.answer);
1042
+ break;
1043
+ case "cancel":
1044
+ context.providerService.cancelOAuthLogin(body.id);
1045
+ break;
1046
+ case "logout":
1047
+ await context.providerService.logoutOAuth(body.providerId);
1048
+ break;
1049
+ default: throw new Error("未知的授权操作。");
1050
+ }
1051
+ json(200, { jobs: context.providerService.oauthSnapshot() });
1052
+ }
1053
+ catch (error) {
1054
+ json(400, { error: error instanceof Error ? error.message : "供应商授权失败。" });
1055
+ }
1056
+ return;
1057
+ }
1013
1058
  if (url.pathname === "/api/providers/fetch-models") {
1014
1059
  if (request.method !== "POST") {
1015
1060
  response.writeHead(405).end();
@@ -8,6 +8,7 @@ import { homedir } from "node:os";
8
8
  import { join, resolve } from "node:path";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { isChildSession } from "../shared/child-session-lock.js";
11
+ import { sanitizeBackgroundOutput } from "../shared/background-task.js";
11
12
  import { openStateStore } from "./persistence/open-state-store.js";
12
13
  import { PiRpcRuntime, WelcomeRuntime } from "./runtime.js";
13
14
  import { agentModeOf, resolveAgentDirectories } from "./agents.js";
@@ -314,7 +315,7 @@ const terminalService = new TerminalService({
314
315
  * Background command execution, independent from subagents. Uses node-pty to run shell commands
315
316
  * and delivers results via WebSocket + injected conversation message.
316
317
  */
317
- const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr, completion) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr, completion), (sessionId, output, offset) => store.checkpointBackgroundOutput(sessionId, output, offset));
318
+ const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr, completion) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr, completion), (sessionId, output, offset) => store.checkpointBackgroundOutput(sessionId, sanitizeBackgroundOutput(output), offset));
318
319
  runService.setExecService(execService, join(dataDir, "background-logs"));
319
320
  replayRuntime = (state, scope) => execService.outputSnapshots(state, scope);
320
321
  projectRuntime = state => {
@@ -91,6 +91,29 @@ interface PiSdk {
91
91
  * when one entry in `models.json` is refused.
92
92
  */
93
93
  getError?: () => string | undefined;
94
+ getProviders?: () => readonly {
95
+ id: string;
96
+ name?: string;
97
+ auth?: {
98
+ oauth?: {
99
+ name?: string;
100
+ isSubscription?: boolean;
101
+ loginLabel?: string;
102
+ };
103
+ };
104
+ }[];
105
+ checkAuth?: (providerId: string) => Promise<{
106
+ type: string;
107
+ } | undefined>;
108
+ login?: (providerId: string, type: "oauth", interaction: {
109
+ signal?: AbortSignal;
110
+ prompt(prompt: any): Promise<string>;
111
+ notify(event: any): void;
112
+ }, options?: {
113
+ agentName?: string;
114
+ }) => Promise<unknown>;
115
+ logout?: (providerId: string) => Promise<void>;
116
+ refresh?: () => Promise<unknown>;
94
117
  }>;
95
118
  };
96
119
  AuthStorage?: {
@@ -188,6 +211,19 @@ export interface SdkCatalog {
188
211
  * settings panel shows instead of a guess.
189
212
  */
190
213
  configError(): string | undefined;
214
+ oauthProviders(): Promise<{
215
+ id: string;
216
+ name: string;
217
+ isSubscription: boolean;
218
+ loginLabel?: string;
219
+ authenticated: boolean;
220
+ }[]>;
221
+ loginOAuth(providerId: string, interaction: {
222
+ signal?: AbortSignal;
223
+ prompt(prompt: any): Promise<string>;
224
+ notify(event: any): void;
225
+ }): Promise<void>;
226
+ logoutOAuth(providerId: string): Promise<void>;
191
227
  }
192
228
  /**
193
229
  * What a session says about one model's thinking: the levels it offers, and the one in force.
@@ -122,6 +122,22 @@ export async function createSdkCatalog(cwd) {
122
122
  return {
123
123
  models,
124
124
  configError: () => modelRuntime.getError?.(),
125
+ oauthProviders: async () => Promise.all((modelRuntime.getProviders?.() ?? []).flatMap((provider) => provider.auth?.oauth
126
+ ? [Promise.resolve(modelRuntime.checkAuth?.(provider.id)).then((auth) => ({ id: provider.id, name: provider.auth.oauth.name ?? provider.name ?? provider.id,
127
+ isSubscription: provider.auth.oauth.isSubscription === true,
128
+ ...(provider.auth.oauth.loginLabel ? { loginLabel: provider.auth.oauth.loginLabel } : {}), authenticated: auth?.type === "oauth" }))]
129
+ : [])),
130
+ loginOAuth: async (providerId, interaction) => {
131
+ if (!modelRuntime.login)
132
+ throw new Error("当前 Pi SDK 不支持供应商登录。");
133
+ await modelRuntime.login(providerId, "oauth", interaction, { agentName: "Super Pi" });
134
+ await modelRuntime.refresh?.();
135
+ },
136
+ logoutOAuth: async (providerId) => {
137
+ if (!modelRuntime.logout)
138
+ throw new Error("当前 Pi SDK 不支持供应商退出登录。");
139
+ await modelRuntime.logout(providerId);
140
+ },
125
141
  ...(resolved ? { defaultModel: resolved.model } : {}),
126
142
  thinkingLevelsFor: async (model) => {
127
143
  const key = `${model.provider}/${model.modelId}`;
@@ -384,6 +384,19 @@ export interface AgentRuntime {
384
384
  * selected model silently clamps away.
385
385
  */
386
386
  catalog(selection?: ModelSelection): Promise<ModelCatalog>;
387
+ oauthProviders?(): Promise<{
388
+ id: string;
389
+ name: string;
390
+ isSubscription: boolean;
391
+ loginLabel?: string;
392
+ authenticated: boolean;
393
+ }[]>;
394
+ loginOAuth?(providerId: string, interaction: {
395
+ signal: AbortSignal;
396
+ prompt(prompt: any): Promise<string>;
397
+ notify(event: any): void;
398
+ }): Promise<void>;
399
+ logoutOAuth?(providerId: string): Promise<void>;
387
400
  /**
388
401
  * Throws away every cached answer about the models Pi offers.
389
402
  *
@@ -1272,6 +1285,19 @@ export declare class PiRpcRuntime implements AgentRuntime {
1272
1285
  * what just changed.
1273
1286
  */
1274
1287
  invalidateCatalog(): void;
1288
+ oauthProviders(): Promise<never[] | {
1289
+ id: string;
1290
+ name: string;
1291
+ isSubscription: boolean;
1292
+ loginLabel?: string;
1293
+ authenticated: boolean;
1294
+ }[]>;
1295
+ loginOAuth(providerId: string, interaction: {
1296
+ signal: AbortSignal;
1297
+ prompt(prompt: any): Promise<string>;
1298
+ notify(event: any): void;
1299
+ }): Promise<void>;
1300
+ logoutOAuth(providerId: string): Promise<void>;
1275
1301
  /**
1276
1302
  * Makes every live session stale, so the next turn builds one that knows the current models.
1277
1303
  *
@@ -34,6 +34,7 @@ import { loadConversationImages } from "./upload.js";
34
34
  import { describeToolCall, describeToolCallArgs, describeToolCallInProgress, extractPartialResultText, extractToolResultText, readQuestionCall } from "./tool-calls.js";
35
35
  import { InlineThinkingSplitter, stripInlineThinking } from "./inline-thinking.js";
36
36
  import { toolTargetPath } from "./file-changes.js";
37
+ import { offeredThinkingLevels, readThinkingLevelMap } from "../shared/thinking-levels.js";
37
38
  const traceLatency = (conversationId, phase, startedAt, extra = "") => {
38
39
  if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
39
40
  return;
@@ -2894,6 +2895,19 @@ export class PiRpcRuntime {
2894
2895
  this.pendingCatalogs.clear();
2895
2896
  this.sdkCatalogPromise = undefined;
2896
2897
  }
2898
+ async oauthProviders() { return (await this.sdkCatalog())?.oauthProviders() ?? []; }
2899
+ async loginOAuth(providerId, interaction) {
2900
+ const catalog = await this.sdkCatalog();
2901
+ if (!catalog)
2902
+ throw new Error("Pi 的供应商登录功能不可用。");
2903
+ await catalog.loginOAuth(providerId, interaction);
2904
+ }
2905
+ async logoutOAuth(providerId) {
2906
+ const catalog = await this.sdkCatalog();
2907
+ if (!catalog)
2908
+ throw new Error("Pi 的供应商登录功能不可用。");
2909
+ await catalog.logoutOAuth(providerId);
2910
+ }
2897
2911
  /**
2898
2912
  * Makes every live session stale, so the next turn builds one that knows the current models.
2899
2913
  *
@@ -3231,7 +3245,9 @@ export function describeModel(value) {
3231
3245
  // check is here because this runs against a field read off the wire from a process that does no
3232
3246
  // validation of its own.
3233
3247
  const input = Array.isArray(model.input) ? model.input.filter((value) => typeof value === "string") : [];
3234
- return { provider: model.provider, modelId: model.id, label, detail: `${model.provider}/${model.id}`, reasoning: model.reasoning === true, contextWindow: typeof model.contextWindow === "number" ? model.contextWindow : 0, maxTokens: typeof model.maxTokens === "number" ? model.maxTokens : 0, imageInput: input.includes("image") };
3248
+ const thinkingLevelMap = readThinkingLevelMap(model.thinkingLevelMap);
3249
+ const thinkingLevels = thinkingLevelMap ? offeredThinkingLevels(thinkingLevelMap) : undefined;
3250
+ return { provider: model.provider, modelId: model.id, label, detail: `${model.provider}/${model.id}`, reasoning: model.reasoning === true, contextWindow: typeof model.contextWindow === "number" ? model.contextWindow : 0, maxTokens: typeof model.maxTokens === "number" ? model.maxTokens : 0, imageInput: input.includes("image"), ...(thinkingLevels ? { thinkingLevels } : {}) };
3235
3251
  }
3236
3252
  export function describeModels(value) {
3237
3253
  if (!Array.isArray(value))
@@ -254,6 +254,11 @@ export declare class Store {
254
254
  thinkingLevel?: string;
255
255
  agentId?: string | null;
256
256
  }): Promise<Workspace>;
257
+ /** Applies the shared model defaults to every mounted workspace and writes them together. */
258
+ setMountedWorkspaceDefaults(defaults: {
259
+ model?: ModelSelection;
260
+ thinkingLevel?: string;
261
+ }): Promise<number>;
257
262
  /**
258
263
  * TAKES A WORKSPACE OUT OF THE SIDEBAR. IT DOES NOT DELETE ANYTHING.
259
264
  *
@@ -1264,6 +1264,47 @@ export class Store {
1264
1264
  await this.persist();
1265
1265
  return structuredClone(workspace);
1266
1266
  }
1267
+ /** Applies the shared model defaults to every mounted workspace and writes them together. */
1268
+ async setMountedWorkspaceDefaults(defaults) {
1269
+ const workspaces = this.state.workspaces.filter((workspace) => !workspace.closedAt);
1270
+ if (!workspaces.length)
1271
+ throw new Error("没有可更新的工作区。");
1272
+ const previous = workspaces.map((workspace) => ({
1273
+ workspace,
1274
+ defaultModel: workspace.defaultModel ? { ...workspace.defaultModel } : undefined,
1275
+ defaultThinkingLevel: workspace.defaultThinkingLevel,
1276
+ updatedAt: workspace.updatedAt,
1277
+ }));
1278
+ for (const workspace of workspaces) {
1279
+ if (defaults.model === undefined)
1280
+ delete workspace.defaultModel;
1281
+ else
1282
+ workspace.defaultModel = { ...defaults.model };
1283
+ if (defaults.thinkingLevel === undefined)
1284
+ delete workspace.defaultThinkingLevel;
1285
+ else
1286
+ workspace.defaultThinkingLevel = defaults.thinkingLevel;
1287
+ workspace.updatedAt = now();
1288
+ }
1289
+ try {
1290
+ await this.persist();
1291
+ }
1292
+ catch (error) {
1293
+ for (const saved of previous) {
1294
+ if (saved.defaultModel)
1295
+ saved.workspace.defaultModel = saved.defaultModel;
1296
+ else
1297
+ delete saved.workspace.defaultModel;
1298
+ if (saved.defaultThinkingLevel === undefined)
1299
+ delete saved.workspace.defaultThinkingLevel;
1300
+ else
1301
+ saved.workspace.defaultThinkingLevel = saved.defaultThinkingLevel;
1302
+ saved.workspace.updatedAt = saved.updatedAt;
1303
+ }
1304
+ throw error;
1305
+ }
1306
+ return workspaces.length;
1307
+ }
1267
1308
  /**
1268
1309
  * TAKES A WORKSPACE OUT OF THE SIDEBAR. IT DOES NOT DELETE ANYTHING.
1269
1310
  *
@@ -380,6 +380,8 @@ export type ModelSelection = {
380
380
  * one boolean instead of a modality list it would have to interpret. It is CATALOG state, never
381
381
  * conversation state: a copy frozen onto a conversation would be wrong the moment Pi changed a
382
382
  * model, and nothing reads one - see the note on `setConversationModel`.
383
+ * `thinkingLevels` is the similarly small, derived list for a model-specific settings picker; the
384
+ * active session's levels cannot stand in for a different model selected as a workspace default.
383
385
  */
384
386
  export type ModelOption = ModelSelection & {
385
387
  detail: string;
@@ -387,6 +389,7 @@ export type ModelOption = ModelSelection & {
387
389
  contextWindow: number;
388
390
  maxTokens: number;
389
391
  imageInput: boolean;
392
+ thinkingLevels?: string[];
390
393
  };
391
394
  /**
392
395
  * What the picker lists, read from Pi and cached by the runtime.
@@ -425,6 +428,10 @@ export type PublicProvider = {
425
428
  baseUrl: string;
426
429
  api: string;
427
430
  hasKey: boolean;
431
+ authType?: "api_key" | "oauth";
432
+ oauthSubscription?: boolean;
433
+ oauthLoginLabel?: string;
434
+ authenticated?: boolean;
428
435
  /**
429
436
  * TRUE when the key lives in `models.json` itself (Pi's `"apiKey": "$MY_KEY"` form) rather than
430
437
  * in `auth.json`. It is a credential all the same, so the panel must not report it as missing.
@@ -1566,6 +1573,13 @@ export type ClientCommandBody =
1566
1573
  } | null;
1567
1574
  thinkingLevel: string | null;
1568
1575
  agentId?: string | null;
1576
+ } | {
1577
+ type: "workspaces.settings.bulk";
1578
+ model: {
1579
+ provider: string;
1580
+ modelId: string;
1581
+ } | null;
1582
+ thinkingLevel: string | null;
1569
1583
  } | {
1570
1584
  type: "conversation.create";
1571
1585
  workspaceId: string;
@@ -10,6 +10,9 @@ export type BackgroundTaskDetails = {
10
10
  reason?: string;
11
11
  };
12
12
  export declare const BACKGROUND_LOG_LIMIT = 128000;
13
+ /** Render a PTY byte stream as readable text for logs and chat. This is deliberately a text view, not a
14
+ * terminal UI: cursor movement edits the buffered lines, while colour, title and mode controls vanish. */
15
+ export declare function sanitizeBackgroundOutput(value: string): string;
13
16
  export type BackgroundCompletion = Omit<BackgroundTaskDetails, "id" | "status"> & {
14
17
  status: Exclude<BackgroundTaskStatus, "running">;
15
18
  };