pi-web-ui 0.116.0 → 0.117.0
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 +38 -4
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +138 -70
- package/dist/server/agent-service-daemon.js +52 -6
- package/dist/server/agent-service.js +495 -141
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +35 -6
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +48 -1
- package/dist/server/device-center/collab-service.js +26 -8
- package/dist/server/device-center/collab-tool.js +394 -18
- package/dist/server/device-center/connector.js +107 -37
- package/dist/server/device-center/delivery-authority.js +98 -0
- package/dist/server/device-center/delivery-subject.js +30 -0
- package/dist/server/device-center/device-integration.js +453 -183
- package/dist/server/device-center/execution-guides.js +15 -5
- package/dist/server/device-center/executor.js +47 -5
- package/dist/server/device-center/hub-conversations.js +14 -4
- package/dist/server/device-center/hub-deliveries.js +120 -15
- package/dist/server/device-center/hub-integration.js +655 -334
- package/dist/server/device-center/hub-page.js +5 -4
- package/dist/server/device-center/hub-setup.js +23 -1
- package/dist/server/device-center/hub-transaction-log.js +197 -0
- package/dist/server/device-center/hub.js +772 -354
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +6 -2
- package/dist/server/device-center/local-publication.js +423 -0
- package/dist/server/device-center/local-verification-job.js +97 -0
- package/dist/server/device-center/local-verification.js +274 -0
- package/dist/server/device-center/local.js +107 -12
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +62 -25
- package/dist/server/device-center/publication-journal.js +312 -0
- package/dist/server/device-center/publish-intent.js +379 -0
- package/dist/server/device-center/relay.js +134 -24
- package/dist/server/device-center/runtime.js +426 -42
- package/dist/server/device-center/store.js +225 -47
- package/dist/server/device-center/task-outcome.js +81 -0
- package/dist/server/device-center/task-recovery.js +603 -178
- package/dist/server/device-center/task-settlement.js +353 -0
- package/dist/server/device-center/task-workspace.js +443 -0
- package/dist/server/device-center/verification-limits.js +10 -0
- package/dist/server/device-center/work-contract.js +995 -0
- package/dist/server/dispatch-domain-handlers.js +15 -0
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/index.js +26 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/quick-ask-settings.js +28 -0
- package/dist/server/quick-ask.js +164 -0
- package/dist/server/resolve-global-sdk.js +61 -11
- package/dist/server/scheduler-tasks.js +35 -8
- package/dist/server/session-list-scan.js +223 -0
- package/dist/server/session-open.js +93 -0
- package/dist/server/session-parser.js +4 -0
- package/dist/server/session-scan.js +90 -38
- package/dist/server/settings-service.js +9 -1
- package/dist/server/soft-cap.js +5 -0
- package/dist/server/transcript-prepare.js +73 -0
- package/dist/server/universal/drivers/claude-code.js +98 -34
- package/dist/server/universal/universal-session.js +4 -0
- package/dist/server/workspace-handle.js +428 -0
- package/docs/architecture-plugins.md +18 -5
- package/docs/device-center.md +30 -22
- package/package.json +3 -4
- package/plugin-sdk/README.md +16 -8
- package/plugin-sdk/client.d.ts +27 -0
- package/plugin-sdk/client.mjs +82 -0
- package/plugin-sdk/index.d.ts +10 -0
- package/plugin-sdk/index.mjs +4 -683
- package/plugin-sdk/package.json +15 -4
- package/plugin-sdk/testing.d.ts +10 -0
- package/plugin-sdk/testing.mjs +566 -0
- package/themes/flow-cristallo.css +168 -0
- package/themes/flow-ink.css +169 -0
- package/themes/flow-obsidian.css +169 -0
- package/themes/flow-zurich.css +169 -0
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
- package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
- package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
- package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
- package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
- package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
- package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
- package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
- package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
- package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
- package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
- package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
- package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
- package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
- package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
- package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
- package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
- package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
- package/web/dist/assets/index-BawF7ZP5.js +397 -0
- package/web/dist/assets/index-BoGCoq5X.js +397 -0
- package/web/dist/assets/index-CVW9FoY2.css +1 -0
- package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/device-center/local-page.js +0 -17
- package/dist/server/device-center/smoke-preview.js +0 -3
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/patch-turn-end-boundary.js +0 -77
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
- package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
- package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
- package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
- package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
- package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
- package/web/dist/assets/index-C6DwztqE.css +0 -1
- package/web/dist/assets/index-CuN802Sj.js +0 -93
- package/web/dist/assets/index-EH5Fw9fa.js +0 -93
|
@@ -450,6 +450,9 @@ export function handleSessionLifecycleMessage(msg, cs, send, daemon, clientId) {
|
|
|
450
450
|
void cs.rollbackSession?.(msg.messageId, msg.conversationId, msg.restoreWorkspace);
|
|
451
451
|
return true;
|
|
452
452
|
case "list_sessions":
|
|
453
|
+
// B5:带 limit 的请求(左栏「显示更多」翻页)先记住该项目的条数,之后的自动刷新沿用它
|
|
454
|
+
if (typeof msg.limit === "number")
|
|
455
|
+
cs.setSessionListLimit?.(msg.path ?? cs.cwd, msg.limit);
|
|
453
456
|
if (msg.path && normalizePathKey(msg.path) !== normalizePathKey(cs.cwd)) {
|
|
454
457
|
void cs.pushSessionsForCwd?.(msg.path);
|
|
455
458
|
}
|
|
@@ -699,12 +702,18 @@ export function handleSettingsMessage(msg, cs, send) {
|
|
|
699
702
|
visionBridgeModel: msg.visionBridgeModel,
|
|
700
703
|
visionBridgePromptMode: msg.visionBridgePromptMode,
|
|
701
704
|
visionBridgePrompt: msg.visionBridgePrompt,
|
|
705
|
+
quickAskEnabled: msg.quickAskEnabled,
|
|
706
|
+
quickAskModel: msg.quickAskModel,
|
|
707
|
+
quickAskThinking: msg.quickAskThinking,
|
|
708
|
+
quickAskSystemPrompt: msg.quickAskSystemPrompt,
|
|
709
|
+
quickAskExplainPrompt: msg.quickAskExplainPrompt,
|
|
702
710
|
subagentDefaultModel: msg.subagentDefaultModel,
|
|
703
711
|
subagentMaxDepth: msg.subagentMaxDepth,
|
|
704
712
|
subagentAutoWakeMaxTurns: msg.subagentAutoWakeMaxTurns,
|
|
705
713
|
retryMaxAttempts: msg.retryMaxAttempts,
|
|
706
714
|
softCapTokens: msg.softCapTokens,
|
|
707
715
|
softCapByModel: msg.softCapByModel,
|
|
716
|
+
autoCompactionInstructions: msg.autoCompactionInstructions,
|
|
708
717
|
reviewPrompt: msg.reviewPrompt,
|
|
709
718
|
reviewDisabledSkills: msg.reviewDisabledSkills,
|
|
710
719
|
markersEnabled: msg.markersEnabled,
|
|
@@ -784,6 +793,12 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
|
|
|
784
793
|
case "question_answer":
|
|
785
794
|
if (clientId && service.resolveSharedQuestion?.(clientId, msg.id, msg.answers, msg.cancelled, msg.cancelReason))
|
|
786
795
|
return true;
|
|
796
|
+
// 1. 优先尝试由当前会话直接解决(若当前客户端直接持有该问卷,即使携带了旧 owner 也能直接消费,防止因 orphan 认领/过户等导致 owner 不匹配)
|
|
797
|
+
if (cs.resolveQuestion?.(msg.id, msg.answers, msg.cancelled, msg.cancelReason))
|
|
798
|
+
return true;
|
|
799
|
+
// 2. 全局问卷直决:无需依赖 ownerId,全局根据唯一问卷 UUID 查找命中目标会话并 resolve
|
|
800
|
+
if (service.resolveGlobalQuestion?.(msg.id, msg.answers, msg.cancelled, msg.cancelReason))
|
|
801
|
+
return true;
|
|
787
802
|
if (msg.owner) {
|
|
788
803
|
// 跨页作答:答案转交持有方会话(本页不持有该问卷)。
|
|
789
804
|
if (typeof service.answerElsewhereQuestion === "function" && clientId) {
|
|
@@ -26,13 +26,14 @@
|
|
|
26
26
|
*/
|
|
27
27
|
import { startTurnTiming, finishTurnTiming } from "../turn-timing.js";
|
|
28
28
|
import { DEFAULT_DSH_CAPABILITIES } from "../engine-capabilities.js";
|
|
29
|
+
import { mergeQuickAskSettings, normalizeQuickAskSettings } from "../quick-ask-settings.js";
|
|
29
30
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
30
31
|
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
31
32
|
import { randomUUID } from "node:crypto";
|
|
32
33
|
import { homedir } from "node:os";
|
|
33
34
|
import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "../bg-servers.js";
|
|
34
35
|
import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizeBgCleanupMinutes, normalizePathKey, normalizeToolWatchdogTimeoutMs, settingsPresetToUi, } from "../client-state.js";
|
|
35
|
-
import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES } from "../client-state.js";
|
|
36
|
+
import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES, RECENT_PROJECTS_MAX, } from "../client-state.js";
|
|
36
37
|
import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
|
|
37
38
|
import { buildToolsSchemaText } from "../prompt-composer.js";
|
|
38
39
|
import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
|
|
@@ -2482,6 +2483,7 @@ export class DshClientSession {
|
|
|
2482
2483
|
summaries.push({
|
|
2483
2484
|
path: file,
|
|
2484
2485
|
sessionId,
|
|
2486
|
+
cwd: this.cwd,
|
|
2485
2487
|
name: explicitTitle,
|
|
2486
2488
|
displayName,
|
|
2487
2489
|
firstMessage: firstMsg,
|
|
@@ -3060,7 +3062,7 @@ export class DshClientSession {
|
|
|
3060
3062
|
return sbx ? { path, lastUsed, sandbox: sbx } : { path, lastUsed };
|
|
3061
3063
|
})
|
|
3062
3064
|
.sort((a, b) => b.lastUsed - a.lastUsed)
|
|
3063
|
-
.slice(0,
|
|
3065
|
+
.slice(0, RECENT_PROJECTS_MAX);
|
|
3064
3066
|
this.emit({ type: "projects", projects: list });
|
|
3065
3067
|
}
|
|
3066
3068
|
decodeProjectKey(key) {
|
|
@@ -3755,6 +3757,7 @@ export class DshClientSession {
|
|
|
3755
3757
|
: this.buildFallbackPromptSourceDefaults();
|
|
3756
3758
|
const promptSections = this.cachedPromptSections.length > 0 ? this.cachedPromptSections : this.buildFallbackPromptSections();
|
|
3757
3759
|
const settings = {
|
|
3760
|
+
...normalizeQuickAskSettings(this.stateStore.getSettingsSnapshot(this.clientId)),
|
|
3758
3761
|
steeringMode: "all",
|
|
3759
3762
|
followUpMode: "all",
|
|
3760
3763
|
promptMode: this.settings.promptMode,
|
|
@@ -3783,6 +3786,7 @@ export class DshClientSession {
|
|
|
3783
3786
|
// DSH 另有运行时:压缩软上限是 pi 引擎概念,这里保持关闭保协议完整。
|
|
3784
3787
|
softCapTokens: 0,
|
|
3785
3788
|
softCapByModel: {},
|
|
3789
|
+
autoCompactionInstructions: "",
|
|
3786
3790
|
questionnaireEnabled: this.settings.questionnaireEnabled,
|
|
3787
3791
|
toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
|
|
3788
3792
|
// DSH 无审批弹窗,策略恒为空(保协议完整)。
|
|
@@ -3935,6 +3939,7 @@ export class DshClientSession {
|
|
|
3935
3939
|
const markerGuidanceChanged = this.markerSvc.buildGuidance() !== prevMarkerGuidance;
|
|
3936
3940
|
// 持久化(跨重连存活)。
|
|
3937
3941
|
this.stateStore.saveSettings(this.clientId, {
|
|
3942
|
+
...mergeQuickAskSettings(this.stateStore.getSettingsSnapshot(this.clientId), partial),
|
|
3938
3943
|
chatUploadMaxMb: partial.chatUploadMaxMb,
|
|
3939
3944
|
workspaceUploadMaxMb: partial.workspaceUploadMaxMb,
|
|
3940
3945
|
folderUploadMaxMb: partial.folderUploadMaxMb,
|
|
@@ -3952,6 +3957,7 @@ export class DshClientSession {
|
|
|
3952
3957
|
// DSH 另有运行时:压缩软上限是 pi 引擎概念,这里保持关闭保协议完整。
|
|
3953
3958
|
softCapTokens: 0,
|
|
3954
3959
|
softCapByModel: {},
|
|
3960
|
+
autoCompactionInstructions: "",
|
|
3955
3961
|
questionnaireEnabled: this.settings.questionnaireEnabled,
|
|
3956
3962
|
toolApprovalEnabled: this.settings.toolApprovalEnabled !== false,
|
|
3957
3963
|
goalModeEnabled: this.settings.goalModeEnabled,
|
|
@@ -4344,6 +4350,7 @@ export class DshClientSession {
|
|
|
4344
4350
|
// DSH 另有运行时:压缩软上限是 pi 引擎概念,预设里保持关闭。
|
|
4345
4351
|
softCapTokens: 0,
|
|
4346
4352
|
softCapByModel: {},
|
|
4353
|
+
autoCompactionInstructions: "",
|
|
4347
4354
|
visionBridgePromptMode: "append",
|
|
4348
4355
|
visionBridgePrompt: "",
|
|
4349
4356
|
reviewPrompt: this.settings.reviewPrompt,
|
package/dist/server/index.js
CHANGED
|
@@ -20,9 +20,9 @@ import { botExecutionMessageAllowed } from "./device-center/bot-execution.js";
|
|
|
20
20
|
import { ALL_AGENT_TOOL_ENTRIES, effectiveDisabledAgentTools, isToolSupportedOnPlatform } from "./tool-manager.js";
|
|
21
21
|
// MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
|
|
22
22
|
import "./patch-remote-catalog.js";
|
|
23
|
-
import "./patch-turn-end-boundary.js";
|
|
24
23
|
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
25
24
|
import { registerPromptTemplateRoutes } from "./prompt-templates.js";
|
|
25
|
+
import { createQuickAskRuntime, registerQuickAskRoutes } from "./quick-ask.js";
|
|
26
26
|
import { readFile, stat } from "node:fs/promises";
|
|
27
27
|
import { createServer } from "node:http";
|
|
28
28
|
import { proxyHttp } from "./http-proxy.js";
|
|
@@ -544,6 +544,10 @@ app.use((req, res, next) => {
|
|
|
544
544
|
/** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
|
|
545
545
|
const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
|
|
546
546
|
registerPromptTemplateRoutes(app, DATA_DIR);
|
|
547
|
+
registerQuickAskRoutes(app, {
|
|
548
|
+
getSettings: () => sharedStateStore.getSettingsSnapshot(""),
|
|
549
|
+
getRuntime: (signal) => createQuickAskRuntime(getAgentDir(), signal),
|
|
550
|
+
});
|
|
547
551
|
/** 启动参数显式指定的引擎(--engine pi|dsh|codex|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
|
|
548
552
|
const EXPLICIT_ENGINE_ARG = cliFlag("--engine") ?? process.env.PI_WEB_ENGINE;
|
|
549
553
|
let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "codex"
|
|
@@ -1078,6 +1082,7 @@ const deviceCenter = await installLocalDeviceCenter({
|
|
|
1078
1082
|
recovery: runtime.recovery,
|
|
1079
1083
|
reportOutbox: runtime.reportOutbox,
|
|
1080
1084
|
onTask: runtime.onTask,
|
|
1085
|
+
onSteer: (taskId, text) => runtime.steerTask(taskId, text),
|
|
1081
1086
|
onInteractionAnswer: (answer) => runtime.answerTaskInteraction(answer.taskId, answer.attemptId, answer),
|
|
1082
1087
|
onConnect: syncBots,
|
|
1083
1088
|
onCommand: runtime.onCommand,
|
|
@@ -1612,6 +1617,13 @@ const service = {
|
|
|
1612
1617
|
resolveSharedQuestion(viewerId, id, answers, cancelled, cancelReason) {
|
|
1613
1618
|
return (ensureEngine(resolveClientEngine(viewerId)).resolveSharedQuestion?.(viewerId, id, answers, cancelled, cancelReason) ?? false);
|
|
1614
1619
|
},
|
|
1620
|
+
resolveGlobalQuestion(id, answers, cancelled, cancelReason) {
|
|
1621
|
+
for (const s of activeEngines()) {
|
|
1622
|
+
if (s.resolveGlobalQuestion?.(id, answers, cancelled, cancelReason))
|
|
1623
|
+
return true;
|
|
1624
|
+
}
|
|
1625
|
+
return false;
|
|
1626
|
+
},
|
|
1615
1627
|
resolveSharedToolApproval(viewerId, ...args) {
|
|
1616
1628
|
return ensureEngine(resolveClientEngine(viewerId)).resolveSharedToolApproval?.(viewerId, ...args) ?? false;
|
|
1617
1629
|
},
|
|
@@ -1916,6 +1928,15 @@ const scheduler = new SchedulerStore(DATA_DIR, {
|
|
|
1916
1928
|
else {
|
|
1917
1929
|
// 降级可见性(issue #231):必须无头时明确广播去向,不静默。
|
|
1918
1930
|
pushNoticeToAll("warning", `定时任务「${task.name}」原对话不在、同项目也无存活对话,已转后台执行(无头)。报告在后台任务面板的调度历史中查看。`, `Scheduled task "${task.name}" found no live conversation and runs headless; see its report in the background-tasks panel history.`);
|
|
1931
|
+
// 周期任务解绑已失效对话(issue #836),转为标准无头模式,避免每轮触发重复探测与广播警告
|
|
1932
|
+
if (!task.oneShot) {
|
|
1933
|
+
try {
|
|
1934
|
+
scheduler.rebind(task.id, { conversationId: "", sessionFile: "" });
|
|
1935
|
+
}
|
|
1936
|
+
catch {
|
|
1937
|
+
// 解绑失败不影响本次无头执行
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1919
1940
|
result = await runHeadless();
|
|
1920
1941
|
}
|
|
1921
1942
|
}
|
|
@@ -3162,6 +3183,8 @@ wss.on("connection", (ws) => {
|
|
|
3162
3183
|
// 新连接/新客户端 attach 首次快照必须强制全量(forceFull=true),
|
|
3163
3184
|
// 保证新标签页/刷新页能立刻拿到完整的会话基线,绝不因增量 delta 而卡在加载中。
|
|
3164
3185
|
cs.flushSnapshot(true);
|
|
3186
|
+
void cs.pushProjects();
|
|
3187
|
+
void cs.refreshSessions();
|
|
3165
3188
|
// 内置定时任务列表随附推一次(后续变更经 pushSchedulerTasks 广播)。
|
|
3166
3189
|
try {
|
|
3167
3190
|
send({ type: "scheduler_tasks", tasks: scheduler.list() });
|
|
@@ -3177,6 +3200,8 @@ wss.on("connection", (ws) => {
|
|
|
3177
3200
|
// ensureLoaded 失败(如磁盘读错)不能卡死快照——前端 30s 无消息
|
|
3178
3201
|
// 会重连,重连又失败会陷入循环。至少把状态推下去(同样强制全量)。
|
|
3179
3202
|
cs.flushSnapshot(true);
|
|
3203
|
+
void cs.pushProjects();
|
|
3204
|
+
void cs.refreshSessions();
|
|
3180
3205
|
replayQueued();
|
|
3181
3206
|
});
|
|
3182
3207
|
// hello may carry the UI locale — persist it before replaying
|
|
@@ -27,7 +27,8 @@
|
|
|
27
27
|
* read-only node_modules or a different node-pty version just skips the patch
|
|
28
28
|
* (the runtime console.warn filter in terminals.ts still guards the flood).
|
|
29
29
|
*/
|
|
30
|
-
import { existsSync, readFileSync
|
|
30
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
31
|
+
import { writeAtomicSync } from "./atomic-file.js";
|
|
31
32
|
import { createRequire } from "node:module";
|
|
32
33
|
import { dirname, join } from "node:path";
|
|
33
34
|
const require = createRequire(import.meta.url);
|
|
@@ -52,7 +53,7 @@ function patchFile(pkgDir, rel, find, replace) {
|
|
|
52
53
|
return; // already patched
|
|
53
54
|
if (!src.includes(find))
|
|
54
55
|
return; // unexpected content — leave alone
|
|
55
|
-
|
|
56
|
+
writeAtomicSync(file, src.replace(find, replace));
|
|
56
57
|
}
|
|
57
58
|
catch {
|
|
58
59
|
// best-effort — the runtime console.warn filter still guards the flood
|
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
* default union semantics — never a crash). MUST be imported before the SDK
|
|
22
22
|
* modules are first loaded (agent-service.ts imports this first).
|
|
23
23
|
*/
|
|
24
|
-
import { existsSync, readFileSync
|
|
24
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
25
|
+
import { writeAtomicSync } from "./atomic-file.js";
|
|
25
26
|
import { fileURLToPath } from "node:url";
|
|
26
27
|
import { dirname, join } from "node:path";
|
|
27
28
|
/** Supported patch pairs across SDK versions (0.87.x, 1.1.0+). */
|
|
@@ -67,7 +68,7 @@ function applyPatch() {
|
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
70
|
if (changed) {
|
|
70
|
-
|
|
71
|
+
writeAtomicSync(file, src);
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
catch {
|
|
@@ -9,11 +9,20 @@
|
|
|
9
9
|
*
|
|
10
10
|
* 纪律:
|
|
11
11
|
* 1. 这里只描述**元数据**(字段名 / 分组 / 文案 key),净化与归一化仍在 preset-share 里;
|
|
12
|
-
* 2. `PRESET_FIELD_NAMES` 必须覆盖 `ClientSettings` 的每个字段 —— 单测
|
|
12
|
+
* 2. `PRESET_FIELD_NAMES` / `PRESET_EXCLUDED_KEYS` 必须覆盖 `ClientSettings` 的每个字段 —— 单测
|
|
13
13
|
* `tests/unit/preset-share.test.ts` 用类型 + 快照双重守卫,漏字段会红;
|
|
14
14
|
* 3. 分组只影响 UI 折叠与「勾一组」,不影响写入逻辑(导入按字段名过滤)。
|
|
15
15
|
*/
|
|
16
16
|
import { resolveEnabledAgentTools } from "./tool-manager.js";
|
|
17
|
+
/** Internal flags and independent popup preferences are excluded from agent presets. */
|
|
18
|
+
export const PRESET_EXCLUDED_KEYS = [
|
|
19
|
+
"_promptPluginDevConfigured",
|
|
20
|
+
"quickAskEnabled",
|
|
21
|
+
"quickAskModel",
|
|
22
|
+
"quickAskThinking",
|
|
23
|
+
"quickAskSystemPrompt",
|
|
24
|
+
"quickAskExplainPrompt",
|
|
25
|
+
];
|
|
17
26
|
/** 预设字段分组(导入预览里的折叠块;顺序即展示顺序)。 */
|
|
18
27
|
export const PRESET_GROUP_ORDER = ["prompt", "tools", "terminal", "skills", "ai", "ui", "engine"];
|
|
19
28
|
/**
|
|
@@ -72,6 +81,7 @@ export const PRESET_FIELD_GROUPS = {
|
|
|
72
81
|
"retryMaxAttempts",
|
|
73
82
|
"softCapTokens",
|
|
74
83
|
"softCapByModel",
|
|
84
|
+
"autoCompactionInstructions",
|
|
75
85
|
"subagentDefaultModel",
|
|
76
86
|
"subagentMaxDepth",
|
|
77
87
|
"subagentAutoWakeMaxTurns",
|
|
@@ -406,6 +416,12 @@ export const PRESET_FIELD_META = {
|
|
|
406
416
|
hintZh: "针对不同模型单独设置的上下文压缩阈值",
|
|
407
417
|
hintEn: "Custom soft-cap thresholds configured per model",
|
|
408
418
|
},
|
|
419
|
+
autoCompactionInstructions: {
|
|
420
|
+
labelZh: "自动压缩附加指令",
|
|
421
|
+
labelEn: "Auto-Compaction Instructions",
|
|
422
|
+
hintZh: "软上限自动压缩时传给 SDK 的自定义指令(留空 = SDK 默认摘要;不影响手动 /compact)",
|
|
423
|
+
hintEn: "Custom instructions passed to automatic soft-cap compaction (empty = SDK default; does not affect manual /compact)",
|
|
424
|
+
},
|
|
409
425
|
subagentDefaultModel: {
|
|
410
426
|
labelZh: "子代理默认模型",
|
|
411
427
|
labelEn: "Subagent Default Model",
|
|
@@ -271,6 +271,7 @@ const PRESET_FIELD_KINDS = {
|
|
|
271
271
|
retryMaxAttempts: "retry",
|
|
272
272
|
softCapTokens: "softCap",
|
|
273
273
|
softCapByModel: "softCapByModel",
|
|
274
|
+
autoCompactionInstructions: "text",
|
|
274
275
|
subagentDefaultModel: "nullableString",
|
|
275
276
|
subagentMaxDepth: "number",
|
|
276
277
|
subagentAutoWakeMaxTurns: "number",
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export const DEFAULT_QUICK_ASK_EXPLAIN_PROMPT = "解释下: {{input}}";
|
|
2
|
+
export const MAX_QUICK_ASK_PROMPT_LENGTH = 16_384;
|
|
3
|
+
const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh"]);
|
|
4
|
+
/** Omitted dispatch fields are represented by undefined; explicit false/null/empty values still apply. */
|
|
5
|
+
export function mergeQuickAskSettings(current, patch) {
|
|
6
|
+
const defined = Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));
|
|
7
|
+
return normalizeQuickAskSettings({ ...current, ...defined });
|
|
8
|
+
}
|
|
9
|
+
export function isQuickAskModel(value) {
|
|
10
|
+
return typeof value === "string" && /^[^\s/]+\/\S+$/.test(value) && value.length <= 512;
|
|
11
|
+
}
|
|
12
|
+
export function normalizeQuickAskSettings(value) {
|
|
13
|
+
const model = typeof value.quickAskModel === "string" ? value.quickAskModel.trim() : null;
|
|
14
|
+
const explainPrompt = value.quickAskExplainPrompt;
|
|
15
|
+
return {
|
|
16
|
+
quickAskEnabled: typeof value.quickAskEnabled === "boolean" ? value.quickAskEnabled : true,
|
|
17
|
+
quickAskModel: isQuickAskModel(model) ? model : null,
|
|
18
|
+
quickAskThinking: THINKING_LEVELS.has(value.quickAskThinking)
|
|
19
|
+
? value.quickAskThinking
|
|
20
|
+
: "off",
|
|
21
|
+
quickAskSystemPrompt: typeof value.quickAskSystemPrompt === "string" && value.quickAskSystemPrompt.length <= MAX_QUICK_ASK_PROMPT_LENGTH
|
|
22
|
+
? value.quickAskSystemPrompt
|
|
23
|
+
: "",
|
|
24
|
+
quickAskExplainPrompt: typeof explainPrompt === "string" && explainPrompt.trim() && explainPrompt.length <= MAX_QUICK_ASK_PROMPT_LENGTH
|
|
25
|
+
? explainPrompt
|
|
26
|
+
: DEFAULT_QUICK_ASK_EXPLAIN_PROMPT,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { ModelRuntime } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isQuickAskModel, normalizeQuickAskSettings } from "./quick-ask-settings.js";
|
|
4
|
+
export const MAX_QUICK_ASK_TEXT_LENGTH = 65_536;
|
|
5
|
+
export const MAX_QUICK_ASK_MESSAGES = 100;
|
|
6
|
+
export const QUICK_ASK_TIMEOUT_MS = 120_000;
|
|
7
|
+
class QuickAskError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
constructor(status, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function parseQuickAskRequest(body) {
|
|
15
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
16
|
+
throw new QuickAskError(400, "Expected an object");
|
|
17
|
+
const value = body;
|
|
18
|
+
if (Object.keys(value).some((key) => key !== "messages" && key !== "fallbackModel"))
|
|
19
|
+
throw new QuickAskError(400, "Unexpected request field");
|
|
20
|
+
if (!Array.isArray(value.messages) || !value.messages.length)
|
|
21
|
+
throw new QuickAskError(400, "messages is required");
|
|
22
|
+
if (value.messages.length > MAX_QUICK_ASK_MESSAGES)
|
|
23
|
+
throw new QuickAskError(413, "Too many messages");
|
|
24
|
+
let length = 0;
|
|
25
|
+
const messages = value.messages.map((item) => {
|
|
26
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
27
|
+
throw new QuickAskError(400, "Invalid message");
|
|
28
|
+
if (Object.keys(item).some((key) => key !== "role" && key !== "content") ||
|
|
29
|
+
(item.role !== "user" && item.role !== "assistant") ||
|
|
30
|
+
typeof item.content !== "string" ||
|
|
31
|
+
!item.content.trim())
|
|
32
|
+
throw new QuickAskError(400, "Messages require a user/assistant role and non-empty content");
|
|
33
|
+
length += item.content.length;
|
|
34
|
+
return { role: item.role, content: item.content };
|
|
35
|
+
});
|
|
36
|
+
if (length > MAX_QUICK_ASK_TEXT_LENGTH)
|
|
37
|
+
throw new QuickAskError(413, "Messages are too long");
|
|
38
|
+
if (messages[0].role !== "user" ||
|
|
39
|
+
messages.at(-1)?.role !== "user" ||
|
|
40
|
+
messages.some((message, index) => index > 0 && messages[index - 1].role === message.role))
|
|
41
|
+
throw new QuickAskError(400, "Messages must alternate user/assistant and end with a user question");
|
|
42
|
+
if (value.fallbackModel !== undefined && !isQuickAskModel(value.fallbackModel))
|
|
43
|
+
throw new QuickAskError(400, "fallbackModel must be provider/id");
|
|
44
|
+
return { messages, ...(value.fallbackModel !== undefined ? { fallbackModel: value.fallbackModel } : {}) };
|
|
45
|
+
}
|
|
46
|
+
async function complete(request, settings, runtime, signal) {
|
|
47
|
+
signal.throwIfAborted();
|
|
48
|
+
const spec = settings.quickAskModel ?? request.fallbackModel;
|
|
49
|
+
const slash = spec?.indexOf("/") ?? -1;
|
|
50
|
+
let model = spec ? runtime.getModel(spec.slice(0, slash), spec.slice(slash + 1)) : undefined;
|
|
51
|
+
// Main conversation engines may expose provider IDs that do not exist in the independent SDK catalog.
|
|
52
|
+
if (!model && !settings.quickAskModel)
|
|
53
|
+
model = (await runtime.getAvailable(undefined, { signal }))[0];
|
|
54
|
+
signal.throwIfAborted();
|
|
55
|
+
if (!model)
|
|
56
|
+
throw new QuickAskError(400, settings.quickAskModel ? `Model not found: ${settings.quickAskModel}` : "No available model");
|
|
57
|
+
const messages = request.messages.map((message) => message.role === "user"
|
|
58
|
+
? { role: "user", content: [{ type: "text", text: message.content }], timestamp: Date.now() }
|
|
59
|
+
: {
|
|
60
|
+
role: "assistant",
|
|
61
|
+
content: [{ type: "text", text: message.content }],
|
|
62
|
+
timestamp: Date.now(),
|
|
63
|
+
api: model.api,
|
|
64
|
+
provider: model.provider,
|
|
65
|
+
model: model.id,
|
|
66
|
+
stopReason: "stop",
|
|
67
|
+
usage: {
|
|
68
|
+
input: 0,
|
|
69
|
+
output: 0,
|
|
70
|
+
cacheRead: 0,
|
|
71
|
+
cacheWrite: 0,
|
|
72
|
+
totalTokens: 0,
|
|
73
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
const result = await runtime.completeSimple(model, {
|
|
77
|
+
messages,
|
|
78
|
+
...(settings.quickAskSystemPrompt ? { systemPrompt: settings.quickAskSystemPrompt } : {}),
|
|
79
|
+
}, {
|
|
80
|
+
...(settings.quickAskThinking !== "off" ? { reasoning: settings.quickAskThinking } : {}),
|
|
81
|
+
signal,
|
|
82
|
+
maxTokens: 4096,
|
|
83
|
+
});
|
|
84
|
+
signal.throwIfAborted();
|
|
85
|
+
if (result.stopReason === "error" || result.stopReason === "aborted")
|
|
86
|
+
throw new QuickAskError(502, result.errorMessage || "Model completion failed");
|
|
87
|
+
const text = result.content
|
|
88
|
+
.filter((part) => part.type === "text")
|
|
89
|
+
.map((part) => part.text)
|
|
90
|
+
.join("\n")
|
|
91
|
+
.trim();
|
|
92
|
+
if (!text)
|
|
93
|
+
throw new QuickAskError(502, "Model returned no answer");
|
|
94
|
+
return { text, model: `${model.provider}/${model.id}` };
|
|
95
|
+
}
|
|
96
|
+
async function respondWithCancellation(req, res, deps, operation) {
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const onDisconnect = () => {
|
|
99
|
+
if (!res.writableEnded)
|
|
100
|
+
controller.abort(new QuickAskError(499, "Request cancelled"));
|
|
101
|
+
};
|
|
102
|
+
req.once("aborted", onDisconnect);
|
|
103
|
+
res.once("close", onDisconnect);
|
|
104
|
+
let rejectAbort;
|
|
105
|
+
const interrupted = new Promise((_resolve, reject) => {
|
|
106
|
+
rejectAbort = reject;
|
|
107
|
+
});
|
|
108
|
+
const onAbort = () => rejectAbort(controller.signal.reason);
|
|
109
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
110
|
+
const timer = setTimeout(() => controller.abort(new QuickAskError(504, "Quick ask timed out")), deps.timeoutMs ?? QUICK_ASK_TIMEOUT_MS);
|
|
111
|
+
timer.unref();
|
|
112
|
+
try {
|
|
113
|
+
const result = await Promise.race([operation(controller.signal), interrupted]);
|
|
114
|
+
if (!res.destroyed)
|
|
115
|
+
res.json(result);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
if (!res.destroyed)
|
|
119
|
+
res
|
|
120
|
+
.status(error instanceof QuickAskError ? error.status : 502)
|
|
121
|
+
.json({ error: error instanceof Error ? error.message : "Quick ask failed" });
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
req.off("aborted", onDisconnect);
|
|
126
|
+
res.off("close", onDisconnect);
|
|
127
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
export function registerQuickAskRoutes(app, deps) {
|
|
131
|
+
app.get("/api/quick-ask/models", async (req, res) => {
|
|
132
|
+
await respondWithCancellation(req, res, deps, async (signal) => {
|
|
133
|
+
const runtime = await deps.getRuntime(signal);
|
|
134
|
+
signal.throwIfAborted();
|
|
135
|
+
const available = await runtime.getAvailable(undefined, { signal });
|
|
136
|
+
signal.throwIfAborted();
|
|
137
|
+
return {
|
|
138
|
+
models: available.map((model) => ({ provider: model.provider, id: model.id, label: model.name || model.id })),
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
app.post("/api/quick-ask", async (req, res) => {
|
|
143
|
+
let request;
|
|
144
|
+
try {
|
|
145
|
+
request = parseQuickAskRequest(req.body);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
res.status(error instanceof QuickAskError ? error.status : 400).json({ error: error.message });
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
await respondWithCancellation(req, res, deps, async (signal) => {
|
|
152
|
+
const settings = normalizeQuickAskSettings(deps.getSettings());
|
|
153
|
+
return complete(request, settings, await deps.getRuntime(signal), signal);
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
/** Only auth/catalog configuration is loaded; no AgentSession or resource loader is created. */
|
|
158
|
+
export function createQuickAskRuntime(agentDir, signal) {
|
|
159
|
+
return ModelRuntime.create({
|
|
160
|
+
authPath: join(agentDir, "auth.json"),
|
|
161
|
+
modelsPath: join(agentDir, "models.json"),
|
|
162
|
+
signal,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
*/
|
|
28
28
|
import { registerBashProcessPatch } from "./patch-bash-process.js";
|
|
29
29
|
import { registerExecutableLookupPatch } from "./patch-executable-lookup.js";
|
|
30
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
30
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
31
31
|
import { registerHooks } from "node:module";
|
|
32
32
|
import { dirname, join } from "node:path";
|
|
33
33
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -66,28 +66,73 @@ export function findBundledCopy(copies, fromFile = import.meta.url) {
|
|
|
66
66
|
const expectedBundledPath = join(pkgRoot, "node_modules", PKG, "package.json").replace(/\\/g, "/");
|
|
67
67
|
return copies.find((c) => c.path.replace(/\\/g, "/") === expectedBundledPath) ?? null;
|
|
68
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* 健全性检查:外部 SDK 副本是否完整可用(防止因中断安装/文件截断导致 SyntaxError 搞崩服务)。
|
|
71
|
+
* 纯内存虚拟测试(文件在磁盘上不存在)默认视为可用,避免破坏单测。
|
|
72
|
+
*/
|
|
73
|
+
export function isSdkCopyUsable(copy) {
|
|
74
|
+
if (!existsSync(copy.path))
|
|
75
|
+
return true;
|
|
76
|
+
try {
|
|
77
|
+
const pkgDir = dirname(copy.path);
|
|
78
|
+
const raw = readFileSync(copy.path, "utf8");
|
|
79
|
+
const info = JSON.parse(raw);
|
|
80
|
+
if (info?.name && info.name !== PKG)
|
|
81
|
+
return false;
|
|
82
|
+
// 检查入口文件是否存在且非空
|
|
83
|
+
const mainRel = typeof info?.main === "string" ? info.main : "dist/index.js";
|
|
84
|
+
const mainFile = join(pkgDir, mainRel);
|
|
85
|
+
if (!existsSync(mainFile) || statSync(mainFile).size === 0)
|
|
86
|
+
return false;
|
|
87
|
+
// 检查核心 agent-session.js(若存在则防截断)
|
|
88
|
+
const sessionFile = join(pkgDir, "dist", "core", "agent-session.js");
|
|
89
|
+
if (existsSync(sessionFile)) {
|
|
90
|
+
const stat = statSync(sessionFile);
|
|
91
|
+
if (stat.size < 10000)
|
|
92
|
+
return false;
|
|
93
|
+
const fd = openSync(sessionFile, "r");
|
|
94
|
+
try {
|
|
95
|
+
const buf = Buffer.alloc(Math.min(2048, stat.size));
|
|
96
|
+
readSync(fd, buf, 0, buf.length, Math.max(0, stat.size - buf.length));
|
|
97
|
+
const tail = buf.toString("utf8").trim();
|
|
98
|
+
if (!tail.includes("sourceMappingURL") && !tail.endsWith("}") && !tail.endsWith("};")) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
closeSync(fd);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
69
112
|
/**
|
|
70
113
|
* 该用哪一份对外解析(纯函数,便于单测)。
|
|
71
114
|
* `copies` 按 Node 的解析顺序,`bundledCopy` 为识别到的随包自带副本(null = 无自带副本)。
|
|
72
115
|
* 返回 null = 保持默认(用自带副本兜底)。
|
|
73
116
|
*/
|
|
74
|
-
export function pickGlobalSdk(copies, mode, bundledCopy = copies[0] ?? null) {
|
|
117
|
+
export function pickGlobalSdk(copies, mode, bundledCopy = copies[0] ?? null, isUsable = isSdkCopyUsable) {
|
|
75
118
|
if (BUNDLED_MODES.has((mode ?? "global").trim().toLowerCase()))
|
|
76
119
|
return null;
|
|
120
|
+
const validCopies = copies.filter(isUsable);
|
|
121
|
+
const validBundled = bundledCopy && isUsable(bundledCopy) ? bundledCopy : null;
|
|
77
122
|
// 显式透传的宿主 SDK 路径(如 extensions/webui.ts 宿主传递,issue #482):若不降级优先选用
|
|
78
123
|
if (process.env.PI_WEB_SDK_DIR) {
|
|
79
|
-
const hostCopy =
|
|
80
|
-
if (hostCopy && (!
|
|
124
|
+
const hostCopy = validCopies.find((c) => dirname(c.path) === process.env.PI_WEB_SDK_DIR);
|
|
125
|
+
if (hostCopy && (!validBundled || compareVersions(hostCopy.version, validBundled.version) >= 0)) {
|
|
81
126
|
return hostCopy;
|
|
82
127
|
}
|
|
83
128
|
}
|
|
84
129
|
// 如果没有随包自带副本(例如 pnpm 隔离安装未包含可选依赖,或轻量部署,issue #562):
|
|
85
130
|
// 机器上只要发现可用副本就必须选用,否则 Node 无法导入 SDK 会报错崩溃。
|
|
86
|
-
if (!
|
|
87
|
-
if (
|
|
131
|
+
if (!validBundled) {
|
|
132
|
+
if (validCopies.length === 0)
|
|
88
133
|
return null;
|
|
89
|
-
let best =
|
|
90
|
-
for (const copy of
|
|
134
|
+
let best = validCopies[0];
|
|
135
|
+
for (const copy of validCopies.slice(1)) {
|
|
91
136
|
if (compareVersions(copy.version, best.version) > 0) {
|
|
92
137
|
best = copy;
|
|
93
138
|
}
|
|
@@ -96,10 +141,10 @@ export function pickGlobalSdk(copies, mode, bundledCopy = copies[0] ?? null) {
|
|
|
96
141
|
}
|
|
97
142
|
// 存在自带副本:只考虑比自带副本**严格更新**的外部副本,多份取版本最高的(旧的/同版本的都不折腾)。
|
|
98
143
|
let best = null;
|
|
99
|
-
for (const copy of
|
|
100
|
-
if (copy.path ===
|
|
144
|
+
for (const copy of validCopies) {
|
|
145
|
+
if (copy.path === validBundled.path)
|
|
101
146
|
continue;
|
|
102
|
-
if (compareVersions(copy.version,
|
|
147
|
+
if (compareVersions(copy.version, validBundled.version) > 0 &&
|
|
103
148
|
(!best || compareVersions(copy.version, best.version) > 0)) {
|
|
104
149
|
best = copy;
|
|
105
150
|
}
|
|
@@ -110,6 +155,11 @@ export function pickGlobalSdk(copies, mode, bundledCopy = copies[0] ?? null) {
|
|
|
110
155
|
export function registerGlobalSdkPreference(mode = process.env.PI_WEB_SDK, fromFile = import.meta.url) {
|
|
111
156
|
try {
|
|
112
157
|
const copies = sdkCopies(fromFile);
|
|
158
|
+
for (const copy of copies) {
|
|
159
|
+
if (existsSync(copy.path) && !isSdkCopyUsable(copy)) {
|
|
160
|
+
console.warn(`[pi-web-ui] SDK copy at ${copy.path} (v${copy.version}) appears incomplete or damaged, skipping.`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
113
163
|
const bundled = findBundledCopy(copies, fromFile);
|
|
114
164
|
const chosen = pickGlobalSdk(copies, mode, bundled);
|
|
115
165
|
if (!chosen)
|