pi-web-ui 0.114.1 → 0.114.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +187 -187
- package/README.zh-CN.md +227 -227
- package/README.zh-TW.md +227 -227
- package/bin/device-hub-cli.mjs +577 -577
- package/bin/frp-manager.mjs +1573 -1573
- package/bin/pi-device-hub.mjs +9 -9
- package/bin/pi-web-ui.mjs +4081 -4081
- package/deploy/nginx-subpath.conf +100 -100
- package/deploy/pi-web-ui.service +36 -36
- package/dist/server/agent-service.js +59 -10
- package/dist/server/attachments.js +6 -6
- package/dist/server/canvas/canvas-orchestrator.js +3 -3
- package/dist/server/communicate-tool.js +37 -11
- package/dist/server/compaction-instructions.js +8 -8
- package/dist/server/device-center/desktop-page.js +228 -228
- package/dist/server/device-center/hub-page.js +64 -64
- package/dist/server/device-center/native-desktop/macos.js +190 -190
- package/dist/server/device-center/native-desktop/windows.js +116 -116
- package/dist/server/dsh/runtime/cordis.yml +1 -1
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
- package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
- package/dist/server/dsh/runtime/launcher.mjs +235 -235
- package/dist/server/dsh/runtime/override.patch.yml +89 -89
- package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
- package/dist/server/durable/durable-event-projector.js +19 -3
- package/dist/server/durable/durable-models.js +134 -65
- package/dist/server/eval-tool.js +135 -135
- package/dist/server/model-resolver.js +4 -1
- package/dist/server/patch-bash-process.js +89 -89
- package/dist/server/patch-tool.js +9 -9
- package/dist/server/patch-turn-end-boundary.js +3 -3
- package/dist/server/persona-chain.js +8 -8
- package/dist/server/remote-ssh-service.js +39 -39
- package/dist/server/schedule-agent-tool.js +11 -6
- package/dist/server/scheduler-tasks.js +84 -2
- package/dist/server/scm-commitmsg.js +10 -10
- package/dist/server/setup-page.js +620 -620
- package/dist/server/universal/universal-session.js +19 -18
- package/dist/server/vision-bridge.js +18 -18
- package/docs/device-center.md +148 -148
- package/docs/device-desktop.md +48 -48
- package/docs/dsh-engine.md +493 -493
- package/extensions/webui.ts +335 -335
- package/package.json +1 -1
- package/plugin-sdk/README.md +174 -174
- package/plugin-sdk/client-utils.mjs +279 -279
- package/plugin-sdk/import-check.mjs +210 -210
- package/plugin-sdk/index.d.ts +698 -698
- package/plugin-sdk/index.mjs +696 -696
- package/plugin-sdk/package.json +13 -13
- package/plugin-sdk/ssh-host-trust.mjs +225 -225
- package/themes/aetheris.css +501 -501
- package/themes/ayu-light.css +116 -116
- package/themes/bases/flow-base.css +1357 -1357
- package/themes/bases/obsidian-base.css +895 -895
- package/themes/bases/statusbar-flat-base.css +112 -112
- package/themes/bases/zhujian-base.css +688 -688
- package/themes/bases/zhupi-base.css +660 -660
- package/themes/catppuccin-latte.css +119 -119
- package/themes/catppuccin.css +116 -116
- package/themes/claude-code-dark.css +147 -147
- package/themes/codex.css +114 -114
- package/themes/cyberpunk.css +50 -50
- package/themes/dark-teal.css +264 -264
- package/themes/dazzle.css +38 -38
- package/themes/everforest-light.css +115 -115
- package/themes/flow-light.css +164 -164
- package/themes/flow.css +161 -161
- package/themes/geist.css +114 -114
- package/themes/gruvbox-light.css +115 -115
- package/themes/kanagawa-lotus.css +115 -115
- package/themes/md-preview.css +24 -24
- package/themes/mist.css +166 -166
- package/themes/nord.css +107 -107
- package/themes/one-dark.css +106 -106
- package/themes/paper.css +174 -174
- package/themes/rose-pine-dawn.css +114 -114
- package/themes/sakura.css +166 -166
- package/themes/solarized-light.css +114 -114
- package/themes/tokyo-night.css +115 -115
- package/themes/translucent.css +85 -85
- package/themes/transparent.css +116 -116
- package/themes/vs-code-dark.css +147 -147
- package/themes/wallpaper-flow.css +382 -382
- package/themes/wallpaper-obsidian.css +74 -74
- package/themes/white.css +164 -164
- package/themes/zhujian-dark.css +115 -115
- package/themes/zhujian.css +114 -114
- package/themes/zhupi-dark.css +115 -115
- package/themes/zhupi.css +114 -114
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BcXJ20RO.js → BgTasksModal-BIlQ89vr.js} +1 -1
- package/web/dist/assets/{BgTasksModal-DjQmiKnE.js → BgTasksModal-Ck2sjlPM.js} +1 -1
- package/web/dist/assets/{CanvasStudio-PI9pid0Y.js → CanvasStudio-B3W6b_rA.js} +1 -1
- package/web/dist/assets/{CanvasStudio-nf5-HxLM.js → CanvasStudio-Csv1Sj1-.js} +1 -1
- package/web/dist/assets/{DeviceCenter-CYttJw2a.js → DeviceCenter-BQdDcO8A.js} +1 -1
- package/web/dist/assets/{DeviceCenter-DPe4sz74.js → DeviceCenter-CHRKL0Vy.js} +1 -1
- package/web/dist/assets/{FilePreview-C9Ut4Lq6.js → FilePreview-B9xoU6ON.js} +1 -1
- package/web/dist/assets/{FilePreview-CvK3ZzX5.js → FilePreview-DUQpVZkH.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-C5e-OCw2.js → GlobalSearchModal-BXEGvUZq.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-H7pFK2UC.js → GlobalSearchModal-CnVPmfOI.js} +1 -1
- package/web/dist/assets/{GroupConversation-C2wNM0dQ.js → GroupConversation-CyIpQzDd.js} +1 -1
- package/web/dist/assets/{GroupConversation-ChN3TWQK.js → GroupConversation-DgYV3uYS.js} +1 -1
- package/web/dist/assets/{SCMPanel-buTGziDB.js → SCMPanel-imYI2Ecw.js} +1 -1
- package/web/dist/assets/{SCMPanel-kx-SCL2s.js → SCMPanel-sVZcV7dR.js} +1 -1
- package/web/dist/assets/{SettingsModal-BsUF8jqr.js → SettingsModal-Xw1Yoi3_.js} +1 -1
- package/web/dist/assets/{SettingsModal-D357Ky7P.js → SettingsModal-mb4e34-0.js} +1 -1
- package/web/dist/assets/{TerminalPanel-BBuM_Sez.js → TerminalPanel-CLkJJvxg.js} +1 -1
- package/web/dist/assets/{TerminalPanel-D6x6xz8Q.js → TerminalPanel-DpcIellm.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-CdbGV3Za.js → TuiOverlayModal-4-fFAZe7.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-d6x9u25n.js → TuiOverlayModal-DCu01lks.js} +1 -1
- package/web/dist/assets/{index-D6u8xH0o.js → index-Cdh3sibd.js} +4 -4
- package/web/dist/assets/{index-BPvpea8t.js → index-DWw_SxRq.js} +4 -4
- package/web/dist/index.html +29 -29
- package/web/dist/sw.js +179 -179
- package/web/public/sw.js +179 -179
|
@@ -62,6 +62,8 @@ export class DurableEventProjector {
|
|
|
62
62
|
textSent = new Map();
|
|
63
63
|
/** 每个思考内容块已下发的字符数 */
|
|
64
64
|
thinkingSent = new Map();
|
|
65
|
+
/** 保留末条消息计数供存储兜底去重;下一条已提交助手消息才换账。 */
|
|
66
|
+
assistantMessageEnded = false;
|
|
65
67
|
/** 每个工具调用已下发的进度输出窗口(用于把 `set` / `append` 换算成增量) */
|
|
66
68
|
toolOutput = new Map();
|
|
67
69
|
/** 已发过 onToolStart 的调用(未见过开始的回执不单独出结果卡) */
|
|
@@ -89,7 +91,7 @@ export class DurableEventProjector {
|
|
|
89
91
|
return;
|
|
90
92
|
// 引擎在同一个提交里会先发 `tool_execution_start`、后发该轮正文的 message 事件(见 events.js 的 Progress 段),
|
|
91
93
|
// 而正文在时间上早于工具调用——“我来看下目录”类的文字必须落在工具卡之前,所以把工具开始推迟到批末
|
|
92
|
-
// (同一批里它自己的
|
|
94
|
+
// (同一批里它自己的 update/end 跟着一起推,保证卡片先开始再更新、结束)。
|
|
93
95
|
const deferred = [];
|
|
94
96
|
const deferredCallIds = new Set();
|
|
95
97
|
for (const event of events) {
|
|
@@ -99,7 +101,8 @@ export class DurableEventProjector {
|
|
|
99
101
|
deferredCallIds.add(String(event?.toolCallId ?? ""));
|
|
100
102
|
continue;
|
|
101
103
|
}
|
|
102
|
-
if (type === "tool_execution_update"
|
|
104
|
+
if ((type === "tool_execution_update" || type === "tool_execution_end") &&
|
|
105
|
+
deferredCallIds.has(String(event?.toolCallId ?? ""))) {
|
|
103
106
|
deferred.push(event);
|
|
104
107
|
continue;
|
|
105
108
|
}
|
|
@@ -121,6 +124,9 @@ export class DurableEventProjector {
|
|
|
121
124
|
return;
|
|
122
125
|
switch (event.type) {
|
|
123
126
|
case "message_start": {
|
|
127
|
+
if (event.message?.role !== "assistant")
|
|
128
|
+
return;
|
|
129
|
+
this.assistantMessageEnded = false;
|
|
124
130
|
// 新一轮助手消息:contentIndex 记账归零,避免沿用上一条消息的下发长度
|
|
125
131
|
this.textSent.clear();
|
|
126
132
|
this.thinkingSent.clear();
|
|
@@ -153,7 +159,15 @@ export class DurableEventProjector {
|
|
|
153
159
|
}
|
|
154
160
|
case "message_end": {
|
|
155
161
|
// 提交后的完整助手消息:补齐流式期间遗漏的尾部
|
|
156
|
-
|
|
162
|
+
const message = event.entry?.model?.[0];
|
|
163
|
+
if (message?.role !== "assistant")
|
|
164
|
+
return;
|
|
165
|
+
if (this.assistantMessageEnded) {
|
|
166
|
+
this.textSent.clear();
|
|
167
|
+
this.thinkingSent.clear();
|
|
168
|
+
}
|
|
169
|
+
this.projectMessage(message, sink);
|
|
170
|
+
this.assistantMessageEnded = true;
|
|
157
171
|
return;
|
|
158
172
|
}
|
|
159
173
|
case "tool_execution_start": {
|
|
@@ -196,6 +210,8 @@ export class DurableEventProjector {
|
|
|
196
210
|
}
|
|
197
211
|
/** 按已下发长度补齐一条完整助手消息(含 thinking / text)。 */
|
|
198
212
|
projectMessage(message, sink) {
|
|
213
|
+
if (message?.role !== "assistant")
|
|
214
|
+
return;
|
|
199
215
|
const blocks = message?.content;
|
|
200
216
|
if (!Array.isArray(blocks))
|
|
201
217
|
return;
|
|
@@ -9,8 +9,16 @@
|
|
|
9
9
|
import { existsSync, readFileSync } from "node:fs";
|
|
10
10
|
import { join } from "node:path";
|
|
11
11
|
import { homedir } from "node:os";
|
|
12
|
-
import { listCustomModelsFromConfig, readModelsJson, resolveProviderCredential, isProtocolSupportedByEngine, } from "../model-resolver.js";
|
|
12
|
+
import { listCustomModelsFromConfig, readModelsJson, resolveProviderCredential, isProtocolSupportedByEngine, resolveModelProtocol, } from "../model-resolver.js";
|
|
13
13
|
import { loadDurablePeerModule } from "./durable-loader.js";
|
|
14
|
+
function mergeProviderHeaders(...sources) {
|
|
15
|
+
const headers = new Map();
|
|
16
|
+
for (const source of sources) {
|
|
17
|
+
for (const [name, value] of Object.entries(source ?? {}))
|
|
18
|
+
headers.set(name.toLowerCase(), [name, value]);
|
|
19
|
+
}
|
|
20
|
+
return Object.fromEntries(headers.values());
|
|
21
|
+
}
|
|
14
22
|
/**
|
|
15
23
|
* 聚合全局所有已鉴权、可用的模型名录(包括官方内置模型与用户自定义模型)。
|
|
16
24
|
* 优先收录并前置展示 models.json 中的用户自定义服务商与模型。
|
|
@@ -90,13 +98,14 @@ export async function setupDurableModels(agentDir) {
|
|
|
90
98
|
/* ignore fallback to minimal builtins */
|
|
91
99
|
}
|
|
92
100
|
// 2. 兜底保障基础内置提供商
|
|
93
|
-
const fallbackBuiltinIds = ["openai", "anthropic", "google", "mistral", "groq", "deepseek"];
|
|
101
|
+
const fallbackBuiltinIds = ["openai", "anthropic", "google", "google-vertex", "mistral", "groq", "deepseek"];
|
|
94
102
|
for (const pid of fallbackBuiltinIds) {
|
|
95
103
|
if (models.providers && models.providers.has(pid))
|
|
96
104
|
continue;
|
|
97
105
|
try {
|
|
98
106
|
const providerModule = await loadDurablePeerModule("@earendil-works/pi-ai", `providers/${pid}`).catch(() => null);
|
|
99
|
-
const providerFactory = providerModule?.[`${pid}Provider`] ||
|
|
107
|
+
const providerFactory = providerModule?.[`${pid.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())}Provider`] ||
|
|
108
|
+
providerModule?.default;
|
|
100
109
|
if (typeof providerFactory === "function") {
|
|
101
110
|
const instance = providerFactory();
|
|
102
111
|
if (typeof models.setProvider === "function") {
|
|
@@ -108,65 +117,14 @@ export async function setupDurableModels(agentDir) {
|
|
|
108
117
|
/* provider loading skipped */
|
|
109
118
|
}
|
|
110
119
|
}
|
|
111
|
-
// 3.
|
|
112
|
-
|
|
113
|
-
const { providers: customProviders } = readModelsJson(agentDir);
|
|
114
|
-
const oCompModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/openai-completions.lazy").catch(() => null);
|
|
115
|
-
const oRespModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/openai-responses.lazy").catch(() => null);
|
|
116
|
-
const aMsgModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/anthropic-messages.lazy").catch(() => null);
|
|
117
|
-
for (const [providerId, pConfig] of Object.entries(customProviders)) {
|
|
118
|
-
if (!pConfig || typeof pConfig !== "object")
|
|
119
|
-
continue;
|
|
120
|
-
const cred = resolveProviderCredential(agentDir, providerId);
|
|
121
|
-
const apiProtocol = (typeof pConfig.api === "string" ? pConfig.api : "").toLowerCase();
|
|
122
|
-
let apiImpl = null;
|
|
123
|
-
if (apiProtocol === "anthropic-messages" && aMsgModule?.anthropicMessagesApi) {
|
|
124
|
-
apiImpl = aMsgModule.anthropicMessagesApi();
|
|
125
|
-
}
|
|
126
|
-
else if (apiProtocol === "openai-responses" && oRespModule?.openAIResponsesApi) {
|
|
127
|
-
apiImpl = oRespModule.openAIResponsesApi();
|
|
128
|
-
}
|
|
129
|
-
else if (oCompModule?.openAICompletionsApi) {
|
|
130
|
-
apiImpl = oCompModule.openAICompletionsApi();
|
|
131
|
-
}
|
|
132
|
-
if (apiImpl && typeof aiModule.createProvider === "function") {
|
|
133
|
-
const rawModels = Array.isArray(pConfig.models) ? pConfig.models : [];
|
|
134
|
-
const customProvider = aiModule.createProvider({
|
|
135
|
-
id: providerId,
|
|
136
|
-
name: pConfig.name || providerId,
|
|
137
|
-
baseUrl: cred.baseUrl,
|
|
138
|
-
headers: cred.headers,
|
|
139
|
-
auth: {
|
|
140
|
-
apiKey: {
|
|
141
|
-
name: `${providerId} API key`,
|
|
142
|
-
login: async () => ({ type: "api_key", key: cred.apiKey || "" }),
|
|
143
|
-
resolve: async () => (cred.apiKey ? { auth: { apiKey: cred.apiKey }, source: "config" } : undefined),
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
models: rawModels.map((m) => ({
|
|
147
|
-
...m,
|
|
148
|
-
provider: providerId,
|
|
149
|
-
api: m.api || pConfig.api || "openai-completions",
|
|
150
|
-
baseUrl: cred.baseUrl,
|
|
151
|
-
cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
152
|
-
type: "chat",
|
|
153
|
-
})),
|
|
154
|
-
api: apiImpl,
|
|
155
|
-
});
|
|
156
|
-
models.setProvider(customProvider);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
catch {
|
|
161
|
-
/* custom provider setup skipped */
|
|
162
|
-
}
|
|
163
|
-
// 4. 继承持久化动态模型缓存 (~/.pi/agent/models-store.json)
|
|
120
|
+
// 3. 继承持久化动态模型缓存 (~/.pi/agent/models-store.json)
|
|
121
|
+
let cachedProviders = {};
|
|
164
122
|
try {
|
|
165
123
|
const userAgentDir = agentDir || join(homedir(), ".pi", "agent");
|
|
166
124
|
const storePath = join(userAgentDir, "models-store.json");
|
|
167
125
|
if (existsSync(storePath)) {
|
|
168
|
-
|
|
169
|
-
for (const [providerId, pData] of Object.entries(
|
|
126
|
+
cachedProviders = JSON.parse(readFileSync(storePath, "utf8"));
|
|
127
|
+
for (const [providerId, pData] of Object.entries(cachedProviders)) {
|
|
170
128
|
const p = typeof models.getProvider === "function" ? models.getProvider(providerId) : undefined;
|
|
171
129
|
if (p && Array.isArray(pData?.models)) {
|
|
172
130
|
const extraModels = pData.models;
|
|
@@ -205,8 +163,102 @@ export async function setupDurableModels(agentDir) {
|
|
|
205
163
|
catch {
|
|
206
164
|
/* dynamic models store read skipped */
|
|
207
165
|
}
|
|
166
|
+
// 4. 动态加载 models.json 中的自定义服务商与模型
|
|
167
|
+
try {
|
|
168
|
+
const { providers: customProviders } = readModelsJson(agentDir);
|
|
169
|
+
const implementations = {};
|
|
170
|
+
for (const [protocol, factory] of [
|
|
171
|
+
["openai-completions", "openAICompletionsApi"],
|
|
172
|
+
["openai-responses", "openAIResponsesApi"],
|
|
173
|
+
["anthropic-messages", "anthropicMessagesApi"],
|
|
174
|
+
["google-generative-ai", "googleGenerativeAIApi"],
|
|
175
|
+
["google-vertex", "googleVertexApi"],
|
|
176
|
+
]) {
|
|
177
|
+
try {
|
|
178
|
+
const module = await loadDurablePeerModule("@earendil-works/pi-ai", `api/${protocol}.lazy`);
|
|
179
|
+
if (typeof module?.[factory] === "function")
|
|
180
|
+
implementations[protocol] = module[factory]();
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
/* An unavailable API must not suppress unrelated providers. */
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
for (const [providerId, pConfig] of Object.entries(customProviders)) {
|
|
187
|
+
if (!pConfig || typeof pConfig !== "object")
|
|
188
|
+
continue;
|
|
189
|
+
const cred = resolveProviderCredential(agentDir, providerId);
|
|
190
|
+
const builtin = models.getProvider(providerId);
|
|
191
|
+
const rawModels = Array.isArray(pConfig.models) ? pConfig.models : [];
|
|
192
|
+
const apiOverride = typeof pConfig.api === "string" && pConfig.api.trim() ? pConfig.api : undefined;
|
|
193
|
+
const mergeModels = (baseline) => {
|
|
194
|
+
const key = (model) => `${model.type ?? "chat"}:${model.id}`;
|
|
195
|
+
const cached = Array.isArray(cachedProviders[providerId]?.models)
|
|
196
|
+
? cachedProviders[providerId].models
|
|
197
|
+
: [];
|
|
198
|
+
const merged = new Map([...cached, ...baseline].map((model) => [key(model), { ...model }]));
|
|
199
|
+
for (const override of rawModels) {
|
|
200
|
+
const original = merged.get(key(override));
|
|
201
|
+
merged.set(key(override), {
|
|
202
|
+
...original,
|
|
203
|
+
...override,
|
|
204
|
+
...(original?.cost && override.cost ? { cost: { ...original.cost, ...override.cost } } : {}),
|
|
205
|
+
api: override.type && override.type !== "chat"
|
|
206
|
+
? (override.api ?? original?.api)
|
|
207
|
+
: resolveModelProtocol(override.api ?? apiOverride ?? original?.api ?? builtin?.getModels()[0]?.api, providerId, override.id),
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
return [...merged.values()].map((model) => ({
|
|
211
|
+
...model,
|
|
212
|
+
provider: providerId,
|
|
213
|
+
api: model.type && model.type !== "chat"
|
|
214
|
+
? model.api
|
|
215
|
+
: resolveModelProtocol(rawModels.find((m) => key(m) === key(model))?.api ?? apiOverride ?? model.api, providerId, model.id),
|
|
216
|
+
cost: model.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
217
|
+
type: model.type ?? "chat",
|
|
218
|
+
}));
|
|
219
|
+
};
|
|
220
|
+
if (Object.keys(implementations).length && typeof aiModule.createProvider === "function") {
|
|
221
|
+
const customProvider = aiModule.createProvider({
|
|
222
|
+
id: providerId,
|
|
223
|
+
name: pConfig.name || providerId,
|
|
224
|
+
baseUrl: cred.baseUrl,
|
|
225
|
+
headers: cred.headers,
|
|
226
|
+
auth: builtin?.auth ?? {
|
|
227
|
+
apiKey: {
|
|
228
|
+
name: `${providerId} API key`,
|
|
229
|
+
login: async () => ({ type: "api_key", key: cred.apiKey || "" }),
|
|
230
|
+
resolve: async () => (cred.apiKey ? { auth: { apiKey: cred.apiKey }, source: "config" } : undefined),
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
models: mergeModels([]),
|
|
234
|
+
api: implementations,
|
|
235
|
+
});
|
|
236
|
+
if (builtin) {
|
|
237
|
+
// Keep native authentication and operations (ADC/OAuth, images, discovery).
|
|
238
|
+
// Only explicit API overrides opt into a different SDK implementation.
|
|
239
|
+
const overridden = (model) => apiOverride ||
|
|
240
|
+
rawModels.some((m) => m.id === model.id && (m.type ?? "chat") === (model.type ?? "chat") && m.api);
|
|
241
|
+
models.setProvider({
|
|
242
|
+
...builtin,
|
|
243
|
+
name: pConfig.name || builtin.name,
|
|
244
|
+
getModels: () => mergeModels(builtin.getModels()).filter((model) => model.type === "chat"),
|
|
245
|
+
getAllModels: () => mergeModels(builtin.getAllModels?.() ?? builtin.getModels()),
|
|
246
|
+
stream: (model, context, options) => (overridden(model) ? customProvider : builtin).stream(model, context, options),
|
|
247
|
+
streamSimple: (model, context, options) => (overridden(model) ? customProvider : builtin).streamSimple(model, context, options),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
models.setProvider(customProvider);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
/* custom provider setup skipped */
|
|
258
|
+
}
|
|
208
259
|
// 5. 为所有已注册 Provider 注入凭证与 BaseURL
|
|
209
260
|
try {
|
|
261
|
+
const { providers } = readModelsJson(agentDir);
|
|
210
262
|
if (models.providers && typeof models.providers.keys === "function") {
|
|
211
263
|
for (const providerId of models.providers.keys()) {
|
|
212
264
|
const cred = resolveProviderCredential(agentDir, providerId);
|
|
@@ -218,15 +270,32 @@ export async function setupDurableModels(agentDir) {
|
|
|
218
270
|
}))
|
|
219
271
|
.catch(() => { });
|
|
220
272
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
273
|
+
const p = models.getProvider(providerId);
|
|
274
|
+
const pConfig = providers[providerId];
|
|
275
|
+
if (p && (cred.baseUrl || cred.headers || pConfig?.api || pConfig?.models)) {
|
|
276
|
+
if (cred.baseUrl)
|
|
224
277
|
p.baseUrl = cred.baseUrl;
|
|
225
|
-
|
|
226
|
-
if (cred.headers) {
|
|
227
|
-
const p = models.getProvider(providerId);
|
|
228
|
-
if (p)
|
|
278
|
+
if (cred.headers)
|
|
229
279
|
p.headers = { ...p.headers, ...cred.headers };
|
|
280
|
+
// pi-ai streams consume model.baseUrl/headers, not provider metadata.
|
|
281
|
+
// Apply provider defaults before explicit per-model configuration.
|
|
282
|
+
const overrides = Array.isArray(pConfig?.models) ? pConfig.models : [];
|
|
283
|
+
for (const method of ["getModels", "getAllModels"]) {
|
|
284
|
+
if (typeof p[method] !== "function")
|
|
285
|
+
continue;
|
|
286
|
+
const getModels = p[method].bind(p);
|
|
287
|
+
p[method] = () => getModels().map((model) => {
|
|
288
|
+
const override = overrides.find((m) => m.id === model.id && (m.type ?? "chat") === (model.type ?? "chat"));
|
|
289
|
+
return {
|
|
290
|
+
...model,
|
|
291
|
+
api: model.type && model.type !== "chat"
|
|
292
|
+
? model.api
|
|
293
|
+
: resolveModelProtocol(override?.api ?? (typeof pConfig?.api === "string" ? pConfig.api : model.api), providerId, model.id),
|
|
294
|
+
baseUrl: override?.baseUrl ?? cred.baseUrl ?? model.baseUrl,
|
|
295
|
+
headers: mergeProviderHeaders(model.headers, cred.headers, override?.headers),
|
|
296
|
+
};
|
|
297
|
+
});
|
|
298
|
+
}
|
|
230
299
|
}
|
|
231
300
|
}
|
|
232
301
|
}
|
package/dist/server/eval-tool.js
CHANGED
|
@@ -67,142 +67,142 @@ function resolvePythonCmd() {
|
|
|
67
67
|
}
|
|
68
68
|
return null;
|
|
69
69
|
}
|
|
70
|
-
const PYTHON_DRIVER_SCRIPT = `
|
|
71
|
-
import sys, io, ast, json, traceback, os
|
|
72
|
-
|
|
73
|
-
# 跨平台编码对齐:Windows 默认代码页(如 CP936/GBK)读取 UTF-8 管道会导致多字节截断、
|
|
74
|
-
# 反斜杠被吞噬破坏 JSON 结构(报 Expecting ',' delimiter)或触发 UnicodeDecodeError。
|
|
75
|
-
# 强制标准流一律按 UTF-8 重配并附带容错替换策略,避免解码死锁。
|
|
76
|
-
if hasattr(sys.stdin, "reconfigure"):
|
|
77
|
-
sys.stdin.reconfigure(encoding="utf-8", errors="replace")
|
|
78
|
-
if hasattr(sys.stdout, "reconfigure"):
|
|
79
|
-
sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
80
|
-
if hasattr(sys.stderr, "reconfigure"):
|
|
81
|
-
sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
82
|
-
|
|
83
|
-
WORKDIR = os.environ.get('PI_EVAL_WORKDIR', '')
|
|
84
|
-
PROJECT_DIR = os.environ.get('PI_EVAL_PROJECT_DIR', '')
|
|
85
|
-
|
|
86
|
-
_scope = {'__name__': '__main__', 'WORKDIR': WORKDIR, 'PROJECT_DIR': PROJECT_DIR}
|
|
87
|
-
|
|
88
|
-
def run_cell(code):
|
|
89
|
-
out = io.StringIO()
|
|
90
|
-
err = io.StringIO()
|
|
91
|
-
old_out, old_err = sys.stdout, sys.stderr
|
|
92
|
-
sys.stdout, sys.stderr = out, err
|
|
93
|
-
res = None
|
|
94
|
-
exc = None
|
|
95
|
-
try:
|
|
96
|
-
parsed = ast.parse(code)
|
|
97
|
-
if parsed.body and isinstance(parsed.body[-1], ast.Expr):
|
|
98
|
-
last = parsed.body.pop()
|
|
99
|
-
if parsed.body:
|
|
100
|
-
exec(compile(parsed, '<eval>', 'exec'), _scope)
|
|
101
|
-
res = eval(compile(ast.Expression(last.value), '<eval>', 'eval'), _scope)
|
|
102
|
-
else:
|
|
103
|
-
exec(compile(code, '<eval>', 'exec'), _scope)
|
|
104
|
-
except Exception:
|
|
105
|
-
exc = traceback.format_exc()
|
|
106
|
-
finally:
|
|
107
|
-
sys.stdout, sys.stderr = old_out, old_err
|
|
108
|
-
return {
|
|
109
|
-
'stdout': out.getvalue(),
|
|
110
|
-
'stderr': err.getvalue(),
|
|
111
|
-
'result': repr(res) if res is not None else None,
|
|
112
|
-
'error': exc
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
for line in sys.stdin:
|
|
116
|
-
if not line.strip():
|
|
117
|
-
continue
|
|
118
|
-
try:
|
|
119
|
-
req = json.loads(line)
|
|
120
|
-
if req.get('action') == 'reset':
|
|
121
|
-
_scope.clear()
|
|
122
|
-
_scope['__name__'] = '__main__'
|
|
123
|
-
_scope['WORKDIR'] = WORKDIR
|
|
124
|
-
_scope['PROJECT_DIR'] = PROJECT_DIR
|
|
125
|
-
resp = {'ok': True, 'stdout': '', 'stderr': '', 'result': None, 'error': None}
|
|
126
|
-
else:
|
|
127
|
-
resp = run_cell(req.get('code', ''))
|
|
128
|
-
resp['ok'] = resp['error'] is None
|
|
129
|
-
except Exception as e:
|
|
130
|
-
resp = {'ok': False, 'stdout': '', 'stderr': '', 'result': None, 'error': traceback.format_exc()}
|
|
131
|
-
|
|
132
|
-
sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=True) + '\\n')
|
|
133
|
-
sys.stdout.flush()
|
|
70
|
+
const PYTHON_DRIVER_SCRIPT = `
|
|
71
|
+
import sys, io, ast, json, traceback, os
|
|
72
|
+
|
|
73
|
+
# 跨平台编码对齐:Windows 默认代码页(如 CP936/GBK)读取 UTF-8 管道会导致多字节截断、
|
|
74
|
+
# 反斜杠被吞噬破坏 JSON 结构(报 Expecting ',' delimiter)或触发 UnicodeDecodeError。
|
|
75
|
+
# 强制标准流一律按 UTF-8 重配并附带容错替换策略,避免解码死锁。
|
|
76
|
+
if hasattr(sys.stdin, "reconfigure"):
|
|
77
|
+
sys.stdin.reconfigure(encoding="utf-8", errors="replace")
|
|
78
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
79
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
80
|
+
if hasattr(sys.stderr, "reconfigure"):
|
|
81
|
+
sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
|
|
82
|
+
|
|
83
|
+
WORKDIR = os.environ.get('PI_EVAL_WORKDIR', '')
|
|
84
|
+
PROJECT_DIR = os.environ.get('PI_EVAL_PROJECT_DIR', '')
|
|
85
|
+
|
|
86
|
+
_scope = {'__name__': '__main__', 'WORKDIR': WORKDIR, 'PROJECT_DIR': PROJECT_DIR}
|
|
87
|
+
|
|
88
|
+
def run_cell(code):
|
|
89
|
+
out = io.StringIO()
|
|
90
|
+
err = io.StringIO()
|
|
91
|
+
old_out, old_err = sys.stdout, sys.stderr
|
|
92
|
+
sys.stdout, sys.stderr = out, err
|
|
93
|
+
res = None
|
|
94
|
+
exc = None
|
|
95
|
+
try:
|
|
96
|
+
parsed = ast.parse(code)
|
|
97
|
+
if parsed.body and isinstance(parsed.body[-1], ast.Expr):
|
|
98
|
+
last = parsed.body.pop()
|
|
99
|
+
if parsed.body:
|
|
100
|
+
exec(compile(parsed, '<eval>', 'exec'), _scope)
|
|
101
|
+
res = eval(compile(ast.Expression(last.value), '<eval>', 'eval'), _scope)
|
|
102
|
+
else:
|
|
103
|
+
exec(compile(code, '<eval>', 'exec'), _scope)
|
|
104
|
+
except Exception:
|
|
105
|
+
exc = traceback.format_exc()
|
|
106
|
+
finally:
|
|
107
|
+
sys.stdout, sys.stderr = old_out, old_err
|
|
108
|
+
return {
|
|
109
|
+
'stdout': out.getvalue(),
|
|
110
|
+
'stderr': err.getvalue(),
|
|
111
|
+
'result': repr(res) if res is not None else None,
|
|
112
|
+
'error': exc
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
for line in sys.stdin:
|
|
116
|
+
if not line.strip():
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
req = json.loads(line)
|
|
120
|
+
if req.get('action') == 'reset':
|
|
121
|
+
_scope.clear()
|
|
122
|
+
_scope['__name__'] = '__main__'
|
|
123
|
+
_scope['WORKDIR'] = WORKDIR
|
|
124
|
+
_scope['PROJECT_DIR'] = PROJECT_DIR
|
|
125
|
+
resp = {'ok': True, 'stdout': '', 'stderr': '', 'result': None, 'error': None}
|
|
126
|
+
else:
|
|
127
|
+
resp = run_cell(req.get('code', ''))
|
|
128
|
+
resp['ok'] = resp['error'] is None
|
|
129
|
+
except Exception as e:
|
|
130
|
+
resp = {'ok': False, 'stdout': '', 'stderr': '', 'result': None, 'error': traceback.format_exc()}
|
|
131
|
+
|
|
132
|
+
sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=True) + '\\n')
|
|
133
|
+
sys.stdout.flush()
|
|
134
134
|
`;
|
|
135
|
-
const NODE_DRIVER_SCRIPT = `
|
|
136
|
-
import repl from "node:repl";
|
|
137
|
-
import { PassThrough } from "node:stream";
|
|
138
|
-
import readline from "node:readline";
|
|
139
|
-
|
|
140
|
-
let server;
|
|
141
|
-
function createRepl() {
|
|
142
|
-
const inStream = new PassThrough();
|
|
143
|
-
const outStream = new PassThrough();
|
|
144
|
-
server = repl.start({
|
|
145
|
-
input: inStream,
|
|
146
|
-
output: outStream,
|
|
147
|
-
terminal: false,
|
|
148
|
-
useColors: false,
|
|
149
|
-
preview: false
|
|
150
|
-
});
|
|
151
|
-
server.context.console = console;
|
|
152
|
-
server.context.setTimeout = setTimeout;
|
|
153
|
-
server.context.clearTimeout = clearTimeout;
|
|
154
|
-
server.context.setInterval = setInterval;
|
|
155
|
-
server.context.clearInterval = clearInterval;
|
|
156
|
-
server.context.Buffer = Buffer;
|
|
157
|
-
server.context.URL = URL;
|
|
158
|
-
server.context.WORKDIR = process.env.PI_EVAL_WORKDIR || "";
|
|
159
|
-
server.context.PROJECT_DIR = process.env.PI_EVAL_PROJECT_DIR || "";
|
|
160
|
-
}
|
|
161
|
-
createRepl();
|
|
162
|
-
|
|
163
|
-
const rl = readline.createInterface({ input: process.stdin });
|
|
164
|
-
rl.on("line", (line) => {
|
|
165
|
-
if (!line.trim()) return;
|
|
166
|
-
try {
|
|
167
|
-
const req = JSON.parse(line);
|
|
168
|
-
if (req.action === "reset") {
|
|
169
|
-
createRepl();
|
|
170
|
-
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify({ ok: true, stdout: "", stderr: "", result: null, error: null }) + "\\n");
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
let capturedOut = "";
|
|
174
|
-
let capturedErr = "";
|
|
175
|
-
const origLog = server.context.console.log;
|
|
176
|
-
const origErr = server.context.console.error;
|
|
177
|
-
const origWarn = server.context.console.warn;
|
|
178
|
-
server.context.console.log = (...args) => {
|
|
179
|
-
capturedOut += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
180
|
-
};
|
|
181
|
-
server.context.console.error = (...args) => {
|
|
182
|
-
capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
183
|
-
};
|
|
184
|
-
server.context.console.warn = (...args) => {
|
|
185
|
-
capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
186
|
-
};
|
|
187
|
-
|
|
188
|
-
server.eval(req.code, server.context, "eval", (err, result) => {
|
|
189
|
-
server.context.console.log = origLog;
|
|
190
|
-
server.context.console.error = origErr;
|
|
191
|
-
server.context.console.warn = origWarn;
|
|
192
|
-
const resp = {
|
|
193
|
-
ok: !err,
|
|
194
|
-
stdout: capturedOut,
|
|
195
|
-
stderr: capturedErr,
|
|
196
|
-
result: result !== undefined ? (typeof result === "string" ? result : JSON.stringify(result, null, 2)) : null,
|
|
197
|
-
error: err ? (err.stack || String(err)) : null
|
|
198
|
-
};
|
|
199
|
-
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
|
|
200
|
-
});
|
|
201
|
-
} catch (e) {
|
|
202
|
-
const resp = { ok: false, stdout: "", stderr: "", result: null, error: e.stack || String(e) };
|
|
203
|
-
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
|
|
204
|
-
}
|
|
205
|
-
});
|
|
135
|
+
const NODE_DRIVER_SCRIPT = `
|
|
136
|
+
import repl from "node:repl";
|
|
137
|
+
import { PassThrough } from "node:stream";
|
|
138
|
+
import readline from "node:readline";
|
|
139
|
+
|
|
140
|
+
let server;
|
|
141
|
+
function createRepl() {
|
|
142
|
+
const inStream = new PassThrough();
|
|
143
|
+
const outStream = new PassThrough();
|
|
144
|
+
server = repl.start({
|
|
145
|
+
input: inStream,
|
|
146
|
+
output: outStream,
|
|
147
|
+
terminal: false,
|
|
148
|
+
useColors: false,
|
|
149
|
+
preview: false
|
|
150
|
+
});
|
|
151
|
+
server.context.console = console;
|
|
152
|
+
server.context.setTimeout = setTimeout;
|
|
153
|
+
server.context.clearTimeout = clearTimeout;
|
|
154
|
+
server.context.setInterval = setInterval;
|
|
155
|
+
server.context.clearInterval = clearInterval;
|
|
156
|
+
server.context.Buffer = Buffer;
|
|
157
|
+
server.context.URL = URL;
|
|
158
|
+
server.context.WORKDIR = process.env.PI_EVAL_WORKDIR || "";
|
|
159
|
+
server.context.PROJECT_DIR = process.env.PI_EVAL_PROJECT_DIR || "";
|
|
160
|
+
}
|
|
161
|
+
createRepl();
|
|
162
|
+
|
|
163
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
164
|
+
rl.on("line", (line) => {
|
|
165
|
+
if (!line.trim()) return;
|
|
166
|
+
try {
|
|
167
|
+
const req = JSON.parse(line);
|
|
168
|
+
if (req.action === "reset") {
|
|
169
|
+
createRepl();
|
|
170
|
+
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify({ ok: true, stdout: "", stderr: "", result: null, error: null }) + "\\n");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
let capturedOut = "";
|
|
174
|
+
let capturedErr = "";
|
|
175
|
+
const origLog = server.context.console.log;
|
|
176
|
+
const origErr = server.context.console.error;
|
|
177
|
+
const origWarn = server.context.console.warn;
|
|
178
|
+
server.context.console.log = (...args) => {
|
|
179
|
+
capturedOut += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
180
|
+
};
|
|
181
|
+
server.context.console.error = (...args) => {
|
|
182
|
+
capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
183
|
+
};
|
|
184
|
+
server.context.console.warn = (...args) => {
|
|
185
|
+
capturedErr += args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ") + "\\n";
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
server.eval(req.code, server.context, "eval", (err, result) => {
|
|
189
|
+
server.context.console.log = origLog;
|
|
190
|
+
server.context.console.error = origErr;
|
|
191
|
+
server.context.console.warn = origWarn;
|
|
192
|
+
const resp = {
|
|
193
|
+
ok: !err,
|
|
194
|
+
stdout: capturedOut,
|
|
195
|
+
stderr: capturedErr,
|
|
196
|
+
result: result !== undefined ? (typeof result === "string" ? result : JSON.stringify(result, null, 2)) : null,
|
|
197
|
+
error: err ? (err.stack || String(err)) : null
|
|
198
|
+
};
|
|
199
|
+
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
|
|
200
|
+
});
|
|
201
|
+
} catch (e) {
|
|
202
|
+
const resp = { ok: false, stdout: "", stderr: "", result: null, error: e.stack || String(e) };
|
|
203
|
+
process.stdout.write("__PI_EVAL_RES__" + JSON.stringify(resp) + "\\n");
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
206
|
`;
|
|
207
207
|
/**
|
|
208
208
|
* 净化 Eval 子进程环境变量:仅保留操作系统基础变量,剥离所有包含 key/token/secret/auth/cred 等敏感环境变量,
|
|
@@ -209,6 +209,8 @@ export function resolveModelProtocol(api, providerId, modelId) {
|
|
|
209
209
|
if (pid === "anthropic" || pid.includes("claude") || pid.includes("anthropic")) {
|
|
210
210
|
return "anthropic-messages";
|
|
211
211
|
}
|
|
212
|
+
if (pid === "google-vertex")
|
|
213
|
+
return "google-vertex";
|
|
212
214
|
if (pid === "google" || pid === "gemini") {
|
|
213
215
|
return "google-generative-ai";
|
|
214
216
|
}
|
|
@@ -256,7 +258,8 @@ export function isProtocolSupportedByEngine(engine, api, providerId, modelId) {
|
|
|
256
258
|
return (protocol === "openai-completions" ||
|
|
257
259
|
protocol === "openai-responses" ||
|
|
258
260
|
protocol === "anthropic-messages" ||
|
|
259
|
-
protocol === "google-generative-ai"
|
|
261
|
+
protocol === "google-generative-ai" ||
|
|
262
|
+
protocol === "google-vertex");
|
|
260
263
|
}
|
|
261
264
|
return true;
|
|
262
265
|
}
|