pi-web-ui 0.108.0 → 0.110.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +21 -1
  3. package/README.zh-CN.md +21 -1
  4. package/README.zh-TW.md +201 -677
  5. package/dist/server/agent-service-daemon.js +2 -2
  6. package/dist/server/agent-service.js +47 -36
  7. package/dist/server/attachments.js +26 -6
  8. package/dist/server/client-state.js +4 -3
  9. package/dist/server/dispatch-domain-handlers.js +2 -0
  10. package/dist/server/dispatch-plugin-handlers.js +1 -0
  11. package/dist/server/dsh/dsh-agent-service.js +2 -2
  12. package/dist/server/durable/durable-driver.js +1 -1
  13. package/dist/server/durable/durable-tools.js +4 -1
  14. package/dist/server/files-service.js +23 -4
  15. package/dist/server/goal-service.js +12 -3
  16. package/dist/server/index.js +39 -10
  17. package/dist/server/locales.js +33 -0
  18. package/dist/server/marker-service.js +7 -13
  19. package/dist/server/markers/builtins/action.js +5 -6
  20. package/dist/server/markers/builtins/notify.js +2 -2
  21. package/dist/server/markers/builtins/rename.js +2 -2
  22. package/dist/server/markers/registry.js +5 -1
  23. package/dist/server/message-window.js +190 -0
  24. package/dist/server/model-admin.js +0 -4
  25. package/dist/server/plugin-catalog-sync.js +10 -2
  26. package/dist/server/plugin-catalog.js +63 -10
  27. package/dist/server/plugins.js +47 -6
  28. package/dist/server/preset-share.js +2 -3
  29. package/dist/server/process-utils.js +58 -24
  30. package/dist/server/protocol-version.js +1 -1
  31. package/dist/server/settings-service.js +8 -3
  32. package/dist/server/slash-commands.js +16 -4
  33. package/dist/server/text-sniff.js +10 -7
  34. package/dist/server/themes.js +36 -1
  35. package/dist/server/universal/drivers/dsh-driver.js +1 -1
  36. package/dist/server/universal/universal-session.js +12 -4
  37. package/dist/server/worktree-service.js +1 -1
  38. package/package.json +7 -2
  39. package/plugin-sdk/index.d.ts +20 -0
  40. package/plugin-sdk/index.mjs +14 -0
  41. package/plugins/catalog.json +22 -2
  42. package/themes/aetheris.css +155 -121
  43. package/themes/ayu-light.css +19 -15
  44. package/themes/bases/flow-base.css +1363 -0
  45. package/themes/bases/obsidian-base.css +679 -0
  46. package/themes/bases/zhujian-base.css +687 -0
  47. package/themes/bases/zhupi-base.css +659 -0
  48. package/themes/catppuccin-latte.css +17 -15
  49. package/themes/catppuccin.css +5 -2
  50. package/themes/claude-code-dark.css +2 -0
  51. package/themes/codex.css +16 -14
  52. package/themes/cyberpunk.css +4 -1
  53. package/themes/dark-teal.css +4 -1
  54. package/themes/dazzle.css +3 -0
  55. package/themes/everforest-light.css +17 -15
  56. package/themes/flow-light.css +10 -931
  57. package/themes/flow.css +13 -946
  58. package/themes/geist.css +16 -14
  59. package/themes/gruvbox-light.css +13 -11
  60. package/themes/kanagawa-lotus.css +16 -14
  61. package/themes/mist.css +18 -16
  62. package/themes/nord.css +16 -12
  63. package/themes/one-dark.css +9 -5
  64. package/themes/paper.css +9 -7
  65. package/themes/rose-pine-dawn.css +14 -12
  66. package/themes/sakura.css +15 -13
  67. package/themes/solarized-light.css +19 -17
  68. package/themes/tokyo-night.css +4 -2
  69. package/themes/vs-code-dark.css +4 -3
  70. package/themes/wallpaper-flow.css +73 -1031
  71. package/themes/wallpaper-obsidian.css +4 -673
  72. package/themes/white.css +8 -6
  73. package/themes/zhujian-dark.css +6 -608
  74. package/themes/zhujian.css +6 -657
  75. package/themes/zhupi-dark.css +6 -579
  76. package/themes/zhupi.css +6 -629
  77. package/web/dist/assets/{TerminalPanel-CslRhcS7.js → TerminalPanel-BHjM6pzY.js} +1 -1
  78. package/web/dist/assets/index-DwInT7-a.css +1 -0
  79. package/web/dist/assets/index-GfVFIgIL.js +693 -0
  80. package/web/dist/index.html +2 -2
  81. package/web/dist/sw.js +1 -1
  82. package/web/dist/assets/index-C_2Fl6f6.js +0 -690
  83. package/web/dist/assets/index-D0BtO5dn.css +0 -1
@@ -870,8 +870,8 @@ export class AgentService {
870
870
  }
871
871
  return;
872
872
  }
873
- if (AgentService.isPseudoClientId(ownerId)) {
874
- fail("定时任务/插件会话不支持过户 —— 报告会自动落回绑定的对话,可在后台任务面板查看进度", "Scheduler/plugin sessions cannot be taken over — reports are saved to the bound conversation automatically; check progress in the Background Tasks panel.");
873
+ if (ownerId.startsWith("scheduler:")) {
874
+ fail("定时任务会话不支持过户 —— 报告会自动落回绑定的对话,可在后台任务面板查看进度", "Scheduler sessions cannot be taken over — reports are saved to the bound conversation automatically; check progress in the Background Tasks panel.");
875
875
  return;
876
876
  }
877
877
  const source = this.clients.get(ownerId);
@@ -17,16 +17,12 @@ import "./patch-remote-catalog.js";
17
17
  import "./patch-turn-end-boundary.js";
18
18
  import { spawn } from "node:child_process";
19
19
  import { createHash, randomUUID } from "node:crypto";
20
- import { createRequire } from "node:module";
21
20
  import * as fsPromises from "node:fs/promises";
22
21
  import { DEFAULT_PI_CAPABILITIES } from "./engine-capabilities.js";
23
- import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, statSync, mkdirSync, watch, writeFileSync, } from "node:fs";
22
+ import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, mkdirSync, watch, writeFileSync, } from "node:fs";
24
23
  import { homedir } from "node:os";
25
- import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
26
- import { fileURLToPath } from "node:url";
27
- import { writeAtomicSync } from "./atomic-file.js";
28
- import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashToolDefinition, createCodemodeExtension, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLsToolDefinition, createToolSearchExtension, createWriteToolDefinition, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, estimateTokens, } from "@earendil-works/pi-coding-agent";
29
- import { Type } from "typebox";
24
+ import { basename, delimiter, join, resolve } from "node:path";
25
+ import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createCodemodeExtension, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLsToolDefinition, createToolSearchExtension, resolveModelScopeWithDiagnostics, getAgentDir, SessionManager, VERSION, } from "@earendil-works/pi-coding-agent";
30
26
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
31
27
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
32
28
  import { collectInstalledEngineTargets } from "./engine-probe.js";
@@ -39,9 +35,7 @@ import { calibrateSessionLeaf } from "./session-branch.js";
39
35
  import { danglingToolResultText, findDanglingToolCalls, healDanglingToolCallFile, } from "./dangling-tools.js";
40
36
  import { removeQueuedByIndexOrText } from "./queue-utils.js";
41
37
  import { syncPluginToolsIntoSession } from "./plugins.js";
42
- import { modelChangeKey, pickClientConversation, pickLatestClientSnapshot } from "./plugin-conversation-view.js";
43
- import { denialText, } from "./plugin-tool-guard.js";
44
- import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
38
+ import { modelChangeKey, pickClientConversation } from "./plugin-conversation-view.js";
45
39
  import { SettingsService } from "./settings-service.js";
46
40
  import { GoalService, buildDiffFingerprint, extractErrorSnippetFromSession, lastToolNameOfSession, } from "./goal-service.js";
47
41
  import { buildEvidenceDigest, sessionMessagesOf } from "./goal-evidence.js";
@@ -53,7 +47,7 @@ import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPro
53
47
  import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, isInternalExtension, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
54
48
  import { isTraditionalLocale, pick, resolveServerLang } from "./i18n.js";
55
49
  import { SubagentTemplatesStore, localizeTemplate, pickTemplatePrompt, } from "./subagent-templates.js";
56
- import { ApprovalRulesStore, extractTargetPath } from "./approval-rules.js";
50
+ import { ApprovalRulesStore } from "./approval-rules.js";
57
51
  import { ComposerDraftsStore } from "./composer-drafts.js";
58
52
  import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGate } from "./sandbox-service.js";
59
53
  import { readPermissionFromSession } from "./permission-preset.js";
@@ -62,25 +56,22 @@ import { createScheduleToolHost, createConversationReadHost, createClaimToolHost
62
56
  import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
63
57
  import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
64
58
  import { fillSkillContents } from "./skill-content-filler.js";
65
- import { hasSettledAssistantUsage, estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
59
+ import { estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
66
60
  import { formatSubagentHandoffMessage, recordSubagentHandoff } from "./subagent-handoff.js";
67
61
  import { executeContextBudgetPruning } from "./context-budget-runner.js";
68
- import { isPathInsideRoot } from "./approval-rules.js";
69
- import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, pluginApprovalCategory, } from "./tool-approval.js";
62
+ import { approvalSuppressionReason, checkDangerousToolCall, isApprovalPolicyEmpty, } from "./tool-approval.js";
70
63
  import { PlanManager } from "./plan-manager.js";
71
64
  import { buildPlanModePrompt, planModeDenial, planModeNoticeText, PLAN_MODE_BLOCKED_TOOL_NAMES } from "./plan-mode.js";
72
- import { DELEGATION_SYSTEM_PROMPT, delegationDenial, delegateNoticeText } from "./delegate-mode.js";
65
+ import { DELEGATION_SYSTEM_PROMPT, delegateNoticeText } from "./delegate-mode.js";
73
66
  import { goalReviewDenial, shouldDeferPromptForReview } from "./goal-review-gate.js";
74
67
  import { readPlanModeFromSession, readPlanFromSession } from "./permission-preset.js";
75
68
  import { readDelegateModeFromSession } from "./permission-preset.js";
76
- import { applyHeadTail, makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE, } from "./terminals.js";
77
- import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, BROWSER_PAGE_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PLAN_UPDATE_TOOL_NAME, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
69
+ import { makePersistentTerminalTools, makeTerminalBashTool, stripAnsi, TERMINAL_TOOLS_GUIDANCE } from "./terminals.js";
70
+ import { applyAgentToolsGating, ASK_USER_QUESTION_TOOL_NAME, effectiveDisabledAgentTools, filterToolsByPreset, isAgentToolEnabled, isTerminalGuidanceOn, LAZY_CORE_TOOL_NAMES, lazyLoadingDisabledTools, LOAD_TOOLS_TOOL_NAME, localizedName, PI_AGENT_PRESETS, PI_PERMISSION_OPTIONS, PRESENT_FILES_TOOL_NAME, presetAllowsPluginTools, presetHasQuestionnaire, presetShowsSkillCatalog, } from "./tool-manager.js";
78
71
  import { makeLoadToolsTool } from "./load-tools-tool.js";
79
72
  import { formatCompactSignature } from "./tool-signature.js";
80
73
  import { WebUIContext } from "./webui-context.js";
81
74
  import { DEFAULT_COMPACTION_RESERVE_TOKENS, effectiveSoftCap, softCapToReserve } from "./soft-cap.js";
82
- import { pruneContextHierarchically } from "./context-budget.js";
83
- import { decodeText } from "./text-sniff.js";
84
75
  import { makeEditSoftTool } from "./edit-soft-tool.js";
85
76
  // 覆盖 SDK 内置 read:路径是目录时列出目录条目(行为开关 readDirEnabled,默认开)。
86
77
  // 覆盖定义与「与扩展同名工具共存」的注入辅助分在两个文件(后者的依据见 tool-overrides.ts)。
@@ -98,9 +89,9 @@ import { normalizeToolInfo } from "./tool-info.js";
98
89
  import { applyToolPromptOverrides, effectiveToolPrompt, toolPromptOverrideOf, } from "./tool-prompt-overrides.js";
99
90
  import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
100
91
  import { makeDelegateTaskTool } from "./delegate-task.js";
101
- import { makeConversationReadTool, parseTranscriptLines, toTranscriptInput, } from "./conversation-read-tool.js";
92
+ import { makeConversationReadTool, toTranscriptInput, } from "./conversation-read-tool.js";
102
93
  import { extractTouches, formatTouchesCompact, intersectTouches } from "./conversation-touches.js";
103
- import { ClaimStore, matchClaims, mergeTouchSidecar, readTouchSidecar, removeTouchSidecar } from "./claim-store.js";
94
+ import { ClaimStore, matchClaims, mergeTouchSidecar, removeTouchSidecar } from "./claim-store.js";
104
95
  import { makeClaimFilesTool } from "./claim-files-tool.js";
105
96
  import { makeSkillTool } from "./skill-tool.js";
106
97
  import { getCompactedMessages } from "./compacted-history.js";
@@ -109,7 +100,7 @@ import { makePatchTool } from "./patch-tool.js";
109
100
  import { makeLspTool } from "./lsp-tool.js";
110
101
  import { makeMcpManageTool } from "./mcp-agent-tool.js";
111
102
  import { makeSandboxTool } from "./sandbox-tool.js";
112
- import { makeWorktreeTool, WORKTREE_TOOL_NAME } from "./worktree-tool.js";
103
+ import { makeWorktreeTool } from "./worktree-tool.js";
113
104
  import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktree-service.js";
114
105
  import { sameSessionFile } from "./scheduler-tasks.js";
115
106
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
@@ -117,11 +108,10 @@ import { scanAtMentions } from "./universal/universal-attachments.js";
117
108
  import { formatQuotedPrompt, formatStreamingPrompt, readTextQuote, splitQuotedPrompt } from "./text-quote.js";
118
109
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
119
110
  import { generateScmCommitMessage } from "./scm-commitmsg.js";
120
- import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, splitExtensionWrap, } from "./prompt-composer.js";
111
+ import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
121
112
  import { listAllMcpServers, checkMcpServer, installMcpServer, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
122
113
  import { fetchRemoteMcpMarket, fetchRemoteSkillMarket, fetchRemoteSkillContent } from "./market-service.js";
123
- import { launchOrigin, toServiceInfo } from "./launch-origin.js";
124
- import { findEntryByUiId, serializeMessage, serializeStreamingMessage, stripTransientRetryErrors, } from "./serialize.js";
114
+ import { serializeMessage, serializeStreamingMessage, stripTransientRetryErrors, } from "./serialize.js";
125
115
  import { loadCommands, saveCommandsFile, TerminalManager } from "./terminals.js";
126
116
  const SNAPSHOT_INTERVAL_MS = 60;
127
117
  /** 服务进程所在机器的用户主目录(wire 格式):进程内不变,模块加载时求值一次,
@@ -212,9 +202,9 @@ export { normalizeSolPlanToPlanSteps, makePlanUpdateTool };
212
202
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
213
203
  import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
214
204
  export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
215
- import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, getMaxOpenConversations, getMaxSubagents, SUBAGENT_PROMPT_SNAPSHOT_CAP, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
205
+ import { RUN_TASK_CAP, RUN_ARGS_CAP, getMaxOpenConversations, getMaxSubagents, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
216
206
  export { workspacePath };
217
- import { MAX_TRANSCRIPT_SCAN_BYTES, sessionMatchesMetadata, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, } from "./session-search.js";
207
+ import { sessionMatchesMetadata, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, } from "./session-search.js";
218
208
  export { piSessionsRoot, isInsideSessionsDir };
219
209
  import { discoverRecentProjectsFromDisk, filterForkedParentSessions, findMostRecentSessionFileFast, parseSessionInfoFast, } from "./session-parser.js";
220
210
  import { pickAdoptableOrphan, sameCwd } from "./orphan-manager.js";
@@ -857,9 +847,9 @@ export class ClientSession {
857
847
  * 集合跟它一起走;会话销毁后 WeakMap 自动回收,不需要清理钩子。
858
848
  */
859
849
  lazyLoadedBySession = new WeakMap();
860
- /** 延迟加载总开关(设置项,默认开;DSH 无 pi 工具注册面,走自己的服务)。 */
850
+ /** 延迟加载总开关(设置项,默认关;DSH 无 pi 工具注册面,走自己的服务)。 */
861
851
  lazyLoadingOn() {
862
- return this.settingsSvc?.current.toolLazyLoading !== false;
852
+ return this.settingsSvc?.current.toolLazyLoading === true;
863
853
  }
864
854
  /** 会话是否已有转录内容 —— 区分「刚建的新会话」(种子为空)与「从转录恢复的会话」
865
855
  * (种子 = 当时活跃的非核心工具,保证上次加载过什么就还是什么)。 */
@@ -1060,6 +1050,16 @@ export class ClientSession {
1060
1050
  for (const n of PLAN_MODE_BLOCKED_TOOL_NAMES)
1061
1051
  disabled.add(n);
1062
1052
  const set = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
1053
+ // 「已加载集合」里有名字 ≠ 活跃集里有它:JIT 自动激活(见 autoActivateToolIfLoadable)
1054
+ // 与任何只标记不重放门控的路径都会造出这种半吊子状态。按活跃集判定,
1055
+ // 否则回一句「已经加载过了」就把模型堵死在死路上(issue #652)。
1056
+ let activeNow = new Set();
1057
+ try {
1058
+ activeNow = new Set(session.getActiveToolNames());
1059
+ }
1060
+ catch {
1061
+ /* session 未就绪:当作什么都不活跃,走正常加载路径 */
1062
+ }
1063
1063
  let changed = false;
1064
1064
  for (const name of names) {
1065
1065
  if (!known.has(name)) {
@@ -1076,7 +1076,7 @@ export class ClientSession {
1076
1076
  });
1077
1077
  continue;
1078
1078
  }
1079
- if (set.has(name)) {
1079
+ if (set.has(name) && activeNow.has(name)) {
1080
1080
  rejected.push({ name, reason: pick(lang, "已经加载过了", "already loaded", "loadtools.already") });
1081
1081
  continue;
1082
1082
  }
@@ -1115,6 +1115,13 @@ export class ClientSession {
1115
1115
  /**
1116
1116
  * JIT Auto-activation: if an allowed catalog tool is executed without prior load_tools,
1117
1117
  * automatically mark it as loaded so subsequent turns track it as fully active.
1118
+ *
1119
+ * 触发点包含「模型直接调了目录里尚未加载的工具」:SDK 在解析工具之前就派发了
1120
+ * `tool_execution_start`(见 pi-agent-core 的 executeToolCalls),随后因该工具不在
1121
+ * 活跃集而回一条 `Tool <name> not found`。此时只把名字塞进已加载集合是不够的
1122
+ * ——活跃集不会自己变,模型下一轮照样调不动,而 `load_tools` 又回「已经加载过了」,
1123
+ * 于是整条路被堵死(issue #652:模型要靠加载别的工具顺带触发门控才自愈)。
1124
+ * 因此这里必须立刻重放门控,让该工具从下一轮起真的活跃。
1118
1125
  */
1119
1126
  autoActivateToolIfLoadable(session, conv, name) {
1120
1127
  if (!this.lazyLoadingOn() ||
@@ -1127,9 +1134,13 @@ export class ClientSession {
1127
1134
  if (loaded.has(name))
1128
1135
  return;
1129
1136
  const allowed = new Set(this.allowedToolNames(session, conv));
1130
- if (allowed.has(name)) {
1131
- loaded.add(name);
1132
- }
1137
+ if (!allowed.has(name))
1138
+ return;
1139
+ loaded.add(name);
1140
+ this.applyToolGating(session, conv.agentPreset);
1141
+ this.sessionStatsCache = null;
1142
+ this.cachedBaseTokens = null;
1143
+ this.flushSnapshot();
1133
1144
  }
1134
1145
  /** 当前活动会话的工具/资源快照 → composer 输入。cwd 取活动对话的。 */
1135
1146
  composeInputs(src) {
@@ -10773,12 +10784,12 @@ export class ClientSession {
10773
10784
  return;
10774
10785
  }
10775
10786
  if (owner) {
10776
- if (AgentService.isPseudoClientId(owner.clientId)) {
10787
+ if (owner.clientId.startsWith("scheduler:")) {
10777
10788
  this.emit({
10778
10789
  type: "notice",
10779
10790
  level: "warning",
10780
- text: `该对话正在由后台任务使用(「${owner.title}」),为避免并发写入,已停止打开。`,
10781
- textEn: `This conversation is currently used by a background task ("${owner.title}"). Opening was blocked to prevent concurrent writes.`,
10791
+ text: `该对话正在由后台定时任务使用(「${owner.title}」),为避免并发写入,已停止打开。可在后台任务面板查看进度。`,
10792
+ textEn: `This conversation is currently used by a background scheduled task ("${owner.title}"). Opening was blocked to prevent concurrent writes.`,
10782
10793
  });
10783
10794
  this.flushSnapshot();
10784
10795
  return;
@@ -726,7 +726,29 @@ export function isUserMessageEntry(entry) {
726
726
  return (e.type === "message" && e.message?.role === "user") || e.type === "user" || e.role === "user";
727
727
  }
728
728
  /**
729
- * 从给定的 entry 节点开始,向上追溯属于该轮提问的前置附件 aside 节点(customType === "file" 等),
729
+ * 判断一个 entry 是否为上一轮对话结束时的有效业务节点
730
+ * (例如助手回复、工具返回、bash 执行、分支或压缩摘要,或者更早一轮的用户提问)。
731
+ */
732
+ export function isConversationTurnEntry(entry) {
733
+ if (!entry || typeof entry !== "object")
734
+ return false;
735
+ const e = entry;
736
+ if (e.type === "compaction" || e.type === "branch_summary")
737
+ return true;
738
+ if (e.type === "message" && e.message) {
739
+ const role = e.message.role;
740
+ return (role === "assistant" ||
741
+ role === "toolResult" ||
742
+ role === "bashExecution" ||
743
+ role === "branchSummary" ||
744
+ role === "compactionSummary" ||
745
+ role === "user");
746
+ }
747
+ return false;
748
+ }
749
+ /**
750
+ * 从给定的 entry 节点开始,向上追溯跳过属于该轮提问的前置附件 aside 节点(customType === "file" 等)、
751
+ * SDK 注入的系统截面(role === "system")以及配置变更节点,
730
752
  * 返回该轮提问之前的基准 entry id(作为 fork/分支截断点)。
731
753
  * 如果追溯到会话根(即该提问是会话第一轮提问),返回 null。
732
754
  */
@@ -734,7 +756,7 @@ export function findTurnBaseEntryId(sm, entryId) {
734
756
  const target = sm.getEntry(entryId);
735
757
  if (!target)
736
758
  return null;
737
- // 只有针对用户消息,才需要向上跳过属于该提问的前置附件 aside 卡片
759
+ // 只有针对用户消息,才需要向上跳过属于该提问的前置附件 aside 卡片和系统截面
738
760
  if (!isUserMessageEntry(target)) {
739
761
  const parentId = target.parentId;
740
762
  return parentId ?? null;
@@ -750,12 +772,10 @@ export function findTurnBaseEntryId(sm, entryId) {
750
772
  const parentEntry = sm.getEntry(parentId);
751
773
  if (!parentEntry)
752
774
  return null;
753
- if (isPromptAsideEntry(parentEntry)) {
754
- currentId = parentId;
755
- }
756
- else {
775
+ if (isConversationTurnEntry(parentEntry)) {
757
776
  return parentId;
758
777
  }
778
+ currentId = parentId;
759
779
  }
760
780
  return null;
761
781
  }
@@ -250,11 +250,12 @@ export function normalizeUiLayout(v) {
250
250
  export function normalizeSkillList(v) {
251
251
  return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
252
252
  }
253
- /** 工具延迟加载的**出厂默认**(默认开;`PI_WEB_TOOL_LAZY_LOADING=0/false/off` 部署级关掉,
254
- * 给「不想让模型多一步 load_tools」的实例一个开关;用户在设置面板的选择优先于此)。 */
253
+ /** 工具延迟加载的**出厂默认**(默认关:模型忘记加载会先吃一次 `Tool <name> not found`,
254
+ * 开箱即用优先——见 #652;`PI_WEB_TOOL_LAZY_LOADING=1/true/on/yes` 部署级打开,给
255
+ * 「想省上下文、愿意让模型多一步 load_tools」的实例一个开关;用户在设置面板的选择优先于此)。 */
255
256
  export const DEFAULT_TOOL_LAZY_LOADING = (() => {
256
257
  const v = (process.env.PI_WEB_TOOL_LAZY_LOADING ?? "").trim().toLowerCase();
257
- return !(v === "0" || v === "false" || v === "off" || v === "no");
258
+ return v === "1" || v === "true" || v === "on" || v === "yes";
258
259
  })();
259
260
  export const DEFAULT_CODEMODE_MODE = "on";
260
261
  export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
@@ -594,6 +594,8 @@ export function handleSettingsMessage(msg, cs) {
594
594
  toolsWrap: msg.toolsWrap,
595
595
  toolImagesEnabled: msg.toolImagesEnabled,
596
596
  keepRecentMessages: msg.keepRecentMessages,
597
+ // 向上分页加载:之前漏在白名单外,设置页的开关一直被静默丢弃(补回归见 message-window-test)。
598
+ reversePagination: msg.reversePagination,
597
599
  showForkedParentSessions: msg.showForkedParentSessions,
598
600
  retainFinishedConversations: msg.retainFinishedConversations,
599
601
  openRecentSessionOnProjectSwitch: msg.openRecentSessionOnProjectSwitch,
@@ -273,6 +273,7 @@ export function handlePluginMessage(msg, ctx) {
273
273
  const requestId = String(msg.requestId ?? "");
274
274
  void syncPluginCatalog(String(msg.source ?? ""), { install: msg.install === true, replace: msg.replace === true }, {
275
275
  customCatalogPath: pluginMgr.customCatalogPath,
276
+ communityCatalogPath: pluginMgr.communityCatalogPath,
276
277
  pluginsDir: join(dataDir, "plugins"),
277
278
  installer: pluginInstaller,
278
279
  afterWrite: () => (msg.install === true ? reloadPluginsAndPush(syncLang) : pluginMgr.pushCatalog()),
@@ -3547,8 +3547,8 @@ export class DshClientSession {
3547
3547
  // DSH 引擎无 customTool 注册面(工具来自 shipped preset),read 目录覆盖面不存在。
3548
3548
  readDirEnabled: true,
3549
3549
  bgAutoCleanupMin: Number(this.settings.bgAutoCleanupMin ?? 0),
3550
- // DSH 无 pi 工具注册面,不适用延迟加载;保协议完整。
3551
- toolLazyLoading: true,
3550
+ // DSH 无 pi 工具注册面,不适用延迟加载;保协议完整(该字段恒为 false,设置页不显示这一行)。
3551
+ toolLazyLoading: false,
3552
3552
  codemodeMode: "on",
3553
3553
  codemodeInlineBudget: 3000,
3554
3554
  editSoftEnabled: this.settings.editSoftEnabled,
@@ -11,7 +11,7 @@ import { BaseAgentDriver } from "../universal/driver-base.js";
11
11
  import { openDurableStorage } from "./durable-storage.js";
12
12
  import { setupDurableRegistry } from "./durable-tools.js";
13
13
  import { listGlobalAvailableModels, setupDurableModels, resolveDurableModelChoice, } from "./durable-models.js";
14
- import { loadDurableModule, loadDurablePeerModule, probeDurableInstallation } from "./durable-loader.js";
14
+ import { loadDurableModule, loadDurablePeerModule } from "./durable-loader.js";
15
15
  export class DurableAgentDriver extends BaseAgentDriver {
16
16
  id = "durable";
17
17
  name = "Pi Durable Agent";
@@ -10,7 +10,10 @@ import { loadDurableModule } from "./durable-loader.js";
10
10
  /**
11
11
  * 为指定工作区配置 Durable Registry 和工具链。
12
12
  */
13
- export async function setupDurableRegistry(cwd, options) {
13
+ export async function setupDurableRegistry(cwd,
14
+ // 预留位(尚未消费):`allowDangerous` / `onToolOutput` 现在没有任何实现,
15
+ // 保留参数形状,后续接线时不必改调用方。
16
+ _options) {
14
17
  const durableModule = await loadDurableModule().catch(() => null);
15
18
  if (!durableModule || typeof durableModule.createRegistry !== "function") {
16
19
  throw new Error("Pi Durable 依赖未安装。请运行 npm i -g @earendil-works/pi-durable 启用该引擎。");
@@ -12,7 +12,7 @@ import { pick } from "./i18n.js";
12
12
  import { previewKind, looksLikeText, decodeText, hexDump, countLines } from "./text-sniff.js";
13
13
  import { extractOfficeText, isOfficeFile, OFFICE_MAX_FILE_BYTES } from "./office-parse.js";
14
14
  import { gitDirOf, isNotRepoError, scmStatus, scmHistory, scmFileDiff, scmCommitDetail } from "./scm.js";
15
- import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, shellQuotePosix, } from "./remote-ssh-service.js";
15
+ import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, } from "./remote-ssh-service.js";
16
16
  export const IS_WIN32 = process.platform === "win32";
17
17
  /** 机器根虚拟路径:工作区「上一级」到达此处,列出所有盘符(Windows)/ "/"(posix)。
18
18
  * 这是 wire 字面量,前端 web/src/components/{RightPanel,FooterBar}.tsx 里同值使用。 */
@@ -381,6 +381,16 @@ export class FilesService {
381
381
  }
382
382
  // ---- 工作区相对视图(原有行为) ----
383
383
  const target = raw ? resolve(root, raw) : root;
384
+ // 若工作区根目录自身尚不存在,自动自愈创建,避免首帧报错
385
+ if (raw === "") {
386
+ try {
387
+ const fsp = await import("node:fs/promises");
388
+ await fsp.mkdir(target, { recursive: true });
389
+ }
390
+ catch {
391
+ /* ignore if exists */
392
+ }
393
+ }
384
394
  const rawRel = relative(root, target);
385
395
  if (rawRel.startsWith("..") || rawRel.includes(`${sep}..`)) {
386
396
  this.host.emit({
@@ -1177,8 +1187,17 @@ export class FilesService {
1177
1187
  /** destDir(wire,空串 = 工作区根)→ 原生绝对目录;不存在/非目录 → null(调用方报错)。 */
1178
1188
  async resolveOpDir(dir) {
1179
1189
  const fsp = await import("node:fs/promises");
1180
- if (!dir.trim())
1181
- return { abs: resolve(this.host.getCwd()), wire: "" };
1190
+ if (!dir.trim()) {
1191
+ const rootAbs = resolve(this.host.getCwd());
1192
+ // 工作区根目录在首次运行可能尚未落地,自愈创建以确保后续操作成功
1193
+ try {
1194
+ await fsp.mkdir(rootAbs, { recursive: true });
1195
+ }
1196
+ catch {
1197
+ /* ignore if exists */
1198
+ }
1199
+ return { abs: rootAbs, wire: "" };
1200
+ }
1182
1201
  const t = this.resolveOpTarget(dir);
1183
1202
  if (!t)
1184
1203
  return null;
@@ -1214,7 +1233,7 @@ export class FilesService {
1214
1233
  return;
1215
1234
  }
1216
1235
  if (kind === "dir")
1217
- await fsp.mkdir(abs);
1236
+ await fsp.mkdir(abs, { recursive: true });
1218
1237
  else
1219
1238
  await fsp.writeFile(abs, "");
1220
1239
  this.host.emit({
@@ -745,6 +745,7 @@ export class GoalService {
745
745
  let refinedGoal = "";
746
746
  let parsedSteps = [];
747
747
  let goalEphemeralDir;
748
+ let srvSession;
748
749
  try {
749
750
  const wmSpec = opts?.wizardModel ? parseModelSpec(opts.wizardModel) : null; // "provider/id" 解析(唯一事实源)
750
751
  const services = await createAgentSessionServices({
@@ -907,6 +908,7 @@ export class GoalService {
907
908
  tools: ["goal_ask", "read", "ls", "find", "grep"],
908
909
  ...(model ? { model } : {}),
909
910
  });
911
+ srvSession = srv.session;
910
912
  const wizard = srv.session;
911
913
  this.wizardSession = wizard;
912
914
  await wizard.bindExtensions({ mode: "rpc", uiContext: this.host.webUi });
@@ -977,7 +979,6 @@ export class GoalService {
977
979
  const parsed = parseWizardOutput(rawAssistantText);
978
980
  refinedGoal = parsed.goal;
979
981
  parsedSteps = parsed.steps;
980
- await srv.session.dispose();
981
982
  }
982
983
  catch (err) {
983
984
  this.host.emit({
@@ -998,6 +999,13 @@ export class GoalService {
998
999
  wgoal.wizard.status = "";
999
1000
  wgoal.wizard.statusEn = "";
1000
1001
  this.wizardSession = null;
1002
+ this.wizardAbort = null;
1003
+ if (srvSession) {
1004
+ try {
1005
+ await srvSession.dispose();
1006
+ }
1007
+ catch { }
1008
+ }
1001
1009
  if (goalEphemeralDir) {
1002
1010
  try {
1003
1011
  rmSync(goalEphemeralDir, { recursive: true, force: true });
@@ -1018,7 +1026,6 @@ export class GoalService {
1018
1026
  textEn: `Goal survey cancelled${ac.signal.reason ? `: ${String(ac.signal.reason?.message ?? ac.signal.reason)}` : ""}` +
1019
1027
  `. The initial goal draft is preserved in the conversation "${wizardConversationTitle}" — copy it and start over.`,
1020
1028
  });
1021
- this.wizardAbort = null;
1022
1029
  return;
1023
1030
  }
1024
1031
  if (!refinedGoal.trim()) {
@@ -1066,7 +1073,6 @@ export class GoalService {
1066
1073
  autoStart: false,
1067
1074
  });
1068
1075
  this.wizardCancelled = false;
1069
- this.wizardAbort = null;
1070
1076
  this.host.emit({
1071
1077
  type: "notice",
1072
1078
  level: "info",
@@ -1507,6 +1513,9 @@ export class GoalService {
1507
1513
  }
1508
1514
  /** 会话过户时清理目标审查态并唤醒等待者(issue #457)。 */
1509
1515
  notifyTakeover(conv) {
1516
+ conv.goalGeneration = (conv.goalGeneration ?? 0) + 1;
1517
+ conv.goal.reviewing = false;
1518
+ this.resetLoopCounters(conv);
1510
1519
  this.delegatedPending.delete(conv.id);
1511
1520
  conv.awaitingVerdict = undefined;
1512
1521
  void this.flushDeferredPrompts(conv);
@@ -19,7 +19,7 @@
19
19
  // MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
20
20
  import "./patch-remote-catalog.js";
21
21
  import "./patch-turn-end-boundary.js";
22
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
22
+ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
23
23
  import { stat } from "node:fs/promises";
24
24
  import { createServer, request as proxyRequest } from "node:http";
25
25
  import { createConnection } from "node:net";
@@ -42,14 +42,15 @@ import { isAudioFile, previewKind } from "./text-sniff.js";
42
42
  import { startControlServer } from "./control-socket.js";
43
43
  import { scheduleUploadCleanup } from "./uploads.js";
44
44
  import { ensureWindowsBash, windowsBashDir } from "./ensure-bash.js";
45
- import { listThemes, resolveThemeFile } from "./themes.js";
45
+ import { listThemes, readThemeCss, resolveThemeFile } from "./themes.js";
46
46
  import { isManaged, managedRefusal } from "./managed.js";
47
47
  import { launchOrigin, toServiceInfo } from "./launch-origin.js";
48
48
  import { parseTabs, tabsRefusal } from "./tabs.js";
49
49
  import { recordUnknownWsType } from "./ws-unknown-types.js";
50
+ import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
50
51
  import { validateClientId } from "./ws-client-id.js";
51
52
  import { PendingCommandQueue } from "./ws-pending-queue.js";
52
- import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, unloadServerStrings, } from "./locales.js";
53
+ import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
53
54
  import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
54
55
  import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
55
56
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
@@ -624,14 +625,14 @@ app.get("/api/themes", (_req, res) => {
624
625
  // 语言包:核心只随包发布中英,其余按需下载到 <dataDir>/locales/<code>.json。
625
626
  // 手工放进去的同名 JSON 也会被识别(离线安装)。PI_WEB_TOKEN 鉴权自动覆盖。
626
627
  /**
627
- * PI_WEB_LOCALE — the language a first visit falls back to.
628
+ * PI_WEB_LOCALE / system locale — the language a first visit falls back to.
628
629
  *
629
630
  * It is a fallback, not an override: an explicit choice, and then the
630
631
  * browser's own languages, come first (web/src/pick-locale.ts). It rides on
631
632
  * /api/locales because the client already asks for that at boot, so naming a
632
633
  * default costs no extra request.
633
634
  */
634
- const DEFAULT_LOCALE = (process.env.PI_WEB_LOCALE ?? "").trim().toLowerCase() || null;
635
+ const DEFAULT_LOCALE = resolveSystemDefaultLocale();
635
636
  app.get("/api/locales", (_req, res) => {
636
637
  res.json({ packs: listPacks(DATA_DIR), defaultLocale: DEFAULT_LOCALE });
637
638
  });
@@ -678,7 +679,23 @@ app.delete("/api/locales/:code", (req, res) => {
678
679
  unloadServerStrings(code);
679
680
  res.json({ ok: true });
680
681
  });
682
+ // Serve theme base stylesheets directly if requested (e.g. /themes/bases/flow-base.css).
683
+ app.get("/themes/bases/:name.css", (req, res) => {
684
+ if (!/^[A-Za-z0-9_-]+$/.test(req.params.name)) {
685
+ res.status(404).end("base not found");
686
+ return;
687
+ }
688
+ const baseFile = join(BUILTIN_THEMES_DIR, "bases", `${req.params.name}.css`);
689
+ if (!existsSync(baseFile) || !statSync(baseFile).isFile()) {
690
+ res.status(404).end("base not found");
691
+ return;
692
+ }
693
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
694
+ res.setHeader("Cache-Control", "no-cache");
695
+ res.sendFile(baseFile);
696
+ });
681
697
  // Serve a theme's full CSS file so the frontend can swap the whole stylesheet.
698
+ // Supports server-side @import inlining for shared theme bases (e.g. bases/flow-base.css).
682
699
  // Registered before the SPA catch-all below (otherwise it'd return index.html).
683
700
  app.get("/themes/:id.css", (req, res) => {
684
701
  const file = resolveThemeFile(BUILTIN_THEMES_DIR, USER_THEMES_DIR, req.params.id);
@@ -688,10 +705,8 @@ app.get("/themes/:id.css", (req, res) => {
688
705
  }
689
706
  res.setHeader("Content-Type", "text/css; charset=utf-8");
690
707
  res.setHeader("Cache-Control", "no-cache");
691
- // dotfiles: allow — issue #223:Express 5 的 send 默认 dotfiles=ignore,主题文件位于
692
- // 隐藏目录下(如 ~/.pi-web/themes、npm 全局目录 ~/.local/…)时会被判 404。路径已由
693
- // resolveThemeFile 校验(id 白名单 + 仅已知目录 + isFile),放行安全。
694
- res.sendFile(file, { dotfiles: "allow" });
708
+ const css = readThemeCss(file);
709
+ res.send(css);
695
710
  });
696
711
  // Plugin client bundles: <dataDir>/plugins/<id>/client/* served at
697
712
  // /plugins/<id>/client/* so the frontend can import() plugin views. Only the
@@ -1896,7 +1911,9 @@ wss.on("connection", (ws) => {
1896
1911
  /* already closing */
1897
1912
  }
1898
1913
  });
1899
- const send = (msg) => {
1914
+ /** 引擎→浏览器的**唯一发送漏斗**:历史消息窗口化(按需加载)在它前面一层,
1915
+ * 见下方 `send`。四个引擎(pi / DSH / claude / durable)都走这条漏斗,引擎侧零改动。 */
1916
+ const sendRaw = (msg) => {
1900
1917
  if (closed || ws.readyState !== WebSocket.OPEN)
1901
1918
  return;
1902
1919
  // 发送背压(issue #11):socket 消费不过来时(前端慢/网络差),堆里会堆积
@@ -1931,6 +1948,11 @@ wss.on("connection", (ws) => {
1931
1948
  lastSnapshotBytes = wire.length * 2;
1932
1949
  ws.send(wire);
1933
1950
  };
1951
+ /** 本连接的历史窗口状态(每标签页一份,见 server/message-window.ts)。
1952
+ * `send` 必须包在 `sendRaw` **外面**:窗口先裁消息,再算背压字节数——否则
1953
+ * 背压阈值还在按未裁剪的 10MB 量级估。 */
1954
+ const windowTap = new MessageWindowTap(sendRaw, readMessageWindowConfig(process.env));
1955
+ const send = (msg) => windowTap.accept(msg);
1934
1956
  // Plugins broadcast to every open socket; unregister on close below.
1935
1957
  // Plugins broadcast to every open socket; unregister on close below. The
1936
1958
  // cid getter lets plugins target THIS socket via host.sendTo(clientId).
@@ -2174,6 +2196,12 @@ wss.on("connection", (ws) => {
2174
2196
  pending.push(msg);
2175
2197
  return;
2176
2198
  }
2199
+ // 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
2200
+ // 放在引擎分发之前:它不是引擎能力,窗口化关闭时静默无回执(前端保持现状)。
2201
+ if (msg.type === "load_earlier_messages") {
2202
+ windowTap.loadEarlier(msg.count, msg.all);
2203
+ return;
2204
+ }
2177
2205
  // Managed instances do not install software on themselves, and tabs this
2178
2206
  // instance does not offer stay closed. Both refusals live here, on the
2179
2207
  // server, because hiding them in the client would still leave the message
@@ -2660,6 +2688,7 @@ const autoInstall = /^(1|true|yes)$/i.test(process.env.PI_WEB_PLUGIN_CATALOG_INS
2660
2688
  if (!bootCatalogDisabled) {
2661
2689
  void syncPluginCatalog(BOOT_CATALOG_URL, { install: autoInstall }, {
2662
2690
  customCatalogPath: pluginMgr.customCatalogPath,
2691
+ communityCatalogPath: pluginMgr.communityCatalogPath,
2663
2692
  pluginsDir: join(DATA_DIR, "plugins"),
2664
2693
  installer: pluginInstaller,
2665
2694
  // 默认仅同步市场列表;重载插件会重复触发其激活广播。
@@ -212,3 +212,36 @@ export async function installPack(dataDir, code, opts = {}) {
212
212
  }
213
213
  throw new Error(lastError || `download failed for ${code}`);
214
214
  }
215
+ /**
216
+ * Resolve the system default fallback locale.
217
+ *
218
+ * Checks PI_WEB_LOCALE first, then inspects standard POSIX environment variables
219
+ * (LC_ALL, LC_MESSAGES, LANG, LANGUAGE). Normalizes tags (e.g. "en_US.UTF-8" -> "en").
220
+ */
221
+ export function resolveSystemDefaultLocale(env = process.env) {
222
+ const explicit = (env.PI_WEB_LOCALE ?? "").trim();
223
+ if (explicit)
224
+ return explicit.toLowerCase();
225
+ const candidates = [env.LC_ALL, env.LC_MESSAGES, env.LANG, env.LANGUAGE];
226
+ for (const raw of candidates) {
227
+ const val = (raw ?? "").trim();
228
+ if (!val || val === "C" || val === "POSIX")
229
+ continue;
230
+ // e.g. "en_US.UTF-8", "zh_CN.gbk", "zh_TW.UTF-8", "en-US", "de"
231
+ const cleaned = val.split(".")[0].split("@")[0].replace(/_/g, "-");
232
+ const lower = cleaned.toLowerCase();
233
+ if (lower === "zh-tw" || lower === "zh-hant" || lower === "zh-mo") {
234
+ return "zh-TW";
235
+ }
236
+ if (lower === "zh-hk") {
237
+ return "zh-HK";
238
+ }
239
+ if (lower === "zh" || lower.startsWith("zh-")) {
240
+ return "zh";
241
+ }
242
+ const primary = lower.split("-")[0];
243
+ if (primary)
244
+ return primary;
245
+ }
246
+ return null;
247
+ }