@tencent-ai/agent-sdk 0.3.132 → 0.3.134
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/cli/CHANGELOG.md +36 -0
- package/cli/dist/codebuddy-headless.js +303 -261
- package/cli/dist/web-ui/assets/{index-MHxdXMys.js → index-cOZxURjm.js} +2 -2
- package/cli/dist/web-ui/index.html +1 -1
- package/cli/dist/web-ui/sw.js +1 -1
- package/cli/package.json +1 -1
- package/cli/product.cloudhosted.json +2 -2
- package/cli/product.internal.json +21 -2
- package/cli/product.ioa.json +25 -2
- package/cli/product.json +2 -2
- package/cli/product.selfhosted.json +2 -2
- package/cli/vendor/sandbox/sandbox-cli +0 -0
- package/cli/vendor/sandbox/sandbox-cli.exe +0 -0
- package/cli/vendor/sandbox/sandbox_ffi.dll +0 -0
- package/cli/vendor/sandbox/tsbx.dll +0 -0
- package/cli/vendor/sandbox/tsbx_rules.json +10 -0
- package/cli/vendor/sandbox/tsbx_sdk.dll +0 -0
- package/package.json +1 -1
|
@@ -616,7 +616,7 @@ WARNING: This link could potentially be dangerous`)){const m=window.open();if(m)
|
|
|
616
616
|
`,u)}paste(m){this._core.paste(m)}refresh(m,u){this._verifyIntegers(m,u),this._core.refresh(m,u)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(m){this._addonManager.loadAddon(this,m)}static get strings(){return a}_verifyIntegers(...m){for(const u of m)if(u===1/0||isNaN(u)||u%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...m){for(const u of m)if(u&&(u===1/0||isNaN(u)||u%1!=0||u<0))throw new Error("This API only accepts positive integers")}}d.Terminal=v})(),l})()))})(Zr)),Zr.exports}var Rb=Ib();const Np="codebuddy-locale";function Ap(){if(typeof navigator>"u")return"en";const e=[];Array.isArray(navigator.languages)&&navigator.languages.length>0&&e.push(...navigator.languages),navigator.language&&e.push(navigator.language);try{const t=Intl.DateTimeFormat().resolvedOptions().locale;t&&e.push(t)}catch{}for(const t of e)if(t.toLowerCase().startsWith("zh"))return"zh";return"en"}function Jr(e){return e==="system"?Ap():e}function Lb(){try{const e=localStorage.getItem(Np);if(e){const t=JSON.parse(e),n=(t==null?void 0:t.mode)??e;if(["zh","en","system"].includes(n))return n}}catch{}return"system"}const fr=Te()($n((e,t)=>{const n=Lb(),i=Jr(n);return typeof window<"u"&&window.addEventListener("languagechange",()=>{const s=fr.getState();if(s.mode==="system"){const l=Ap();l!==s.resolved&&fr.setState({resolved:l})}}),{mode:n,resolved:i,setLocale:s=>{const l=Jr(s);e({mode:s,resolved:l})},toggle:()=>{const s=t().mode,l=s==="zh"?"en":s==="en"?"system":"zh";t().setLocale(l)}}},{namespace:"locale",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:Np,onLoad:(e,t)=>{if(e.mode){const n=Jr(e.mode);t({mode:e.mode,resolved:n})}}})),Dd={zh:{"app.connecting":"正在连接 CodeBuddy Code...","app.connectFailed":"连接失败","app.retry":"重试","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"今天有什么可以帮到你?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"幻灯片生成","chat.empty.tag.research":"深度研究","chat.empty.tag.docs":"文档处理","chat.empty.tag.data":"数据分析","chat.thinking":"思考中","chat.waitingPermission":"等待权限确认","chat.waitingUser":"等待用户回答","chat.error":"错误","chat.sessionEnded":"会话已结束","chat.stopped":"已停止","chat.error.refusal":"Agent 拒绝继续执行。这可能是由于内容策略限制或其他限制。","chat.error.network":"网络连接异常或服务暂时不可用,请稍后重试。","chat.error.auth":"身份验证失败或权限不足,请重新登录后再试。","chat.error.quota":"已达到配额上限或请求过于频繁,请稍后再试。","chat.error.modelService":"模型服务返回异常,请重试或稍后再试。","chat.error.maxTokens":"响应因达到最大 token 限制而被截断。您可以继续对话或要求更简洁的回复。","chat.error.maxTurnRequests":"已超过单轮对话允许的最大模型请求次数。您可以发送新消息以继续。","chat.newChat":"新对话","chat.disclaimer":"回答由 AI 生成,仅供参考","chat.compacted":"已精简历史对话","chat.compacting":"正在精简历史对话...","phase.preparing":"准备中","phase.modelRequesting":"等待模型响应","phase.modelStreaming":"接收中","phase.modelDone":"处理中","phase.toolExecuting":"执行工具","phase.modelStreamingTool":"正在写入","phase.retrying":"重试中","progress.compacting":"压缩上下文中","input.placeholder":"从一个想法开始...","input.placeholderRunning":"消息将排队等待处理...","input.placeholderPending":"请先处理权限请求...","input.send":"发送 (Enter)","input.stop":"停止","input.thinking":"思考中","input.deepThinking":"深度思考","input.promptFailed":"发送失败","input.sendQueued":"发送排队消息 (Enter)","input.dropHint":"拖拽文件到这里","input.addImage":"添加图片","input.addFile":"添加文件","input.imageTooLarge":"图片不能超过 10MB","input.tooManyImages":"最多添加 5 张图片","input.fileTooLarge":"文件不能超过 1MB","input.tooManyFiles":"最多添加 10 个文件","input.menu.image":"图片","input.menu.file":"文件","input.newline":"换行","input.contextMenu.newline":"换行","input.contextMenu.send":"发送","queue.more":" 条消息排队中","status.running":"运行中","tool.writeFile":"写入文件","tool.readFile":"读取文件","tool.execute":"执行指令","tool.searchFiles":"搜索文件","tool.searchContent":"搜索内容","tool.fetchWeb":"获取网页","tool.searchWeb":"搜索网络","tool.defaultName":"工具","tool.moreItems":"... 还有 {count} 项","interruption.title":"需要授权","interruption.tool":"工具","interruption.allow":"允许","interruption.allowAll":"全部允许","interruption.deny":"拒绝","interruption.approved":"已允许","interruption.denied":"已拒绝","interruption.edits":"{count} 处编辑","interruption.yes":"是","interruption.keepPlanning":"继续规划","interruption.exitPlanMode":"退出计划模式","interruption.readyToCode":"准备好开始编码了吗?","theme.light":"浅色","theme.dark":"深色","theme.system":"跟随系统","locale.zh":"中文","locale.en":"English","locale.system":"跟随系统","sidebar.nav.plugins":"插件","sidebar.nav.tasks":"任务","sidebar.search.placeholder":"搜索...","sidebar.chatHistory":"对话历史","sidebar.workspace":"工作区","sidebar.connectionStatus":"连接状态","sidebar.status":"状态","sidebar.sessionId":"会话ID","sidebar.notConnected":"未连接","sidebar.modelSelection":"模型选择","sidebar.noModels":"暂无可用模型","sidebar.environment":"环境信息","sidebar.cwd":"工作目录","sidebar.os":"操作系统","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"网关模式","sidebar.tunnelUrl":"Tunnel 地址","sidebar.clickToCopy":"点击复制","sidebar.copied":"已复制","sidebar.permissionMode":"权限模式","sidebar.noModes":"暂无可用模式","sidebar.preferences":"设置","sidebar.keybindings":"快捷键","sidebar.group.workspace":"工作区","sidebar.group.observability":"可观测","sidebar.group.preferences":"配置","bottomSheet.attachments":"添加","bottomSheet.navigation":"导航","sidebar.theme":"界面主题","sidebar.language":"界面语言","sidebar.user":"用户","sidebar.authMethod":"密码认证","sidebar.noAuth":"无认证","sidebar.version":"Remote UI v1.0","connection.connected":"已连接","connection.connecting":"连接中","connection.disconnected":"未连接","connection.error":"连接错误","message.copyToClipboard":"复制到剪贴板","message.copied":"已复制","message.copy":"复制","message.assistantName":"CodeBuddy Code","thinking.title":"思考过程","thinking.thinking":"思考中","thinking.done":"已思考","thinking.seconds":"(用时 {n} 秒)","thinking.expand":"展开","thinking.collapse":"收起","diff.noChanges":"无变更","login.title":"CodeBuddy Remote Control","login.subtitle":"请输入终端中显示的密码","login.placeholder":"密码","login.submit":"登录","login.error.incorrect":"密码错误","login.error.rateLimit":"登录尝试次数过多,请稍后再试","login.error.required":"请输入密码","login.hint.password":"提示:密码在服务启动时显示在终端中。","login.hint.urlAuth":"也可以使用 <code>?password=xxx</code> 自动登录。","login.hint.disable":'或在 <code>~/.codebuddy/settings.json</code> 中设置 <code>gateway.auth: "none"</code> 来禁用认证。',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"隐私政策","login.terms":"服务条款","sidebar.interactionMode":"交互模式","sidebar.chatMode":"对话","sidebar.terminalMode":"终端","sidebar.canvas":"画布","canvas.title":"无限画布","canvas.addTerminal":"添加终端","canvas.zoomIn":"放大","canvas.zoomOut":"缩小","canvas.fitView":"适应视图","canvas.resetView":"重置视图","canvas.empty":"点击工具栏 + 按钮添加终端","canvas.openStandalone":"在新窗口打开画布","canvas.tileMenu.close":"关闭","canvas.tileMenu.duplicate":"复刻终端","canvas.tileMenu.maximize":"最大化","canvas.tileMenu.minimize":"最小化","canvas.tileMenu.restore":"还原","canvas.tileMenu.openStandalone":"在新窗口打开","canvas.standalone.missingPaneId":"未指定终端 ID","canvas.defaultTitle":"终端","terminal.connecting":"终端连接中...","terminal.title":"终端","terminal.disconnected":"终端已断开","terminal.error":"终端连接失败","terminal.reconnect":"重新连接","terminal.splitHorizontal":"左右分屏","terminal.splitVertical":"上下分屏","terminal.closePane":"关闭终端","terminal.maxPanes":"已达最大面板数","sidebar.instances":"实例","sidebar.activeInstances":"个活跃实例","sidebar.manageInstances":"管理实例","sidebar.remoteControl":"远程控制","instance.title":"实例列表","instance.switch":"实例","instance.switchTitle":"切换实例","instance.current":"当前实例","instance.manual":"手动添加","instance.switchTo":"切换到此实例","instance.manage":"管理实例","instance.managerTitle":"实例管理","instance.addInstance":"添加实例","instance.name":"实例名称","instance.namePlaceholder":"自定义实例名称(可选,默认为目录名)","instance.url":"实例地址","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"密码","instance.optional":"可选","instance.passwordPlaceholder":"访问密码","instance.cancel":"取消","instance.add":"添加","instance.remove":"删除此实例","instance.noInstances":"暂无其他实例","instance.noInstancesHint":"启动更多 CodeBuddy Code 实例,或手动添加远程实例","instance.cwd":"工作目录","instance.topic":"当前话题","instance.startedAt":"启动于","instance.local":"本地","instance.tunnel":"隧道","instance.uptime.days":"天前","instance.uptime.hours":"小时前","instance.uptime.minutes":"分钟前","instance.uptime.justNow":"刚刚","instance.addError":"添加实例失败","instance.removeError":"删除实例失败","instance.copyUrl":"复制链接","instance.copied":"已复制","instance.subtitle":"管理和切换工作实例","instance.refresh":"刷新","instance.refreshed":"已刷新","instance.loading":"加载实例中...","instance.error":"加载实例列表失败","instance.retry":"重试","question.multiple":"多选","question.customAnswer":"或输入自定义答案...","question.reviewAnswers":"审核答案","question.singleTitle":"问题","question.titleWithCount":"问题({count})","question.reviewTab":"审核","question.next":"下一步","question.submit":"提交","question.cancel":"取消","question.answered":"已回答","question.cancelled":"问题已取消","todo.title":"任务清单","todo.executing":"任务{n}正在执行中","todo.untitled":"未命名","history.title":"会话历史","history.description":"点击会话可切换到该对话","history.noData":"暂无会话历史","history.noDataHint":"开始一段新对话吧","history.backToChat":"返回对话","history.loading":"加载中...","history.loadError":"加载失败","history.retry":"重试","history.current":"当前","history.messages":"{count} 条消息","history.delete":"删除","history.deleteConfirm":"确定要删除这个会话吗?","history.deleteCancel":"取消","history.deleteOk":"删除","history.rename":"重命名","history.renameTitle":"重命名会话","history.renamePlaceholder":"输入新名称","history.renameCancel":"取消","history.renameOk":"确定","history.cannotDeleteCurrent":"无法删除当前会话","settings.title":"设置","settings.appearance":"外观","settings.model":"模型选择","settings.mode":"权限模式","settings.systemInfo":"系统信息","settings.backToChat":"返回对话","settings.tab.user":"用户级","settings.tab.project":"工作空间级","settings.group.modelAndReasoning":"模型与推理","settings.group.behavior":"行为","settings.group.memory":"记忆","settings.group.language":"语言","settings.group.advanced":"高级","settings.group.sandbox":"安全沙箱","settings.item.model":"默认模型","settings.item.model.desc":"设置默认使用的 AI 模型","settings.item.reasoningEffort":"推理努力级别","settings.item.reasoningEffort.desc":"控制模型的推理深度","settings.item.alwaysThinkingEnabled":"始终启用深度思考","settings.item.autoCompactEnabled":"自动压缩上下文","settings.item.includeCoAuthoredBy":"提交包含 Co-authored-by","settings.item.fileCheckpointingEnabled":"文件检查点","settings.item.fileCheckpointingEnabled.desc":"启用文件版本回退功能","settings.item.promptSuggestionEnabled":"提示建议","settings.item.ignoreGitIgnore":"忽略 .gitignore","settings.item.ignoreGitIgnore.desc":"搜索文件时忽略 .gitignore 规则","settings.item.deferToolLoading":"延迟加载工具","settings.item.hookOutputCollapsed":"折叠 Hook 输出","settings.item.memory.enabled":"启用记忆功能","settings.item.memory.autoMemoryEnabled":"自动记忆","settings.item.memory.autoMemoryEnabled.desc":"自动保存重要信息到记忆库","settings.item.language":"响应语言","settings.item.language.desc":"设置 AI 回复使用的语言","settings.item.cleanupPeriodDays":"聊天记录保留天数","settings.item.imageHistoryRetainRounds":"图片保留轮数","settings.item.imageHistoryRetainRounds.desc":"对话历史中保留图片的最近轮数","settings.item.env":"环境变量","settings.item.env.desc":"应用于每个会话的环境变量 (JSON)","settings.item.sandbox.enabled":"启用安全沙箱","settings.item.sandbox.enabled.desc":"在沙箱中运行 Bash 命令,限制文件和网络访问","settings.item.sandbox.autoAllowBashIfSandboxed":"沙箱内自动批准命令","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"命令在沙箱中运行时自动批准","settings.loading":"加载中...","settings.saved":"已保存","settings.saveFailed":"保存失败","settings.notSet":"未设置","settings.default":"默认","settings.reset":"重置","settings.noProjectSettings":"当前工作空间暂无可配置项","settings.effort.low":"低","settings.effort.medium":"中","settings.effort.high":"高","settings.effort.xhigh":"极高","page.title":"CodeBuddy Code","tool.processExited":"[进程已退出]","tool.itemsCount":"{count} 项","tool.showAllItems":"显示全部 {count} 项","tool.moreLinesCount":"... 还有 {count} 行","tool.generatedImage":"生成的图片","tool.editedImage":"编辑后的图片","tool.imageGen":"图片生成","tool.imageEdit":"图片编辑","tool.toolSearch":"工具搜索","tool.teamCreate":"创建团队","tool.teamDelete":"删除团队","tool.taskCreate":"创建任务","tool.taskUpdate":"更新任务","tool.taskList":"任务列表","tool.taskGet":"获取任务","tool.sendMessage":"发送消息","tool.shutdown":"关闭","tool.taskCompleted":"任务完成","tool.shutdownRejected":"关闭被拒绝","tool.planResponse":"计划回复","tool.approved":"已批准","tool.rejected":"已拒绝","tool.webSearch":"网络搜索","tool.webFetch":"网页获取","tool.saveMemory":"保存记忆","tool.askUserQuestion":"询问用户","tool.enterPlanMode":"进入计划模式","tool.exitPlanMode":"退出计划模式","tool.allowedActions":"允许的操作:","tool.skill":"技能","tool.agent":"代理","tool.failed":"失败","tool.completed":"完成","tool.toolsCount":"{count} 个工具","tool.background":"后台","tool.permissionsCount":"{count} 项权限","terminal.unknownError":"未知错误","terminal.processExited":"[进程已退出]","terminal.connectionLost":"连接已断开","terminal.wsConnectionFailed":"WebSocket 连接失败","terminal.createSessionFailed":"创建终端会话失败","terminal.reconnectFailed":"重连失败","team.title":"团队","team.activeCount":"{count} 个活跃","team.doneCount":"{count} 个完成","team.waitingForTeammates":"等待 {count} 个成员完成…","team.backToMain":"返回主对话","team.loadingHistory":"加载对话历史…","team.noHistory":"暂无对话历史","team.agentRunning":"正在运行…","team.delivered":"已送达","team.showLess":"收起","team.moreLines":"… ({count} 更多行)","team.tools":"{count} 工具","team.tokens":"{count} tokens","instance.tunnelMode":"隧道","instance.localMode":"本地","workspace.searchPlaceholder":"搜索目录...","workspace.switch":"切换","workspace.switchHere":"切换到此目录","workspace.switching":"切换中...","workspace.noResults":"没有匹配的目录","workspace.emptyDir":"此目录为空","workspace.pathPlaceholder":"输入路径或目录名...","workspace.selectDir":"在此目录创建机器人","workspace.filterPlaceholder":"过滤子目录...","workspace.recent.title":"最近工作区","workspace.recent.daysAgo":"天前","workspace.recent.hoursAgo":"小时前","workspace.recent.minutesAgo":"分钟前","workspace.recent.justNow":"刚刚","workspace.recent.remove":"移除","workspace.browseTitle":"浏览工作区","workspace.recentWorkspaces":"最近工作区","workspace.createNew":"创建新机器人","workspace.browseDir":"浏览目录","workspace.instanceLocal":"本地","workspace.instanceTunnel":"隧道","workspace.instanceCurrent":"当前","workspace.switchInstance":"切换","workspace.switchingInstance":"切换中...","workspace.switchingWithGateway":"正在准备切换...","workspace.instanceStarted":"启动于","workspace.noWorkspaces":"暂无活跃的工作区","workspace.noWorkspacesHint":"浏览目录创建新机器人","workspace.instanceCount":"{count} 个机器人","question.multiLabel":"多选","tasks.title":"推荐模版","tasks.subtitle":"选择一个模版快速创建定时任务","tasks.loading":"正在获取推荐模版...","tasks.error":"获取模版失败","tasks.retry":"重试","tasks.refresh":"刷新推荐","tasks.refreshed":"已刷新","tasks.empty":"暂无推荐模版","tasks.interval":"每 {value}","tasks.interval.1d":"每天","tasks.interval.2d":"每 2 天","tasks.interval.3d":"每 3 天","tasks.interval.1w":"每周","tasks.interval.2w":"每 2 周","tasks.interval.1m":"每月","scheduled.title":"定时任务","scheduled.subtitle":"当前会话中的活跃定时任务","scheduled.loading":"加载中...","scheduled.empty":"暂无定时任务","scheduled.emptyHint":"在对话中使用 /loop 或 CronCreate 创建","scheduled.create":"创建任务","scheduled.creating":"创建中...","scheduled.delete":"删除","scheduled.cron":"Cron 表达式","scheduled.prompt":"执行内容","scheduled.promptPlaceholder":"定时触发时要执行的提示词...","scheduled.recurring":"循环","scheduled.oneShot":"一次性","scheduled.durable":"持久化","scheduled.sessionOnly":"仅会话","scheduled.lastFired":"上次触发","plugins.title":"插件管理","plugins.installedPlugins":"已安装插件","plugins.browseMarketplace":"浏览市场","plugins.marketplaces":"插件市场","plugins.enabled":"已启用","plugins.disabled":"已禁用","plugins.enable":"启用","plugins.disable":"禁用","plugins.uninstall":"卸载","plugins.install":"安装","plugins.confirmUninstall":"确定要卸载此插件吗?","plugins.marketplace":"市场","plugins.addMarketplace":"添加市场","plugins.removeMarketplace":"移除","plugins.confirmRemoveMarketplace":"确定要移除此市场吗?","plugins.noPlugins":"暂无已安装的插件","plugins.noPluginsHint":"通过插件市场安装插件来扩展功能","plugins.noMarketplaces":"暂无配置的市场","plugins.noMarketplacesHint":"添加一个插件市场来浏览和安装插件","plugins.selectMarketplace":"选择市场","plugins.selectMarketplaceHint":"选择一个市场来浏览可用插件","plugins.marketplaceNotFound":"市场不存在","plugins.noAvailablePlugins":"该市场暂无可用插件","plugins.noAvailablePluginsHint":"请尝试添加其他市场或稍后再试","plugins.installed":"已安装","plugins.browsingMarketplace":"浏览中...","plugins.loading":"加载中...","plugins.error":"加载插件失败","plugins.retry":"重试","plugins.sourcePlaceholder":"市场地址(Git URL 或本地路径)","plugins.namePlaceholder":"市场名称(可选)","plugins.cancel":"取消","plugins.add":"添加","plugins.version":"版本","plugins.operationFailed":"操作失败","plugins.searchPlaceholder":"搜索插件...","plugins.allMarketplaces":"全部市场","plugins.noSearchResults":"没有找到匹配的插件","plugins.totalCount":"个插件","plugins.refresh":"刷新","plugins.installedLabel":"已安装","plugins.category":"分类","plugins.author":"作者","plugins.license":"许可证","plugins.homepage":"主页","plugins.repository":"仓库","plugins.source":"来源","plugins.keywords":"关键词","plugins.features":"功能","plugins.scope":"范围","plugins.scope.user":"用户","plugins.scope.project":"项目","plugins.scope.project-local":"本地","plugins.installScope.user":"为你安装(用户级)","plugins.installScope.project":"为所有协作者安装(项目级)","plugins.installScope.local":"仅在此仓库为你安装(本地级)","plugins.policyCannotRemove":"不可卸载","plugins.policyCannotSwitchoff":"不可禁用","plugins.policyCannotEdit":"不可编辑","channel.from":"来自","channel.group":"群聊","channel.replyTo":"回复来自 {source}","channel.wechat":"微信","channel.wecom":"企业微信","channel.wecomBot":"企微机器人","remoteControl.title":"远程控制","remoteControl.subtitle":"管理渠道连接","remoteControl.connectedChannels":"已连接渠道","remoteControl.noChannels":"暂无已连接渠道","remoteControl.noChannelsHint":"添加微信或企业微信渠道,或从插件市场安装更多","remoteControl.addWeChat":"添加微信机器人","remoteControl.addWeCom":"添加企微机器人","remoteControl.connect":"连接","remoteControl.disconnect":"断开","remoteControl.delete":"删除","remoteControl.add":"添加","remoteControl.connected":"已连接","remoteControl.disconnected":"未连接","remoteControl.connecting":"连接中...","remoteControl.installMore":"安装更多渠道","remoteControl.installMoreHint":"浏览插件市场,安装第三方渠道插件","remoteControl.browseMarketplace":"浏览插件市场","remoteControl.builtIn":"内置","remoteControl.plugin":"插件","remoteControl.rebind":"重新绑定","remoteControl.unbind":"解绑","remoteControl.bot":"机器人","remoteControl.default":"默认","remoteControl.next":"下一步","remoteControl.cancel":"取消","remoteControl.wecomBotIdHint":"从企业微信管理后台 → 应用管理 → AI 助手获取","remoteControl.wecomSecretHint":"输入 Secret 后按回车或点“连接”","remoteControl.fetchingQr":"正在获取二维码...","remoteControl.scanQr":"请用微信扫描二维码","sidebar.docs":"文档","docs.title":"文档中心","docs.search.placeholder":"搜索文档...","docs.search.noResults":"未找到相关文档","docs.search.resultsCount":"{count} 个结果","docs.loading":"加载中...","docs.loadError":"文档加载失败","docs.notFound":"未找到该文档","docs.apiReference":"API 文档","docs.toc":"目录","docs.retry":"重试","docs.backToList":"返回文档列表","docs.expandAll":"展开全部","docs.collapseAll":"收起全部","docs.openStandalone":"独立窗口打开","sidebar.stats":"统计","stats.title":"统计","stats.loading":"正在加载统计数据...","stats.refresh":"刷新","stats.noData":"暂无统计数据","stats.tab.overview":"概览","stats.tab.models":"模型","stats.tab.tools":"工具","stats.sessions":"会话数","stats.messages":"消息数","stats.activeDays":"活跃天数","stats.currentStreak":"当前连续","stats.longestStreak":"最长连续","stats.peakHour":"高峰时段","stats.longestSession":"最长会话","stats.favoriteModel":"最常用模型","stats.totalTokens":"总 Token","stats.timeRange":"统计范围: 最近 {days} 天","stats.heatmap.less":"少","stats.heatmap.more":"多","stats.days":"天","stats.tokensPerDay":"每日 Token 趋势","stats.allModels":"所有模型","stats.input":"输入","stats.output":"输出","stats.cacheRead":"缓存读取","stats.cacheHitRate":"缓存命中率","stats.cost":"成本","stats.topTools":"工具使用排行","stats.session.title":"当前会话","stats.session.apiDuration":"API 时长","stats.session.wallTime":"总时长","stats.session.linesAdded":"新增行","stats.session.linesDeleted":"删除行","stats.session.tokens":"Token","stats.na":"N/A","stats.heatmap.messages":"条消息","stats.funFact.moreTokens":"你已使用约 {times} 倍于《{book}》的 Token 量","stats.funFact.sameTokens":"你使用的 Token 量约等于一本《{book}》","stats.funFact.longerSession":"你最长的会话时长约为「{activity}」的 {times} 倍","sidebar.traces":"链路","traces.title":"链路追踪","traces.loading":"加载中...","traces.refresh":"刷新","traces.clear":"清空","traces.clearConfirm":"确定清空所有链路数据?","traces.noData":"暂无链路数据,发送一条消息后将自动收集","traces.selectWorker":"选择 Worker","traces.current":"当前","traces.spanCount":"{count} spans","traces.duration":"耗时","traces.status.ok":"成功","traces.status.error":"错误","traces.status.running":"运行中","traces.status.cancelled":"已取消","traces.bottleneck":"瓶颈","traces.bottleneckTip":"耗时最长,占总时间 {pct}%","traces.spanDetail":"Span 详情","traces.spanDetail.type":"类型","traces.spanDetail.duration":"耗时","traces.spanDetail.model":"模型","traces.spanDetail.tokens":"Token","traces.spanDetail.input":"输入","traces.spanDetail.output":"输出","traces.spanDetail.error":"错误","traces.spanDetail.attributes":"属性","traces.legend.agent":"Agent","traces.legend.generation":"模型调用","traces.legend.function":"工具","traces.legend.handoff":"切换","traces.legend.guardrail":"防护","traces.back":"返回","traces.tab.timeline":"时间线","traces.tab.tree":"树形","traces.tab.flame":"火焰图","traces.tab.graph":"依赖图","traces.expandAll":"全部展开","traces.collapseAll":"全部收起","traces.search":"搜索 span...","traces.selfTime":"自身耗时","traces.spanDetail.overview":"概览","traces.spanDetail.io":"输入/输出","traces.noSpans":"无 span 数据","traces.auto":"自动","traces.auxiliaryCount":"{count} 个辅助 trace(memory、title 等)","traces.noIO":"无输入/输出数据","traces.noAttrs":"无属性","traces.fit":"适应","traces.allSessions":"所有会话","traces.allInstances":"所有实例","traces.llmCalls":"{count} 次 LLM","sidebar.metrics":"监控","metrics.title":"系统监控","metrics.loading":"加载指标数据...","metrics.refresh":"刷新","metrics.cpu":"CPU","metrics.memory":"内存","metrics.disk":"磁盘","metrics.cores":"核心","metrics.workers":"Workers","metrics.noWorkers":"暂无运行中的 Worker","metrics.current":"当前","metrics.uptime":"运行时长","metrics.version":"版本","sidebar.editor":"文件","editor.title":"代码编辑器","editor.loading":"加载中...","editor.loadError":"加载失败","editor.noFile":"选择一个文件开始编辑","editor.unsaved":"未保存","editor.save":"保存","editor.saveAll":"全部保存","editor.close":"关闭","editor.closeOthers":"关闭其他","editor.closeAll":"关闭全部","editor.newFile":"新建文件","editor.newFolder":"新建文件夹","editor.rename":"重命名","editor.delete":"删除","editor.refresh":"刷新","editor.emptyFolder":"空文件夹","editor.explorer":"资源管理器","editor.toggleSidebar":"切换侧边栏","editor.collapseAll":"全部折叠","editor.openFolder":"打开目录","editor.openFolderPlaceholder":"输入目录路径...","editor.parentFolder":"上级目录","editor.pin":"固定","editor.unpin":"取消固定","editor.copyPath":"复制路径","editor.copyRelativePath":"复制相对路径","editor.revealInExplorer":"在文件树中定位","editor.closeToRight":"关闭右侧","editor.closeSaved":"关闭已保存","editor.quickOpen":"快速打开文件","editor.focusExplorer":"聚焦资源管理器","editor.recentFiles":"最近文件","editor.quickOpenPlaceholder":"输入文件名以搜索...","editor.quickOpenEmpty":"没有匹配的文件","editor.quickOpenLoading":"正在加载文件列表...","editor.selected":"已选","editor.lines":"行","editor.preview":"切换到预览","editor.source":"切换到源码","sidebar.workers":"实例","workers.title":"Agent 实例管理","workers.refresh":"刷新","workers.active":"活跃 Workers","workers.empty":"没有活跃的 worker 进程","workers.daemon":"Daemon 服务","workers.daemon.running":"运行中","workers.daemon.stopped":"已停止","workers.daemon.start":"启动","workers.daemon.starting":"启动中...","workers.daemon.stop":"停止","workers.daemon.restart":"重启","workers.action.logs":"查看日志","workers.action.open":"打开","workers.action.kill":"终止","workers.action.kill.confirm":"确定要终止这个 worker 进程吗?","sidebar.logs":"日志","logs.title":"日志查看器","logs.selectWorker":"选择 Worker","logs.current":"当前","logs.search":"搜索日志...","logs.autoRefresh":"自动刷新","logs.refresh":"刷新","logs.empty":"暂无日志内容","command.btw.description":"快速提问,不打断主要 Agent 工作","command.clear.description":"开始新的对话(之前的对话仍可通过 /resume 访问)","command.context.description":"计算并显示上下文 Token 分布","command.cost.description":"显示当前会话的总费用和持续时间","command.doctor.description":"诊断和验证 CodeBuddy 的安装和设置","command.feedback.description":"打开反馈页面以报告问题或提出建议","command.gateway.description":'管理远程控制网关。子命令: "status" 查看状态, "stop" 停止网关, "token" 重新生成访问令牌, "tunnel" 启动隧道',"command.remote-control.description":"管理远程控制长连接客户端(start, stop, status, list)","command.login.description":"切换腾讯云 CodeBuddy 账号","command.logout.description":"退出 CodeBuddy Code 账号","command.plan.description":"预览当前计划文件内容","command.pr-comments.description":"获取 GitHub Pull Request 的评论","command.release-notes.description":"查看更新日志","command.review.description":"审查 Pull Request","command.skills.description":"列出可用的技能","command.todos.description":"显示当前会话的任务清单","command.reload-plugins.description":"重新加载所有插件、技能、代理、钩子和 MCP/LSP 服务器(无需重启)","command.plugin-validate.description":"验证插件目录结构和清单文件","command.init.description":"正在分析你的代码库…","command.compact.description":"清除对话历史但保留摘要在上下文中。可选: /compact [摘要指令]","command.upgrade.description":"在浏览器中打开升级页面","command.statusline.description":"设置 CodeBuddy Code 的状态栏 UI","command.security-review.description":"对当前分支的待提交变更进行安全审查","command.insights.description":"生成 AI 驱动的 CodeBuddy Code 使用模式和活动洞察","command.loop.description":"按固定间隔运行提示或斜杠命令(例如 /loop 5m /foo,默认 10m)","command.task-manager.description":"团队任务管理 - 智能任务录入、分配、追踪和分析","sidebar.changes":"变更","fileChanges.title":"变更","fileChanges.changesSection":"文件变更","fileChanges.empty":"暂无文件变更","fileChanges.showChanges":"显示文件变更","fileChanges.hideChanges":"隐藏文件变更","fileChanges.revertAll":"撤回全部","fileChanges.revertCode":"回退代码","fileChanges.revertChat":"回退对话","fileChanges.revertCodeAndChat":"回退全部","fileChanges.checkpoints":"回退点","fileChanges.noCheckpoints":"暂无回退点","filePreview.binaryNotSupported":"该文件无法在编辑器中预览","filePreview.download":"下载文件","error.viewCrashed":"页面加载出错","error.appCrashed":"应用遇到了问题","error.newChatFailed":"创建新对话失败,请重试","error.switchSessionFailed":"切换会话失败,请重试","commandPalette.placeholder":"输入命令...","commandPalette.commands":"命令","commandPalette.views":"视图","commandPalette.actions":"操作","commandPalette.noResults":"没有匹配的命令","commandPalette.newChat":"新建对话","commandPalette.toggleTheme":"切换主题","commandPalette.toggleLocale":"切换语言","commandPalette.tip":"打开命令面板","app.confirm":"确定","app.cancel":"取消","tool.toolSingular":"个工具已执行","tool.toolPlural":"个工具已执行","keybindings.title":"快捷键","keybindings.search.placeholder":"搜索快捷键... (如 submit, ctrl+enter)","keybindings.source.default":"默认","keybindings.source.user":"自定义","keybindings.record.title":"录制快捷键","keybindings.record.hint":"请按下快捷键组合...","keybindings.record.conflict":"冲突","keybindings.action.edit":"编辑","keybindings.action.reset":"重置","keybindings.action.unbind":"解绑","keybindings.reset.all":"重置全部","keybindings.noResults":"没有匹配的快捷键","keybindings.empty":"暂无快捷键","keybindings.loading":"加载中...","keybindings.ctx.Global":"全局","keybindings.ctx.Chat":"聊天输入","keybindings.ctx.InputBox":"文本输入","keybindings.ctx.Terminal":"终端","keybindings.ctx.Autocomplete":"自动补全","keybindings.ctx.Confirmation":"确认对话框","keybindings.ctx.HistorySearch":"历史搜索","keybindings.ctx.Task":"任务运行中","keybindings.ctx.Settings":"设置","keybindings.ctx.CommandPalette":"命令面板","keybindings.ctx.Select":"选择列表","keybindings.ctx.PermissionDialog":"权限对话框","keybindings.ctx.Help":"帮助","keybindings.ctx.Plugin":"插件","keybindings.ctx.DiffDialog":"Diff 对话框","keybindings.ctx.MessageSelector":"消息选择器","keybindings.ctxDesc.Global":"在任何位置都生效","keybindings.ctxDesc.Chat":"聊天输入框获得焦点时","keybindings.ctxDesc.InputBox":"文本输入框处于活跃状态时","keybindings.ctxDesc.Terminal":"终端视图处于活跃状态时","keybindings.ctxDesc.Autocomplete":"自动补全菜单显示时","keybindings.ctxDesc.Confirmation":"确认/权限对话框显示时","keybindings.ctxDesc.HistorySearch":"搜索命令历史时 (ctrl+r)","keybindings.ctxDesc.Task":"任务/代理在前台运行时","keybindings.ctxDesc.Settings":"设置面板打开时","keybindings.ctxDesc.CommandPalette":"命令面板打开时","keybindings.ctxDesc.Select":"选择/列表组件获得焦点时","keybindings.ctxDesc.PermissionDialog":"工具权限对话框显示时","keybindings.ctxDesc.Help":"帮助页面打开时","keybindings.ctxDesc.Plugin":"插件对话框打开时","keybindings.ctxDesc.DiffDialog":"Diff 对话框打开时","keybindings.ctxDesc.MessageSelector":"消息选择器 (rewind) 打开时","keybindings.act.app:interrupt":"中断","keybindings.act.app:exit":"退出","keybindings.act.app:redraw":"刷新屏幕","keybindings.act.app:toggleTodos":"切换待办事项","keybindings.act.app:toggleTranscript":"切换转录","keybindings.act.app:toggleSidebar":"切换侧边栏","keybindings.act.app:toggleTerminal":"切换终端","keybindings.act.app:commandPalette":"命令面板","keybindings.act.app:newChat":"新对话","keybindings.act.app:settings":"设置","keybindings.act.app:focusInput":"聚焦输入框","keybindings.act.app:keybindings":"快捷键设置","keybindings.act.history:search":"搜索历史","keybindings.act.history:previous":"上一条历史","keybindings.act.history:next":"下一条历史","keybindings.act.history:open":"打开历史","keybindings.act.chat:cancel":"取消","keybindings.act.chat:submit":"发送","keybindings.act.chat:newline":"换行","keybindings.act.chat:killAgents":"终止代理","keybindings.act.chat:cycleMode":"切换模式","keybindings.act.chat:modelPicker":"选择模型","keybindings.act.chat:thinkingToggle":"切换思考","keybindings.act.chat:undo":"撤销","keybindings.act.chat:externalEditor":"外部编辑器","keybindings.act.chat:stash":"暂存","keybindings.act.chat:imagePaste":"粘贴图片","keybindings.act.autocomplete:accept":"接受补全","keybindings.act.autocomplete:dismiss":"关闭补全","keybindings.act.autocomplete:previous":"上一项","keybindings.act.autocomplete:next":"下一项","keybindings.act.confirm:yes":"确认","keybindings.act.confirm:no":"取消","keybindings.act.confirm:previous":"上一项","keybindings.act.confirm:next":"下一项","keybindings.act.confirm:toggle":"切换选中","keybindings.act.confirm:toggleExplanation":"切换说明","keybindings.act.task:background":"后台运行","keybindings.act.historySearch:next":"下一条","keybindings.act.historySearch:accept":"接受","keybindings.act.historySearch:cancel":"取消","keybindings.act.historySearch:execute":"执行","keybindings.act.settings:close":"关闭设置","keybindings.act.settings:search":"搜索设置","keybindings.act.select:previous":"上一项","keybindings.act.select:next":"下一项","keybindings.act.select:accept":"选择","keybindings.act.select:cancel":"取消","keybindings.act.commandPalette:close":"关闭面板","keybindings.act.commandPalette:execute":"执行命令","keybindings.act.commandPalette:previous":"上一项","keybindings.act.commandPalette:next":"下一项","keybindings.act.permission:toggleDebug":"切换调试","keybindings.act.diff:dismiss":"关闭 Diff","keybindings.act.diff:previousFile":"上一个文件","keybindings.act.diff:nextFile":"下一个文件","keybindings.act.diff:viewDetails":"查看详情","keybindings.act.plugin:toggle":"切换插件","keybindings.act.plugin:install":"安装插件","keybindings.act.help:dismiss":"关闭帮助","keybindings.act.transcript:exit":"退出转录","keybindings.act.transcript:toggleShowAll":"显示全部","keybindings.act.messageSelector:up":"向上","keybindings.act.messageSelector:down":"向下","keybindings.act.messageSelector:top":"到顶部","keybindings.act.messageSelector:bottom":"到底部","keybindings.act.messageSelector:select":"选择","common.close":"关闭","changes.revert":"还原","changes.revertDirectory":"还原目录","message.clickToEnlarge":"点击放大","channel.botIdPlaceholder":"输入 Bot ID","channel.secretPlaceholder":"输入 Secret","filePreview.zoomOut":"缩小","filePreview.zoomIn":"放大","filePreview.fitToWindow":"适应窗口","filePreview.actualSize":"实际大小 (1:1)","filePreview.pdfPreview":"PDF 预览"},en:{"app.connecting":"Connecting to CodeBuddy Code...","app.connectFailed":"Connection failed","app.retry":"Retry","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"How can I help you today?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"Slide Generation","chat.empty.tag.research":"Deep Research","chat.empty.tag.docs":"Document Processing","chat.empty.tag.data":"Data Analysis","chat.thinking":"Thinking","chat.waitingPermission":"Waiting for permission","chat.waitingUser":"Waiting for user","chat.error":"Error","chat.sessionEnded":"Session ended","chat.stopped":"Stopped","chat.error.refusal":"The agent refused to continue execution. This may be due to content policy restrictions or other limitations.","chat.error.network":"Network connection failed or the service is temporarily unavailable. Please try again later.","chat.error.auth":"Authentication failed or insufficient permissions. Please sign in again and retry.","chat.error.quota":"Quota limit reached or too many requests. Please try again later.","chat.error.modelService":"The model service returned an error. Please retry or try again later.","chat.error.maxTokens":"Response was truncated due to reaching the maximum token limit. You may continue the conversation or ask for a more concise response.","chat.error.maxTurnRequests":"The maximum number of model requests per turn has been exceeded. You may send a new message to continue.","chat.newChat":"New Chat","chat.disclaimer":"Answers generated by AI are for reference only","chat.compacted":"Conversation compacted","chat.compacting":"Compacting conversation...","phase.preparing":"Preparing","phase.modelRequesting":"Waiting for model","phase.modelStreaming":"Streaming","phase.modelDone":"Processing","phase.toolExecuting":"Running tool","phase.modelStreamingTool":"Writing","phase.retrying":"Retrying","progress.compacting":"Compacting context","input.placeholder":"Start from an idea...","input.placeholderRunning":"Messages will be queued...","input.placeholderPending":"Please handle the permission request first...","input.send":"Send (Enter)","input.stop":"Stop","input.thinking":"Thinking","input.deepThinking":"Deep Thinking","input.promptFailed":"Prompt failed","input.sendQueued":"Send queued (Enter)","input.dropHint":"Drop files here","input.addImage":"Add image","input.addFile":"Add file","input.imageTooLarge":"Image must be under 10MB","input.tooManyImages":"Up to 5 images allowed","input.fileTooLarge":"File must be under 1MB","input.tooManyFiles":"Up to 10 files allowed","input.menu.image":"Image","input.menu.file":"File","input.newline":"New line","input.contextMenu.newline":"New line","input.contextMenu.send":"Send","queue.more":" more queued","status.running":"Running","tool.writeFile":"Write file","tool.readFile":"Read file","tool.execute":"Execute","tool.searchFiles":"Search files","tool.searchContent":"Search content","tool.fetchWeb":"Fetch web","tool.searchWeb":"Search web","tool.defaultName":"Tool","tool.moreItems":"... {count} more","interruption.title":"Permission Required","interruption.tool":"Tool","interruption.allow":"Allow","interruption.allowAll":"Allow All","interruption.deny":"Deny","interruption.approved":"Approved","interruption.denied":"Denied","interruption.edits":"{count} edits","interruption.yes":"Yes","interruption.keepPlanning":"No, keep planning","interruption.exitPlanMode":"Exit plan mode","interruption.readyToCode":"Ready to code?","theme.light":"Light","theme.dark":"Dark","theme.system":"System","locale.zh":"Chinese","locale.en":"English","locale.system":"System","sidebar.nav.plugins":"Plugins","sidebar.nav.tasks":"Tasks","sidebar.search.placeholder":"Search...","sidebar.chatHistory":"Chat History","sidebar.workspace":"Workspace","sidebar.connectionStatus":"Connection Status","sidebar.status":"Status","sidebar.sessionId":"Session ID","sidebar.notConnected":"Not connected","sidebar.modelSelection":"Model Selection","sidebar.noModels":"No models available","sidebar.environment":"Environment","sidebar.cwd":"Working Directory","sidebar.os":"OS","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"Gateway Mode","sidebar.tunnelUrl":"Tunnel URL","sidebar.clickToCopy":"Click to copy","sidebar.copied":"Copied","sidebar.permissionMode":"Permission Mode","sidebar.noModes":"No modes available","sidebar.preferences":"Preferences","sidebar.keybindings":"Keybindings","sidebar.group.workspace":"Workspace","sidebar.group.observability":"Observability","sidebar.group.preferences":"Preferences","bottomSheet.attachments":"Attach","bottomSheet.navigation":"Navigate","sidebar.theme":"Theme","sidebar.language":"Language","sidebar.user":"User","sidebar.authMethod":"Password","sidebar.noAuth":"No Auth","sidebar.version":"Remote UI v1.0","connection.connected":"Connected","connection.connecting":"Connecting","connection.disconnected":"Disconnected","connection.error":"Error","message.copyToClipboard":"Copy to clipboard","message.copied":"Copied","message.copy":"Copy","message.assistantName":"CodeBuddy Code","thinking.title":"Thinking Process","thinking.thinking":"Thinking","thinking.done":"Thought for","thinking.seconds":" {n}s","thinking.expand":"Expand","thinking.collapse":"Collapse","diff.noChanges":"No changes","login.title":"CodeBuddy Remote Control","login.subtitle":"Enter the password shown in your terminal","login.placeholder":"Password","login.submit":"Login","login.error.incorrect":"Incorrect password","login.error.rateLimit":"Too many login attempts. Please try again later.","login.error.required":"Password is required","login.hint.password":"Tip: The password is displayed when the server starts.","login.hint.urlAuth":"You can also use <code>?password=xxx</code> to login automatically.","login.hint.disable":'Or set <code>gateway.auth: "none"</code> in <code>~/.codebuddy/settings.json</code> to disable.',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"Privacy Policy","login.terms":"Terms of Service","sidebar.interactionMode":"Interaction Mode","sidebar.chatMode":"Chat","sidebar.terminalMode":"Terminal","sidebar.canvas":"Canvas","canvas.title":"Infinite Canvas","canvas.addTerminal":"Add Terminal","canvas.zoomIn":"Zoom In","canvas.zoomOut":"Zoom Out","canvas.fitView":"Fit View","canvas.resetView":"Reset View","canvas.empty":"Click the + button in the toolbar to add a terminal","canvas.openStandalone":"Open canvas in new window","canvas.tileMenu.close":"Close","canvas.tileMenu.duplicate":"Duplicate Terminal","canvas.tileMenu.maximize":"Maximize","canvas.tileMenu.minimize":"Minimize","canvas.tileMenu.restore":"Restore","canvas.tileMenu.openStandalone":"Open in new window","canvas.standalone.missingPaneId":"Missing pane ID","canvas.defaultTitle":"Terminal","terminal.connecting":"Connecting terminal...","terminal.title":"Terminal","terminal.disconnected":"Terminal disconnected","terminal.error":"Terminal connection failed","terminal.reconnect":"Reconnect","terminal.splitHorizontal":"Split Right","terminal.splitVertical":"Split Down","terminal.closePane":"Close Terminal","terminal.maxPanes":"Max panes reached","sidebar.instances":"Instances","sidebar.activeInstances":"active instances","sidebar.manageInstances":"Manage Instances","sidebar.remoteControl":"Channels","instance.title":"Instance List","instance.switch":"Instance","instance.switchTitle":"Switch Instance","instance.current":"Current","instance.manual":"Manual","instance.switchTo":"Switch to this instance","instance.manage":"Manage Instances","instance.managerTitle":"Instance Manager","instance.addInstance":"Add Instance","instance.name":"Instance Name","instance.namePlaceholder":"Custom instance name (optional, defaults to directory name)","instance.url":"Instance URL","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"Password","instance.optional":"Optional","instance.passwordPlaceholder":"Access password","instance.cancel":"Cancel","instance.add":"Add","instance.remove":"Remove this instance","instance.noInstances":"No other instances","instance.noInstancesHint":"Start more CodeBuddy Code instances or add remote instances manually","instance.cwd":"Working Directory","instance.topic":"Topic","instance.startedAt":"Started at","instance.local":"Local","instance.tunnel":"Tunnel","instance.uptime.days":"d ago","instance.uptime.hours":"h ago","instance.uptime.minutes":"m ago","instance.uptime.justNow":"Just now","instance.addError":"Failed to add instance","instance.removeError":"Failed to remove instance","instance.copyUrl":"Copy URL","instance.copied":"Copied","instance.subtitle":"Manage and switch between instances","instance.refresh":"Refresh","instance.refreshed":"Refreshed","instance.loading":"Loading instances...","instance.error":"Failed to load instances","instance.retry":"Retry","question.multiple":"multiple","question.customAnswer":"Or type a custom answer...","question.reviewAnswers":"Review answers","question.singleTitle":"Question","question.titleWithCount":"Questions ({count})","question.reviewTab":"Review","question.next":"Next","question.submit":"Submit","question.cancel":"Cancel","question.answered":"Answered","question.cancelled":"Question cancelled","todo.title":"Tasks","todo.executing":"Task {n} executing","todo.untitled":"Untitled","history.title":"Sessions","history.description":"Click a session to switch to that conversation","history.noData":"No sessions","history.noDataHint":"Start a new conversation","history.backToChat":"Back to Chat","history.loading":"Loading...","history.loadError":"Failed to load","history.retry":"Retry","history.current":"Current","history.messages":"{count} messages","history.delete":"Delete","history.deleteConfirm":"Are you sure you want to delete this session?","history.deleteCancel":"Cancel","history.deleteOk":"Delete","history.rename":"Rename","history.renameTitle":"Rename Session","history.renamePlaceholder":"Enter new name","history.renameCancel":"Cancel","history.renameOk":"OK","history.cannotDeleteCurrent":"Cannot delete current session","settings.title":"Preferences","settings.appearance":"Appearance","settings.model":"Model Selection","settings.mode":"Permission Mode","settings.systemInfo":"System Info","settings.backToChat":"Back to Chat","settings.tab.user":"User","settings.tab.project":"Project","settings.group.modelAndReasoning":"Model & Reasoning","settings.group.behavior":"Behavior","settings.group.memory":"Memory","settings.group.language":"Language","settings.group.advanced":"Advanced","settings.group.sandbox":"Security Sandbox","settings.item.model":"Default Model","settings.item.model.desc":"Set the default AI model","settings.item.reasoningEffort":"Reasoning Effort","settings.item.reasoningEffort.desc":"Control model reasoning depth","settings.item.alwaysThinkingEnabled":"Always Enable Thinking","settings.item.autoCompactEnabled":"Auto Compact Context","settings.item.includeCoAuthoredBy":"Include Co-authored-by","settings.item.fileCheckpointingEnabled":"File Checkpointing","settings.item.fileCheckpointingEnabled.desc":"Enable file version rollback","settings.item.promptSuggestionEnabled":"Prompt Suggestions","settings.item.ignoreGitIgnore":"Ignore .gitignore","settings.item.ignoreGitIgnore.desc":"Ignore .gitignore rules when searching","settings.item.deferToolLoading":"Defer Tool Loading","settings.item.hookOutputCollapsed":"Collapse Hook Output","settings.item.memory.enabled":"Enable Memory","settings.item.memory.autoMemoryEnabled":"Auto Memory","settings.item.memory.autoMemoryEnabled.desc":"Auto-save important info to memory","settings.item.language":"Response Language","settings.item.language.desc":"Language for AI responses","settings.item.cleanupPeriodDays":"Chat History Retention (days)","settings.item.imageHistoryRetainRounds":"Image Retention Rounds","settings.item.imageHistoryRetainRounds.desc":"Rounds to retain images in history","settings.item.env":"Environment Variables","settings.item.env.desc":"Variables applied to each session (JSON)","settings.item.sandbox.enabled":"Enable Sandbox","settings.item.sandbox.enabled.desc":"Run Bash commands in sandbox, restrict file and network access","settings.item.sandbox.autoAllowBashIfSandboxed":"Auto-approve in Sandbox","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"Auto-approve commands when running in sandbox","settings.loading":"Loading...","settings.saved":"Saved","settings.saveFailed":"Save failed","settings.notSet":"Not set","settings.default":"Default","settings.reset":"Reset","settings.noProjectSettings":"No project-level settings available","settings.effort.low":"Low","settings.effort.medium":"Medium","settings.effort.high":"High","settings.effort.xhigh":"Extra High","page.title":"CodeBuddy Code","tool.processExited":"[Process exited]","tool.itemsCount":"{count} items","tool.showAllItems":"Show all {count} items","tool.moreLinesCount":"... {count} more lines","tool.generatedImage":"Generated image","tool.editedImage":"Edited image","tool.imageGen":"ImageGen","tool.imageEdit":"ImageEdit","tool.toolSearch":"ToolSearch","tool.teamCreate":"TeamCreate","tool.teamDelete":"TeamDelete","tool.taskCreate":"TaskCreate","tool.taskUpdate":"TaskUpdate","tool.taskList":"TaskList","tool.taskGet":"TaskGet","tool.sendMessage":"SendMessage","tool.shutdown":"Shutdown","tool.taskCompleted":"Task completed","tool.shutdownRejected":"Shutdown rejected","tool.planResponse":"Plan response","tool.approved":"approved","tool.rejected":"rejected","tool.webSearch":"WebSearch","tool.webFetch":"WebFetch","tool.saveMemory":"SaveMemory","tool.askUserQuestion":"AskUserQuestion","tool.enterPlanMode":"Enter Plan Mode","tool.exitPlanMode":"Exit Plan Mode","tool.allowedActions":"Allowed actions:","tool.skill":"Skill","tool.agent":"Agent","tool.failed":"failed","tool.completed":"completed","tool.toolsCount":"{count} tools","tool.background":"background","tool.permissionsCount":"{count} permissions","terminal.unknownError":"Unknown error","terminal.processExited":"[Process exited]","terminal.connectionLost":"Connection lost","terminal.wsConnectionFailed":"WebSocket connection failed","terminal.createSessionFailed":"Failed to create terminal session","terminal.reconnectFailed":"Reconnect failed","team.title":"Team","team.activeCount":"{count} active","team.doneCount":"{count} done","team.waitingForTeammates":"Waiting for {count} teammate{s}…","team.backToMain":"Back to main chat","team.loadingHistory":"Loading conversation…","team.noHistory":"No conversation history yet","team.agentRunning":"Agent is running…","team.delivered":"Delivered","team.showLess":"Show less","team.moreLines":"… ({count} more lines)","team.tools":"{count} tools","team.tokens":"{count} tokens","instance.tunnelMode":"Tunnel","instance.localMode":"Local","workspace.searchPlaceholder":"Search directories...","workspace.switch":"Switch","workspace.switchHere":"Switch to this directory","workspace.switching":"Switching...","workspace.noResults":"No matching directories","workspace.emptyDir":"This directory is empty","workspace.pathPlaceholder":"Enter path or directory name...","workspace.selectDir":"Create bot in this directory","workspace.filterPlaceholder":"Filter subdirectories...","workspace.recent.title":"Recent Workspaces","workspace.recent.daysAgo":"d ago","workspace.recent.hoursAgo":"h ago","workspace.recent.minutesAgo":"m ago","workspace.recent.justNow":"Just now","workspace.recent.remove":"Remove","workspace.browseTitle":"Browse Workspaces","workspace.recentWorkspaces":"Recent Workspaces","workspace.createNew":"Create New Bot","workspace.browseDir":"Browse Directory","workspace.instanceLocal":"Local","workspace.instanceTunnel":"Tunnel","workspace.instanceCurrent":"Current","workspace.switchInstance":"Switch","workspace.switchingInstance":"Switching...","workspace.switchingWithGateway":"Preparing to switch...","workspace.instanceStarted":"Started","workspace.noWorkspaces":"No active workspaces","workspace.noWorkspacesHint":"Browse directories to create a new bot","workspace.instanceCount":"{count} bots","question.multiLabel":"multi","tasks.title":"Recommended Templates","tasks.subtitle":"Select a template to create a scheduled task","tasks.loading":"Loading recommended templates...","tasks.error":"Failed to load templates","tasks.retry":"Retry","tasks.refresh":"Refresh","tasks.refreshed":"Refreshed","tasks.empty":"No templates available","tasks.interval":"Every {value}","tasks.interval.1d":"Daily","tasks.interval.2d":"Every 2 days","tasks.interval.3d":"Every 3 days","tasks.interval.1w":"Weekly","tasks.interval.2w":"Every 2 weeks","tasks.interval.1m":"Monthly","scheduled.title":"Scheduled Tasks","scheduled.subtitle":"Active scheduled tasks in the current session","scheduled.loading":"Loading...","scheduled.empty":"No scheduled tasks","scheduled.emptyHint":"Use /loop or CronCreate in chat to create one","scheduled.create":"Create Task","scheduled.creating":"Creating...","scheduled.delete":"Delete","scheduled.cron":"Cron Expression","scheduled.prompt":"Prompt","scheduled.promptPlaceholder":"Prompt to execute on each fire...","scheduled.recurring":"Recurring","scheduled.oneShot":"One-shot","scheduled.durable":"Durable","scheduled.sessionOnly":"Session-only","scheduled.lastFired":"Last fired","plugins.title":"Plugins","plugins.installedPlugins":"Installed Plugins","plugins.browseMarketplace":"Browse Marketplace","plugins.marketplaces":"Marketplaces","plugins.enabled":"Enabled","plugins.disabled":"Disabled","plugins.enable":"Enable","plugins.disable":"Disable","plugins.uninstall":"Uninstall","plugins.install":"Install","plugins.confirmUninstall":"Are you sure you want to uninstall this plugin?","plugins.marketplace":"Marketplace","plugins.addMarketplace":"Add Marketplace","plugins.removeMarketplace":"Remove","plugins.confirmRemoveMarketplace":"Are you sure you want to remove this marketplace?","plugins.noPlugins":"No plugins installed","plugins.noPluginsHint":"Install plugins from a marketplace to extend functionality","plugins.noMarketplaces":"No marketplaces configured","plugins.noMarketplacesHint":"Add a plugin marketplace to browse and install plugins","plugins.selectMarketplace":"Select Marketplace","plugins.selectMarketplaceHint":"Select a marketplace to browse available plugins","plugins.marketplaceNotFound":"Marketplace not found","plugins.noAvailablePlugins":"No available plugins in this marketplace","plugins.noAvailablePluginsHint":"Try adding other marketplaces or check back later","plugins.installed":"Installed","plugins.browsingMarketplace":"Loading...","plugins.loading":"Loading...","plugins.error":"Failed to load plugins","plugins.retry":"Retry","plugins.sourcePlaceholder":"Marketplace URL (Git URL or local path)","plugins.namePlaceholder":"Marketplace name (optional)","plugins.cancel":"Cancel","plugins.add":"Add","plugins.version":"Version","plugins.operationFailed":"Operation failed","plugins.searchPlaceholder":"Search plugins...","plugins.allMarketplaces":"All Marketplaces","plugins.noSearchResults":"No matching plugins found","plugins.totalCount":"plugins","plugins.refresh":"Refresh","plugins.installedLabel":"Installed","plugins.category":"Category","plugins.author":"Author","plugins.license":"License","plugins.homepage":"Homepage","plugins.repository":"Repository","plugins.source":"Source","plugins.keywords":"Keywords","plugins.features":"Features","plugins.scope":"Scope","plugins.scope.user":"User","plugins.scope.project":"Project","plugins.scope.project-local":"Local","plugins.installScope.user":"Install for you (user scope)","plugins.installScope.project":"Install for all collaborators (project scope)","plugins.installScope.local":"Install for you, in this repo only (local scope)","plugins.policyCannotRemove":"Cannot be uninstalled","plugins.policyCannotSwitchoff":"Cannot be disabled","plugins.policyCannotEdit":"Cannot be edited","channel.from":"From","channel.group":"Group","channel.replyTo":"Reply to {source}","channel.wechat":"WeChat","channel.wecom":"WeCom","channel.wecomBot":"WeCom Bot","remoteControl.title":"Remote Control","remoteControl.subtitle":"Manage channel connections","remoteControl.connectedChannels":"Connected Channels","remoteControl.noChannels":"No channels connected","remoteControl.noChannelsHint":"Add a WeChat or WeCom channel, or install more from the marketplace","remoteControl.addWeChat":"Add WeChat Bot","remoteControl.addWeCom":"Add WeCom Bot","remoteControl.connect":"Connect","remoteControl.disconnect":"Disconnect","remoteControl.delete":"Delete","remoteControl.add":"Add","remoteControl.connected":"Connected","remoteControl.disconnected":"Disconnected","remoteControl.connecting":"Connecting...","remoteControl.installMore":"Install More Channels","remoteControl.installMoreHint":"Browse the plugin marketplace for third-party channel plugins","remoteControl.browseMarketplace":"Browse Marketplace","remoteControl.builtIn":"Built-in","remoteControl.plugin":"Plugin","remoteControl.rebind":"Rebind","remoteControl.unbind":"Unbind","remoteControl.bot":" Bot","remoteControl.default":"Default ","remoteControl.next":"Next","remoteControl.cancel":"Cancel","remoteControl.wecomBotIdHint":"From: WeCom Admin → Apps → AI Assistant","remoteControl.wecomSecretHint":"Enter Secret and press Enter or click Connect","remoteControl.fetchingQr":"Fetching QR code...","remoteControl.scanQr":"Scan QR code with WeChat","sidebar.docs":"Docs","docs.title":"Documentation","docs.search.placeholder":"Search docs...","docs.search.noResults":"No matching documents found","docs.search.resultsCount":"{count} results","docs.loading":"Loading...","docs.loadError":"Failed to load document","docs.notFound":"Document not found","docs.apiReference":"API Reference","docs.toc":"On this page","docs.retry":"Retry","docs.backToList":"Back to docs","docs.expandAll":"Expand all","docs.collapseAll":"Collapse all","docs.openStandalone":"Open in new window","sidebar.stats":"Statistics","stats.title":"Statistics","stats.loading":"Loading statistics...","stats.refresh":"Refresh","stats.noData":"No statistics available","stats.tab.overview":"Overview","stats.tab.models":"Models","stats.tab.tools":"Tools","stats.sessions":"Sessions","stats.messages":"Messages","stats.activeDays":"Active Days","stats.currentStreak":"Current Streak","stats.longestStreak":"Longest Streak","stats.peakHour":"Peak Hour","stats.longestSession":"Longest Session","stats.favoriteModel":"Favorite Model","stats.totalTokens":"Total Tokens","stats.timeRange":"Stats from the last {days} days","stats.heatmap.less":"Less","stats.heatmap.more":"More","stats.days":"days","stats.tokensPerDay":"Tokens per Day","stats.allModels":"All Models","stats.input":"Input","stats.output":"Output","stats.cacheRead":"Cache Read","stats.cacheHitRate":"Cache Hit Rate","stats.cost":"Cost","stats.topTools":"Top Tools","stats.session.title":"Current Session","stats.session.apiDuration":"API Duration","stats.session.wallTime":"Wall Time","stats.session.linesAdded":"Lines Added","stats.session.linesDeleted":"Lines Deleted","stats.session.tokens":"Tokens","stats.na":"N/A","stats.heatmap.messages":"messages","stats.funFact.moreTokens":"You've used ~{times}x more tokens than {book}","stats.funFact.sameTokens":"You've used the same number of tokens as {book}","stats.funFact.longerSession":"Your longest session is ~{times}x longer than {activity}","sidebar.traces":"Traces","traces.title":"Traces","traces.loading":"Loading...","traces.refresh":"Refresh","traces.clear":"Clear","traces.clearConfirm":"Clear all trace data?","traces.noData":"No trace data yet. Send a message and traces will be collected automatically.","traces.selectWorker":"Select Worker","traces.current":"current","traces.spanCount":"{count} spans","traces.duration":"Duration","traces.status.ok":"OK","traces.status.error":"Error","traces.status.running":"Running","traces.status.cancelled":"Cancelled","traces.bottleneck":"Bottleneck","traces.bottleneckTip":"Slowest span, {pct}% of total","traces.spanDetail":"Span Detail","traces.spanDetail.type":"Type","traces.spanDetail.duration":"Duration","traces.spanDetail.model":"Model","traces.spanDetail.tokens":"Tokens","traces.spanDetail.input":"Input","traces.spanDetail.output":"Output","traces.spanDetail.error":"Error","traces.spanDetail.attributes":"Attributes","traces.legend.agent":"Agent","traces.legend.generation":"Generation","traces.legend.function":"Function","traces.legend.handoff":"Handoff","traces.legend.guardrail":"Guardrail","traces.back":"Back","traces.tab.timeline":"Timeline","traces.tab.tree":"Tree","traces.tab.flame":"Flame","traces.tab.graph":"Graph","traces.expandAll":"Expand All","traces.collapseAll":"Collapse All","traces.search":"Search spans...","traces.selfTime":"Self Time","traces.spanDetail.overview":"Overview","traces.spanDetail.io":"Input/Output","traces.noSpans":"No spans","traces.auto":"auto","traces.auxiliaryCount":"{count} auxiliary traces (memory, title, etc.)","traces.noIO":"No input/output data","traces.noAttrs":"No attributes","traces.fit":"Fit","traces.allSessions":"All sessions","traces.allInstances":"All instances","traces.llmCalls":"{count} LLM","sidebar.metrics":"Metrics","metrics.title":"System Metrics","metrics.loading":"Loading metrics...","metrics.refresh":"Refresh","metrics.cpu":"CPU","metrics.memory":"Memory","metrics.disk":"Disk","metrics.cores":"cores","metrics.workers":"Workers","metrics.noWorkers":"No running workers","metrics.current":"Current","metrics.uptime":"Uptime","metrics.version":"Version","sidebar.editor":"Files","editor.title":"Code Editor","editor.loading":"Loading...","editor.loadError":"Failed to load","editor.noFile":"Select a file to start editing","editor.unsaved":"Unsaved","editor.save":"Save","editor.saveAll":"Save All","editor.close":"Close","editor.closeOthers":"Close Others","editor.closeAll":"Close All","editor.newFile":"New File","editor.newFolder":"New Folder","editor.rename":"Rename","editor.delete":"Delete","editor.refresh":"Refresh","editor.emptyFolder":"Empty folder","editor.explorer":"EXPLORER","editor.toggleSidebar":"Toggle Sidebar","editor.collapseAll":"Collapse All","editor.openFolder":"Open Folder","editor.openFolderPlaceholder":"Enter directory path...","editor.parentFolder":"Parent Folder","editor.pin":"Pin","editor.unpin":"Unpin","editor.copyPath":"Copy Path","editor.copyRelativePath":"Copy Relative Path","editor.revealInExplorer":"Reveal in Explorer","editor.closeToRight":"Close to the Right","editor.closeSaved":"Close Saved","editor.quickOpen":"Quick Open File","editor.focusExplorer":"Focus Explorer","editor.recentFiles":"Recent Files","editor.quickOpenPlaceholder":"Type filename to search...","editor.quickOpenEmpty":"No matching files","editor.quickOpenLoading":"Loading file list...","editor.selected":"selected","editor.lines":"lines","editor.preview":"Switch to Preview","editor.source":"Switch to Source","sidebar.workers":"Workers","workers.title":"Worker Processes","workers.refresh":"Refresh","workers.active":"Active Workers","workers.empty":"No active worker processes","workers.daemon":"Daemon","workers.daemon.running":"Running","workers.daemon.stopped":"Stopped","workers.daemon.start":"Start","workers.daemon.starting":"Starting...","workers.daemon.stop":"Stop","workers.daemon.restart":"Restart","workers.action.logs":"Logs","workers.action.open":"Open","workers.action.kill":"Kill","workers.action.kill.confirm":"Are you sure you want to kill this worker process?","sidebar.logs":"Logs","logs.title":"Log Viewer","logs.selectWorker":"Select Worker","logs.current":"current","logs.search":"Search logs...","logs.autoRefresh":"Auto Refresh","logs.refresh":"Refresh","logs.empty":"No log content","command.btw.description":"Ask a quick side question without interrupting the main Agent work","command.clear.description":"Start a fresh conversation (previous chats remain accessible via /resume)","command.context.description":"Calculate and display context token distribution","command.cost.description":"Show the total cost and duration of the current session","command.doctor.description":"Diagnose and verify your CodeBuddy installation and settings","command.feedback.description":"Open the issue feedback page to report bugs or suggest features","command.gateway.description":'Manage the remote control gateway. Subcommands: "status" to show current status, "stop" to stop the gateway, "token" to regenerate access token, "tunnel" to start with tunnel',"command.remote-control.description":"Manage remote control long connection clients (start, stop, status, list)","command.login.description":"Switch Tencent Cloud CodeBuddy accounts","command.logout.description":"Sign out from your CodeBuddy Code account","command.plan.description":"Preview the current plan file content","command.pr-comments.description":"Get comments from a GitHub pull request","command.release-notes.description":"View release notes","command.review.description":"Review a pull request","command.skills.description":"List available skills","command.todos.description":"Display the current session's todo list","command.reload-plugins.description":"Reload all plugins, skills, agents, hooks, and MCP/LSP servers without restarting","command.plugin-validate.description":"Validate a plugin directory structure and manifest","command.init.description":"Analyzing your codebase…","command.compact.description":"Clear conversation history but keep a summary in context. Optional: /compact [instructions for summarization]","command.upgrade.description":"Open upgrade page in browser","command.statusline.description":"Set up Codebuddy Code's status line UI","command.security-review.description":"Complete a security review of the pending changes on the current branch","command.insights.description":"Generate AI-powered insights about your CodeBuddy Code usage patterns and activity","command.loop.description":"Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo, defaults to 10m)","command.task-manager.description":"Team task management - Smart task entry, assignment, tracking and analysis","sidebar.changes":"Changes","fileChanges.title":"Changes","fileChanges.changesSection":"FILE CHANGES","fileChanges.empty":"No file changes","fileChanges.showChanges":"Show file changes","fileChanges.hideChanges":"Hide file changes","fileChanges.revertAll":"Revert all","fileChanges.revertCode":"Revert code","fileChanges.revertChat":"Revert chat","fileChanges.revertCodeAndChat":"Revert all","fileChanges.checkpoints":"Checkpoints","fileChanges.noCheckpoints":"No checkpoints","filePreview.binaryNotSupported":"This file cannot be previewed in the editor","filePreview.download":"Download","error.viewCrashed":"This view encountered an error","error.appCrashed":"Something went wrong","error.newChatFailed":"Failed to create new chat, please try again","error.switchSessionFailed":"Failed to switch session, please try again","commandPalette.placeholder":"Type a command...","commandPalette.commands":"Commands","commandPalette.views":"Views","commandPalette.actions":"Actions","commandPalette.noResults":"No matching commands","commandPalette.newChat":"New Chat","commandPalette.toggleTheme":"Toggle Theme","commandPalette.toggleLocale":"Toggle Language","commandPalette.tip":"Open command palette","app.confirm":"Confirm","app.cancel":"Cancel","tool.toolSingular":"tool executed","tool.toolPlural":"tools executed","keybindings.title":"Keybindings","keybindings.search.placeholder":"Search keybindings... (e.g. submit, ctrl+enter)","keybindings.source.default":"Default","keybindings.source.user":"User","keybindings.record.title":"Record Shortcut","keybindings.record.hint":"Press desired key combination...","keybindings.record.conflict":"Conflicts with","keybindings.action.edit":"Edit","keybindings.action.reset":"Reset","keybindings.action.unbind":"Unbind","keybindings.reset.all":"Reset all","keybindings.noResults":"No matching keybindings","keybindings.empty":"No keybindings","keybindings.loading":"Loading...","keybindings.ctx.Global":"Global","keybindings.ctx.Chat":"Chat Input","keybindings.ctx.InputBox":"Text Input","keybindings.ctx.Terminal":"Terminal","keybindings.ctx.Autocomplete":"Autocomplete","keybindings.ctx.Confirmation":"Confirmation","keybindings.ctx.HistorySearch":"History Search","keybindings.ctx.Task":"Task Running","keybindings.ctx.Settings":"Settings","keybindings.ctx.CommandPalette":"Command Palette","keybindings.ctx.Select":"Select List","keybindings.ctx.PermissionDialog":"Permission Dialog","keybindings.ctx.Help":"Help","keybindings.ctx.Plugin":"Plugin","keybindings.ctx.DiffDialog":"Diff Dialog","keybindings.ctx.MessageSelector":"Message Selector","keybindings.ctxDesc.Global":"Active everywhere, regardless of focus","keybindings.ctxDesc.Chat":"When the chat input is focused","keybindings.ctxDesc.InputBox":"When a text input is active","keybindings.ctxDesc.Terminal":"When the terminal view is active","keybindings.ctxDesc.Autocomplete":"When autocomplete menu is visible","keybindings.ctxDesc.Confirmation":"When a confirmation/permission dialog is shown","keybindings.ctxDesc.HistorySearch":"When searching command history (ctrl+r)","keybindings.ctxDesc.Task":"When a task/agent is running in the foreground","keybindings.ctxDesc.Settings":"When the settings panel is open","keybindings.ctxDesc.CommandPalette":"When the command palette is open","keybindings.ctxDesc.Select":"When a select/list component is focused","keybindings.ctxDesc.PermissionDialog":"When a tool permission dialog is shown","keybindings.ctxDesc.Help":"When the help overlay is open","keybindings.ctxDesc.Plugin":"When the plugin dialog is open","keybindings.ctxDesc.DiffDialog":"When the diff dialog is open","keybindings.ctxDesc.MessageSelector":"When the message selector (rewind) is open","keybindings.act.app:interrupt":"Interrupt","keybindings.act.app:exit":"Exit","keybindings.act.app:redraw":"Redraw Screen","keybindings.act.app:toggleTodos":"Toggle Todos","keybindings.act.app:toggleTranscript":"Toggle Transcript","keybindings.act.app:toggleSidebar":"Toggle Sidebar","keybindings.act.app:toggleTerminal":"Toggle Terminal","keybindings.act.app:commandPalette":"Command Palette","keybindings.act.app:newChat":"New Chat","keybindings.act.app:settings":"Settings","keybindings.act.app:focusInput":"Focus Input","keybindings.act.app:keybindings":"Keybinding Settings","keybindings.act.history:search":"Search History","keybindings.act.history:previous":"Previous History","keybindings.act.history:next":"Next History","keybindings.act.history:open":"Open History","keybindings.act.chat:cancel":"Cancel","keybindings.act.chat:submit":"Submit","keybindings.act.chat:newline":"New Line","keybindings.act.chat:killAgents":"Kill Agents","keybindings.act.chat:cycleMode":"Cycle Mode","keybindings.act.chat:modelPicker":"Model Picker","keybindings.act.chat:thinkingToggle":"Toggle Thinking","keybindings.act.chat:undo":"Undo","keybindings.act.chat:externalEditor":"External Editor","keybindings.act.chat:stash":"Stash","keybindings.act.chat:imagePaste":"Paste Image","keybindings.act.autocomplete:accept":"Accept","keybindings.act.autocomplete:dismiss":"Dismiss","keybindings.act.autocomplete:previous":"Previous","keybindings.act.autocomplete:next":"Next","keybindings.act.confirm:yes":"Confirm","keybindings.act.confirm:no":"Cancel","keybindings.act.confirm:previous":"Previous","keybindings.act.confirm:next":"Next","keybindings.act.confirm:toggle":"Toggle","keybindings.act.confirm:toggleExplanation":"Toggle Explanation","keybindings.act.task:background":"Run in Background","keybindings.act.historySearch:next":"Next","keybindings.act.historySearch:accept":"Accept","keybindings.act.historySearch:cancel":"Cancel","keybindings.act.historySearch:execute":"Execute","keybindings.act.settings:close":"Close Settings","keybindings.act.settings:search":"Search Settings","keybindings.act.select:previous":"Previous","keybindings.act.select:next":"Next","keybindings.act.select:accept":"Select","keybindings.act.select:cancel":"Cancel","keybindings.act.commandPalette:close":"Close Palette","keybindings.act.commandPalette:execute":"Execute Command","keybindings.act.commandPalette:previous":"Previous","keybindings.act.commandPalette:next":"Next","keybindings.act.permission:toggleDebug":"Toggle Debug","keybindings.act.diff:dismiss":"Close Diff","keybindings.act.diff:previousFile":"Previous File","keybindings.act.diff:nextFile":"Next File","keybindings.act.diff:viewDetails":"View Details","keybindings.act.plugin:toggle":"Toggle Plugin","keybindings.act.plugin:install":"Install Plugin","keybindings.act.help:dismiss":"Close Help","keybindings.act.transcript:exit":"Exit Transcript","keybindings.act.transcript:toggleShowAll":"Show All","keybindings.act.messageSelector:up":"Up","keybindings.act.messageSelector:down":"Down","keybindings.act.messageSelector:top":"Top","keybindings.act.messageSelector:bottom":"Bottom","keybindings.act.messageSelector:select":"Select","common.close":"Close","changes.revert":"Revert","changes.revertDirectory":"Revert directory","message.clickToEnlarge":"Click to enlarge","channel.botIdPlaceholder":"Enter Bot ID","channel.secretPlaceholder":"Enter Secret","filePreview.zoomOut":"Zoom Out","filePreview.zoomIn":"Zoom In","filePreview.fitToWindow":"Fit to Window","filePreview.actualSize":"Actual Size (1:1)","filePreview.pdfPreview":"PDF Preview"}};function ne(){const{mode:e,resolved:t,setLocale:n,toggle:i}=fr();function s(d){return Dd[t][d]??d}function l(d){return Dd[t][d]}return{t:s,tryT:l,locale:e,resolved:t,setLocale:n,toggleLocale:i}}const Ip=4;let Db=0;function Ob(){return`pane-${Date.now()}-${++Db}`}function Rp(e){return{id:Ob(),ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}function an(e){return e.type==="leaf"?1:an(e.children[0])+an(e.children[1])}function br(e){return e.type==="leaf"?[e.paneId]:[...br(e.children[0]),...br(e.children[1])]}function wi(e,t,n,i){return e.type==="leaf"?e.paneId===t?{type:"split",direction:n,children:[{type:"leaf",paneId:t},{type:"leaf",paneId:i}],ratio:.5}:e:{...e,children:[wi(e.children[0],t,n,i),wi(e.children[1],t,n,i)]}}function Ei(e,t){if(e.type==="leaf")return e.paneId===t?null:e;const n=Ei(e.children[0],t),i=Ei(e.children[1],t);return n===null?i:i===null?n:{...e,children:[n,i]}}function Lp(e,t,n){if(t.length===0)return e.type==="split"?{...e,ratio:n}:e;if(e.type==="split"){const[i,...s]=t,l=[...e.children];return l[i]=Lp(l[i],s,n),{...e,children:l}}return e}function Od(e){const t=ae({"Content-Type":"application/json"});fetch(`/api/v1/pty/${e}`,{method:"DELETE",headers:t}).catch(()=>{})}function Dp(){const e=Rp();return{panes:{[e.id]:e},layout:{type:"leaf",paneId:e.id},activePaneId:e.id}}const Qr=Dp(),me=Te()($n((e,t)=>({mode:"chat",mainView:"chat",terminalTitle:null,panes:Qr.panes,layout:Qr.layout,activePaneId:Qr.activePaneId,setMode:n=>{e({mode:n,mainView:n==="terminal"?"terminal":"chat"})},setMainView:n=>{e({mainView:n,mode:n==="terminal"?"terminal":"chat"})},setTerminalTitle:n=>e({terminalTitle:n}),splitPane:(n,i)=>{const s=t(),l=i??s.activePaneId;if(an(s.layout)>=Ip)return;const d=Rp(),a=wi(s.layout,l,n,d.id),o={...s.panes,[d.id]:d};e({layout:a,panes:o,activePaneId:d.id})},closePane:n=>{const i=t();if(an(i.layout)<=1)return;const s=Ei(i.layout,n);if(!s)return;const l=i.panes[n];l!=null&&l.ptySessionId&&Od(l.ptySessionId);const d={...i.panes};delete d[n];const a=br(s),o=a.includes(i.activePaneId)?i.activePaneId:a[0];e({layout:s,panes:d,activePaneId:o})},setActivePaneId:n=>e({activePaneId:n}),setRatio:(n,i)=>{const s=Math.max(.1,Math.min(.9,i)),l=Lp(t().layout,n,s);e({layout:l})},setPaneSession:(n,i)=>{const s={...t().panes};s[n]&&(s[n]={...s[n],ptySessionId:i},e({panes:s}))},setPaneStatus:(n,i)=>{const s={...t().panes};s[n]&&(s[n]={...s[n],ptyStatus:i},e({panes:s}))},setPaneError:(n,i)=>{const s={...t().panes};s[n]&&(s[n]={...s[n],errorMessage:i},e({panes:s}))},setPaneTitle:(n,i)=>{const s={...t().panes};s[n]&&(s[n]={...s[n],title:i},e({panes:s}))},reset:()=>{const n=t().panes;for(const s of Object.values(n))s.ptySessionId&&Od(s.ptySessionId);const i=Dp();e({panes:i.panes,layout:i.layout,activePaneId:i.activePaneId})}}),{namespace:"terminal",fields:["layout","panes"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{if(e.layout&&e.panes){const n=e.layout,i=e.panes,s=br(n);if(s.every(l=>l in i)){const l={};for(const d of s)l[d]={...i[d],ptyStatus:"disconnected",errorMessage:null};t({layout:n,panes:l,activePaneId:s[0]})}}}})),Op="/assets/dark-claw-cat-D_ew_BKV.png",$p="/assets/light-claw-cat-BgBWmnmi.png",jp="/assets/red-claw-cat--t2EuBIB.png",Mp={small:{container:"w-20 h-20",text:"text-[12px]"},medium:{container:"w-32 h-32",text:"text-[14px]"},large:{container:"w-40 h-40",text:"text-[16px]"}};function Pp({size:e="medium",className:t=""}){const i=Ke(l=>l.resolved)==="dark"?Op:$p,s=Mp[e];return r.jsxs("div",{className:`relative ${s.container} ${t}`,children:[r.jsx("img",{src:i,alt:"",className:"cat-loading-layer cat-loading-layer-base absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"}),r.jsx("img",{src:jp,alt:"",className:"cat-loading-layer cat-loading-layer-color absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"})]})}function dt({size:e="medium",text:t="Loading...",className:n=""}){const i=Mp[e];return r.jsxs("div",{className:`flex flex-col items-center justify-center gap-4 ${n}`,children:[r.jsx(Pp,{size:e}),t&&r.jsx("div",{className:`text-text-secondary ${i.text} font-medium animate-pulse`,children:t})]})}function $b({size:e="medium",className:t=""}){return r.jsx(Pp,{size:e,className:t})}const Vn={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},Kn={background:"#121212",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#121212",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"},jb=2e3;function hn(){return ae({"Content-Type":"application/json"})}function Mb(e){const t=Cr(),n=t?`?password=${encodeURIComponent(t)}`:"";return`/api/v1/pty/${e}/output${n}`}async function Pb(e,t){try{await fetch(`/api/v1/pty/${e}/input/send`,{method:"POST",headers:hn(),body:JSON.stringify({data:t})})}catch{}}async function $d(e,t,n){try{await fetch(`/api/v1/pty/${e}/resize`,{method:"POST",headers:hn(),body:JSON.stringify({cols:t,rows:n})})}catch{}}async function jd(e){try{return(await fetch(`/api/v1/pty/${e}`,{headers:hn()})).ok}catch{return!1}}async function Md(e,t,n){const i={cols:e,rows:t};n&&(i.cwd=n);const s=await fetch("/api/v1/pty",{method:"POST",headers:hn(),body:JSON.stringify(i)});if(!s.ok){const a=await s.json().catch(()=>null),o=typeof(a==null?void 0:a.error)=="string"?a.error:typeof(a==null?void 0:a.message)=="string"?a.message:`HTTP ${s.status}`;throw new Error(o)}const l=await s.json(),d=l.data??l;return{sessionId:d.sessionId,cwd:typeof d.cwd=="string"?d.cwd:""}}async function Pd(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:hn()});if(!t.ok)return null;const n=await t.json(),i=n.data??n;return{cwd:typeof(i==null?void 0:i.cwd)=="string"?i.cwd:""}}catch{return null}}async function Fb(){try{const e=await fetch("/api/v1/pty",{headers:hn()});if(!e.ok)return[];const t=await e.json();return(t.data??t).sessions||[]}catch{return[]}}function Bb(e){const t=me.getState().panes,n=new Set;for(const[i,s]of Object.entries(t))i!==e&&s.ptySessionId&&n.add(s.ptySessionId);return n}function Ub(e,t){const n=[];let i="",s="",l=t;for(;l<e.length;){const d=e.indexOf(`
|
|
617
617
|
`,l);if(d===-1)break;const a=e.substring(l,d);l=d+1,a===""?(s&&n.push({event:i||"message",data:s}),i="",s=""):a.startsWith("event: ")?i=a.substring(7):a.startsWith("data: ")&&(s=a.substring(6))}return{events:n,newIndex:l}}function ts({paneId:e,initialCwd:t,onPtyCreated:n}){const{t:i}=ne(),{resolved:s}=Ke(),l=me(A=>A.panes[e]),d=me(A=>A.activePaneId),a=me(A=>A.layout),o=me(A=>A.mainView),c=me(A=>A.setActivePaneId),p=me(A=>A.closePane),h=me(A=>A.setPaneSession),b=me(A=>A.setPaneStatus),y=me(A=>A.setPaneError),k=me(A=>A.setPaneTitle),v=me(A=>A.setTerminalTitle),g=d===e,m=an(a),u=T.useRef(null),f=T.useRef(null),x=T.useRef(null),E=T.useRef(null),_=T.useRef(!0),S=T.useRef(!1),w=T.useRef(!1),N=T.useRef(null),D=T.useRef(null),R=T.useRef(t);R.current=t;const j=T.useRef(n);j.current=n;const O=T.useCallback(()=>{const A=E.current;A&&(A.abort(),E.current=null)},[]),H=T.useCallback((A,L)=>{O(),b(e,"connecting"),D.current=L;const I=new XMLHttpRequest;E.current=I;let G=0;I.open("GET",Mb(L)),I.setRequestHeader(mt,xt);const B=Cr();B&&I.setRequestHeader("Authorization",`Bearer ${B}`),I.onreadystatechange=()=>{if(I.readyState===XMLHttpRequest.HEADERS_RECEIVED)if(I.status===200){if(!_.current)return;b(e,"connected"),y(e,null);const $=x.current;if($)try{$.fit(),$d(L,A.cols,A.rows)}catch{}A.focus()}else{if(!_.current)return;b(e,"error"),y(e,`HTTP ${I.status}`)}},I.onprogress=()=>{if(!_.current)return;const{events:$,newIndex:Y}=Ub(I.responseText,G);G=Y;let X="";for(const ee of $)try{const J=JSON.parse(ee.data);switch(ee.event){case"output":X+=J.data;break;case"exit":X&&(A.write(X),X=""),h(e,null),b(e,"disconnected"),w.current=!1,D.current=null,A.write(`\r
|
|
618
618
|
${i("terminal.processExited")}\r
|
|
619
|
-
`);break;case"keepalive":break}}catch{}X&&A.write(X)},I.onerror=()=>{_.current&&(b(e,"error"),y(e,i("terminal.connectionLost")))},I.onloadend=()=>{var Y;if(!_.current)return;((Y=me.getState().panes[e])==null?void 0:Y.ptyStatus)==="connected"&&(b(e,"error"),y(e,i("terminal.connectionLost")))},I.send();const W=A.onData($=>{D.current&&Pb(D.current,$)}),z=A.onResize(({cols:$,rows:Y})=>{D.current&&$d(D.current,$,Y)});w.current=!0;const U=()=>{W.dispose(),z.dispose(),O(),D.current=null};return N.current=U,U},[O,e,h,b,y]),M=T.useCallback(()=>{const A=u.current;if(!A||S.current)return;const L=s==="dark"?Kn:Vn;for(;A.firstChild;)A.removeChild(A.firstChild);const I=new Rb.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:L,allowProposedApi:!0,scrollback:1e4}),G=new Ab.FitAddon;I.loadAddon(G),I.open(A);const B=A.querySelector(".xterm-helper-textarea");B&&(B.setAttribute("autocomplete","off"),B.setAttribute("autocorrect","off"),B.setAttribute("autocapitalize","off"),B.setAttribute("spellcheck","false"),B.setAttribute("unselectable","on")),f.current=I,x.current=G,S.current=!0;const W=I.onTitleChange(Y=>{_.current&&(v(Y||null),k(e,Y||null))});let z=null;const U=()=>{z&&clearTimeout(z),z=setTimeout(()=>{if(_.current)try{G.fit()}catch{}},50)},$=new ResizeObserver(U);return $.observe(A),window.addEventListener("resize",U),()=>{W.dispose(),$.disconnect(),window.removeEventListener("resize",U),z&&clearTimeout(z)}},[]),F=T.useCallback(async()=>{var W,z;const A=f.current,L=x.current;if(!A||!L||!_.current||w.current)return;try{L.fit()}catch{}const I=A.cols||80,G=A.rows||24,B=(W=me.getState().panes[e])==null?void 0:W.ptySessionId;if(B&&await jd(B)&&_.current){if(H(A,B),j.current){const $=await Pd(B);$&&_.current&&j.current({sessionId:B,cwd:$.cwd})}return}if(_.current){if(!B){const U=Bb(e),Y=(await Fb()).find(X=>!X.hasClient&&!U.has(X.id));if(Y&&_.current){if(h(e,Y.id),H(A,Y.id),j.current){const X=await Pd(Y.id);X&&_.current&&j.current({sessionId:Y.id,cwd:X.cwd})}return}}if(_.current){b(e,"connecting");try{const U=R.current||void 0,{sessionId:$,cwd:Y}=await Md(I,G,U);if(!_.current)return;h(e,$),H(A,$),(z=j.current)==null||z.call(j,{sessionId:$,cwd:Y})}catch(U){if(!_.current)return;b(e,"error"),y(e,U.message||i("terminal.createSessionFailed"))}}}},[H,e,h,b,y]),V=T.useRef(null);T.useEffect(()=>{_.current=!0;const A=u.current;if(!A)return;const L=()=>{if(!_.current)return;const{clientWidth:G,clientHeight:B}=A;if(!(G===0||B===0)&&(S.current||(V.current=M()||null),f.current&&x.current)){try{x.current.fit()}catch{}w.current||F()}};if(A.clientWidth>0&&A.clientHeight>0){const G=requestAnimationFrame(L);return()=>cancelAnimationFrame(G)}const I=new ResizeObserver(G=>{for(const B of G){const{width:W,height:z}=B.contentRect;if(W>0&&z>0){I.disconnect(),L();break}}});return I.observe(A),()=>I.disconnect()},[M,F]),T.useEffect(()=>()=>{var A,L,I;_.current=!1,(A=N.current)==null||A.call(N),(L=V.current)==null||L.call(V),(I=f.current)==null||I.dispose(),f.current=null,x.current=null,S.current=!1,w.current=!1},[]),T.useEffect(()=>{const A=f.current;if(A){const L=s==="dark"?Kn:Vn;A.options.theme=L;try{A.refresh(0,A.rows-1)}catch{}}},[s,o]);const q=T.useCallback(async()=>{var L,I,G;if(O(),w.current=!1,b(e,"connecting"),y(e,null),await new Promise(B=>setTimeout(B,jb)),!_.current)return;const A=f.current;if(A)try{A.clear();try{(L=x.current)==null||L.fit()}catch{}const B=A.cols||80,W=A.rows||24,z=(I=me.getState().panes[e])==null?void 0:I.ptySessionId;if(z&&await jd(z)&&_.current){H(A,z);return}if(!_.current)return;const U=R.current||void 0,{sessionId:$,cwd:Y}=await Md(B,W,U);if(!_.current)return;h(e,$),H(A,$),(G=j.current)==null||G.call(j,{sessionId:$,cwd:Y})}catch(B){if(!_.current)return;b(e,"error"),y(e,B.message||i("terminal.reconnectFailed"))}},[O,H,e,h,b,y]),C=T.useCallback(()=>{var A;g||c(e),(A=f.current)==null||A.focus()},[g,e,c]);return l?r.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full ${g&&m>1?"active":""}`,style:{backgroundColor:s==="dark"?Kn.background:Vn.background},onClick:C,children:[m>1&&r.jsx("div",{className:"terminal-pane-toolbar",children:r.jsx("button",{onClick:A=>{A.stopPropagation(),p(e)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:i("terminal.closePane"),children:r.jsx(Ce,{size:14})})}),r.jsx("div",{ref:u,className:"flex-1 w-full",style:{overflow:"hidden",padding:"4px"}}),l.ptyStatus==="connecting"&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{backgroundColor:s==="dark"?`${Kn.background}cc`:`${Vn.background}cc`},children:r.jsx(dt,{size:"small",text:i("terminal.connecting")})}),l.ptyStatus==="error"&&r.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[r.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[r.jsx(Ym,{size:14}),r.jsx("span",{children:l.errorMessage||i("terminal.error")})]}),r.jsxs("button",{onClick:q,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[r.jsx(Ve,{size:12}),r.jsx("span",{children:i("terminal.reconnect")})]})]})]}):r.jsx("div",{})}const zb="chat",Fd=new Set(["chat","tasks","plugins","terminal","canvas","canvas-pane","remote-control","settings","docs","editor","changes","metrics","workers","logs","keybindings","stats","traces"]);function ns(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const n=t.split("?")[0]||"";if(Fd.has(n))return n;const i=n.split("/")[0];return Fd.has(i)?i:zb}function Bd(e){const t=new URLSearchParams(window.location.search),n=window.location.hash.slice(1),i=n.indexOf("?");i!==-1&&new URLSearchParams(n.slice(i+1)).forEach((a,o)=>{t.has(o)||t.set(o,a)});const s=t.toString(),l=s?`#/${e}?${s}`:`#/${e}`;window.location.hash=l}function Hb(e){const t=()=>{const n=ns();e(n)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function yr(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],n=t.indexOf("/");return n>0?t.slice(n+1):void 0}function wn(e,t){const i=new URLSearchParams(window.location.search).toString(),s=i?`#/${e}/${t}?${i}`:`#/${e}/${t}`;window.location.hash=s}function xr(){const e=window.location.hash.slice(1),t=e.indexOf("?");return t>=0?new URLSearchParams(e.slice(t+1)):new URLSearchParams}function Fp(e){const t=new URLSearchParams(window.location.search);t.set("path",e),window.location.hash=`#/editor?${t.toString()}`}const Ud=400,zd=300,ei=200,ti=150,ni=.1,ri=5,ht=20,Hd=3,Bp=8,Gb=10,Up=32,Wb=Up;function zp(){return ae({"Content-Type":"application/json"})}async function qb(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:zp()});if(!t.ok)return null;const n=await t.json(),i=n.data??n;return typeof(i==null?void 0:i.cwd)=="string"?i.cwd:null}catch{return null}}function Hp(e){const t=Object.values(e);if(t.length===0)return;const i={...me.getState().panes};let s=!1;for(const l of t){const d=i[l.paneId];d?!d.ptySessionId&&l.ptySessionId&&(i[l.paneId]={...d,ptySessionId:l.ptySessionId},s=!0):(i[l.paneId]={id:l.paneId,ptySessionId:l.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null},s=!0)}s&&me.setState({panes:i})}const Ee=Te()($n((e,t)=>({viewport:{panX:0,panY:0,zoom:1},tiles:{},nextZIndex:1,selectedTileIds:[],setViewport:n=>{e({viewport:n})},addTile:()=>{const n=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=`canvas-pane-${n}`,{nextZIndex:s,viewport:l}=t(),d=l.zoom||1,a=(-l.panX+window.innerWidth/2)/d-Ud/2,o=(-l.panY+window.innerHeight/2)/d-zd/2,c=Math.round(a/ht)*ht,p=Math.round(o/ht)*ht,h={id:n,type:"terminal",x:c,y:p,width:Ud,height:zd,zIndex:s,paneId:i,windowState:"normal",ptySessionId:null,cwd:null},b=me.getState();if(!b.panes[i]){const y={...b.panes,[i]:{id:i,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}};me.setState({panes:y})}return e(y=>({tiles:{...y.tiles,[n]:h},nextZIndex:y.nextZIndex+1})),n},duplicateTile:n=>{var g,m,u,f;const i=t().tiles[n];if(!i)return null;const s=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,l=`canvas-pane-${s}`,{nextZIndex:d}=t(),a=((g=i.prevBounds)==null?void 0:g.width)??i.width,o=((m=i.prevBounds)==null?void 0:m.height)??i.height,c=((u=i.prevBounds)==null?void 0:u.x)??i.x,p=((f=i.prevBounds)==null?void 0:f.y)??i.y,h=ht*2,b=Math.round((c+h)/ht)*ht,y=Math.round((p+h)/ht)*ht,k={id:s,type:"terminal",x:b,y,width:a,height:o,zIndex:d,paneId:l,windowState:"normal",ptySessionId:null,cwd:i.cwd??null},v=me.getState();if(v.panes[l]||me.setState({panes:{...v.panes,[l]:{id:l,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}}),e(x=>({tiles:{...x.tiles,[s]:k},nextZIndex:x.nextZIndex+1})),!i.cwd){const x=me.getState().panes[i.paneId],E=x==null?void 0:x.ptySessionId;E&&qb(E).then(_=>{_&&(t().updateTile(i.id,{cwd:_}),t().updateTile(s,{cwd:_}))})}return s},removeTile:n=>{const i=t().tiles[n];if(i){const s=me.getState(),l=s.panes[i.paneId];if(l!=null&&l.ptySessionId&&fetch(`/api/v1/pty/${l.ptySessionId}`,{method:"DELETE",headers:zp()}).catch(()=>{}),s.panes[i.paneId]){const{[i.paneId]:d,...a}=s.panes;me.setState({panes:a})}}e(s=>{const{[n]:l,...d}=s.tiles;return{tiles:d,selectedTileIds:s.selectedTileIds.filter(a=>a!==n)}})},updateTile:(n,i)=>{e(s=>{const l=s.tiles[n];return l?{tiles:{...s.tiles,[n]:{...l,...i}}}:s})},selectTile:n=>e({selectedTileIds:[n]}),deselectAll:()=>e({selectedTileIds:[]}),selectTiles:n=>e({selectedTileIds:n}),bringToFront:n=>{e(i=>{const s=i.tiles[n];return s?{tiles:{...i.tiles,[n]:{...s,zIndex:i.nextZIndex}},nextZIndex:i.nextZIndex+1}:i})},maximizeTile:n=>{e(i=>{const s=i.tiles[n];if(!s)return i;const l=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...i.tiles,[n]:{...s,windowState:"maximized",prevBounds:l,zIndex:i.nextZIndex}},nextZIndex:i.nextZIndex+1}})},minimizeTile:n=>{e(i=>{const s=i.tiles[n];if(!s)return i;const l=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...i.tiles,[n]:{...s,height:Wb,windowState:"minimized",prevBounds:l}}}})},restoreTile:n=>{e(i=>{const s=i.tiles[n];return!s||!s.prevBounds?s?{tiles:{...i.tiles,[n]:{...s,windowState:"normal"}}}:i:{tiles:{...i.tiles,[n]:{...s,x:s.prevBounds.x,y:s.prevBounds.y,width:s.prevBounds.width,height:s.prevBounds.height,windowState:"normal",prevBounds:void 0}}}})},toggleMaximize:n=>{const i=t().tiles[n];i&&(i.windowState==="maximized"?t().restoreTile(n):t().maximizeTile(n))},toggleMinimize:n=>{const i=t().tiles[n];i&&(i.windowState==="minimized"?t().restoreTile(n):t().minimizeTile(n))},setTilePty:(n,i,s)=>{e(l=>{const d=l.tiles[n];if(!d)return l;const a={...d,ptySessionId:i};return s!==void 0&&(a.cwd=s),{tiles:{...l.tiles,[n]:a}}})},loadFromStorage:()=>{}}),{namespace:"canvas",fields:["viewport","tiles","nextZIndex"],scope:"workspace",debounceMs:1e3,onLoad:(e,t)=>{const n={};e.viewport&&(n.viewport=e.viewport),e.tiles&&(n.tiles=e.tiles),e.nextZIndex!==void 0&&(n.nextZIndex=e.nextZIndex),Object.keys(n).length>0&&(t(n),n.tiles&&Hp(n.tiles))}}));Hp(Ee.getState().tiles);function Vb(){const{t:e}=ne(),[t,n]=T.useState(()=>xr().get("paneId")||"");T.useEffect(()=>{const a=()=>{n(xr().get("paneId")||"")};return window.addEventListener("hashchange",a),()=>window.removeEventListener("hashchange",a)},[]);const i=Ee(a=>Object.values(a.tiles).find(o=>o.paneId===t)??null),s=me(a=>{var o;return t?(o=a.panes[t])==null?void 0:o.title:null}),l=Ee(a=>a.setTilePty),d=T.useCallback(a=>{i&&l(i.id,a.sessionId,a.cwd||null)},[i,l]);return T.useEffect(()=>{if(!t)return;const a=me.getState();a.panes[t]||me.setState({panes:{...a.panes,[t]:{id:t,ptySessionId:(i==null?void 0:i.ptySessionId)??null,ptyStatus:"disconnected",errorMessage:null}}})},[t,i==null?void 0:i.ptySessionId]),t?r.jsxs("div",{className:"flex flex-col h-full w-full bg-bg-primary",children:[r.jsxs("div",{className:"flex items-center gap-2 px-3 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",borderBottom:"1px solid var(--color-border-default)"},children:[r.jsx(un,{size:14,style:{opacity:.6}}),r.jsx("span",{className:"text-xs truncate",style:{fontSize:12,fontWeight:500},children:s||e("canvas.defaultTitle")})]}),r.jsx("div",{className:"flex-1 min-h-0 relative",children:r.jsx(ts,{paneId:t,initialCwd:(i==null?void 0:i.cwd)??null,onPtyCreated:d})})]}):r.jsx("div",{className:"flex items-center justify-center h-full w-full bg-bg-primary text-text-secondary text-sm",children:e("canvas.standalone.missingPaneId")})}class ir{constructor(){fe(this,"panX",0);fe(this,"panY",0);fe(this,"zoom",1)}getState(){return{panX:this.panX,panY:this.panY,zoom:this.zoom}}setState(t){this.panX=t.panX,this.panY=t.panY,this.zoom=Math.max(ni,Math.min(ri,t.zoom))}screenToWorld(t,n){return this.zoom===0?{x:0,y:0}:{x:(t-this.panX)/this.zoom,y:(n-this.panY)/this.zoom}}worldToScreen(t,n){return{x:t*this.zoom+this.panX,y:n*this.zoom+this.panY}}applyZoom(t,n,i){const s=this.zoom,l=Math.exp(-t*.6/100),d=Math.max(ni,Math.min(ri,s*l));if(s===0)return this.zoom=d,this.getState();const a=d/s-1;return this.panX-=(n-this.panX)*a,this.panY-=(i-this.panY)*a,this.zoom=d,this.getState()}applyPan(t,n){return this.panX+=t,this.panY+=n,this.getState()}fitTiles(t,n,i,s=40){if(t.length===0)return this.resetView();let l=1/0,d=1/0,a=-1/0,o=-1/0;for(const g of t)l=Math.min(l,g.x),d=Math.min(d,g.y),a=Math.max(a,g.x+g.width),o=Math.max(o,g.y+g.height);const c=a-l,p=o-d;if(c<=0||p<=0)return this.resetView();const h=n-s*2,b=i-s*2;if(h<=0||b<=0)return this.resetView();const y=Math.max(ni,Math.min(ri,Math.min(h/c,b/p))),k=(n-c*y)/2-l*y,v=(i-p*y)/2-d*y;return this.panX=k,this.panY=v,this.zoom=y,this.getState()}resetView(){return this.panX=0,this.panY=0,this.zoom=1,this.getState()}}const Gd=120;function Kb(){const{t:e}=ne(),t=Ee(m=>m.viewport),n=Ee(m=>m.tiles),i=Ee(m=>m.setViewport),s=Ee(m=>m.addTile),l=T.useRef(null),d=Math.round(t.zoom*100),a=typeof window<"u"&&window.location.hash.includes("standalone");if(Object.values(n).some(m=>m.windowState==="maximized"))return null;const c=()=>{var u;const m=(u=l.current)==null?void 0:u.parentElement;return{w:(m==null?void 0:m.clientWidth)??window.innerWidth,h:(m==null?void 0:m.clientHeight)??window.innerHeight}},p=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=m.applyZoom(-Gd,u/2,f/2);i(x)},h=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=m.applyZoom(Gd,u/2,f/2);i(x)},b=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=Object.values(n);x.length===0?i(m.resetView()):i(m.fitTiles(x,u,f,60))},y=()=>{s()},k=()=>{const m=new URLSearchParams(window.location.search),u=new URLSearchParams;u.set("standalone","1"),m.forEach((x,E)=>{u.has(E)||u.set(E,x)});const f=`${window.location.pathname}${window.location.search}#/canvas?${u.toString()}`;window.open(f,"canvas-standalone","noopener,noreferrer")},v="w-8 h-8 flex items-center justify-center rounded-lg transition-colors",g={border:"none",background:"transparent",color:"var(--color-text-secondary)",cursor:"pointer"};return r.jsxs("div",{ref:l,className:"canvas-toolbar fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 px-2 py-1 rounded-xl",style:{background:"var(--color-bg-card)",border:"1px solid var(--color-border-default)",boxShadow:"0 2px 12px rgba(0,0,0,0.12)",zIndex:1e4},children:[r.jsx("button",{className:v,style:g,onClick:y,title:e("canvas.addTerminal"),children:r.jsx(at,{size:16})}),r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:h,title:e("canvas.zoomOut"),children:r.jsx(Tb,{size:16})}),r.jsxs("span",{className:"text-xs tabular-nums select-none",style:{minWidth:40,textAlign:"center",color:"var(--color-text-secondary)"},children:[d,"%"]}),r.jsx("button",{className:v,style:g,onClick:p,title:e("canvas.zoomIn"),children:r.jsx(Eb,{size:16})}),r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:b,title:e("canvas.fitView"),children:r.jsx(uf,{size:16})}),!a&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:k,title:e("canvas.openStandalone"),children:r.jsx(it,{size:16})})]})]})}function Vt(e,t=ht,n=Gb){const i=(e%t+t)%t;return i<=n?e-i:t-i<=n?e+(t-i):e}function Yb(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}class Xb{constructor(){fe(this,"dragState",null);fe(this,"spacePressed",!1);fe(this,"callbacks",null);fe(this,"keydownHandler",null);fe(this,"keyupHandler",null);fe(this,"dragStarted",!1);fe(this,"panSamples",[])}attach(t){this.callbacks=t,this.keydownHandler=n=>{if(n.code==="Space"&&!n.repeat){if(Yb(n.target))return;this.spacePressed=!0,n.preventDefault()}},this.keyupHandler=n=>{n.code==="Space"&&(this.spacePressed=!1)},window.addEventListener("keydown",this.keydownHandler),window.addEventListener("keyup",this.keyupHandler)}detach(){this.keydownHandler&&(window.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null),this.keyupHandler&&(window.removeEventListener("keyup",this.keyupHandler),this.keyupHandler=null),this.callbacks=null,this.dragState=null}get isSpacePressed(){return this.spacePressed}get isDragging(){return this.dragState!==null&&this.dragStarted}get currentDrag(){return this.dragState}handlePointerDown(t,n,i,s){var o,c,p;const l=t.clientX,d=t.clientY;this.dragStarted=!1,this.panSamples=[],(c=(o=this.callbacks)==null?void 0:o.onInteractionStart)==null||c.call(o);const a=(p=this.callbacks)==null?void 0:p.getViewport();if(this.spacePressed||!n&&!i){const h=t.shiftKey||t.ctrlKey||t.metaKey;!this.spacePressed&&h?this.dragState={type:"select",startScreenX:l,startScreenY:d}:(this.dragState={type:"pan",startScreenX:l,startScreenY:d,initialViewport:a?{...a}:void 0},this.panSamples=[{t:performance.now(),x:l,y:d}]);return}if(n&&i){const h=s[n];if(!h)return;this.dragState={type:"resize",startScreenX:l,startScreenY:d,tileId:n,handle:i,initialTiles:{[n]:{x:h.x,y:h.y,width:h.width,height:h.height}}};return}if(n){const h=s[n];if(!h)return;const b={};b[n]={x:h.x,y:h.y,width:h.width,height:h.height},this.dragState={type:"move",startScreenX:l,startScreenY:d,tileId:n,initialTiles:b}}}handlePointerMove(t){var l,d;if(!this.dragState||!this.callbacks)return;const n=t.clientX-this.dragState.startScreenX,i=t.clientY-this.dragState.startScreenY;if(!this.dragStarted){if(Math.abs(n)<Hd&&Math.abs(i)<Hd)return;this.dragStarted=!0}const s=this.callbacks.getViewport();switch(this.dragState.type){case"pan":{const a=this.dragState.initialViewport;if(a){const p=n,h=i;this.callbacks.onViewportPan(a.panX+p-s.panX,a.panY+h-s.panY)}const o=performance.now();this.panSamples.push({t:o,x:t.clientX,y:t.clientY});const c=o-100;for(;this.panSamples.length>2&&this.panSamples[0].t<c;)this.panSamples.shift();break}case"move":{if(this.dragState.tileId&&s.zoom!==0){const a=n/s.zoom,o=i/s.zoom,c=(l=this.dragState.initialTiles)==null?void 0:l[this.dragState.tileId];c&&this.callbacks.onTileMove(this.dragState.tileId,Vt(c.x+a),Vt(c.y+o))}break}case"resize":{if(this.dragState.tileId&&this.dragState.handle&&s.zoom!==0){const a=(d=this.dragState.initialTiles)==null?void 0:d[this.dragState.tileId];if(a){const o=n/s.zoom,c=i/s.zoom,p=this.applyResize(this.dragState.handle,a,o,c);this.callbacks.onTileResize(this.dragState.tileId,p)}}break}case"select":{const a={x:Math.min(this.dragState.startScreenX,t.clientX),y:Math.min(this.dragState.startScreenY,t.clientY),width:Math.abs(n),height:Math.abs(i)};this.callbacks.onSelectionBox(a);break}}}handlePointerUp(t){var s,l,d,a;if(!this.callbacks){this.dragState=null;return}const n=((s=this.dragState)==null?void 0:s.type)==="pan",i=this.dragStarted;if(this.dragStarted?((a=this.dragState)==null?void 0:a.type)==="select"&&(this.callbacks.onSelectionBox(null),this.callbacks.onBoxSelectEnd([])):(l=this.dragState)!=null&&l.tileId?this.callbacks.onTileClick(this.dragState.tileId):((d=this.dragState)==null?void 0:d.type)==="select"&&this.callbacks.onCanvasClick(),n&&i&&this.panSamples.length>=2&&this.callbacks.onPanInertiaStart){const o=this.panSamples[this.panSamples.length-1],c=this.panSamples[0],p=o.t-c.t;if(p>0){const h=(o.x-c.x)/p,b=(o.y-c.y)/p;Math.hypot(h,b)>.05&&this.callbacks.onPanInertiaStart(h,b)}}this.dragState=null,this.dragStarted=!1,this.panSamples=[]}getSelectedTileIds(t,n){const i=[],s=t.x,l=t.y,d=t.width,a=t.height;for(const o of Object.values(n))o.x<s+d&&o.x+o.width>s&&o.y<l+a&&o.y+o.height>l&&i.push(o.id);return i}getResizeHandle(t,n,i,s=Bp){const{x:l,y:d,width:a,height:o}=t,c=l+a/2,p=d+o/2,h=l+a,b=d+o;return this.hitTest(n,i,l,d,s)?"nw":this.hitTest(n,i,h,d,s)?"ne":this.hitTest(n,i,l,b,s)?"sw":this.hitTest(n,i,h,b,s)?"se":this.hitTest(n,i,c,d,s)?"n":this.hitTest(n,i,c,b,s)?"s":this.hitTest(n,i,l,p,s)?"w":this.hitTest(n,i,h,p,s)?"e":null}applyResize(t,n,i,s){let{x:l,y:d,width:a,height:o}=n;switch(t){case"n":d=n.y+s,o=n.height-s;break;case"s":o=n.height+s;break;case"w":l=n.x+i,a=n.width-i;break;case"e":a=n.width+i;break;case"nw":l=n.x+i,d=n.y+s,a=n.width-i,o=n.height-s;break;case"ne":d=n.y+s,a=n.width+i,o=n.height-s;break;case"sw":l=n.x+i,a=n.width-i,o=n.height+s;break;case"se":a=n.width+i,o=n.height+s;break}return a<ei&&((t==="w"||t==="nw"||t==="sw")&&(l=n.x+n.width-ei),a=ei),o<ti&&((t==="n"||t==="nw"||t==="ne")&&(d=n.y+n.height-ti),o=ti),l=Vt(l),d=Vt(d),a=Vt(a),o=Vt(o),{x:l,y:d,width:a,height:o}}isInTileHeader(t,n,i,s){const l=Up*s;return n>=t.x&&n<=t.x+t.width&&i>=t.y&&i<=t.y+l}hitTest(t,n,i,s,l){return Math.abs(t-i)<=l&&Math.abs(n-s)<=l}}const Zb=[{position:"n",cursor:"ns-resize",className:"top-0 left-2 right-2 h-1.5 -translate-y-1/2"},{position:"s",cursor:"ns-resize",className:"bottom-0 left-2 right-2 h-1.5 translate-y-1/2"},{position:"e",cursor:"ew-resize",className:"right-0 top-2 bottom-2 w-1.5 translate-x-1/2"},{position:"w",cursor:"ew-resize",className:"left-0 top-2 bottom-2 w-1.5 -translate-x-1/2"},{position:"nw",cursor:"nwse-resize",className:"top-0 left-0 w-3 h-3 -translate-x-1/2 -translate-y-1/2"},{position:"ne",cursor:"nesw-resize",className:"top-0 right-0 w-3 h-3 translate-x-1/2 -translate-y-1/2"},{position:"sw",cursor:"nesw-resize",className:"bottom-0 left-0 w-3 h-3 -translate-x-1/2 translate-y-1/2"},{position:"se",cursor:"nwse-resize",className:"bottom-0 right-0 w-3 h-3 translate-x-1/2 translate-y-1/2"}];function Jb({tile:e,viewport:t,isSelected:n}){const{t:i}=ne(),s=Ee(C=>C.removeTile),l=Ee(C=>C.duplicateTile),d=Ee(C=>C.toggleMaximize),a=Ee(C=>C.toggleMinimize),o=Ee(C=>C.setTilePty),c=Ee(C=>C.selectTile),p=Ee(C=>C.bringToFront),h=me(C=>{var A;return(A=C.panes[e.paneId])==null?void 0:A.title}),{panX:b,panY:y,zoom:k}=t,v=e.x*k+b,g=e.y*k+y,m=e.windowState==="maximized",u=e.windowState==="minimized",f=n?"var(--color-canvas-tile-border-selected)":"var(--color-canvas-tile-border)",x=T.useCallback(()=>{d(e.id)},[e.id,d]),E=T.useCallback(()=>{a(e.id)},[e.id,a]),_=T.useCallback(()=>{l(e.id)},[e.id,l]),S=T.useCallback(C=>{C.target.closest("button")||(C.stopPropagation(),u?a(e.id):d(e.id))},[e.id,u,d,a]),w=T.useCallback(C=>{o(e.id,C.sessionId,C.cwd||null)},[e.id,o]),N=T.useRef(null),[D,R]=T.useState(!1);T.useEffect(()=>{const C=A=>{R(A.shiftKey||A.altKey)};return window.addEventListener("keydown",C),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",C),window.removeEventListener("keyup",C)}},[]);const j=T.useRef(null),O=T.useCallback(C=>{j.current={x:C.clientX,y:C.clientY,id:C.pointerId}},[]),H=T.useCallback(C=>{j.current=null},[]),M=T.useCallback(C=>{var I;if(C.ctrlKey||C.metaKey||C.shiftKey)return;const L=(I=N.current)==null?void 0:I.querySelector(".xterm-viewport");L&&(L.scrollTop+=C.deltaY,C.stopPropagation())},[]),F=T.useCallback(()=>{const C=new URLSearchParams(window.location.search),A=new URLSearchParams;A.set("paneId",e.paneId),C.forEach((I,G)=>{A.has(G)||A.set(G,I)});const L=`${window.location.pathname}${window.location.search}#/canvas-pane?${A.toString()}`;window.open(L,`canvas-pane-${e.paneId}`,"noopener,noreferrer")},[e.paneId]),V=m?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh",transform:"none",pointerEvents:"auto",zIndex:9999,borderRadius:0,border:"none",overflow:"hidden",boxShadow:"none"}:{transform:`translate(${v}px, ${g}px) scale(${k})`,transformOrigin:"top left",width:e.width,height:e.height,willChange:"transform",pointerEvents:"auto",zIndex:e.zIndex,borderRadius:8,border:`1px solid ${f}`,overflow:"hidden",boxShadow:n?"0 0 0 1px var(--color-canvas-tile-border-selected)":"0 2px 8px rgba(0,0,0,0.08)"},q=T.useCallback(C=>{var G;if(C.button!==0)return;c(e.id),p(e.id);const A=(G=N.current)==null?void 0:G.querySelector(".xterm-helper-textarea");if(!A)return;const L=()=>{try{A.focus()}catch{}};L();const I=()=>{window.removeEventListener("pointerup",I,!0),L()};window.addEventListener("pointerup",I,!0)},[e.id,c,p]);return r.jsxs("div",{className:m?"canvas-tile":"absolute canvas-tile",style:V,onPointerDownCapture:q,children:[r.jsxs("div",{className:"canvas-tile-header flex items-center gap-1.5 px-2 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",cursor:"grab",borderBottom:u?"none":"1px solid var(--color-canvas-tile-border)"},onDoubleClick:S,children:[r.jsx(un,{size:13,style:{opacity:.5,flexShrink:0}}),r.jsx("span",{className:"flex-1 text-xs truncate",style:{fontSize:12,fontWeight:500},children:h||i("canvas.defaultTitle")}),r.jsx("button",{onClick:C=>{C.stopPropagation(),_()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.duplicate"),children:r.jsx(pr,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),F()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.openStandalone"),children:r.jsx(it,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),E()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i(u?"canvas.tileMenu.restore":"canvas.tileMenu.minimize"),children:u?r.jsx(es,{size:12}):r.jsx(bp,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),x()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i(m?"canvas.tileMenu.restore":"canvas.tileMenu.maximize"),children:m?r.jsx(xf,{size:12}):r.jsx(Zi,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),s(e.id)},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.close"),children:r.jsx(Ce,{size:12})})]}),!u&&r.jsxs("div",{ref:N,className:"flex-1 relative",style:{height:"calc(100% - 32px)",overflow:"hidden"},children:[r.jsx(ts,{paneId:e.paneId,initialCwd:e.cwd??null,onPtyCreated:w}),r.jsx("div",{className:"absolute inset-0",style:{zIndex:5,pointerEvents:D?"none":"auto",background:"transparent"},onPointerDown:O,onPointerUp:H,onWheel:M})]}),!u&&Zb.map(C=>r.jsx("div",{className:`absolute ${C.className}`,style:{cursor:C.cursor,zIndex:10,opacity:0},"data-resize-handle":C.position},C.position))]})}function Qb({rect:e}){return r.jsx("div",{className:"absolute pointer-events-none",style:{left:e.x,top:e.y,width:e.width,height:e.height,background:"var(--color-canvas-selection-fill)",border:"1px solid var(--color-canvas-selection-stroke)",borderRadius:2,zIndex:999}})}function ey(){const e=T.useRef(null),t=T.useRef(new ir),n=T.useRef(new Xb),i=Ee(A=>A.tiles),s=Ee(A=>A.viewport),l=Ee(A=>A.selectedTileIds),d=Ee(A=>A.setViewport),a=Ee(A=>A.updateTile),o=Ee(A=>A.selectTile),c=Ee(A=>A.selectTiles),p=Ee(A=>A.deselectAll),h=Ee(A=>A.bringToFront),[b,y]=T.useState(null),[k,v]=T.useState(!1),[g,m]=T.useState(!1),[u,f]=T.useState(null);T.useEffect(()=>{t.current.setState(s)},[s]);const x=T.useMemo(()=>Object.values(i).sort((A,L)=>A.zIndex-L.zIndex),[i]),E=T.useMemo(()=>new Set(l),[l]),_=T.useRef(s);_.current=s;const S=T.useRef({setViewport:d,updateTile:a,selectTile:o,deselectAll:p,bringToFront:h,selectTiles:c});S.current={setViewport:d,updateTile:a,selectTile:o,deselectAll:p,bringToFront:h,selectTiles:c};const w=.92,N=.01,D=3.5,R=T.useRef(null),j=T.useRef({vx:0,vy:0,last:0}),O=T.useCallback(()=>{R.current!==null&&(cancelAnimationFrame(R.current),R.current=null)},[]),H=T.useCallback((A,L)=>{O();const I=Math.hypot(A,L);if(I>D){const B=D/I;A*=B,L*=B}j.current={vx:A,vy:L,last:performance.now()};const G=()=>{const B=performance.now(),W=j.current,z=Math.min(32,B-W.last);W.last=B;const $=t.current.applyPan(W.vx*z,W.vy*z);S.current.setViewport($);const Y=Math.pow(w,z/16.67);if(W.vx*=Y,W.vy*=Y,Math.hypot(W.vx,W.vy)<N){R.current=null;return}R.current=requestAnimationFrame(G)};R.current=requestAnimationFrame(G)},[O]);T.useEffect(()=>()=>O(),[O]),T.useEffect(()=>{const A=n.current,L={onViewportPan:(I,G)=>{const W=t.current.applyPan(I,G);S.current.setViewport(W)},onTileMove:(I,G,B)=>{S.current.updateTile(I,{x:G,y:B})},onTileResize:(I,G)=>{S.current.updateTile(I,G)},onTileSelect:I=>{S.current.selectTile(I),S.current.bringToFront(I)},onSelectionBox:I=>{if(I){const G=e.current,B=G==null?void 0:G.getBoundingClientRect();y(B?{x:I.x-B.left,y:I.y-B.top,width:I.width,height:I.height}:I)}else y(null)},onBoxSelectEnd:()=>{},onTileClick:I=>{S.current.selectTile(I),S.current.bringToFront(I)},onCanvasClick:()=>{S.current.deselectAll()},onInteractionStart:()=>{O()},onPanInertiaStart:(I,G)=>{H(I,G)},getViewport:()=>_.current};return A.attach(L),()=>A.detach()},[]),T.useEffect(()=>{const A=e.current;if(!A)return;const L=t.current,I=W=>{const z=W.target,U=!!(z&&z.closest('.xterm, .xterm-screen, .xterm-viewport, input, textarea, [contenteditable="true"], [contenteditable=""]')),$=W.ctrlKey||W.metaKey;if(U&&!$&&!W.shiftKey)return;W.preventDefault();const Y=A.getBoundingClientRect(),X=W.clientX-Y.left,ee=W.clientY-Y.top;if($){const ge=L.applyZoom(W.deltaY,X,ee);d(ge);return}let J=-W.deltaX,oe=-W.deltaY;W.shiftKey&&J===0&&(J=-W.deltaY,oe=0);const ue=W.deltaMode===1?16:W.deltaMode===2?100:1,ce=L.applyPan(J*ue,oe*ue);d(ce)},G=W=>{if(!(W.ctrlKey||W.metaKey))return;const z=W.target;if(z){const U=z.tagName;if(U==="INPUT"||U==="TEXTAREA"||U==="SELECT"||z.isContentEditable)return}if(W.key==="+"||W.key==="="||W.key==="-"||W.key==="_"||W.key==="0"){W.preventDefault();const U=A.clientWidth,$=A.clientHeight;if(W.key==="0")d(L.resetView());else if(W.key==="-"||W.key==="_"){const Y=L.applyZoom(120,U/2,$/2);d(Y)}else{const Y=L.applyZoom(-120,U/2,$/2);d(Y)}}},B=W=>{W.preventDefault()};return A.addEventListener("wheel",I,{passive:!1}),window.addEventListener("keydown",G),A.addEventListener("gesturestart",B),A.addEventListener("gesturechange",B),A.addEventListener("gestureend",B),()=>{A.removeEventListener("wheel",I),window.removeEventListener("keydown",G),A.removeEventListener("gesturestart",B),A.removeEventListener("gesturechange",B),A.removeEventListener("gestureend",B)}},[d]);const M=T.useCallback(A=>{const L=e.current;if(!L)return;const I=A.button===1||A.button===2,G=n.current.isSpacePressed,B=L.getBoundingClientRect(),W=A.clientX-B.left,z=A.clientY-B.top,U=n.current;let $=null,Y=null,X=null;if(!I&&!G){const ue=[...Object.values(i)].sort((ce,ge)=>ge.zIndex-ce.zIndex);for(const ce of ue){const ge=ce.x*s.zoom+s.panX,ie=ce.y*s.zoom+s.panY,$e=ce.width*s.zoom,re=ce.height*s.zoom,de={x:ge,y:ie,width:$e,height:re},xe=U.getResizeHandle(de,W,z,Bp);if(xe){$=ce.id,Y=xe,X=ce.id;break}if(U.isInTileHeader(de,W,z,s.zoom)){$=ce.id,X=ce.id;break}if(W>=ge&&W<=ge+$e&&z>=ie&&z<=ie+re){X=ce.id;break}}}const ee=A.target;if(ee&&!(I||G||Y!==null)&&(ee.closest("button")||ee.closest("input, textarea:not(.xterm-helper-textarea), select")||ee.closest('[contenteditable="true"], [contenteditable=""]')))return;if(I&&A.preventDefault(),!X&&!Y){const ue=document.activeElement;ue&&typeof ue.blur=="function"&&ue.blur(),p()}const oe=A.nativeEvent;U.handlePointerDown(oe,$,Y,i),X?(o(X),h(X)):(A.shiftKey||A.ctrlKey||A.metaKey)&&p(),L.setPointerCapture(A.pointerId),v(U.isSpacePressed)},[i,s,o,p,h]),F=T.useCallback(A=>{var I;const L=n.current;L.handlePointerMove(A.nativeEvent),v(L.isSpacePressed),m(L.isDragging),f(((I=L.currentDrag)==null?void 0:I.type)??null)},[]),V=T.useCallback(A=>{var G;const L=n.current;if(((G=L.currentDrag)==null?void 0:G.type)==="select"&&L.isDragging&&b){const B=s.zoom||1,W={x:(b.x-s.panX)/B,y:(b.y-s.panY)/B,width:b.width/B,height:b.height/B},z=L.getSelectedTileIds(W,i);c(z)}L.handlePointerUp(A.nativeEvent);const I=e.current;I&&I.releasePointerCapture(A.pointerId),m(!1),f(null),y(null)},[s,i,c,b]),C=g&&u==="pan"?"grabbing":k?"grab":"default";return r.jsxs("div",{ref:e,className:"absolute inset-0",style:{cursor:C,touchAction:"none",overscrollBehavior:"contain"},onPointerDown:M,onPointerMove:F,onPointerUp:V,onContextMenu:A=>A.preventDefault(),children:[r.jsx("div",{className:"absolute inset-0",style:{pointerEvents:"none"},children:x.map(A=>r.jsx(Jb,{tile:A,viewport:s,isSelected:E.has(A.id)},A.id))}),b&&r.jsx(Qb,{rect:b})]})}function Wd(){const e=Ee(i=>i.tiles),{t}=ne(),n=Object.keys(e).length>0;return r.jsxs("div",{className:"relative w-full h-full overflow-hidden bg-bg-primary",children:[r.jsx(ey,{}),r.jsx(Kb,{}),!n&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:r.jsx("p",{className:"text-text-tertiary text-sm",children:t("canvas.empty")})})]})}function qd(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function ty(e){if(Array.isArray(e))return e}function ny(e,t,n){return(t=cy(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ry(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,s,l,d,a=[],o=!0,c=!1;try{if(l=(n=n.call(e)).next,t!==0)for(;!(o=(i=l.call(n)).done)&&(a.push(i.value),a.length!==t);o=!0);}catch(p){c=!0,s=p}finally{try{if(!o&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(c)throw s}}return a}}function iy(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
619
|
+
`);break;case"keepalive":break}}catch{}X&&A.write(X)},I.onerror=()=>{_.current&&(b(e,"error"),y(e,i("terminal.connectionLost")))},I.onloadend=()=>{var Y;if(!_.current)return;((Y=me.getState().panes[e])==null?void 0:Y.ptyStatus)==="connected"&&(b(e,"error"),y(e,i("terminal.connectionLost")))},I.send();const W=A.onData($=>{D.current&&Pb(D.current,$)}),z=A.onResize(({cols:$,rows:Y})=>{D.current&&$d(D.current,$,Y)});w.current=!0;const U=()=>{W.dispose(),z.dispose(),O(),D.current=null};return N.current=U,U},[O,e,h,b,y]),M=T.useCallback(()=>{const A=u.current;if(!A||S.current)return;const L=s==="dark"?Kn:Vn;for(;A.firstChild;)A.removeChild(A.firstChild);const I=new Rb.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:L,allowProposedApi:!0,scrollback:1e4}),G=new Ab.FitAddon;I.loadAddon(G),I.open(A);const B=A.querySelector(".xterm-helper-textarea");B&&(B.setAttribute("autocomplete","off"),B.setAttribute("autocorrect","off"),B.setAttribute("autocapitalize","off"),B.setAttribute("spellcheck","false"),B.setAttribute("unselectable","on")),f.current=I,x.current=G,S.current=!0;const W=I.onTitleChange(Y=>{_.current&&(v(Y||null),k(e,Y||null))});let z=null;const U=()=>{z&&clearTimeout(z),z=setTimeout(()=>{if(_.current)try{G.fit()}catch{}},50)},$=new ResizeObserver(U);return $.observe(A),window.addEventListener("resize",U),()=>{W.dispose(),$.disconnect(),window.removeEventListener("resize",U),z&&clearTimeout(z)}},[]),F=T.useCallback(async()=>{var W,z;const A=f.current,L=x.current;if(!A||!L||!_.current||w.current)return;try{L.fit()}catch{}const I=A.cols||80,G=A.rows||24,B=(W=me.getState().panes[e])==null?void 0:W.ptySessionId;if(B&&await jd(B)&&_.current){if(H(A,B),j.current){const $=await Pd(B);$&&_.current&&j.current({sessionId:B,cwd:$.cwd})}return}if(_.current){if(!B){const U=Bb(e),Y=(await Fb()).find(X=>!X.hasClient&&!U.has(X.id));if(Y&&_.current){if(h(e,Y.id),H(A,Y.id),j.current){const X=await Pd(Y.id);X&&_.current&&j.current({sessionId:Y.id,cwd:X.cwd})}return}}if(_.current){b(e,"connecting");try{const U=R.current||void 0,{sessionId:$,cwd:Y}=await Md(I,G,U);if(!_.current)return;h(e,$),H(A,$),(z=j.current)==null||z.call(j,{sessionId:$,cwd:Y})}catch(U){if(!_.current)return;b(e,"error"),y(e,U.message||i("terminal.createSessionFailed"))}}}},[H,e,h,b,y]),V=T.useRef(null);T.useEffect(()=>{_.current=!0;const A=u.current;if(!A)return;const L=()=>{if(!_.current)return;const{clientWidth:G,clientHeight:B}=A;if(!(G===0||B===0)&&(S.current||(V.current=M()||null),f.current&&x.current)){try{x.current.fit()}catch{}w.current||F()}};if(A.clientWidth>0&&A.clientHeight>0){const G=requestAnimationFrame(L);return()=>cancelAnimationFrame(G)}const I=new ResizeObserver(G=>{for(const B of G){const{width:W,height:z}=B.contentRect;if(W>0&&z>0){I.disconnect(),L();break}}});return I.observe(A),()=>I.disconnect()},[M,F]),T.useEffect(()=>()=>{var A,L,I;_.current=!1,(A=N.current)==null||A.call(N),(L=V.current)==null||L.call(V),(I=f.current)==null||I.dispose(),f.current=null,x.current=null,S.current=!1,w.current=!1},[]),T.useEffect(()=>{const A=f.current;if(A){const L=s==="dark"?Kn:Vn;A.options.theme=L;try{A.refresh(0,A.rows-1)}catch{}}},[s,o]);const q=T.useCallback(async()=>{var L,I,G;if(O(),w.current=!1,b(e,"connecting"),y(e,null),await new Promise(B=>setTimeout(B,jb)),!_.current)return;const A=f.current;if(A)try{A.clear();try{(L=x.current)==null||L.fit()}catch{}const B=A.cols||80,W=A.rows||24,z=(I=me.getState().panes[e])==null?void 0:I.ptySessionId;if(z&&await jd(z)&&_.current){H(A,z);return}if(!_.current)return;const U=R.current||void 0,{sessionId:$,cwd:Y}=await Md(B,W,U);if(!_.current)return;h(e,$),H(A,$),(G=j.current)==null||G.call(j,{sessionId:$,cwd:Y})}catch(B){if(!_.current)return;b(e,"error"),y(e,B.message||i("terminal.reconnectFailed"))}},[O,H,e,h,b,y]),C=T.useCallback(()=>{var A;g||c(e),(A=f.current)==null||A.focus()},[g,e,c]);return l?r.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full ${g&&m>1?"active":""}`,style:{backgroundColor:s==="dark"?Kn.background:Vn.background},onClick:C,children:[m>1&&r.jsx("div",{className:"terminal-pane-toolbar",children:r.jsx("button",{onClick:A=>{A.stopPropagation(),p(e)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:i("terminal.closePane"),children:r.jsx(Ce,{size:14})})}),r.jsx("div",{ref:u,className:"flex-1 w-full",style:{overflow:"hidden",padding:"4px"}}),l.ptyStatus==="connecting"&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{backgroundColor:s==="dark"?`${Kn.background}cc`:`${Vn.background}cc`},children:r.jsx(dt,{size:"small",text:i("terminal.connecting")})}),l.ptyStatus==="error"&&r.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[r.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[r.jsx(Ym,{size:14}),r.jsx("span",{children:l.errorMessage||i("terminal.error")})]}),r.jsxs("button",{onClick:q,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[r.jsx(Ve,{size:12}),r.jsx("span",{children:i("terminal.reconnect")})]})]})]}):r.jsx("div",{})}const zb="chat",Fd=new Set(["chat","tasks","plugins","terminal","canvas","canvas-pane","remote-control","settings","docs","editor","changes","metrics","workers","logs","keybindings","stats","traces"]);function ns(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const n=t.split("?")[0]||"";if(Fd.has(n))return n;const i=n.split("/")[0];return Fd.has(i)?i:zb}function Bd(e){const t=new URLSearchParams(window.location.search),n=window.location.hash.slice(1),i=n.indexOf("?");i!==-1&&new URLSearchParams(n.slice(i+1)).forEach((a,o)=>{t.has(o)||t.set(o,a)});const s=t.toString(),l=s?`#/${e}?${s}`:`#/${e}`;window.location.hash=l}function Hb(e){const t=()=>{const n=ns();e(n)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function yr(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],n=t.indexOf("/");return n>0?t.slice(n+1):void 0}function wn(e,t){const i=new URLSearchParams(window.location.search).toString(),s=i?`#/${e}/${t}?${i}`:`#/${e}/${t}`;window.location.hash=s}function xr(){const e=window.location.hash.slice(1),t=e.indexOf("?");return t>=0?new URLSearchParams(e.slice(t+1)):new URLSearchParams}function Fp(e){const t=new URLSearchParams(window.location.search);t.set("path",e),window.location.hash=`#/editor?${t.toString()}`}const Ud=400,zd=300,ei=200,ti=150,ni=.1,ri=5,ht=20,Hd=3,Bp=8,Gb=10,Up=32,Wb=Up;function zp(){return ae({"Content-Type":"application/json"})}async function qb(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:zp()});if(!t.ok)return null;const n=await t.json(),i=n.data??n;return typeof(i==null?void 0:i.cwd)=="string"?i.cwd:null}catch{return null}}function Hp(e){const t=Object.values(e);if(t.length===0)return;const i={...me.getState().panes};let s=!1;for(const l of t){const d=i[l.paneId];d?!d.ptySessionId&&l.ptySessionId&&(i[l.paneId]={...d,ptySessionId:l.ptySessionId},s=!0):(i[l.paneId]={id:l.paneId,ptySessionId:l.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null},s=!0)}s&&me.setState({panes:i})}const Ee=Te()($n((e,t)=>({viewport:{panX:0,panY:0,zoom:1},tiles:{},nextZIndex:1,selectedTileIds:[],setViewport:n=>{e({viewport:n})},addTile:()=>{const n=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=`canvas-pane-${n}`,{nextZIndex:s,viewport:l}=t(),d=l.zoom||1,a=(-l.panX+window.innerWidth/2)/d-Ud/2,o=(-l.panY+window.innerHeight/2)/d-zd/2,c=Math.round(a/ht)*ht,p=Math.round(o/ht)*ht,h={id:n,type:"terminal",x:c,y:p,width:Ud,height:zd,zIndex:s,paneId:i,windowState:"normal",ptySessionId:null,cwd:null},b=me.getState();if(!b.panes[i]){const y={...b.panes,[i]:{id:i,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}};me.setState({panes:y})}return e(y=>({tiles:{...y.tiles,[n]:h},nextZIndex:y.nextZIndex+1})),n},duplicateTile:n=>{var u,f,x,E;const i=t().tiles[n];if(!i)return null;const s=`tile-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,l=`canvas-pane-${s}`,{nextZIndex:d}=t(),a=((u=i.prevBounds)==null?void 0:u.width)??i.width,o=((f=i.prevBounds)==null?void 0:f.height)??i.height,c=((x=i.prevBounds)==null?void 0:x.x)??i.x,p=((E=i.prevBounds)==null?void 0:E.y)??i.y,h=ht*2,b=Math.round((c+h)/ht)*ht,y=Math.round((p+h)/ht)*ht,k={id:s,type:"terminal",x:b,y,width:a,height:o,zIndex:d,paneId:l,windowState:"normal",ptySessionId:null,cwd:i.cwd??null},v=me.getState();v.panes[l]||me.setState({panes:{...v.panes,[l]:{id:l,ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}}),e(_=>({tiles:{..._.tiles,[s]:k},nextZIndex:_.nextZIndex+1}));const g=me.getState().panes[i.paneId],m=g==null?void 0:g.ptySessionId;return m&&qb(m).then(_=>{_&&(t().updateTile(i.id,{cwd:_}),t().updateTile(s,{cwd:_}))}),s},removeTile:n=>{const i=t().tiles[n];if(i){const s=me.getState(),l=s.panes[i.paneId];if(l!=null&&l.ptySessionId&&fetch(`/api/v1/pty/${l.ptySessionId}`,{method:"DELETE",headers:zp()}).catch(()=>{}),s.panes[i.paneId]){const{[i.paneId]:d,...a}=s.panes;me.setState({panes:a})}}e(s=>{const{[n]:l,...d}=s.tiles;return{tiles:d,selectedTileIds:s.selectedTileIds.filter(a=>a!==n)}})},updateTile:(n,i)=>{e(s=>{const l=s.tiles[n];return l?{tiles:{...s.tiles,[n]:{...l,...i}}}:s})},selectTile:n=>e({selectedTileIds:[n]}),deselectAll:()=>e({selectedTileIds:[]}),selectTiles:n=>e({selectedTileIds:n}),bringToFront:n=>{e(i=>{const s=i.tiles[n];return s?{tiles:{...i.tiles,[n]:{...s,zIndex:i.nextZIndex}},nextZIndex:i.nextZIndex+1}:i})},maximizeTile:n=>{e(i=>{const s=i.tiles[n];if(!s)return i;const l=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...i.tiles,[n]:{...s,windowState:"maximized",prevBounds:l,zIndex:i.nextZIndex}},nextZIndex:i.nextZIndex+1}})},minimizeTile:n=>{e(i=>{const s=i.tiles[n];if(!s)return i;const l=s.windowState==="normal"?{x:s.x,y:s.y,width:s.width,height:s.height}:s.prevBounds;return{tiles:{...i.tiles,[n]:{...s,height:Wb,windowState:"minimized",prevBounds:l}}}})},restoreTile:n=>{e(i=>{const s=i.tiles[n];return!s||!s.prevBounds?s?{tiles:{...i.tiles,[n]:{...s,windowState:"normal"}}}:i:{tiles:{...i.tiles,[n]:{...s,x:s.prevBounds.x,y:s.prevBounds.y,width:s.prevBounds.width,height:s.prevBounds.height,windowState:"normal",prevBounds:void 0}}}})},toggleMaximize:n=>{const i=t().tiles[n];i&&(i.windowState==="maximized"?t().restoreTile(n):t().maximizeTile(n))},toggleMinimize:n=>{const i=t().tiles[n];i&&(i.windowState==="minimized"?t().restoreTile(n):t().minimizeTile(n))},setTilePty:(n,i,s)=>{e(l=>{const d=l.tiles[n];if(!d)return l;const a={...d,ptySessionId:i};return s!==void 0&&(a.cwd=s),{tiles:{...l.tiles,[n]:a}}})},loadFromStorage:()=>{}}),{namespace:"canvas",fields:["viewport","tiles","nextZIndex"],scope:"workspace",debounceMs:1e3,onLoad:(e,t)=>{const n={};e.viewport&&(n.viewport=e.viewport),e.tiles&&(n.tiles=e.tiles),e.nextZIndex!==void 0&&(n.nextZIndex=e.nextZIndex),Object.keys(n).length>0&&(t(n),n.tiles&&Hp(n.tiles))}}));Hp(Ee.getState().tiles);function Vb(){const{t:e}=ne(),[t,n]=T.useState(()=>xr().get("paneId")||"");T.useEffect(()=>{const a=()=>{n(xr().get("paneId")||"")};return window.addEventListener("hashchange",a),()=>window.removeEventListener("hashchange",a)},[]);const i=Ee(a=>Object.values(a.tiles).find(o=>o.paneId===t)??null),s=me(a=>{var o;return t?(o=a.panes[t])==null?void 0:o.title:null}),l=Ee(a=>a.setTilePty),d=T.useCallback(a=>{i&&l(i.id,a.sessionId,a.cwd||null)},[i,l]);return T.useEffect(()=>{if(!t)return;const a=me.getState();a.panes[t]||me.setState({panes:{...a.panes,[t]:{id:t,ptySessionId:(i==null?void 0:i.ptySessionId)??null,ptyStatus:"disconnected",errorMessage:null}}})},[t,i==null?void 0:i.ptySessionId]),t?r.jsxs("div",{className:"flex flex-col h-full w-full bg-bg-primary",children:[r.jsxs("div",{className:"flex items-center gap-2 px-3 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",borderBottom:"1px solid var(--color-border-default)"},children:[r.jsx(un,{size:14,style:{opacity:.6}}),r.jsx("span",{className:"text-xs truncate",style:{fontSize:12,fontWeight:500},children:s||e("canvas.defaultTitle")})]}),r.jsx("div",{className:"flex-1 min-h-0 relative",children:r.jsx(ts,{paneId:t,initialCwd:(i==null?void 0:i.cwd)??null,onPtyCreated:d})})]}):r.jsx("div",{className:"flex items-center justify-center h-full w-full bg-bg-primary text-text-secondary text-sm",children:e("canvas.standalone.missingPaneId")})}class ir{constructor(){fe(this,"panX",0);fe(this,"panY",0);fe(this,"zoom",1)}getState(){return{panX:this.panX,panY:this.panY,zoom:this.zoom}}setState(t){this.panX=t.panX,this.panY=t.panY,this.zoom=Math.max(ni,Math.min(ri,t.zoom))}screenToWorld(t,n){return this.zoom===0?{x:0,y:0}:{x:(t-this.panX)/this.zoom,y:(n-this.panY)/this.zoom}}worldToScreen(t,n){return{x:t*this.zoom+this.panX,y:n*this.zoom+this.panY}}applyZoom(t,n,i){const s=this.zoom,l=Math.exp(-t*.6/100),d=Math.max(ni,Math.min(ri,s*l));if(s===0)return this.zoom=d,this.getState();const a=d/s-1;return this.panX-=(n-this.panX)*a,this.panY-=(i-this.panY)*a,this.zoom=d,this.getState()}applyPan(t,n){return this.panX+=t,this.panY+=n,this.getState()}fitTiles(t,n,i,s=40){if(t.length===0)return this.resetView();let l=1/0,d=1/0,a=-1/0,o=-1/0;for(const g of t)l=Math.min(l,g.x),d=Math.min(d,g.y),a=Math.max(a,g.x+g.width),o=Math.max(o,g.y+g.height);const c=a-l,p=o-d;if(c<=0||p<=0)return this.resetView();const h=n-s*2,b=i-s*2;if(h<=0||b<=0)return this.resetView();const y=Math.max(ni,Math.min(ri,Math.min(h/c,b/p))),k=(n-c*y)/2-l*y,v=(i-p*y)/2-d*y;return this.panX=k,this.panY=v,this.zoom=y,this.getState()}resetView(){return this.panX=0,this.panY=0,this.zoom=1,this.getState()}}const Gd=120;function Kb(){const{t:e}=ne(),t=Ee(m=>m.viewport),n=Ee(m=>m.tiles),i=Ee(m=>m.setViewport),s=Ee(m=>m.addTile),l=T.useRef(null),d=Math.round(t.zoom*100),a=typeof window<"u"&&window.location.hash.includes("standalone");if(Object.values(n).some(m=>m.windowState==="maximized"))return null;const c=()=>{var u;const m=(u=l.current)==null?void 0:u.parentElement;return{w:(m==null?void 0:m.clientWidth)??window.innerWidth,h:(m==null?void 0:m.clientHeight)??window.innerHeight}},p=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=m.applyZoom(-Gd,u/2,f/2);i(x)},h=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=m.applyZoom(Gd,u/2,f/2);i(x)},b=()=>{const m=new ir;m.setState(t);const{w:u,h:f}=c(),x=Object.values(n);x.length===0?i(m.resetView()):i(m.fitTiles(x,u,f,60))},y=()=>{s()},k=()=>{const m=new URLSearchParams(window.location.search),u=new URLSearchParams;u.set("standalone","1"),m.forEach((x,E)=>{u.has(E)||u.set(E,x)});const f=`${window.location.pathname}${window.location.search}#/canvas?${u.toString()}`;window.open(f,"canvas-standalone","noopener,noreferrer")},v="w-8 h-8 flex items-center justify-center rounded-lg transition-colors",g={border:"none",background:"transparent",color:"var(--color-text-secondary)",cursor:"pointer"};return r.jsxs("div",{ref:l,className:"canvas-toolbar fixed bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1 px-2 py-1 rounded-xl",style:{background:"var(--color-bg-card)",border:"1px solid var(--color-border-default)",boxShadow:"0 2px 12px rgba(0,0,0,0.12)",zIndex:1e4},children:[r.jsx("button",{className:v,style:g,onClick:y,title:e("canvas.addTerminal"),children:r.jsx(at,{size:16})}),r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:h,title:e("canvas.zoomOut"),children:r.jsx(Tb,{size:16})}),r.jsxs("span",{className:"text-xs tabular-nums select-none",style:{minWidth:40,textAlign:"center",color:"var(--color-text-secondary)"},children:[d,"%"]}),r.jsx("button",{className:v,style:g,onClick:p,title:e("canvas.zoomIn"),children:r.jsx(Eb,{size:16})}),r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:b,title:e("canvas.fitView"),children:r.jsx(uf,{size:16})}),!a&&r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{width:1,height:20,background:"var(--color-border-muted)"}}),r.jsx("button",{className:v,style:g,onClick:k,title:e("canvas.openStandalone"),children:r.jsx(it,{size:16})})]})]})}function Vt(e,t=ht,n=Gb){const i=(e%t+t)%t;return i<=n?e-i:t-i<=n?e+(t-i):e}function Yb(e){if(!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}class Xb{constructor(){fe(this,"dragState",null);fe(this,"spacePressed",!1);fe(this,"callbacks",null);fe(this,"keydownHandler",null);fe(this,"keyupHandler",null);fe(this,"dragStarted",!1);fe(this,"panSamples",[])}attach(t){this.callbacks=t,this.keydownHandler=n=>{if(n.code==="Space"&&!n.repeat){if(Yb(n.target))return;this.spacePressed=!0,n.preventDefault()}},this.keyupHandler=n=>{n.code==="Space"&&(this.spacePressed=!1)},window.addEventListener("keydown",this.keydownHandler),window.addEventListener("keyup",this.keyupHandler)}detach(){this.keydownHandler&&(window.removeEventListener("keydown",this.keydownHandler),this.keydownHandler=null),this.keyupHandler&&(window.removeEventListener("keyup",this.keyupHandler),this.keyupHandler=null),this.callbacks=null,this.dragState=null}get isSpacePressed(){return this.spacePressed}get isDragging(){return this.dragState!==null&&this.dragStarted}get currentDrag(){return this.dragState}handlePointerDown(t,n,i,s){var o,c,p;const l=t.clientX,d=t.clientY;this.dragStarted=!1,this.panSamples=[],(c=(o=this.callbacks)==null?void 0:o.onInteractionStart)==null||c.call(o);const a=(p=this.callbacks)==null?void 0:p.getViewport();if(this.spacePressed||!n&&!i){const h=t.shiftKey||t.ctrlKey||t.metaKey;!this.spacePressed&&h?this.dragState={type:"select",startScreenX:l,startScreenY:d}:(this.dragState={type:"pan",startScreenX:l,startScreenY:d,initialViewport:a?{...a}:void 0},this.panSamples=[{t:performance.now(),x:l,y:d}]);return}if(n&&i){const h=s[n];if(!h)return;this.dragState={type:"resize",startScreenX:l,startScreenY:d,tileId:n,handle:i,initialTiles:{[n]:{x:h.x,y:h.y,width:h.width,height:h.height}}};return}if(n){const h=s[n];if(!h)return;const b={};b[n]={x:h.x,y:h.y,width:h.width,height:h.height},this.dragState={type:"move",startScreenX:l,startScreenY:d,tileId:n,initialTiles:b}}}handlePointerMove(t){var l,d;if(!this.dragState||!this.callbacks)return;const n=t.clientX-this.dragState.startScreenX,i=t.clientY-this.dragState.startScreenY;if(!this.dragStarted){if(Math.abs(n)<Hd&&Math.abs(i)<Hd)return;this.dragStarted=!0}const s=this.callbacks.getViewport();switch(this.dragState.type){case"pan":{const a=this.dragState.initialViewport;if(a){const p=n,h=i;this.callbacks.onViewportPan(a.panX+p-s.panX,a.panY+h-s.panY)}const o=performance.now();this.panSamples.push({t:o,x:t.clientX,y:t.clientY});const c=o-100;for(;this.panSamples.length>2&&this.panSamples[0].t<c;)this.panSamples.shift();break}case"move":{if(this.dragState.tileId&&s.zoom!==0){const a=n/s.zoom,o=i/s.zoom,c=(l=this.dragState.initialTiles)==null?void 0:l[this.dragState.tileId];c&&this.callbacks.onTileMove(this.dragState.tileId,Vt(c.x+a),Vt(c.y+o))}break}case"resize":{if(this.dragState.tileId&&this.dragState.handle&&s.zoom!==0){const a=(d=this.dragState.initialTiles)==null?void 0:d[this.dragState.tileId];if(a){const o=n/s.zoom,c=i/s.zoom,p=this.applyResize(this.dragState.handle,a,o,c);this.callbacks.onTileResize(this.dragState.tileId,p)}}break}case"select":{const a={x:Math.min(this.dragState.startScreenX,t.clientX),y:Math.min(this.dragState.startScreenY,t.clientY),width:Math.abs(n),height:Math.abs(i)};this.callbacks.onSelectionBox(a);break}}}handlePointerUp(t){var s,l,d,a;if(!this.callbacks){this.dragState=null;return}const n=((s=this.dragState)==null?void 0:s.type)==="pan",i=this.dragStarted;if(this.dragStarted?((a=this.dragState)==null?void 0:a.type)==="select"&&(this.callbacks.onSelectionBox(null),this.callbacks.onBoxSelectEnd([])):(l=this.dragState)!=null&&l.tileId?this.callbacks.onTileClick(this.dragState.tileId):((d=this.dragState)==null?void 0:d.type)==="select"&&this.callbacks.onCanvasClick(),n&&i&&this.panSamples.length>=2&&this.callbacks.onPanInertiaStart){const o=this.panSamples[this.panSamples.length-1],c=this.panSamples[0],p=o.t-c.t;if(p>0){const h=(o.x-c.x)/p,b=(o.y-c.y)/p;Math.hypot(h,b)>.05&&this.callbacks.onPanInertiaStart(h,b)}}this.dragState=null,this.dragStarted=!1,this.panSamples=[]}getSelectedTileIds(t,n){const i=[],s=t.x,l=t.y,d=t.width,a=t.height;for(const o of Object.values(n))o.x<s+d&&o.x+o.width>s&&o.y<l+a&&o.y+o.height>l&&i.push(o.id);return i}getResizeHandle(t,n,i,s=Bp){const{x:l,y:d,width:a,height:o}=t,c=l+a/2,p=d+o/2,h=l+a,b=d+o;return this.hitTest(n,i,l,d,s)?"nw":this.hitTest(n,i,h,d,s)?"ne":this.hitTest(n,i,l,b,s)?"sw":this.hitTest(n,i,h,b,s)?"se":this.hitTest(n,i,c,d,s)?"n":this.hitTest(n,i,c,b,s)?"s":this.hitTest(n,i,l,p,s)?"w":this.hitTest(n,i,h,p,s)?"e":null}applyResize(t,n,i,s){let{x:l,y:d,width:a,height:o}=n;switch(t){case"n":d=n.y+s,o=n.height-s;break;case"s":o=n.height+s;break;case"w":l=n.x+i,a=n.width-i;break;case"e":a=n.width+i;break;case"nw":l=n.x+i,d=n.y+s,a=n.width-i,o=n.height-s;break;case"ne":d=n.y+s,a=n.width+i,o=n.height-s;break;case"sw":l=n.x+i,a=n.width-i,o=n.height+s;break;case"se":a=n.width+i,o=n.height+s;break}return a<ei&&((t==="w"||t==="nw"||t==="sw")&&(l=n.x+n.width-ei),a=ei),o<ti&&((t==="n"||t==="nw"||t==="ne")&&(d=n.y+n.height-ti),o=ti),l=Vt(l),d=Vt(d),a=Vt(a),o=Vt(o),{x:l,y:d,width:a,height:o}}isInTileHeader(t,n,i,s){const l=Up*s;return n>=t.x&&n<=t.x+t.width&&i>=t.y&&i<=t.y+l}hitTest(t,n,i,s,l){return Math.abs(t-i)<=l&&Math.abs(n-s)<=l}}const Zb=[{position:"n",cursor:"ns-resize",className:"top-0 left-2 right-2 h-1.5 -translate-y-1/2"},{position:"s",cursor:"ns-resize",className:"bottom-0 left-2 right-2 h-1.5 translate-y-1/2"},{position:"e",cursor:"ew-resize",className:"right-0 top-2 bottom-2 w-1.5 translate-x-1/2"},{position:"w",cursor:"ew-resize",className:"left-0 top-2 bottom-2 w-1.5 -translate-x-1/2"},{position:"nw",cursor:"nwse-resize",className:"top-0 left-0 w-3 h-3 -translate-x-1/2 -translate-y-1/2"},{position:"ne",cursor:"nesw-resize",className:"top-0 right-0 w-3 h-3 translate-x-1/2 -translate-y-1/2"},{position:"sw",cursor:"nesw-resize",className:"bottom-0 left-0 w-3 h-3 -translate-x-1/2 translate-y-1/2"},{position:"se",cursor:"nwse-resize",className:"bottom-0 right-0 w-3 h-3 translate-x-1/2 translate-y-1/2"}];function Jb({tile:e,viewport:t,isSelected:n}){const{t:i}=ne(),s=Ee(C=>C.removeTile),l=Ee(C=>C.duplicateTile),d=Ee(C=>C.toggleMaximize),a=Ee(C=>C.toggleMinimize),o=Ee(C=>C.setTilePty),c=Ee(C=>C.selectTile),p=Ee(C=>C.bringToFront),h=me(C=>{var A;return(A=C.panes[e.paneId])==null?void 0:A.title}),{panX:b,panY:y,zoom:k}=t,v=e.x*k+b,g=e.y*k+y,m=e.windowState==="maximized",u=e.windowState==="minimized",f=n?"var(--color-canvas-tile-border-selected)":"var(--color-canvas-tile-border)",x=T.useCallback(()=>{d(e.id)},[e.id,d]),E=T.useCallback(()=>{a(e.id)},[e.id,a]),_=T.useCallback(()=>{l(e.id)},[e.id,l]),S=T.useCallback(C=>{C.target.closest("button")||(C.stopPropagation(),u?a(e.id):d(e.id))},[e.id,u,d,a]),w=T.useCallback(C=>{o(e.id,C.sessionId,C.cwd||null)},[e.id,o]),N=T.useRef(null),[D,R]=T.useState(!1);T.useEffect(()=>{const C=A=>{R(A.shiftKey||A.altKey)};return window.addEventListener("keydown",C),window.addEventListener("keyup",C),()=>{window.removeEventListener("keydown",C),window.removeEventListener("keyup",C)}},[]);const j=T.useRef(null),O=T.useCallback(C=>{j.current={x:C.clientX,y:C.clientY,id:C.pointerId}},[]),H=T.useCallback(C=>{j.current=null},[]),M=T.useCallback(C=>{var I;if(C.ctrlKey||C.metaKey||C.shiftKey)return;const L=(I=N.current)==null?void 0:I.querySelector(".xterm-viewport");L&&(L.scrollTop+=C.deltaY,C.stopPropagation())},[]),F=T.useCallback(()=>{const C=new URLSearchParams(window.location.search),A=new URLSearchParams;A.set("paneId",e.paneId),C.forEach((I,G)=>{A.has(G)||A.set(G,I)});const L=`${window.location.pathname}${window.location.search}#/canvas-pane?${A.toString()}`;window.open(L,`canvas-pane-${e.paneId}`,"noopener,noreferrer")},[e.paneId]),V=m?{position:"fixed",top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh",transform:"none",pointerEvents:"auto",zIndex:9999,borderRadius:0,border:"none",overflow:"hidden",boxShadow:"none"}:{transform:`translate(${v}px, ${g}px) scale(${k})`,transformOrigin:"top left",width:e.width,height:e.height,willChange:"transform",pointerEvents:"auto",zIndex:e.zIndex,borderRadius:8,border:`1px solid ${f}`,overflow:"hidden",boxShadow:n?"0 0 0 1px var(--color-canvas-tile-border-selected)":"0 2px 8px rgba(0,0,0,0.08)"},q=T.useCallback(C=>{var G;if(C.button!==0)return;c(e.id),p(e.id);const A=(G=N.current)==null?void 0:G.querySelector(".xterm-helper-textarea");if(!A)return;const L=()=>{try{A.focus()}catch{}};L();const I=()=>{window.removeEventListener("pointerup",I,!0),L()};window.addEventListener("pointerup",I,!0)},[e.id,c,p]);return r.jsxs("div",{className:m?"canvas-tile":"absolute canvas-tile",style:V,onPointerDownCapture:q,children:[r.jsxs("div",{className:"canvas-tile-header flex items-center gap-1.5 px-2 select-none",style:{height:32,background:"var(--color-canvas-tile-header)",color:"var(--color-canvas-tile-header-text)",cursor:"grab",borderBottom:u?"none":"1px solid var(--color-canvas-tile-border)"},onDoubleClick:S,children:[r.jsx(un,{size:13,style:{opacity:.5,flexShrink:0}}),r.jsx("span",{className:"flex-1 text-xs truncate",style:{fontSize:12,fontWeight:500},children:h||i("canvas.defaultTitle")}),r.jsx("button",{onClick:C=>{C.stopPropagation(),_()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.duplicate"),children:r.jsx(pr,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),F()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.openStandalone"),children:r.jsx(it,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),E()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i(u?"canvas.tileMenu.restore":"canvas.tileMenu.minimize"),children:u?r.jsx(es,{size:12}):r.jsx(bp,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),x()},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i(m?"canvas.tileMenu.restore":"canvas.tileMenu.maximize"),children:m?r.jsx(xf,{size:12}):r.jsx(Zi,{size:12})}),r.jsx("button",{onClick:C=>{C.stopPropagation(),s(e.id)},className:"w-5 h-5 flex items-center justify-center rounded hover:bg-bg-hover transition-colors",style:{cursor:"pointer",border:"none",background:"transparent",color:"inherit"},title:i("canvas.tileMenu.close"),children:r.jsx(Ce,{size:12})})]}),!u&&r.jsxs("div",{ref:N,className:"flex-1 relative",style:{height:"calc(100% - 32px)",overflow:"hidden"},children:[r.jsx(ts,{paneId:e.paneId,initialCwd:e.cwd??null,onPtyCreated:w}),r.jsx("div",{className:"absolute inset-0",style:{zIndex:5,pointerEvents:D?"none":"auto",background:"transparent"},onPointerDown:O,onPointerUp:H,onWheel:M})]}),!u&&Zb.map(C=>r.jsx("div",{className:`absolute ${C.className}`,style:{cursor:C.cursor,zIndex:10,opacity:0},"data-resize-handle":C.position},C.position))]})}function Qb({rect:e}){return r.jsx("div",{className:"absolute pointer-events-none",style:{left:e.x,top:e.y,width:e.width,height:e.height,background:"var(--color-canvas-selection-fill)",border:"1px solid var(--color-canvas-selection-stroke)",borderRadius:2,zIndex:999}})}function ey(){const e=T.useRef(null),t=T.useRef(new ir),n=T.useRef(new Xb),i=Ee(A=>A.tiles),s=Ee(A=>A.viewport),l=Ee(A=>A.selectedTileIds),d=Ee(A=>A.setViewport),a=Ee(A=>A.updateTile),o=Ee(A=>A.selectTile),c=Ee(A=>A.selectTiles),p=Ee(A=>A.deselectAll),h=Ee(A=>A.bringToFront),[b,y]=T.useState(null),[k,v]=T.useState(!1),[g,m]=T.useState(!1),[u,f]=T.useState(null);T.useEffect(()=>{t.current.setState(s)},[s]);const x=T.useMemo(()=>Object.values(i).sort((A,L)=>A.zIndex-L.zIndex),[i]),E=T.useMemo(()=>new Set(l),[l]),_=T.useRef(s);_.current=s;const S=T.useRef({setViewport:d,updateTile:a,selectTile:o,deselectAll:p,bringToFront:h,selectTiles:c});S.current={setViewport:d,updateTile:a,selectTile:o,deselectAll:p,bringToFront:h,selectTiles:c};const w=.92,N=.01,D=3.5,R=T.useRef(null),j=T.useRef({vx:0,vy:0,last:0}),O=T.useCallback(()=>{R.current!==null&&(cancelAnimationFrame(R.current),R.current=null)},[]),H=T.useCallback((A,L)=>{O();const I=Math.hypot(A,L);if(I>D){const B=D/I;A*=B,L*=B}j.current={vx:A,vy:L,last:performance.now()};const G=()=>{const B=performance.now(),W=j.current,z=Math.min(32,B-W.last);W.last=B;const $=t.current.applyPan(W.vx*z,W.vy*z);S.current.setViewport($);const Y=Math.pow(w,z/16.67);if(W.vx*=Y,W.vy*=Y,Math.hypot(W.vx,W.vy)<N){R.current=null;return}R.current=requestAnimationFrame(G)};R.current=requestAnimationFrame(G)},[O]);T.useEffect(()=>()=>O(),[O]),T.useEffect(()=>{const A=n.current,L={onViewportPan:(I,G)=>{const W=t.current.applyPan(I,G);S.current.setViewport(W)},onTileMove:(I,G,B)=>{S.current.updateTile(I,{x:G,y:B})},onTileResize:(I,G)=>{S.current.updateTile(I,G)},onTileSelect:I=>{S.current.selectTile(I),S.current.bringToFront(I)},onSelectionBox:I=>{if(I){const G=e.current,B=G==null?void 0:G.getBoundingClientRect();y(B?{x:I.x-B.left,y:I.y-B.top,width:I.width,height:I.height}:I)}else y(null)},onBoxSelectEnd:()=>{},onTileClick:I=>{S.current.selectTile(I),S.current.bringToFront(I)},onCanvasClick:()=>{S.current.deselectAll()},onInteractionStart:()=>{O()},onPanInertiaStart:(I,G)=>{H(I,G)},getViewport:()=>_.current};return A.attach(L),()=>A.detach()},[]),T.useEffect(()=>{const A=e.current;if(!A)return;const L=t.current,I=W=>{const z=W.target,U=!!(z&&z.closest('.xterm, .xterm-screen, .xterm-viewport, input, textarea, [contenteditable="true"], [contenteditable=""]')),$=W.ctrlKey||W.metaKey;if(U&&!$&&!W.shiftKey)return;W.preventDefault();const Y=A.getBoundingClientRect(),X=W.clientX-Y.left,ee=W.clientY-Y.top;if($){const ge=L.applyZoom(W.deltaY,X,ee);d(ge);return}let J=-W.deltaX,oe=-W.deltaY;W.shiftKey&&J===0&&(J=-W.deltaY,oe=0);const ue=W.deltaMode===1?16:W.deltaMode===2?100:1,ce=L.applyPan(J*ue,oe*ue);d(ce)},G=W=>{if(!(W.ctrlKey||W.metaKey))return;const z=W.target;if(z){const U=z.tagName;if(U==="INPUT"||U==="TEXTAREA"||U==="SELECT"||z.isContentEditable)return}if(W.key==="+"||W.key==="="||W.key==="-"||W.key==="_"||W.key==="0"){W.preventDefault();const U=A.clientWidth,$=A.clientHeight;if(W.key==="0")d(L.resetView());else if(W.key==="-"||W.key==="_"){const Y=L.applyZoom(120,U/2,$/2);d(Y)}else{const Y=L.applyZoom(-120,U/2,$/2);d(Y)}}},B=W=>{W.preventDefault()};return A.addEventListener("wheel",I,{passive:!1}),window.addEventListener("keydown",G),A.addEventListener("gesturestart",B),A.addEventListener("gesturechange",B),A.addEventListener("gestureend",B),()=>{A.removeEventListener("wheel",I),window.removeEventListener("keydown",G),A.removeEventListener("gesturestart",B),A.removeEventListener("gesturechange",B),A.removeEventListener("gestureend",B)}},[d]);const M=T.useCallback(A=>{const L=e.current;if(!L)return;const I=A.button===1||A.button===2,G=n.current.isSpacePressed,B=L.getBoundingClientRect(),W=A.clientX-B.left,z=A.clientY-B.top,U=n.current;let $=null,Y=null,X=null;if(!I&&!G){const ue=[...Object.values(i)].sort((ce,ge)=>ge.zIndex-ce.zIndex);for(const ce of ue){const ge=ce.x*s.zoom+s.panX,ie=ce.y*s.zoom+s.panY,$e=ce.width*s.zoom,re=ce.height*s.zoom,de={x:ge,y:ie,width:$e,height:re},xe=U.getResizeHandle(de,W,z,Bp);if(xe){$=ce.id,Y=xe,X=ce.id;break}if(U.isInTileHeader(de,W,z,s.zoom)){$=ce.id,X=ce.id;break}if(W>=ge&&W<=ge+$e&&z>=ie&&z<=ie+re){X=ce.id;break}}}const ee=A.target;if(ee&&!(I||G||Y!==null)&&(ee.closest("button")||ee.closest("input, textarea:not(.xterm-helper-textarea), select")||ee.closest('[contenteditable="true"], [contenteditable=""]')))return;if(I&&A.preventDefault(),!X&&!Y){const ue=document.activeElement;ue&&typeof ue.blur=="function"&&ue.blur(),p()}const oe=A.nativeEvent;U.handlePointerDown(oe,$,Y,i),X?(o(X),h(X)):(A.shiftKey||A.ctrlKey||A.metaKey)&&p(),L.setPointerCapture(A.pointerId),v(U.isSpacePressed)},[i,s,o,p,h]),F=T.useCallback(A=>{var I;const L=n.current;L.handlePointerMove(A.nativeEvent),v(L.isSpacePressed),m(L.isDragging),f(((I=L.currentDrag)==null?void 0:I.type)??null)},[]),V=T.useCallback(A=>{var G;const L=n.current;if(((G=L.currentDrag)==null?void 0:G.type)==="select"&&L.isDragging&&b){const B=s.zoom||1,W={x:(b.x-s.panX)/B,y:(b.y-s.panY)/B,width:b.width/B,height:b.height/B},z=L.getSelectedTileIds(W,i);c(z)}L.handlePointerUp(A.nativeEvent);const I=e.current;I&&I.releasePointerCapture(A.pointerId),m(!1),f(null),y(null)},[s,i,c,b]),C=g&&u==="pan"?"grabbing":k?"grab":"default";return r.jsxs("div",{ref:e,className:"absolute inset-0",style:{cursor:C,touchAction:"none",overscrollBehavior:"contain"},onPointerDown:M,onPointerMove:F,onPointerUp:V,onContextMenu:A=>A.preventDefault(),children:[r.jsx("div",{className:"absolute inset-0",style:{pointerEvents:"none"},children:x.map(A=>r.jsx(Jb,{tile:A,viewport:s,isSelected:E.has(A.id)},A.id))}),b&&r.jsx(Qb,{rect:b})]})}function Wd(){const e=Ee(i=>i.tiles),{t}=ne(),n=Object.keys(e).length>0;return r.jsxs("div",{className:"relative w-full h-full overflow-hidden bg-bg-primary",children:[r.jsx(ey,{}),r.jsx(Kb,{}),!n&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:r.jsx("p",{className:"text-text-tertiary text-sm",children:t("canvas.empty")})})]})}function qd(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function ty(e){if(Array.isArray(e))return e}function ny(e,t,n){return(t=cy(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ry(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,s,l,d,a=[],o=!0,c=!1;try{if(l=(n=n.call(e)).next,t!==0)for(;!(o=(i=l.call(n)).done)&&(a.push(i.value),a.length!==t);o=!0);}catch(p){c=!0,s=p}finally{try{if(!o&&n.return!=null&&(d=n.return(),Object(d)!==d))return}finally{if(c)throw s}}return a}}function iy(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
620
620
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Vd(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,i)}return n}function Kd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Vd(Object(n),!0).forEach(function(i){ny(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Vd(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function sy(e,t){if(e==null)return{};var n,i,s=ay(e,t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(i=0;i<l.length;i++)n=l[i],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function ay(e,t){if(e==null)return{};var n={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(t.indexOf(i)!==-1)continue;n[i]=e[i]}return n}function oy(e,t){return ty(e)||ry(e,t)||dy(e,t)||iy()}function ly(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cy(e){var t=ly(e,"string");return typeof t=="symbol"?t:t+""}function dy(e,t){if(e){if(typeof e=="string")return qd(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?qd(e,t):void 0}}function uy(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yd(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,i)}return n}function Xd(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Yd(Object(n),!0).forEach(function(i){uy(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Yd(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function py(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(i){return t.reduceRight(function(s,l){return l(s)},i)}}function En(e){return function t(){for(var n=this,i=arguments.length,s=new Array(i),l=0;l<i;l++)s[l]=arguments[l];return s.length>=e.length?e.apply(this,s):function(){for(var d=arguments.length,a=new Array(d),o=0;o<d;o++)a[o]=arguments[o];return t.apply(n,[].concat(s,a))}}}function vr(e){return{}.toString.call(e).includes("Object")}function hy(e){return!Object.keys(e).length}function Dn(e){return typeof e=="function"}function my(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gy(e,t){return vr(t)||Nt("changeType"),Object.keys(t).some(function(n){return!my(e,n)})&&Nt("changeField"),t}function fy(e){Dn(e)||Nt("selectorType")}function by(e){Dn(e)||vr(e)||Nt("handlerType"),vr(e)&&Object.values(e).some(function(t){return!Dn(t)})&&Nt("handlersType")}function yy(e){e||Nt("initialIsRequired"),vr(e)||Nt("initialType"),hy(e)&&Nt("initialContent")}function xy(e,t){throw new Error(e[t]||e.default)}var vy={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},Nt=En(xy)(vy),Yn={changes:gy,selector:fy,handler:by,initial:yy};function _y(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Yn.initial(e),Yn.handler(t);var n={current:e},i=En(wy)(n,t),s=En(ky)(n),l=En(Yn.changes)(e),d=En(Sy)(n);function a(){var c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(p){return p};return Yn.selector(c),c(n.current)}function o(c){py(i,s,l,d)(c)}return[a,o]}function Sy(e,t){return Dn(t)?t(e.current):t}function ky(e,t){return e.current=Xd(Xd({},e.current),t),t}function wy(e,t,n){return Dn(t)?t(e.current):Object.keys(n).forEach(function(i){var s;return(s=t[i])===null||s===void 0?void 0:s.call(t,e.current[i])}),n}var Ey={create:_y},Cy={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function Ty(e){return function t(){for(var n=this,i=arguments.length,s=new Array(i),l=0;l<i;l++)s[l]=arguments[l];return s.length>=e.length?e.apply(this,s):function(){for(var d=arguments.length,a=new Array(d),o=0;o<d;o++)a[o]=arguments[o];return t.apply(n,[].concat(s,a))}}}function Ny(e){return{}.toString.call(e).includes("Object")}function Ay(e){return e||Zd("configIsRequired"),Ny(e)||Zd("configType"),e.urls?(Iy(),{paths:{vs:e.urls.monacoBase}}):e}function Iy(){console.warn(Gp.deprecation)}function Ry(e,t){throw new Error(e[t]||e.default)}var Gp={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
621
621
|
You are using deprecated way of configuration.
|
|
622
622
|
|
|
@@ -655,7 +655,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
655
655
|
${n("tool.moreLinesCount").replace("{count}",String(s.length-t))}`})]})}function Cn({src:e,alt:t}){const n=e.startsWith("file://")?Ct(e.replace("file://","")):e.startsWith("/")&&!e.startsWith("/api/")?Ct(e):e;return r.jsx("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40 p-2",children:r.jsx("img",{src:n,alt:t||"Image",className:"max-w-full max-h-64 rounded object-contain",loading:"lazy"})})}const gu={read:{Icon:Vv,render:e=>{const t=Di(e);if(t){const i=ye(e),s=i.file_path?String(i.file_path).split("/").pop():void 0;return r.jsx(Cn,{src:t,alt:s})}if(e.result===void 0)return null;const n=ot(e.result);return n?r.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre overflow-x-auto max-h-64 overflow-y-auto bg-bg-secondary/40 rounded-md",children:n}):null}},edit:{Icon:bh,render:e=>{const t=Sh(e.content);if(t){const n=e.status==="failed";return r.jsxs("div",{className:n?"opacity-40":"",children:[r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-mono text-text-tertiary",children:[r.jsx(ct,{size:10,className:"flex-shrink-0"}),r.jsx(vt,{path:t.path,className:"truncate"})]}),r.jsx(nn,{path:t.path,oldText:t.oldText,newText:t.newText,maxHeight:"max-h-64"})]})}if(e.status==="running"){const n=ye(e),i=typeof n.new_string=="string"?n.new_string:void 0;if(i)return r.jsx(_h,{text:i,streaming:!0})}return e.result!==void 0?r.jsx(rt,{result:e.result}):null}},execute:{Icon:Kv,render:e=>{const t=ye(e),i=(e.result!==void 0?s_(e.result):"")||(e.result!==void 0?ot(e.result):"");return r.jsxs("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40",children:[!!t.command&&r.jsxs("pre",{className:"px-2.5 py-1.5 font-mono text-xs whitespace-pre overflow-x-auto text-text-primary",children:[r.jsx("span",{className:"text-text-tertiary select-none",children:"$ "}),String(t.command)]}),i&&r.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto border-t border-border-muted/30",children:i})]})}},search:{Icon:yh,render:e=>r.jsx(a_,{result:e.result})},fetch:{Icon:Ri,render:e=>{const t=ye(e);return!t.url&&!t.query?null:r.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&r.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&r.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)}),!!t.query&&r.jsx("div",{className:"text-text-secondary",children:String(t.query)})]})}}},fu={Write:{Icon:bh,getSummary:e=>{const t=ye(e);return t.file_path?String(t.file_path):void 0},render:e=>{const t=ye(e),n=Sh(e.content);if(n){const s=e.status==="failed";return r.jsxs("div",{className:s?"opacity-40":"",children:[r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-mono text-text-tertiary",children:[r.jsx(ct,{size:10,className:"flex-shrink-0"}),r.jsx(vt,{path:n.path,className:"truncate"})]}),r.jsx(nn,{path:n.path,oldText:n.oldText,newText:n.newText,maxHeight:"max-h-64"})]})}const i=typeof t.content=="string"?t.content:void 0;if(i){const s=e.status==="running";return r.jsx(_h,{text:i,streaming:s})}return e.result!==void 0?r.jsx(rt,{result:e.result}):null}},ImageGen:{Icon:hu,getTitle:(e,t)=>t("tool.imageGen"),getSummary:e=>{const t=ye(e);return t.prompt?qe(String(t.prompt),60):void 0},render:(e,t)=>{const n=Di(e);if(n)return r.jsx(Cn,{src:n,alt:t("tool.generatedImage")});const i=mu(e.result);return i?r.jsx(Cn,{src:Ct(i),alt:t("tool.generatedImage")}):e.result!==void 0?r.jsx(rt,{result:e.result,maxLines:6}):null}},ImageEdit:{Icon:hu,getTitle:(e,t)=>t("tool.imageEdit"),getSummary:e=>{const t=ye(e);return t.prompt?qe(String(t.prompt),60):void 0},render:(e,t)=>{const n=Di(e);if(n)return r.jsx(Cn,{src:n,alt:t("tool.editedImage")});const i=mu(e.result);return i?r.jsx(Cn,{src:Ct(i),alt:t("tool.editedImage")}):e.result!==void 0?r.jsx(rt,{result:e.result,maxLines:6}):null}},ToolSearch:{Icon:yh,getTitle:(e,t)=>t("tool.toolSearch"),getSummary:e=>{const t=ye(e);if(t.query)return String(t.query);if(t.tool_names)return`[${String(t.tool_names)}]`},render:e=>e.result===void 0?null:r.jsx(rt,{result:e.result,maxLines:12})},TeamCreate:{Icon:uu,getTitle:(e,t)=>t("tool.teamCreate"),getSummary:e=>{const t=ye(e),n=t.name?String(t.name):void 0,i=t.description?String(t.description):void 0;return n&&i?`${n} · ${i}`:n||i},render:e=>{if(e.result===void 0)return null;const t=ot(e.result);return t?r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 bg-bg-secondary/40 rounded-md text-xs",children:[r.jsx(np,{size:12,className:"text-accent-green flex-shrink-0"}),r.jsx("span",{className:"text-text-secondary",children:qe(t,120)})]}):null}},TeamDelete:{Icon:uu,getTitle:(e,t)=>t("tool.teamDelete"),getSummary:e=>{const t=ye(e);return t.team_name?String(t.team_name):void 0}},TaskCreate:{Icon:pu,getTitle:(e,t)=>t("tool.taskCreate"),getSummary:e=>{const t=ye(e);return t.subject?qe(String(t.subject),80):void 0}},TaskUpdate:{Icon:Xv,getTitle:(e,t)=>t("tool.taskUpdate"),getSummary:e=>{const t=ye(e),n=[];return t.taskId&&n.push(`#${t.taskId}`),t.status&&n.push(String(t.status)),t.subject&&n.push(qe(String(t.subject),40)),n.join(" · ")||void 0}},TaskList:{Icon:pu,getTitle:(e,t)=>t("tool.taskList")},TaskGet:{Icon:Zv,getTitle:(e,t)=>t("tool.taskGet"),getSummary:e=>{const t=ye(e);return t.taskId?`#${t.taskId}`:void 0},render:e=>e.result===void 0?null:r.jsx(rt,{result:e.result,maxLines:8})},SendMessage:{Icon:Yv,getTitle:(e,t)=>{const n=ye(e),i=String(n.type||"message"),s=n.recipient?String(n.recipient):void 0;switch(i){case"message":return s?`@${s}`:t("tool.sendMessage");case"broadcast":return"@team";case"shutdown_request":return s?`@${s} · shutdown`:t("tool.shutdown");case"shutdown_response":return n.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected");case"plan_approval_response":return s?`@${s} · ${n.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");default:return s?`@${s}`:i}},getSummary:e=>{const t=ye(e);return t.summary?qe(String(t.summary),80):void 0},render:(e,t)=>{if(e.result===void 0)return null;let n;try{const s=e.result,l=typeof s=="string"?s:String(s&&typeof s=="object"?s.text??s.output??JSON.stringify(s):s);n=JSON.parse(l)}catch{try{n=typeof e.result=="object"?e.result:void 0}catch{}}if(n!=null&&n.success||n!=null&&n.routing)return r.jsx("div",{className:"text-xs text-text-tertiary pl-2.5 py-0.5",children:t("team.delivered")});const i=ot(e.result);return i?r.jsx("div",{className:"text-xs text-text-secondary px-2.5 py-1.5 bg-bg-secondary/40 rounded-md",children:qe(i,200)}):null}},WebSearch:{Icon:Ri,getTitle:(e,t)=>t("tool.webSearch"),getSummary:e=>{const t=ye(e);return t.query?qe(String(t.query),80):void 0},render:e=>e.result===void 0?null:r.jsx(rt,{result:e.result,maxLines:10})},WebFetch:{Icon:Ri,getTitle:(e,t)=>t("tool.webFetch"),getSummary:e=>{const t=ye(e);return t.url?qe(String(t.url),60):void 0},render:e=>{const t=ye(e);return r.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&r.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&r.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)})]})}},SaveMemory:{Icon:Jv,getTitle:(e,t)=>t("tool.saveMemory"),getSummary:e=>{const t=ye(e);return t.content?qe(String(t.content),60):void 0}},AskUserQuestion:{Icon:Qv,getTitle:(e,t)=>t("tool.askUserQuestion"),getSummary:e=>{const n=ye(e).questions;if(!n||n.length===0)return;if(n.length===1)return n[0].question?qe(String(n[0].question),80):n[0].header;const i=n.map(s=>s.header||"?").join(", ");return`${n.length} questions: ${i}`},render:(e,t)=>{const i=ye(e).questions;return!i||i.length===0?e.result!==void 0?r.jsx(rt,{result:e.result,maxLines:6}):null:r.jsxs("div",{className:"space-y-2",children:[i.map((s,l)=>r.jsxs("div",{className:"rounded-md bg-bg-secondary/40 overflow-hidden",children:[r.jsxs("div",{className:"px-2.5 py-1.5 text-xs",children:[s.header&&r.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded bg-accent-brand/10 text-accent-brand text-[11px] font-medium mr-1.5",children:s.header}),r.jsx("span",{className:"text-text-primary font-medium",children:s.question}),s.multiSelect&&r.jsxs("span",{className:"text-[10px] text-text-tertiary ml-1",children:["(",t("question.multiLabel"),")"]})]}),s.options&&s.options.length>0&&r.jsx("div",{className:"border-t border-border-muted/30 px-2.5 py-1",children:s.options.map((d,a)=>r.jsxs("div",{className:"flex items-baseline gap-1.5 py-0.5 text-xs",children:[r.jsx("span",{className:"text-text-secondary font-medium",children:d.label}),d.description&&r.jsxs("span",{className:"text-text-tertiary",children:["— ",qe(String(d.description),60)]})]},a))})]},l)),e.result!==void 0&&r.jsx(rt,{result:e.result,maxLines:4})]})}},EnterPlanMode:{Icon:e_,getTitle:(e,t)=>t("tool.enterPlanMode"),render:e=>{if(e.result===void 0)return null;const t=ot(e.result);if(!t)return null;const n=e.result,i=n!=null&&n.planFilePath?String(n.planFilePath):void 0;return r.jsxs("div",{className:"text-xs px-2.5 py-1.5 bg-bg-secondary/40 rounded-md space-y-1",children:[i&&r.jsxs("div",{className:"flex items-center gap-1.5 text-text-tertiary",children:[r.jsx(sp,{size:10,className:"flex-shrink-0"}),r.jsx(vt,{path:i,className:"font-mono truncate"})]}),!i&&t&&r.jsx("div",{className:"text-text-secondary",children:qe(t,200)})]})}},ExitPlanMode:{Icon:t_,getTitle:(e,t)=>t("tool.exitPlanMode"),getSummary:(e,t)=>{const i=ye(e).allowedPrompts;if(i&&i.length>0)return t("tool.permissionsCount").replace("{count}",String(i.length))},render:(e,t)=>{const i=ye(e).allowedPrompts,s=i&&i.length>0,l=e.result!==void 0;return!s&&!l?null:r.jsxs("div",{className:"space-y-1",children:[s&&r.jsxs("div",{className:"rounded-md bg-bg-secondary/40 px-2.5 py-1.5",children:[r.jsx("div",{className:"text-[11px] text-text-tertiary mb-1",children:t("tool.allowedActions")}),i.map((d,a)=>r.jsxs("div",{className:"flex items-center gap-1.5 text-xs py-0.5",children:[r.jsx(jn,{size:10,className:"text-text-tertiary flex-shrink-0"}),r.jsx("span",{className:"text-text-secondary",children:d.prompt})]},a))]}),l&&r.jsx(rt,{result:e.result,maxLines:6})]})}},Skill:{Icon:xh,getTitle:(e,t)=>t("tool.skill"),getSummary:e=>{const t=ye(e);return t.skill?String(t.skill):t.command?String(t.command):void 0}}};function o_(e){return e.toolName&&fu[e.toolName]?fu[e.toolName]:e.kind&&gu[e.kind]?gu[e.kind]:kh}function l_(e){return!!(e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0)}const kh={Icon:xh,getSummary:e=>{const t=ye(e),n=r_(t);return n||void 0},render:e=>{const t=ye(e),n=Object.keys(t).length>0,i=e.result,s=i!==void 0&&!l_(i)&&ot(i).length>0;return!n&&!s?null:r.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[n&&r.jsx("pre",{className:"text-text-tertiary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:JSON.stringify(t,null,2)}),s&&r.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:ot(i)})]})}},wh="subagent-collapse-pref";function bu(){try{return localStorage.getItem(wh)==="true"}catch{return!1}}function c_(e){try{localStorage.setItem(wh,String(e))}catch{}}function d_(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5 ml-1 align-middle",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0s_infinite]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.2s_infinite]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.4s_infinite]"})]})}function yu({entry:e,isActive:t}){const n=e.streaming&&t,i=e.content&&e.content.trim().length>0;return!i&&!n?r.jsx(r.Fragment,{}):r.jsxs("div",{className:"markdown-body text-chat text-text-primary py-0.5",children:[i&&r.jsx(on,{remarkPlugins:[ln],children:e.content}),n&&r.jsx(d_,{})]})}function u_(e){return T.useMemo(()=>{const t=e.subagentTimeline||[];let n=0,i=0;for(const s of t)s.type==="tool_call_ref"?n++:s.type==="message"&&i++;return{toolCount:n,messageCount:i}},[e.subagentTimeline])}function p_({toolCall:e}){var m,u,f,x,E;const{t}=ne(),n=et(_=>_.childToolCalls),i=e.subagentTimeline||[],s=e.status==="running",l=e.status==="failed",d=!!((m=e.subagent)!=null&&m.memberName),a=u_(e),[o,c]=T.useState(()=>!s&&bu());T.useEffect(()=>{c(s?!1:bu())},[s]);const p=T.useCallback(()=>{s||c(_=>{const S=!_;return c_(S),S})},[s]),h=(u=e.subagent)!=null&&u.memberName?`@${e.subagent.memberName}`:((f=e.subagent)==null?void 0:f.type)||t("tool.agent"),b=((x=e.subagent)==null?void 0:x.description)||"",y=(E=e.subagent)==null?void 0:E.isBackground,k=i.length>0,v=k&&!o,g=T.useMemo(()=>{if(s)return null;const _=[];return l?_.push(t("tool.failed")):e.status==="completed"&&_.push(t("tool.completed")),a.toolCount>0&&_.push(t("tool.toolsCount").replace("{count}",String(a.toolCount))),_.length>0?_.join(" · "):null},[s,l,e.status,a.toolCount,t]);return d?r.jsxs("div",{className:`mb-1 rounded-lg border transition-colors ${s?"border-accent-purple/30 bg-accent-purple/5":l?"border-accent-red/20 bg-accent-red/5":"border-border-muted/50 bg-bg-secondary/30"}`,children:[r.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 ${k?"cursor-pointer":""}`,onClick:k?p:void 0,children:[r.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${s?"animate-pulse":""}`,children:r.jsx(dr,{size:12,className:"text-accent-purple"})}),r.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),b&&r.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",b]}),r.jsx("span",{className:"flex-1"}),g&&r.jsx("span",{className:"text-[11px] text-text-tertiary",children:g}),s&&r.jsx(ke,{size:12,className:"text-accent-purple animate-spin"}),l&&r.jsx(ur,{size:12,className:"text-accent-red"}),!s&&!l&&e.status==="completed"&&r.jsx(Bt,{size:12,className:"text-accent-green"}),k&&!s&&(o?r.jsx(Ae,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):r.jsx(nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),v&&r.jsx("div",{className:"px-3 pb-2 pt-0 ml-2.5 pl-3 border-l border-accent-purple/20",children:i.map(_=>{if(_.type==="message")return r.jsx(yu,{entry:_,isActive:s},_.id);const S=n.get(_.toolCallId);return S?S.toolName==="SendMessage"?r.jsx(xu,{toolCall:S},S.id):r.jsx(Oi,{toolCall:S},S.id):null})})]}):r.jsxs("div",{className:"mb-0.5",children:[r.jsxs("div",{className:`flex items-center gap-1.5 py-0.5 ${k?"cursor-pointer hover:bg-bg-hover/30 rounded-md -mx-1 px-1":""}`,onClick:k?p:void 0,children:[r.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${s?"animate-pulse":""}`,children:r.jsx(dr,{size:12,className:"text-accent-purple"})}),r.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),b&&r.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",b]}),y&&r.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-secondary text-text-tertiary",children:t("tool.background")}),r.jsx("span",{className:"flex-1"}),g&&r.jsx("span",{className:"text-[11px] text-text-tertiary",children:g}),s&&r.jsx(ke,{size:12,className:"text-accent-purple animate-spin"}),l&&r.jsx(ur,{size:12,className:"text-accent-red"}),k&&!s&&(o?r.jsx(Ae,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):r.jsx(nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),v&&r.jsx("div",{className:"ml-2.5 pl-3 border-l border-accent-purple/25",children:i.map(_=>{if(_.type==="message")return r.jsx(yu,{entry:_,isActive:s},_.id);const S=n.get(_.toolCallId);return S?S.toolName==="SendMessage"?r.jsx(xu,{toolCall:S},S.id):r.jsx(Oi,{toolCall:S},S.id):null})})]})}function xu({toolCall:e}){const{t}=ne(),n=ye(e),i=String(n.type||"message"),s=n.recipient?String(n.recipient):void 0,l=n.summary?String(n.summary):void 0,d=e.status==="completed";let a="";switch(i){case"message":a=s?`@${s}`:"message";break;case"broadcast":a="@team";break;case"shutdown_request":a=s?`@${s} · shutdown`:"shutdown";break;case"shutdown_response":a=n.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected");break;case"plan_approval_response":a=s?`@${s} · ${n.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");break;default:a=s?`@${s}`:i}return r.jsxs("div",{className:"flex items-center gap-1.5 py-0.5 text-xs text-text-tertiary",children:[r.jsx("span",{className:"font-medium text-accent-purple",children:a}),l&&r.jsxs("span",{className:"truncate",children:["· ",l]}),d&&r.jsxs("span",{className:"text-text-tertiary/60",children:["· ",t("team.delivered")]}),!d&&r.jsx(vh,{status:e.status})]})}function Oi({toolCall:e}){var k,v;const{t}=ne(),n=o_(e),[i,s]=T.useState(()=>e.status==="failed"||(e.toolName==="Write"||e.kind==="edit")&&e.status==="running");if(T.useEffect(()=>{e.status==="failed"&&s(!0)},[e.status]),e.subagent)return r.jsx(p_,{toolCall:e});const l=n.Icon,d=e.status==="completed"||e.status==="failed",a=!!n.render||e.result!==void 0&&n===kh,o=(k=n.getTitle)==null?void 0:k.call(n,e,t),c=n_(e),p=o||(e.kind==="execute"&&c?c:void 0)||e.name||e.toolName||t("tool.defaultName"),b=((v=n.getSummary)==null?void 0:v.call(n,e,t))||(e.kind!=="execute"?c:void 0),y=e.status==="completed";return r.jsxs("div",{className:"mb-0.5",children:[r.jsxs("button",{onClick:()=>a&&s(!i),className:["flex items-center gap-1.5 py-1 px-1 text-left w-full rounded-lg transition-colors",a?"hover:bg-bg-hover/60 cursor-pointer":"cursor-default"].join(" "),"aria-expanded":a?i:void 0,children:[r.jsx(l,{}),r.jsx("span",{className:`text-[13px] font-medium truncate ${y?"text-text-tertiary":"text-text-secondary"}`,children:p}),b&&r.jsx(Lv,{text:b,className:`text-[12px] truncate flex-1 ${y?"text-text-tertiary/70":"text-text-tertiary"}`}),!b&&r.jsx("span",{className:"flex-1"}),r.jsx(vh,{status:e.status}),a&&r.jsx(Ae,{size:12,strokeWidth:2,className:`text-text-tertiary flex-shrink-0 transition-transform duration-150 ${i?"rotate-90":""}`})]}),a&&i&&r.jsx("div",{className:"pl-5",children:r.jsx(h_,{renderer:n,toolCall:e,t,isFinished:d})})]})}function h_({renderer:e,toolCall:t,t:n,isFinished:i}){const s=e.render?e.render(t,n):r.jsx(rt,{result:t.result});return r.jsx("div",{className:"mt-0.5 mb-1",children:r.jsx("div",{className:i?"empty-result-container":"",children:s})})}const m_=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","AskUserQuestion"]),g_=2;function f_(e){const t=new Map;for(const n of e){const i=n.toolName.replace(/Tool$/,"");t.set(i,(t.get(i)||0)+1)}return Array.from(t.entries()).map(([n,i])=>i>1?`${n} ×${i}`:n).join(", ")}function Eh({entries:e}){const{t}=ne(),n=T.useMemo(()=>e.filter(m=>m.type==="tool_call"?!m_.has(m.toolName):m.type==="interruption"||m.type==="question"),[e]),i=T.useMemo(()=>n.filter(m=>m.type==="tool_call"),[n]),s=T.useMemo(()=>i.filter(m=>!m.subagent),[i]),l=i.some(m=>m.status==="running"),d=i.some(m=>m.status==="failed"),a=n.some(m=>m.type==="interruption"&&!m.resolved||m.type==="question"&&m.status==="pending"),c=!l&&!a&&!d&&!a&&s.length>=g_,[p,h]=T.useState(null),b=p!==null?!p:c,y=s.length,k=s.filter(m=>m.status==="failed").length,v=T.useMemo(()=>f_(s),[s]);if(n.length===0)return null;if(b)return r.jsx("div",{className:"mb-1.5 w-full",children:r.jsxs("button",{onClick:()=>h(!0),className:"flex items-center gap-2 py-1 px-1.5 w-full text-left rounded-lg hover:bg-bg-hover/50 transition-colors group","aria-expanded":!1,"aria-label":`${y} tools executed. Click to expand.`,children:[r.jsx(Ae,{size:12,strokeWidth:2.5,className:"text-text-tertiary shrink-0"}),r.jsx("span",{className:"text-[12px] text-text-tertiary",children:y===1?`1 ${t("tool.toolSingular")}`:`${y} ${t("tool.toolPlural")}`}),k>0&&r.jsxs("span",{className:"inline-flex items-center gap-1 text-[12px] text-accent-red",children:[r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent-red"}),k," failed"]}),r.jsx("span",{className:"flex-1 text-[11px] text-text-tertiary/60 truncate opacity-0 group-hover:opacity-100 transition-opacity",children:v})]})});const g=n.length>1;return r.jsxs("div",{className:"flex flex-col gap-0 mb-2 w-full",children:[c&&r.jsxs("button",{onClick:()=>h(!1),className:"flex items-center gap-2 py-0.5 px-1.5 text-left rounded-lg hover:bg-bg-hover/50 transition-colors","aria-expanded":!0,children:[r.jsx(nt,{size:12,strokeWidth:2.5,className:"text-text-tertiary shrink-0"}),r.jsx("span",{className:"text-[12px] text-text-tertiary",children:y===1?`1 ${t("tool.toolSingular")}`:`${y} ${t("tool.toolPlural")}`})]}),r.jsxs("div",{className:`relative ${g?"pl-4 ml-1.5":""}`,children:[g&&r.jsx("div",{className:"absolute left-0 top-1 bottom-1 w-px bg-border-default"}),r.jsx("div",{className:"flex flex-col gap-0.5",children:n.map(m=>m.type==="tool_call"?r.jsx(Oi,{toolCall:m},m.id):m.type==="interruption"?r.jsx(zv,{interruption:m},m.id):m.type==="question"?r.jsx(qv,{question:m},m.id):null)})]})]})}function b_(e){const t=e.match(/<command-name>(\/[^<]+)<\/command-name>/);if(!t)return null;const n=t[1];if(n==="/clear")return"";const i=e.match(/<command-args>([^<]*)<\/command-args>/),s=i?i[1]:"",l=e.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/),d=l?l[1].trim():"";let a=n;return s&&(a+=" "+s),d&&(a+=`
|
|
656
656
|
`+d),a}function y_(e){const t=e.replace(/<command-message>[\s\S]*?<\/command-message>\s*/g,"").replace(/<command-name>[\s\S]*?<\/command-name>\s*/g,"").replace(/<command-args>[\s\S]*?<\/command-args>\s*/g,"").replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>\s*/g,"").replace(/<user-prompt-submit-hook>[\s\S]*?<\/user-prompt-submit-hook>\s*/g,"").trim();return Cx(t).trim()}function Ch(e){const t=e.match(/<teammate-message\s+teammate_id="([^"]+)"(?:\s+summary="([^"]*)")?[^>]*>\n?([\s\S]*?)\n?<\/teammate-message>/);if(t)return{from:t[1],summary:t[2],content:t[3].trim()}}function x_(e){try{const t=JSON.parse(e);if(t&&typeof t=="object"&&t.type)return t.type==="shutdown_response"?t.reason||`Shutdown ${t.approve!==!1?"accepted":"rejected"}`:t.type==="shutdown_request"?t.reason||"Shutdown requested":t.reason||t.summary||e}catch{}return e}function Th({msg:e}){var b;const[t,n]=T.useState(!1),{t:i}=ne(),l=(b=We(y=>y.members).find(y=>y.name===e.from))==null?void 0:b.color,d=is(l),a=x_(e.content),o=a.split(`
|
|
657
657
|
`),c=8,p=o.length>c,h=p&&!t?o.slice(0,c).join(`
|
|
658
|
-
`):a;return r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[r.jsx("span",{className:"text-[13px] font-semibold",style:{color:d},children:e.from}),e.summary&&r.jsxs("span",{className:"text-[12px] text-text-tertiary",children:["· ",e.summary]})]}),r.jsxs("div",{className:"ml-2 pl-3 border-l-2",style:{borderColor:`${d}33`},children:[r.jsx("div",{className:"prose prose-sm prose-invert max-w-none text-text-secondary text-[13px] [&_p]:my-1 [&_pre]:my-2 [&_code]:text-[12px] [&_h1]:text-[15px] [&_h2]:text-[14px] [&_h3]:text-[13px] [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5",children:r.jsx(on,{remarkPlugins:[ln],children:h})}),p&&r.jsx("button",{type:"button",onClick:()=>n(!t),className:"text-[11px] text-text-tertiary hover:text-text-secondary mt-1 transition-colors",children:t?i("team.showLess"):i("team.moreLines").replace("{count}",String(o.length-c))})]})]})}function v_(e){if(!e)return!0;const t=e.trimStart();return!!/^\/clear\b/.test(t)}function Nh(e){const t=[];for(let n=0;n<e.length;n++){const i=e[n];if(i.type==="message"){const s=i;if(s.isCompactInternal){const l=t[t.length-1];l&&l.kind==="compact_group"?l.entries.push(s):t.push({kind:"compact_group",entries:[s]})}else if(s.role==="user"&&s.channel)t.push({kind:"channel_incoming",entry:s});else if(s.role==="user"){if(v_(s.content))continue;t.push({kind:"user",entry:s})}else{if(!s.thinking){const l=e[n+1];if(l&&l.type==="tool_call"&&l.subagent)continue}t.push({kind:"assistant_message",entry:s})}}else{const s=t[t.length-1];s&&s.kind==="assistant_tools"?s.entries.push(i):t.push({kind:"assistant_tools",entries:[i]})}}return t}function vu(e){var t;switch(e.kind){case"user":case"assistant_message":case"channel_incoming":return e.entry.timestamp;case"compact_group":return(t=e.entries[0])==null?void 0:t.timestamp;case"assistant_tools":return}}function __(e,t=150){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function _u(){const{t:e}=ne(),n=Ke(l=>l.resolved)==="dark"?Op:$p,i=zt(l=>{var d;return(d=l.info)==null?void 0:d.cwd}),s=T.useMemo(()=>{if(!i)return"";const l=i.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(\/.*)?$/);return l?"~"+(l[2]||""):i},[i]);return r.jsxs("div",{className:"empty-state",children:[r.jsx("div",{className:"empty-state-logo",children:r.jsx("img",{src:n,alt:"CodeBuddy"})}),s&&r.jsx("p",{className:"empty-state-cwd",title:i,children:s}),r.jsxs("p",{className:"empty-state-hint hidden md:block",children:[r.jsxs("kbd",{children:[/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl","+Shift+P"]}),r.jsx("span",{children:e("commandPalette.tip")})]})]})}function S_({onClickCloseBottomSheet:e}={}){const{timeline:t,isAgentRunning:n,stopReason:i,errorMessage:s,errorCategory:l,historyLoading:d,agentPhaseLabel:a,progressLabel:o,hasPendingInterruption:c}=et(),p=T.useRef(null),h=T.useRef(null),{t:b,resolved:y}=ne(),[k,v]=T.useState(null);T.useEffect(()=>{if(!k)return;const M=F=>{F.key==="Escape"&&v(null)};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[k]);const g=T.useRef(!0),m=T.useRef(0),u=T.useRef(!1),f=T.useMemo(()=>Nh(t),[t]),x=f.length===0,[E,_]=T.useState(!0),[S,w]=T.useState(!1),N=T.useRef(!1);T.useEffect(()=>{if(!x&&!N.current){w(!0);const M=setTimeout(()=>{_(!1),N.current=!0},600);return()=>clearTimeout(M)}},[x]);const D=T.useCallback(()=>{if(u.current)return;const M=h.current;M&&(g.current=__(M))},[]);T.useEffect(()=>{const M=t.length;if(M>m.current){const F=t[m.current];(F==null?void 0:F.type)==="message"&&F.role==="user"&&(g.current=!0)}m.current=M},[t]),T.useEffect(()=>{if(!g.current)return;const M=h.current;M&&(u.current=!0,M.scrollTop=M.scrollHeight,requestAnimationFrame(()=>{u.current=!1}))},[t,n]);const R=t[t.length-1],j=(R==null?void 0:R.type)==="message"&&R.streaming,O=j&&!!R.thinking&&!R.content,H=T.useRef(!1);return T.useEffect(()=>{if(c&&!H.current){const M=h.current;M&&(u.current=!0,M.scrollTop=M.scrollHeight,requestAnimationFrame(()=>{u.current=!1}))}H.current=c},[c]),r.jsxs("div",{ref:h,onScroll:D,onClick:()=>e==null?void 0:e(),className:"absolute inset-0 overflow-y-auto overflow-x-hidden",role:"log","aria-label":"Chat messages",children:[E&&r.jsx("div",{className:`empty-state-wrapper${S?" empty-state-fadeout":""}`,children:r.jsx(_u,{})}),!E&&d&&t.length===0&&r.jsx("div",{className:"flex items-center justify-center min-h-[60vh] h-full pb-20",children:r.jsx($b,{size:"large"})}),!E&&x&&!n&&!d&&r.jsx(_u,{}),!x&&r.jsx("div",{className:"px-4 sm:px-6 pt-6 pb-4 animate-fadeIn",children:r.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[r.jsx("div",{className:"text-center mb-8",children:r.jsx("span",{className:"text-[13px] text-text-tertiary",children:b("chat.disclaimer")})}),f.map((M,F)=>{var A,L,I,G;const V=vu(M);let q=!1,C="";if(V!==void 0){const B=Sr(V);let W=null;for(let z=F-1;z>=0;z--){const U=vu(f[z]);if(U!==void 0){W=Sr(U);break}}B!==W&&(q=!0,C=fh(V,y))}if(M.kind==="user"){const B=M.entry.content?Ch(M.entry.content):void 0;if(B)return B.from==="system"?null:r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Th,{msg:B})]},M.entry.id);const W=M.entry.content||"",z=b_(W);if(z==="")return null;const U=z??y_(W);return!U&&!((A=M.entry.images)!=null&&A.length)&&!((L=M.entry.files)!=null&&L.length)?null:r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx("div",{className:"flex justify-end mb-6",children:r.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] px-5 py-3 rounded-2xl rounded-tr-sm bg-bg-user border border-transparent",children:[M.entry.images&&M.entry.images.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:M.entry.images.map(($,Y)=>{const X="url"in $?$.url:`data:${$.mimeType};base64,${$.data}`;return r.jsx("img",{src:X,alt:"",className:"max-w-full h-auto rounded-lg cursor-pointer hover:opacity-80 transition-opacity",style:{maxHeight:360},onClick:()=>v(X)},Y)})}),M.entry.files&&M.entry.files.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:M.entry.files.map(($,Y)=>r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-bg-primary/50 border border-border-muted/30 max-w-[180px]",children:[r.jsx(ct,{size:14,className:"shrink-0 text-text-tertiary"}),r.jsx("span",{className:"text-[12px] text-text-primary truncate",title:$.name,children:$.name})]},Y))}),U&&r.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:U})]})})]},M.entry.id)}if(M.kind==="channel_incoming")return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Rx,{content:M.entry.content,channel:M.entry.channel})]},M.entry.id);if(M.kind==="assistant_message"){if(!M.entry.content&&!M.entry.thinking)return null;const B=F>0?f[F-1]:void 0,W=(B==null?void 0:B.kind)==="channel_incoming";return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),W&&B.kind==="channel_incoming"&&r.jsx(Lx,{channel:B.entry.channel}),r.jsx("div",{className:"mb-2 w-full",children:r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx(ad,{message:M.entry})})})]},M.entry.id)}if(M.kind==="assistant_tools"){const B=((I=M.entries[0])==null?void 0:I.id)||`tools-${F}`;return r.jsx(Eh,{entries:M.entries},B)}if(M.kind==="compact_group"){const B=((G=M.entries[0])==null?void 0:G.id)||`compact-${F}`;return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Fv,{entries:M.entries})]},B)}return null}),n&&t.length>0&&!j&&!O&&(()=>{const M=c&&a&&(a==="chat.waitingPermission"||a==="chat.waitingUser"),F=a==="phase.retrying";let V;if(o)V=b(o)||b("chat.thinking");else if(!a)V=b("chat.thinking");else if(a.startsWith("phase.toolExecutingName:")){const C=a.slice(24);V=`${b("phase.toolExecuting")} ${C}`}else if(a.startsWith("phase.modelStreamingName:")){const C=a.slice(25);V=y!=null&&y.startsWith("zh")?b("phase.modelStreamingTool"):`${b("phase.modelStreamingTool")} ${C}`}else V=b(a)||b("chat.thinking");const q=M||F;return r.jsx("div",{className:"mb-2",children:r.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs ${q?"text-accent-brand animate-pulse":"text-text-tertiary"}`,children:[r.jsx(ke,{size:12,className:"text-accent-brand animate-spin"}),r.jsx("span",{children:V})]})})})(),i&&!n&&r.jsx("div",{className:"py-2",children:r.jsx("span",{className:"text-xs text-text-tertiary",children:(()=>{if(i==="max_tokens")return b("chat.error.maxTokens");if(i==="max_turn_requests")return b("chat.error.maxTurnRequests");if(i==="refusal")switch(l){case"network":return b("chat.error.network");case"auth":return b("chat.error.auth");case"quota":return b("chat.error.quota");case"model_service":return b("chat.error.modelService");default:return s?`${b("chat.error")}: ${s}`:b("chat.error.refusal")}return s?`${b("chat.error")}: ${s}`:b("chat.stopped")})()})})]})}),r.jsx("div",{ref:p,className:"h-6"}),k&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 cursor-zoom-out",onClick:()=>v(null),children:r.jsx("img",{src:k,alt:"",className:"max-w-[90vw] max-h-[90vh] object-contain rounded-lg shadow-2xl",onClick:M=>M.stopPropagation()})})]})}function or(e,t){const n=e.toLowerCase(),i=t.toLowerCase();let s=0,l=0,d=-1;const a=[];for(let o=0;o<i.length&&s<n.length;o++)i[o]===n[s]&&(l+=o===d+1?2:1,(o===0||/[/.\-_ ]/.test(i[o-1]))&&(l+=3),o>0&&i[o]!==t[o]&&t[o]===t[o].toUpperCase()&&(l+=2),a.push(o),d=o,s++);return{match:s===n.length,score:l,positions:a}}function Su(e){const t=e.split("+"),n={key:"",ctrl:!1,alt:!1,shift:!1,meta:!1,super:!1};for(const i of t){const s=i.toLowerCase();switch(s){case"ctrl":case"control":n.ctrl=!0;break;case"alt":case"opt":case"option":n.alt=!0;break;case"shift":n.shift=!0;break;case"meta":n.meta=!0;break;case"cmd":case"command":case"super":case"win":n.super=!0;break;case"esc":n.key="escape";break;case"return":n.key="enter";break;case"space":n.key=" ";break;default:n.key=s;break}}return n}function k_(e){return e===" "?[Su("space")]:e.trim().split(/\s+/).map(Su)}function w_(e){switch(e){case"escape":return"Esc";case" ":return"Space";case"tab":return"Tab";case"enter":return"Enter";case"backspace":return"Backspace";case"delete":return"Delete";case"up":return"↑";case"down":return"↓";case"left":return"←";case"right":return"→";default:return e.length===1?e.toUpperCase():e}}const $i=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform||navigator.userAgent);function Ah(e){const t=[];return e.ctrl&&t.push("Ctrl"),(e.alt||e.meta)&&t.push($i?"Opt":"Alt"),e.shift&&t.push("Shift"),e.super&&t.push($i?"Cmd":"Super"),t.push(w_(e.key)),t.join("+")}function kr(e){return e.map(Ah).join(" ")}function ku(e){const t=[];for(const n of e)for(const[i,s]of Object.entries(n.bindings))t.push({chord:k_(i),action:s,context:n.context});return t}function E_(e){switch(e){case"Escape":return"escape";case"Enter":return"enter";case"Tab":return"tab";case"Backspace":return"backspace";case"Delete":return"delete";case"ArrowUp":return"up";case"ArrowDown":return"down";case"ArrowLeft":return"left";case"ArrowRight":return"right";case" ":return" ";default:return e.length===1,e.toLowerCase()}}function Ih(e){const t=E_(e.key);return!t||e.key==="Control"||e.key==="Shift"||e.key==="Alt"||e.key==="Meta"?null:{key:t,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey,meta:e.metaKey,super:$i?e.metaKey:!1}}const C_=1e3,od=Te((e,t)=>({defaults:[],userBlocks:null,bindings:[],warnings:[],contexts:[],actions:[],reserved:[],filePath:"",loaded:!1,activeContexts:new Set(["Global"]),pendingChord:null,chordTimeoutId:null,loadBindings:async()=>{try{const n=await fetch(`${window.location.origin}/api/v1/keybindings`,{headers:ae()});if(!n.ok)return;const i=await n.json(),s=i.data??i,l=ku(s.defaults),d=s.user?ku(s.user):[],a=[...l,...d];e({defaults:s.defaults,userBlocks:s.user,bindings:a,warnings:s.warnings,contexts:s.contexts,actions:s.actions,reserved:s.reserved,filePath:s.filePath,loaded:!0})}catch(n){console.error("[KeybindingStore] Failed to load bindings:",n),e({loaded:!0})}},resolveKeyboardEvent:n=>{const i=t(),{bindings:s,activeContexts:l,pendingChord:d,chordTimeoutId:a}=i,o=Ih(n);if(!o)return d&&li(e,a),{type:"none"};if(n.key==="Escape"&&d)return li(e,a),{type:"none"};const c=d?[...d,o]:[o],p=l,h=s.filter(k=>p.has(k.context));let b=!1;for(const k of h)if(k.chord.length>c.length&&T_(c,k)&&k.action!==null){b=!0;break}if(b){a&&clearTimeout(a);const k=setTimeout(()=>{e({pendingChord:null,chordTimeoutId:null})},C_);return e({pendingChord:c,chordTimeoutId:k}),{type:"none"}}let y;for(const k of h)N_(c,k)&&(y=k);return li(e,a),y?y.action===null?{type:"unbound"}:{type:"match",action:y.action}:{type:"none"}},registerContext:n=>{e(i=>{const s=new Set(i.activeContexts);return s.add(n),{activeContexts:s}})},unregisterContext:n=>{e(i=>{const s=new Set(i.activeContexts);return s.delete(n),{activeContexts:s}})},saveUserBindings:async n=>{try{const i=await fetch(`${window.location.origin}/api/v1/keybindings`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify(n)});if(!i.ok)return console.error(`[KeybindingStore] Save failed: ${i.status}`),[];const s=await i.json(),l=s.data??s;return await t().loadBindings(),l.warnings??[]}catch(i){return console.error("[KeybindingStore] Failed to save bindings:",i),[]}},resetBindings:async()=>{try{const n=await fetch(`${window.location.origin}/api/v1/keybindings/reset`,{method:"POST",headers:ae()});if(!n.ok){console.error(`[KeybindingStore] Reset failed: ${n.status}`);return}await t().loadBindings()}catch(n){console.error("[KeybindingStore] Failed to reset bindings:",n)}},getDisplayText:(n,i)=>{const{bindings:s}=t();for(let l=s.length-1;l>=0;l--)if(s[l].action===n&&s[l].context===i)return kr(s[l].chord)}}));function li(e,t){t&&clearTimeout(t),e({pendingChord:null,chordTimeoutId:null})}function Rh(e,t){return e.key===t.key&&e.ctrl===t.ctrl&&e.shift===t.shift&&(e.alt||e.meta)===(t.alt||t.meta)&&e.super===t.super}function T_(e,t){if(e.length>=t.chord.length)return!1;for(let n=0;n<e.length;n++)if(!Rh(e[n],t.chord[n]))return!1;return!0}function N_(e,t){if(e.length!==t.chord.length)return!1;for(let n=0;n<e.length;n++)if(!Rh(e[n],t.chord[n]))return!1;return!0}class A_{constructor(){fe(this,"bindings",[]);fe(this,"actionHandlers",new Map);fe(this,"_suspended",!1)}register(t){return this.bindings.push(t),()=>{this.bindings=this.bindings.filter(n=>n!==t)}}registerAction(t,n,i){const s={id:t,handler:n,when:i};return this.actionHandlers.set(t,s),()=>{this.actionHandlers.get(t)===s&&this.actionHandlers.delete(t)}}suspend(){this._suspended=!0}resume(){this._suspended=!1}handleKeyDown(t){var d;const n=(d=t.target)==null?void 0:d.tagName,i=n==="INPUT"||n==="TEXTAREA",s=od.getState();if(s.loaded&&s.bindings.length>0){const a=s.resolveKeyboardEvent(t);if(a.type==="match"){const o=this.actionHandlers.get(a.action),c=a.action==="app:commandPalette";if(this._suspended&&!c||i&&!c)return;if(o){if(o.when&&!o.when())return;t.preventDefault(),t.stopPropagation(),o.handler(t);return}}if(a.type==="unbound")return}const l=t.metaKey||t.ctrlKey;for(const a of this.bindings)if(a.meta===l&&(a.shift??!1)===t.shiftKey&&a.key===t.key.toLowerCase()&&!(this._suspended&&a.id!=="commandPalette.toggle")&&!(i&&a.id!=="commandPalette.toggle")&&!(a.when&&!a.when())){t.preventDefault(),t.stopPropagation(),a.handler(t);return}}}const Ge=new A_,I_=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),ji=I_?"⌘":"Ctrl",R_=[{view:"chat",icon:r.jsx(dn,{size:16}),labelKey:"sidebar.chatMode"},{view:"workers",icon:r.jsx(Gt,{size:16}),labelKey:"sidebar.workers"},{view:"remote-control",icon:r.jsx(hr,{size:16}),labelKey:"sidebar.remoteControl"},{view:"tasks",icon:r.jsx(Xi,{size:16}),labelKey:"sidebar.nav.tasks"},{view:"terminal",icon:r.jsx(un,{size:16}),labelKey:"sidebar.terminalMode",shortcut:`${ji}+J`},{view:"canvas",icon:r.jsx(mp,{size:16}),labelKey:"sidebar.canvas"},{view:"editor",icon:r.jsx(op,{size:16}),labelKey:"sidebar.editor"},{view:"changes",icon:r.jsx(Tr,{size:16}),labelKey:"sidebar.changes"},{view:"plugins",icon:r.jsx(Ft,{size:16}),labelKey:"sidebar.nav.plugins"},{view:"stats",icon:r.jsx(Vi,{size:16}),labelKey:"sidebar.stats"},{view:"traces",icon:r.jsx(Cp,{size:16}),labelKey:"sidebar.traces"},{view:"metrics",icon:r.jsx(Wi,{size:16}),labelKey:"sidebar.metrics"},{view:"logs",icon:r.jsx(Ki,{size:16}),labelKey:"sidebar.logs"},{view:"settings",icon:r.jsx(Qi,{size:16}),labelKey:"sidebar.preferences",shortcut:`${ji}+,`},{view:"keybindings",icon:r.jsx(hp,{size:16}),labelKey:"sidebar.keybindings"},{view:"docs",icon:r.jsx(qi,{size:16}),labelKey:"sidebar.docs"}];function L_({text:e,positions:t}){if(t.length===0)return r.jsx(r.Fragment,{children:e});const n=new Set(t);return r.jsx(r.Fragment,{children:e.split("").map((i,s)=>n.has(s)?r.jsx("span",{className:"font-bold text-accent-brand",children:i},s):r.jsx("span",{children:i},s))})}const Qn=12;function D_({isOpen:e,onClose:t,onNavigate:n,onNewChat:i}){const{t:s,tryT:l,resolved:d}=ne(),a=tt(S=>S.commands),o=tt(S=>S.sessionId),c=Ke(S=>S.toggle),p=Ke(S=>S.resolved),[h,b]=T.useState(""),[y,k]=T.useState(0),v=T.useRef(null),g=T.useRef(null);T.useEffect(()=>{e?(Ge.suspend(),b(""),k(0),setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},50)):Ge.resume()},[e]);const m=T.useMemo(()=>{const S=[];for(const w of R_)S.push({id:`view:${w.view}`,label:s(w.labelKey),category:"view",icon:r.jsx("span",{className:"text-text-tertiary",children:w.icon}),shortcut:w.shortcut,action:()=>n(w.view)});S.push({id:"action:newChat",label:s("commandPalette.newChat"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx(dn,{size:16})}),shortcut:`${ji}+N`,action:i}),S.push({id:"action:toggleTheme",label:s("commandPalette.toggleTheme"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:p==="dark"?r.jsx(kp,{size:16}):r.jsx(yp,{size:16})}),action:c}),S.push({id:"action:toggleLocale",label:s("commandPalette.toggleLocale"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx($f,{size:16})}),action:()=>fr.getState().toggle()});for(const w of a){const N=l(`command.${w.name}.description`)||w.description;S.push({id:`cmd:${w.name}`,label:`/${w.name}`,description:N,category:"command",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx(un,{size:16})}),action:()=>{o&&Ie().prompt(o,`/${w.name}`).catch(()=>{})}})}return S},[a,o,n,i,c,p,s,d]),u=T.useMemo(()=>{const S=h.trim();if(S.startsWith(">")){const w=S.slice(1).trim(),N=m.filter(D=>D.category==="command");return w?N.map(D=>({item:D,result:or(w,D.label)})).filter(D=>D.result.match).sort((D,R)=>R.result.score-D.result.score).slice(0,Qn).map(D=>({...D.item,_positions:D.result.positions})):N.slice(0,Qn)}if(!S){const w=m.filter(R=>R.category==="action"),N=m.filter(R=>R.category==="view").slice(0,6),D=m.filter(R=>R.category==="command").slice(0,4);return[...w,...N,...D].slice(0,Qn)}return m.map(w=>({item:w,result:or(S,w.label+" "+(w.description||""))})).filter(w=>w.result.match).sort((w,N)=>N.result.score-w.result.score).slice(0,Qn).map(w=>({...w.item,_positions:or(S,w.item.label).positions}))},[h,m]);T.useEffect(()=>{k(0)},[u.length]);const f=T.useCallback(S=>{t(),setTimeout(()=>S.action(),50)},[t]),x=T.useCallback(S=>{switch(S.key){case"ArrowDown":S.preventDefault(),k(w=>(w+1)%Math.max(u.length,1));break;case"ArrowUp":S.preventDefault(),k(w=>(w-1+u.length)%Math.max(u.length,1));break;case"Enter":S.preventDefault(),u[y]&&f(u[y]);break;case"Escape":S.preventDefault(),t();break}},[u,y,f,t]);if(T.useEffect(()=>{const S=g.current;if(!S)return;const w=S.children[y];w&&w.scrollIntoView({block:"nearest"})},[y]),!e)return null;const E=S=>{switch(S){case"command":return s("commandPalette.commands");case"view":return s("commandPalette.views");case"action":return s("commandPalette.actions");default:return""}};let _="";return r.jsxs("div",{className:"fixed inset-0 z-[200] flex items-start justify-center pt-[12vh] max-md:items-end max-md:pt-0",onClick:t,children:[r.jsx("div",{className:"absolute inset-0 bg-black/30"}),r.jsxs("div",{className:"relative w-full max-w-[640px] mx-4 bg-bg-card border border-border-default rounded-xl shadow-2xl overflow-hidden max-md:rounded-b-none max-md:rounded-t-xl max-md:max-w-none max-md:mx-0",onClick:S=>S.stopPropagation(),onKeyDown:x,children:[r.jsxs("div",{className:"flex items-center px-5 py-3.5 border-b border-border-muted",children:[r.jsx(st,{size:18,className:"text-text-tertiary shrink-0 mr-3"}),r.jsx("input",{ref:v,type:"text",className:"flex-1 bg-transparent text-text-primary text-[15px] outline-none placeholder:text-text-tertiary",placeholder:s("commandPalette.placeholder"),value:h,onChange:S=>b(S.target.value),"aria-label":s("commandPalette.placeholder"),autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1})]}),r.jsx("div",{ref:g,className:"max-h-[400px] overflow-y-auto py-1.5",role:"listbox",children:u.length===0?r.jsx("div",{className:"px-5 py-6 text-center text-text-tertiary text-[13px]",children:s("commandPalette.noResults")}):u.map((S,w)=>{const N=S.category!==_;_=S.category;const D=S._positions;return r.jsxs("div",{children:[N&&r.jsx("div",{className:"px-5 pt-2.5 pb-1 text-[11px] font-medium text-text-tertiary uppercase tracking-wide",children:E(S.category)}),r.jsxs("div",{role:"option","aria-selected":w===y,className:["flex items-center gap-3 px-5 py-2 mx-1.5 rounded-lg cursor-pointer transition-colors",w===y?"bg-bg-hover text-text-primary":"text-text-secondary hover:bg-bg-hover"].join(" "),onClick:()=>f(S),onMouseEnter:()=>k(w),children:[r.jsx("span",{className:"shrink-0 w-5 flex items-center justify-center",children:S.icon}),r.jsxs("span",{className:"flex-1 text-[13px] truncate",children:[D?r.jsx(L_,{text:S.label,positions:D}):S.label,S.description&&r.jsx("span",{className:"ml-2 text-text-tertiary text-[12px]",children:S.description})]}),S.shortcut&&r.jsx("kbd",{className:"shrink-0 text-[11px] text-text-tertiary font-mono bg-bg-tertiary px-1.5 py-0.5 rounded",children:S.shortcut})]})]},S.id)})}),r.jsxs("div",{className:"flex items-center gap-4 px-5 py-2.5 border-t border-border-muted text-[11px] text-text-tertiary",children:[r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"↑↓"})," navigate"]}),r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"↵"})," execute"]}),r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"esc"})," close"]})]})]})]})}const O_="ENTRIES",Lh="KEYS",Dh="VALUES",De="";class ci{constructor(t,n){const i=t._tree,s=Array.from(i.keys());this.set=t,this._type=n,this._path=s.length>0?[{node:i,keys:s}]:[]}next(){const t=this.dive();return this.backtrack(),t}dive(){if(this._path.length===0)return{done:!0,value:void 0};const{node:t,keys:n}=Kt(this._path);if(Kt(n)===De)return{done:!1,value:this.result()};const i=t.get(Kt(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;const t=Kt(this._path).keys;t.pop(),!(t.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:t})=>Kt(t)).filter(t=>t!==De).join("")}value(){return Kt(this._path).node.get(De)}result(){switch(this._type){case Dh:return this.value();case Lh:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}}const Kt=e=>e[e.length-1],$_=(e,t,n)=>{const i=new Map;if(t===void 0)return i;const s=t.length+1,l=s+n,d=new Uint8Array(l*s).fill(n+1);for(let a=0;a<s;++a)d[a]=a;for(let a=1;a<l;++a)d[a*s]=a;return Oh(e,t,n,i,d,1,s,""),i},Oh=(e,t,n,i,s,l,d,a)=>{const o=l*d;e:for(const c of e.keys())if(c===De){const p=s[o-1];p<=n&&i.set(a,[e.get(c),p])}else{let p=l;for(let h=0;h<c.length;++h,++p){const b=c[h],y=d*p,k=y-d;let v=s[y];const g=Math.max(0,p-n-1),m=Math.min(d-1,p+n);for(let u=g;u<m;++u){const f=b!==t[u],x=s[k+u]+ +f,E=s[k+u+1]+1,_=s[y+u]+1,S=s[y+u+1]=Math.min(x,E,_);S<v&&(v=S)}if(v>n)continue e}Oh(e.get(c),t,n,i,s,p,d,a+c)}};class Tt{constructor(t=new Map,n=""){this._size=void 0,this._tree=t,this._prefix=n}atPrefix(t){if(!t.startsWith(this._prefix))throw new Error("Mismatched prefix");const[n,i]=wr(this._tree,t.slice(this._prefix.length));if(n===void 0){const[s,l]=ld(i);for(const d of s.keys())if(d!==De&&d.startsWith(l)){const a=new Map;return a.set(d.slice(l.length),s.get(d)),new Tt(a,t)}}return new Tt(n,t)}clear(){this._size=void 0,this._tree.clear()}delete(t){return this._size=void 0,j_(this._tree,t)}entries(){return new ci(this,O_)}forEach(t){for(const[n,i]of this)t(n,i,this)}fuzzyGet(t,n){return $_(this._tree,t,n)}get(t){const n=Mi(this._tree,t);return n!==void 0?n.get(De):void 0}has(t){const n=Mi(this._tree,t);return n!==void 0&&n.has(De)}keys(){return new ci(this,Lh)}set(t,n){if(typeof t!="string")throw new Error("key must be a string");return this._size=void 0,di(this._tree,t).set(De,n),this}get size(){if(this._size)return this._size;this._size=0;const t=this.entries();for(;!t.next().done;)this._size+=1;return this._size}update(t,n){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;const i=di(this._tree,t);return i.set(De,n(i.get(De))),this}fetch(t,n){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;const i=di(this._tree,t);let s=i.get(De);return s===void 0&&i.set(De,s=n()),s}values(){return new ci(this,Dh)}[Symbol.iterator](){return this.entries()}static from(t){const n=new Tt;for(const[i,s]of t)n.set(i,s);return n}static fromObject(t){return Tt.from(Object.entries(t))}}const wr=(e,t,n=[])=>{if(t.length===0||e==null)return[e,n];for(const i of e.keys())if(i!==De&&t.startsWith(i))return n.push([e,i]),wr(e.get(i),t.slice(i.length),n);return n.push([e,t]),wr(void 0,"",n)},Mi=(e,t)=>{if(t.length===0||e==null)return e;for(const n of e.keys())if(n!==De&&t.startsWith(n))return Mi(e.get(n),t.slice(n.length))},di=(e,t)=>{const n=t.length;e:for(let i=0;e&&i<n;){for(const l of e.keys())if(l!==De&&t[i]===l[0]){const d=Math.min(n-i,l.length);let a=1;for(;a<d&&t[i+a]===l[a];)++a;const o=e.get(l);if(a===l.length)e=o;else{const c=new Map;c.set(l.slice(a),o),e.set(t.slice(i,i+a),c),e.delete(l),e=c}i+=a;continue e}const s=new Map;return e.set(t.slice(i),s),s}return e},j_=(e,t)=>{const[n,i]=wr(e,t);if(n!==void 0){if(n.delete(De),n.size===0)$h(i);else if(n.size===1){const[s,l]=n.entries().next().value;jh(i,s,l)}}},$h=e=>{if(e.length===0)return;const[t,n]=ld(e);if(t.delete(n),t.size===0)$h(e.slice(0,-1));else if(t.size===1){const[i,s]=t.entries().next().value;i!==De&&jh(e.slice(0,-1),i,s)}},jh=(e,t,n)=>{if(e.length===0)return;const[i,s]=ld(e);i.set(s+t,n),i.delete(s)},ld=e=>e[e.length-1],cd="or",Mh="and",M_="and_not";class rn{constructor(t){if((t==null?void 0:t.fields)==null)throw new Error('MiniSearch: option "fields" must be provided');const n=t.autoVacuum==null||t.autoVacuum===!0?hi:t.autoVacuum;this._options={...pi,...t,autoVacuum:n,searchOptions:{...wu,...t.searchOptions||{}},autoSuggestOptions:{...z_,...t.autoSuggestOptions||{}}},this._index=new Tt,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Fi,this.addFields(this._options.fields)}add(t){const{extractField:n,stringifyField:i,tokenize:s,processTerm:l,fields:d,idField:a}=this._options,o=n(t,a);if(o==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(o))throw new Error(`MiniSearch: duplicate ID ${o}`);const c=this.addDocumentId(o);this.saveStoredFields(c,t);for(const p of d){const h=n(t,p);if(h==null)continue;const b=s(i(h,p),p),y=this._fieldIds[p],k=new Set(b).size;this.addFieldLength(c,y,this._documentCount-1,k);for(const v of b){const g=l(v,p);if(Array.isArray(g))for(const m of g)this.addTerm(y,c,m);else g&&this.addTerm(y,c,g)}}}addAll(t){for(const n of t)this.add(n)}addAllAsync(t,n={}){const{chunkSize:i=10}=n,s={chunk:[],promise:Promise.resolve()},{chunk:l,promise:d}=t.reduce(({chunk:a,promise:o},c,p)=>(a.push(c),(p+1)%i===0?{chunk:[],promise:o.then(()=>new Promise(h=>setTimeout(h,0))).then(()=>this.addAll(a))}:{chunk:a,promise:o}),s);return d.then(()=>this.addAll(l))}remove(t){const{tokenize:n,processTerm:i,extractField:s,stringifyField:l,fields:d,idField:a}=this._options,o=s(t,a);if(o==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);const c=this._idToShortId.get(o);if(c==null)throw new Error(`MiniSearch: cannot remove document with ID ${o}: it is not in the index`);for(const p of d){const h=s(t,p);if(h==null)continue;const b=n(l(h,p),p),y=this._fieldIds[p],k=new Set(b).size;this.removeFieldLength(c,y,this._documentCount,k);for(const v of b){const g=i(v,p);if(Array.isArray(g))for(const m of g)this.removeTerm(y,c,m);else g&&this.removeTerm(y,c,g)}}this._storedFields.delete(c),this._documentIds.delete(c),this._idToShortId.delete(o),this._fieldLength.delete(c),this._documentCount-=1}removeAll(t){if(t)for(const n of t)this.remove(n);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Tt,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(t){const n=this._idToShortId.get(t);if(n==null)throw new Error(`MiniSearch: cannot discard document with ID ${t}: it is not in the index`);this._idToShortId.delete(t),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach((i,s)=>{this.removeFieldLength(n,s,this._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;const{minDirtFactor:t,minDirtCount:n,batchSize:i,batchWait:s}=this._options.autoVacuum;this.conditionalVacuum({batchSize:i,batchWait:s},{minDirtCount:n,minDirtFactor:t})}discardAll(t){const n=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(const i of t)this.discard(i)}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()}replace(t){const{idField:n,extractField:i}=this._options,s=i(t,n);this.discard(s),this.add(t)}vacuum(t={}){return this.conditionalVacuum(t)}conditionalVacuum(t,n){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&n,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{const i=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Fi,this.performVacuuming(t,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(n)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(t),this._currentVacuum)}async performVacuuming(t,n){const i=this._dirtCount;if(this.vacuumConditionsMet(n)){const s=t.batchSize||Pi.batchSize,l=t.batchWait||Pi.batchWait;let d=1;for(const[a,o]of this._index){for(const[c,p]of o)for(const[h]of p)this._documentIds.has(h)||(p.size<=1?o.delete(c):p.delete(h));this._index.get(a).size===0&&this._index.delete(a),d%s===0&&await new Promise(c=>setTimeout(c,l)),d+=1}this._dirtCount-=i}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(t){if(t==null)return!0;let{minDirtCount:n,minDirtFactor:i}=t;return n=n||hi.minDirtCount,i=i||hi.minDirtFactor,this.dirtCount>=n&&this.dirtFactor>=i}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(t){return this._idToShortId.has(t)}getStoredFields(t){const n=this._idToShortId.get(t);if(n!=null)return this._storedFields.get(n)}search(t,n={}){const{searchOptions:i}=this._options,s={...i,...n},l=this.executeQuery(t,n),d=[];for(const[a,{score:o,terms:c,match:p}]of l){const h=c.length||1,b={id:this._documentIds.get(a),score:o*h,terms:Object.keys(p),queryTerms:c,match:p};Object.assign(b,this._storedFields.get(a)),(s.filter==null||s.filter(b))&&d.push(b)}return t===rn.wildcard&&s.boostDocument==null||d.sort(Cu),d}autoSuggest(t,n={}){n={...this._options.autoSuggestOptions,...n};const i=new Map;for(const{score:l,terms:d}of this.search(t,n)){const a=d.join(" "),o=i.get(a);o!=null?(o.score+=l,o.count+=1):i.set(a,{score:l,terms:d,count:1})}const s=[];for(const[l,{score:d,terms:a,count:o}]of i)s.push({suggestion:l,terms:a,score:d/o});return s.sort(Cu),s}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(t,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(t),n)}static async loadJSONAsync(t,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(t),n)}static getDefault(t){if(pi.hasOwnProperty(t))return ui(pi,t);throw new Error(`MiniSearch: unknown option "${t}"`)}static loadJS(t,n){const{index:i,documentIds:s,fieldLength:l,storedFields:d,serializationVersion:a}=t,o=this.instantiateMiniSearch(t,n);o._documentIds=er(s),o._fieldLength=er(l),o._storedFields=er(d);for(const[c,p]of o._documentIds)o._idToShortId.set(p,c);for(const[c,p]of i){const h=new Map;for(const b of Object.keys(p)){let y=p[b];a===1&&(y=y.ds),h.set(parseInt(b,10),er(y))}o._index.set(c,h)}return o}static async loadJSAsync(t,n){const{index:i,documentIds:s,fieldLength:l,storedFields:d,serializationVersion:a}=t,o=this.instantiateMiniSearch(t,n);o._documentIds=await tr(s),o._fieldLength=await tr(l),o._storedFields=await tr(d);for(const[p,h]of o._documentIds)o._idToShortId.set(h,p);let c=0;for(const[p,h]of i){const b=new Map;for(const y of Object.keys(h)){let k=h[y];a===1&&(k=k.ds),b.set(parseInt(y,10),await tr(k))}++c%1e3===0&&await Ph(0),o._index.set(p,b)}return o}static instantiateMiniSearch(t,n){const{documentCount:i,nextId:s,fieldIds:l,averageFieldLength:d,dirtCount:a,serializationVersion:o}=t;if(o!==1&&o!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");const c=new rn(n);return c._documentCount=i,c._nextId=s,c._idToShortId=new Map,c._fieldIds=l,c._avgFieldLength=d,c._dirtCount=a||0,c._index=new Tt,c}executeQuery(t,n={}){if(t===rn.wildcard)return this.executeWildcardQuery(n);if(typeof t!="string"){const b={...n,...t,queries:void 0},y=t.queries.map(k=>this.executeQuery(k,b));return this.combineResults(y,b.combineWith)}const{tokenize:i,processTerm:s,searchOptions:l}=this._options,d={tokenize:i,processTerm:s,...l,...n},{tokenize:a,processTerm:o}=d,h=a(t).flatMap(b=>o(b)).filter(b=>!!b).map(U_(d)).map(b=>this.executeQuerySpec(b,d));return this.combineResults(h,d.combineWith)}executeQuerySpec(t,n){const i={...this._options.searchOptions,...n},s=(i.fields||this._options.fields).reduce((v,g)=>({...v,[g]:ui(i.boost,g)||1}),{}),{boostDocument:l,weights:d,maxFuzzy:a,bm25:o}=i,{fuzzy:c,prefix:p}={...wu.weights,...d},h=this._index.get(t.term),b=this.termResults(t.term,t.term,1,t.termBoost,h,s,l,o);let y,k;if(t.prefix&&(y=this._index.atPrefix(t.term)),t.fuzzy){const v=t.fuzzy===!0?.2:t.fuzzy,g=v<1?Math.min(a,Math.round(t.term.length*v)):v;g&&(k=this._index.fuzzyGet(t.term,g))}if(y)for(const[v,g]of y){const m=v.length-t.term.length;if(!m)continue;k==null||k.delete(v);const u=p*v.length/(v.length+.3*m);this.termResults(t.term,v,u,t.termBoost,g,s,l,o,b)}if(k)for(const v of k.keys()){const[g,m]=k.get(v);if(!m)continue;const u=c*v.length/(v.length+m);this.termResults(t.term,v,u,t.termBoost,g,s,l,o,b)}return b}executeWildcardQuery(t){const n=new Map,i={...this._options.searchOptions,...t};for(const[s,l]of this._documentIds){const d=i.boostDocument?i.boostDocument(l,"",this._storedFields.get(s)):1;n.set(s,{score:d,terms:[],match:{}})}return n}combineResults(t,n=cd){if(t.length===0)return new Map;const i=n.toLowerCase(),s=P_[i];if(!s)throw new Error(`Invalid combination operator: ${n}`);return t.reduce(s)||new Map}toJSON(){const t=[];for(const[n,i]of this._index){const s={};for(const[l,d]of i)s[l]=Object.fromEntries(d);t.push([n,s])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:t,serializationVersion:2}}termResults(t,n,i,s,l,d,a,o,c=new Map){if(l==null)return c;for(const p of Object.keys(d)){const h=d[p],b=this._fieldIds[p],y=l.get(b);if(y==null)continue;let k=y.size;const v=this._avgFieldLength[b];for(const g of y.keys()){if(!this._documentIds.has(g)){this.removeTerm(b,g,n),k-=1;continue}const m=a?a(this._documentIds.get(g),n,this._storedFields.get(g)):1;if(!m)continue;const u=y.get(g),f=this._fieldLength.get(g)[b],x=B_(u,k,this._documentCount,f,v,o),E=i*s*h*m*x,_=c.get(g);if(_){_.score+=E,H_(_.terms,t);const S=ui(_.match,n);S?S.push(p):_.match[n]=[p]}else c.set(g,{score:E,terms:[t],match:{[n]:[p]}})}}return c}addTerm(t,n,i){const s=this._index.fetch(i,Tu);let l=s.get(t);if(l==null)l=new Map,l.set(n,1),s.set(t,l);else{const d=l.get(n);l.set(n,(d||0)+1)}}removeTerm(t,n,i){if(!this._index.has(i)){this.warnDocumentChanged(n,t,i);return}const s=this._index.fetch(i,Tu),l=s.get(t);l==null||l.get(n)==null?this.warnDocumentChanged(n,t,i):l.get(n)<=1?l.size<=1?s.delete(t):l.delete(n):l.set(n,l.get(n)-1),this._index.get(i).size===0&&this._index.delete(i)}warnDocumentChanged(t,n,i){for(const s of Object.keys(this._fieldIds))if(this._fieldIds[s]===n){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(t)} has changed before removal: term "${i}" was not present in field "${s}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(t){const n=this._nextId;return this._idToShortId.set(t,n),this._documentIds.set(n,t),this._documentCount+=1,this._nextId+=1,n}addFields(t){for(let n=0;n<t.length;n++)this._fieldIds[t[n]]=n}addFieldLength(t,n,i,s){let l=this._fieldLength.get(t);l==null&&this._fieldLength.set(t,l=[]),l[n]=s;const a=(this._avgFieldLength[n]||0)*i+s;this._avgFieldLength[n]=a/(i+1)}removeFieldLength(t,n,i,s){if(i===1){this._avgFieldLength[n]=0;return}const l=this._avgFieldLength[n]*i-s;this._avgFieldLength[n]=l/(i-1)}saveStoredFields(t,n){const{storeFields:i,extractField:s}=this._options;if(i==null||i.length===0)return;let l=this._storedFields.get(t);l==null&&this._storedFields.set(t,l={});for(const d of i){const a=s(n,d);a!==void 0&&(l[d]=a)}}}rn.wildcard=Symbol("*");const ui=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,P_={[cd]:(e,t)=>{for(const n of t.keys()){const i=e.get(n);if(i==null)e.set(n,t.get(n));else{const{score:s,terms:l,match:d}=t.get(n);i.score=i.score+s,i.match=Object.assign(i.match,d),Eu(i.terms,l)}}return e},[Mh]:(e,t)=>{const n=new Map;for(const i of t.keys()){const s=e.get(i);if(s==null)continue;const{score:l,terms:d,match:a}=t.get(i);Eu(s.terms,d),n.set(i,{score:s.score+l,terms:s.terms,match:Object.assign(s.match,a)})}return n},[M_]:(e,t)=>{for(const n of t.keys())e.delete(n);return e}},F_={k:1.2,b:.7,d:.5},B_=(e,t,n,i,s,l)=>{const{k:d,b:a,d:o}=l;return Math.log(1+(n-t+.5)/(t+.5))*(o+e*(d+1)/(e+d*(1-a+a*i/s)))},U_=e=>(t,n,i)=>{const s=typeof e.fuzzy=="function"?e.fuzzy(t,n,i):e.fuzzy||!1,l=typeof e.prefix=="function"?e.prefix(t,n,i):e.prefix===!0,d=typeof e.boostTerm=="function"?e.boostTerm(t,n,i):1;return{term:t,fuzzy:s,prefix:l,termBoost:d}},pi={idField:"id",extractField:(e,t)=>e[t],stringifyField:(e,t)=>e.toString(),tokenize:e=>e.split(G_),processTerm:e=>e.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(e,t)=>{typeof(console==null?void 0:console[e])=="function"&&console[e](t)},autoVacuum:!0},wu={combineWith:cd,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:F_},z_={combineWith:Mh,prefix:(e,t,n)=>t===n.length-1},Pi={batchSize:1e3,batchWait:10},Fi={minDirtFactor:.1,minDirtCount:20},hi={...Pi,...Fi},H_=(e,t)=>{e.includes(t)||e.push(t)},Eu=(e,t)=>{for(const n of t)e.includes(n)||e.push(n)},Cu=({score:e},{score:t})=>t-e,Tu=()=>new Map,er=e=>{const t=new Map;for(const n of Object.keys(e))t.set(parseInt(n,10),e[n]);return t},tr=async e=>{const t=new Map;let n=0;for(const i of Object.keys(e))t.set(parseInt(i,10),e[i]),++n%1e3===0&&await Ph(0);return t},Ph=e=>new Promise(t=>setTimeout(t,e)),G_=/[\n\r\p{Z}\p{P}]+/u;function W_(e){const t=/[\u4e00-\u9fff]|[a-zA-Z0-9]+/g;return(e.match(t)||[]).map(n=>n.toLowerCase())}const q_=Te((e,t)=>({sidebar:null,sidebarLoading:!1,sidebarLang:null,currentPath:null,currentContent:null,contentLoading:!1,contentError:null,searchQuery:"",searchResults:[],searchIndex:null,searchDocuments:[],searchLang:null,loadSidebar:async n=>{if(!(t().sidebarLang===n&&t().sidebar)){e({sidebarLoading:!0});try{const i=await fetch(`/docs/sidebar-${n}.json`);if(!i.ok)throw new Error(`HTTP ${i.status}`);const s=await i.json();e({sidebar:s,sidebarLoading:!1,sidebarLang:n})}catch{e({sidebar:null,sidebarLoading:!1,sidebarLang:null})}}},loadDocument:async(n,i)=>{e({contentLoading:!0,contentError:null,currentPath:n});try{const l=await fetch(`/docs/${i==="zh"?"cn":"en"}${n}.md`);if(!l.ok)throw new Error(`HTTP ${l.status}`);const d=await l.text();t().currentPath===n&&e({currentContent:d,contentLoading:!1})}catch{t().currentPath===n&&e({currentContent:null,contentLoading:!1,contentError:n})}},initSearchIndex:async n=>{if(!(t().searchLang===n&&t().searchIndex))try{const i=await fetch(`/docs/search-index-${n}.json`);if(!i.ok)return;const s=await i.json(),l=new rn({fields:["title","body"],storeFields:["title","body"],tokenize:W_,searchOptions:{prefix:!0,fuzzy:.2,boost:{title:2}}});l.addAll(s),e({searchIndex:l,searchDocuments:[],searchLang:n})}catch{}},search:n=>{const{searchIndex:i}=t();if(e({searchQuery:n}),!n.trim()||!i){e({searchResults:[]});return}const l=i.search(n,{prefix:!0,fuzzy:.2}).slice(0,20).map(d=>{const a=d,o=a.title||d.id,c=a.body||"",p=c.toLowerCase(),h=n.toLowerCase(),b=p.indexOf(h);let y;if(b>=0){const k=Math.max(0,b-40),v=Math.min(c.length,b+n.length+80);y=(k>0?"...":"")+c.slice(k,v)+(v<c.length?"...":"")}else y=c.slice(0,120)+(c.length>120?"...":"");return{id:d.id,title:o,score:d.score,excerpt:y}});e({searchResults:l})},setCurrentPath:n=>e({currentPath:n}),clearSearch:()=>e({searchQuery:"",searchResults:[]})})),V_=Gn;function K_(e){const t=e.split(`
|
|
658
|
+
`):a;return r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[r.jsx("span",{className:"text-[13px] font-semibold",style:{color:d},children:e.from}),e.summary&&r.jsxs("span",{className:"text-[12px] text-text-tertiary",children:["· ",e.summary]})]}),r.jsxs("div",{className:"ml-2 pl-3 border-l-2",style:{borderColor:`${d}33`},children:[r.jsx("div",{className:"prose prose-sm prose-invert max-w-none text-text-secondary text-[13px] [&_p]:my-1 [&_pre]:my-2 [&_code]:text-[12px] [&_h1]:text-[15px] [&_h2]:text-[14px] [&_h3]:text-[13px] [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5",children:r.jsx(on,{remarkPlugins:[ln],children:h})}),p&&r.jsx("button",{type:"button",onClick:()=>n(!t),className:"text-[11px] text-text-tertiary hover:text-text-secondary mt-1 transition-colors",children:t?i("team.showLess"):i("team.moreLines").replace("{count}",String(o.length-c))})]})]})}function v_(e){if(!e)return!0;const t=e.trimStart();return!!/^\/clear\b/.test(t)}function Nh(e){const t=[];for(let n=0;n<e.length;n++){const i=e[n];if(i.type==="message"){const s=i;if(s.isCompactInternal){const l=t[t.length-1];l&&l.kind==="compact_group"?l.entries.push(s):t.push({kind:"compact_group",entries:[s]})}else if(s.role==="user"&&s.channel)t.push({kind:"channel_incoming",entry:s});else if(s.role==="user"){if(v_(s.content))continue;t.push({kind:"user",entry:s})}else{if(!s.thinking){const l=e[n+1];if(l&&l.type==="tool_call"&&l.subagent)continue}t.push({kind:"assistant_message",entry:s})}}else{const s=t[t.length-1];s&&s.kind==="assistant_tools"?s.entries.push(i):t.push({kind:"assistant_tools",entries:[i]})}}return t}function vu(e){var t;switch(e.kind){case"user":case"assistant_message":case"channel_incoming":return e.entry.timestamp;case"compact_group":return(t=e.entries[0])==null?void 0:t.timestamp;case"assistant_tools":return}}function __(e,t=150){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function _u(){const{t:e}=ne(),n=Ke(l=>l.resolved)==="dark"?Op:$p,i=zt(l=>{var d;return(d=l.info)==null?void 0:d.cwd}),s=T.useMemo(()=>{if(!i)return"";const l=i.match(/^(\/Users\/[^/]+|\/home\/[^/]+)(\/.*)?$/);return l?"~"+(l[2]||""):i},[i]);return r.jsxs("div",{className:"empty-state",children:[r.jsx("div",{className:"empty-state-logo",children:r.jsx("img",{src:n,alt:"CodeBuddy"})}),s&&r.jsx("p",{className:"empty-state-cwd",title:i,children:s}),r.jsxs("p",{className:"empty-state-hint hidden md:block",children:[r.jsxs("kbd",{children:[/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl","+Shift+P"]}),r.jsx("span",{children:e("commandPalette.tip")})]})]})}function S_({onClickCloseBottomSheet:e}={}){const{timeline:t,isAgentRunning:n,stopReason:i,errorMessage:s,errorCategory:l,historyLoading:d,agentPhaseLabel:a,progressLabel:o,hasPendingInterruption:c}=et(),p=T.useRef(null),h=T.useRef(null),{t:b,resolved:y}=ne(),[k,v]=T.useState(null);T.useEffect(()=>{if(!k)return;const M=F=>{F.key==="Escape"&&v(null)};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[k]);const g=T.useRef(!0),m=T.useRef(0),u=T.useRef(!1),f=T.useMemo(()=>Nh(t),[t]),x=f.length===0,[E,_]=T.useState(!0),[S,w]=T.useState(!1),N=T.useRef(!1);T.useEffect(()=>{if(!x&&!N.current){w(!0);const M=setTimeout(()=>{_(!1),N.current=!0},600);return()=>clearTimeout(M)}},[x]);const D=T.useCallback(()=>{if(u.current)return;const M=h.current;M&&(g.current=__(M))},[]);T.useEffect(()=>{const M=t.length;if(M>m.current){const F=t[m.current];(F==null?void 0:F.type)==="message"&&F.role==="user"&&(g.current=!0)}m.current=M},[t]),T.useEffect(()=>{if(!g.current)return;const M=h.current;M&&(u.current=!0,M.scrollTop=M.scrollHeight,requestAnimationFrame(()=>{u.current=!1}))},[t,n]);const R=t[t.length-1],j=(R==null?void 0:R.type)==="message"&&R.streaming,O=j&&!!R.thinking&&!R.content,H=T.useRef(!1);return T.useEffect(()=>{if(c&&!H.current){const M=h.current;M&&(u.current=!0,M.scrollTop=M.scrollHeight,requestAnimationFrame(()=>{u.current=!1}))}H.current=c},[c]),r.jsxs("div",{ref:h,onScroll:D,onClick:()=>e==null?void 0:e(),className:"absolute inset-0 overflow-y-auto overflow-x-hidden",role:"log","aria-label":"Chat messages",children:[E&&r.jsx("div",{className:`empty-state-wrapper${S?" empty-state-fadeout":""}`,children:r.jsx(_u,{})}),!E&&d&&t.length===0&&r.jsx("div",{className:"flex items-center justify-center min-h-[60vh] h-full pb-20",children:r.jsx($b,{size:"large"})}),!E&&x&&!n&&!d&&r.jsx(_u,{}),!x&&r.jsx("div",{className:"px-4 sm:px-6 pt-6 pb-4 animate-fadeIn",children:r.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[r.jsx("div",{className:"text-center mb-8",children:r.jsx("span",{className:"text-[13px] text-text-tertiary",children:b("chat.disclaimer")})}),f.map((M,F)=>{var A,L,I,G;const V=vu(M);let q=!1,C="";if(V!==void 0){const B=Sr(V);let W=null;for(let z=F-1;z>=0;z--){const U=vu(f[z]);if(U!==void 0){W=Sr(U);break}}B!==W&&(q=!0,C=fh(V,y))}if(M.kind==="user"){const B=M.entry.content?Ch(M.entry.content):void 0;if(B)return B.from==="system"?null:r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Th,{msg:B})]},M.entry.id);const W=M.entry.content||"",z=b_(W);if(z==="")return null;const U=z??y_(W);return!U&&!((A=M.entry.images)!=null&&A.length)&&!((L=M.entry.files)!=null&&L.length)?null:r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx("div",{className:"flex justify-end mb-6",children:r.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] px-5 py-3 rounded-2xl rounded-tr-sm bg-bg-user border border-transparent",children:[M.entry.images&&M.entry.images.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:M.entry.images.map(($,Y)=>{const X="url"in $?$.url:`data:${$.mimeType};base64,${$.data}`;return r.jsx("img",{src:X,alt:"",className:"max-w-full h-auto rounded-lg cursor-pointer hover:opacity-80 transition-opacity",style:{maxHeight:360},onClick:()=>v(X)},Y)})}),M.entry.files&&M.entry.files.length>0&&r.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:M.entry.files.map(($,Y)=>r.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-bg-primary/50 border border-border-muted/30 max-w-[180px]",children:[r.jsx(ct,{size:14,className:"shrink-0 text-text-tertiary"}),r.jsx("span",{className:"text-[12px] text-text-primary truncate",title:$.name,children:$.name})]},Y))}),U&&r.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:U})]})})]},M.entry.id)}if(M.kind==="channel_incoming")return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Rx,{content:M.entry.content,channel:M.entry.channel})]},M.entry.id);if(M.kind==="assistant_message"){if(!M.entry.content&&!M.entry.thinking)return null;const B=F>0?f[F-1]:void 0,W=(B==null?void 0:B.kind)==="channel_incoming";return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),W&&B.kind==="channel_incoming"&&r.jsx(Lx,{channel:B.entry.channel}),r.jsx("div",{className:"mb-2 w-full",children:r.jsx("div",{className:"flex-1 min-w-0",children:r.jsx(ad,{message:M.entry})})})]},M.entry.id)}if(M.kind==="assistant_tools"){const B=((I=M.entries[0])==null?void 0:I.id)||`tools-${F}`;return r.jsx(Eh,{entries:M.entries},B)}if(M.kind==="compact_group"){const B=((G=M.entries[0])==null?void 0:G.id)||`compact-${F}`;return r.jsxs("div",{children:[q&&r.jsx(Zt,{label:C}),r.jsx(Fv,{entries:M.entries})]},B)}return null}),n&&t.length>0&&!j&&!O&&(()=>{const M=c&&a&&(a==="chat.waitingPermission"||a==="chat.waitingUser"),F=a==="phase.retrying";let V;if(o)V=b(o)||b("chat.thinking");else if(!a)V=b("chat.thinking");else if(a.startsWith("phase.toolExecutingName:")){const C=a.slice(24);V=`${b("phase.toolExecuting")} ${C}`}else if(a.startsWith("phase.modelStreamingName:")){const C=a.slice(25);V=y!=null&&y.startsWith("zh")?b("phase.modelStreamingTool"):`${b("phase.modelStreamingTool")} ${C}`}else V=b(a)||b("chat.thinking");const q=M||F;return r.jsx("div",{className:"mb-2",children:r.jsxs("span",{className:`inline-flex items-center gap-1.5 text-xs ${q?"text-accent-brand animate-pulse":"text-text-tertiary"}`,children:[r.jsx(ke,{size:12,className:"text-accent-brand animate-spin"}),r.jsx("span",{children:V})]})})})(),i&&!n&&r.jsx("div",{className:"py-2",children:r.jsx("span",{className:"text-xs text-text-tertiary",children:(()=>{if(i==="max_tokens")return b("chat.error.maxTokens");if(i==="max_turn_requests")return b("chat.error.maxTurnRequests");if(i==="refusal"){const M=(()=>{switch(l){case"network":return b("chat.error.network");case"auth":return b("chat.error.auth");case"quota":return b("chat.error.quota");case"model_service":return b("chat.error.modelService");default:return b("chat.error.refusal")}})();return s?`${b("chat.error")}: ${s}`:M}return s?`${b("chat.error")}: ${s}`:b("chat.stopped")})()})})]})}),r.jsx("div",{ref:p,className:"h-6"}),k&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 cursor-zoom-out",onClick:()=>v(null),children:r.jsx("img",{src:k,alt:"",className:"max-w-[90vw] max-h-[90vh] object-contain rounded-lg shadow-2xl",onClick:M=>M.stopPropagation()})})]})}function or(e,t){const n=e.toLowerCase(),i=t.toLowerCase();let s=0,l=0,d=-1;const a=[];for(let o=0;o<i.length&&s<n.length;o++)i[o]===n[s]&&(l+=o===d+1?2:1,(o===0||/[/.\-_ ]/.test(i[o-1]))&&(l+=3),o>0&&i[o]!==t[o]&&t[o]===t[o].toUpperCase()&&(l+=2),a.push(o),d=o,s++);return{match:s===n.length,score:l,positions:a}}function Su(e){const t=e.split("+"),n={key:"",ctrl:!1,alt:!1,shift:!1,meta:!1,super:!1};for(const i of t){const s=i.toLowerCase();switch(s){case"ctrl":case"control":n.ctrl=!0;break;case"alt":case"opt":case"option":n.alt=!0;break;case"shift":n.shift=!0;break;case"meta":n.meta=!0;break;case"cmd":case"command":case"super":case"win":n.super=!0;break;case"esc":n.key="escape";break;case"return":n.key="enter";break;case"space":n.key=" ";break;default:n.key=s;break}}return n}function k_(e){return e===" "?[Su("space")]:e.trim().split(/\s+/).map(Su)}function w_(e){switch(e){case"escape":return"Esc";case" ":return"Space";case"tab":return"Tab";case"enter":return"Enter";case"backspace":return"Backspace";case"delete":return"Delete";case"up":return"↑";case"down":return"↓";case"left":return"←";case"right":return"→";default:return e.length===1?e.toUpperCase():e}}const $i=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform||navigator.userAgent);function Ah(e){const t=[];return e.ctrl&&t.push("Ctrl"),(e.alt||e.meta)&&t.push($i?"Opt":"Alt"),e.shift&&t.push("Shift"),e.super&&t.push($i?"Cmd":"Super"),t.push(w_(e.key)),t.join("+")}function kr(e){return e.map(Ah).join(" ")}function ku(e){const t=[];for(const n of e)for(const[i,s]of Object.entries(n.bindings))t.push({chord:k_(i),action:s,context:n.context});return t}function E_(e){switch(e){case"Escape":return"escape";case"Enter":return"enter";case"Tab":return"tab";case"Backspace":return"backspace";case"Delete":return"delete";case"ArrowUp":return"up";case"ArrowDown":return"down";case"ArrowLeft":return"left";case"ArrowRight":return"right";case" ":return" ";default:return e.length===1,e.toLowerCase()}}function Ih(e){const t=E_(e.key);return!t||e.key==="Control"||e.key==="Shift"||e.key==="Alt"||e.key==="Meta"?null:{key:t,ctrl:e.ctrlKey,alt:e.altKey,shift:e.shiftKey,meta:e.metaKey,super:$i?e.metaKey:!1}}const C_=1e3,od=Te((e,t)=>({defaults:[],userBlocks:null,bindings:[],warnings:[],contexts:[],actions:[],reserved:[],filePath:"",loaded:!1,activeContexts:new Set(["Global"]),pendingChord:null,chordTimeoutId:null,loadBindings:async()=>{try{const n=await fetch(`${window.location.origin}/api/v1/keybindings`,{headers:ae()});if(!n.ok)return;const i=await n.json(),s=i.data??i,l=ku(s.defaults),d=s.user?ku(s.user):[],a=[...l,...d];e({defaults:s.defaults,userBlocks:s.user,bindings:a,warnings:s.warnings,contexts:s.contexts,actions:s.actions,reserved:s.reserved,filePath:s.filePath,loaded:!0})}catch(n){console.error("[KeybindingStore] Failed to load bindings:",n),e({loaded:!0})}},resolveKeyboardEvent:n=>{const i=t(),{bindings:s,activeContexts:l,pendingChord:d,chordTimeoutId:a}=i,o=Ih(n);if(!o)return d&&li(e,a),{type:"none"};if(n.key==="Escape"&&d)return li(e,a),{type:"none"};const c=d?[...d,o]:[o],p=l,h=s.filter(k=>p.has(k.context));let b=!1;for(const k of h)if(k.chord.length>c.length&&T_(c,k)&&k.action!==null){b=!0;break}if(b){a&&clearTimeout(a);const k=setTimeout(()=>{e({pendingChord:null,chordTimeoutId:null})},C_);return e({pendingChord:c,chordTimeoutId:k}),{type:"none"}}let y;for(const k of h)N_(c,k)&&(y=k);return li(e,a),y?y.action===null?{type:"unbound"}:{type:"match",action:y.action}:{type:"none"}},registerContext:n=>{e(i=>{const s=new Set(i.activeContexts);return s.add(n),{activeContexts:s}})},unregisterContext:n=>{e(i=>{const s=new Set(i.activeContexts);return s.delete(n),{activeContexts:s}})},saveUserBindings:async n=>{try{const i=await fetch(`${window.location.origin}/api/v1/keybindings`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify(n)});if(!i.ok)return console.error(`[KeybindingStore] Save failed: ${i.status}`),[];const s=await i.json(),l=s.data??s;return await t().loadBindings(),l.warnings??[]}catch(i){return console.error("[KeybindingStore] Failed to save bindings:",i),[]}},resetBindings:async()=>{try{const n=await fetch(`${window.location.origin}/api/v1/keybindings/reset`,{method:"POST",headers:ae()});if(!n.ok){console.error(`[KeybindingStore] Reset failed: ${n.status}`);return}await t().loadBindings()}catch(n){console.error("[KeybindingStore] Failed to reset bindings:",n)}},getDisplayText:(n,i)=>{const{bindings:s}=t();for(let l=s.length-1;l>=0;l--)if(s[l].action===n&&s[l].context===i)return kr(s[l].chord)}}));function li(e,t){t&&clearTimeout(t),e({pendingChord:null,chordTimeoutId:null})}function Rh(e,t){return e.key===t.key&&e.ctrl===t.ctrl&&e.shift===t.shift&&(e.alt||e.meta)===(t.alt||t.meta)&&e.super===t.super}function T_(e,t){if(e.length>=t.chord.length)return!1;for(let n=0;n<e.length;n++)if(!Rh(e[n],t.chord[n]))return!1;return!0}function N_(e,t){if(e.length!==t.chord.length)return!1;for(let n=0;n<e.length;n++)if(!Rh(e[n],t.chord[n]))return!1;return!0}class A_{constructor(){fe(this,"bindings",[]);fe(this,"actionHandlers",new Map);fe(this,"_suspended",!1)}register(t){return this.bindings.push(t),()=>{this.bindings=this.bindings.filter(n=>n!==t)}}registerAction(t,n,i){const s={id:t,handler:n,when:i};return this.actionHandlers.set(t,s),()=>{this.actionHandlers.get(t)===s&&this.actionHandlers.delete(t)}}suspend(){this._suspended=!0}resume(){this._suspended=!1}handleKeyDown(t){var d;const n=(d=t.target)==null?void 0:d.tagName,i=n==="INPUT"||n==="TEXTAREA",s=od.getState();if(s.loaded&&s.bindings.length>0){const a=s.resolveKeyboardEvent(t);if(a.type==="match"){const o=this.actionHandlers.get(a.action),c=a.action==="app:commandPalette";if(this._suspended&&!c||i&&!c)return;if(o){if(o.when&&!o.when())return;t.preventDefault(),t.stopPropagation(),o.handler(t);return}}if(a.type==="unbound")return}const l=t.metaKey||t.ctrlKey;for(const a of this.bindings)if(a.meta===l&&(a.shift??!1)===t.shiftKey&&a.key===t.key.toLowerCase()&&!(this._suspended&&a.id!=="commandPalette.toggle")&&!(i&&a.id!=="commandPalette.toggle")&&!(a.when&&!a.when())){t.preventDefault(),t.stopPropagation(),a.handler(t);return}}}const Ge=new A_,I_=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),ji=I_?"⌘":"Ctrl",R_=[{view:"chat",icon:r.jsx(dn,{size:16}),labelKey:"sidebar.chatMode"},{view:"workers",icon:r.jsx(Gt,{size:16}),labelKey:"sidebar.workers"},{view:"remote-control",icon:r.jsx(hr,{size:16}),labelKey:"sidebar.remoteControl"},{view:"tasks",icon:r.jsx(Xi,{size:16}),labelKey:"sidebar.nav.tasks"},{view:"terminal",icon:r.jsx(un,{size:16}),labelKey:"sidebar.terminalMode",shortcut:`${ji}+J`},{view:"canvas",icon:r.jsx(mp,{size:16}),labelKey:"sidebar.canvas"},{view:"editor",icon:r.jsx(op,{size:16}),labelKey:"sidebar.editor"},{view:"changes",icon:r.jsx(Tr,{size:16}),labelKey:"sidebar.changes"},{view:"plugins",icon:r.jsx(Ft,{size:16}),labelKey:"sidebar.nav.plugins"},{view:"stats",icon:r.jsx(Vi,{size:16}),labelKey:"sidebar.stats"},{view:"traces",icon:r.jsx(Cp,{size:16}),labelKey:"sidebar.traces"},{view:"metrics",icon:r.jsx(Wi,{size:16}),labelKey:"sidebar.metrics"},{view:"logs",icon:r.jsx(Ki,{size:16}),labelKey:"sidebar.logs"},{view:"settings",icon:r.jsx(Qi,{size:16}),labelKey:"sidebar.preferences",shortcut:`${ji}+,`},{view:"keybindings",icon:r.jsx(hp,{size:16}),labelKey:"sidebar.keybindings"},{view:"docs",icon:r.jsx(qi,{size:16}),labelKey:"sidebar.docs"}];function L_({text:e,positions:t}){if(t.length===0)return r.jsx(r.Fragment,{children:e});const n=new Set(t);return r.jsx(r.Fragment,{children:e.split("").map((i,s)=>n.has(s)?r.jsx("span",{className:"font-bold text-accent-brand",children:i},s):r.jsx("span",{children:i},s))})}const Qn=12;function D_({isOpen:e,onClose:t,onNavigate:n,onNewChat:i}){const{t:s,tryT:l,resolved:d}=ne(),a=tt(S=>S.commands),o=tt(S=>S.sessionId),c=Ke(S=>S.toggle),p=Ke(S=>S.resolved),[h,b]=T.useState(""),[y,k]=T.useState(0),v=T.useRef(null),g=T.useRef(null);T.useEffect(()=>{e?(Ge.suspend(),b(""),k(0),setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},50)):Ge.resume()},[e]);const m=T.useMemo(()=>{const S=[];for(const w of R_)S.push({id:`view:${w.view}`,label:s(w.labelKey),category:"view",icon:r.jsx("span",{className:"text-text-tertiary",children:w.icon}),shortcut:w.shortcut,action:()=>n(w.view)});S.push({id:"action:newChat",label:s("commandPalette.newChat"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx(dn,{size:16})}),shortcut:`${ji}+N`,action:i}),S.push({id:"action:toggleTheme",label:s("commandPalette.toggleTheme"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:p==="dark"?r.jsx(kp,{size:16}):r.jsx(yp,{size:16})}),action:c}),S.push({id:"action:toggleLocale",label:s("commandPalette.toggleLocale"),category:"action",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx($f,{size:16})}),action:()=>fr.getState().toggle()});for(const w of a){const N=l(`command.${w.name}.description`)||w.description;S.push({id:`cmd:${w.name}`,label:`/${w.name}`,description:N,category:"command",icon:r.jsx("span",{className:"text-text-tertiary",children:r.jsx(un,{size:16})}),action:()=>{o&&Ie().prompt(o,`/${w.name}`).catch(()=>{})}})}return S},[a,o,n,i,c,p,s,d]),u=T.useMemo(()=>{const S=h.trim();if(S.startsWith(">")){const w=S.slice(1).trim(),N=m.filter(D=>D.category==="command");return w?N.map(D=>({item:D,result:or(w,D.label)})).filter(D=>D.result.match).sort((D,R)=>R.result.score-D.result.score).slice(0,Qn).map(D=>({...D.item,_positions:D.result.positions})):N.slice(0,Qn)}if(!S){const w=m.filter(R=>R.category==="action"),N=m.filter(R=>R.category==="view").slice(0,6),D=m.filter(R=>R.category==="command").slice(0,4);return[...w,...N,...D].slice(0,Qn)}return m.map(w=>({item:w,result:or(S,w.label+" "+(w.description||""))})).filter(w=>w.result.match).sort((w,N)=>N.result.score-w.result.score).slice(0,Qn).map(w=>({...w.item,_positions:or(S,w.item.label).positions}))},[h,m]);T.useEffect(()=>{k(0)},[u.length]);const f=T.useCallback(S=>{t(),setTimeout(()=>S.action(),50)},[t]),x=T.useCallback(S=>{switch(S.key){case"ArrowDown":S.preventDefault(),k(w=>(w+1)%Math.max(u.length,1));break;case"ArrowUp":S.preventDefault(),k(w=>(w-1+u.length)%Math.max(u.length,1));break;case"Enter":S.preventDefault(),u[y]&&f(u[y]);break;case"Escape":S.preventDefault(),t();break}},[u,y,f,t]);if(T.useEffect(()=>{const S=g.current;if(!S)return;const w=S.children[y];w&&w.scrollIntoView({block:"nearest"})},[y]),!e)return null;const E=S=>{switch(S){case"command":return s("commandPalette.commands");case"view":return s("commandPalette.views");case"action":return s("commandPalette.actions");default:return""}};let _="";return r.jsxs("div",{className:"fixed inset-0 z-[200] flex items-start justify-center pt-[12vh] max-md:items-end max-md:pt-0",onClick:t,children:[r.jsx("div",{className:"absolute inset-0 bg-black/30"}),r.jsxs("div",{className:"relative w-full max-w-[640px] mx-4 bg-bg-card border border-border-default rounded-xl shadow-2xl overflow-hidden max-md:rounded-b-none max-md:rounded-t-xl max-md:max-w-none max-md:mx-0",onClick:S=>S.stopPropagation(),onKeyDown:x,children:[r.jsxs("div",{className:"flex items-center px-5 py-3.5 border-b border-border-muted",children:[r.jsx(st,{size:18,className:"text-text-tertiary shrink-0 mr-3"}),r.jsx("input",{ref:v,type:"text",className:"flex-1 bg-transparent text-text-primary text-[15px] outline-none placeholder:text-text-tertiary",placeholder:s("commandPalette.placeholder"),value:h,onChange:S=>b(S.target.value),"aria-label":s("commandPalette.placeholder"),autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1})]}),r.jsx("div",{ref:g,className:"max-h-[400px] overflow-y-auto py-1.5",role:"listbox",children:u.length===0?r.jsx("div",{className:"px-5 py-6 text-center text-text-tertiary text-[13px]",children:s("commandPalette.noResults")}):u.map((S,w)=>{const N=S.category!==_;_=S.category;const D=S._positions;return r.jsxs("div",{children:[N&&r.jsx("div",{className:"px-5 pt-2.5 pb-1 text-[11px] font-medium text-text-tertiary uppercase tracking-wide",children:E(S.category)}),r.jsxs("div",{role:"option","aria-selected":w===y,className:["flex items-center gap-3 px-5 py-2 mx-1.5 rounded-lg cursor-pointer transition-colors",w===y?"bg-bg-hover text-text-primary":"text-text-secondary hover:bg-bg-hover"].join(" "),onClick:()=>f(S),onMouseEnter:()=>k(w),children:[r.jsx("span",{className:"shrink-0 w-5 flex items-center justify-center",children:S.icon}),r.jsxs("span",{className:"flex-1 text-[13px] truncate",children:[D?r.jsx(L_,{text:S.label,positions:D}):S.label,S.description&&r.jsx("span",{className:"ml-2 text-text-tertiary text-[12px]",children:S.description})]}),S.shortcut&&r.jsx("kbd",{className:"shrink-0 text-[11px] text-text-tertiary font-mono bg-bg-tertiary px-1.5 py-0.5 rounded",children:S.shortcut})]})]},S.id)})}),r.jsxs("div",{className:"flex items-center gap-4 px-5 py-2.5 border-t border-border-muted text-[11px] text-text-tertiary",children:[r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"↑↓"})," navigate"]}),r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"↵"})," execute"]}),r.jsxs("span",{children:[r.jsx("kbd",{className:"font-mono",children:"esc"})," close"]})]})]})]})}const O_="ENTRIES",Lh="KEYS",Dh="VALUES",De="";class ci{constructor(t,n){const i=t._tree,s=Array.from(i.keys());this.set=t,this._type=n,this._path=s.length>0?[{node:i,keys:s}]:[]}next(){const t=this.dive();return this.backtrack(),t}dive(){if(this._path.length===0)return{done:!0,value:void 0};const{node:t,keys:n}=Kt(this._path);if(Kt(n)===De)return{done:!1,value:this.result()};const i=t.get(Kt(n));return this._path.push({node:i,keys:Array.from(i.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;const t=Kt(this._path).keys;t.pop(),!(t.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:t})=>Kt(t)).filter(t=>t!==De).join("")}value(){return Kt(this._path).node.get(De)}result(){switch(this._type){case Dh:return this.value();case Lh:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}}const Kt=e=>e[e.length-1],$_=(e,t,n)=>{const i=new Map;if(t===void 0)return i;const s=t.length+1,l=s+n,d=new Uint8Array(l*s).fill(n+1);for(let a=0;a<s;++a)d[a]=a;for(let a=1;a<l;++a)d[a*s]=a;return Oh(e,t,n,i,d,1,s,""),i},Oh=(e,t,n,i,s,l,d,a)=>{const o=l*d;e:for(const c of e.keys())if(c===De){const p=s[o-1];p<=n&&i.set(a,[e.get(c),p])}else{let p=l;for(let h=0;h<c.length;++h,++p){const b=c[h],y=d*p,k=y-d;let v=s[y];const g=Math.max(0,p-n-1),m=Math.min(d-1,p+n);for(let u=g;u<m;++u){const f=b!==t[u],x=s[k+u]+ +f,E=s[k+u+1]+1,_=s[y+u]+1,S=s[y+u+1]=Math.min(x,E,_);S<v&&(v=S)}if(v>n)continue e}Oh(e.get(c),t,n,i,s,p,d,a+c)}};class Tt{constructor(t=new Map,n=""){this._size=void 0,this._tree=t,this._prefix=n}atPrefix(t){if(!t.startsWith(this._prefix))throw new Error("Mismatched prefix");const[n,i]=wr(this._tree,t.slice(this._prefix.length));if(n===void 0){const[s,l]=ld(i);for(const d of s.keys())if(d!==De&&d.startsWith(l)){const a=new Map;return a.set(d.slice(l.length),s.get(d)),new Tt(a,t)}}return new Tt(n,t)}clear(){this._size=void 0,this._tree.clear()}delete(t){return this._size=void 0,j_(this._tree,t)}entries(){return new ci(this,O_)}forEach(t){for(const[n,i]of this)t(n,i,this)}fuzzyGet(t,n){return $_(this._tree,t,n)}get(t){const n=Mi(this._tree,t);return n!==void 0?n.get(De):void 0}has(t){const n=Mi(this._tree,t);return n!==void 0&&n.has(De)}keys(){return new ci(this,Lh)}set(t,n){if(typeof t!="string")throw new Error("key must be a string");return this._size=void 0,di(this._tree,t).set(De,n),this}get size(){if(this._size)return this._size;this._size=0;const t=this.entries();for(;!t.next().done;)this._size+=1;return this._size}update(t,n){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;const i=di(this._tree,t);return i.set(De,n(i.get(De))),this}fetch(t,n){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;const i=di(this._tree,t);let s=i.get(De);return s===void 0&&i.set(De,s=n()),s}values(){return new ci(this,Dh)}[Symbol.iterator](){return this.entries()}static from(t){const n=new Tt;for(const[i,s]of t)n.set(i,s);return n}static fromObject(t){return Tt.from(Object.entries(t))}}const wr=(e,t,n=[])=>{if(t.length===0||e==null)return[e,n];for(const i of e.keys())if(i!==De&&t.startsWith(i))return n.push([e,i]),wr(e.get(i),t.slice(i.length),n);return n.push([e,t]),wr(void 0,"",n)},Mi=(e,t)=>{if(t.length===0||e==null)return e;for(const n of e.keys())if(n!==De&&t.startsWith(n))return Mi(e.get(n),t.slice(n.length))},di=(e,t)=>{const n=t.length;e:for(let i=0;e&&i<n;){for(const l of e.keys())if(l!==De&&t[i]===l[0]){const d=Math.min(n-i,l.length);let a=1;for(;a<d&&t[i+a]===l[a];)++a;const o=e.get(l);if(a===l.length)e=o;else{const c=new Map;c.set(l.slice(a),o),e.set(t.slice(i,i+a),c),e.delete(l),e=c}i+=a;continue e}const s=new Map;return e.set(t.slice(i),s),s}return e},j_=(e,t)=>{const[n,i]=wr(e,t);if(n!==void 0){if(n.delete(De),n.size===0)$h(i);else if(n.size===1){const[s,l]=n.entries().next().value;jh(i,s,l)}}},$h=e=>{if(e.length===0)return;const[t,n]=ld(e);if(t.delete(n),t.size===0)$h(e.slice(0,-1));else if(t.size===1){const[i,s]=t.entries().next().value;i!==De&&jh(e.slice(0,-1),i,s)}},jh=(e,t,n)=>{if(e.length===0)return;const[i,s]=ld(e);i.set(s+t,n),i.delete(s)},ld=e=>e[e.length-1],cd="or",Mh="and",M_="and_not";class rn{constructor(t){if((t==null?void 0:t.fields)==null)throw new Error('MiniSearch: option "fields" must be provided');const n=t.autoVacuum==null||t.autoVacuum===!0?hi:t.autoVacuum;this._options={...pi,...t,autoVacuum:n,searchOptions:{...wu,...t.searchOptions||{}},autoSuggestOptions:{...z_,...t.autoSuggestOptions||{}}},this._index=new Tt,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Fi,this.addFields(this._options.fields)}add(t){const{extractField:n,stringifyField:i,tokenize:s,processTerm:l,fields:d,idField:a}=this._options,o=n(t,a);if(o==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(o))throw new Error(`MiniSearch: duplicate ID ${o}`);const c=this.addDocumentId(o);this.saveStoredFields(c,t);for(const p of d){const h=n(t,p);if(h==null)continue;const b=s(i(h,p),p),y=this._fieldIds[p],k=new Set(b).size;this.addFieldLength(c,y,this._documentCount-1,k);for(const v of b){const g=l(v,p);if(Array.isArray(g))for(const m of g)this.addTerm(y,c,m);else g&&this.addTerm(y,c,g)}}}addAll(t){for(const n of t)this.add(n)}addAllAsync(t,n={}){const{chunkSize:i=10}=n,s={chunk:[],promise:Promise.resolve()},{chunk:l,promise:d}=t.reduce(({chunk:a,promise:o},c,p)=>(a.push(c),(p+1)%i===0?{chunk:[],promise:o.then(()=>new Promise(h=>setTimeout(h,0))).then(()=>this.addAll(a))}:{chunk:a,promise:o}),s);return d.then(()=>this.addAll(l))}remove(t){const{tokenize:n,processTerm:i,extractField:s,stringifyField:l,fields:d,idField:a}=this._options,o=s(t,a);if(o==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);const c=this._idToShortId.get(o);if(c==null)throw new Error(`MiniSearch: cannot remove document with ID ${o}: it is not in the index`);for(const p of d){const h=s(t,p);if(h==null)continue;const b=n(l(h,p),p),y=this._fieldIds[p],k=new Set(b).size;this.removeFieldLength(c,y,this._documentCount,k);for(const v of b){const g=i(v,p);if(Array.isArray(g))for(const m of g)this.removeTerm(y,c,m);else g&&this.removeTerm(y,c,g)}}this._storedFields.delete(c),this._documentIds.delete(c),this._idToShortId.delete(o),this._fieldLength.delete(c),this._documentCount-=1}removeAll(t){if(t)for(const n of t)this.remove(n);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Tt,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(t){const n=this._idToShortId.get(t);if(n==null)throw new Error(`MiniSearch: cannot discard document with ID ${t}: it is not in the index`);this._idToShortId.delete(t),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach((i,s)=>{this.removeFieldLength(n,s,this._documentCount,i)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;const{minDirtFactor:t,minDirtCount:n,batchSize:i,batchWait:s}=this._options.autoVacuum;this.conditionalVacuum({batchSize:i,batchWait:s},{minDirtCount:n,minDirtFactor:t})}discardAll(t){const n=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(const i of t)this.discard(i)}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()}replace(t){const{idField:n,extractField:i}=this._options,s=i(t,n);this.discard(s),this.add(t)}vacuum(t={}){return this.conditionalVacuum(t)}conditionalVacuum(t,n){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&n,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{const i=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Fi,this.performVacuuming(t,i)}),this._enqueuedVacuum)):this.vacuumConditionsMet(n)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(t),this._currentVacuum)}async performVacuuming(t,n){const i=this._dirtCount;if(this.vacuumConditionsMet(n)){const s=t.batchSize||Pi.batchSize,l=t.batchWait||Pi.batchWait;let d=1;for(const[a,o]of this._index){for(const[c,p]of o)for(const[h]of p)this._documentIds.has(h)||(p.size<=1?o.delete(c):p.delete(h));this._index.get(a).size===0&&this._index.delete(a),d%s===0&&await new Promise(c=>setTimeout(c,l)),d+=1}this._dirtCount-=i}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(t){if(t==null)return!0;let{minDirtCount:n,minDirtFactor:i}=t;return n=n||hi.minDirtCount,i=i||hi.minDirtFactor,this.dirtCount>=n&&this.dirtFactor>=i}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(t){return this._idToShortId.has(t)}getStoredFields(t){const n=this._idToShortId.get(t);if(n!=null)return this._storedFields.get(n)}search(t,n={}){const{searchOptions:i}=this._options,s={...i,...n},l=this.executeQuery(t,n),d=[];for(const[a,{score:o,terms:c,match:p}]of l){const h=c.length||1,b={id:this._documentIds.get(a),score:o*h,terms:Object.keys(p),queryTerms:c,match:p};Object.assign(b,this._storedFields.get(a)),(s.filter==null||s.filter(b))&&d.push(b)}return t===rn.wildcard&&s.boostDocument==null||d.sort(Cu),d}autoSuggest(t,n={}){n={...this._options.autoSuggestOptions,...n};const i=new Map;for(const{score:l,terms:d}of this.search(t,n)){const a=d.join(" "),o=i.get(a);o!=null?(o.score+=l,o.count+=1):i.set(a,{score:l,terms:d,count:1})}const s=[];for(const[l,{score:d,terms:a,count:o}]of i)s.push({suggestion:l,terms:a,score:d/o});return s.sort(Cu),s}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(t,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(t),n)}static async loadJSONAsync(t,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(t),n)}static getDefault(t){if(pi.hasOwnProperty(t))return ui(pi,t);throw new Error(`MiniSearch: unknown option "${t}"`)}static loadJS(t,n){const{index:i,documentIds:s,fieldLength:l,storedFields:d,serializationVersion:a}=t,o=this.instantiateMiniSearch(t,n);o._documentIds=er(s),o._fieldLength=er(l),o._storedFields=er(d);for(const[c,p]of o._documentIds)o._idToShortId.set(p,c);for(const[c,p]of i){const h=new Map;for(const b of Object.keys(p)){let y=p[b];a===1&&(y=y.ds),h.set(parseInt(b,10),er(y))}o._index.set(c,h)}return o}static async loadJSAsync(t,n){const{index:i,documentIds:s,fieldLength:l,storedFields:d,serializationVersion:a}=t,o=this.instantiateMiniSearch(t,n);o._documentIds=await tr(s),o._fieldLength=await tr(l),o._storedFields=await tr(d);for(const[p,h]of o._documentIds)o._idToShortId.set(h,p);let c=0;for(const[p,h]of i){const b=new Map;for(const y of Object.keys(h)){let k=h[y];a===1&&(k=k.ds),b.set(parseInt(y,10),await tr(k))}++c%1e3===0&&await Ph(0),o._index.set(p,b)}return o}static instantiateMiniSearch(t,n){const{documentCount:i,nextId:s,fieldIds:l,averageFieldLength:d,dirtCount:a,serializationVersion:o}=t;if(o!==1&&o!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");const c=new rn(n);return c._documentCount=i,c._nextId=s,c._idToShortId=new Map,c._fieldIds=l,c._avgFieldLength=d,c._dirtCount=a||0,c._index=new Tt,c}executeQuery(t,n={}){if(t===rn.wildcard)return this.executeWildcardQuery(n);if(typeof t!="string"){const b={...n,...t,queries:void 0},y=t.queries.map(k=>this.executeQuery(k,b));return this.combineResults(y,b.combineWith)}const{tokenize:i,processTerm:s,searchOptions:l}=this._options,d={tokenize:i,processTerm:s,...l,...n},{tokenize:a,processTerm:o}=d,h=a(t).flatMap(b=>o(b)).filter(b=>!!b).map(U_(d)).map(b=>this.executeQuerySpec(b,d));return this.combineResults(h,d.combineWith)}executeQuerySpec(t,n){const i={...this._options.searchOptions,...n},s=(i.fields||this._options.fields).reduce((v,g)=>({...v,[g]:ui(i.boost,g)||1}),{}),{boostDocument:l,weights:d,maxFuzzy:a,bm25:o}=i,{fuzzy:c,prefix:p}={...wu.weights,...d},h=this._index.get(t.term),b=this.termResults(t.term,t.term,1,t.termBoost,h,s,l,o);let y,k;if(t.prefix&&(y=this._index.atPrefix(t.term)),t.fuzzy){const v=t.fuzzy===!0?.2:t.fuzzy,g=v<1?Math.min(a,Math.round(t.term.length*v)):v;g&&(k=this._index.fuzzyGet(t.term,g))}if(y)for(const[v,g]of y){const m=v.length-t.term.length;if(!m)continue;k==null||k.delete(v);const u=p*v.length/(v.length+.3*m);this.termResults(t.term,v,u,t.termBoost,g,s,l,o,b)}if(k)for(const v of k.keys()){const[g,m]=k.get(v);if(!m)continue;const u=c*v.length/(v.length+m);this.termResults(t.term,v,u,t.termBoost,g,s,l,o,b)}return b}executeWildcardQuery(t){const n=new Map,i={...this._options.searchOptions,...t};for(const[s,l]of this._documentIds){const d=i.boostDocument?i.boostDocument(l,"",this._storedFields.get(s)):1;n.set(s,{score:d,terms:[],match:{}})}return n}combineResults(t,n=cd){if(t.length===0)return new Map;const i=n.toLowerCase(),s=P_[i];if(!s)throw new Error(`Invalid combination operator: ${n}`);return t.reduce(s)||new Map}toJSON(){const t=[];for(const[n,i]of this._index){const s={};for(const[l,d]of i)s[l]=Object.fromEntries(d);t.push([n,s])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:t,serializationVersion:2}}termResults(t,n,i,s,l,d,a,o,c=new Map){if(l==null)return c;for(const p of Object.keys(d)){const h=d[p],b=this._fieldIds[p],y=l.get(b);if(y==null)continue;let k=y.size;const v=this._avgFieldLength[b];for(const g of y.keys()){if(!this._documentIds.has(g)){this.removeTerm(b,g,n),k-=1;continue}const m=a?a(this._documentIds.get(g),n,this._storedFields.get(g)):1;if(!m)continue;const u=y.get(g),f=this._fieldLength.get(g)[b],x=B_(u,k,this._documentCount,f,v,o),E=i*s*h*m*x,_=c.get(g);if(_){_.score+=E,H_(_.terms,t);const S=ui(_.match,n);S?S.push(p):_.match[n]=[p]}else c.set(g,{score:E,terms:[t],match:{[n]:[p]}})}}return c}addTerm(t,n,i){const s=this._index.fetch(i,Tu);let l=s.get(t);if(l==null)l=new Map,l.set(n,1),s.set(t,l);else{const d=l.get(n);l.set(n,(d||0)+1)}}removeTerm(t,n,i){if(!this._index.has(i)){this.warnDocumentChanged(n,t,i);return}const s=this._index.fetch(i,Tu),l=s.get(t);l==null||l.get(n)==null?this.warnDocumentChanged(n,t,i):l.get(n)<=1?l.size<=1?s.delete(t):l.delete(n):l.set(n,l.get(n)-1),this._index.get(i).size===0&&this._index.delete(i)}warnDocumentChanged(t,n,i){for(const s of Object.keys(this._fieldIds))if(this._fieldIds[s]===n){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(t)} has changed before removal: term "${i}" was not present in field "${s}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(t){const n=this._nextId;return this._idToShortId.set(t,n),this._documentIds.set(n,t),this._documentCount+=1,this._nextId+=1,n}addFields(t){for(let n=0;n<t.length;n++)this._fieldIds[t[n]]=n}addFieldLength(t,n,i,s){let l=this._fieldLength.get(t);l==null&&this._fieldLength.set(t,l=[]),l[n]=s;const a=(this._avgFieldLength[n]||0)*i+s;this._avgFieldLength[n]=a/(i+1)}removeFieldLength(t,n,i,s){if(i===1){this._avgFieldLength[n]=0;return}const l=this._avgFieldLength[n]*i-s;this._avgFieldLength[n]=l/(i-1)}saveStoredFields(t,n){const{storeFields:i,extractField:s}=this._options;if(i==null||i.length===0)return;let l=this._storedFields.get(t);l==null&&this._storedFields.set(t,l={});for(const d of i){const a=s(n,d);a!==void 0&&(l[d]=a)}}}rn.wildcard=Symbol("*");const ui=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,P_={[cd]:(e,t)=>{for(const n of t.keys()){const i=e.get(n);if(i==null)e.set(n,t.get(n));else{const{score:s,terms:l,match:d}=t.get(n);i.score=i.score+s,i.match=Object.assign(i.match,d),Eu(i.terms,l)}}return e},[Mh]:(e,t)=>{const n=new Map;for(const i of t.keys()){const s=e.get(i);if(s==null)continue;const{score:l,terms:d,match:a}=t.get(i);Eu(s.terms,d),n.set(i,{score:s.score+l,terms:s.terms,match:Object.assign(s.match,a)})}return n},[M_]:(e,t)=>{for(const n of t.keys())e.delete(n);return e}},F_={k:1.2,b:.7,d:.5},B_=(e,t,n,i,s,l)=>{const{k:d,b:a,d:o}=l;return Math.log(1+(n-t+.5)/(t+.5))*(o+e*(d+1)/(e+d*(1-a+a*i/s)))},U_=e=>(t,n,i)=>{const s=typeof e.fuzzy=="function"?e.fuzzy(t,n,i):e.fuzzy||!1,l=typeof e.prefix=="function"?e.prefix(t,n,i):e.prefix===!0,d=typeof e.boostTerm=="function"?e.boostTerm(t,n,i):1;return{term:t,fuzzy:s,prefix:l,termBoost:d}},pi={idField:"id",extractField:(e,t)=>e[t],stringifyField:(e,t)=>e.toString(),tokenize:e=>e.split(G_),processTerm:e=>e.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(e,t)=>{typeof(console==null?void 0:console[e])=="function"&&console[e](t)},autoVacuum:!0},wu={combineWith:cd,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:F_},z_={combineWith:Mh,prefix:(e,t,n)=>t===n.length-1},Pi={batchSize:1e3,batchWait:10},Fi={minDirtFactor:.1,minDirtCount:20},hi={...Pi,...Fi},H_=(e,t)=>{e.includes(t)||e.push(t)},Eu=(e,t)=>{for(const n of t)e.includes(n)||e.push(n)},Cu=({score:e},{score:t})=>t-e,Tu=()=>new Map,er=e=>{const t=new Map;for(const n of Object.keys(e))t.set(parseInt(n,10),e[n]);return t},tr=async e=>{const t=new Map;let n=0;for(const i of Object.keys(e))t.set(parseInt(i,10),e[i]),++n%1e3===0&&await Ph(0);return t},Ph=e=>new Promise(t=>setTimeout(t,e)),G_=/[\n\r\p{Z}\p{P}]+/u;function W_(e){const t=/[\u4e00-\u9fff]|[a-zA-Z0-9]+/g;return(e.match(t)||[]).map(n=>n.toLowerCase())}const q_=Te((e,t)=>({sidebar:null,sidebarLoading:!1,sidebarLang:null,currentPath:null,currentContent:null,contentLoading:!1,contentError:null,searchQuery:"",searchResults:[],searchIndex:null,searchDocuments:[],searchLang:null,loadSidebar:async n=>{if(!(t().sidebarLang===n&&t().sidebar)){e({sidebarLoading:!0});try{const i=await fetch(`/docs/sidebar-${n}.json`);if(!i.ok)throw new Error(`HTTP ${i.status}`);const s=await i.json();e({sidebar:s,sidebarLoading:!1,sidebarLang:n})}catch{e({sidebar:null,sidebarLoading:!1,sidebarLang:null})}}},loadDocument:async(n,i)=>{e({contentLoading:!0,contentError:null,currentPath:n});try{const l=await fetch(`/docs/${i==="zh"?"cn":"en"}${n}.md`);if(!l.ok)throw new Error(`HTTP ${l.status}`);const d=await l.text();t().currentPath===n&&e({currentContent:d,contentLoading:!1})}catch{t().currentPath===n&&e({currentContent:null,contentLoading:!1,contentError:n})}},initSearchIndex:async n=>{if(!(t().searchLang===n&&t().searchIndex))try{const i=await fetch(`/docs/search-index-${n}.json`);if(!i.ok)return;const s=await i.json(),l=new rn({fields:["title","body"],storeFields:["title","body"],tokenize:W_,searchOptions:{prefix:!0,fuzzy:.2,boost:{title:2}}});l.addAll(s),e({searchIndex:l,searchDocuments:[],searchLang:n})}catch{}},search:n=>{const{searchIndex:i}=t();if(e({searchQuery:n}),!n.trim()||!i){e({searchResults:[]});return}const l=i.search(n,{prefix:!0,fuzzy:.2}).slice(0,20).map(d=>{const a=d,o=a.title||d.id,c=a.body||"",p=c.toLowerCase(),h=n.toLowerCase(),b=p.indexOf(h);let y;if(b>=0){const k=Math.max(0,b-40),v=Math.min(c.length,b+n.length+80);y=(k>0?"...":"")+c.slice(k,v)+(v<c.length?"...":"")}else y=c.slice(0,120)+(c.length>120?"...":"");return{id:d.id,title:o,score:d.score,excerpt:y}});e({searchResults:l})},setCurrentPath:n=>e({currentPath:n}),clearSearch:()=>e({searchQuery:"",searchResults:[]})})),V_=Gn;function K_(e){const t=e.split(`
|
|
659
659
|
`),n=[];let i=!1;for(const s of t){if(s.startsWith("```")){i=!i;continue}if(i)continue;const l=s.match(/^##\s+(.+)$/),d=s.match(/^###\s+(.+)$/),a=d||l;if(!a)continue;const o=a[1].trim(),c=o.toLowerCase().replace(/[^\w\u4e00-\u9fff\s-]/g,"").replace(/\s+/g,"-");n.push({id:c,text:o,level:d?3:2})}return n}function Y_({className:e,children:t,...n}){const i=Ke(d=>d.resolved),s=(e||"").match(/language-(\w+)/),l=String(t).replace(/\n$/,"");return s?r.jsx("div",{className:"relative group my-3",children:r.jsx(V_,{style:i==="dark"?Pr:Fr,language:s[1],PreTag:"div",customStyle:{margin:0,borderRadius:"8px",fontSize:"13px",lineHeight:"1.6"},codeTagProps:{style:{background:"transparent",textShadow:"none"}},children:l})}):r.jsx("code",{className:"bg-bg-tertiary text-text-primary px-1.5 py-0.5 rounded text-[13px]",...n,children:t})}function X_({content:e,onNavigate:t}){const{t:n}=ne(),i=T.useMemo(()=>K_(e),[e]),[s,l]=T.useState(""),d=T.useRef(null);T.useEffect(()=>{var o;(o=d.current)==null||o.scrollTo(0,0)},[e]),T.useEffect(()=>{if(i.length===0)return;const o=new IntersectionObserver(c=>{for(const p of c)p.isIntersecting&&l(p.target.id)},{rootMargin:"-80px 0px -80% 0px"});for(const c of i){const p=document.getElementById(c.id);p&&o.observe(p)}return()=>o.disconnect()},[i]);const a=T.useCallback(o=>{const c=o.currentTarget.getAttribute("href");c&&c.startsWith("/cli/")&&(o.preventDefault(),t(c))},[t]);return r.jsxs("div",{className:"flex gap-6 h-full",children:[r.jsx("div",{ref:d,className:"flex-1 min-w-0 overflow-y-auto px-6 py-6",children:r.jsx("article",{className:"max-w-3xl mx-auto docs-markdown",children:r.jsx(on,{remarkPlugins:[ln],components:{code:Y_,h2:({children:o,...c})=>{const h=String(o).toLowerCase().replace(/[^\w\u4e00-\u9fff\s-]/g,"").replace(/\s+/g,"-");return r.jsx("h2",{id:h,className:"text-xl font-semibold mt-8 mb-3 text-text-primary scroll-mt-20",...c,children:o})},h3:({children:o,...c})=>{const h=String(o).toLowerCase().replace(/[^\w\u4e00-\u9fff\s-]/g,"").replace(/\s+/g,"-");return r.jsx("h3",{id:h,className:"text-lg font-medium mt-6 mb-2 text-text-primary scroll-mt-20",...c,children:o})},h1:({children:o,...c})=>r.jsx("h1",{className:"text-2xl font-bold mb-4 text-text-primary",...c,children:o}),p:({children:o,...c})=>r.jsx("p",{className:"text-sm leading-7 text-text-secondary mb-4",...c,children:o}),a:({children:o,href:c,...p})=>r.jsx("a",{href:c,onClick:c!=null&&c.startsWith("/cli/")?a:void 0,className:"text-accent-brand hover:underline",target:c!=null&&c.startsWith("http")?"_blank":void 0,rel:c!=null&&c.startsWith("http")?"noopener noreferrer":void 0,...p,children:o}),ul:({children:o,...c})=>r.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1 text-sm text-text-secondary",...c,children:o}),ol:({children:o,...c})=>r.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1 text-sm text-text-secondary",...c,children:o}),blockquote:({children:o,...c})=>r.jsx("blockquote",{className:"border-l-4 border-border-primary pl-4 my-4 text-sm text-text-tertiary italic",...c,children:o}),table:({children:o,...c})=>r.jsx("div",{className:"overflow-x-auto my-4",children:r.jsx("table",{className:"min-w-full text-sm border-collapse",...c,children:o})}),th:({children:o,...c})=>r.jsx("th",{className:"border border-border-primary px-3 py-2 bg-bg-secondary text-left font-medium text-text-primary",...c,children:o}),td:({children:o,...c})=>r.jsx("td",{className:"border border-border-primary px-3 py-2 text-text-secondary",...c,children:o}),hr:()=>r.jsx("hr",{className:"my-6 border-border-primary"}),img:({src:o,alt:c,...p})=>r.jsx("img",{src:o,alt:c,className:"max-w-full rounded-lg my-4",loading:"lazy",...p})},children:e})})}),i.length>0&&r.jsx("div",{className:"hidden xl:block w-56 flex-shrink-0 py-6 pr-4",children:r.jsxs("div",{className:"sticky top-6",children:[r.jsx("h4",{className:"text-xs font-semibold text-text-tertiary uppercase tracking-wider mb-3",children:n("docs.toc")}),r.jsx("nav",{className:"space-y-1",children:i.map(o=>r.jsx("a",{href:`#${o.id}`,onClick:c=>{var p;c.preventDefault(),(p=document.getElementById(o.id))==null||p.scrollIntoView({behavior:"smooth"})},className:`block text-xs py-0.5 transition-colors truncate
|
|
660
660
|
${o.level===3?"pl-3":""}
|
|
661
661
|
${s===o.id?"text-accent-brand font-medium":"text-text-tertiary hover:text-text-secondary"}`,children:o.text},o.id))})]})})]})}function Z_({query:e,results:t,onSelect:n}){const{t:i}=ne();return e.trim()?t.length===0?r.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:r.jsxs("div",{className:"text-center",children:[r.jsx(st,{size:40,className:"mx-auto mb-4 text-text-tertiary opacity-30"}),r.jsx("div",{className:"text-text-secondary text-sm mb-1",children:i("docs.search.noResults")}),r.jsxs("div",{className:"text-text-tertiary text-xs",children:['"',e,'"']})]})}):r.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:[r.jsx("p",{className:"text-xs font-medium text-text-tertiary uppercase tracking-wider mb-4",children:i("docs.search.resultsCount").replace("{count}",String(t.length))}),r.jsx("div",{className:"space-y-2 max-w-3xl",children:t.map(s=>r.jsxs("button",{onClick:()=>n(s.id),className:"w-full text-left p-4 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[r.jsx(ct,{size:14,className:"text-text-tertiary flex-shrink-0"}),r.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:s.title})]}),r.jsx("p",{className:"text-xs text-text-tertiary line-clamp-2 pl-[22px] leading-relaxed",children:s.excerpt})]},s.id))})]}):r.jsx(r.Fragment,{})}function Bi({item:e,currentPath:t,onSelect:n,depth:i}){const[s,l]=T.useState(!e.collapsed),d=e.items&&e.items.length>0,a=e.link===t,o=d&&!e.link,c=T.useCallback(()=>{e.link&&n(e.link),d&&l(p=>!p)},[e.link,d,n]);return o&&i===0?r.jsxs("div",{className:"mt-4 first:mt-0",children:[r.jsxs("button",{onClick:c,className:["w-full text-left flex items-center gap-1.5 px-4 py-2 text-xs","font-semibold text-text-tertiary uppercase tracking-wider","hover:text-text-secondary transition-colors"].join(" "),children:[r.jsx("span",{className:"flex-shrink-0 w-4 h-4 flex items-center justify-center",children:s?r.jsx(nt,{size:12}):r.jsx(Ae,{size:12})}),r.jsx("span",{className:"truncate",children:e.text})]}),s&&r.jsx("div",{children:e.items.map((p,h)=>r.jsx(Bi,{item:p,currentPath:t,onSelect:n,depth:i+1},p.link||`${p.text}-${h}`))})]}):r.jsxs("div",{children:[r.jsxs("button",{onClick:c,className:`w-full text-left flex items-center gap-1.5 py-1.5 rounded-lg text-[13px] transition-colors
|