pi-web-ui 0.114.0 → 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.
Files changed (122) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/bin/pi-web-ui.mjs +15 -7
  3. package/dist/server/agent-service.js +190 -65
  4. package/dist/server/attachments.js +48 -2
  5. package/dist/server/canvas/canvas-agent-tool.js +3 -3
  6. package/dist/server/canvas/canvas-cards.js +1 -1
  7. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  8. package/dist/server/canvas/canvas-validation.js +1 -1
  9. package/dist/server/client-state.js +6 -2
  10. package/dist/server/communicate-tool.js +37 -11
  11. package/dist/server/device-center/connector.js +33 -14
  12. package/dist/server/device-center/hub-page.js +1 -1
  13. package/dist/server/device-center/hub.js +2 -1
  14. package/dist/server/device-center/local-hub.js +92 -0
  15. package/dist/server/device-center/local.js +60 -7
  16. package/dist/server/device-center/path-portal.js +1 -1
  17. package/dist/server/device-center/relay.js +45 -8
  18. package/dist/server/dispatch-domain-handlers.js +1 -0
  19. package/dist/server/dsh/dsh-agent-service.js +5 -1
  20. package/dist/server/durable/durable-event-projector.js +19 -3
  21. package/dist/server/durable/durable-models.js +134 -65
  22. package/dist/server/engine-probe.js +36 -6
  23. package/dist/server/global-loader.js +40 -2
  24. package/dist/server/index.js +56 -32
  25. package/dist/server/model-resolver.js +4 -1
  26. package/dist/server/patch-bash-process.js +125 -0
  27. package/dist/server/plugins.js +26 -2
  28. package/dist/server/preset-fields.js +7 -0
  29. package/dist/server/preset-share.js +1 -0
  30. package/dist/server/prompt-templates.js +106 -0
  31. package/dist/server/protocol-version.js +1 -1
  32. package/dist/server/resolve-global-sdk.js +2 -0
  33. package/dist/server/schedule-agent-tool.js +49 -26
  34. package/dist/server/scheduler-tasks.js +129 -11
  35. package/dist/server/settings-service.js +6 -0
  36. package/dist/server/text-quote.js +9 -0
  37. package/dist/server/tool-manager.js +2 -1
  38. package/dist/server/universal/drivers/claude-code.js +5 -0
  39. package/dist/server/universal/drivers/codex.js +336 -0
  40. package/dist/server/universal/index.js +1 -0
  41. package/dist/server/universal/universal-attachments.js +24 -1
  42. package/dist/server/universal/universal-session.js +42 -18
  43. package/docs/device-center.md +9 -3
  44. package/package.json +2 -2
  45. package/plugins/catalog.json +10 -0
  46. package/web/dist/.build-assets.json +1 -1
  47. package/web/dist/assets/BgTasksModal-BIlQ89vr.js +1 -0
  48. package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +1 -0
  49. package/web/dist/assets/{CanvasStudio-BEJZE5BI.js → CanvasStudio-B3W6b_rA.js} +3 -3
  50. package/web/dist/assets/{CanvasStudio-CgUNHqos.js → CanvasStudio-Csv1Sj1-.js} +3 -3
  51. package/web/dist/assets/DeviceCenter-BQdDcO8A.js +3 -0
  52. package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +3 -0
  53. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  54. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  55. package/web/dist/assets/FilePreview-B9xoU6ON.js +2 -0
  56. package/web/dist/assets/FilePreview-DUQpVZkH.js +2 -0
  57. package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +1 -0
  58. package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +1 -0
  59. package/web/dist/assets/GroupConversation-CyIpQzDd.js +1 -0
  60. package/web/dist/assets/GroupConversation-DgYV3uYS.js +1 -0
  61. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  62. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  63. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  64. package/web/dist/assets/SCMPanel-imYI2Ecw.js +2 -0
  65. package/web/dist/assets/SCMPanel-sVZcV7dR.js +2 -0
  66. package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +20 -0
  67. package/web/dist/assets/SettingsModal-mb4e34-0.js +20 -0
  68. package/web/dist/assets/{TerminalPanel-DL20uKgU.js → TerminalPanel-CLkJJvxg.js} +2 -2
  69. package/web/dist/assets/{TerminalPanel-D6cPRFei.js → TerminalPanel-DpcIellm.js} +2 -2
  70. package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +1 -0
  71. package/web/dist/assets/TuiOverlayModal-DCu01lks.js +1 -0
  72. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  73. package/web/dist/assets/{desktop-DPyTy4M3.js → desktop-YguLbrX1.js} +1 -1
  74. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  75. package/web/dist/assets/index-Cdh3sibd.js +85 -0
  76. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  77. package/web/dist/assets/index-DWw_SxRq.js +85 -0
  78. package/web/dist/assets/{plugin-host-CqA4yW6w.js → plugin-host-BRBg6zmQ.js} +1 -1
  79. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  80. package/web/dist/index.html +10 -9
  81. package/web/dist/sw.js +1 -1
  82. package/dist/gh-comment-781.md +0 -5
  83. package/dist/server/device-center/local-page.js +0 -17
  84. package/dist/server/device-center/smoke-preview.js +0 -3
  85. package/dist/server/durable/durable-capabilities.js +0 -11
  86. package/dist/server/markers/builtins/services.js +0 -123
  87. package/dist/server/markers/builtins/todo.js +0 -189
  88. package/dist/server/markers-list-tool.js +0 -34
  89. package/dist/server/orchestrator.js +0 -109
  90. package/dist/server/system-prompt-soul.js +0 -41
  91. package/dist/server/univer-service.js +0 -448
  92. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  93. package/dist/test-artifact.md +0 -9
  94. package/dist/test-preview-modal.md +0 -11
  95. package/dist/test-report.html +0 -20
  96. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +0 -1
  97. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +0 -1
  98. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +0 -3
  99. package/web/dist/assets/DeviceCenter-CVblvhNX.js +0 -3
  100. package/web/dist/assets/Dropdown-Oug0DDte.js +0 -1
  101. package/web/dist/assets/FilePreview-CvdX6nr6.js +0 -2
  102. package/web/dist/assets/FilePreview-kCZhfBAF.js +0 -2
  103. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +0 -1
  104. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +0 -1
  105. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +0 -1
  106. package/web/dist/assets/GroupConversation-DZ71jEi8.js +0 -1
  107. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +0 -2
  108. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +0 -1
  109. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +0 -1
  110. package/web/dist/assets/SCMPanel-BP1TUT-V.js +0 -2
  111. package/web/dist/assets/SCMPanel-BscPm9kf.js +0 -2
  112. package/web/dist/assets/SettingsModal-C8UgMjVM.js +0 -20
  113. package/web/dist/assets/SettingsModal-VynB7jNb.js +0 -20
  114. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +0 -1
  115. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +0 -1
  116. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +0 -1
  117. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +0 -1
  118. package/web/dist/assets/app-globals-CnO6KlEM.js +0 -325
  119. package/web/dist/assets/index-CPgAH5q7.js +0 -83
  120. package/web/dist/assets/index-Cje8iugL.js +0 -83
  121. package/web/dist/assets/index-DnKeiDbj.css +0 -1
  122. package/web/dist/assets/theme-BqdAjEjF.js +0 -1
@@ -41,7 +41,7 @@ import { assertEngineWorkspaceSupported } from "../sandbox-engines.js";
41
41
  import { QuiesceRejectedError } from "../agent-service.js";
42
42
  import { NATIVE_COMMANDS, parseSlash } from "../slash-commands.js";
43
43
  import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
44
- import { scanAtMentions, formatPromptWithSkills } from "../universal/universal-attachments.js";
44
+ import { scanAtMentions, formatPromptWithSkills, formatUnavailableCanvasReference, } from "../universal/universal-attachments.js";
45
45
  import { bilingual, pick, resolveServerLang } from "../i18n.js";
46
46
  import { ModelAdminService } from "../model-admin.js";
47
47
  import { normalizeToolInfo, unsupportedToolInfo } from "../tool-info.js";
@@ -2184,6 +2184,10 @@ export class DshClientSession {
2184
2184
  });
2185
2185
  continue;
2186
2186
  }
2187
+ if (a.mode === "canvas") {
2188
+ blocks.push({ type: "text", text: formatUnavailableCanvasReference(a) });
2189
+ continue;
2190
+ }
2187
2191
  const resolved = a.path ? workspacePath(this.cwd, a.path) : null;
2188
2192
  if (a.imageData) {
2189
2193
  // 视觉桥:base64 图片 → attachment store → 真 image 块(模型可看图)。
@@ -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
- // (同一批里它自己的 `tool_execution_update` 跟着一起推,避免先到进度后到卡片)。
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" && deferredCallIds.has(String(event?.toolCallId ?? ""))) {
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
- this.projectMessage(event.entry?.model?.[0], sink);
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`] || providerModule?.default;
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. 动态加载 models.json 中的自定义服务商与模型
112
- try {
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
- const store = JSON.parse(readFileSync(storePath, "utf8"));
169
- for (const [providerId, pData] of Object.entries(store)) {
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
- if (cred.baseUrl) {
222
- const p = models.getProvider(providerId);
223
- if (p)
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
  }
@@ -5,6 +5,7 @@ import { VERSION } from "@earendil-works/pi-coding-agent";
5
5
  import { runtimeBaseCandidates } from "./dsh/preset-clones.js";
6
6
  import { killPidTree } from "./process-utils.js";
7
7
  import { probeClaudeCode } from "./universal/drivers/claude-code.js";
8
+ import { probeCodex } from "./universal/drivers/codex.js";
8
9
  import { compareVersions, defaultFetcher, fetchLatest, NPM_DEFAULT_REGISTRY, } from "./update-check.js";
9
10
  import { probeGlobalPackage } from "./global-loader.js";
10
11
  export const ENGINE_PACKAGES = {
@@ -23,6 +24,11 @@ export const ENGINE_PACKAGES = {
23
24
  packageName: "@anthropic-ai/claude-code",
24
25
  installCommand: "npm i -g @anthropic-ai/claude-code",
25
26
  },
27
+ codex: {
28
+ id: "codex",
29
+ packageName: "@openai/codex",
30
+ installCommand: "npm i -g @openai/codex",
31
+ },
26
32
  durable: {
27
33
  id: "durable",
28
34
  packageName: "@earendil-works/pi-durable",
@@ -60,6 +66,14 @@ const engineRegistry = new Map([
60
66
  updating: false,
61
67
  },
62
68
  ],
69
+ [
70
+ "codex",
71
+ {
72
+ status: { id: "codex", installed: false, packageName: ENGINE_PACKAGES.codex.packageName },
73
+ probedAt: 0,
74
+ updating: false,
75
+ },
76
+ ],
63
77
  [
64
78
  "durable",
65
79
  {
@@ -128,11 +142,11 @@ export function probePi() {
128
142
  * 1. 优先检查常见全局 node_modules / 候选路径中的 @deepseek-ai/dsh package.json 与 dsh-base;
129
143
  * 2. 回退通过命令行探针执行 `dsh --version`。
130
144
  */
131
- export async function probeDsh() {
145
+ export async function probeDsh(force = false) {
132
146
  const pkgName = ENGINE_PACKAGES.dsh.packageName;
133
147
  // 0. 通用全局包探测器(覆盖 fnm / nvm / pnpm / 全局 prefix 等)
134
148
  try {
135
- const globalProbe = probeGlobalPackage(pkgName);
149
+ const globalProbe = probeGlobalPackage(pkgName, { refresh: force });
136
150
  if (globalProbe.installed) {
137
151
  return { id: "dsh", installed: true, packageName: pkgName, version: globalProbe.version };
138
152
  }
@@ -274,11 +288,20 @@ export async function probeEngine(id, force = false) {
274
288
  }
275
289
  let result;
276
290
  if (id === "dsh") {
277
- result = await probeDsh();
291
+ result = await probeDsh(force);
278
292
  }
279
293
  else if (id === "claude") {
280
294
  result = await probeClaude(force);
281
295
  }
296
+ else if (id === "codex") {
297
+ const probe = await probeCodex();
298
+ result = {
299
+ id: "codex",
300
+ installed: probe.available,
301
+ version: probe.version,
302
+ packageName: ENGINE_PACKAGES.codex.packageName,
303
+ };
304
+ }
282
305
  else if (id === "durable") {
283
306
  result = await probeDurable(force);
284
307
  }
@@ -304,20 +327,27 @@ export async function probeAllEngines(force = false) {
304
327
  if (!force && allFresh && entries.length > 0) {
305
328
  return entries.map(toPublicStatus);
306
329
  }
307
- const [pi, dsh, claude, durable] = await Promise.all([
330
+ const [pi, dsh, claude, durable, codex] = await Promise.all([
308
331
  probePi(),
309
- probeDsh(),
332
+ probeDsh(force),
310
333
  probeClaude(force),
311
334
  probeDurable(force),
335
+ probeCodex().then((probe) => ({
336
+ id: "codex",
337
+ installed: probe.available,
338
+ version: probe.version,
339
+ packageName: ENGINE_PACKAGES.codex.packageName,
340
+ })),
312
341
  ]);
313
342
  await Promise.all([
314
343
  enrichWithUpdateInfo(pi, force),
315
344
  enrichWithUpdateInfo(dsh, force),
316
345
  enrichWithUpdateInfo(claude, force),
317
346
  enrichWithUpdateInfo(durable, force),
347
+ enrichWithUpdateInfo(codex, force),
318
348
  ]);
319
349
  const timestamp = Date.now();
320
- const results = [pi, dsh, claude, durable];
350
+ const results = [pi, dsh, claude, durable, codex];
321
351
  for (const res of results) {
322
352
  const existing = engineRegistry.get(res.id);
323
353
  engineRegistry.set(res.id, {
@@ -19,6 +19,8 @@ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  let cachedNpmRootG = null;
21
21
  let cachedCandidateRoots = null;
22
+ let candidateRootsCachedAt = 0;
23
+ const CANDIDATE_CACHE_TTL_MS = 5000;
22
24
  const packageRootCache = new Map();
23
25
  /**
24
26
  * 安全且带缓存地获取系统 npm 全局 root 目录。
@@ -50,9 +52,13 @@ export function getSystemNpmRootG() {
50
52
  * 覆盖:本地项目链、Node 邻近目录、fnm、nvm、pnpm、volta、yarn、bun、npm 全局 prefix 等。
51
53
  */
52
54
  export function getCandidateNodeModulesRoots(options) {
53
- if (!options?.refresh && cachedCandidateRoots !== null) {
55
+ if (!options?.refresh &&
56
+ cachedCandidateRoots !== null &&
57
+ Date.now() - candidateRootsCachedAt < CANDIDATE_CACHE_TTL_MS) {
54
58
  return cachedCandidateRoots;
55
59
  }
60
+ // A refreshed discovery must also re-query npm when its prefix changed.
61
+ cachedNpmRootG = null;
56
62
  const candidates = new Set();
57
63
  // 1. 本包内部与向上的祖先链路 node_modules
58
64
  let cur = dirname(fileURLToPath(import.meta.url));
@@ -100,7 +106,38 @@ export function getCandidateNodeModulesRoots(options) {
100
106
  candidates.add(npmGlobal);
101
107
  const env = process.env;
102
108
  const home = env.HOME || env.USERPROFILE || homedir();
103
- // 6. 版本管理器:fnm 自动嗅探
109
+ // 6. fnm 的 multishell 是临时链接;桌面/服务启动时可能完全不存在。
110
+ // 持久安装位于 FNM_DIR/node-versions/<version>/installation。
111
+ if (env.FNM_MULTISHELL_PATH) {
112
+ for (const suffix of ["node_modules", join("lib", "node_modules")]) {
113
+ const nm = join(env.FNM_MULTISHELL_PATH, suffix);
114
+ if (existsSync(nm))
115
+ candidates.add(resolve(nm));
116
+ }
117
+ }
118
+ const fnmDirs = new Set([
119
+ env.FNM_DIR,
120
+ env.APPDATA && join(env.APPDATA, "fnm"),
121
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, "fnm"),
122
+ join(env.XDG_DATA_HOME || join(home, ".local", "share"), "fnm"),
123
+ join(home, ".fnm"),
124
+ ].filter((dir) => !!dir));
125
+ for (const fnmDir of fnmDirs) {
126
+ try {
127
+ const versionsDir = join(fnmDir, "node-versions");
128
+ const versions = readdirSync(versionsDir).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
129
+ for (const version of versions) {
130
+ for (const suffix of ["node_modules", join("lib", "node_modules")]) {
131
+ const nm = join(versionsDir, version, "installation", suffix);
132
+ if (existsSync(nm))
133
+ candidates.add(resolve(nm));
134
+ }
135
+ }
136
+ }
137
+ catch {
138
+ /* Missing or unreadable version store; continue with other managers. */
139
+ }
140
+ }
104
141
  if (process.platform === "win32") {
105
142
  const localAppData = env.LOCALAPPDATA;
106
143
  if (localAppData) {
@@ -202,6 +239,7 @@ export function getCandidateNodeModulesRoots(options) {
202
239
  candidates.add(resolve("/usr/lib/node_modules"));
203
240
  }
204
241
  cachedCandidateRoots = Array.from(candidates);
242
+ candidateRootsCachedAt = Date.now();
205
243
  return cachedCandidateRoots;
206
244
  }
207
245
  /**