pi-web-ui 0.103.2 → 0.104.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 +37 -0
- package/dist/server/agent-formatters.js +18 -2
- package/dist/server/agent-service-daemon.js +4 -3
- package/dist/server/agent-service.js +773 -181
- package/dist/server/compaction-markers.js +111 -3
- package/dist/server/delegate-mode.js +2 -0
- package/dist/server/dispatch-domain-handlers.js +25 -0
- package/dist/server/dsh/dsh-agent-service.js +265 -11
- package/dist/server/goal-review-gate.js +2 -0
- package/dist/server/goal-service.js +59 -2
- package/dist/server/index.js +1 -0
- package/dist/server/markers-list-tool.js +1 -1
- package/dist/server/market-service.js +36 -9
- package/dist/server/mcp-agent-tool.js +164 -0
- package/dist/server/mcp-manager.js +182 -0
- package/dist/server/plan-mode.js +3 -0
- package/dist/server/plugin-api-catalog.js +24 -0
- package/dist/server/plugins.js +113 -0
- package/dist/server/preset-share.js +52 -1
- package/dist/server/remote-ssh-service.js +90 -25
- package/dist/server/sandbox-service.js +705 -0
- package/dist/server/sandbox-tool.js +365 -0
- package/dist/server/session-parser.js +48 -21
- package/dist/server/subagent-helpers.js +32 -1
- package/dist/server/terminals.js +210 -10
- package/dist/server/tool-manager.js +24 -0
- package/dist/server/webui-context.js +16 -2
- package/dist/server/workspace-snapshot.js +51 -13
- package/package.json +1 -1
- package/plugin-sdk/index.d.ts +39 -0
- package/plugin-sdk/index.mjs +14 -0
- package/plugins/catalog.json +110 -0
- package/themes/zhujian-dark.css +711 -0
- package/themes/zhujian.css +760 -0
- package/web/dist/assets/{TerminalPanel-DQFDRz0A.js → TerminalPanel-28naZdcs.js} +1 -1
- package/web/dist/assets/index-DbGGBf5I.js +680 -0
- package/web/dist/assets/index-RqIdFOsh.css +1 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-CYQdZEbx.css +0 -1
- package/web/dist/assets/index-aGRL6x3h.js +0 -680
|
@@ -52,10 +52,11 @@ import { pick, resolveServerLang } from "./i18n.js";
|
|
|
52
52
|
import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
|
|
53
53
|
import { ApprovalRulesStore, extractTargetPath } from "./approval-rules.js";
|
|
54
54
|
import { ComposerDraftsStore } from "./composer-drafts.js";
|
|
55
|
+
import { SandboxManager, evaluateSandboxJail, isSameOrSubpath, withSandboxJailGate } from "./sandbox-service.js";
|
|
55
56
|
import { readPermissionFromSession } from "./permission-preset.js";
|
|
56
57
|
import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, } from "./workspace-snapshot.js";
|
|
57
58
|
import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
|
|
58
|
-
import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf } from "./subagent-helpers.js";
|
|
59
|
+
import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
|
|
59
60
|
import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
|
|
60
61
|
import { fillSkillContents } from "./skill-content-filler.js";
|
|
61
62
|
import { hasSettledAssistantUsage, estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
|
|
@@ -103,13 +104,15 @@ import { getCompactedMessages } from "./compacted-history.js";
|
|
|
103
104
|
import { makeScheduleTool } from "./schedule-agent-tool.js";
|
|
104
105
|
import { makePatchTool } from "./patch-tool.js";
|
|
105
106
|
import { makeLspTool } from "./lsp-tool.js";
|
|
107
|
+
import { makeMcpManageTool } from "./mcp-agent-tool.js";
|
|
108
|
+
import { makeSandboxTool } from "./sandbox-tool.js";
|
|
106
109
|
import { sameSessionFile } from "./scheduler-tasks.js";
|
|
107
110
|
import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
|
|
108
111
|
import { formatQuotedPrompt, readTextQuote } from "./text-quote.js";
|
|
109
112
|
import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
|
|
110
113
|
import { generateScmCommitMessage } from "./scm-commitmsg.js";
|
|
111
114
|
import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, estimatePromptTokens, renderPromptTemplate, resolveSectionTexts, splitExtensionWrap, } from "./prompt-composer.js";
|
|
112
|
-
import { listAllMcpServers, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
|
|
115
|
+
import { listAllMcpServers, checkMcpServer, installMcpServer, saveMcpServer as saveMcpServerFile, deleteMcpServer as deleteMcpServerFile, toggleMcpServer as toggleMcpServerFile, } from "./mcp-manager.js";
|
|
113
116
|
import { fetchRemoteMcpMarket, fetchRemoteSkillMarket, fetchRemoteSkillContent } from "./market-service.js";
|
|
114
117
|
import { launchOrigin, toServiceInfo } from "./launch-origin.js";
|
|
115
118
|
import { findEntryByUiId, serializeMessage, serializeStreamingMessage, stripTransientRetryErrors, } from "./serialize.js";
|
|
@@ -204,7 +207,7 @@ import { makeMarkersListTool } from "./markers-list-tool.js";
|
|
|
204
207
|
import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
|
|
205
208
|
import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
|
|
206
209
|
export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
|
|
207
|
-
import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP,
|
|
210
|
+
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";
|
|
208
211
|
export { workspacePath };
|
|
209
212
|
import { MAX_TRANSCRIPT_SCAN_BYTES, MAX_SEARCH_TEXT_CHARS, sessionMatchesMetadata, messageSearchText, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
|
|
210
213
|
export { piSessionsRoot, isInsideSessionsDir };
|
|
@@ -425,6 +428,8 @@ export class ClientSession {
|
|
|
425
428
|
.catch(() => { });
|
|
426
429
|
}
|
|
427
430
|
}
|
|
431
|
+
/** 正在创建 runtime 尚未注册进 convs 的轻量子代理数量(防并发 spawn 绕过并发名额,#589)。 */
|
|
432
|
+
spawningSubagents = 0;
|
|
428
433
|
/** 创建子代理 conversation(inMemory runtime + 独立 terminals),listed 入左栏,
|
|
429
434
|
* 并在其上触发一次完整回合。返回 convId(= 工具 runId)。
|
|
430
435
|
*
|
|
@@ -438,164 +443,194 @@ export class ClientSession {
|
|
|
438
443
|
const baseCwdForLimit = parentId ? (this.convs.get(parentId)?.cwd ?? this.cwd) : this.cwd;
|
|
439
444
|
const resolvedCwdForLimit = cwd ? resolve(baseCwdForLimit, cwd) : baseCwdForLimit;
|
|
440
445
|
const openInProject = [...this.convs.values()].filter((c) => c.cwd === resolvedCwdForLimit && !c.isSubagent && !c.isEphemeral).length;
|
|
441
|
-
|
|
442
|
-
|
|
446
|
+
const maxOpenConversations = getMaxOpenConversations();
|
|
447
|
+
if (openInProject >= maxOpenConversations) {
|
|
448
|
+
throw new Error(pick(this.getLang(), `目标项目运行的普通对话已达上限(${maxOpenConversations} 个),无法创建持久化对话。请先关闭不需要的对话,或以轻量子代理(persist=false)方式运行`, `The project already has max open regular conversations (${maxOpenConversations}). Please close some or run as a lightweight subagent (persist=false)`, "agent.conv.limit.reached", { limit: maxOpenConversations }));
|
|
443
449
|
}
|
|
444
450
|
}
|
|
445
451
|
else {
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
// 跟随思考强度一律读它,而不是派发瞬间的 active——后台对话产出时用户可能正
|
|
453
|
-
// 看着别的项目,读 active 会跟错模型、把相对 cwd 解析到错误的项目下。
|
|
454
|
-
const spawner = parentId ? this.convs.get(parentId) : undefined;
|
|
455
|
-
const spawnerSession = spawner?.session ?? this.session;
|
|
456
|
-
const baseCwd = spawner?.cwd ?? this.cwd;
|
|
457
|
-
// 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
|
|
458
|
-
const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
|
|
459
|
-
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
|
|
460
|
-
const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
|
|
461
|
-
const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
|
|
462
|
-
const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
|
|
463
|
-
if (!persist) {
|
|
464
|
-
// 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
|
|
465
|
-
// 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
|
|
466
|
-
const ephemeralDir = join(this.agentDir, "subagent-sessions", conversationId);
|
|
467
|
-
try {
|
|
468
|
-
mkdirSync(ephemeralDir, { recursive: true });
|
|
469
|
-
sessionManager.sessionDir = ephemeralDir;
|
|
452
|
+
// #589:名额与可见性解耦——只统计正在运行/启动中的活跃子代理,已结束(done/canceled/error)
|
|
453
|
+
// 的子代理留在左栏供用户审阅追溯,不再占用并发名额,使 wait_all / stop 能真正释放名额。
|
|
454
|
+
const maxSubagents = getMaxSubagents();
|
|
455
|
+
const liveSubagents = countActiveSubagents(this.convs.values(), this.spawningSubagents);
|
|
456
|
+
if (liveSubagents >= maxSubagents) {
|
|
457
|
+
throw new Error(pick(this.getLang(), `同时运行的子代理数量已达上限(${maxSubagents} 个),请先用 subagent_wait_all 等一部分完成、或用 subagent_stop 停掉不需要的再派发`, `Active subagent limit reached (${maxSubagents} live). Wait for some with subagent_wait_all or stop unneeded ones with subagent_stop before spawning more`, "agent.subagent.limit.reached", { limit: maxSubagents }));
|
|
470
458
|
}
|
|
471
|
-
catch { }
|
|
472
459
|
}
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
const conv = this.makeConversation(runtime, conversationId, terminals);
|
|
479
|
-
conv.cwd = resolvedCwd;
|
|
480
|
-
conv.isSubagent = !persist;
|
|
481
|
-
// 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
|
|
482
|
-
// 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
|
|
483
|
-
// 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
|
|
484
|
-
conv.parentId = parentId ?? this.activeId ?? undefined;
|
|
485
|
-
conv.subagentType = type;
|
|
486
|
-
conv.subagentPrompt = prompt;
|
|
487
|
-
// 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
|
|
488
|
-
// (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
|
|
489
|
-
conv.subagentTemplate = apply;
|
|
490
|
-
// 插件工具门与模板扩展白名单对齐:白名单非空时插件/MCP 工具(无 SDK
|
|
491
|
-
// extensionKey 身份)不进该会话。工厂期 customTools 不注册 + 下面的
|
|
492
|
-
// syncPluginTools 不回补,模板热改不影响已运行的子代理(与 prompt/技能一致)。
|
|
493
|
-
conv.subagentBarsPluginTools = !!apply && apply.enabledExtensions.length > 0;
|
|
494
|
-
conv.listed = true;
|
|
495
|
-
conv.title = title ?? subagentTitle(prompt);
|
|
496
|
-
this.convs.set(conv.id, conv);
|
|
497
|
-
// 子代理会话同样订阅 SDK 事件:否则 onEvent 永不触发,点开查看时没有
|
|
498
|
-
// message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
|
|
499
|
-
// 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
|
|
500
|
-
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
501
|
-
// 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
|
|
502
|
-
this.applyRetryOverrides();
|
|
503
|
-
// 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
|
|
504
|
-
this.applyCompactionOverrides();
|
|
505
|
-
this.applyCodemodeOverrides();
|
|
506
|
-
// 扩展绑定(rpc 模式);用 headless 的 Web UI context:
|
|
507
|
-
// 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
|
|
460
|
+
const isEphemeralSubagent = !persist;
|
|
461
|
+
if (isEphemeralSubagent) {
|
|
462
|
+
this.spawningSubagents++;
|
|
463
|
+
}
|
|
464
|
+
let handedOffToConv = false;
|
|
508
465
|
try {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
466
|
+
// 真正的派发者(withSubagentOwner 按 runtime 归属填入):cwd 基准 / 跟随模型 /
|
|
467
|
+
// 跟随思考强度一律读它,而不是派发瞬间的 active——后台对话产出时用户可能正
|
|
468
|
+
// 看着别的项目,读 active 会跟错模型、把相对 cwd 解析到错误的项目下。
|
|
469
|
+
const spawner = parentId ? this.convs.get(parentId) : undefined;
|
|
470
|
+
const spawnerSession = spawner?.session ?? this.session;
|
|
471
|
+
const baseCwd = spawner?.cwd ?? this.cwd;
|
|
472
|
+
// 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
|
|
473
|
+
const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
|
|
474
|
+
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
|
|
475
|
+
const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
|
|
476
|
+
const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
|
|
477
|
+
const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
|
|
478
|
+
if (!persist) {
|
|
479
|
+
// 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
|
|
480
|
+
// 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
|
|
481
|
+
const ephemeralDir = join(this.agentDir, "subagent-sessions", conversationId);
|
|
482
|
+
try {
|
|
483
|
+
mkdirSync(ephemeralDir, { recursive: true });
|
|
484
|
+
sessionManager.sessionDir = ephemeralDir;
|
|
485
|
+
}
|
|
486
|
+
catch { }
|
|
487
|
+
}
|
|
488
|
+
const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
|
|
489
|
+
cwd: sessionBaseDir,
|
|
490
|
+
agentDir: this.agentDir,
|
|
491
|
+
sessionManager,
|
|
519
492
|
});
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
493
|
+
const conv = this.makeConversation(runtime, conversationId, terminals);
|
|
494
|
+
conv.cwd = resolvedCwd;
|
|
495
|
+
conv.isSubagent = !persist;
|
|
496
|
+
if (conv.isSubagent) {
|
|
497
|
+
// 首轮 sendUserMessage 进入流式前的预检/模型切换窗口标记为投递中,
|
|
498
|
+
// 确保并发名额与快照状态在此窗口内均按运行中处理(#589)。
|
|
499
|
+
conv.promptInFlight = true;
|
|
500
|
+
}
|
|
501
|
+
// 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
|
|
502
|
+
// 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
|
|
503
|
+
// 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
|
|
504
|
+
conv.parentId = parentId ?? this.activeId ?? undefined;
|
|
505
|
+
conv.subagentType = type;
|
|
506
|
+
conv.subagentPrompt = prompt;
|
|
507
|
+
// 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
|
|
508
|
+
// (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
|
|
509
|
+
conv.subagentTemplate = apply;
|
|
510
|
+
// 插件工具门与模板扩展白名单对齐:白名单非空时插件/MCP 工具(无 SDK
|
|
511
|
+
// extensionKey 身份)不进该会话。工厂期 customTools 不注册 + 下面的
|
|
512
|
+
// syncPluginTools 不回补,模板热改不影响已运行的子代理(与 prompt/技能一致)。
|
|
513
|
+
conv.subagentBarsPluginTools = !!apply && apply.enabledExtensions.length > 0;
|
|
514
|
+
conv.listed = true;
|
|
515
|
+
conv.title = title ?? subagentTitle(prompt);
|
|
516
|
+
this.convs.set(conv.id, conv);
|
|
517
|
+
if (isEphemeralSubagent) {
|
|
518
|
+
handedOffToConv = true;
|
|
519
|
+
this.spawningSubagents = Math.max(0, this.spawningSubagents - 1);
|
|
520
|
+
}
|
|
521
|
+
// 子代理会话同样订阅 SDK 事件:否则 onEvent 永不触发,点开查看时没有
|
|
522
|
+
// message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
|
|
523
|
+
// 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
|
|
524
|
+
conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
|
|
525
|
+
// 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
|
|
526
|
+
this.applyRetryOverrides();
|
|
527
|
+
// 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
|
|
528
|
+
this.applyCompactionOverrides();
|
|
529
|
+
this.applyCodemodeOverrides();
|
|
530
|
+
// 扩展绑定(rpc 模式);用 headless 的 Web UI context:
|
|
531
|
+
// 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
|
|
532
|
+
try {
|
|
533
|
+
await conv.session.bindExtensions({
|
|
534
|
+
mode: "rpc",
|
|
535
|
+
// 子代理的扩展照常拿到完整 ExtensionUIContext(扩展调用新增方法不会因
|
|
536
|
+
// 局部 mock 缺失而崩),但它是 headless 的:UI 输出全部丢弃、弹窗按取消返回,
|
|
537
|
+
// 因此既不与主对话的 widget/status 串台,也不会让扩展卡在永远无人应答的弹窗上。
|
|
538
|
+
uiContext: WebUIContext.headless(),
|
|
539
|
+
onError: this.makeExtensionErrorReporter({
|
|
540
|
+
text: `子代理 ${conversationId}:`,
|
|
541
|
+
textEn: `Subagent ${conversationId}: `,
|
|
542
|
+
}),
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
// 绑定失败不阻断运行。
|
|
547
|
+
}
|
|
548
|
+
// 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
|
|
549
|
+
// 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
|
|
550
|
+
// 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
|
|
551
|
+
const resolvedModel = model ?? (apply?.model?.trim() || null) ?? (this.settingsSvc.current.subagentDefaultModel || null);
|
|
552
|
+
const followModel = resolvedModel
|
|
553
|
+
? resolvedModel
|
|
554
|
+
: spawnerSession.model
|
|
555
|
+
? `${spawnerSession.model.provider}/${spawnerSession.model.id}`
|
|
556
|
+
: null;
|
|
557
|
+
if (followModel) {
|
|
558
|
+
const slash = followModel.indexOf("/");
|
|
559
|
+
const m = slash > 0 && slash < followModel.length - 1
|
|
560
|
+
? this.sharedModelRuntime?.getModel(followModel.slice(0, slash), followModel.slice(slash + 1))
|
|
561
|
+
: undefined;
|
|
562
|
+
if (m) {
|
|
563
|
+
try {
|
|
564
|
+
// 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
|
|
565
|
+
// 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
|
|
566
|
+
await this.restoreKeyForModel(followModel, resolvedCwd);
|
|
567
|
+
await conv.session.setModel(m);
|
|
568
|
+
}
|
|
569
|
+
catch (err) {
|
|
570
|
+
// 换模型失败不阻断运行——沿用默认模型继续。
|
|
571
|
+
this.emit({
|
|
572
|
+
type: "notice",
|
|
573
|
+
level: "warning",
|
|
574
|
+
text: `子代理模型切换失败(将按默认模型运行):${followModel}(${err.message})`,
|
|
575
|
+
textEn: `Failed to set subagent model, running with default: ${followModel} (${err.message})`,
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
else {
|
|
580
|
+
this.emit({
|
|
581
|
+
type: "notice",
|
|
582
|
+
level: "warning",
|
|
583
|
+
text: `子代理模型不存在,将按默认模型运行:${followModel}`,
|
|
584
|
+
textEn: `Subagent model not found, running with default: ${followModel}`,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
// 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
|
|
589
|
+
// 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
|
|
590
|
+
// SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
|
|
591
|
+
// 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
|
|
592
|
+
// 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
|
|
593
|
+
const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
|
|
594
|
+
if (thinkingLevel) {
|
|
539
595
|
try {
|
|
540
|
-
|
|
541
|
-
// 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
|
|
542
|
-
await this.restoreKeyForModel(followModel, resolvedCwd);
|
|
543
|
-
await conv.session.setModel(m);
|
|
596
|
+
conv.session.setThinkingLevel(thinkingLevel);
|
|
544
597
|
}
|
|
545
598
|
catch (err) {
|
|
546
|
-
//
|
|
599
|
+
// 强度不合法/会话未就绪都不阻断运行(沿用当前档位)。
|
|
547
600
|
this.emit({
|
|
548
601
|
type: "notice",
|
|
549
602
|
level: "warning",
|
|
550
|
-
text:
|
|
551
|
-
textEn: `Failed to set subagent
|
|
603
|
+
text: `子代理思考强度设置失败(将按当前档位运行):${thinkingLevel}(${err.message})`,
|
|
604
|
+
textEn: `Failed to set subagent thinking level, keeping the current one: ${thinkingLevel} (${err.message})`,
|
|
552
605
|
});
|
|
553
606
|
}
|
|
554
607
|
}
|
|
555
|
-
|
|
608
|
+
// 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
|
|
609
|
+
// 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
|
|
610
|
+
conv.kickoff = conv.session
|
|
611
|
+
.sendUserMessage(prompt)
|
|
612
|
+
.catch((err) => {
|
|
556
613
|
this.emit({
|
|
557
614
|
type: "notice",
|
|
558
|
-
level: "
|
|
559
|
-
text:
|
|
560
|
-
textEn: `Subagent
|
|
615
|
+
level: "error",
|
|
616
|
+
text: `子代理 ${conversationId} 启动失败: ${err instanceof Error ? err.message : String(err)}`,
|
|
617
|
+
textEn: `Subagent ${conversationId} failed to start: ${err instanceof Error ? err.message : String(err)}`,
|
|
561
618
|
});
|
|
619
|
+
})
|
|
620
|
+
.finally(() => {
|
|
621
|
+
conv.promptInFlight = false;
|
|
622
|
+
});
|
|
623
|
+
if (persist) {
|
|
624
|
+
this.pushProjects().catch(() => { });
|
|
562
625
|
}
|
|
626
|
+
this.emitConversations();
|
|
627
|
+
return conv.id;
|
|
563
628
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
// 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
|
|
568
|
-
// 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
|
|
569
|
-
const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
|
|
570
|
-
if (thinkingLevel) {
|
|
571
|
-
try {
|
|
572
|
-
conv.session.setThinkingLevel(thinkingLevel);
|
|
573
|
-
}
|
|
574
|
-
catch (err) {
|
|
575
|
-
// 强度不合法/会话未就绪都不阻断运行(沿用当前档位)。
|
|
576
|
-
this.emit({
|
|
577
|
-
type: "notice",
|
|
578
|
-
level: "warning",
|
|
579
|
-
text: `子代理思考强度设置失败(将按当前档位运行):${thinkingLevel}(${err.message})`,
|
|
580
|
-
textEn: `Failed to set subagent thinking level, keeping the current one: ${thinkingLevel} (${err.message})`,
|
|
581
|
-
});
|
|
629
|
+
finally {
|
|
630
|
+
if (isEphemeralSubagent && !handedOffToConv) {
|
|
631
|
+
this.spawningSubagents = Math.max(0, this.spawningSubagents - 1);
|
|
582
632
|
}
|
|
583
633
|
}
|
|
584
|
-
// 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
|
|
585
|
-
// 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
|
|
586
|
-
conv.kickoff = conv.session.sendUserMessage(prompt).catch((err) => {
|
|
587
|
-
this.emit({
|
|
588
|
-
type: "notice",
|
|
589
|
-
level: "error",
|
|
590
|
-
text: `子代理 ${conversationId} 启动失败: ${err instanceof Error ? err.message : String(err)}`,
|
|
591
|
-
textEn: `Subagent ${conversationId} failed to start: ${err instanceof Error ? err.message : String(err)}`,
|
|
592
|
-
});
|
|
593
|
-
});
|
|
594
|
-
if (persist) {
|
|
595
|
-
this.pushProjects().catch(() => { });
|
|
596
|
-
}
|
|
597
|
-
this.emitConversations();
|
|
598
|
-
return conv.id;
|
|
599
634
|
}
|
|
600
635
|
getSubagentSnapshot(convId) {
|
|
601
636
|
const conv = this.convs.get(convId);
|
|
@@ -1292,8 +1327,11 @@ export class ClientSession {
|
|
|
1292
1327
|
},
|
|
1293
1328
|
stopSubagent: async (convId) => {
|
|
1294
1329
|
const conv = this.convs.get(convId);
|
|
1295
|
-
if (conv
|
|
1296
|
-
|
|
1330
|
+
if (conv) {
|
|
1331
|
+
conv.promptInFlight = false;
|
|
1332
|
+
if (conv.session.isStreaming || !conv.session.isIdle) {
|
|
1333
|
+
await this.interruptRun(conv, pick(this.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
|
|
1334
|
+
}
|
|
1297
1335
|
}
|
|
1298
1336
|
},
|
|
1299
1337
|
getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
|
|
@@ -1488,6 +1526,8 @@ export class ClientSession {
|
|
|
1488
1526
|
approvalRules;
|
|
1489
1527
|
/** 未发送输入框草稿(全局共享,<dataDir>/composer-drafts.json,按 sessionId 键入,见 server/composer-drafts.ts)。 */
|
|
1490
1528
|
drafts;
|
|
1529
|
+
/** 隔离沙盒项目管理器(全局共享,<dataDir>/sandboxes/registry.json)。 */
|
|
1530
|
+
sandboxes;
|
|
1491
1531
|
/** 内置标记服务(todo/notify/svc/rename 等,可全局/分组开关)。 */
|
|
1492
1532
|
markerSvc;
|
|
1493
1533
|
// -----------------------------------------------------------------------
|
|
@@ -1528,6 +1568,7 @@ export class ClientSession {
|
|
|
1528
1568
|
this.subagentTemplates = new SubagentTemplatesStore(join(stateStore.dataDir, "subagent-templates.json"));
|
|
1529
1569
|
this.approvalRules = new ApprovalRulesStore(join(stateStore.dataDir, "approval-rules.json"));
|
|
1530
1570
|
this.drafts = new ComposerDraftsStore(join(stateStore.dataDir, "composer-drafts.json"));
|
|
1571
|
+
this.sandboxes = new SandboxManager(stateStore.dataDir);
|
|
1531
1572
|
this.planManager = new PlanManager(join(stateStore.dataDir, "plans.json"));
|
|
1532
1573
|
this.markerSvc = new MarkerService({
|
|
1533
1574
|
clientId,
|
|
@@ -1722,7 +1763,7 @@ export class ClientSession {
|
|
|
1722
1763
|
if (!conv)
|
|
1723
1764
|
return;
|
|
1724
1765
|
try {
|
|
1725
|
-
if (conv
|
|
1766
|
+
if (this.conversationStreaming(conv) || !conv.session.isIdle) {
|
|
1726
1767
|
await this.interruptRun(conv, pick(this.getLang(), "目标模式停止角色对话", "Goal mode stopped a role conversation", "agent.role.stop"));
|
|
1727
1768
|
}
|
|
1728
1769
|
}
|
|
@@ -1730,6 +1771,19 @@ export class ClientSession {
|
|
|
1730
1771
|
// best-effort
|
|
1731
1772
|
}
|
|
1732
1773
|
},
|
|
1774
|
+
interruptMainConv: async (convId) => {
|
|
1775
|
+
const conv = this.convs.get(convId);
|
|
1776
|
+
if (!conv)
|
|
1777
|
+
return;
|
|
1778
|
+
try {
|
|
1779
|
+
if (this.conversationStreaming(conv) || !conv.session.isIdle) {
|
|
1780
|
+
await this.interruptRun(conv, pick(this.getLang(), "目标已设定,主对话当前运行已让位给目标执行者", "Goal set — stopped the main conversation's run so the goal executor can take over", "agent.goal.preempt_main"));
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
catch {
|
|
1784
|
+
// best-effort
|
|
1785
|
+
}
|
|
1786
|
+
},
|
|
1733
1787
|
dismissRoleAgent: async (convId) => {
|
|
1734
1788
|
const conv = this.convs.get(convId);
|
|
1735
1789
|
if (!conv)
|
|
@@ -1848,8 +1902,9 @@ export class ClientSession {
|
|
|
1848
1902
|
}
|
|
1849
1903
|
// 恢复本项目其他已被钉住的会话(重启后常驻运行列表,issue #433)
|
|
1850
1904
|
const pinnedPaths = cs.stateStore?.getPinnedSessions(cwd) ?? [];
|
|
1905
|
+
const maxOpenConversations = getMaxOpenConversations();
|
|
1851
1906
|
for (const p of pinnedPaths) {
|
|
1852
|
-
if (cs.convs.size >=
|
|
1907
|
+
if (cs.convs.size >= maxOpenConversations)
|
|
1853
1908
|
break;
|
|
1854
1909
|
const normP = normalizePathKey(p);
|
|
1855
1910
|
const alreadyOpen = [...cs.convs.values()].some((c) => c.session.sessionFile && normalizePathKey(c.session.sessionFile) === normP);
|
|
@@ -1957,6 +2012,13 @@ export class ClientSession {
|
|
|
1957
2012
|
if (this.delegateModeOf(ownerId) && !this.planModeOf(ownerId)) {
|
|
1958
2013
|
out.push(DELEGATION_SYSTEM_PROMPT);
|
|
1959
2014
|
}
|
|
2015
|
+
const activeSandbox = this.sandboxes.getByCwd(effectiveCwd);
|
|
2016
|
+
if (activeSandbox) {
|
|
2017
|
+
out.push(`[Sandbox Isolation Mode] You are operating inside an isolated sandbox workspace "${activeSandbox.name}" at "${activeSandbox.path}".` +
|
|
2018
|
+
(activeSandbox.sourcePath
|
|
2019
|
+
? ` This sandbox is an isolated copy of "${activeSandbox.sourcePath}". NEVER read from or modify "${activeSandbox.sourcePath}" directly; make all changes exclusively within the current sandbox directory "${activeSandbox.path}".`
|
|
2020
|
+
: ` Keep all file writes, edits, and command side effects strictly inside "${activeSandbox.path}".`));
|
|
2021
|
+
}
|
|
1960
2022
|
const realCwd = restoreWorkspaceUriFromSessionDir(effectiveCwd);
|
|
1961
2023
|
if (isRemoteWorkspaceUri(realCwd)) {
|
|
1962
2024
|
// 远程 SSH 工作区:明确告知 AI 当前处于远程主机以及所有工具已透明桥接至远端,
|
|
@@ -2128,7 +2190,9 @@ export class ClientSession {
|
|
|
2128
2190
|
// 避免 SDK findInitialModel 在无 model 时回退到内置硬编码默认(如 deepseek-v4-pro):
|
|
2129
2191
|
let sessionModel = initialModel;
|
|
2130
2192
|
if (!sessionModel) {
|
|
2131
|
-
const isBlank = sessionManager.
|
|
2193
|
+
const isBlank = typeof sessionManager.getEntries === "function"
|
|
2194
|
+
? !sessionManager.getEntries().some((e) => e.type === "message")
|
|
2195
|
+
: sessionManager.buildSessionContext().messages.length === 0;
|
|
2132
2196
|
if (isBlank) {
|
|
2133
2197
|
const savedModelId = this.stateStore.getProjectModel(this.clientId, effectiveCwd) ?? this.stateStore.getDefaultModel();
|
|
2134
2198
|
if (savedModelId) {
|
|
@@ -2193,6 +2257,13 @@ export class ClientSession {
|
|
|
2193
2257
|
"workspace-write-never", () => this.getLang()),
|
|
2194
2258
|
...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang(), {
|
|
2195
2259
|
checkSafety: (cmd) => {
|
|
2260
|
+
// 沙盒硬围栏:禁止引用源项目路径或跳出沙盒根。
|
|
2261
|
+
const activeSbx = this.sandboxes.getByCwd(effectiveCwd);
|
|
2262
|
+
if (activeSbx) {
|
|
2263
|
+
const sbxDenied = evaluateSandboxJail(activeSbx, "bash", { command: cmd }, effectiveCwd);
|
|
2264
|
+
if (sbxDenied)
|
|
2265
|
+
return { blocked: true, reason: sbxDenied.reason };
|
|
2266
|
+
}
|
|
2196
2267
|
// 计划模式:终端只放行只读命令(常驻终端也走这条,与 bash 覆盖同口径)。
|
|
2197
2268
|
if (this.planModeOf(ownerId)) {
|
|
2198
2269
|
const denied = planModeDenial("bash", { command: cmd });
|
|
@@ -2226,9 +2297,9 @@ export class ClientSession {
|
|
|
2226
2297
|
// tool-overrides.ts);它们改在会话建好后由 installToolOverrides 注入。
|
|
2227
2298
|
// 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置;带权限沙箱拦截与人机协同)。
|
|
2228
2299
|
// 目标审查闸门包在最外层:审查回合的理由最贴合此刻(跟模型说「这是审查回合」)。
|
|
2229
|
-
withGoalReviewGate(withDelegationGate(withPlanModeGate(wrapEditSoftToolWithPermission(makeEditSoftTool(effectiveCwd, () => this.getLang()), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
2300
|
+
withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(wrapEditSoftToolWithPermission(makeEditSoftTool(effectiveCwd, () => this.getLang()), effectiveCwd, () => (ownerId ? this.convs.get(ownerId)?.permissionPreset : undefined) ??
|
|
2230
2301
|
this.settingsSvc.current.defaultPermissionPreset ??
|
|
2231
|
-
"workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category), () => ownerId, () => this.approvalRules.list()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()),
|
|
2302
|
+
"workspace-write-never", () => this.roots, () => this.getLang(), (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category), () => ownerId, () => this.approvalRules.list()), () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang()),
|
|
2232
2303
|
// 插件注册的 AI 工具(创建时刻的实时快照,已按 disabledPluginTools 过滤;
|
|
2233
2304
|
// 后续注册经 refreshPluginTools 动态补入已有会话)。
|
|
2234
2305
|
// 子代理模板带非空扩展白名单时不注入:插件/MCP 工具没有 SDK extensionKey
|
|
@@ -2326,11 +2397,26 @@ export class ClientSession {
|
|
|
2326
2397
|
makePatchTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
|
|
2327
2398
|
// 原生语言服务器工具(lsp,定义跳转/引用/悬停/诊断)。
|
|
2328
2399
|
makeLspTool({ cwd: effectiveCwd, ownerId, lang: () => this.getLang() }),
|
|
2400
|
+
// MCP 服务器检测与安装管理工具(mcp_manage:list/check/install/remove/reload)。
|
|
2401
|
+
makeMcpManageTool(this.mcpManageToolHost(effectiveCwd), () => this.getLang()),
|
|
2402
|
+
// 隔离沙盒项目管理工具(sandbox:list/create/diff/reset/persist/promote/apply_to_source/destroy)。
|
|
2403
|
+
makeSandboxTool({
|
|
2404
|
+
sandboxes: this.sandboxes,
|
|
2405
|
+
getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
|
|
2406
|
+
setCwd: (newCwd) => this.setCwd(newCwd),
|
|
2407
|
+
onSandboxesChanged: async () => {
|
|
2408
|
+
this.invalidateProjectsCache();
|
|
2409
|
+
await this.pushProjects();
|
|
2410
|
+
this.flushSnapshot();
|
|
2411
|
+
},
|
|
2412
|
+
askApproval: (toolCallId, toolName, params, reason, reasonEn, convId, category) => this.askApproval(toolCallId, toolName, params, reason, reasonEn, convId, category),
|
|
2413
|
+
getConversationId: () => ownerId,
|
|
2414
|
+
}, () => this.getLang()),
|
|
2329
2415
|
].map((t) =>
|
|
2330
2416
|
// 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
|
|
2331
2417
|
// 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
|
|
2332
2418
|
// 计划/审查者闸门同口径不在覆盖面,见 goal-review-gate.ts 头注)。
|
|
2333
|
-
withGoalReviewGate(withDelegationGate(withPlanModeGate(t, () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
|
|
2419
|
+
withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(t, () => this.sandboxes.getByCwd(effectiveCwd), () => effectiveCwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang())),
|
|
2334
2420
|
});
|
|
2335
2421
|
// 桥接工具归属锚点:SDK 会话对象在本 runtime 生命周期内稳定,过户只搬对话
|
|
2336
2422
|
// 不改它(见 ClientSession.findConversationHome)。
|
|
@@ -3418,6 +3504,7 @@ export class ClientSession {
|
|
|
3418
3504
|
// 本轮结束且无后续重试:任何残留占位都是过期的(会话替换、
|
|
3419
3505
|
// 结束信号丢失等),清掉,否则横幅会卡住不消失。
|
|
3420
3506
|
conv.retryState = null;
|
|
3507
|
+
conv.promptInFlight = false;
|
|
3421
3508
|
}
|
|
3422
3509
|
// 轨迹事件:本轮结束(放最前——aborted 中断路径也会 break,
|
|
3423
3510
|
// 轨迹里必须留下「已停止」而不是凭空消失)。
|
|
@@ -3577,6 +3664,8 @@ export class ClientSession {
|
|
|
3577
3664
|
break;
|
|
3578
3665
|
}
|
|
3579
3666
|
case "agent_start": {
|
|
3667
|
+
// 本轮已正式进入流式(session.isStreaming=true),清除首轮启动期投递标记(#589)。
|
|
3668
|
+
conv.promptInFlight = false;
|
|
3580
3669
|
// 轨迹事件:新一轮开始(任务文本由 prompt() 暂存;steer/内部续跑
|
|
3581
3670
|
// 无暂存时省略,插件回退为「继续执行」)。
|
|
3582
3671
|
const task = conv.pendingTask;
|
|
@@ -3923,6 +4012,7 @@ export class ClientSession {
|
|
|
3923
4012
|
// 必须**恒存在**(不能只在 true 时展开):转正后它由 true→false,而增量快照是
|
|
3924
4013
|
// `{...ui, ...d.state}` 浅合并,缺字段会把 true 残留下来。
|
|
3925
4014
|
isEphemeral: !!this.conv?.isEphemeral,
|
|
4015
|
+
sandbox: this.sandboxes?.getByCwd(this.cwd) ?? null,
|
|
3926
4016
|
rev,
|
|
3927
4017
|
streamingMessage,
|
|
3928
4018
|
isStreaming: this.session.isStreaming,
|
|
@@ -5882,6 +5972,80 @@ export class ClientSession {
|
|
|
5882
5972
|
projectConfigPath: data.projectPath,
|
|
5883
5973
|
});
|
|
5884
5974
|
}
|
|
5975
|
+
/** 构造 mcp_manage 工具宿主:安装/删除/重载后同步本客户端会话工具表与设置面板。 */
|
|
5976
|
+
mcpManageToolHost(cwd) {
|
|
5977
|
+
return {
|
|
5978
|
+
listServers: () => listAllMcpServers({
|
|
5979
|
+
agentDir: this.agentDir,
|
|
5980
|
+
cwd,
|
|
5981
|
+
dataDir: this.stateStore.dataDir,
|
|
5982
|
+
bridge: ClientSession.mcpBridge ?? undefined,
|
|
5983
|
+
}),
|
|
5984
|
+
checkServer: (query) => checkMcpServer({
|
|
5985
|
+
agentDir: this.agentDir,
|
|
5986
|
+
cwd,
|
|
5987
|
+
dataDir: this.stateStore.dataDir,
|
|
5988
|
+
bridge: ClientSession.mcpBridge ?? undefined,
|
|
5989
|
+
query,
|
|
5990
|
+
}),
|
|
5991
|
+
installServer: async (spec) => {
|
|
5992
|
+
const res = await installMcpServer({
|
|
5993
|
+
agentDir: this.agentDir,
|
|
5994
|
+
cwd,
|
|
5995
|
+
dataDir: this.stateStore.dataDir,
|
|
5996
|
+
bridge: ClientSession.mcpBridge ?? undefined,
|
|
5997
|
+
spec,
|
|
5998
|
+
});
|
|
5999
|
+
if (res.ok) {
|
|
6000
|
+
this.refreshPluginTools();
|
|
6001
|
+
this.broadcastMcpServers();
|
|
6002
|
+
this.pushSettings();
|
|
6003
|
+
}
|
|
6004
|
+
return res;
|
|
6005
|
+
},
|
|
6006
|
+
removeServer: async (name, scope) => {
|
|
6007
|
+
const targetScope = scope ??
|
|
6008
|
+
(checkMcpServer({
|
|
6009
|
+
agentDir: this.agentDir,
|
|
6010
|
+
cwd,
|
|
6011
|
+
dataDir: this.stateStore.dataDir,
|
|
6012
|
+
bridge: ClientSession.mcpBridge ?? undefined,
|
|
6013
|
+
query: name,
|
|
6014
|
+
}).server?.scope ||
|
|
6015
|
+
"project");
|
|
6016
|
+
const res = deleteMcpServerFile({
|
|
6017
|
+
agentDir: this.agentDir,
|
|
6018
|
+
cwd,
|
|
6019
|
+
dataDir: this.stateStore.dataDir,
|
|
6020
|
+
name,
|
|
6021
|
+
scope: targetScope,
|
|
6022
|
+
});
|
|
6023
|
+
if (res.ok) {
|
|
6024
|
+
if (ClientSession.mcpBridge) {
|
|
6025
|
+
await ClientSession.mcpBridge.reload();
|
|
6026
|
+
}
|
|
6027
|
+
this.refreshPluginTools();
|
|
6028
|
+
this.broadcastMcpServers();
|
|
6029
|
+
this.pushSettings();
|
|
6030
|
+
}
|
|
6031
|
+
return res;
|
|
6032
|
+
},
|
|
6033
|
+
reloadServers: async () => {
|
|
6034
|
+
if (ClientSession.mcpBridge) {
|
|
6035
|
+
await ClientSession.mcpBridge.reload();
|
|
6036
|
+
}
|
|
6037
|
+
this.refreshPluginTools();
|
|
6038
|
+
this.broadcastMcpServers();
|
|
6039
|
+
this.pushSettings();
|
|
6040
|
+
return listAllMcpServers({
|
|
6041
|
+
agentDir: this.agentDir,
|
|
6042
|
+
cwd,
|
|
6043
|
+
dataDir: this.stateStore.dataDir,
|
|
6044
|
+
bridge: ClientSession.mcpBridge ?? undefined,
|
|
6045
|
+
});
|
|
6046
|
+
},
|
|
6047
|
+
};
|
|
6048
|
+
}
|
|
5885
6049
|
/** 从技能市场安装技能到全局 (~/.pi/agent/skills) 或当前项目 (.pi/skills) */
|
|
5886
6050
|
async installSkill(name, scope, content) {
|
|
5887
6051
|
const cleanName = name.trim();
|
|
@@ -6070,7 +6234,7 @@ export class ClientSession {
|
|
|
6070
6234
|
};
|
|
6071
6235
|
// 写/编的权限沙箱包装:同一个函数,有扩展同名工具时把它的定义当基底(末参)。
|
|
6072
6236
|
// 目标审查闸门包在**最外层**(权限沙箱之前):审查回合只读核实,写类直接拒。
|
|
6073
|
-
const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(def, () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
|
|
6237
|
+
const planGate = (def) => withGoalReviewGate(withDelegationGate(withPlanModeGate(withSandboxJailGate(def, () => this.sandboxes.getByCwd(cwd), () => cwd, () => this.getLang()), () => this.planModeOf(ownerId), () => this.getLang()), () => this.delegateModeOf(ownerId), () => this.getLang()), () => this.goalReviewTurnOf(ownerId), () => this.getLang());
|
|
6074
6238
|
const composeWrite = (base) => planGate(wrapWriteToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
|
|
6075
6239
|
const composeEdit = (base) => planGate(wrapEditToolWithPermission(cwd, currentPermission, () => this.roots, () => this.getLang(), approve, () => ownerId, () => this.approvalRules.list(), base));
|
|
6076
6240
|
const remoteOps = createRemoteSdkOperations(cwd);
|
|
@@ -7860,12 +8024,13 @@ export class ClientSession {
|
|
|
7860
8024
|
// (inMemory 后台任务,不占位)。临时会话也不占名额。
|
|
7861
8025
|
if (!ephemeral) {
|
|
7862
8026
|
const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd && !c.isSubagent && !c.isEphemeral).length;
|
|
7863
|
-
|
|
8027
|
+
const maxOpenConversations = getMaxOpenConversations();
|
|
8028
|
+
if (openInProject >= maxOpenConversations) {
|
|
7864
8029
|
this.emit({
|
|
7865
8030
|
type: "notice",
|
|
7866
8031
|
level: "warning",
|
|
7867
|
-
text: `当前项目运行的对话已达上限(${
|
|
7868
|
-
textEn: `This project already has the max open conversations (${
|
|
8032
|
+
text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
|
|
8033
|
+
textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
|
|
7869
8034
|
});
|
|
7870
8035
|
return false;
|
|
7871
8036
|
}
|
|
@@ -7883,6 +8048,16 @@ export class ClientSession {
|
|
|
7883
8048
|
const conversationId = this.nextConversationId();
|
|
7884
8049
|
const terminals = this.makeTerminalManager(conversationId, this.cwd);
|
|
7885
8050
|
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, this.cwd);
|
|
8051
|
+
this.emit({
|
|
8052
|
+
type: "transition_progress",
|
|
8053
|
+
kind: "new_chat",
|
|
8054
|
+
target: this.cwd,
|
|
8055
|
+
phase: "runtime",
|
|
8056
|
+
progress: 45,
|
|
8057
|
+
text: "正在初始化新对话环境…",
|
|
8058
|
+
textEn: "Initializing new chat runtime…",
|
|
8059
|
+
});
|
|
8060
|
+
await new Promise((r) => setImmediate(r));
|
|
7886
8061
|
let sessionManager;
|
|
7887
8062
|
if (ephemeral) {
|
|
7888
8063
|
sessionManager = SessionManager.inMemory(sessionBaseDir);
|
|
@@ -7976,9 +8151,27 @@ export class ClientSession {
|
|
|
7976
8151
|
// 新对话即当前打开 → 插件重拉(轨迹视图跟随)。
|
|
7977
8152
|
this.notifyConversationChanged();
|
|
7978
8153
|
this.pushSettings();
|
|
8154
|
+
this.emit({
|
|
8155
|
+
type: "transition_progress",
|
|
8156
|
+
kind: "new_chat",
|
|
8157
|
+
target: this.cwd,
|
|
8158
|
+
phase: "done",
|
|
8159
|
+
progress: 100,
|
|
8160
|
+
text: "新对话已就绪",
|
|
8161
|
+
textEn: "New chat ready",
|
|
8162
|
+
});
|
|
7979
8163
|
ready = true;
|
|
7980
8164
|
}
|
|
7981
8165
|
catch (err) {
|
|
8166
|
+
this.emit({
|
|
8167
|
+
type: "transition_progress",
|
|
8168
|
+
kind: "new_chat",
|
|
8169
|
+
target: this.cwd,
|
|
8170
|
+
phase: "error",
|
|
8171
|
+
progress: 100,
|
|
8172
|
+
text: `新建对话失败:${err.message}`,
|
|
8173
|
+
textEn: `Failed to create chat: ${err.message}`,
|
|
8174
|
+
});
|
|
7982
8175
|
this.emit({
|
|
7983
8176
|
type: "notice",
|
|
7984
8177
|
level: "error",
|
|
@@ -8185,15 +8378,49 @@ export class ClientSession {
|
|
|
8185
8378
|
this.emit(n);
|
|
8186
8379
|
return repair;
|
|
8187
8380
|
}
|
|
8381
|
+
/**
|
|
8382
|
+
* 从已打开并校准叶子节点的 SessionManager 中提取尾部预览消息与总条数。
|
|
8383
|
+
* 在耗时的 createAgentSessionRuntime(扫扩展/技能)开始前先行流式推给浏览器,
|
|
8384
|
+
* 让切换目录/历史会话在几十毫秒内就能在屏幕上流式呈现对话内容。
|
|
8385
|
+
*/
|
|
8386
|
+
extractTranscriptPreview(manager, maxPreview = 16) {
|
|
8387
|
+
try {
|
|
8388
|
+
const branch = manager.getBranch();
|
|
8389
|
+
const msgEntries = [];
|
|
8390
|
+
for (const e of branch) {
|
|
8391
|
+
if (e.type === "message") {
|
|
8392
|
+
const m = e.message;
|
|
8393
|
+
if (m && m.role !== "system") {
|
|
8394
|
+
msgEntries.push(m);
|
|
8395
|
+
}
|
|
8396
|
+
}
|
|
8397
|
+
}
|
|
8398
|
+
const totalMessages = msgEntries.length;
|
|
8399
|
+
const tail = msgEntries.slice(-maxPreview);
|
|
8400
|
+
const startOffset = totalMessages - tail.length;
|
|
8401
|
+
const previewMessages = [];
|
|
8402
|
+
for (let i = 0; i < tail.length; i++) {
|
|
8403
|
+
const ui = serializeMessage(tail[i], startOffset + i + 1);
|
|
8404
|
+
if (ui)
|
|
8405
|
+
previewMessages.push(ui);
|
|
8406
|
+
}
|
|
8407
|
+
return { totalMessages, previewMessages };
|
|
8408
|
+
}
|
|
8409
|
+
catch {
|
|
8410
|
+
return { totalMessages: 0, previewMessages: [] };
|
|
8411
|
+
}
|
|
8412
|
+
}
|
|
8188
8413
|
/**
|
|
8189
8414
|
* #235:manager+runtime 一起建,链损坏报错则修最近文件后重试一次。
|
|
8190
8415
|
* SessionManager.open 本身不走 parent 链(真正死循环的是 runtime 初始化里的
|
|
8191
8416
|
* getBranch),所以重试必须把两步都包进来;修完用全新 manager 重读。
|
|
8192
8417
|
*/
|
|
8193
|
-
async openManagerAndRuntime(makeManager, makeRuntime, locateFile) {
|
|
8418
|
+
async openManagerAndRuntime(makeManager, makeRuntime, locateFile, onTranscriptLoaded) {
|
|
8194
8419
|
try {
|
|
8195
8420
|
const manager = makeManager();
|
|
8196
8421
|
calibrateSessionLeaf(manager);
|
|
8422
|
+
if (onTranscriptLoaded)
|
|
8423
|
+
await onTranscriptLoaded(manager);
|
|
8197
8424
|
const runtime = await makeRuntime(manager);
|
|
8198
8425
|
return { manager, runtime, repair: null };
|
|
8199
8426
|
}
|
|
@@ -8206,6 +8433,8 @@ export class ClientSession {
|
|
|
8206
8433
|
throw err;
|
|
8207
8434
|
const manager = makeManager();
|
|
8208
8435
|
calibrateSessionLeaf(manager);
|
|
8436
|
+
if (onTranscriptLoaded)
|
|
8437
|
+
await onTranscriptLoaded(manager);
|
|
8209
8438
|
const runtime = await makeRuntime(manager);
|
|
8210
8439
|
return { manager, runtime, repair };
|
|
8211
8440
|
}
|
|
@@ -8951,9 +9180,10 @@ export class ClientSession {
|
|
|
8951
9180
|
static sessionInfosCache = new Map();
|
|
8952
9181
|
static sessionInfosInFlight = new Map();
|
|
8953
9182
|
static SESSION_INFO_CACHE_TTL = 30_000;
|
|
8954
|
-
async loadSessionInfos() {
|
|
9183
|
+
async loadSessionInfos(forCwd) {
|
|
9184
|
+
const targetCwd = forCwd ?? this.cwd;
|
|
8955
9185
|
const now = Date.now();
|
|
8956
|
-
const cwdKey = normalizePathKey(
|
|
9186
|
+
const cwdKey = normalizePathKey(targetCwd);
|
|
8957
9187
|
const c = ClientSession.sessionInfosCache.get(cwdKey);
|
|
8958
9188
|
if (c && now - c.at < ClientSession.SESSION_INFO_CACHE_TTL) {
|
|
8959
9189
|
return c.infos;
|
|
@@ -8961,7 +9191,7 @@ export class ClientSession {
|
|
|
8961
9191
|
const inFlight = ClientSession.sessionInfosInFlight.get(cwdKey);
|
|
8962
9192
|
if (inFlight)
|
|
8963
9193
|
return inFlight;
|
|
8964
|
-
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir,
|
|
9194
|
+
const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
|
|
8965
9195
|
const run = (async () => {
|
|
8966
9196
|
try {
|
|
8967
9197
|
const sessionDir = piSessionsRoot()
|
|
@@ -9047,10 +9277,14 @@ export class ClientSession {
|
|
|
9047
9277
|
this.sessionsRequested = true;
|
|
9048
9278
|
await this.pushSessions();
|
|
9049
9279
|
}
|
|
9050
|
-
/**
|
|
9051
|
-
*
|
|
9280
|
+
/** 切项目时的会话列表刷新:sessionInfosCache 已按 cwdKey 隔离(30s TTL),
|
|
9281
|
+
* 若刚刚在 setCwd 并行预热过(<2s 内)则直接复用预热结果推送,不再清空重扫。 */
|
|
9052
9282
|
refreshSessionsOnSwitch() {
|
|
9053
|
-
this.
|
|
9283
|
+
const cwdKey = normalizePathKey(this.cwd);
|
|
9284
|
+
const cached = ClientSession.sessionInfosCache.get(cwdKey);
|
|
9285
|
+
if (!cached || Date.now() - cached.at > 2_000) {
|
|
9286
|
+
ClientSession.sessionInfosCache.delete(cwdKey);
|
|
9287
|
+
}
|
|
9054
9288
|
if (this.sessionsRequested)
|
|
9055
9289
|
void this.refreshSessions();
|
|
9056
9290
|
}
|
|
@@ -9098,8 +9332,13 @@ export class ClientSession {
|
|
|
9098
9332
|
this.emit({ type: "sessions", sessions: [] });
|
|
9099
9333
|
}
|
|
9100
9334
|
}
|
|
9101
|
-
/** Remove an entry from the client's recent-project list (UI state only). */
|
|
9335
|
+
/** Remove an entry from the client's recent-project list (UI state only, or destroy if sandbox). */
|
|
9102
9336
|
async removeProject(path) {
|
|
9337
|
+
const sbx = this.sandboxes.get(path) ?? this.sandboxes.getByCwd(path);
|
|
9338
|
+
if (sbx) {
|
|
9339
|
+
await this.destroySandbox(sbx.path);
|
|
9340
|
+
return;
|
|
9341
|
+
}
|
|
9103
9342
|
this.stateStore.removeProject(this.clientId, path);
|
|
9104
9343
|
this.invalidateProjectsCache();
|
|
9105
9344
|
await this.pushProjects();
|
|
@@ -10041,9 +10280,38 @@ export class ClientSession {
|
|
|
10041
10280
|
}
|
|
10042
10281
|
// #235:先修后开——坏转录到 open 后的 getBranch 会死循环,修完再读。
|
|
10043
10282
|
// 单文件预扫描,健康文件只多一次小读;修过即弹提示(含压缩被打断与分支拓扑纠偏)。
|
|
10283
|
+
this.emit({
|
|
10284
|
+
type: "transition_progress",
|
|
10285
|
+
kind: "session",
|
|
10286
|
+
target: targetPath,
|
|
10287
|
+
phase: "fs",
|
|
10288
|
+
progress: 28,
|
|
10289
|
+
text: "正在读取历史会话记录…",
|
|
10290
|
+
textEn: "Reading session transcript…",
|
|
10291
|
+
});
|
|
10292
|
+
await new Promise((r) => setImmediate(r));
|
|
10044
10293
|
this.repairTranscriptFileBeforeOpen(targetPath);
|
|
10045
10294
|
const sessionManager = SessionManager.open(targetPath);
|
|
10046
10295
|
calibrateSessionLeaf(sessionManager);
|
|
10296
|
+
{
|
|
10297
|
+
const { totalMessages, previewMessages } = this.extractTranscriptPreview(sessionManager, 16);
|
|
10298
|
+
this.emit({
|
|
10299
|
+
type: "transition_progress",
|
|
10300
|
+
kind: "session",
|
|
10301
|
+
target: targetPath,
|
|
10302
|
+
phase: "transcript",
|
|
10303
|
+
progress: 62,
|
|
10304
|
+
text: totalMessages > 0
|
|
10305
|
+
? `已流式载入会话记录(${totalMessages} 条消息),正在挂载智能体环境…`
|
|
10306
|
+
: "会话记录已就绪,正在挂载智能体环境…",
|
|
10307
|
+
textEn: totalMessages > 0
|
|
10308
|
+
? `Streamed session transcript (${totalMessages} messages), mounting agent runtime…`
|
|
10309
|
+
: "Transcript ready, mounting agent runtime…",
|
|
10310
|
+
totalMessages,
|
|
10311
|
+
...(previewMessages.length > 0 ? { previewMessages } : {}),
|
|
10312
|
+
});
|
|
10313
|
+
await new Promise((r) => setImmediate(r));
|
|
10314
|
+
}
|
|
10047
10315
|
const rawSessionCwd = sessionManager.getCwd();
|
|
10048
10316
|
const targetCwd = restoreWorkspaceUriFromSessionDir(rawSessionCwd);
|
|
10049
10317
|
const runtimeCwd = resolveWorkspaceSessionDir(this.stateStore?.dataDir, targetCwd);
|
|
@@ -10061,7 +10329,8 @@ export class ClientSession {
|
|
|
10061
10329
|
const openInProject = [...this.convs.values()].filter((c) => c.cwd === targetCwd && !c.isSubagent && !c.isEphemeral).length +
|
|
10062
10330
|
1 -
|
|
10063
10331
|
(displaced?.cwd === targetCwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
|
|
10064
|
-
|
|
10332
|
+
const maxOpenConversations = getMaxOpenConversations();
|
|
10333
|
+
if (openInProject > maxOpenConversations) {
|
|
10065
10334
|
// displaceActive() may have promoted a streaming conversation into the
|
|
10066
10335
|
// running list. Roll that presentation-only mutation back because no
|
|
10067
10336
|
// switch will take place.
|
|
@@ -10070,11 +10339,20 @@ export class ClientSession {
|
|
|
10070
10339
|
await openedRuntime.dispose();
|
|
10071
10340
|
openedRuntime = null;
|
|
10072
10341
|
openedTerminals = null;
|
|
10342
|
+
this.emit({
|
|
10343
|
+
type: "transition_progress",
|
|
10344
|
+
kind: "session",
|
|
10345
|
+
target: targetPath,
|
|
10346
|
+
phase: "error",
|
|
10347
|
+
progress: 100,
|
|
10348
|
+
text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
|
|
10349
|
+
textEn: `Max open conversations (${maxOpenConversations}) reached`,
|
|
10350
|
+
});
|
|
10073
10351
|
this.emit({
|
|
10074
10352
|
type: "notice",
|
|
10075
10353
|
level: "warning",
|
|
10076
|
-
text: `当前项目运行的对话已达上限(${
|
|
10077
|
-
textEn: `This project already has the max open conversations (${
|
|
10354
|
+
text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
|
|
10355
|
+
textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
|
|
10078
10356
|
});
|
|
10079
10357
|
return;
|
|
10080
10358
|
}
|
|
@@ -10102,8 +10380,24 @@ export class ClientSession {
|
|
|
10102
10380
|
// 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
|
|
10103
10381
|
// 历史列表/命令目录/最近项目)必须跟着切,否则 UI 停在旧项目。
|
|
10104
10382
|
this.applyCwdSideEffects(targetCwd);
|
|
10105
|
-
|
|
10106
|
-
|
|
10383
|
+
// 模型与 key 恢复走后台异步(带代际守卫),不阻塞历史会话快照首帧送达
|
|
10384
|
+
{
|
|
10385
|
+
const convId = this.activeId;
|
|
10386
|
+
void (async () => {
|
|
10387
|
+
try {
|
|
10388
|
+
await this.restoreProjectProviderKeysForCwd(targetCwd);
|
|
10389
|
+
if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
|
|
10390
|
+
return;
|
|
10391
|
+
await this.restoreProjectModelForCwd(targetCwd);
|
|
10392
|
+
if (this.disposed || this.activeId !== convId || this.cwd !== targetCwd)
|
|
10393
|
+
return;
|
|
10394
|
+
this.flushSnapshot();
|
|
10395
|
+
}
|
|
10396
|
+
catch {
|
|
10397
|
+
/* 静默:恢复失败保持会话默认 */
|
|
10398
|
+
}
|
|
10399
|
+
})();
|
|
10400
|
+
}
|
|
10107
10401
|
this.conv.lastActiveAt = Date.now();
|
|
10108
10402
|
this.webUi.refresh();
|
|
10109
10403
|
this.emitConversations();
|
|
@@ -10114,11 +10408,29 @@ export class ClientSession {
|
|
|
10114
10408
|
// 切历史会话成功 → 插件重拉(轨迹视图立即显示该会话时间线)。
|
|
10115
10409
|
this.notifyConversationChanged();
|
|
10116
10410
|
this.pushSettings();
|
|
10411
|
+
this.emit({
|
|
10412
|
+
type: "transition_progress",
|
|
10413
|
+
kind: "session",
|
|
10414
|
+
target: targetPath,
|
|
10415
|
+
phase: "done",
|
|
10416
|
+
progress: 100,
|
|
10417
|
+
text: "会话加载完成",
|
|
10418
|
+
textEn: "Session loaded",
|
|
10419
|
+
});
|
|
10117
10420
|
}
|
|
10118
10421
|
catch (err) {
|
|
10119
10422
|
openedTerminals?.killAll();
|
|
10120
10423
|
if (openedRuntime)
|
|
10121
10424
|
await openedRuntime.dispose().catch(() => { });
|
|
10425
|
+
this.emit({
|
|
10426
|
+
type: "transition_progress",
|
|
10427
|
+
kind: "session",
|
|
10428
|
+
target: path || sessionId || "",
|
|
10429
|
+
phase: "error",
|
|
10430
|
+
progress: 100,
|
|
10431
|
+
text: `切换会话失败:${err.message}`,
|
|
10432
|
+
textEn: `Failed to switch session: ${err.message}`,
|
|
10433
|
+
});
|
|
10122
10434
|
this.emit({
|
|
10123
10435
|
type: "notice",
|
|
10124
10436
|
level: "error",
|
|
@@ -10246,7 +10558,8 @@ export class ClientSession {
|
|
|
10246
10558
|
const openInProject = [...this.convs.values()].filter((c) => c.cwd === targetConv.cwd && !c.isSubagent && !c.isEphemeral).length +
|
|
10247
10559
|
1 -
|
|
10248
10560
|
(displaced?.cwd === targetConv.cwd && !displaced?.isSubagent && !displaced?.isEphemeral ? 1 : 0);
|
|
10249
|
-
|
|
10561
|
+
const maxOpenConversations = getMaxOpenConversations();
|
|
10562
|
+
if (openInProject > maxOpenConversations) {
|
|
10250
10563
|
// displaceActive() 可能只是把旧对话标成后台展示(presentation-only);
|
|
10251
10564
|
// 没有切换发生时回滚该标记,新 fork 的 runtime/终端直接释放。
|
|
10252
10565
|
this.conv.listed = oldListed;
|
|
@@ -10255,8 +10568,8 @@ export class ClientSession {
|
|
|
10255
10568
|
this.emit({
|
|
10256
10569
|
type: "notice",
|
|
10257
10570
|
level: "warning",
|
|
10258
|
-
text: `当前项目运行的对话已达上限(${
|
|
10259
|
-
textEn: `This project already has the max open conversations (${
|
|
10571
|
+
text: `当前项目运行的对话已达上限(${maxOpenConversations} 个),请先移出不需要的对话(打开后离开不继续对话即移出;钉住的对话需先取消钉住)`,
|
|
10572
|
+
textEn: `This project already has the max open conversations (${maxOpenConversations}). Open one and leave it (without continuing) to remove it from the list; pinned chats must be unpinned first.`,
|
|
10260
10573
|
});
|
|
10261
10574
|
return;
|
|
10262
10575
|
}
|
|
@@ -10524,9 +10837,12 @@ export class ClientSession {
|
|
|
10524
10837
|
async pushProjects() {
|
|
10525
10838
|
const now = Date.now();
|
|
10526
10839
|
const cached = ClientSession.projectsCache;
|
|
10527
|
-
// TTL
|
|
10528
|
-
|
|
10529
|
-
|
|
10840
|
+
// TTL 命中(或已建立过项目缓存):直接把当前 cwd 合并重排并续期,
|
|
10841
|
+
// 避免切换工作区时因为刚好跨过 60s TTL 而触发全盘 30 个会话子目录重扫。
|
|
10842
|
+
if (cached) {
|
|
10843
|
+
const updated = this.withCurrentCwd(cached.projects, now);
|
|
10844
|
+
ClientSession.projectsCache = { at: now, projects: updated };
|
|
10845
|
+
this.emit({ type: "projects", projects: updated });
|
|
10530
10846
|
return;
|
|
10531
10847
|
}
|
|
10532
10848
|
// 已有扫描在跑:搭车等它,不要并发扫两遍盘。
|
|
@@ -10574,15 +10890,41 @@ export class ClientSession {
|
|
|
10574
10890
|
withCurrentCwd(projects, now) {
|
|
10575
10891
|
const currentKey = normalizePathKey(this.cwd);
|
|
10576
10892
|
const removedKeys = new Set(this.stateStore.getRemovedProjects(this.clientId).map(normalizePathKey));
|
|
10893
|
+
// 过滤掉已销毁(不在沙盒注册表且目录位于 sandboxesRoot 下)的残留沙盒条目
|
|
10894
|
+
const validProjects = projects.filter((p) => {
|
|
10895
|
+
if (isSameOrSubpath(p.path, this.sandboxes.sandboxesRoot)) {
|
|
10896
|
+
return Boolean(this.sandboxes.getByCwd(p.path));
|
|
10897
|
+
}
|
|
10898
|
+
return true;
|
|
10899
|
+
});
|
|
10900
|
+
let list;
|
|
10577
10901
|
if (removedKeys.has(currentKey)) {
|
|
10578
|
-
|
|
10902
|
+
list = validProjects;
|
|
10579
10903
|
}
|
|
10580
|
-
if (
|
|
10581
|
-
|
|
10904
|
+
else if (validProjects.some((p) => normalizePathKey(p.path) === currentKey)) {
|
|
10905
|
+
list = validProjects
|
|
10582
10906
|
.map((p) => (normalizePathKey(p.path) === currentKey && p.lastUsed < now ? { ...p, lastUsed: now } : p))
|
|
10583
10907
|
.sort((a, b) => b.lastUsed - a.lastUsed);
|
|
10584
10908
|
}
|
|
10585
|
-
|
|
10909
|
+
else {
|
|
10910
|
+
list = [{ path: this.cwd, lastUsed: now }, ...validProjects].slice(0, 20);
|
|
10911
|
+
}
|
|
10912
|
+
// 确保所有仍存活的注册沙盒也出现在列表里,并附带 sandbox 元数据
|
|
10913
|
+
const existingKeys = new Set(list.map((p) => normalizePathKey(p.path)));
|
|
10914
|
+
for (const sbx of this.sandboxes.list()) {
|
|
10915
|
+
const k = normalizePathKey(sbx.path);
|
|
10916
|
+
if (!existingKeys.has(k) && !removedKeys.has(k)) {
|
|
10917
|
+
list.push({ path: sbx.path, lastUsed: sbx.createdAt, sandbox: sbx });
|
|
10918
|
+
existingKeys.add(k);
|
|
10919
|
+
}
|
|
10920
|
+
}
|
|
10921
|
+
return list
|
|
10922
|
+
.map((p) => {
|
|
10923
|
+
const sbx = this.sandboxes.getByCwd(p.path);
|
|
10924
|
+
return sbx ? { ...p, sandbox: sbx } : p;
|
|
10925
|
+
})
|
|
10926
|
+
.sort((a, b) => b.lastUsed - a.lastUsed)
|
|
10927
|
+
.slice(0, 25);
|
|
10586
10928
|
}
|
|
10587
10929
|
/** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
|
|
10588
10930
|
invalidateProjectsCache() {
|
|
@@ -10824,14 +11166,24 @@ export class ClientSession {
|
|
|
10824
11166
|
}
|
|
10825
11167
|
else {
|
|
10826
11168
|
// 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
|
|
10827
|
-
//
|
|
11169
|
+
// 流式进度 + 快照,点击立即呈现阶段进度与转录预览;落地后再推完整全量。
|
|
10828
11170
|
this.emit({
|
|
10829
|
-
type: "
|
|
10830
|
-
|
|
10831
|
-
|
|
10832
|
-
|
|
11171
|
+
type: "transition_progress",
|
|
11172
|
+
kind: "cwd",
|
|
11173
|
+
target: abs,
|
|
11174
|
+
phase: "fs",
|
|
11175
|
+
progress: 28,
|
|
11176
|
+
text: `正在同步目录与检查最近会话:${abs}`,
|
|
11177
|
+
textEn: `Validating workspace & checking recent session: ${abs}`,
|
|
10833
11178
|
});
|
|
10834
11179
|
this.flushSnapshot();
|
|
11180
|
+
// 让出事件循环,确保首帧进度在同步磁盘扫描前真正发往浏览器
|
|
11181
|
+
await new Promise((r) => setImmediate(r));
|
|
11182
|
+
// 在耗时的 runtime 初始化期间,并行预热目标项目的会话列表缓存
|
|
11183
|
+
if (this.sessionsRequested) {
|
|
11184
|
+
ClientSession.sessionInfosCache.delete(normalizePathKey(abs));
|
|
11185
|
+
void this.loadSessionInfos(abs).catch(() => { });
|
|
11186
|
+
}
|
|
10835
11187
|
// First visit to this project: resume its most recent session —
|
|
10836
11188
|
// unless that transcript is still held on another client (#145):
|
|
10837
11189
|
// default-opening it would strand the tab on a conversation it
|
|
@@ -10862,7 +11214,25 @@ export class ClientSession {
|
|
|
10862
11214
|
cwd: sessionBaseDir,
|
|
10863
11215
|
agentDir: this.agentDir,
|
|
10864
11216
|
sessionManager: m,
|
|
10865
|
-
}), async () => (await SessionManager.list(sessionBaseDir))[0]?.path)
|
|
11217
|
+
}), async () => (await SessionManager.list(sessionBaseDir))[0]?.path, async (m) => {
|
|
11218
|
+
const { totalMessages, previewMessages } = this.extractTranscriptPreview(m, 16);
|
|
11219
|
+
this.emit({
|
|
11220
|
+
type: "transition_progress",
|
|
11221
|
+
kind: "cwd",
|
|
11222
|
+
target: abs,
|
|
11223
|
+
phase: "transcript",
|
|
11224
|
+
progress: 64,
|
|
11225
|
+
text: totalMessages > 0
|
|
11226
|
+
? `已流式载入最近会话(${totalMessages} 条消息),正在挂载智能体与工具…`
|
|
11227
|
+
: `工作区会话已就绪,正在挂载智能体与工具…`,
|
|
11228
|
+
textEn: totalMessages > 0
|
|
11229
|
+
? `Streamed recent session (${totalMessages} messages), mounting agent & tools…`
|
|
11230
|
+
: `Workspace session ready, mounting agent & tools…`,
|
|
11231
|
+
totalMessages,
|
|
11232
|
+
...(previewMessages.length > 0 ? { previewMessages } : {}),
|
|
11233
|
+
});
|
|
11234
|
+
await new Promise((r) => setImmediate(r));
|
|
11235
|
+
});
|
|
10866
11236
|
const newRuntime = opened.runtime;
|
|
10867
11237
|
if (opened.repair) {
|
|
10868
11238
|
for (const n of this.transcriptRepairNotices(opened.repair))
|
|
@@ -10929,8 +11299,11 @@ export class ClientSession {
|
|
|
10929
11299
|
// Skills / prompt templates are project-bound — refresh the catalog.
|
|
10930
11300
|
void this.pushSlashCommands();
|
|
10931
11301
|
this.emit({
|
|
10932
|
-
type: "
|
|
10933
|
-
|
|
11302
|
+
type: "transition_progress",
|
|
11303
|
+
kind: "cwd",
|
|
11304
|
+
target: abs,
|
|
11305
|
+
phase: "done",
|
|
11306
|
+
progress: 100,
|
|
10934
11307
|
text: `已切换到工作目录:${abs}`,
|
|
10935
11308
|
textEn: `Switched to directory: ${abs}`,
|
|
10936
11309
|
});
|
|
@@ -10939,6 +11312,15 @@ export class ClientSession {
|
|
|
10939
11312
|
this.pushSettings();
|
|
10940
11313
|
}
|
|
10941
11314
|
catch (err) {
|
|
11315
|
+
this.emit({
|
|
11316
|
+
type: "transition_progress",
|
|
11317
|
+
kind: "cwd",
|
|
11318
|
+
target: newCwd.trim(),
|
|
11319
|
+
phase: "error",
|
|
11320
|
+
progress: 100,
|
|
11321
|
+
text: `切换工作目录失败:${err.message}`,
|
|
11322
|
+
textEn: `Failed to switch directory: ${err.message}`,
|
|
11323
|
+
});
|
|
10942
11324
|
this.emit({
|
|
10943
11325
|
type: "notice",
|
|
10944
11326
|
level: "error",
|
|
@@ -10948,6 +11330,216 @@ export class ClientSession {
|
|
|
10948
11330
|
}
|
|
10949
11331
|
this.flushSnapshot();
|
|
10950
11332
|
}
|
|
11333
|
+
/** 创建隔离沙盒项目(空白或从 sourcePath 导入)并自动切换到该沙盒。 */
|
|
11334
|
+
async createSandbox(opts) {
|
|
11335
|
+
try {
|
|
11336
|
+
const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
|
|
11337
|
+
this.invalidateProjectsCache();
|
|
11338
|
+
await this.setCwd(sandbox.path);
|
|
11339
|
+
await this.pushProjects();
|
|
11340
|
+
const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
|
|
11341
|
+
const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
|
|
11342
|
+
this.emit({
|
|
11343
|
+
type: "notice",
|
|
11344
|
+
level: "info",
|
|
11345
|
+
text: `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`,
|
|
11346
|
+
textEn: `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`,
|
|
11347
|
+
});
|
|
11348
|
+
}
|
|
11349
|
+
catch (err) {
|
|
11350
|
+
this.emit({
|
|
11351
|
+
type: "notice",
|
|
11352
|
+
level: "error",
|
|
11353
|
+
text: `创建沙盒失败:${err.message}`,
|
|
11354
|
+
textEn: `Failed to create sandbox: ${err.message}`,
|
|
11355
|
+
});
|
|
11356
|
+
}
|
|
11357
|
+
}
|
|
11358
|
+
/** 重置沙盒工作区到初始状态(空白或重新从源项目复制)。 */
|
|
11359
|
+
async resetSandbox(path) {
|
|
11360
|
+
const target = path?.trim() || this.cwd;
|
|
11361
|
+
try {
|
|
11362
|
+
const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
|
|
11363
|
+
await this.listFiles();
|
|
11364
|
+
this.flushSnapshot();
|
|
11365
|
+
this.emit({
|
|
11366
|
+
type: "notice",
|
|
11367
|
+
level: "info",
|
|
11368
|
+
text: sandbox.sourcePath
|
|
11369
|
+
? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
|
|
11370
|
+
: `🔄 已清空并重置沙盒「${sandbox.name}」`,
|
|
11371
|
+
textEn: sandbox.sourcePath
|
|
11372
|
+
? `🔄 Reset sandbox "${sandbox.name}" (re-synced ${copiedFiles} files from source)`
|
|
11373
|
+
: `🔄 Cleared and reset sandbox "${sandbox.name}"`,
|
|
11374
|
+
});
|
|
11375
|
+
}
|
|
11376
|
+
catch (err) {
|
|
11377
|
+
this.emit({
|
|
11378
|
+
type: "notice",
|
|
11379
|
+
level: "error",
|
|
11380
|
+
text: `重置沙盒失败:${err.message}`,
|
|
11381
|
+
textEn: `Failed to reset sandbox: ${err.message}`,
|
|
11382
|
+
});
|
|
11383
|
+
}
|
|
11384
|
+
}
|
|
11385
|
+
/** 将临时沙盒转为永久保留的沙盒项目。 */
|
|
11386
|
+
async persistSandbox(path) {
|
|
11387
|
+
const target = path?.trim() || this.cwd;
|
|
11388
|
+
try {
|
|
11389
|
+
const sandbox = this.sandboxes.persist(target);
|
|
11390
|
+
this.invalidateProjectsCache();
|
|
11391
|
+
await this.pushProjects();
|
|
11392
|
+
this.flushSnapshot();
|
|
11393
|
+
this.emit({
|
|
11394
|
+
type: "notice",
|
|
11395
|
+
level: "info",
|
|
11396
|
+
text: `📌 沙盒「${sandbox.name}」已转为永久保留`,
|
|
11397
|
+
textEn: `📌 Sandbox "${sandbox.name}" is now saved permanently`,
|
|
11398
|
+
});
|
|
11399
|
+
}
|
|
11400
|
+
catch (err) {
|
|
11401
|
+
this.emit({
|
|
11402
|
+
type: "notice",
|
|
11403
|
+
level: "error",
|
|
11404
|
+
text: `转换永久沙盒失败:${err.message}`,
|
|
11405
|
+
textEn: `Failed to persist sandbox: ${err.message}`,
|
|
11406
|
+
});
|
|
11407
|
+
}
|
|
11408
|
+
}
|
|
11409
|
+
/** 将沙盒导出/另存为正式项目目录,可选立即切换过去。 */
|
|
11410
|
+
async promoteSandbox(targetPath, path, switchToTarget = true) {
|
|
11411
|
+
const sbxTarget = path?.trim() || this.cwd;
|
|
11412
|
+
try {
|
|
11413
|
+
const { sandbox, targetPath: resolvedTarget, copiedFiles } = await this.sandboxes.promote(sbxTarget, targetPath);
|
|
11414
|
+
this.invalidateProjectsCache();
|
|
11415
|
+
if (switchToTarget) {
|
|
11416
|
+
await this.setCwd(resolvedTarget);
|
|
11417
|
+
}
|
|
11418
|
+
else {
|
|
11419
|
+
await this.pushProjects();
|
|
11420
|
+
}
|
|
11421
|
+
this.emit({
|
|
11422
|
+
type: "notice",
|
|
11423
|
+
level: "info",
|
|
11424
|
+
text: `📤 已将沙盒「${sandbox.name}」导出为正式项目:${resolvedTarget}(共 ${copiedFiles} 个文件)`,
|
|
11425
|
+
textEn: `📤 Exported sandbox "${sandbox.name}" to formal project: ${resolvedTarget} (${copiedFiles} files)`,
|
|
11426
|
+
});
|
|
11427
|
+
}
|
|
11428
|
+
catch (err) {
|
|
11429
|
+
this.emit({
|
|
11430
|
+
type: "notice",
|
|
11431
|
+
level: "error",
|
|
11432
|
+
text: `导出沙盒失败:${err.message}`,
|
|
11433
|
+
textEn: `Failed to export sandbox: ${err.message}`,
|
|
11434
|
+
});
|
|
11435
|
+
}
|
|
11436
|
+
}
|
|
11437
|
+
/** 对比沙盒与源项目之间的新增/修改/删除文件清单并推送给前端。 */
|
|
11438
|
+
async diffSandbox(path) {
|
|
11439
|
+
const target = path?.trim() || this.cwd;
|
|
11440
|
+
try {
|
|
11441
|
+
const res = await this.sandboxes.diffWithSource(target);
|
|
11442
|
+
this.emit({
|
|
11443
|
+
type: "sandbox_diff",
|
|
11444
|
+
diff: {
|
|
11445
|
+
sandboxId: res.sandbox.id,
|
|
11446
|
+
path: res.sandbox.path,
|
|
11447
|
+
sourcePath: res.sourcePath,
|
|
11448
|
+
added: res.added.slice(0, 200),
|
|
11449
|
+
modified: res.modified.slice(0, 200),
|
|
11450
|
+
deleted: res.deleted.slice(0, 200),
|
|
11451
|
+
unchangedCount: res.unchangedCount,
|
|
11452
|
+
},
|
|
11453
|
+
});
|
|
11454
|
+
}
|
|
11455
|
+
catch (err) {
|
|
11456
|
+
this.emit({
|
|
11457
|
+
type: "sandbox_diff",
|
|
11458
|
+
diff: {
|
|
11459
|
+
sandboxId: "",
|
|
11460
|
+
path: target,
|
|
11461
|
+
added: [],
|
|
11462
|
+
modified: [],
|
|
11463
|
+
deleted: [],
|
|
11464
|
+
unchangedCount: 0,
|
|
11465
|
+
error: err.message,
|
|
11466
|
+
},
|
|
11467
|
+
});
|
|
11468
|
+
}
|
|
11469
|
+
}
|
|
11470
|
+
/** 将导入型沙盒的改动写回源项目(保留源项目 .git 与依赖缓存)。 */
|
|
11471
|
+
async applySandboxToSource(path) {
|
|
11472
|
+
const target = path?.trim() || this.cwd;
|
|
11473
|
+
try {
|
|
11474
|
+
const { sandbox, sourcePath, copiedFiles } = await this.sandboxes.applyToSource(target);
|
|
11475
|
+
this.emit({
|
|
11476
|
+
type: "notice",
|
|
11477
|
+
level: "info",
|
|
11478
|
+
text: `✅ 已将沙盒「${sandbox.name}」中的 ${copiedFiles} 个文件同步回源项目:${sourcePath}`,
|
|
11479
|
+
textEn: `✅ Applied ${copiedFiles} files from sandbox "${sandbox.name}" back to source project: ${sourcePath}`,
|
|
11480
|
+
});
|
|
11481
|
+
}
|
|
11482
|
+
catch (err) {
|
|
11483
|
+
this.emit({
|
|
11484
|
+
type: "notice",
|
|
11485
|
+
level: "error",
|
|
11486
|
+
text: `写回源项目失败:${err.message}`,
|
|
11487
|
+
textEn: `Failed to apply sandbox changes to source: ${err.message}`,
|
|
11488
|
+
});
|
|
11489
|
+
}
|
|
11490
|
+
}
|
|
11491
|
+
/** 彻底销毁沙盒目录:若当前正在该沙盒内,先自动切回源项目或其它最近项目。 */
|
|
11492
|
+
async destroySandbox(path) {
|
|
11493
|
+
const target = path?.trim() || this.cwd;
|
|
11494
|
+
const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
|
|
11495
|
+
if (!sbx) {
|
|
11496
|
+
this.stateStore.removeProject(this.clientId, target);
|
|
11497
|
+
this.invalidateProjectsCache();
|
|
11498
|
+
await this.pushProjects();
|
|
11499
|
+
return;
|
|
11500
|
+
}
|
|
11501
|
+
try {
|
|
11502
|
+
const activeInSbx = isSameOrSubpath(this.cwd, sbx.path);
|
|
11503
|
+
if (activeInSbx) {
|
|
11504
|
+
// 挑选回退目录:优先源项目 → 最近非当前沙盒项目 → homedir
|
|
11505
|
+
let fallbackCwd = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : "";
|
|
11506
|
+
if (!fallbackCwd) {
|
|
11507
|
+
const recent = await this.stateStore.getRecentProjects(this.clientId);
|
|
11508
|
+
const other = recent.find((p) => {
|
|
11509
|
+
const pk = normalizePathKey(p.path);
|
|
11510
|
+
return pk !== normalizePathKey(sbx.path) && existsSync(p.path);
|
|
11511
|
+
});
|
|
11512
|
+
fallbackCwd = other?.path || homedir();
|
|
11513
|
+
}
|
|
11514
|
+
await this.setCwd(fallbackCwd);
|
|
11515
|
+
}
|
|
11516
|
+
// 清理仍挂在该沙盒下的后台会话
|
|
11517
|
+
for (const [cid, c] of this.convs) {
|
|
11518
|
+
if (cid !== this.activeId && normalizePathKey(c.cwd) === normalizePathKey(sbx.path)) {
|
|
11519
|
+
this.removeConversation(cid);
|
|
11520
|
+
}
|
|
11521
|
+
}
|
|
11522
|
+
await this.sandboxes.destroy(sbx.id);
|
|
11523
|
+
this.stateStore.removeProject(this.clientId, sbx.path);
|
|
11524
|
+
this.invalidateProjectsCache();
|
|
11525
|
+
await this.pushProjects();
|
|
11526
|
+
this.flushSnapshot();
|
|
11527
|
+
this.emit({
|
|
11528
|
+
type: "notice",
|
|
11529
|
+
level: "info",
|
|
11530
|
+
text: `🗑️ 已销毁沙盒项目「${sbx.name}」并清理隔离目录`,
|
|
11531
|
+
textEn: `🗑️ Destroyed sandbox project "${sbx.name}" and cleaned up isolated directory`,
|
|
11532
|
+
});
|
|
11533
|
+
}
|
|
11534
|
+
catch (err) {
|
|
11535
|
+
this.emit({
|
|
11536
|
+
type: "notice",
|
|
11537
|
+
level: "error",
|
|
11538
|
+
text: `销毁沙盒失败:${err.message}`,
|
|
11539
|
+
textEn: `Failed to destroy sandbox: ${err.message}`,
|
|
11540
|
+
});
|
|
11541
|
+
}
|
|
11542
|
+
}
|
|
10951
11543
|
/** Strip the "(New)" freshness marker some catalogs append to display names
|
|
10952
11544
|
* (pi.dev data, e.g. "DeepSeek V4 Pro (New)") — display-only; the model id
|
|
10953
11545
|
* is untouched so switching still uses the exact official id. */
|