pi-web-ui 0.101.0 → 0.103.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 (39) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/bin/pi-web-ui.mjs +13 -9
  5. package/dist/server/agent-service-daemon.js +19 -12
  6. package/dist/server/agent-service.js +255 -58
  7. package/dist/server/ask-user-question-tool.js +12 -2
  8. package/dist/server/bash-tool.js +19 -1
  9. package/dist/server/client-state.js +24 -1
  10. package/dist/server/dispatch-domain-handlers.js +69 -3
  11. package/dist/server/dsh/dsh-agent-service.js +21 -4
  12. package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
  13. package/dist/server/edit-soft-tool.js +15 -3
  14. package/dist/server/files-service.js +636 -14
  15. package/dist/server/index.js +7 -1
  16. package/dist/server/plugin-installer.js +6 -1
  17. package/dist/server/plugins.js +1 -0
  18. package/dist/server/preset-fields.js +28 -0
  19. package/dist/server/preset-share.js +8 -0
  20. package/dist/server/protocol-version.js +1 -1
  21. package/dist/server/read-tool.js +11 -4
  22. package/dist/server/remote-ssh-service.js +1314 -0
  23. package/dist/server/scm.js +16 -0
  24. package/dist/server/settings-service.js +15 -0
  25. package/dist/server/terminals.js +65 -20
  26. package/dist/server/tool-guards.js +18 -6
  27. package/dist/server/virtual-tui.js +258 -0
  28. package/dist/server/webui-context.js +109 -4
  29. package/package.json +7 -1
  30. package/themes/zhupi-dark.css +3 -14
  31. package/themes/zhupi.css +2 -16
  32. package/web/dist/assets/TerminalPanel-PIx1pMZ0.js +3 -0
  33. package/web/dist/assets/index-CYQdZEbx.css +1 -0
  34. package/web/dist/assets/index-CtaYhpZt.js +680 -0
  35. package/web/dist/index.html +4 -2
  36. package/web/dist/sw.js +1 -1
  37. package/web/dist/assets/TerminalPanel-DD7I5_aC.js +0 -3
  38. package/web/dist/assets/index-CpjA1YdT.css +0 -1
  39. package/web/dist/assets/index-nKn87VuM.js +0 -678
@@ -19,12 +19,12 @@ import { spawn } from "node:child_process";
19
19
  import { createHash, randomUUID } from "node:crypto";
20
20
  import { createRequire } from "node:module";
21
21
  import * as fsPromises from "node:fs/promises";
22
- import { appendFileSync, existsSync, readFileSync, rmSync, statSync, mkdirSync, watch, writeFileSync } from "node:fs";
22
+ import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, statSync, mkdirSync, watch, writeFileSync, } from "node:fs";
23
23
  import { homedir } from "node:os";
24
24
  import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { writeAtomicSync } from "./atomic-file.js";
27
- import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashToolDefinition, createCodemodeExtension, createEditToolDefinition, createLocalBashOperations, createToolSearchExtension, createWriteToolDefinition, getAgentDir, SessionManager, VERSION, estimateTokens, } from "@earendil-works/pi-coding-agent";
27
+ import { createAgentSessionFromServices, createAgentSessionRuntime, createAgentSessionServices, createBashToolDefinition, createCodemodeExtension, createEditToolDefinition, createFindToolDefinition, createGrepToolDefinition, createLocalBashOperations, createLsToolDefinition, createToolSearchExtension, createWriteToolDefinition, getAgentDir, SessionManager, VERSION, estimateTokens, } from "@earendil-works/pi-coding-agent";
28
28
  import { Type } from "typebox";
29
29
  import { BG_CLEANUP_FALLBACK_MIN, BgServerTracker } from "./bg-servers.js";
30
30
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, detectPiSdkSplit, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
@@ -46,6 +46,7 @@ import { MarkerService } from "./marker-service.js";
46
46
  import { SlashCommandsService, parseSlash } from "./slash-commands.js";
47
47
  import { ModelAdminService } from "./model-admin.js";
48
48
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
49
+ import { buildRemoteWorkspacePersona, createRemoteSdkOperations, formatCwdForPrompt, getGlobalRemoteSshService, isRemoteWorkspaceUri, RemoteSshService, resolveWorkspaceSessionDir, restoreWorkspaceUriFromSessionDir, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
49
50
  import { DEFAULT_TOOL_WATCHDOG_TIMEOUT_MS, effectiveToolWatchdogMs, isExtensionDisabled, isExtensionEnabled, normalizeDisabledPluginTools, normalizePathKey, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
50
51
  import { pick, resolveServerLang } from "./i18n.js";
51
52
  import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
@@ -454,10 +455,11 @@ export class ClientSession {
454
455
  const spawnerSession = spawner?.session ?? this.session;
455
456
  const baseCwd = spawner?.cwd ?? this.cwd;
456
457
  // 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
457
- const resolvedCwd = cwd ? resolve(baseCwd, cwd) : baseCwd;
458
+ const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
459
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
458
460
  const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
459
461
  const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
460
- const sessionManager = persist ? SessionManager.create(resolvedCwd) : SessionManager.inMemory(resolvedCwd);
462
+ const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
461
463
  if (!persist) {
462
464
  // 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
463
465
  // 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
@@ -469,11 +471,12 @@ export class ClientSession {
469
471
  catch { }
470
472
  }
471
473
  const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
472
- cwd: resolvedCwd,
474
+ cwd: sessionBaseDir,
473
475
  agentDir: this.agentDir,
474
476
  sessionManager,
475
477
  });
476
478
  const conv = this.makeConversation(runtime, conversationId, terminals);
479
+ conv.cwd = resolvedCwd;
477
480
  conv.isSubagent = !persist;
478
481
  // 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
479
482
  // 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
@@ -499,6 +502,7 @@ export class ClientSession {
499
502
  this.applyRetryOverrides();
500
503
  // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
501
504
  this.applyCompactionOverrides();
505
+ this.applyCodemodeOverrides();
502
506
  // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
503
507
  // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
504
508
  try {
@@ -1003,8 +1007,10 @@ export class ClientSession {
1003
1007
  this.noteSkillCatalogDigest(src.skills);
1004
1008
  const showSkills = presetShowsSkillCatalog(preset);
1005
1009
  const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
1010
+ const realCwd = restoreWorkspaceUriFromSessionDir(src.cwd);
1011
+ const isRemote = isRemoteWorkspaceUri(realCwd);
1006
1012
  return {
1007
- cwd: src.cwd,
1013
+ cwd: formatCwdForPrompt(realCwd),
1008
1014
  systemPromptFile: this.lastBaseSystemPrompt || undefined,
1009
1015
  builtinSoul: BUILTIN_SOUL,
1010
1016
  selectedTools: src.selectedTools,
@@ -1017,7 +1023,11 @@ export class ClientSession {
1017
1023
  piDocs: PI_DOC_PATHS.docs,
1018
1024
  piExamples: PI_DOC_PATHS.examples,
1019
1025
  appendFiles: this.lastSdkAppendFiles,
1020
- windowsPersona: process.platform === "win32" ? WINDOWS_PERSONA : "",
1026
+ windowsPersona: isRemote
1027
+ ? buildRemoteWorkspacePersona(realCwd)
1028
+ : process.platform === "win32"
1029
+ ? WINDOWS_PERSONA
1030
+ : "",
1021
1031
  terminalGuidance: isTerminalGuidanceOn(effectiveDisabledAgentTools(this.settingsSvc.current), preset)
1022
1032
  ? TERMINAL_TOOLS_GUIDANCE
1023
1033
  : "",
@@ -1564,12 +1574,14 @@ export class ClientSession {
1564
1574
  // (含重试次数覆盖)——依次重放:重试覆盖 → 软上限覆盖 → 终端门控。
1565
1575
  this.applyRetryOverrides();
1566
1576
  this.applyCompactionOverrides();
1577
+ this.applyCodemodeOverrides();
1567
1578
  // reload() 会把 custom 工具重新加回活跃集——重放当前会话归属预设门控。
1568
1579
  this.applyToolGating(this.session, this.conv?.agentPreset);
1569
1580
  await this.pushSlashCommands();
1570
1581
  },
1571
1582
  applyRetryOverrides: () => this.applyRetryOverrides(),
1572
1583
  applyCompactionOverrides: () => this.applyCompactionOverrides(),
1584
+ applyCodemodeOverrides: () => this.applyCodemodeOverrides(),
1573
1585
  applyToolGating: () => {
1574
1586
  for (const conv of this.convs.values()) {
1575
1587
  this.applyToolGating(conv.session, conv.agentPreset);
@@ -1754,6 +1766,10 @@ export class ClientSession {
1754
1766
  static async create(clientId, cwd, stateStore, opts) {
1755
1767
  const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
1756
1768
  const cs = new ClientSession(clientId, cwd, agentDir, stateStore);
1769
+ if (!getGlobalRemoteSshService()) {
1770
+ setGlobalRemoteSshService(new RemoteSshService(stateStore.dataDir));
1771
+ }
1772
+ const sessionBaseDir = resolveWorkspaceSessionDir(stateStore.dataDir, cwd);
1757
1773
  const conversationId = cs.nextConversationId();
1758
1774
  const terminals = cs.makeTerminalManager(conversationId, cwd);
1759
1775
  // Resume the most recent session for this project — the SDK default
@@ -1762,11 +1778,11 @@ export class ClientSession {
1762
1778
  // issue #145: opts.blank = 跳过恢复(最近那条在别处跑着),直接空白新对话。
1763
1779
  // issue #235:坏转录(重复压缩标记成环)修一次再试,否则整项目首屏
1764
1780
  // "Failed to initialize session"。
1765
- const opened = await cs.openManagerAndRuntime(() => (opts?.blank ? SessionManager.create(cwd) : SessionManager.continueRecent(cwd)), (m) => createAgentSessionRuntime(cs.makeRuntimeFactory(terminals, undefined, conversationId), {
1766
- cwd,
1781
+ const opened = await cs.openManagerAndRuntime(() => (opts?.blank ? SessionManager.create(sessionBaseDir) : SessionManager.continueRecent(sessionBaseDir)), (m) => createAgentSessionRuntime(cs.makeRuntimeFactory(terminals, undefined, conversationId), {
1782
+ cwd: sessionBaseDir,
1767
1783
  agentDir,
1768
1784
  sessionManager: m,
1769
- }), async () => (await SessionManager.list(cwd))[0]?.path);
1785
+ }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path);
1770
1786
  const runtime = opened.runtime;
1771
1787
  if (opened.repair) {
1772
1788
  for (const n of cs.transcriptRepairNotices(opened.repair))
@@ -1776,6 +1792,7 @@ export class ClientSession {
1776
1792
  // ModelRuntime that every later conversation reuses.
1777
1793
  cs.sharedModelRuntime = runtime.services.modelRuntime;
1778
1794
  const conv = cs.makeConversation(runtime, conversationId, terminals);
1795
+ conv.cwd = cwd;
1779
1796
  cs.convs.set(conv.id, conv);
1780
1797
  cs.activeId = conv.id;
1781
1798
  for (const d of runtime.diagnostics) {
@@ -1940,7 +1957,13 @@ export class ClientSession {
1940
1957
  if (this.delegateModeOf(ownerId) && !this.planModeOf(ownerId)) {
1941
1958
  out.push(DELEGATION_SYSTEM_PROMPT);
1942
1959
  }
1943
- if (process.platform === "win32") {
1960
+ const realCwd = restoreWorkspaceUriFromSessionDir(effectiveCwd);
1961
+ if (isRemoteWorkspaceUri(realCwd)) {
1962
+ // 远程 SSH 工作区:明确告知 AI 当前处于远程主机以及所有工具已透明桥接至远端,
1963
+ // 绝不注入本地 WINDOWS_PERSONA 以免误导模型以为在本地 Windows 环境。
1964
+ out.push(buildRemoteWorkspacePersona(realCwd));
1965
+ }
1966
+ else if (process.platform === "win32") {
1944
1967
  // Windows 专属 persona:bash 工具跑 Git Bash 且无默认超时、终端
1945
1968
  // 是交互式 TTY——注入约束避免 heredoc/交互/长驻命令挂死整个会话;
1946
1969
  // GBK 老中文文件让模型改用终端按正确编码读(iconv/chcp/Get-Content)。
@@ -2000,7 +2023,7 @@ export class ClientSession {
2000
2023
  // 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
2001
2024
  // 等都取自本次 run 的 systemPromptOptions,永远最新)。
2002
2025
  extensionFactories: [
2003
- createCodemodeExtension({ mode: "on" }),
2026
+ createCodemodeExtension(),
2004
2027
  createToolSearchExtension(),
2005
2028
  {
2006
2029
  name: "pi-webui-persona",
@@ -2062,8 +2085,10 @@ export class ClientSession {
2062
2085
  }
2063
2086
  const currentPreset = conv?.agentPreset ?? targetPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
2064
2087
  const opts = event.systemPromptOptions;
2088
+ const rawCwdForPrompt = typeof opts?.cwd === "string" ? opts.cwd : (conv?.cwd ?? effectiveCwd ?? this.cwd);
2089
+ const realCwdForPrompt = restoreWorkspaceUriFromSessionDir(rawCwdForPrompt);
2065
2090
  const rendered = this.renderMainCompose({
2066
- cwd: typeof opts?.cwd === "string" ? opts.cwd : (conv?.cwd ?? effectiveCwd ?? this.cwd),
2091
+ cwd: realCwdForPrompt,
2067
2092
  selectedTools: baseNames.length > 0 ? baseNames : (opts?.selectedTools ?? []),
2068
2093
  toolSnippets: activeSnippets,
2069
2094
  toolSignatures: activeSignatures,
@@ -2077,8 +2102,17 @@ export class ClientSession {
2077
2102
  })),
2078
2103
  preset: currentPreset,
2079
2104
  });
2080
- // 不自定义时 rendered 为 undefined:不返回提示词,前面扩展的改动原样保留。
2081
- return rendered ? { systemPrompt: rewrap(rendered) } : undefined;
2105
+ if (rendered) {
2106
+ return { systemPrompt: rewrap(rendered) };
2107
+ }
2108
+ // 未自定义模板但处于远程工作区时,将 SDK 默认提示词里的本地缓存目录替换为远程真实目录
2109
+ if (isRemoteWorkspaceUri(realCwdForPrompt)) {
2110
+ const patchedCore = core.replace(/Current working directory:\s*[^\r\n]+/, `Current working directory: ${formatCwdForPrompt(realCwdForPrompt)}`);
2111
+ if (patchedCore !== core) {
2112
+ return { systemPrompt: rewrap(patchedCore) };
2113
+ }
2114
+ }
2115
+ return undefined;
2082
2116
  });
2083
2117
  },
2084
2118
  },
@@ -2331,7 +2365,7 @@ export class ClientSession {
2331
2365
  isSubagent: false,
2332
2366
  runtime,
2333
2367
  session: runtime.session,
2334
- cwd: runtime.cwd,
2368
+ cwd: restoreWorkspaceUriFromSessionDir(runtime.cwd),
2335
2369
  createdAt: Date.now(),
2336
2370
  agentPreset: this.settingsSvc.current.defaultAgentPreset ?? "standard",
2337
2371
  presetLocked: false,
@@ -2366,6 +2400,7 @@ export class ClientSession {
2366
2400
  queueFollowUp: [],
2367
2401
  toolStartTimes: new Map(),
2368
2402
  toolPendingArgs: new Map(),
2403
+ activeToolCalls: new Map(),
2369
2404
  toolWatchdogs: new Map(),
2370
2405
  workspaceSnapshots: [],
2371
2406
  };
@@ -2649,6 +2684,7 @@ export class ClientSession {
2649
2684
  this.applyRetryOverrides();
2650
2685
  // 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
2651
2686
  this.applyCompactionOverrides();
2687
+ this.applyCodemodeOverrides();
2652
2688
  this.scheduleSnapshot();
2653
2689
  this.webUi.refresh();
2654
2690
  this.startWidgetsTimer();
@@ -3161,6 +3197,7 @@ export class ClientSession {
3161
3197
  // Record the moment the tool actually starts so tool_status can
3162
3198
  // report real execution time (vs. time spent waiting on the model).
3163
3199
  conv.toolStartTimes.set(event.toolCallId, Date.now());
3200
+ conv.activeToolCalls.set(event.toolCallId, event.toolName);
3164
3201
  // Snapshot listeners before a bash run — the post-run diff catches
3165
3202
  // servers the agent started in the background.
3166
3203
  if (event.toolName === "bash") {
@@ -3201,6 +3238,7 @@ export class ClientSession {
3201
3238
  case "tool_execution_end": {
3202
3239
  const startedAt = conv.toolStartTimes.get(event.toolCallId);
3203
3240
  conv.toolStartTimes.delete(event.toolCallId);
3241
+ conv.activeToolCalls.delete(event.toolCallId);
3204
3242
  this.clearToolWatchdog(conv, event.toolCallId);
3205
3243
  const pendingArgs = conv.toolPendingArgs.get(event.toolCallId);
3206
3244
  conv.toolPendingArgs.delete(event.toolCallId);
@@ -4000,6 +4038,15 @@ export class ClientSession {
4000
4038
  resolveDialog(id, value) {
4001
4039
  this.webUi.resolveDialog(id, value);
4002
4040
  }
4041
+ handleTuiOverlayInput(id, data) {
4042
+ this.webUi.handleTuiOverlayInput(id, data);
4043
+ }
4044
+ handleTuiOverlayResize(id, cols, rows) {
4045
+ this.webUi.handleTuiOverlayResize(id, cols, rows);
4046
+ }
4047
+ handleTuiOverlayCancel(id) {
4048
+ this.webUi.handleTuiOverlayCancel(id);
4049
+ }
4003
4050
  // -----------------------------------------------------------------------
4004
4051
  // 用户提问桥(标准 pi 引擎 ask_user_question customTool)
4005
4052
  // -----------------------------------------------------------------------
@@ -4076,12 +4123,17 @@ export class ClientSession {
4076
4123
  * 成功 resolve 后同步推 question_retracted + conversations:本页 live 对话框
4077
4124
  * 靠前者收起(跨页作答时源页就靠它),别处的「?」角标靠后者即时消失。
4078
4125
  * 返回是否真的恢复了一个挂起提问(跨页作答的送达回执用)。 */
4079
- resolveQuestion(id, answers, cancelled) {
4126
+ resolveQuestion(id, answers, cancelled, cancelReason) {
4080
4127
  const pending = this.pendingQuestions.get(id);
4081
4128
  if (!pending)
4082
4129
  return false;
4083
4130
  this.pendingQuestions.delete(id);
4084
- pending.resolve(cancelled ? null : answers);
4131
+ if (cancelled) {
4132
+ pending.resolve(cancelReason?.trim() ? { cancelled: true, reason: cancelReason.trim() } : null);
4133
+ }
4134
+ else {
4135
+ pending.resolve(answers);
4136
+ }
4085
4137
  this.emit({ type: "question_retracted", id });
4086
4138
  // 同上:角标消失也要即时推送(否则要等到 run 结束别处才知道问完了)。
4087
4139
  this.emitConversations();
@@ -4118,8 +4170,8 @@ export class ClientSession {
4118
4170
  }
4119
4171
  /** 标准引擎的 question_answer 路由入口(index.ts 经 cs.answerQuestion?. 转发)。
4120
4172
  * DSH 引擎的 AgentService 也实现了同名方法,此处为 ClientSession 的转发。 */
4121
- answerQuestion(id, answers, cancelled) {
4122
- this.resolveQuestion(id, answers, cancelled);
4173
+ answerQuestion(id, answers, cancelled, cancelReason) {
4174
+ this.resolveQuestion(id, answers, cancelled, cancelReason);
4123
4175
  return Promise.resolve();
4124
4176
  }
4125
4177
  /** 取某对话的等答复问卷原文(跨页作答的 peek 用;只读,不改变状态)。 */
@@ -4180,6 +4232,15 @@ export class ClientSession {
4180
4232
  return;
4181
4233
  }
4182
4234
  const conversationTitle = conv?.title;
4235
+ let parentTool;
4236
+ if (conv?.activeToolCalls) {
4237
+ for (const [id, name] of conv.activeToolCalls.entries()) {
4238
+ if (name === "codemode" && id !== toolCallId) {
4239
+ parentTool = "codemode";
4240
+ break;
4241
+ }
4242
+ }
4243
+ }
4183
4244
  const entry = {
4184
4245
  id,
4185
4246
  toolCallId,
@@ -4189,6 +4250,7 @@ export class ClientSession {
4189
4250
  reasonEn,
4190
4251
  ...(category ? { category } : {}),
4191
4252
  ...(hits && hits.length > 0 ? { hits } : {}),
4253
+ ...(parentTool ? { parentTool } : {}),
4192
4254
  conversationId,
4193
4255
  conversationTitle,
4194
4256
  resolve,
@@ -4205,6 +4267,7 @@ export class ClientSession {
4205
4267
  reasonEn,
4206
4268
  ...(category ? { category } : {}),
4207
4269
  ...(hits && hits.length > 0 ? { hits } : {}),
4270
+ ...(parentTool ? { parentTool } : {}),
4208
4271
  ...(conversationId !== undefined ? { conversationId } : {}),
4209
4272
  ...(conversationTitle ? { conversationTitle } : {}),
4210
4273
  });
@@ -5165,6 +5228,7 @@ export class ClientSession {
5165
5228
  // /reload 同样重读磁盘 settings.json——重放重试覆盖 + 软上限覆盖 + 终端门控。
5166
5229
  this.applyRetryOverrides();
5167
5230
  this.applyCompactionOverrides();
5231
+ this.applyCodemodeOverrides();
5168
5232
  this.applyToolGating(this.session, this.conv?.agentPreset);
5169
5233
  },
5170
5234
  pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
@@ -5554,6 +5618,21 @@ export class ClientSession {
5554
5618
  compaction: { reserveTokens: reserve ?? DEFAULT_COMPACTION_RESERVE_TOKENS },
5555
5619
  });
5556
5620
  }
5621
+ /** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
5622
+ applyCodemodeOverrides() {
5623
+ const mode = this.settingsSvc.current.codemodeMode ?? "on";
5624
+ const inlineBudget = this.settingsSvc.current.codemodeInlineBudget ?? 3000;
5625
+ for (const c of this.convs.values()) {
5626
+ try {
5627
+ c.session.settingsManager.applyOverrides({
5628
+ codemode: { mode, inlineBudget },
5629
+ });
5630
+ }
5631
+ catch {
5632
+ // 会话未就绪或已释放 → 其 runtime 创建时统一注入。
5633
+ }
5634
+ }
5635
+ }
5557
5636
  /** 会话模型变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
5558
5637
  * (findInitialModel)与 /model 命令都不经过 pi-web-ui 的 setModel
5559
5638
  * 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
@@ -5994,7 +6073,8 @@ export class ClientSession {
5994
6073
  const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(def, () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
5995
6074
  const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
5996
6075
  const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
5997
- return [
6076
+ const remoteOps = createRemoteSdkOperations(cwd);
6077
+ const specs = [
5998
6078
  {
5999
6079
  name: "read",
6000
6080
  // 没有扩展 read:完整覆盖(内置基底 + 英文描述 + file_path 别名)。
@@ -6009,13 +6089,35 @@ export class ClientSession {
6009
6089
  // guidelines 逐条复述(唯一/合并/不要垫大段未改区域都说两遍)。只改描述,保留 SDK 的
6010
6090
  // 参数 schema / guidelines / 执行体;有扩展 edit 时(composeWith)一律不动它的文案。
6011
6091
  fallback: () => composeEdit({
6012
- ...createEditToolDefinition(cwd),
6092
+ ...createEditToolDefinition(cwd, remoteOps ? { operations: remoteOps.edit } : undefined),
6013
6093
  description: EDIT_DESCRIPTION,
6014
6094
  promptGuidelines: EDIT_GUIDELINES,
6015
6095
  }),
6016
6096
  composeWith: (base) => composeEdit(base),
6017
6097
  },
6018
6098
  ];
6099
+ if (remoteOps) {
6100
+ specs.push({
6101
+ name: "ls",
6102
+ fallback: () => createLsToolDefinition(cwd, { operations: remoteOps.ls }),
6103
+ }, {
6104
+ name: "find",
6105
+ fallback: () => createFindToolDefinition(cwd, { operations: remoteOps.find }),
6106
+ }, {
6107
+ name: "grep",
6108
+ fallback: () => {
6109
+ const baseGrep = createGrepToolDefinition(cwd);
6110
+ return {
6111
+ ...baseGrep,
6112
+ execute: async (_id, params) => {
6113
+ const text = await remoteOps.grepExecute(params ?? {});
6114
+ return { content: [{ type: "text", text }], details: undefined };
6115
+ },
6116
+ };
6117
+ },
6118
+ });
6119
+ }
6120
+ return specs;
6019
6121
  }
6020
6122
  /** 统一工具门控(tool_manage 唯一落点):按 disabledAgentTools 把目录内工具
6021
6123
  * 逐个加回/剔除活跃集(工具仍留在注册表,重开可直接加回;live 生效无需
@@ -7630,16 +7732,17 @@ export class ClientSession {
7630
7732
  // #280 & #335:转录链损坏时修一次再试(见 openManagerAndRuntime)。
7631
7733
  // 严禁在 ownFile 不存在时回退到 continueRecent(conv.cwd) 或按 mtime list 历史文件,
7632
7734
  // 否则会直接接错并顶替同项目的其它历史会话,污染别人的转录记录。
7735
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, conv.cwd);
7633
7736
  const opened = await this.openManagerAndRuntime(() => {
7634
7737
  if (ownFile && existsSync(ownFile)) {
7635
7738
  return SessionManager.open(ownFile);
7636
7739
  }
7637
- return conv.isEphemeral ? SessionManager.inMemory(conv.cwd) : SessionManager.create(conv.cwd);
7740
+ return conv.isEphemeral ? SessionManager.inMemory(sessionBaseDir) : SessionManager.create(sessionBaseDir);
7638
7741
  }, (m) =>
7639
7742
  // 子代理带模板时按原模板重建(conv.subagentTemplate 是派发时工厂
7640
7743
  // 用的同一快照);普通对话 undefined,行为不变。
7641
7744
  createAgentSessionRuntime(this.makeRuntimeFactory(conv.terminals, conv.subagentTemplate, conv.id), {
7642
- cwd: conv.cwd,
7745
+ cwd: sessionBaseDir,
7643
7746
  agentDir: this.agentDir,
7644
7747
  sessionManager: m,
7645
7748
  }), async () => (ownFile && existsSync(ownFile) ? ownFile : undefined));
@@ -7779,9 +7882,10 @@ export class ClientSession {
7779
7882
  try {
7780
7883
  const conversationId = this.nextConversationId();
7781
7884
  const terminals = this.makeTerminalManager(conversationId, this.cwd);
7885
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, this.cwd);
7782
7886
  let sessionManager;
7783
7887
  if (ephemeral) {
7784
- sessionManager = SessionManager.inMemory(this.cwd);
7888
+ sessionManager = SessionManager.inMemory(sessionBaseDir);
7785
7889
  // 为无痕临时会话提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
7786
7890
  // 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
7787
7891
  const ephemeralDir = join(this.agentDir, "ephemeral-sessions", conversationId);
@@ -7792,14 +7896,15 @@ export class ClientSession {
7792
7896
  catch { }
7793
7897
  }
7794
7898
  else {
7795
- sessionManager = SessionManager.create(this.cwd);
7899
+ sessionManager = SessionManager.create(sessionBaseDir);
7796
7900
  }
7797
7901
  const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId, prevModel ?? undefined, _preset), {
7798
- cwd: this.cwd,
7902
+ cwd: sessionBaseDir,
7799
7903
  agentDir: this.agentDir,
7800
7904
  sessionManager,
7801
7905
  });
7802
7906
  const conv = this.makeConversation(runtime, conversationId, terminals);
7907
+ conv.cwd = this.cwd;
7803
7908
  if (ephemeral)
7804
7909
  conv.isEphemeral = true;
7805
7910
  if (_preset) {
@@ -8661,8 +8766,12 @@ export class ClientSession {
8661
8766
  // 落盘会话才有文件(inMemory 子代理缺省):右键复制路径 / AI 按 path 读历史时用。
8662
8767
  ...(() => {
8663
8768
  try {
8769
+ const sid = conv.session.sessionId;
8664
8770
  const f = conv.session.sessionFile;
8665
- return f ? { sessionFile: f } : {};
8771
+ return {
8772
+ ...(sid ? { sessionId: sid } : {}),
8773
+ ...(f ? { sessionFile: f } : {}),
8774
+ };
8666
8775
  }
8667
8776
  catch {
8668
8777
  return {};
@@ -8852,11 +8961,12 @@ export class ClientSession {
8852
8961
  const inFlight = ClientSession.sessionInfosInFlight.get(cwdKey);
8853
8962
  if (inFlight)
8854
8963
  return inFlight;
8964
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, this.cwd);
8855
8965
  const run = (async () => {
8856
8966
  try {
8857
8967
  const sessionDir = piSessionsRoot()
8858
8968
  ? resolve(piSessionsRoot())
8859
- : SessionManager.create(this.cwd).getSessionDir();
8969
+ : SessionManager.create(sessionBaseDir).getSessionDir();
8860
8970
  if (!existsSync(sessionDir))
8861
8971
  return [];
8862
8972
  const dirEntries = await fsPromises.readdir(sessionDir);
@@ -8893,16 +9003,8 @@ export class ClientSession {
8893
9003
  return info;
8894
9004
  }));
8895
9005
  const validInfos = results.filter((info) => info !== null);
8896
- // issue #438:扁平布局(PI_CODING_AGENT_SESSION_DIR)下根目录顶层直接是**所有项目**
8897
- // 共享的 .jsonl,所属 cwd 是文件内字段;不过滤的话其他项目的会话会混进本项目
8898
- // 「历史会话」列表,点开即把整个工作区切走。与 SessionManager.list(cwd, ...) 的
8899
- // fallback 及 discoverRecentProjectsFromDisk 同口径:normalizePathKey(Windows
8900
- // 大小写/斜杠归一)。空 cwd 的损坏文件须排除——normalizePathKey("") 会 resolve 到
8901
- // process.cwd(),恰好等于本项目时会把垃圾文件误收进来。
8902
- const ownInfos = validInfos.filter((info) => info.cwd !== "" && normalizePathKey(info.cwd) === cwdKey);
8903
- // 200 名额只在 cwd 过滤**之后**分配:扁平布局下若先截断,本项目会话可能被
8904
- // 其他项目的文件挤出列表。截断仍按上面的 mtime 降序序取(Promise.all 保序),
8905
- // 与原有选集口径一致;非扁平布局每-cwd 子目录内文件全属本项目,过滤幂等。
9006
+ const baseDirKey = normalizePathKey(sessionBaseDir);
9007
+ const ownInfos = validInfos.filter((info) => info.cwd !== "" && (normalizePathKey(info.cwd) === cwdKey || normalizePathKey(info.cwd) === baseDirKey));
8906
9008
  const candidates = ownInfos.slice(0, 200);
8907
9009
  candidates.sort((a, b) => b.modified.getTime() - a.modified.getTime());
8908
9010
  ClientSession.sessionInfosCache.set(cwdKey, { infos: candidates, at: Date.now() });
@@ -8910,7 +9012,7 @@ export class ClientSession {
8910
9012
  }
8911
9013
  catch {
8912
9014
  try {
8913
- const fallback = await SessionManager.list(this.cwd, piSessionsRoot());
9015
+ const fallback = await SessionManager.list(sessionBaseDir, piSessionsRoot());
8914
9016
  // 统一口径:列表缓存一律不带转录全文(issue #440),搜索按需另行加载
8915
9017
  const stripped = fallback.map((s) => ({ ...s, allMessagesText: "" }));
8916
9018
  ClientSession.sessionInfosCache.set(cwdKey, { infos: stripped, at: Date.now() });
@@ -8980,6 +9082,7 @@ export class ClientSession {
8980
9082
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
8981
9083
  sessions.set(s.path, {
8982
9084
  path: s.path,
9085
+ ...(s.id ? { sessionId: s.id } : {}),
8983
9086
  name: s.name,
8984
9087
  firstMessage: s.firstMessage,
8985
9088
  messageCount: s.messageCount,
@@ -9336,7 +9439,8 @@ export class ClientSession {
9336
9439
  const wasEphemeral = !!conv.isEphemeral;
9337
9440
  try {
9338
9441
  const cwd = conv.cwd || this.cwd;
9339
- const sampleSm = SessionManager.create(cwd);
9442
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, cwd);
9443
+ const sampleSm = SessionManager.create(sessionBaseDir);
9340
9444
  const sessionDir = sampleSm.getSessionDir();
9341
9445
  if (!existsSync(sessionDir)) {
9342
9446
  mkdirSync(sessionDir, { recursive: true });
@@ -9792,7 +9896,55 @@ export class ClientSession {
9792
9896
  });
9793
9897
  }
9794
9898
  }
9795
- /** Open a persisted session as the active conversation (from listSessions).
9899
+ /** 按 sessionId 解析磁盘上的转录文件路径(issue #587:供 `#s=<sessionId>` 深链直接打开尚未加载进列表的历史会话)。 */
9900
+ async resolveSessionPathById(sessionId) {
9901
+ const want = sessionId.trim();
9902
+ if (!want)
9903
+ return null;
9904
+ const infos = await this.loadSessionInfos();
9905
+ for (const info of infos) {
9906
+ if (info.id === want)
9907
+ return info.path;
9908
+ const base = basename(info.path);
9909
+ if (base === `${want}.jsonl` || base.endsWith(`_${want}.jsonl`))
9910
+ return info.path;
9911
+ }
9912
+ // 跨项目目录兜底扫描(<agentDir>/sessions 及 PI_CODING_AGENT_SESSION_DIR)
9913
+ const roots = [join(this.agentDir, "sessions")];
9914
+ const extra = piSessionsRoot();
9915
+ if (extra)
9916
+ roots.push(extra);
9917
+ for (const root of roots) {
9918
+ if (!existsSync(root))
9919
+ continue;
9920
+ try {
9921
+ const entries = readdirSync(root, { withFileTypes: true });
9922
+ for (const e of entries) {
9923
+ if (e.isFile() && (e.name === `${want}.jsonl` || e.name.endsWith(`_${want}.jsonl`))) {
9924
+ return join(root, e.name);
9925
+ }
9926
+ if (e.isDirectory()) {
9927
+ const subDir = join(root, e.name);
9928
+ try {
9929
+ for (const f of readdirSync(subDir)) {
9930
+ if (f === `${want}.jsonl` || f.endsWith(`_${want}.jsonl`)) {
9931
+ return join(subDir, f);
9932
+ }
9933
+ }
9934
+ }
9935
+ catch {
9936
+ /* ignore unreadable subdir */
9937
+ }
9938
+ }
9939
+ }
9940
+ }
9941
+ catch {
9942
+ /* ignore unreadable root */
9943
+ }
9944
+ }
9945
+ return null;
9946
+ }
9947
+ /** Open a persisted session as the active conversation (from listSessions or `#s=<sessionId>` deep link).
9796
9948
  *
9797
9949
  * A persisted-session click must follow the same ownership rule as
9798
9950
  * new_chat/switch_conversation: every open conversation keeps its own
@@ -9800,12 +9952,40 @@ export class ClientSession {
9800
9952
  * current runtime, which would otherwise stop a response merely because the
9801
9953
  * user opened history while it was streaming.
9802
9954
  */
9803
- async switchSession(path) {
9955
+ async switchSession(path, sessionId) {
9804
9956
  if (this.quiesceBlocked())
9805
9957
  return;
9806
9958
  let openedRuntime = null;
9807
9959
  let openedTerminals = null;
9808
9960
  try {
9961
+ const wantSid = sessionId?.trim() ?? "";
9962
+ if (!path.trim() && wantSid) {
9963
+ for (const conv of this.convs.values()) {
9964
+ let sid = "";
9965
+ try {
9966
+ sid = conv.session.sessionId;
9967
+ }
9968
+ catch {
9969
+ /* ignore */
9970
+ }
9971
+ if (sid === wantSid || conv.id === wantSid) {
9972
+ await this.switchConversation(conv.id);
9973
+ return;
9974
+ }
9975
+ }
9976
+ const resolved = await this.resolveSessionPathById(wantSid);
9977
+ if (!resolved) {
9978
+ this.emit({
9979
+ type: "notice",
9980
+ level: "warning",
9981
+ text: `未找到会话:${wantSid}`,
9982
+ textEn: `Session not found: ${wantSid}`,
9983
+ });
9984
+ this.flushSnapshot();
9985
+ return;
9986
+ }
9987
+ path = resolved;
9988
+ }
9809
9989
  const targetPath = resolve(path);
9810
9990
  if (!isInsideSessionsDir(this.agentDir, targetPath)) {
9811
9991
  this.emit({
@@ -9864,11 +10044,13 @@ export class ClientSession {
9864
10044
  this.repairTranscriptFileBeforeOpen(targetPath);
9865
10045
  const sessionManager = SessionManager.open(targetPath);
9866
10046
  calibrateSessionLeaf(sessionManager);
9867
- const targetCwd = sessionManager.getCwd();
10047
+ const rawSessionCwd = sessionManager.getCwd();
10048
+ const targetCwd = restoreWorkspaceUriFromSessionDir(rawSessionCwd);
10049
+ const runtimeCwd = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
9868
10050
  const conversationId = this.nextConversationId();
9869
10051
  openedTerminals = this.makeTerminalManager(conversationId, targetCwd);
9870
10052
  openedRuntime = await createAgentSessionRuntime(this.makeRuntimeFactory(openedTerminals, undefined, conversationId), {
9871
- cwd: targetCwd,
10053
+ cwd: runtimeCwd,
9872
10054
  agentDir: this.agentDir,
9873
10055
  sessionManager,
9874
10056
  });
@@ -10004,12 +10186,13 @@ export class ClientSession {
10004
10186
  const prevThinking = targetConv.session.thinkingLevel ?? null;
10005
10187
  const conversationId = this.nextConversationId();
10006
10188
  const terminals = this.makeTerminalManager(conversationId, targetConv.cwd);
10189
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetConv.cwd);
10007
10190
  let forkedManager;
10008
10191
  if (isPersisted) {
10009
10192
  const sessionDir = targetConv.session.sessionManager.getSessionDir();
10010
10193
  let forkedSessionPath;
10011
10194
  if (!targetLeafId) {
10012
- const sm = SessionManager.create(targetConv.cwd, sessionDir);
10195
+ const sm = SessionManager.create(sessionBaseDir, sessionDir);
10013
10196
  sm.newSession({ parentSession: currentSessionFile });
10014
10197
  forkedSessionPath = sm.getSessionFile();
10015
10198
  }
@@ -10024,7 +10207,7 @@ export class ClientSession {
10024
10207
  calibrateSessionLeaf(forkedManager);
10025
10208
  }
10026
10209
  else {
10027
- forkedManager = SessionManager.create(targetConv.cwd);
10210
+ forkedManager = SessionManager.create(sessionBaseDir);
10028
10211
  if (targetLeafId) {
10029
10212
  const branch = targetConv.session.sessionManager.getBranch(targetLeafId);
10030
10213
  for (const e of branch) {
@@ -10040,7 +10223,7 @@ export class ClientSession {
10040
10223
  }
10041
10224
  }
10042
10225
  const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId, prevModel ?? undefined), {
10043
- cwd: targetConv.cwd,
10226
+ cwd: sessionBaseDir,
10044
10227
  agentDir: this.agentDir,
10045
10228
  sessionManager: forkedManager,
10046
10229
  });
@@ -10434,6 +10617,7 @@ export class ClientSession {
10434
10617
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
10435
10618
  const base = {
10436
10619
  path: s.path,
10620
+ ...(s.id ? { sessionId: s.id } : {}),
10437
10621
  name: s.name,
10438
10622
  firstMessage: s.firstMessage,
10439
10623
  messageCount: s.messageCount,
@@ -10591,12 +10775,24 @@ export class ClientSession {
10591
10775
  });
10592
10776
  return;
10593
10777
  }
10594
- // Windows 裸盘符("C:")与相对路径基准的处理收敛到 resolveCwdTarget
10595
- // (纯函数,含 win32/posix 差异说明与单测)。
10596
- const abs = resolveCwdTarget(trimmed, this.cwd);
10597
- const st = await fs.stat(abs);
10598
- if (!st.isDirectory()) {
10599
- throw new Error("路径不是目录");
10778
+ const isRemote = isRemoteWorkspaceUri(trimmed);
10779
+ let abs;
10780
+ let sessionBaseDir;
10781
+ if (isRemote) {
10782
+ abs = trimmed;
10783
+ // 远程工作区在本地数据目录下分配隔离的物理会话存储目录,保证所有对话历史、记录 100% 存在本地
10784
+ sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, abs);
10785
+ }
10786
+ else {
10787
+ // Windows 裸盘符("C:")与相对路径基准的处理收敛到 resolveCwdTarget
10788
+ // (纯函数,含 win32/posix 差异说明与单测)。
10789
+ const baseForResolve = isRemoteWorkspaceUri(this.cwd) ? homedir() : this.cwd;
10790
+ abs = resolveCwdTarget(trimmed, baseForResolve);
10791
+ const st = await fs.stat(abs);
10792
+ if (!st.isDirectory()) {
10793
+ throw new Error("路径不是目录");
10794
+ }
10795
+ sessionBaseDir = abs;
10600
10796
  }
10601
10797
  if (abs === this.cwd) {
10602
10798
  this.emit({
@@ -10647,7 +10843,7 @@ export class ClientSession {
10647
10843
  // 别处无可见行时不扫目录(首访切项目的常见情形零开销)。
10648
10844
  if ((this.listExternalRunning?.() ?? []).length > 0) {
10649
10845
  try {
10650
- const infos = await SessionManager.list(abs, piSessionsRoot());
10846
+ const infos = await SessionManager.list(sessionBaseDir, piSessionsRoot());
10651
10847
  const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
10652
10848
  const owner = recent ? this.findSessionOwner?.(recent) : null;
10653
10849
  if (owner) {
@@ -10662,17 +10858,18 @@ export class ClientSession {
10662
10858
  const terminals = this.makeTerminalManager(conversationId, abs);
10663
10859
  // #235:manager+runtime 一起建,转录链损坏时修最近文件后重试一次
10664
10860
  // (见 openManagerAndRuntime)。blank(别处在跑)是全新空会话,不会坏。
10665
- const opened = await this.openManagerAndRuntime(() => (resumeSkipped ? SessionManager.create(abs) : SessionManager.continueRecent(abs)), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId), {
10666
- cwd: abs,
10861
+ const opened = await this.openManagerAndRuntime(() => (resumeSkipped ? SessionManager.create(sessionBaseDir) : SessionManager.continueRecent(sessionBaseDir)), (m) => createAgentSessionRuntime(this.makeRuntimeFactory(terminals, undefined, conversationId), {
10862
+ cwd: sessionBaseDir,
10667
10863
  agentDir: this.agentDir,
10668
10864
  sessionManager: m,
10669
- }), async () => (await SessionManager.list(abs))[0]?.path);
10865
+ }), async () => (await SessionManager.list(sessionBaseDir))[0]?.path);
10670
10866
  const newRuntime = opened.runtime;
10671
10867
  if (opened.repair) {
10672
10868
  for (const n of this.transcriptRepairNotices(opened.repair))
10673
10869
  this.emit(n);
10674
10870
  }
10675
10871
  const conv = this.makeConversation(newRuntime, conversationId, terminals);
10872
+ conv.cwd = abs;
10676
10873
  this.convs.set(conv.id, conv);
10677
10874
  this.activeId = conv.id;
10678
10875
  if (displaced)