@prismshadow/penguin-server 0.2.6 → 0.2.7
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/dist/api/types.d.ts +4 -3
- package/dist/index.js +123 -17
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/web-dist/assets/{addon-fit-CE-3eCvv.js → addon-fit-BXTX0Xqu.js} +1 -1
- package/web-dist/assets/{addon-web-links-DeODgawX.js → addon-web-links-KebkunbU.js} +1 -1
- package/web-dist/assets/{highlighter-DpnM5FfD.js → highlighter-B3HctNDB.js} +1 -1
- package/web-dist/assets/index-BbLm3DrY.css +1 -0
- package/web-dist/assets/{index-gNzir_kH.js → index-DwgTjTHO.js} +5 -5
- package/web-dist/assets/{xterm-BjU-ZsL5.js → xterm-fEUfDV0F.js} +1 -1
- package/web-dist/index.html +2 -2
- package/web-dist/assets/index-aRsvImZt.css +0 -1
|
@@ -65,7 +65,7 @@ Benchmark:
|
|
|
65
65
|
场景:
|
|
66
66
|
1. 根据历史比赛与当前信息进行足球投注决策。
|
|
67
67
|
2. 根据售后政策与工单事实选择处置动作。
|
|
68
|
-
3. 根据投资策略、历史市场与当前指标选择投资动作。`},agentOptimization:{label:"优化通用决策智能体的准确率",desc:"根据已有评测结果改进 Agent,并验证新版本是否真正提升",prompt:"请使用 `agent-optimization`,根据 Frozen Benchmark 优化决策 Agent。\n\n- test_agent_id:`finite_choice_agent`\n- benchmark_id:`contextual-choice-adaptation`\n- capability_direction:提高信息不完整、规则冲突和有限选项决策中的稳定性\n- runs:`3`\n- desired_score:`>=95`\n- candidate_round_limit:`5`"},dailyPlan:{label:"每天早 9 点的计划对话",desc:"每天 09:00 在同一个会话里聊当天计划,并回顾昨天的进展",prompt:"建一个定时任务:每天早上 9 点在这个会话里和我聊今天的计划。先回看上文说清昨天定的事做完了多少、哪些卡住,再给我一份排好序的今日候选、每条一句理由,我确认后写成清单。"},githubDigest:{label:"每天汇总 GitHub 项目状态",desc:"定时跑一遍仓库的 Issue、PR 与 CI,日报结尾给出按优先级排序的建议",prompt:"建一个定时任务:每天早上用 gh 汇总一个 GitHub 仓库的 Issue、PR 与 CI 状态,挑出停滞的、待评审的和挂掉的,结尾给出按优先级排序的建议,每条说清为什么排在这个位置。"},memoryReview:{label:"每周五晚回顾并记录 Memory",desc:"周五傍晚一起过一遍这周值得长期记住的事,确认后由你写进 Memory",prompt:"建一个定时任务:每周五傍晚在这个会话里和我过一遍这周值得长期记住的事。先看已有记忆索引避免重复,再逐条问我该记什么、要不要改已有的,我确认后你写进 Memory。"}},sessionList:"Session",defaultSessionTitle:"新对话",agent:"Agent",model:"Model",workspace:"Workspace",workspaceHint:"留空自动创建临时工作区;指定时必须是服务器上已存在的目录",workspaceHintShort:"留空自动创建临时工作区",approvalMode:"审批模式",approvalModeNames:{"allow-all":"全部放行","deny-all":"全部拒绝","read-only":"放行只读","always-ask":"总是询问"},approvalModes:{"allow-all":"全部放行(allow-all)","deny-all":"全部拒绝(deny-all)","read-only":"放行只读(read-only)","always-ask":"总是询问(always-ask)"},statusRunning:"运行中",statusCompacting:"压缩中",statusCompletedUnread:"运行完毕,未读",pendingApprovals:e=>`${e} 个待审批`,jumpToLatest:"回到最新消息",loadingEarlier:"正在加载更早的对话…",loadEarlierRetry:"更早的对话加载失败,点击重试",historyBeginning:"已是对话开头",outlineTitle:"对话索引",outlineTickLabel:(e,t)=>`第 ${e} 轮:${t}`,outlineNoText:"(图片或附件)",outlineAnswering:"回答生成中…",inputPlaceholder:"输入消息,Enter 发送,Shift+Enter 换行,可粘贴图片",inputPlaceholderShort:"输入消息…",steerPlaceholder:"给运行中的 Agent 留言,随下一轮对话送达",steerPlaceholderShort:"给运行中的 Agent 留言…",steerSend:"发送给运行中的 Agent",steerQueuedIndicator:"插话已排队,将随下一轮送达",steerQueuedItem:e=>`插话已排队,将随下一轮送达:${e}`,userSteering:"用户插话",steerModeLabel:"运行中发送方式",steerModeSteer:"插话",steerModeSteerHint:"立即插话:随下一轮对话送达运行中的 Agent",steerModeFollowUp:"排队",steerModeFollowUpHint:"排队跟进:本轮结束后自动作为新消息发送",followUpPlaceholder:"排队为下一条消息,本轮结束后自动发送",followUpPlaceholderShort:"排队为下一条消息…",followUpSend:"排队为下一条消息",followUpQueuedChip:e=>`${e} 条跟进消息已排队,本轮结束后自动发送`,followUpQueuedItem:e=>`跟进消息已排队,本轮结束后自动发送:${e}`,recallQueued:"撤回",recallQueuedTitle:"撤回到输入框,编辑后重新发送",send:"发送",stop:"停止",compact:"压缩上下文",approve:"允许",deny:"拒绝",decisionAllow:"已批准",decisionDeny:"已拒绝",decisionManual:"手动",decisionAuto:"自动",decisionPolicy:"策略",thinking:"思考",subagent:"子会话",subagentRunning:"运行中",aborted:e=>{const t=e?.errorCode==="user_abort"?"用户中断":e?.errorCode==="backoff_interrupted"?"重试等待中被中断":e?.errorCode==="compaction_interrupted"?"压缩过程中被中断":e?.errorCode??e?.reason??"",n=t?`${t}${e?.errorMessage?`:${e.errorMessage}`:""}`:"";return`[已中断]${n?`:${n}`:""}`},reconnect:(e,t,n,s,o,c)=>{const u=c??e,f=u==="timeout"?"连接超时或网络中断":u==="malformed"?"响应不完整或无法解析":u==="network"?"网络或服务暂时不可用":u==="failed"?"模型服务返回错误":"请求失败",p=t==="gaveUp"?`第 ${n} 次尝试后放弃${o?`:${o}`:""}`:t==="retried"?`已发起第 ${n} 次重试`:s!==void 0?`第 ${n} 次重试,${s} 秒后发起…`:`正在发起第 ${n} 次重试…`;return`[重试] ${f},${p}`},llmError:e=>`[错误]:模型请求错误${e?`:${e}`:""}`,reconnectRetryNow:"立即重试",reconnectGiveUp:"放弃",imageAlt:"用户上传的图片",toolImageAlt:"工具输出的图片",imagesAsPathHint:"当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 describe_image 查看)",infoPanel:"Session 信息",sessionStats:"统计",sessionIdLabel:"Session id",copySessionId:"复制 Session id",processList:"会话进程",processStop:"停止",processExited:"已退出",processRemove:"移除",processRemoveHint:"移除该条目——该进程已捕获的输出也会一并丢弃",runningServices:e=>`${e} 个运行中的服务`,statTokens:"Token 累计",statTotalTokens:"总 Token",statCacheHit:e=>`缓存命中率 ${e}`,statElapsed:"用时",statInput:"输入 tokens",statCached:"已缓存",statOutput:"输出 tokens",statTps:"输出 TPS",statParenOpen:"(",statParenClose:")",noSessions:"还没有 Session",emptyStream:"发送一条消息开始对话",historyLoadFailed:"历史消息加载失败",statsLabel:"统计信息",removeImage:"移除图片",openAgents:"智能体面板",workspacePanel:"工作区",filesInMessage:e=>`${e} 个文件`,imagesInMessage:e=>`${e} 张图片`,openPreview:"点击预览",showMoreFiles:e=>`显示其余 ${e} 个文件`,showLess:"收起",memoryChangesTitle:e=>`${e} 条记忆更新`,memoryScopeWorkspace:e=>`工作区记忆(${e})`,memoryOpWrite:"写入",memoryOpEdit:"编辑",memoryViewTitle:"记忆",memoryChangedMark:"本次对话已更改",memoryContentUnavailable:"无法加载内容(文件可能已被移动或删除)",memoryRowOpen:"查看内容",memoryBack:"返回列表",memoryEmptyAll:"还没有任何记忆——在对话里说「记住……」即可让 agent 保存",openAgentMemory:"在 Agent 设置中管理",memoryShowMore:e=>`显示其余 ${e} 条`,prevGroupPage:"上一页分组",nextGroupPage:"下一页分组",groupPagePosition:(e,t)=>`第 ${e} 页,共 ${t} 页`,contextUsage:"上下文占用",contextUnknown:"上下文占用:压缩后待下次请求回报",contextComposition:"上下文构成",contextPartSystemPrompt:"系统提示词",contextPartToolDefs:"工具定义",contextPartUserMessages:"用户消息",contextPartAssistantMessages:"模型消息",contextPartToolRequests:"工具请求",contextPartToolResults:"工具结果",contextTopTools:"工具用量 Top 5",contextCompactAt:e=>`压缩阈值 ${e}`,contextTopToolsHint:"按每个工具的调用与结果所占上下文排序(工具定义计入「工具定义」一项)",contextUnknownHint:"刚压缩过,占用待下次请求回报,届时才能给出构成",contextBreakdownEmpty:"当前上下文还没有可统计的内容",contextBreakdownFailed:"读取上下文构成失败",slashHint:"输入 / 使用命令",switchAgent:"交给其他 Agent,发送时开启新会话",switchAgentTitle:"选择 Agent",agentSearchPlaceholder:"搜索 Agent:id / 名称",agentsNoMatch:"没有匹配的 Agent",handoffTargetTitle:e=>`发送后交接给 ${e}`,handoffRemove:"移除交接目标",skillsSelect:"技能",skillRemove:"移除技能",skillsSearchPlaceholder:"搜索技能",skillsNoMatch:"没有匹配的技能",skillsEmptyHint:"暂无已装技能,去技能库添加",skillsAutoMessage:e=>`使用 ${e.join("、")} 技能`,handoffFrom:e=>`由 ${e} 的对话交接而来`,handoffBack:e=>e?`回到原对话:${e}`:"回到原对话",switchModel:"切换模型,发送时开启新会话延续本对话",switchModelTitle:"切换模型",modelSwitchTargetTitle:e=>`发送后换用 ${e} 延续本对话`,modelSwitchRemove:"移除切换模型",modelSwitchBusyHint:"本轮结束后才能切换模型:新会话要从当前会话的记录接续",modelSwitchFrom:e=>e?`已切换模型(原为 ${e}),延续原会话`:"已切换模型,延续原会话",modelSwitchAutoMessage:"换用新模型继续这段对话",modelLockedHint:"输入 /model 切换模型",scheduledFrom:e=>`由定时任务「${e}」触发`,backgroundDone:(e,t)=>{const n=e==="command"?"后台命令":"后台任务";return t==="stopped"?`${n}已停止`:t==="completed"?`${n}完成`:`${n}失败`},emptyGreeting:"开始一段新对话",mcpConnectTitle:"MCP 连接",mcpServerList:e=>e.join("、"),mcpConnectResult:(e,t)=>{const n=[];return(e>0||t.length===0)&&n.push(`发现 ${e} 个工具`),t.length>0&&n.push(`不可用:${t.join("、")}`),n.join(";")},mcpToolsCount:e=>`${e} 个工具`,mcpServerFailed:"连接失败",mcpConnectAborted:"已中断,下次发送时重新连接",compactionTitle:e=>e==="discard"?"清空":"压缩",compactionFailed:(e,t)=>{if(e==="aborted")return"已中断,保留当前上下文";const n=t!==void 0?`(${t})`:"";return e==="retryable"?`失败${n},保留当前上下文,下次触发时重试`:e==="fatal"?`失败${n},保留当前上下文,需修复模型配置后重试`:`失败${n},保留当前上下文`},unknownTool:"(未知工具)",workRunning:"运行中",workDone:"运行完毕",workGroupSteps:e=>`${e} 步`,approvalWaiting:"待审批",copyCode:"复制代码",copyReply:"复制回复",forkSession:"从这里分叉对话",forkSessionConfirmBody:"将把这段对话(截至这条回复)复制为一个新对话,原对话保持不变。",forkSessionConfirmAction:"分叉",forkSessionFailed:"无法定位这条回复,请刷新后重试。",copyMessage:"复制消息",deleteSession:"删除对话",renameSession:"重命名对话",renameSessionLabel:"标题",deleteSessionConfirm:e=>`确定删除「${e}」?该对话的消息与 Trace 将被移除,且不可恢复。`,draftGroup:"草稿",draftUntitled:"(无标题草稿)",deleteDraft:"删除草稿",deleteDraftConfirm:e=>`确定删除草稿「${e}」?未发送的内容将被丢弃。`,archiveSession:"归档",unarchiveSession:"取消归档",pinSession:"置顶",unpinSession:"取消置顶",pinnedSession:"已置顶",moreActions:"更多",loadMore:"更多",expandRestSessions:e=>`展开其余 ${e} 个对话`,loadMoreSessions:"加载更多会话",folderGroups:{subagent:e=>`子智能体(${e})`,schedule:e=>`定时任务(${e})`,archived:e=>`已归档(${e})`},skillsBanner:e=>`使用技能:${e.join("、")}`,attachedFilesBanner:e=>`附加文件:${e.join("、")}`,plusMenu:"更多输入方式",uploadImage:"上传图片",uploadImageDesc:"为本条消息附加图片",uploadFile:"上传文件",uploadFileDesc:"文件存入会话临时目录,模型按路径读取",removeFile:"移除文件",attachmentTooLarge:(e,t)=>`${e} 超过 ${t}MB 上限,未添加。`,dropFilesTitle:"松开以添加附件",dropFilesDesc:"图片与文件将添加到输入框",dropFilesGoalHint:"目标模式仅支持附加图片,文件未添加。",goalMode:"目标模式",goalModeDesc:"循环运行直至目标完成",goalBudgetLabel:"Token 预算",goalBudgetUnlimited:"预算不限",goalBudgetValue:e=>`预算 ${e}`,goalBudgetPlaceholder:"例如 500k",goalBudgetHint:"支持 k/m 后缀;留空表示预算不限",goalBudgetInvalid:"无效预算:应为正数,可带 k/m 后缀(500k、2m)",goalBudgetSave:"保存预算",goalRemove:"退出目标模式",goalRoundBanner:e=>`目标 · 第 ${e} 轮`,goalRoundImages:e=>`${e} 张附图`,goalProgress:(e,t)=>`第 ${e} 轮 · tokens ${t}`,goalStatus:{active:"进行中",complete:"已完成",blocked:"受阻",budget_limited:"预算耗尽",aborted:"已中断"}},feishu:{intro:"绑定后,发给飞书机器人的消息会进入本对话,AI 的回复会以纯文本发回飞书。需要一个开通了机器人能力、订阅了接收消息事件(长连接方式)的飞书自建应用。",appId:"App ID",appSecret:"App Secret",appSecretKeepHint:"留空保持已保存的 App Secret 不变",clearSecret:"清除已存 App Secret",baseDomain:"API 域名",baseDomainHint:"飞书为 https://open.feishu.cn,Lark 为 https://open.larksuite.com",invalidDomain:"域名需为 http(s):// 地址",testMessageNoChat:"先在飞书中给机器人发一条消息,机器人才知道要发到哪个会话",setupSteps:["在飞书开发者后台创建一个企业自建应用","为应用开通机器人能力","订阅「接收消息」事件,事件订阅方式选择「长连接」","在「凭证与基础信息」页取得 App ID 与 App Secret,填入上方表单","发布应用版本并通过审核,然后在飞书中给机器人发一条消息"]},telegram:{intro:"绑定后,发给 Telegram 机器人的消息会进入本对话,AI 的回复会以纯文本发回 Telegram。用 @BotFather 创建机器人并粘贴其 Bot Token 即可,无需公网地址。",botToken:"Bot Token",botTokenKeepHint:"留空保持已保存的 Bot Token 不变",clearToken:"清除已存 Bot Token",invalidToken:"Bot Token 形如「数字:密钥」,由 @BotFather 签发",testMessageNoChat:"先在 Telegram 中给机器人发一条消息,机器人才知道要发到哪个会话",setupSteps:["在 Telegram 中打开 @BotFather,发送 /newbot 创建机器人","按提示取名后,复制 @BotFather 返回的 Bot Token,填入上方表单","在 Telegram 中找到这个机器人,给它发一条消息"]},messaging:{panelTitle:"消息软件",bindAction:"消息软件绑定…",dialogTitle:"消息软件绑定",channelLabel:"渠道",channelName:{feishu:"飞书",telegram:"Telegram"},tutorial:"前往教程",console:"前往开发者后台",enabled:"启用连接",saveBeforeEnable:"先保存凭证,再启用连接",test:"测试连接",testing:"测试中…",testOk:e=>`连接成功(${e}ms)`,testOkAs:(e,t)=>`连接成功,机器人为 ${e}(${t}ms)`,testFail:e=>`连接失败:${e}`,sendTestMessage:"发送测试消息",sendingTestMessage:"发送中…",testMessageSent:"测试消息已发送",statusLabel:"连接状态",status:{disconnected:"未连接",connecting:"连接中",connected:"已连接",error:"连接错误"},otherEnabledHint:e=>`同一会话只能启用一个渠道:先停用${e}连接`,credentialMissingHint:"先填写并保存凭证,再启用连接",disableBeforeClearHint:"先停用连接,才能清除凭证",enabledIndicator:{feishu:"飞书连接已启用",telegram:"Telegram 连接已启用"},faqSetupTitle:"如何创建机器人",faqWhatTitle:"绑定后会发生什么",faqTroubleTitle:"常见问题",troubleNoChat:"「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",troubleConnError:"连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。"},subagentPanel:{topologyLabel:"调用关系",mainSessionNote:"主会话请在对话区查看",empty:"本次任务尚未派生子智能体",nodeRunning:"运行中",nodeDone:"已完成",openAsSession:"跳转到该会话",subagentGone:"该子会话已不存在,无法恢复"},files:{title:"文件",upload:"上传",download:"下载",openInNewTab:"新页面打开",previewNotIsolatedHint:"当前访问地址无法提供独立预览源,页面将以沙箱模式打开:localStorage、Cookie 与第三方 embed 不可用。经 127.0.0.1 或 localhost 访问,或配置 PENGUIN_PREVIEW_ORIGIN 即可解除。",refresh:"刷新",root:"根目录",empty:"空目录",previewUnsupported:"该类型不支持预览,请下载查看",uploaded:"已上传",overwriteTitle:"覆盖同名文件",overwriteConfirm:e=>`当前目录已存在以下 ${e} 个同名文件,上传将覆盖:`,loadFailed:"加载失败",previewTruncated:"内容过大,预览已截断,请下载查看完整文件",details:"详情",workspacePath:"Workspace 路径",htmlRendered:"渲染视图",htmlSource:"源码",backToList:"返回列表"},usage:{title:"成本与统计",today:"今日",last7d:"近 7 天",total:"累计",tokens:"Token",requests:"Requests",from:"起始日期",to:"结束日期",colCacheRead:"cache_read",colCacheWrite:"cache_write",colOutput:"output",uncostedNote:"* 只计入配置了价格的模型成本",filterAllAgents:"全部 Agent",filterAllModels:"全部模型",rangeLabel:"日期范围",rangeHour:"最近一小时",rangeDay:"最近一天",range7d:"近 7 天",range30d:"近 30 天",range90d:"近 90 天",rangeCustom:"自定义",chartRequestsByAgent:"各 Agent 请求与成功率",chartRequestsByModel:"各模型请求与成功率",legendSuccessRate:"成功率",chartTokenTrend:"Token 变化",chartCostTrend:"成本变化",legendOther:e=>`其他 ${e} 项`,bucketTotal:"合计",legendHitRate:"缓存命中率",empty:"暂无用量记录",errors:"异常",errorsTotal:"总数",errorsUnexpected:"未预期",errorsExpected:"预期内",errorsTopCode:"最常见",errorsColCode:"来源 · 错误码",errorsColKind:"类型",errorsColMessage:"消息",errorsEmpty:"暂无异常",errorsNewer:"较新",errorsOlder:"更早",errorsPageOf:(e,t,n)=>`第 ${e} / ${t} 页 · 共 ${n} 条`},traces:{timeline:"执行时间线",laneLLM:"模型",kindThinking:"思考",kindModelReply:"模型回复",kindToolGen:"工具调用生成",legendToolExec:"工具调用执行",legendOther:"其他",toolParams:"参数 Schema",requiredParam:"必填",legendApprovalWait:"审批等待",task:e=>`第 ${e} 轮`,globalSummary:"全局统计",tasksLabel:"轮次",messages:"消息",truncatedNote:(e,t)=>`仅展示前 ${e} / ${t} 条消息`,zoom:"缩放",zoomReset:"双击复位缩放",zoomOut:"缩小",zoomIn:"放大",linkHint:"鼠标移到时间线段或消息行即可联动高亮,点击时间线段跳转到对应消息;图例可高亮同类;拖动下方滑块平移/缩放",filesTitle:"Trace 文件",toolCalls:"工具调用",taskInput:"本轮输入 tokens",taskOutput:"本轮输出 tokens",cacheHit:"命中缓存",hitRate:"命中率",compactions:"压缩次数",inProgress:"进行中",systemPrompt:"系统提示词",toolDefs:e=>`工具定义(${e})`,exportFile:"导出"},benchmark:{title:"评估中心",selectBenchmark:"在左侧选择一个 Benchmark",emptyAgent:"该 Agent 暂无 Benchmark",caseCount:e=>`${e} 题`,trendTitle:e=>`${e}随时间变化`,cases:"题目",viewCase:"查看详情",taskMaterials:"任务材料",rubric:"评分标准",agentHidden:"被测 Agent 不可见",caseFileUnavailable:"案例文件暂时无法读取",evaluations:"评估明细",noEvaluations:"暂无评估记录",summaryLabel:"评估说明",legendUnlabeled:"未标注模型",colVersion:"版本",colModel:"模型 ID",colThinkingLevel:"推理强度",colScore:"Score",colDuration:"耗时",colCase:"题目",colRun:"运行",colSession:"Session"},errors:{networkError:"网络错误,请检查连接",modelCredentialMissing:e=>`模型 ${e} 还没有可用的 API key,请先在「模型」页为它配置`,noDefaultModel:"该 Project 还没有默认模型,请先在「模型」页添加模型并设为默认",byCode:{invalid_credentials:"用户名或密码错误。",too_many_attempts:"登录失败次数过多,请稍后重试。",password_mismatch:"当前密码不正确。",invalid_password:"密码至少 8 位。",admin_required:"仅管理员可执行此操作。",desktop_single_user:"桌面应用为单用户模式,用户管理不可用。",not_found:"资源不存在,或你没有访问权限。",internal:"服务器内部错误,请稍后重试。",agent_not_found:"该 Agent 已不存在。",unknown_agent:"该 Agent 不存在于本 Project。",agent_exists:"该 Agent id 已被占用。",agent_deleting:"该 Agent 正在删除中。",project_exists:"该 Project id 已被占用。",project_not_found:"该 Project 已不存在,或你没有访问权限。",cannot_delete_last_project:"这是最后一个 Project,不能删除。",user_exists:"该用户名已被占用。",user_not_found:"该用户已不存在。",cannot_delete_admin:"内置 admin 不可删除。",member_not_found:"该用户不是本 Project 的成员。",already_member:"该用户已是本 Project 的成员。",already_owner:"该用户已是本 Project 的所有者。",memory_import_confirm_required:"本次导入会覆盖或删除已有记忆,请确认后继续。",schedule_exists:"已存在同名定时任务。",schedule_not_found:"该定时任务已不存在。",unknown_skill:"该技能不在技能库中。",skill_too_large:"该技能目录过大,超出了导入限制。",file_not_found:"该文件已不存在。",not_pending:"该消息已发出,无法撤回。",file_too_large:"文件过大。",too_many_files:"一条消息附加的文件过多。",payload_too_large:"请求体过大。",image_too_large:"图片过大,无法随对话发送。",dir_not_absolute:"目录必须是绝对路径。",dir_not_found:"该目录不存在或不可访问。",not_a_dir:"该路径不是目录。",path_not_found:"该路径不存在。",workspace_missing:"该 Session 的 Workspace 已不存在。",workspace_not_found:"该 Workspace 不存在或不是目录。",session_not_found:"该 Session 已不存在,或你没有访问权限。",session_deleting:"该 Session 正在删除中。",approval_not_found:"该授权请求已处理或已失效。",process_not_found:"该后台进程已结束或已被移除。",process_running:"该后台进程仍在运行,请先结束再移除。",memory_file_not_found:"该记忆文件已不存在。",memory_scope_not_found:"该记忆范围已不存在。",task_in_progress:"该 Session 已有任务在运行。",compacting:"该 Session 正在压缩上下文,暂不接受新的输入。",shutting_down:"服务正在关闭,请稍后重试。",compaction_not_configured:"该 Agent 没有配置上下文压缩。",nothing_to_compact:"当前上下文还没有可压缩的内容(尚未完成一轮对话)。",already_compacted:"刚刚压缩过,之后还没有新的对话,无需重复压缩。",version_conflict:"快照版本不高于当前版本。",invalid_title:"标题无效。",invalid_proxy_url:"代理地址无效:应为 http(s):// 或 socks5:// 代理 URL,或 主机[:端口]。",invalid_attachment_limit:"上传限制无效:请填写允许范围内的整数 MB,且合计不低于单个上限。",invalid_trace:"该文件不是有效的 Trace 文件。",trace_not_found:"该 Trace 文件已不存在。",trace_session_exists:"该 Agent 已存在同名 Session,无法导入重复的 Trace。",feishu_app_in_use:"该飞书应用已绑定到其他 Session,请先解除或换一个应用。",feishu_secret_required:"需要填写 App Secret。",feishu_not_bound:"该 Session 尚未绑定飞书。",feishu_no_chat:"尚未收到飞书消息:先在飞书中给机器人发一条消息。",feishu_send_failed:"飞书消息发送失败。",telegram_bot_in_use:"该 Telegram 机器人已绑定到其他 Session,请先解除或换一个机器人。",telegram_token_required:"需要填写 Bot Token。",telegram_token_invalid:"Bot Token 格式不正确:应形如「数字:密钥」。",telegram_not_bound:"该 Session 尚未绑定 Telegram。",telegram_no_chat:"尚未收到 Telegram 消息:先在 Telegram 中给机器人发一条消息。",telegram_send_failed:"Telegram 消息发送失败。",another_channel_enabled:"该会话已启用另一渠道的连接:先停用它,再启用当前渠道。",messaging_disable_before_clear:"先停用该渠道的连接,才能清除其凭证。"}}};let d=Uj;function K3(e){d=e}const W3={appName:"PenguinHarness",nav:{chat:"Chat",newChat:"New chat",agents:"Agents",skills:"Skills",models:"Models",usage:"Cost Center",traces:"Trajectories",benchmark:"Evaluation Center",lastConversation:"Last conversation",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",collapseGroup:"Collapse",expandGroup:"Expand",pinGroup:"Pin group",unpinGroup:"Unpin group"},terminal:{title:"Terminal",newShell:"New shell",killShell:"Kill this terminal",createFailed:"Could not start a terminal",noTerminalApi:"this server has no terminal API: the running runtime predates it. A hot push replaces the platform and Web App, but the terminal endpoints are runtime-owned — the runtime itself has to be updated (restarting will not help)",detach:"Open in new window",status:{connecting:"connecting",ready:"ready",exited:"exited",error:"error"},exitedWithCode:e=>`exit code ${e}`},dock:{addTab:"Add panel",closeTab:"Close panel",hideDock:"Hide sidebar",moveToRight:"Move to the right",moveToBottom:"Move to the bottom",resize:"Resize panel",rightDock:"Right sidebar",bottomDock:"Bottom panel",draftEmpty:"Available once the conversation starts",killConfirmTitle:"Close this terminal?",killConfirmBody:e=>`This ends the shell "${e}" — it cannot be restored.`},tracePanel:{empty:"No traces yet",emptyHint:"This session has not produced a Trace file yet",loadFailed:"Failed to load traces"},settings:{language:"Language",languageInfo:"Interface language; can follow the browser.",systemSettings:"System settings",groupPersonal:"Personal",groupServer:"Server",generalTitle:"General",appearanceTitle:"Appearance",accountTitle:"Account",importTrace:"Import Trace",importTraceInfo:"Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",importTraceProject:"Import into project",importTraceAgent:"Import into agent",importTracePick:"Choose file",importTraceRunning:"Importing…",importTraceDone:e=>`Trace imported into ${e}`,importTraceTooLarge:"The file exceeds the 14MB limit.",proxyTitle:"Proxy options",proxyInfo:"Server-global, and in force the moment it is saved — nothing to restart. Loopback addresses always go direct.",proxyForApp:"Application uses the proxy",proxyForAgent:"Agent environment uses the proxy",proxyAddress:"Proxy address",proxyAddressPlaceholder:"Empty = follow system proxy",uploadLimitsTitle:"Upload limits",attachmentMaxMb:"Max attachment size (MB)",attachmentTotalMb:"Max total per message (MB)",attachmentMaxMbHint:(e,t)=>`${e}–${t} MB`,attachmentTotalMbHint:(e,t)=>`${e}–${t} MB, and not below the per-file limit`,uploadLimitsInfo:(e,t)=>`A message may carry at most ${e} attachments. Images placed inline in the conversation keep a separate ${t}MB limit that this setting does not raise — an inline image enters the conversation and the Trace, where its size is paid again on every history page and resume.`,theme:"Theme",themeInfo:"Light or dark look of the app.",themeLight:"Light",themeDark:"Dark",followSystem:"System",terminalTheme:"Terminal theme",terminalThemeInfo:"Colors of the terminal panel; follows the app theme by default.",followAppTheme:"App",langZh:"中文",langEn:"English",fontSize:"Font size",fontSizeInfo:"Overall interface font size.",fontSmall:"S",fontMedium:"M",fontLarge:"L",accent:"Accent",accentInfo:"Interface accent color.",currencyInfo:"Display currency for prices; storage is always USD.",changePasswordInfo:"Change this account's sign-in password.",accentNames:{neutral:"Neutral",blue:"Blue",green:"Green",violet:"Violet",rose:"Rose",amber:"Amber"}},update:{lastUpdated:e=>`Last updated ${e}`,newVersionBadge:"New version available",newVersion:e=>`New version v${e} available`,updatesAvailable:"Updates available",checkNow:"Check for updates",checking:"Checking…",foundNew:e=>`New version v${e} found — use the update entry to install`,upToDate:"You're on the latest version",checkFailed:"Update check failed — try again later",checkDisabled:"Update checks are disabled (PENGUIN_UPDATE_CHECK=off)",releaseNotes:"Release notes",updateNow:"Update now",updating:"Updating…",updated:"Update complete — restart the service to apply",restartHint:"Restart by re-running penguin web (or penguin server) in a terminal",failed:"Update failed",unsupported:"This install cannot be updated from the web UI",confirmBody:"Downloads the latest release and installs it into the install directory on the server (the data directory is not touched). Restart the service afterwards for the update to take effect.",adminOnly:"Only an administrator can run the update from here.",clientCheckNow:"Check for updates",clientFoundNew:e=>e!==null?`Version v${e} found — downloading in the background…`:"New version found — downloading in the background…",clientDownloading:(e,t)=>`Downloading${e!==null?` v${e}`:""}…${t!==null?` ${t}%`:""}`,clientRestartToInstall:e=>e!==null?`Restart to install v${e}`:"Restart to install the update",clientDownloadReady:e=>e!==null?`Version v${e} is ready — restart to install`:"The update is ready — restart to install",clientUpdateFailed:e=>`Client update failed: ${e}`,clientInstallFailed:e=>`Could not start the install: ${e}`,clientInstallConfirmTitle:"Restart and install the update",clientInstallConfirmBody:"PenguinHarness will restart to finish updating. Running tasks will be interrupted.",clientInstallConfirmAction:"Restart now",clientUnsupportedDev:"A dev run does not update itself",clientUnsupportedNonAppImage:"Only the AppImage build updates itself on Linux — update a package install through your package manager"},notify:{taskCompleteTitle:"Task completed",taskCompleteBody:e=>`"${e}" has finished — click to view`},common:{save:"Save",cancel:"Cancel",close:"Close",create:"Create",delete:"Delete",edit:"Edit",settings:"Settings",confirm:"Confirm",loading:"Loading…",saved:"Saved",saving:"Saving…",noChangesToSave:"No changes to save",confirmSaveTitle:"Save changes",confirmSaveBody:"Save these changes? They will be written to the configuration files on the server.",none:"(none)",retry:"Retry",unknownError:"Request failed, please try again later",requiredField:"This field is required",copied:"Copied",moreInfo:"More info",moreInfoAbout:e=>`More info: ${e}`,name:"Name",username:"Username",role:"Role",actions:"Actions",created:"Created",cost:"Cost",time:"Time"},auth:{usernameHint:"2–32 chars: starts with a lowercase letter; lowercase letters, digits and underscores only",password:"Password",passwordHint:"At least 8 characters",showPassword:"Show password",hidePassword:"Hide password",login:"Sign in",logout:"Sign out",admin:"Admin",defaultAdminNote:"First run: sign in as the built-in admin “admin” with the initial password printed in the server startup output (looks like penguin-1234), then change it soon",forgotAdminNote:"Forgot the admin password? Stop the server and run penguin server reset-admin-password to issue a fresh initial one"},account:{changePassword:"Change password",oldPassword:"Current password",oldPasswordHint:"The built-in admin's initial password is printed in the server startup output (looks like penguin-1234)",newPassword:"New password",confirmPassword:"Confirm new password",passwordMismatch:"New passwords do not match",initialPasswordBanner:"This account is using its initial password. Please change it soon.",changeNow:"Change now"},admin:{users:"Users",roleAdmin:"Admin",roleUser:"User",createUser:"Add user",initialPassword:"Initial password",initialPasswordFlag:"initial password",defaultProjectNote:e=>`A default Project will be created: ${e}`,resetPassword:"Reset password",resetPasswordTitle:e=>`Reset password for ${e}`,resetPasswordNote:"All sign-in sessions of this user will be revoked; they must sign in with the new password",deleteUserTitle:e=>`Delete user ${e}`,deleteUserConfirm:e=>`This deletes user ${e} and every Project they own (including data directories). This cannot be undone.`},project:{switcher:"Project",create:"New Project",createTitle:"New Project",id:"Project id",idHint:"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",idPrefixHint:"The id is prefixed with your username and a hyphen; append lowercase letters, digits or underscores. Cannot be changed later.",displayName:"Display name",displayNameHint:"Leave empty to use the Project id as the name",settings:"Project settings",settingsTitle:"Project settings",members:"Members",addMember:"Add member",removeMember:"Remove",chatDefaultsTitle:"New chat defaults",chatDefaultsHint:"Prefilled defaults for every new chat: agent, working directory, approval mode, thinking level and default model.",chatDefaultsAgent:"Agent",chatDefaultsNotSet:"Not set",chatDefaultsApprovalNotSet:"Not set (defaults to allow all)",chatDefaultsThinkingNotSet:"Not set (follow the agent's config)",chatDefaultsModelHint:"Same default model as the Models page",settingsTabGeneral:"General",settingsTabMembers:"Members",settingsTabDefaults:"Defaults",settingsTabSecurity:"Security policy",projectIdLabel:"Project ID",deleteProjectDesc:"The project directory is removed recursively and cannot be recovered.",commandPolicyInfo:"The command text is normalized for whitespace and quoting, then matched against each enabled rule's regular expression; a hit is refused outright whatever the approval mode allows. It is an accident guardrail: a command assembled at run time is not covered.",commandPolicyEnable:"Enable policy",commandPolicyEnableDesc:"When off, no rule blocks anything.",commandPolicyRules:"Rules",commandPolicyRestore:"Restore defaults",commandPolicyAddRule:"Add rule",commandPolicyEditRule:"Edit",commandPolicyApplyRule:"Apply",commandPolicyEmpty:"No rules.",commandPolicyOn:"Enabled",commandPolicyOff:"Disabled",commandPolicyRuleName:"Name",commandPolicyRulePattern:"Regular expression",commandPolicyRuleDesc:"Description",commandPolicyInvalidPattern:"Invalid regular expression",deleteProject:"Delete Project",deleteConfirm:"Delete this Project? Its directory will be removed recursively and cannot be recovered.",deleteLastForbidden:"This is the last Project on this account; create another Project before deleting it",deleteDefaultForbidden:"default_project is shared with the CLI and cannot be deleted from the web",noCredentialTitle:"No model credential configured",noCredentialBody:"The default model of this Project has no API key yet. Configure it on the Models page before chatting.",goToModels:"Go to Models",later:"Later"},agent:{listTitle:"Agents",create:"Create agent",createTitle:"Create agent",id:"Agent id",idHint:"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",nameHint:"Leave empty to use the agent id as the name",description:"Description",createSkills:"Skills",createSkillsPlaceholder:"No skills selected",createSkillsPicked:e=>`${e} skill${e===1?"":"s"} selected`,createSkillsHint:"Installed into the agent at creation; add or remove them later in its Skills tab.",createSkillsEmpty:"The skill library has nothing to install.",createDirSkills:"Import Skills from a project directory",createDirSkillsPick:"No directory selected",createDirSkillsHint:"Pick a project directory to read the Skills under its .agents/skills and .claude/skills",createDirSkillsEmpty:"This directory carries no installable Skills",createDirSkillsFound:e=>`${e} skill${e===1?"":"s"} found in this directory`,createDirSkillsClear:"Clear the selected directory",createSnapshot:"Initialize from a snapshot",createSnapshotPick:"Choose a snapshot package",createSnapshotHint:"Pick an exported Agent State snapshot package (.tar.gz) to start the new agent from its state; name and description left empty keep the package's values.",createSnapshotSkillsOff:"The snapshot package carries its own skills, so skill seeding is unavailable.",createSnapshotClear:"Remove the selected package",sessionCount:e=>`${e} session${e===1?"":"s"}`,toolCount:e=>`${e} tool${e===1?"":"s"}`,vaultKeyCount:e=>`${e} vault key${e===1?"":"s"}`,scheduleCount:e=>`${e} scheduled task${e===1?"":"s"}`,memoryCount:e=>e===1?"1 memory":`${e} memories`,updatedAt:"Last modified",activity:e=>`${e}-day session activity`,settings:"Agent settings",backToList:"Back to Agents",tabOverview:"Overview",tabPrompt:"System Prompt",tabMemory:"Memory",tabRuntime:"Runtime",tabTools:"Tools",tabSkills:"Skills",tabVault:"Vault",tabSchedules:"Schedules",stateDir:"State path",copyStateDir:"Copy State path",agentsMd:"AGENTS.md",systemPrompt:"system_prompt template",placeholdersTitle:"Available placeholders (click to insert)",insertPlaceholder:"Insert at the system_prompt cursor",placeholders:[["{{AGENTS_MD}}","Injects the AGENTS.md content"],["{{VAULT}}","Injects the vault block (vault.prompt with the key-name list); empty when its toggle is off"],["{{SKILLS}}","Injects the skills block (skills.prompt with installed-skill metadata); empty when its toggle is off"],["{{MEMORY}}","Injects the memory block: memory.prompt plus memory.workspace_prompt (persistent workspaces only); empty when memory is off"],["{{SCHEDULES}}","Injects the scheduled-tasks block (schedules.prompt with the task-name roster); empty when its toggle is off"],["{{PLATFORM}}","Runtime platform"],["{{OS_VERSION}}","Operating system version"],["{{SHELL}}","Shell used to run commands"],["{{DATE}}","Current date"],["{{PROJECT_DIR}}","PenguinHarness app data root — all agents' data and project-level data; not the task working directory"],["{{AGENT_ID}}","Current agent id"],["{{CWD}}","Absolute Workspace path"],["{{PROVIDER}}","Model provider group"],["{{MODEL_ID}}","Upstream model id"],["{{SESSION_ID}}","Current Session id"]],maxTurns:"max_turns (max turns per Task, -1 = unlimited)",maxTokens:"model.max_tokens",thinkingLevel:"model.thinking_level",thinkingLevelOptions:[["","Send no override — keep whatever is currently configured."],["low","Enables a lower tier of extended reasoning."],["medium","Enables a medium tier of extended reasoning (the default tier for a newly created agent)."],["high","Enables a higher tier of extended reasoning; slower responses."],["xhigh","Enables an extended tier of reasoning beyond high; identical to high on some models."],["max","Enables the deepest tier of extended reasoning; slowest and identical to xhigh on some models."]],thinkingLevelNoneKept:"Stored legacy tier: new selections no longer offer the off tier (many models cannot disable thinking).",timeoutMs:"model.timeoutMs",timeoutMsHint:"Per-request timeout, ms",compaction:"Context compaction",maxContextLength:"max_context_length",maxContextLengthHint:"Context threshold that triggers compaction",maxSessionTurns:"max_session_turns",maxSessionTurnsHint:"Turn threshold that triggers compaction",compactionMode:"mode (compaction strategy)",compactionModeOptions:[["","Send no override — keep whatever is currently configured."],["summarize","Summarizes the old context with the model, then continues from that summary in a fresh window (default)."],["discard","Drops the old context without summarizing; the next turn starts fresh in a new window."]],compactionPrompt:"prompt (summarization prompt)",maxTurnsInvalid:"max_turns must be > 0 or -1",timeoutInvalid:"timeoutMs must be > 0 or -1",toolFieldInvalid:(e,t)=>`${e}: ${t} must be a positive integer or -1`,toolPermission:"permission",permissionReadLabel:"Read-only",permissionReadDescription:"Only reads. Auto-approved when the approval mode is read-only.",permissionReadWriteLabel:"Read & write",permissionReadWriteDescription:"Can modify things. Needs manual confirmation when the approval mode is read-only.",toolTimeout:"timeoutMs",toolMaxOutput:"maxOutputLength",toolCallDescription:"call_description",callDescriptionHint:"call_description: when on (the default), the tool's schema keeps the optional description argument — a model-written sentence about each call, shown to the user while it runs; when off, the argument is filtered out of the schema at assembly. Only tools whose parameters declare a description property can be toggled.",mcpServers:"MCP Servers",mcpDesc:"Connect external MCP Servers: their tools join this agent's toolset as mcp__<name>__<tool>. Changes in this block save immediately.",mcpEmpty:"No MCP Servers configured yet",mcpAdd:"Add MCP Server",mcpEditTitle:"Edit MCP Server",mcpRemove:"Remove",mcpName:"name",mcpNameHint:"Tool-name prefix: mcp__<name>__<tool>; letters, digits, _ and - only",mcpTransport:"transport",mcpTransportStdio:"Local process: spawns command and talks over stdin/stdout",mcpTransportHttp:"Streamable HTTP: the current spec's remote transport",mcpTransportSse:"Legacy HTTP+SSE: kept for servers that have not migrated",mcpTarget:"command / url",mcpCommand:"command",mcpArgs:"args",mcpArgsHint:"One argument per line",mcpEnv:"env",mcpEnvHint:"One KEY=value per line; the Agent vault is not injected into MCP Server processes",mcpCwd:"cwd",mcpCwdHint:"Leave empty to use the Session's Workspace",mcpUrl:"url",mcpHeaders:"headers",mcpHeadersHint:"One Header-Name: value per line (auth headers such as Authorization)",mcpPermission:"permission",mcpPermissionAuto:"auto",mcpPermissionAutoLabel:"Auto (readOnlyHint)",mcpPermissionAutoDescription:"Each tool gets the level its own readOnlyHint annotation implies: read-only when it declares one, read & write otherwise.",mcpPermissionReadDescription:"Treat every tool of this server as read-only, whatever it declares. Auto-approved when the approval mode is read-only.",mcpPermissionReadWriteDescription:"Treat every tool of this server as read & write, whatever it declares. Needs manual confirmation when the approval mode is read-only.",mcpPermissionHint:"Only the read-only approval mode reads this level; allow-all, deny-all and always-ask ignore it. It never restricts what the server itself can do — marking a server read-only that is not one only drops the confirmation read-only mode would have asked for.",mcpConnectTimeout:"connectTimeoutMs",mcpBudgetsHint:"Leave empty for defaults: connectTimeoutMs is the connect + tool-discovery budget (default 10000); timeoutMs / maxOutputLength bound every tool of this Server.",mcpNameInvalid:"Letters, digits, _ and - only, starting with a letter or digit",mcpUrlInvalid:"Must be a valid http(s) URL",mcpLineInvalid:e=>`Line ${e} is not valid`,mcpNumberInvalid:"Must be an integer > 0",mcpDuplicateName:"A server with this name already exists",mcpTest:"Test connection",mcpTesting:"Testing…",mcpTestOk:(e,t)=>{const n=t!==void 0?` (${(t/1e3).toFixed(1)}s)`:"";return e===0?`Connected, but the server exposes no tools${n}`:`Connected — ${e} tool${e===1?"":"s"}${n}`},mcpTestFail:e=>`Connection failed: ${e}`,mcpTestAllConfirm:e=>`Connects to ${e===1?"the configured MCP server":`each of the ${e} configured MCP servers`} in turn and runs tool discovery (real connections, nothing is saved); results land on each row.`,mcpTestAllStart:"Start test",mcpTestPending:"Testing…",mcpTestBadge:(e,t)=>`${e} tool${e===1?"":"s"}${t!==void 0?` · ${(t/1e3).toFixed(1)}s`:""}`,mcpTestBadgeFail:"Connection failed",mcpDeleteTitle:"Delete MCP Server",mcpDeleteConfirm:e=>`Delete MCP Server "${e}"? Its tools stop being available from the next Session on.`,defaultValue:"(default)",deleteAgent:"Delete agent",builtinUndeletable:"Built-in agents cannot be deleted",deleteConfirm:e=>`Delete agent "${e}"? Its directory (including all Traces) will be removed recursively and cannot be recovered.`,stateTitle:"Agent State",stateVersion:"Agent State version",transferDesc:"Export the current Agent State snapshot (tar.gz); importing overwrites the whole directory and adopts the version inside the package.",exportSnapshot:"Export snapshot",importSnapshot:"Import snapshot",importing:"Importing…",importDone:e=>`Import finished, Agent State version v${e}`,importConflictTitle:"Version conflict",importConflictBody:"The snapshot's version is not newer than the current one; importing will overwrite the existing Agent State. Continue?",resetConfigTitle:"Restore default configuration",resetConfigAction:"Restore default configuration",resetConfigConfirmBody:"This overwrites the agent's existing configuration with the current defaults: the custom system prompt, tool list, model/compaction settings and MCP servers are all replaced, keeping only name and description. Like a skill update this cannot be undone. Continue?",resetConfigDone:"Configuration restored to the current defaults",kernelTitle:"Kernel",kernelLegacy:"predates kernel versioning",kernelOutdatedHint:"Kernel update available",kernelUpdateNeeded:"Kernel update needed",kernelUpToDate:"Up to date",kernelUpdateTitle:"Update kernel",kernelCurrent:"current",kernelLatest:"latest",kernelUpdateAction:"Update kernel",kernelUpdateConfirmBody:"Settings tabs you have not customized will be updated to the current built-in defaults; a tab you have edited stays unchanged in full and is listed in the result. Name, description, the State version and MCP servers are unaffected. Continue?",kernelUpdateDone:(e,t)=>t>0?`Kernel updated to ${e}; ${t} tab(s) now follow the new defaults`:`Kernel updated to ${e}; every tab was already current or kept as customized`,kernelUpdateKeptIntro:"Kept whole because customized:",kernelListSeparator:", "},models:{title:"Models",addCustom:"Add custom model",addToGroup:"Add model",editTitle:"Model settings",addTitle:"Add model (OpenAI protocol)",addTitleVendor:"Add model",addProtocolHint:"New models use the OpenAI Chat Completions protocol; set the base URL to a compatible endpoint",vendorProtocolHint:e=>`Only ${e}'s official API protocol is supported; use a custom model group for OpenAI-compatible endpoints.`,autoRouteNone:"This model ID cannot be routed with the current provider protocol. If it uses an OpenAI-compatible endpoint, move it to Custom.",useCustomGroup:"Move to Custom",addGroup:"Add group",addGroupTitle:"Add group",addGroupDesc:`User-defined groups share Custom semantics. "Import models" detects (or lets you pick) the endpoint's protocol, then imports every model it serves in one go; "Create only" adds models one by one after the group. Groups live on model entries — the group appears once its first model is saved.`,groupModeCreate:"Create only",groupModeImport:"Import models",groupImportAll:"Import all models",groupImportNeedUrl:"Fill in a valid base URL first (http/https)",groupImportKeyHint:"Leave empty to read the protocol's OPENAI_* / ANTHROPIC_* env vars",groupImportListing:"Fetching model list…",groupImportSaving:e=>`Importing ${e} models…`,groupImportUnsupported:"This protocol cannot list models — add them manually",groupImportFailed:"Fetching the model list failed",groupImportEmpty:"No models to import from this endpoint",groupImported:(e,t)=>t>0?`Imported ${e} models, skipped ${t} entries`:`Imported ${e} models`,groupNameLabel:"Group name",groupNameHint:"Starts with a lowercase letter / digit; may contain - and _",groupNameInvalid:"Group names may only use lowercase letters, digits, - and _ (starting with a letter or digit), up to 32 characters",groupNameExists:"This name is taken by a built-in group or an existing entry",groupEmptyHint:"No models in this group yet; use “Add model” to create one",deleteGroup:"Delete group",deleteGroupTitle:"Delete group",deleteGroupConfirm:(e,t)=>`Delete the group “${e}”? Its ${t} models and their API key configuration will be removed.`,groupDeleted:e=>`Group deleted (${e} models)`,searchPlaceholder:"Search models: id / name / provider",noSearchResults:"No matching models",syncCatalog:"Sync presets",syncCatalogHint:"Update preset models from the built-in catalog: add missing entries and reset differing ones to the catalog's fields; locally added models and API keys are left untouched",syncDone:(e,t)=>`Presets synced: ${e} added, ${t} updated`,syncUpToDate:"Presets are already up to date",homepage:"Model page",speedTest:"Speed test",speedTestTitle:"Speed test",speedTestConfirm:e=>`This sends one real request to each of the ${e} models in this group, one at a time, to measure time-to-first-token (TTFT) and output rate (TPS). It consumes a small amount of API quota. Continue?`,speedTestStart:"Start",speedPending:"Testing…",speedFailed:"Test failed",ttftTitle:"Time to first token (TTFT)",tpsTitle:"Output rate (TPS)",modelCount:e=>`${e} model${e===1?"":"s"}`,modelId:"Model ID",modelIdHint:"The upstream API model id, e.g. gpt-5.5",displayName:"Display name",displayNameHint:"Defaults to the model ID",providerGroup:"Group",contextWindow:"Context window",tokenUnit:"Token",contextWindowHint:"Leave empty if unknown",maxTokens:"Max output tokens",maxTokensHint:"Empty = inherit agent setting",maxTokensTitle:"Caps output tokens per request; leave empty to inherit the agent setting — lower it for small-context models",maxTokensInvalid:"Must be a positive integer",clientTypeLocked:e=>`Protocol: ${e} (kept as configured; not editable)`,protocol:"Protocol",protocolNames:{"openai-responses":"OpenAI Responses","ant-messages":"Anthropic Messages","openai-chat":"OpenAI Chat Completions"},protocolTriggerTitle:e=>`Protocol: ${e}. Click to change it.`,protocolUnset:"Select protocol",detectProtocol:"Detect",detectProtocolHint:"Probe the base URL and apply the protocol it serves",detecting:"Detecting…",detectedProtocol:e=>`Detected ${e}; applied`,detectFailedBody:"Could not detect the protocol. Please check the API key and the base URL.",detectFellBack:"Protocol not detected; saved as OpenAI Chat Completions",addProtocolHintDetect:"Pick the protocol from the base URL field's suffix (OpenAI Responses / Anthropic Messages / OpenAI Chat Completions), or press Detect to probe the endpoint — saving without one detects it first",addTitleCustom:"Add model",vision:"Vision support",detectVision:"Detect",detectingVision:"Testing…",detectVisionHint:"Send one tiny test image to see whether this model accepts images (uses your API key)",detectVisionNeedsId:"Fill in the model id first, then detect.",detectVisionOk:"This model accepts images; vision turned on",detectVisionNo:"This model does not accept images; vision left off",visionOffProxyHint:"Images are read via the vision proxy model",fastMode:"Fast mode",fastModeHint:"Faster output, billed at the provider's premium tier; the Cost center still counts it at the entry's standard prices",fastModeUnsupported:"This model does not support fast mode — turn it off, or its requests will fail",fastModeConfirmTitle:"Enable fast mode",fastModeConfirmBody:"Fast mode is billed at the provider's premium price list (MiniMax charges 1.5x standard; OpenAI and Anthropic publish separate premium rates). The entry's recorded per-token prices are not adjusted, so the Cost center will under-report this usage.",fastModeConfirmPreview:"Anthropic's fast mode is a limited research preview: until your organization is granted access, requests return a 429 rate-limit error.",fastModeBadge:"Fast",visionBadge:"Vision",freeBadge:"Free",visionModelBadge:"Proxy vision",setVisionModel:"Set as proxy vision model",visionModelHint:"Describes images via describe_image for models without vision",priceUnitShort:"/M tok",testConnection:"Test connection",testing:"Testing…",testOk:e=>`Connected (${e} ms)`,testFailed:e=>`Failed: ${e}`,priceCacheRead:"Cache read price",priceCacheWrite:"Cache write price",priceOutput:"Output price",currency:"Currency",currencyUsd:"USD $",currencyCny:"CNY ¥",apiKey:"API key",apiKeyKeepHint:"Leave empty to keep the current key",apiKeyEnvHint:e=>`Leave empty to use the ${e} env var`,keyConfigured:"Key configured",clearApiKey:"Clear stored API key",baseUrl:"Custom base URL",baseUrlHint:"Leave empty to use the provider default",baseUrlSuffixTitle:"The client appends the protocol path shown at the field's right edge to the base URL",baseUrlRequired:"A base URL is required",contextWindowDefaultHint:e=>`Defaults to ${e} if empty`,confirmDeleteTitle:"Delete model",confirmDelete:e=>`Delete "${e}"? Its configuration and API key will be removed.`,groupApiKey:"Set key",groupApiKeyTitle:e=>`Set the API key for ${e}`,groupApiKeyHint:e=>`Applies to all ${e} models in this group; leave empty to keep them unchanged.`,getApiKey:"Manage keys",getModelIds:"Get model IDs",groupKeyApplied:e=>`API key set for ${e} models`,oauthKey:"Authorize key",oauthTitle:e=>`Authorize a new ${e} API key`,oauthIntro:(e,t)=>`A new API key will be created on your ${e} account and written to all ${t} models in this group, replacing the key they use now.`,oauthAuthorize:"Open authorization page",oauthWaiting:"Waiting for the authorization to finish in the other tab…",oauthApplied:e=>`New API key set for ${e} models`,oauthManualSwitch:"Page can't redirect back? Enter the code by hand",oauthCallbackSwitch:"Go back to the automatic redirect",oauthManualHint:"Open the authorization page, then paste the one-time code it shows you here.",oauthCodeLabel:"Authorization code",oauthSubmitCode:"Submit code",oauthTimedOut:"The authorization never came back. Enter the code by hand, or start again.",oauthRetry:"Start again",oauthErrors:{invalid_request:"The authorization request was rejected. Start again.",code_rejected:"That authorization is no longer valid: it expired or was already used. Start again.",upstream_failed:"The provider returned no usable key. Start again.",unreachable:"The provider could not be reached. Check the network and start again.",apply_failed:"A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console."},providerEnvNotes:{zhipu:"Defaults to the Z.AI global endpoint (api.z.ai); keys from bigmodel.cn need base URL https://open.bigmodel.cn/api/paas/v4",moonshot:"Defaults to the China endpoint (api.moonshot.cn); keys from platform.kimi.com need base URL https://api.moonshot.ai/v1"},confirmVisionModelTitle:"Set as proxy vision model",confirmVisionModel:e=>`Make "${e}" the proxy vision model? Models without vision will read images through it via describe_image.`,confirmSaveTitle:"Save model settings",confirmSave:e=>`Save the changes to "${e}"?`,confirmDefaultTitle:"Set as default model",confirmDefault:e=>`Make "${e}" the default model? New sessions will use it by default.`,default:"Default",setDefault:"Set as default model",remove:"Delete model",readOnlyHint:"Members have read-only access; only owners can change models and credentials",empty:"No models configured yet",noKey:"No key",readFromEnv:"Read from environment variable",showModelsWithoutKey:e=>`Show model${e===1?"":"s"} without a key (${e})`,modelIdExists:"This model id already exists",pricingAllOrNone:"Fill all three prices",pricingInvalid:"Must be a number",contextWindowInvalid:"Must be a number"},memory:{desc:"Long-term memory across Sessions (stored in agent_state/memory/): the agent saves what is worth keeping as it works, and you can also just ask it to remember something. User memory applies to all of this agent's sessions; workspace memory is kept per workspace. Memory edits are made by the agent in chat. Turning the switch off only stops memory from being used and deletes nothing.",enable:"Enable memory",userScope:"User memory",templateMissing:"The prompt template has no {{MEMORY}} placeholder, so memory never enters the context.",insertPlaceholder:"Insert the {{MEMORY}} placeholder",insertPlaceholderDone:"Inserted",promptSection:"Memory prompt",promptSectionHint:"What the template's {{MEMORY}} placeholder expands to. The main prompt is injected into every session; the workspace addendum only in sessions with a persistent workspace.",promptLabel:"Main prompt",workspacePromptLabel:"Workspace addendum",promptPlaceholders:[["{{USER_MEMORY_INDEX}}","Content of the user MEMORY.md index (at most 200 lines and 25,000 characters total)"],["{{WORKSPACE_MEMORY_INDEX}}","Content of the workspace MEMORY.md index (at most 200 lines and 25,000 characters total); effective only in the workspace addendum"],["{{WORKSPACE_MEMORY_DIR}}","Absolute path of the current workspace's memory directory; effective only in the workspace addendum"]],insertToken:"Insert at the cursor",itemCount:e=>e===1?"1 item":`${e} items`,emptyScope:"No memories for this Workspace yet — the agent saves what is worth keeping as it works",emptyUserScope:'No user memories yet — say "remember …" in a chat and the agent will save it',add:"Add",addScopeLabel:e=>`Add to ${e}`,addTitle:"Add memory",addWhy:"The agent organizes and saves memories in a chat: fill in the content, open a new conversation, and the agent does the rest.",addContentLabel:"Content or source to remember",addContentPlaceholder:"Paste the content to remember, or a file path / URL",addPromptLead:{user:"Please turn the following into memories in user memory:",workspace:"Please turn the following into memories in this workspace's memory:"},view:"View",edit:"Edit",editTitle:"Edit memory",editWhy:"Content edits are made by the agent in a chat: confirm the prompt to open a new conversation, and the agent updates the memory file and its MEMORY.md index together.",editRequirementLabel:"What to change",editRequirementPlaceholder:"Describe the change — you can finish it in the chat",editPromptLabel:"Prompt preview",editCopyPrompt:"Copy prompt",editOpenChat:"Open a new chat",delete:"Delete",deleteTitle:"Delete this memory?",deleteConfirm:e=>`This deletes "${e}" and removes its index line from MEMORY.md. This cannot be undone.`,deleteDone:"Deleted",editPromptLead:e=>`Please update a memory: ${e}`,editPromptTail:"What to change: ",exportScope:"Export",exportScopeHint:"Download every memory in this group as one JSON document",exportScopeLabel:e=>`Export ${e}`,importScope:"Import",importScopeHint:"Restore memories into this group from an exported JSON document",importScopeLabel:e=>`Import into ${e}`,importTitle:"Import memories",importWhy:"Reads a memory group exported from this or another agent: a JSON file holding the memories and the group's MEMORY.md index.",importFile:(e,t)=>`${e} — ${t} memories`,importModeLabel:"When this group already has a memory of the same name",importModeSkip:"Keep the one that is here",importModeSkipHint:"Adds only what this group does not have. Nothing here is lost.",importModeOverwrite:"Take the file's version",importModeOverwriteHint:"Memories the file does not carry are left alone.",importModeReplace:"Replace the whole group",importModeReplaceHint:"Every memory the file does not carry is deleted.",importAction:"Import",importInvalidFile:"This file is not a memory export.",importEmptyFile:"This file carries no memories.",importConfirmTitle:"Confirm the import",importWillOverwrite:e=>`${e.length} memories will be overwritten: ${e.join(", ")}`,importWillRemove:e=>`${e.length} memories will be deleted: ${e.join(", ")}`,importWillReplaceIndex:"The group's MEMORY.md index will be replaced.",importIrreversible:"This cannot be undone.",importDone:(e,t,n)=>`Imported: ${e} added, ${t} replaced, ${n} deleted`,importNothingNew:"Nothing to import — this group already has every memory in the file"},vault:{desc:"Environment variables owned by this agent (stored in agent_state/.vault.toml), injected into the environment of its shell commands (exec_command); key names are shared with the model, values never enter the model context. Subagents use their own vaults and do not inherit this one. Saved changes take effect from the next task (a task already running is unaffected).",key:"Name",value:"Value",valueMasked:"Value (masked)",add:"Add",addTitle:"Add variable",remove:"Remove",deleteTitle:"Delete variable",deleteConfirm:e=>`Delete variable "${e}"? Its value cannot be recovered.`,overwriteTitle:"Overwrite existing variable",overwriteConfirm:e=>`"${e}" already exists — saving will overwrite its value, which cannot be recovered.`,empty:"No variables configured yet",readOnlyHint:"Members are read-only; only the owner can edit the vault",keyHint:"Letters, digits and underscores; must not start with a digit",keyInvalid:"Invalid name: only letters, digits and underscores, not starting with a digit",valueRequired:"Value must not be empty",injection:{enable:"Enable vault",templateMissing:"The prompt template has no {{VAULT}} placeholder, so the vault section never enters the context.",legacyTemplate:"The template still carries the legacy hardcoded # Vault section: one-click migration replaces it in place with the {{VAULT}} placeholder, wording unchanged, after which it is editable below.",insertPlaceholder:"Insert the {{VAULT}} placeholder",migrate:"Migrate to the {{VAULT}} placeholder",promptSection:"Vault prompt",promptSectionHint:"What the template's {{VAULT}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{VAULT_KEYS}}",'Vault key-name list (one "- KEY" line per key, names only — values are never injected; empty when no keys)']]}},schedule:{desc:"Scheduled tasks (agent_state/schedule/*.toml): the prompt is sent to the target Session on schedule; files can also be edited by hand, and changes made here take effect immediately.",readOnlyHint:"Members are read-only; only the owner can modify schedules",colStatus:"Status",colPeriod:"Period",colTarget:"Target",colFireTimes:"Next / last fired",colQueued:"Queue",statusNames:{active:"Active",disabled:"Disabled",expired:"Expired",done:"Done",missed:"Missed",invalid:"Invalid"},queued:"Queued",once:"One-off",newSession:"New session",invalidFiles:"Files that failed to parse (skipped by the scheduler)",empty:"No scheduled tasks yet",enable:"Enable",disable:"Disable",addTitle:"New scheduled task",editTitle:e=>`Edit scheduled task "${e}"`,nameHint:"The file name (without .toml); cannot be changed later",prompt:"Prompt",enabled:"Enabled",startAt:"Start at",endAt:"End at",period:"Period",periodPlaceholder:"30m / 12h / 7d; leave empty for a one-off task",target:"Target",targetNew:"New session each time",targetSession:"Bound Session",sessionId:"Session",chooseSession:"Choose a Session to bind",sessionSearch:"Search title or Session id…",sessionNoMatch:"No matching Session",sessionEmpty:"This agent has no Sessions yet",workspace:"Workspace",model:"Model",modelDefault:"Project default",deleteTitle:"Delete scheduled task",deleteConfirm:e=>`Delete scheduled task "${e}"?`,injection:{enable:"Enable schedules",templateMissing:"The prompt template has no {{SCHEDULES}} placeholder, so the scheduled-tasks section never enters the context.",insertPlaceholder:"Insert the {{SCHEDULES}} placeholder",promptSection:"Schedules prompt",promptSectionHint:"What the template's {{SCHEDULES}} placeholder expands to — teaches the model to manage scheduled tasks with its file tools; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{SCHEDULE_LIST}}",'Current task-name list (one "- name" line per task; an empty-roster note when none exist)']]}},skills:{pageTitle:"Skill library",pageDesc:"Built-in skill library: browse, quick-start a chat, or install to agents.",quickInvoke:"Quick start",quickInvokeText:e=>`use the ${e} skill`,quickInvokeNeedsInstall:"Install this skill on the current agent first to quick-start",selectAll:"Select all",selectNone:"Select none",selectedCount:e=>`${e} selected`,manageInstall:"Manage installs",manageInstallTitle:e=>`Manage installs: ${e}`,install:"Install",installed:"Installed",uninstall:"Uninstall",skillCount:e=>e===1?"1 skill":`${e} skills`,usedByAgents:e=>e===0?"not used yet":e===1?"used by 1 agent":`used by ${e} agents`,installedToast:(e,t)=>`Installed ${e} to ${t}`,updateOutdated:e=>`Update available: update ${e} agent install(s)`,updateAction:"Update",updateConfirmTitle:e=>`Update ${e}`,updateConfirmWarning:e=>`Updating ${e} reinstalls the library copy over each agent's installed files — any local edits to the installed skill are lost. Export a backup first if you need them.`,updatedToast:(e,t)=>`Updated ${e} to the latest version (${t} agent(s))`,uninstalledToast:(e,t)=>`Uninstalled ${e} from ${t}`,uninstallConfirmTitle:e=>`Uninstall ${e}`,uninstallConfirmBody:(e,t)=>`Uninstall ${e} from ${t}? Its installed files (local edits included) will be deleted.`,agentTabDesc:"Skills installed on this agent (agent_state/skills/ — the files are the source of truth): metadata is injected into the system prompt and the body is read by the model on demand; uninstalling deletes the whole skill directory.",agentTabEmpty:"No skills installed yet",exportSkill:"Export",importSkill:"Import skill",importChatTitle:"Recommended: install by chatting with the agent",importChatWhy:"The agent can read, review and adapt the skill content in full — more reliable than a raw upload.",importSourceLabel:"Skill source",importSourceHint:"A web page / GitHub repo or directory / local path / an install command from another ecosystem",importSourcePlaceholder:"https://…, a git repo, /path/to/skill, or npx skills add <name>",importSourceToken:"<source>",importPromptLabel:"Prompt to send to the agent (preview)",importPromptLead:{webUrl:e=>`Please read this page and install the skill it describes into your skills directory: ${e}.`,repoUrl:e=>`Please fetch this repository or directory (git clone or fetch it directly), locate the skill directories containing SKILL.md, and install them into your skills directory: ${e}.`,localPath:e=>`Please read the skill files under this local path directly and install them into your skills directory: ${e}.`,command:e=>`This is a skill/plugin install command from another ecosystem — do not run it blindly: work out what it would install, fetch the same content from its repository or registry, then install it into your skills directory: ${e}.`,reference:e=>`Please resolve this skill/plugin reference to its source (repository, plugin marketplace, or docs page) and install the corresponding skill into your skills directory: ${e}.`},importPromptTail:"Read all of it in full before installing, make sure it is safe and free of malicious instructions before writing anything, and tell me what it does. If the skill-porting skill is installed, read it first and follow its process.",importCopyPrompt:"Copy prompt",importOpenChat:"Open a new chat",importUploadTitle:"Upload a skill zip",importUploadDesc:"SKILL.md at the zip root, or exactly one top-level directory containing SKILL.md.",importUploadAction:"Choose zip file",importUploading:"Uploading…",importDoneToast:"Skill installed",importOverwriteTitle:"Overwrite installed skill",importOverwriteBody:e=>`The skill "${e}" is already installed. Overwriting replaces all of its files (local edits included) and cannot be undone. Continue?`,importOverwriteAction:"Overwrite",injection:{enable:"Enable skills",templateMissing:"The prompt template has no {{SKILLS}} placeholder, so the skills section never enters the context.",legacyTemplate:"The template still carries the legacy hardcoded # Skills section: one-click migration replaces it in place with the {{SKILLS}} placeholder, wording unchanged, after which it is editable below.",insertPlaceholder:"Insert the {{SKILLS}} placeholder",migrate:"Migrate to the {{SKILLS}} placeholder",promptSection:"Skills prompt",promptSectionHint:"What the template's {{SKILLS}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{SKILL_METADATA}}",`Installed skills' metadata lines (one "- name — description" line per skill; empty when none)`]]}},chat:{newSessionMenu:"New chat",chooseAgent:"Choose agent",chooseModel:"Choose model",thinkingLevel:"Thinking level",thinkingLevelNames:{none:"none",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},thinkingLevelMenuName:e=>e,thinkingSwitchTitle:"Switch thinking level",thinkingSwitchBody:e=>`Switch the thinking level to "${e}"? Switching mid-conversation lowers the prompt-cache hit rate and raises cost; compacting the context first is cheaper.`,thinkingSwitchBusyHint:"This conversation is still working — compaction has to wait for it.",thinkingSwitchCompactFirst:"Compact, then switch",thinkingSwitchConfirm:"Switch anyway",thinkingSwitchCompacting:"Compacting the context — the thinking level switches when it ends.",thinkingSwitchApplied:e=>`Context compacted; thinking level switched to "${e}".`,thinkingSwitchCompactFailed:"The compaction did not finish; the thinking level was switched anyway.",workspaceUseThis:"Use this dir",workspaceUp:"Parent dir",workspaceNoSubdirs:"No subdirectories",workspaceAuto:"Temporary workspace",workspaceClear:"Use a temporary workspace instead",workspaceDirInvalid:"Directory does not exist or is inaccessible; reverted",groupByWorkspace:"Group by workspace",groupByAgent:"Group by agent",groupByTime:"Group by time",timeGroups:{day:"Past day",month:"Past month",earlier:"Earlier"},searchSessions:"Search chats",searchSessionsPlaceholder:"Search chats…",searchClear:"Clear search",searchNoMatches:"No matches among loaded chats",listSettings:"List options",groupModeSection:"Group by",sortModeSection:"Sort by",sortManual:"Manual order",sortRecent:"Most recent",newWorkspaceEntity:"New workspace",workspaceMenu:"Workspace options",renameWorkspace:"Rename workspace",renameWorkspaceLabel:"Name",renameWorkspaceHint:"Leave empty to use the folder name",deleteWorkspace:"Remove workspace",deleteWorkspaceConfirm:e=>`Remove "${e}"? This only removes the workspace group from the sidebar — the directory on disk and existing chats are untouched, and it can be re-added anytime.`,tempWorkspaces:"Temporary workspaces",newSessionInWorkspace:"New chat in this workspace",draftSubtitle:"The self-evolving agent that excels at AI development tasks",exampleFolders:{webapps:"Build web apps",agents:"Build and optimize agents",schedules:"Create scheduled tasks"},exampleFillHint:"Click to fill the composer — edit it if you like, then send",shortcuts:{folder:"My shortcuts",new:"New shortcut",newFromComposer:"Starts from whatever is in the composer",createTitle:"New shortcut",editTitle:"Edit shortcut",titleLabel:"Name",titleHint:e=>`At most ${e} characters`,promptLabel:"Prompt",promptHint:e=>`At most ${e} characters`,promptInfo:"Clicking this shortcut puts the text into the composer verbatim and sends nothing; Skills stay a separate pick in the composer.",titleTooLong:e=>`The name may be at most ${e} characters`,promptTooLong:e=>`The prompt may be at most ${e} characters`,deleteTitle:"Delete shortcut",deleteConfirm:e=>`Delete "${e}"? The shortcut disappears from every device you use.`},exampleTasks:{game:{label:"2D penguin sled game",desc:"A cute Antarctic penguin sleds over rocks, easy start with a gentle difficulty ramp — a 2D pure-frontend mini game",prompt:"Build a cute Antarctic penguin sledding 2D game: press Space to jump over the rocks coming up on the ice; start easy and forgiving, with sled speed and obstacle density ramping up smoothly and gradually over time (no sudden spikes), live scoring, and hitting a rock ending the run with one-click restart. A 2D side-scroller with a cute cartoon look, pure frontend (a single HTML file is fine), styled per the web-design skill. When done, test it in a browser once, confirm the first few seconds are easy to clear, and tell me how to open it and how to play."},gamecenter:{label:"A mini-game center built by multiple agents",desc:"Ten pure-frontend games with no repeated mechanics, built in parallel behind one index page",prompt:`Build a web mini-game center with multiple agents working in parallel: 10 pure-frontend games with no two sharing the same mechanic, plus an index page.
|
|
68
|
+
3. 根据投资策略、历史市场与当前指标选择投资动作。`},agentOptimization:{label:"优化通用决策智能体的准确率",desc:"根据已有评测结果改进 Agent,并验证新版本是否真正提升",prompt:"请使用 `agent-optimization`,根据 Frozen Benchmark 优化决策 Agent。\n\n- test_agent_id:`finite_choice_agent`\n- benchmark_id:`contextual-choice-adaptation`\n- capability_direction:提高信息不完整、规则冲突和有限选项决策中的稳定性\n- runs:`3`\n- desired_score:`>=95`\n- candidate_round_limit:`5`"},dailyPlan:{label:"每天早 9 点的计划对话",desc:"每天 09:00 在同一个会话里聊当天计划,并回顾昨天的进展",prompt:"建一个定时任务:每天早上 9 点在这个会话里和我聊今天的计划。先回看上文说清昨天定的事做完了多少、哪些卡住,再给我一份排好序的今日候选、每条一句理由,我确认后写成清单。"},githubDigest:{label:"每天汇总 GitHub 项目状态",desc:"定时跑一遍仓库的 Issue、PR 与 CI,日报结尾给出按优先级排序的建议",prompt:"建一个定时任务:每天早上用 gh 汇总一个 GitHub 仓库的 Issue、PR 与 CI 状态,挑出停滞的、待评审的和挂掉的,结尾给出按优先级排序的建议,每条说清为什么排在这个位置。"},memoryReview:{label:"每周五晚回顾并记录 Memory",desc:"周五傍晚一起过一遍这周值得长期记住的事,确认后由你写进 Memory",prompt:"建一个定时任务:每周五傍晚在这个会话里和我过一遍这周值得长期记住的事。先看已有记忆索引避免重复,再逐条问我该记什么、要不要改已有的,我确认后你写进 Memory。"}},sessionList:"Session",defaultSessionTitle:"新对话",agent:"Agent",model:"Model",workspace:"Workspace",workspaceHint:"留空自动创建临时工作区;指定时必须是服务器上已存在的目录",workspaceHintShort:"留空自动创建临时工作区",approvalMode:"审批模式",approvalModeNames:{"allow-all":"全部放行","deny-all":"全部拒绝","read-only":"放行只读","always-ask":"总是询问"},approvalModes:{"allow-all":"全部放行(allow-all)","deny-all":"全部拒绝(deny-all)","read-only":"放行只读(read-only)","always-ask":"总是询问(always-ask)"},statusRunning:"运行中",statusCompacting:"压缩中",statusCompletedUnread:"运行完毕,未读",pendingApprovals:e=>`${e} 个待审批`,jumpToLatest:"回到最新消息",loadingEarlier:"正在加载更早的对话…",loadEarlierRetry:"更早的对话加载失败,点击重试",historyBeginning:"已是对话开头",outlineTitle:"对话索引",outlineTickLabel:(e,t)=>`第 ${e} 轮:${t}`,outlineNoText:"(图片或附件)",outlineAnswering:"回答生成中…",inputPlaceholder:"输入消息,Enter 发送,Shift+Enter 换行,可粘贴图片",inputPlaceholderShort:"输入消息…",steerPlaceholder:"给运行中的 Agent 留言,随下一轮对话送达",steerPlaceholderShort:"给运行中的 Agent 留言…",steerSend:"发送给运行中的 Agent",steerQueuedIndicator:"插话已排队,将随下一轮送达",steerQueuedItem:e=>`插话已排队,将随下一轮送达:${e}`,userSteering:"用户插话",steerModeLabel:"运行中发送方式",steerModeSteer:"插话",steerModeSteerHint:"立即插话:随下一轮对话送达运行中的 Agent",steerModeFollowUp:"排队",steerModeFollowUpHint:"排队跟进:本轮结束后自动作为新消息发送",followUpPlaceholder:"排队为下一条消息,本轮结束后自动发送",followUpPlaceholderShort:"排队为下一条消息…",followUpSend:"排队为下一条消息",followUpQueuedChip:e=>`${e} 条跟进消息已排队,本轮结束后自动发送`,followUpQueuedItem:e=>`跟进消息已排队,本轮结束后自动发送:${e}`,recallQueued:"撤回",recallQueuedTitle:"撤回到输入框,编辑后重新发送",send:"发送",stop:"停止",compact:"压缩上下文",approve:"允许",deny:"拒绝",decisionAllow:"已批准",decisionDeny:"已拒绝",decisionManual:"手动",decisionAuto:"自动",decisionPolicy:"策略",thinking:"思考",subagent:"子会话",subagentRunning:"运行中",aborted:e=>{const t=e?.errorCode==="user_abort"?"用户中断":e?.errorCode==="backoff_interrupted"?"重试等待中被中断":e?.errorCode==="compaction_interrupted"?"压缩过程中被中断":e?.errorCode??e?.reason??"",n=t?`${t}${e?.errorMessage?`:${e.errorMessage}`:""}`:"";return`[已中断]${n?`:${n}`:""}`},reconnect:(e,t,n,s,o,c)=>{const u=c??e,f=u==="timeout"?"连接超时或网络中断":u==="malformed"?"响应不完整或无法解析":u==="network"?"网络或服务暂时不可用":u==="failed"?"模型服务返回错误":"请求失败",p=t==="gaveUp"?`第 ${n} 次尝试后放弃${o?`:${o}`:""}`:t==="retried"?`已发起第 ${n} 次重试`:s!==void 0?`第 ${n} 次重试,${s} 秒后发起…`:`正在发起第 ${n} 次重试…`;return`[重试] ${f},${p}`},llmError:e=>`[错误]:模型请求错误${e?`:${e}`:""}`,reconnectRetryNow:"立即重试",reconnectGiveUp:"放弃",imageAlt:"用户上传的图片",toolImageAlt:"工具输出的图片",imagesAsPathHint:"当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 describe_image 查看)",infoPanel:"Session 信息",sessionStats:"统计",sessionIdLabel:"Session id",copySessionId:"复制 Session id",processList:"会话进程",processStop:"停止",processExited:"已退出",processRemove:"移除",processRemoveHint:"移除该条目——该进程已捕获的输出也会一并丢弃",runningServices:e=>`${e} 个运行中的服务`,statTokens:"Token 累计",statTotalTokens:"总 Token",statCacheHit:e=>`缓存命中率 ${e}`,statElapsed:"用时",statInput:"输入 tokens",statCached:"已缓存",statOutput:"输出 tokens",statTps:"输出 TPS",statParenOpen:"(",statParenClose:")",noSessions:"还没有 Session",emptyStream:"发送一条消息开始对话",historyLoadFailed:"历史消息加载失败",statsLabel:"统计信息",removeImage:"移除图片",openAgents:"智能体面板",workspacePanel:"工作区",filesInMessage:e=>`${e} 个文件`,imagesInMessage:e=>`${e} 张图片`,openPreview:"点击预览",showMoreFiles:e=>`显示其余 ${e} 个文件`,showLess:"收起",memoryChangesTitle:e=>`${e} 条记忆更新`,memoryScopeWorkspace:e=>`工作区记忆(${e})`,memoryOpWrite:"写入",memoryOpEdit:"编辑",memoryViewTitle:"记忆",memoryChangedMark:"本次对话已更改",memoryContentUnavailable:"无法加载内容(文件可能已被移动或删除)",memoryRowOpen:"查看内容",memoryBack:"返回列表",memoryEmptyAll:"还没有任何记忆——在对话里说「记住……」即可让 agent 保存",openAgentMemory:"在 Agent 设置中管理",memoryShowMore:e=>`显示其余 ${e} 条`,prevGroupPage:"上一页分组",nextGroupPage:"下一页分组",groupPagePosition:(e,t)=>`第 ${e} 页,共 ${t} 页`,contextUsage:"上下文占用",contextUnknown:"上下文占用:压缩后待下次请求回报",contextComposition:"上下文构成",contextPartSystemPrompt:"系统提示词",contextPartToolDefs:"工具定义",contextPartUserMessages:"用户消息",contextPartAssistantMessages:"模型消息",contextPartToolRequests:"工具请求",contextPartToolResults:"工具结果",contextTopTools:"工具用量 Top 5",contextCompactAt:e=>`压缩阈值 ${e}`,contextTopToolsHint:"按每个工具的调用与结果所占上下文排序(工具定义计入「工具定义」一项)",contextUnknownHint:"刚压缩过,占用待下次请求回报,届时才能给出构成",contextBreakdownEmpty:"当前上下文还没有可统计的内容",contextBreakdownFailed:"读取上下文构成失败",slashHint:"输入 / 使用命令",switchAgent:"交给其他 Agent,发送时开启新会话",switchAgentTitle:"选择 Agent",agentSearchPlaceholder:"搜索 Agent:id / 名称",agentsNoMatch:"没有匹配的 Agent",handoffTargetTitle:e=>`发送后交接给 ${e}`,handoffRemove:"移除交接目标",skillsSelect:"技能",skillRemove:"移除技能",skillsSearchPlaceholder:"搜索技能",skillsNoMatch:"没有匹配的技能",skillsEmptyHint:"暂无已装技能,去技能库添加",skillsAutoMessage:e=>`使用 ${e.join("、")} 技能`,handoffFrom:e=>`由 ${e} 的对话交接而来`,handoffBack:e=>e?`回到原对话:${e}`:"回到原对话",switchModel:"切换模型,发送时开启新会话延续本对话",switchModelTitle:"切换模型",modelSwitchTargetTitle:e=>`发送后换用 ${e} 延续本对话`,modelSwitchRemove:"移除切换模型",modelSwitchBusyHint:"本轮结束后才能切换模型:新会话要从当前会话的记录接续",modelSwitchFrom:e=>e?`已切换模型(原为 ${e}),延续原会话`:"已切换模型,延续原会话",modelSwitchAutoMessage:"换用新模型继续这段对话",modelLockedHint:"输入 /model 切换模型",scheduledFrom:e=>`由定时任务「${e}」触发`,backgroundDone:(e,t)=>{const n=e==="command"?"后台命令":"后台任务";return t==="stopped"?`${n}已停止`:t==="completed"?`${n}完成`:`${n}失败`},emptyGreeting:"开始一段新对话",mcpConnectTitle:"MCP 连接",mcpServerList:e=>e.join("、"),mcpConnectResult:(e,t)=>{const n=[];return(e>0||t.length===0)&&n.push(`发现 ${e} 个工具`),t.length>0&&n.push(`不可用:${t.join("、")}`),n.join(";")},mcpToolsCount:e=>`${e} 个工具`,mcpServerFailed:"连接失败",mcpConnectAborted:"已中断,下次发送时重新连接",compactionTitle:e=>e==="discard"?"清空":"压缩",compactionFailed:(e,t)=>{if(e==="aborted")return"已中断,保留当前上下文";const n=t!==void 0?`(${t})`:"";return e==="retryable"?`失败${n},保留当前上下文,下次触发时重试`:e==="fatal"?`失败${n},保留当前上下文,需修复模型配置后重试`:`失败${n},保留当前上下文`},unknownTool:"(未知工具)",workRunning:"运行中",workDone:"运行完毕",workGroupSteps:e=>`${e} 步`,approvalWaiting:"待审批",copyCode:"复制代码",copyReply:"复制回复",forkSession:"从这里分叉对话",forkSessionConfirmBody:"将把这段对话(截至这条回复)复制为一个新对话,原对话保持不变。",forkSessionConfirmAction:"分叉",forkSessionFailed:"无法定位这条回复,请刷新后重试。",copyMessage:"复制消息",deleteSession:"删除对话",renameSession:"重命名对话",renameSessionLabel:"标题",deleteSessionConfirm:e=>`确定删除「${e}」?该对话的消息与 Trace 将被移除,且不可恢复。`,draftGroup:"草稿",draftUntitled:"(无标题草稿)",deleteDraft:"删除草稿",deleteDraftConfirm:e=>`确定删除草稿「${e}」?未发送的内容将被丢弃。`,archiveSession:"归档",unarchiveSession:"取消归档",pinSession:"置顶",unpinSession:"取消置顶",pinnedSession:"已置顶",moreActions:"更多",loadMore:"更多",expandRestSessions:e=>`展开其余 ${e} 个对话`,loadMoreSessions:"加载更多会话",folderGroups:{subagent:e=>`子智能体(${e})`,schedule:e=>`定时任务(${e})`,archived:e=>`已归档(${e})`},skillsBanner:e=>`使用技能:${e.join("、")}`,attachedFilesBanner:e=>`附加文件:${e.join("、")}`,plusMenu:"更多输入方式",uploadImage:"上传图片",uploadImageDesc:"为本条消息附加图片",uploadFile:"上传文件",uploadFileDesc:"文件存入会话临时目录,模型按路径读取",removeFile:"移除文件",attachmentTooLarge:(e,t)=>`${e} 超过 ${t}MB 上限,未添加。`,dropFilesTitle:"松开以添加附件",dropFilesDesc:"图片与文件将添加到输入框",dropFilesGoalHint:"目标模式仅支持附加图片,文件未添加。",goalMode:"目标模式",goalModeDesc:"循环运行直至目标完成",goalBudgetLabel:"Token 预算",goalBudgetUnlimited:"预算不限",goalBudgetValue:e=>`预算 ${e}`,goalBudgetPlaceholder:"例如 500k",goalBudgetHint:"支持 k/m 后缀;留空表示预算不限",goalBudgetInvalid:"无效预算:应为正数,可带 k/m 后缀(500k、2m)",goalBudgetSave:"保存预算",goalRemove:"退出目标模式",goalRoundBanner:e=>`目标 · 第 ${e} 轮`,goalRoundImages:e=>`${e} 张附图`,goalProgress:(e,t)=>`第 ${e} 轮 · tokens ${t}`,goalStatus:{active:"进行中",complete:"已完成",blocked:"受阻",budget_limited:"预算耗尽",aborted:"已中断"}},feishu:{intro:"绑定后,发给飞书机器人的消息会进入本对话,AI 的回复会以纯文本发回飞书。需要一个开通了机器人能力、订阅了接收消息事件(长连接方式)的飞书自建应用。",appId:"App ID",appSecret:"App Secret",appSecretKeepHint:"留空保持已保存的 App Secret 不变",clearSecret:"清除已存 App Secret",baseDomain:"API 域名",baseDomainHint:"飞书为 https://open.feishu.cn,Lark 为 https://open.larksuite.com",invalidDomain:"域名需为 http(s):// 地址",testMessageNoChat:"先在飞书中给机器人发一条消息,机器人才知道要发到哪个会话",setupSteps:["在飞书开发者后台创建一个企业自建应用","为应用开通机器人能力","订阅「接收消息」事件,事件订阅方式选择「长连接」","在「凭证与基础信息」页取得 App ID 与 App Secret,填入上方表单","发布应用版本并通过审核,然后在飞书中给机器人发一条消息"]},telegram:{intro:"绑定后,发给 Telegram 机器人的消息会进入本对话,AI 的回复会以纯文本发回 Telegram。用 @BotFather 创建机器人并粘贴其 Bot Token 即可,无需公网地址。",botToken:"Bot Token",botTokenKeepHint:"留空保持已保存的 Bot Token 不变",clearToken:"清除已存 Bot Token",invalidToken:"Bot Token 形如「数字:密钥」,由 @BotFather 签发",testMessageNoChat:"先在 Telegram 中给机器人发一条消息,机器人才知道要发到哪个会话",setupSteps:["在 Telegram 中打开 @BotFather,发送 /newbot 创建机器人","按提示取名后,复制 @BotFather 返回的 Bot Token,填入上方表单","在 Telegram 中找到这个机器人,给它发一条消息"]},messaging:{panelTitle:"消息软件",bindAction:"消息软件绑定…",dialogTitle:"消息软件绑定",channelLabel:"渠道",channelName:{feishu:"飞书",telegram:"Telegram"},tutorial:"前往教程",console:"前往开发者后台",enabled:"启用连接",saveBeforeEnable:"先保存凭证,再启用连接",test:"测试连接",testing:"测试中…",testOk:e=>`连接成功(${e}ms)`,testOkAs:(e,t)=>`连接成功,机器人为 ${e}(${t}ms)`,testFail:e=>`连接失败:${e}`,sendTestMessage:"发送测试消息",sendingTestMessage:"发送中…",testMessageSent:"测试消息已发送",statusLabel:"连接状态",status:{disconnected:"未连接",connecting:"连接中",connected:"已连接",error:"连接错误"},otherEnabledHint:e=>`同一会话只能启用一个渠道:先停用${e}连接`,credentialMissingHint:"先填写并保存凭证,再启用连接",disableBeforeClearHint:"先停用连接,才能清除凭证",enabledIndicator:{feishu:"飞书连接已启用",telegram:"Telegram 连接已启用"},faqSetupTitle:"如何创建机器人",faqWhatTitle:"绑定后会发生什么",faqTroubleTitle:"常见问题",troubleNoChat:"「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",troubleConnError:"连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。",troubleOnePoller:"Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。"},subagentPanel:{topologyLabel:"调用关系",mainSessionNote:"主会话请在对话区查看",empty:"本次任务尚未派生子智能体",nodeRunning:"运行中",nodeDone:"已完成",openAsSession:"跳转到该会话",subagentGone:"该子会话已不存在,无法恢复"},files:{title:"文件",upload:"上传",download:"下载",openInNewTab:"新页面打开",previewNotIsolatedHint:"当前访问地址无法提供独立预览源,页面将以沙箱模式打开:localStorage、Cookie 与第三方 embed 不可用。经 127.0.0.1 或 localhost 访问,或配置 PENGUIN_PREVIEW_ORIGIN 即可解除。",refresh:"刷新",root:"根目录",empty:"空目录",previewUnsupported:"该类型不支持预览,请下载查看",uploaded:"已上传",overwriteTitle:"覆盖同名文件",overwriteConfirm:e=>`当前目录已存在以下 ${e} 个同名文件,上传将覆盖:`,loadFailed:"加载失败",previewTruncated:"内容过大,预览已截断,请下载查看完整文件",details:"详情",workspacePath:"Workspace 路径",htmlRendered:"渲染视图",htmlSource:"源码",backToList:"返回列表"},usage:{title:"成本与统计",today:"今日",last7d:"近 7 天",total:"累计",tokens:"Token",requests:"Requests",from:"起始日期",to:"结束日期",colCacheRead:"cache_read",colCacheWrite:"cache_write",colOutput:"output",uncostedNote:"* 只计入配置了价格的模型成本",filterAllAgents:"全部 Agent",filterAllModels:"全部模型",rangeLabel:"日期范围",rangeHour:"最近一小时",rangeDay:"最近一天",range7d:"近 7 天",range30d:"近 30 天",range90d:"近 90 天",rangeCustom:"自定义",chartRequestsByAgent:"各 Agent 请求与成功率",chartRequestsByModel:"各模型请求与成功率",legendSuccessRate:"成功率",chartTokenTrend:"Token 变化",chartCostTrend:"成本变化",legendOther:e=>`其他 ${e} 项`,bucketTotal:"合计",legendHitRate:"缓存命中率",empty:"暂无用量记录",errors:"异常",errorsTotal:"总数",errorsUnexpected:"未预期",errorsExpected:"预期内",errorsTopCode:"最常见",errorsColCode:"来源 · 错误码",errorsColKind:"类型",errorsColMessage:"消息",errorsEmpty:"暂无异常",errorsNewer:"较新",errorsOlder:"更早",errorsPageOf:(e,t,n)=>`第 ${e} / ${t} 页 · 共 ${n} 条`},traces:{timeline:"执行时间线",laneLLM:"模型",kindThinking:"思考",kindModelReply:"模型回复",kindToolGen:"工具调用生成",legendToolExec:"工具调用执行",legendOther:"其他",toolParams:"参数 Schema",requiredParam:"必填",legendApprovalWait:"审批等待",task:e=>`第 ${e} 轮`,globalSummary:"全局统计",tasksLabel:"轮次",messages:"消息",truncatedNote:(e,t)=>`仅展示前 ${e} / ${t} 条消息`,zoom:"缩放",zoomReset:"双击复位缩放",zoomOut:"缩小",zoomIn:"放大",linkHint:"鼠标移到时间线段或消息行即可联动高亮,点击时间线段跳转到对应消息;图例可高亮同类;拖动下方滑块平移/缩放",filesTitle:"Trace 文件",toolCalls:"工具调用",taskInput:"本轮输入 tokens",taskOutput:"本轮输出 tokens",cacheHit:"命中缓存",hitRate:"命中率",compactions:"压缩次数",inProgress:"进行中",systemPrompt:"系统提示词",toolDefs:e=>`工具定义(${e})`,exportFile:"导出"},benchmark:{title:"评估中心",selectBenchmark:"在左侧选择一个 Benchmark",emptyAgent:"该 Agent 暂无 Benchmark",caseCount:e=>`${e} 题`,trendTitle:e=>`${e}随时间变化`,cases:"题目",viewCase:"查看详情",taskMaterials:"任务材料",rubric:"评分标准",agentHidden:"被测 Agent 不可见",caseFileUnavailable:"案例文件暂时无法读取",evaluations:"评估明细",noEvaluations:"暂无评估记录",summaryLabel:"评估说明",legendUnlabeled:"未标注模型",colVersion:"版本",colModel:"模型 ID",colThinkingLevel:"推理强度",colScore:"Score",colDuration:"耗时",colCase:"题目",colRun:"运行",colSession:"Session"},errors:{networkError:"网络错误,请检查连接",modelCredentialMissing:e=>`模型 ${e} 还没有可用的 API key,请先在「模型」页为它配置`,noDefaultModel:"该 Project 还没有默认模型,请先在「模型」页添加模型并设为默认",byCode:{invalid_credentials:"用户名或密码错误。",too_many_attempts:"登录失败次数过多,请稍后重试。",password_mismatch:"当前密码不正确。",invalid_password:"密码至少 8 位。",admin_required:"仅管理员可执行此操作。",desktop_single_user:"桌面应用为单用户模式,用户管理不可用。",not_found:"资源不存在,或你没有访问权限。",internal:"服务器内部错误,请稍后重试。",agent_not_found:"该 Agent 已不存在。",unknown_agent:"该 Agent 不存在于本 Project。",agent_exists:"该 Agent id 已被占用。",agent_deleting:"该 Agent 正在删除中。",project_exists:"该 Project id 已被占用。",project_not_found:"该 Project 已不存在,或你没有访问权限。",cannot_delete_last_project:"这是最后一个 Project,不能删除。",user_exists:"该用户名已被占用。",user_not_found:"该用户已不存在。",cannot_delete_admin:"内置 admin 不可删除。",member_not_found:"该用户不是本 Project 的成员。",already_member:"该用户已是本 Project 的成员。",already_owner:"该用户已是本 Project 的所有者。",memory_import_confirm_required:"本次导入会覆盖或删除已有记忆,请确认后继续。",schedule_exists:"已存在同名定时任务。",schedule_not_found:"该定时任务已不存在。",unknown_skill:"该技能不在技能库中。",skill_too_large:"该技能目录过大,超出了导入限制。",file_not_found:"该文件已不存在。",not_pending:"该插话已随本轮送达模型,无法撤回。",follow_up_started:"该跟进消息已开始发送,无法撤回。",file_too_large:"文件过大。",too_many_files:"一条消息附加的文件过多。",payload_too_large:"请求体过大。",image_too_large:"图片过大,无法随对话发送。",dir_not_absolute:"目录必须是绝对路径。",dir_not_found:"该目录不存在或不可访问。",not_a_dir:"该路径不是目录。",path_not_found:"该路径不存在。",workspace_missing:"该 Session 的 Workspace 已不存在。",workspace_not_found:"该 Workspace 不存在或不是目录。",session_not_found:"该 Session 已不存在,或你没有访问权限。",session_deleting:"该 Session 正在删除中。",approval_not_found:"该授权请求已处理或已失效。",process_not_found:"该后台进程已结束或已被移除。",process_running:"该后台进程仍在运行,请先结束再移除。",memory_file_not_found:"该记忆文件已不存在。",memory_scope_not_found:"该记忆范围已不存在。",task_in_progress:"该 Session 已有任务在运行。",compacting:"该 Session 正在压缩上下文,暂不接受新的输入。",shutting_down:"服务正在关闭,请稍后重试。",compaction_not_configured:"该 Agent 没有配置上下文压缩。",nothing_to_compact:"当前上下文还没有可压缩的内容(尚未完成一轮对话)。",already_compacted:"刚刚压缩过,之后还没有新的对话,无需重复压缩。",version_conflict:"快照版本不高于当前版本。",invalid_title:"标题无效。",invalid_proxy_url:"代理地址无效:应为 http(s):// 或 socks5:// 代理 URL,或 主机[:端口]。",invalid_attachment_limit:"上传限制无效:请填写允许范围内的整数 MB,且合计不低于单个上限。",invalid_trace:"该文件不是有效的 Trace 文件。",trace_not_found:"该 Trace 文件已不存在。",trace_session_exists:"该 Agent 已存在同名 Session,无法导入重复的 Trace。",feishu_app_in_use:"该飞书应用已绑定到其他 Session,请先解除或换一个应用。",feishu_secret_required:"需要填写 App Secret。",feishu_not_bound:"该 Session 尚未绑定飞书。",feishu_no_chat:"尚未收到飞书消息:先在飞书中给机器人发一条消息。",feishu_send_failed:"飞书消息发送失败。",telegram_bot_in_use:"该 Telegram 机器人已绑定到其他 Session,请先解除或换一个机器人。",telegram_token_required:"需要填写 Bot Token。",telegram_token_invalid:"Bot Token 格式不正确:应形如「数字:密钥」。",telegram_not_bound:"该 Session 尚未绑定 Telegram。",telegram_no_chat:"尚未收到 Telegram 消息:先在 Telegram 中给机器人发一条消息。",telegram_send_failed:"Telegram 消息发送失败。",another_channel_enabled:"该会话已启用另一渠道的连接:先停用它,再启用当前渠道。",messaging_disable_before_clear:"先停用该渠道的连接,才能清除其凭证。"}}};let d=Uj;function K3(e){d=e}const W3={appName:"PenguinHarness",nav:{chat:"Chat",newChat:"New chat",agents:"Agents",skills:"Skills",models:"Models",usage:"Cost Center",traces:"Trajectories",benchmark:"Evaluation Center",lastConversation:"Last conversation",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",collapseGroup:"Collapse",expandGroup:"Expand",pinGroup:"Pin group",unpinGroup:"Unpin group"},terminal:{title:"Terminal",newShell:"New shell",killShell:"Kill this terminal",createFailed:"Could not start a terminal",noTerminalApi:"this server has no terminal API: the running runtime predates it. A hot push replaces the platform and Web App, but the terminal endpoints are runtime-owned — the runtime itself has to be updated (restarting will not help)",detach:"Open in new window",status:{connecting:"connecting",ready:"ready",exited:"exited",error:"error"},exitedWithCode:e=>`exit code ${e}`},dock:{addTab:"Add panel",closeTab:"Close panel",hideDock:"Hide sidebar",moveToRight:"Move to the right",moveToBottom:"Move to the bottom",resize:"Resize panel",rightDock:"Right sidebar",bottomDock:"Bottom panel",draftEmpty:"Available once the conversation starts",killConfirmTitle:"Close this terminal?",killConfirmBody:e=>`This ends the shell "${e}" — it cannot be restored.`},tracePanel:{empty:"No traces yet",emptyHint:"This session has not produced a Trace file yet",loadFailed:"Failed to load traces"},settings:{language:"Language",languageInfo:"Interface language; can follow the browser.",systemSettings:"System settings",groupPersonal:"Personal",groupServer:"Server",generalTitle:"General",appearanceTitle:"Appearance",accountTitle:"Account",importTrace:"Import Trace",importTraceInfo:"Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",importTraceProject:"Import into project",importTraceAgent:"Import into agent",importTracePick:"Choose file",importTraceRunning:"Importing…",importTraceDone:e=>`Trace imported into ${e}`,importTraceTooLarge:"The file exceeds the 14MB limit.",proxyTitle:"Proxy options",proxyInfo:"Server-global, and in force the moment it is saved — nothing to restart. Loopback addresses always go direct.",proxyForApp:"Application uses the proxy",proxyForAgent:"Agent environment uses the proxy",proxyAddress:"Proxy address",proxyAddressPlaceholder:"Empty = follow system proxy",uploadLimitsTitle:"Upload limits",attachmentMaxMb:"Max attachment size (MB)",attachmentTotalMb:"Max total per message (MB)",attachmentMaxMbHint:(e,t)=>`${e}–${t} MB`,attachmentTotalMbHint:(e,t)=>`${e}–${t} MB, and not below the per-file limit`,uploadLimitsInfo:(e,t)=>`A message may carry at most ${e} attachments. Images placed inline in the conversation keep a separate ${t}MB limit that this setting does not raise — an inline image enters the conversation and the Trace, where its size is paid again on every history page and resume.`,theme:"Theme",themeInfo:"Light or dark look of the app.",themeLight:"Light",themeDark:"Dark",followSystem:"System",terminalTheme:"Terminal theme",terminalThemeInfo:"Colors of the terminal panel; follows the app theme by default.",followAppTheme:"App",langZh:"中文",langEn:"English",fontSize:"Font size",fontSizeInfo:"Overall interface font size.",fontSmall:"S",fontMedium:"M",fontLarge:"L",accent:"Accent",accentInfo:"Interface accent color.",currencyInfo:"Display currency for prices; storage is always USD.",changePasswordInfo:"Change this account's sign-in password.",accentNames:{neutral:"Neutral",blue:"Blue",green:"Green",violet:"Violet",rose:"Rose",amber:"Amber"}},update:{lastUpdated:e=>`Last updated ${e}`,newVersionBadge:"New version available",newVersion:e=>`New version v${e} available`,updatesAvailable:"Updates available",checkNow:"Check for updates",checking:"Checking…",foundNew:e=>`New version v${e} found — use the update entry to install`,upToDate:"You're on the latest version",checkFailed:"Update check failed — try again later",checkDisabled:"Update checks are disabled (PENGUIN_UPDATE_CHECK=off)",releaseNotes:"Release notes",updateNow:"Update now",updating:"Updating…",updated:"Update complete — restart the service to apply",restartHint:"Restart by re-running penguin web (or penguin server) in a terminal",failed:"Update failed",unsupported:"This install cannot be updated from the web UI",confirmBody:"Downloads the latest release and installs it into the install directory on the server (the data directory is not touched). Restart the service afterwards for the update to take effect.",adminOnly:"Only an administrator can run the update from here.",clientCheckNow:"Check for updates",clientFoundNew:e=>e!==null?`Version v${e} found — downloading in the background…`:"New version found — downloading in the background…",clientDownloading:(e,t)=>`Downloading${e!==null?` v${e}`:""}…${t!==null?` ${t}%`:""}`,clientRestartToInstall:e=>e!==null?`Restart to install v${e}`:"Restart to install the update",clientDownloadReady:e=>e!==null?`Version v${e} is ready — restart to install`:"The update is ready — restart to install",clientUpdateFailed:e=>`Client update failed: ${e}`,clientInstallFailed:e=>`Could not start the install: ${e}`,clientInstallConfirmTitle:"Restart and install the update",clientInstallConfirmBody:"PenguinHarness will restart to finish updating. Running tasks will be interrupted.",clientInstallConfirmAction:"Restart now",clientUnsupportedDev:"A dev run does not update itself",clientUnsupportedNonAppImage:"Only the AppImage build updates itself on Linux — update a package install through your package manager"},notify:{taskCompleteTitle:"Task completed",taskCompleteBody:e=>`"${e}" has finished — click to view`},common:{save:"Save",cancel:"Cancel",close:"Close",create:"Create",delete:"Delete",edit:"Edit",settings:"Settings",confirm:"Confirm",loading:"Loading…",saved:"Saved",saving:"Saving…",noChangesToSave:"No changes to save",confirmSaveTitle:"Save changes",confirmSaveBody:"Save these changes? They will be written to the configuration files on the server.",none:"(none)",retry:"Retry",unknownError:"Request failed, please try again later",requiredField:"This field is required",copied:"Copied",moreInfo:"More info",moreInfoAbout:e=>`More info: ${e}`,name:"Name",username:"Username",role:"Role",actions:"Actions",created:"Created",cost:"Cost",time:"Time"},auth:{usernameHint:"2–32 chars: starts with a lowercase letter; lowercase letters, digits and underscores only",password:"Password",passwordHint:"At least 8 characters",showPassword:"Show password",hidePassword:"Hide password",login:"Sign in",logout:"Sign out",admin:"Admin",defaultAdminNote:"First run: sign in as the built-in admin “admin” with the initial password printed in the server startup output (looks like penguin-1234), then change it soon",forgotAdminNote:"Forgot the admin password? Stop the server and run penguin server reset-admin-password to issue a fresh initial one"},account:{changePassword:"Change password",oldPassword:"Current password",oldPasswordHint:"The built-in admin's initial password is printed in the server startup output (looks like penguin-1234)",newPassword:"New password",confirmPassword:"Confirm new password",passwordMismatch:"New passwords do not match",initialPasswordBanner:"This account is using its initial password. Please change it soon.",changeNow:"Change now"},admin:{users:"Users",roleAdmin:"Admin",roleUser:"User",createUser:"Add user",initialPassword:"Initial password",initialPasswordFlag:"initial password",defaultProjectNote:e=>`A default Project will be created: ${e}`,resetPassword:"Reset password",resetPasswordTitle:e=>`Reset password for ${e}`,resetPasswordNote:"All sign-in sessions of this user will be revoked; they must sign in with the new password",deleteUserTitle:e=>`Delete user ${e}`,deleteUserConfirm:e=>`This deletes user ${e} and every Project they own (including data directories). This cannot be undone.`},project:{switcher:"Project",create:"New Project",createTitle:"New Project",id:"Project id",idHint:"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",idPrefixHint:"The id is prefixed with your username and a hyphen; append lowercase letters, digits or underscores. Cannot be changed later.",displayName:"Display name",displayNameHint:"Leave empty to use the Project id as the name",settings:"Project settings",settingsTitle:"Project settings",members:"Members",addMember:"Add member",removeMember:"Remove",chatDefaultsTitle:"New chat defaults",chatDefaultsHint:"Prefilled defaults for every new chat: agent, working directory, approval mode, thinking level and default model.",chatDefaultsAgent:"Agent",chatDefaultsNotSet:"Not set",chatDefaultsApprovalNotSet:"Not set (defaults to allow all)",chatDefaultsThinkingNotSet:"Not set (follow the agent's config)",chatDefaultsModelHint:"Same default model as the Models page",settingsTabGeneral:"General",settingsTabMembers:"Members",settingsTabDefaults:"Defaults",settingsTabSecurity:"Security policy",projectIdLabel:"Project ID",deleteProjectDesc:"The project directory is removed recursively and cannot be recovered.",commandPolicyInfo:"The command text is normalized for whitespace and quoting, then matched against each enabled rule's regular expression; a hit is refused outright whatever the approval mode allows. It is an accident guardrail: a command assembled at run time is not covered.",commandPolicyEnable:"Enable policy",commandPolicyEnableDesc:"When off, no rule blocks anything.",commandPolicyRules:"Rules",commandPolicyRestore:"Restore defaults",commandPolicyAddRule:"Add rule",commandPolicyEditRule:"Edit",commandPolicyApplyRule:"Apply",commandPolicyEmpty:"No rules.",commandPolicyOn:"Enabled",commandPolicyOff:"Disabled",commandPolicyRuleName:"Name",commandPolicyRulePattern:"Regular expression",commandPolicyRuleDesc:"Description",commandPolicyInvalidPattern:"Invalid regular expression",deleteProject:"Delete Project",deleteConfirm:"Delete this Project? Its directory will be removed recursively and cannot be recovered.",deleteLastForbidden:"This is the last Project on this account; create another Project before deleting it",deleteDefaultForbidden:"default_project is shared with the CLI and cannot be deleted from the web",noCredentialTitle:"No model credential configured",noCredentialBody:"The default model of this Project has no API key yet. Configure it on the Models page before chatting.",goToModels:"Go to Models",later:"Later"},agent:{listTitle:"Agents",create:"Create agent",createTitle:"Create agent",id:"Agent id",idHint:"2–64 chars: starts with a lowercase letter; lowercase letters, digits and underscores only. Cannot be changed later.",nameHint:"Leave empty to use the agent id as the name",description:"Description",createSkills:"Skills",createSkillsPlaceholder:"No skills selected",createSkillsPicked:e=>`${e} skill${e===1?"":"s"} selected`,createSkillsHint:"Installed into the agent at creation; add or remove them later in its Skills tab.",createSkillsEmpty:"The skill library has nothing to install.",createDirSkills:"Import Skills from a project directory",createDirSkillsPick:"No directory selected",createDirSkillsHint:"Pick a project directory to read the Skills under its .agents/skills and .claude/skills",createDirSkillsEmpty:"This directory carries no installable Skills",createDirSkillsFound:e=>`${e} skill${e===1?"":"s"} found in this directory`,createDirSkillsClear:"Clear the selected directory",createSnapshot:"Initialize from a snapshot",createSnapshotPick:"Choose a snapshot package",createSnapshotHint:"Pick an exported Agent State snapshot package (.tar.gz) to start the new agent from its state; name and description left empty keep the package's values.",createSnapshotSkillsOff:"The snapshot package carries its own skills, so skill seeding is unavailable.",createSnapshotClear:"Remove the selected package",sessionCount:e=>`${e} session${e===1?"":"s"}`,toolCount:e=>`${e} tool${e===1?"":"s"}`,vaultKeyCount:e=>`${e} vault key${e===1?"":"s"}`,scheduleCount:e=>`${e} scheduled task${e===1?"":"s"}`,memoryCount:e=>e===1?"1 memory":`${e} memories`,updatedAt:"Last modified",activity:e=>`${e}-day session activity`,settings:"Agent settings",backToList:"Back to Agents",tabOverview:"Overview",tabPrompt:"System Prompt",tabMemory:"Memory",tabRuntime:"Runtime",tabTools:"Tools",tabSkills:"Skills",tabVault:"Vault",tabSchedules:"Schedules",stateDir:"State path",copyStateDir:"Copy State path",agentsMd:"AGENTS.md",systemPrompt:"system_prompt template",placeholdersTitle:"Available placeholders (click to insert)",insertPlaceholder:"Insert at the system_prompt cursor",placeholders:[["{{AGENTS_MD}}","Injects the AGENTS.md content"],["{{VAULT}}","Injects the vault block (vault.prompt with the key-name list); empty when its toggle is off"],["{{SKILLS}}","Injects the skills block (skills.prompt with installed-skill metadata); empty when its toggle is off"],["{{MEMORY}}","Injects the memory block: memory.prompt plus memory.workspace_prompt (persistent workspaces only); empty when memory is off"],["{{SCHEDULES}}","Injects the scheduled-tasks block (schedules.prompt with the task-name roster); empty when its toggle is off"],["{{PLATFORM}}","Runtime platform"],["{{OS_VERSION}}","Operating system version"],["{{SHELL}}","Shell used to run commands"],["{{DATE}}","Current date"],["{{PROJECT_DIR}}","PenguinHarness app data root — all agents' data and project-level data; not the task working directory"],["{{AGENT_ID}}","Current agent id"],["{{CWD}}","Absolute Workspace path"],["{{PROVIDER}}","Model provider group"],["{{MODEL_ID}}","Upstream model id"],["{{SESSION_ID}}","Current Session id"]],maxTurns:"max_turns (max turns per Task, -1 = unlimited)",maxTokens:"model.max_tokens",thinkingLevel:"model.thinking_level",thinkingLevelOptions:[["","Send no override — keep whatever is currently configured."],["low","Enables a lower tier of extended reasoning."],["medium","Enables a medium tier of extended reasoning (the default tier for a newly created agent)."],["high","Enables a higher tier of extended reasoning; slower responses."],["xhigh","Enables an extended tier of reasoning beyond high; identical to high on some models."],["max","Enables the deepest tier of extended reasoning; slowest and identical to xhigh on some models."]],thinkingLevelNoneKept:"Stored legacy tier: new selections no longer offer the off tier (many models cannot disable thinking).",timeoutMs:"model.timeoutMs",timeoutMsHint:"Per-request timeout, ms",compaction:"Context compaction",maxContextLength:"max_context_length",maxContextLengthHint:"Context threshold that triggers compaction",maxSessionTurns:"max_session_turns",maxSessionTurnsHint:"Turn threshold that triggers compaction",compactionMode:"mode (compaction strategy)",compactionModeOptions:[["","Send no override — keep whatever is currently configured."],["summarize","Summarizes the old context with the model, then continues from that summary in a fresh window (default)."],["discard","Drops the old context without summarizing; the next turn starts fresh in a new window."]],compactionPrompt:"prompt (summarization prompt)",maxTurnsInvalid:"max_turns must be > 0 or -1",timeoutInvalid:"timeoutMs must be > 0 or -1",toolFieldInvalid:(e,t)=>`${e}: ${t} must be a positive integer or -1`,toolPermission:"permission",permissionReadLabel:"Read-only",permissionReadDescription:"Only reads. Auto-approved when the approval mode is read-only.",permissionReadWriteLabel:"Read & write",permissionReadWriteDescription:"Can modify things. Needs manual confirmation when the approval mode is read-only.",toolTimeout:"timeoutMs",toolMaxOutput:"maxOutputLength",toolCallDescription:"call_description",callDescriptionHint:"call_description: when on (the default), the tool's schema keeps the optional description argument — a model-written sentence about each call, shown to the user while it runs; when off, the argument is filtered out of the schema at assembly. Only tools whose parameters declare a description property can be toggled.",mcpServers:"MCP Servers",mcpDesc:"Connect external MCP Servers: their tools join this agent's toolset as mcp__<name>__<tool>. Changes in this block save immediately.",mcpEmpty:"No MCP Servers configured yet",mcpAdd:"Add MCP Server",mcpEditTitle:"Edit MCP Server",mcpRemove:"Remove",mcpName:"name",mcpNameHint:"Tool-name prefix: mcp__<name>__<tool>; letters, digits, _ and - only",mcpTransport:"transport",mcpTransportStdio:"Local process: spawns command and talks over stdin/stdout",mcpTransportHttp:"Streamable HTTP: the current spec's remote transport",mcpTransportSse:"Legacy HTTP+SSE: kept for servers that have not migrated",mcpTarget:"command / url",mcpCommand:"command",mcpArgs:"args",mcpArgsHint:"One argument per line",mcpEnv:"env",mcpEnvHint:"One KEY=value per line; the Agent vault is not injected into MCP Server processes",mcpCwd:"cwd",mcpCwdHint:"Leave empty to use the Session's Workspace",mcpUrl:"url",mcpHeaders:"headers",mcpHeadersHint:"One Header-Name: value per line (auth headers such as Authorization)",mcpPermission:"permission",mcpPermissionAuto:"auto",mcpPermissionAutoLabel:"Auto (readOnlyHint)",mcpPermissionAutoDescription:"Each tool gets the level its own readOnlyHint annotation implies: read-only when it declares one, read & write otherwise.",mcpPermissionReadDescription:"Treat every tool of this server as read-only, whatever it declares. Auto-approved when the approval mode is read-only.",mcpPermissionReadWriteDescription:"Treat every tool of this server as read & write, whatever it declares. Needs manual confirmation when the approval mode is read-only.",mcpPermissionHint:"Only the read-only approval mode reads this level; allow-all, deny-all and always-ask ignore it. It never restricts what the server itself can do — marking a server read-only that is not one only drops the confirmation read-only mode would have asked for.",mcpConnectTimeout:"connectTimeoutMs",mcpBudgetsHint:"Leave empty for defaults: connectTimeoutMs is the connect + tool-discovery budget (default 10000); timeoutMs / maxOutputLength bound every tool of this Server.",mcpNameInvalid:"Letters, digits, _ and - only, starting with a letter or digit",mcpUrlInvalid:"Must be a valid http(s) URL",mcpLineInvalid:e=>`Line ${e} is not valid`,mcpNumberInvalid:"Must be an integer > 0",mcpDuplicateName:"A server with this name already exists",mcpTest:"Test connection",mcpTesting:"Testing…",mcpTestOk:(e,t)=>{const n=t!==void 0?` (${(t/1e3).toFixed(1)}s)`:"";return e===0?`Connected, but the server exposes no tools${n}`:`Connected — ${e} tool${e===1?"":"s"}${n}`},mcpTestFail:e=>`Connection failed: ${e}`,mcpTestAllConfirm:e=>`Connects to ${e===1?"the configured MCP server":`each of the ${e} configured MCP servers`} in turn and runs tool discovery (real connections, nothing is saved); results land on each row.`,mcpTestAllStart:"Start test",mcpTestPending:"Testing…",mcpTestBadge:(e,t)=>`${e} tool${e===1?"":"s"}${t!==void 0?` · ${(t/1e3).toFixed(1)}s`:""}`,mcpTestBadgeFail:"Connection failed",mcpDeleteTitle:"Delete MCP Server",mcpDeleteConfirm:e=>`Delete MCP Server "${e}"? Its tools stop being available from the next Session on.`,defaultValue:"(default)",deleteAgent:"Delete agent",builtinUndeletable:"Built-in agents cannot be deleted",deleteConfirm:e=>`Delete agent "${e}"? Its directory (including all Traces) will be removed recursively and cannot be recovered.`,stateTitle:"Agent State",stateVersion:"Agent State version",transferDesc:"Export the current Agent State snapshot (tar.gz); importing overwrites the whole directory and adopts the version inside the package.",exportSnapshot:"Export snapshot",importSnapshot:"Import snapshot",importing:"Importing…",importDone:e=>`Import finished, Agent State version v${e}`,importConflictTitle:"Version conflict",importConflictBody:"The snapshot's version is not newer than the current one; importing will overwrite the existing Agent State. Continue?",resetConfigTitle:"Restore default configuration",resetConfigAction:"Restore default configuration",resetConfigConfirmBody:"This overwrites the agent's existing configuration with the current defaults: the custom system prompt, tool list, model/compaction settings and MCP servers are all replaced, keeping only name and description. Like a skill update this cannot be undone. Continue?",resetConfigDone:"Configuration restored to the current defaults",kernelTitle:"Kernel",kernelLegacy:"predates kernel versioning",kernelOutdatedHint:"Kernel update available",kernelUpdateNeeded:"Kernel update needed",kernelUpToDate:"Up to date",kernelUpdateTitle:"Update kernel",kernelCurrent:"current",kernelLatest:"latest",kernelUpdateAction:"Update kernel",kernelUpdateConfirmBody:"Settings tabs you have not customized will be updated to the current built-in defaults; a tab you have edited stays unchanged in full and is listed in the result. Name, description, the State version and MCP servers are unaffected. Continue?",kernelUpdateDone:(e,t)=>t>0?`Kernel updated to ${e}; ${t} tab(s) now follow the new defaults`:`Kernel updated to ${e}; every tab was already current or kept as customized`,kernelUpdateKeptIntro:"Kept whole because customized:",kernelListSeparator:", "},models:{title:"Models",addCustom:"Add custom model",addToGroup:"Add model",editTitle:"Model settings",addTitle:"Add model (OpenAI protocol)",addTitleVendor:"Add model",addProtocolHint:"New models use the OpenAI Chat Completions protocol; set the base URL to a compatible endpoint",vendorProtocolHint:e=>`Only ${e}'s official API protocol is supported; use a custom model group for OpenAI-compatible endpoints.`,autoRouteNone:"This model ID cannot be routed with the current provider protocol. If it uses an OpenAI-compatible endpoint, move it to Custom.",useCustomGroup:"Move to Custom",addGroup:"Add group",addGroupTitle:"Add group",addGroupDesc:`User-defined groups share Custom semantics. "Import models" detects (or lets you pick) the endpoint's protocol, then imports every model it serves in one go; "Create only" adds models one by one after the group. Groups live on model entries — the group appears once its first model is saved.`,groupModeCreate:"Create only",groupModeImport:"Import models",groupImportAll:"Import all models",groupImportNeedUrl:"Fill in a valid base URL first (http/https)",groupImportKeyHint:"Leave empty to read the protocol's OPENAI_* / ANTHROPIC_* env vars",groupImportListing:"Fetching model list…",groupImportSaving:e=>`Importing ${e} models…`,groupImportUnsupported:"This protocol cannot list models — add them manually",groupImportFailed:"Fetching the model list failed",groupImportEmpty:"No models to import from this endpoint",groupImported:(e,t)=>t>0?`Imported ${e} models, skipped ${t} entries`:`Imported ${e} models`,groupNameLabel:"Group name",groupNameHint:"Starts with a lowercase letter / digit; may contain - and _",groupNameInvalid:"Group names may only use lowercase letters, digits, - and _ (starting with a letter or digit), up to 32 characters",groupNameExists:"This name is taken by a built-in group or an existing entry",groupEmptyHint:"No models in this group yet; use “Add model” to create one",deleteGroup:"Delete group",deleteGroupTitle:"Delete group",deleteGroupConfirm:(e,t)=>`Delete the group “${e}”? Its ${t} models and their API key configuration will be removed.`,groupDeleted:e=>`Group deleted (${e} models)`,searchPlaceholder:"Search models: id / name / provider",noSearchResults:"No matching models",syncCatalog:"Sync presets",syncCatalogHint:"Update preset models from the built-in catalog: add missing entries and reset differing ones to the catalog's fields; locally added models and API keys are left untouched",syncDone:(e,t)=>`Presets synced: ${e} added, ${t} updated`,syncUpToDate:"Presets are already up to date",homepage:"Model page",speedTest:"Speed test",speedTestTitle:"Speed test",speedTestConfirm:e=>`This sends one real request to each of the ${e} models in this group, one at a time, to measure time-to-first-token (TTFT) and output rate (TPS). It consumes a small amount of API quota. Continue?`,speedTestStart:"Start",speedPending:"Testing…",speedFailed:"Test failed",ttftTitle:"Time to first token (TTFT)",tpsTitle:"Output rate (TPS)",modelCount:e=>`${e} model${e===1?"":"s"}`,modelId:"Model ID",modelIdHint:"The upstream API model id, e.g. gpt-5.5",displayName:"Display name",displayNameHint:"Defaults to the model ID",providerGroup:"Group",contextWindow:"Context window",tokenUnit:"Token",contextWindowHint:"Leave empty if unknown",maxTokens:"Max output tokens",maxTokensHint:"Empty = inherit agent setting",maxTokensTitle:"Caps output tokens per request; leave empty to inherit the agent setting — lower it for small-context models",maxTokensInvalid:"Must be a positive integer",clientTypeLocked:e=>`Protocol: ${e} (kept as configured; not editable)`,protocol:"Protocol",protocolNames:{"openai-responses":"OpenAI Responses","ant-messages":"Anthropic Messages","openai-chat":"OpenAI Chat Completions"},protocolTriggerTitle:e=>`Protocol: ${e}. Click to change it.`,protocolUnset:"Select protocol",detectProtocol:"Detect",detectProtocolHint:"Probe the base URL and apply the protocol it serves",detecting:"Detecting…",detectedProtocol:e=>`Detected ${e}; applied`,detectFailedBody:"Could not detect the protocol. Please check the API key and the base URL.",detectFellBack:"Protocol not detected; saved as OpenAI Chat Completions",addProtocolHintDetect:"Pick the protocol from the base URL field's suffix (OpenAI Responses / Anthropic Messages / OpenAI Chat Completions), or press Detect to probe the endpoint — saving without one detects it first",addTitleCustom:"Add model",vision:"Vision support",detectVision:"Detect",detectingVision:"Testing…",detectVisionHint:"Send one tiny test image to see whether this model accepts images (uses your API key)",detectVisionNeedsId:"Fill in the model id first, then detect.",detectVisionOk:"This model accepts images; vision turned on",detectVisionNo:"This model does not accept images; vision left off",visionOffProxyHint:"Images are read via the vision proxy model",fastMode:"Fast mode",fastModeHint:"Faster output, billed at the provider's premium tier; the Cost center still counts it at the entry's standard prices",fastModeUnsupported:"This model does not support fast mode — turn it off, or its requests will fail",fastModeConfirmTitle:"Enable fast mode",fastModeConfirmBody:"Fast mode is billed at the provider's premium price list (MiniMax charges 1.5x standard; OpenAI and Anthropic publish separate premium rates). The entry's recorded per-token prices are not adjusted, so the Cost center will under-report this usage.",fastModeConfirmPreview:"Anthropic's fast mode is a limited research preview: until your organization is granted access, requests return a 429 rate-limit error.",fastModeBadge:"Fast",visionBadge:"Vision",freeBadge:"Free",visionModelBadge:"Proxy vision",setVisionModel:"Set as proxy vision model",visionModelHint:"Describes images via describe_image for models without vision",priceUnitShort:"/M tok",testConnection:"Test connection",testing:"Testing…",testOk:e=>`Connected (${e} ms)`,testFailed:e=>`Failed: ${e}`,priceCacheRead:"Cache read price",priceCacheWrite:"Cache write price",priceOutput:"Output price",currency:"Currency",currencyUsd:"USD $",currencyCny:"CNY ¥",apiKey:"API key",apiKeyKeepHint:"Leave empty to keep the current key",apiKeyEnvHint:e=>`Leave empty to use the ${e} env var`,keyConfigured:"Key configured",clearApiKey:"Clear stored API key",baseUrl:"Custom base URL",baseUrlHint:"Leave empty to use the provider default",baseUrlSuffixTitle:"The client appends the protocol path shown at the field's right edge to the base URL",baseUrlRequired:"A base URL is required",contextWindowDefaultHint:e=>`Defaults to ${e} if empty`,confirmDeleteTitle:"Delete model",confirmDelete:e=>`Delete "${e}"? Its configuration and API key will be removed.`,groupApiKey:"Set key",groupApiKeyTitle:e=>`Set the API key for ${e}`,groupApiKeyHint:e=>`Applies to all ${e} models in this group; leave empty to keep them unchanged.`,getApiKey:"Manage keys",getModelIds:"Get model IDs",groupKeyApplied:e=>`API key set for ${e} models`,oauthKey:"Authorize key",oauthTitle:e=>`Authorize a new ${e} API key`,oauthIntro:(e,t)=>`A new API key will be created on your ${e} account and written to all ${t} models in this group, replacing the key they use now.`,oauthAuthorize:"Open authorization page",oauthWaiting:"Waiting for the authorization to finish in the other tab…",oauthApplied:e=>`New API key set for ${e} models`,oauthManualSwitch:"Page can't redirect back? Enter the code by hand",oauthCallbackSwitch:"Go back to the automatic redirect",oauthManualHint:"Open the authorization page, then paste the one-time code it shows you here.",oauthCodeLabel:"Authorization code",oauthSubmitCode:"Submit code",oauthTimedOut:"The authorization never came back. Enter the code by hand, or start again.",oauthRetry:"Start again",oauthErrors:{invalid_request:"The authorization request was rejected. Start again.",code_rejected:"That authorization is no longer valid: it expired or was already used. Start again.",upstream_failed:"The provider returned no usable key. Start again.",unreachable:"The provider could not be reached. Check the network and start again.",apply_failed:"A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console."},providerEnvNotes:{zhipu:"Defaults to the Z.AI global endpoint (api.z.ai); keys from bigmodel.cn need base URL https://open.bigmodel.cn/api/paas/v4",moonshot:"Defaults to the China endpoint (api.moonshot.cn); keys from platform.kimi.com need base URL https://api.moonshot.ai/v1"},confirmVisionModelTitle:"Set as proxy vision model",confirmVisionModel:e=>`Make "${e}" the proxy vision model? Models without vision will read images through it via describe_image.`,confirmSaveTitle:"Save model settings",confirmSave:e=>`Save the changes to "${e}"?`,confirmDefaultTitle:"Set as default model",confirmDefault:e=>`Make "${e}" the default model? New sessions will use it by default.`,default:"Default",setDefault:"Set as default model",remove:"Delete model",readOnlyHint:"Members have read-only access; only owners can change models and credentials",empty:"No models configured yet",noKey:"No key",readFromEnv:"Read from environment variable",showModelsWithoutKey:e=>`Show model${e===1?"":"s"} without a key (${e})`,modelIdExists:"This model id already exists",pricingAllOrNone:"Fill all three prices",pricingInvalid:"Must be a number",contextWindowInvalid:"Must be a number"},memory:{desc:"Long-term memory across Sessions (stored in agent_state/memory/): the agent saves what is worth keeping as it works, and you can also just ask it to remember something. User memory applies to all of this agent's sessions; workspace memory is kept per workspace. Memory edits are made by the agent in chat. Turning the switch off only stops memory from being used and deletes nothing.",enable:"Enable memory",userScope:"User memory",templateMissing:"The prompt template has no {{MEMORY}} placeholder, so memory never enters the context.",insertPlaceholder:"Insert the {{MEMORY}} placeholder",insertPlaceholderDone:"Inserted",promptSection:"Memory prompt",promptSectionHint:"What the template's {{MEMORY}} placeholder expands to. The main prompt is injected into every session; the workspace addendum only in sessions with a persistent workspace.",promptLabel:"Main prompt",workspacePromptLabel:"Workspace addendum",promptPlaceholders:[["{{USER_MEMORY_INDEX}}","Content of the user MEMORY.md index (at most 200 lines and 25,000 characters total)"],["{{WORKSPACE_MEMORY_INDEX}}","Content of the workspace MEMORY.md index (at most 200 lines and 25,000 characters total); effective only in the workspace addendum"],["{{WORKSPACE_MEMORY_DIR}}","Absolute path of the current workspace's memory directory; effective only in the workspace addendum"]],insertToken:"Insert at the cursor",itemCount:e=>e===1?"1 item":`${e} items`,emptyScope:"No memories for this Workspace yet — the agent saves what is worth keeping as it works",emptyUserScope:'No user memories yet — say "remember …" in a chat and the agent will save it',add:"Add",addScopeLabel:e=>`Add to ${e}`,addTitle:"Add memory",addWhy:"The agent organizes and saves memories in a chat: fill in the content, open a new conversation, and the agent does the rest.",addContentLabel:"Content or source to remember",addContentPlaceholder:"Paste the content to remember, or a file path / URL",addPromptLead:{user:"Please turn the following into memories in user memory:",workspace:"Please turn the following into memories in this workspace's memory:"},view:"View",edit:"Edit",editTitle:"Edit memory",editWhy:"Content edits are made by the agent in a chat: confirm the prompt to open a new conversation, and the agent updates the memory file and its MEMORY.md index together.",editRequirementLabel:"What to change",editRequirementPlaceholder:"Describe the change — you can finish it in the chat",editPromptLabel:"Prompt preview",editCopyPrompt:"Copy prompt",editOpenChat:"Open a new chat",delete:"Delete",deleteTitle:"Delete this memory?",deleteConfirm:e=>`This deletes "${e}" and removes its index line from MEMORY.md. This cannot be undone.`,deleteDone:"Deleted",editPromptLead:e=>`Please update a memory: ${e}`,editPromptTail:"What to change: ",exportScope:"Export",exportScopeHint:"Download every memory in this group as one JSON document",exportScopeLabel:e=>`Export ${e}`,importScope:"Import",importScopeHint:"Restore memories into this group from an exported JSON document",importScopeLabel:e=>`Import into ${e}`,importTitle:"Import memories",importWhy:"Reads a memory group exported from this or another agent: a JSON file holding the memories and the group's MEMORY.md index.",importFile:(e,t)=>`${e} — ${t} memories`,importModeLabel:"When this group already has a memory of the same name",importModeSkip:"Keep the one that is here",importModeSkipHint:"Adds only what this group does not have. Nothing here is lost.",importModeOverwrite:"Take the file's version",importModeOverwriteHint:"Memories the file does not carry are left alone.",importModeReplace:"Replace the whole group",importModeReplaceHint:"Every memory the file does not carry is deleted.",importAction:"Import",importInvalidFile:"This file is not a memory export.",importEmptyFile:"This file carries no memories.",importConfirmTitle:"Confirm the import",importWillOverwrite:e=>`${e.length} memories will be overwritten: ${e.join(", ")}`,importWillRemove:e=>`${e.length} memories will be deleted: ${e.join(", ")}`,importWillReplaceIndex:"The group's MEMORY.md index will be replaced.",importIrreversible:"This cannot be undone.",importDone:(e,t,n)=>`Imported: ${e} added, ${t} replaced, ${n} deleted`,importNothingNew:"Nothing to import — this group already has every memory in the file"},vault:{desc:"Environment variables owned by this agent (stored in agent_state/.vault.toml), injected into the environment of its shell commands (exec_command); key names are shared with the model, values never enter the model context. Subagents use their own vaults and do not inherit this one. Saved changes take effect from the next task (a task already running is unaffected).",key:"Name",value:"Value",valueMasked:"Value (masked)",add:"Add",addTitle:"Add variable",remove:"Remove",deleteTitle:"Delete variable",deleteConfirm:e=>`Delete variable "${e}"? Its value cannot be recovered.`,overwriteTitle:"Overwrite existing variable",overwriteConfirm:e=>`"${e}" already exists — saving will overwrite its value, which cannot be recovered.`,empty:"No variables configured yet",readOnlyHint:"Members are read-only; only the owner can edit the vault",keyHint:"Letters, digits and underscores; must not start with a digit",keyInvalid:"Invalid name: only letters, digits and underscores, not starting with a digit",valueRequired:"Value must not be empty",injection:{enable:"Enable vault",templateMissing:"The prompt template has no {{VAULT}} placeholder, so the vault section never enters the context.",legacyTemplate:"The template still carries the legacy hardcoded # Vault section: one-click migration replaces it in place with the {{VAULT}} placeholder, wording unchanged, after which it is editable below.",insertPlaceholder:"Insert the {{VAULT}} placeholder",migrate:"Migrate to the {{VAULT}} placeholder",promptSection:"Vault prompt",promptSectionHint:"What the template's {{VAULT}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{VAULT_KEYS}}",'Vault key-name list (one "- KEY" line per key, names only — values are never injected; empty when no keys)']]}},schedule:{desc:"Scheduled tasks (agent_state/schedule/*.toml): the prompt is sent to the target Session on schedule; files can also be edited by hand, and changes made here take effect immediately.",readOnlyHint:"Members are read-only; only the owner can modify schedules",colStatus:"Status",colPeriod:"Period",colTarget:"Target",colFireTimes:"Next / last fired",colQueued:"Queue",statusNames:{active:"Active",disabled:"Disabled",expired:"Expired",done:"Done",missed:"Missed",invalid:"Invalid"},queued:"Queued",once:"One-off",newSession:"New session",invalidFiles:"Files that failed to parse (skipped by the scheduler)",empty:"No scheduled tasks yet",enable:"Enable",disable:"Disable",addTitle:"New scheduled task",editTitle:e=>`Edit scheduled task "${e}"`,nameHint:"The file name (without .toml); cannot be changed later",prompt:"Prompt",enabled:"Enabled",startAt:"Start at",endAt:"End at",period:"Period",periodPlaceholder:"30m / 12h / 7d; leave empty for a one-off task",target:"Target",targetNew:"New session each time",targetSession:"Bound Session",sessionId:"Session",chooseSession:"Choose a Session to bind",sessionSearch:"Search title or Session id…",sessionNoMatch:"No matching Session",sessionEmpty:"This agent has no Sessions yet",workspace:"Workspace",model:"Model",modelDefault:"Project default",deleteTitle:"Delete scheduled task",deleteConfirm:e=>`Delete scheduled task "${e}"?`,injection:{enable:"Enable schedules",templateMissing:"The prompt template has no {{SCHEDULES}} placeholder, so the scheduled-tasks section never enters the context.",insertPlaceholder:"Insert the {{SCHEDULES}} placeholder",promptSection:"Schedules prompt",promptSectionHint:"What the template's {{SCHEDULES}} placeholder expands to — teaches the model to manage scheduled tasks with its file tools; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{SCHEDULE_LIST}}",'Current task-name list (one "- name" line per task; an empty-roster note when none exist)']]}},skills:{pageTitle:"Skill library",pageDesc:"Built-in skill library: browse, quick-start a chat, or install to agents.",quickInvoke:"Quick start",quickInvokeText:e=>`use the ${e} skill`,quickInvokeNeedsInstall:"Install this skill on the current agent first to quick-start",selectAll:"Select all",selectNone:"Select none",selectedCount:e=>`${e} selected`,manageInstall:"Manage installs",manageInstallTitle:e=>`Manage installs: ${e}`,install:"Install",installed:"Installed",uninstall:"Uninstall",skillCount:e=>e===1?"1 skill":`${e} skills`,usedByAgents:e=>e===0?"not used yet":e===1?"used by 1 agent":`used by ${e} agents`,installedToast:(e,t)=>`Installed ${e} to ${t}`,updateOutdated:e=>`Update available: update ${e} agent install(s)`,updateAction:"Update",updateConfirmTitle:e=>`Update ${e}`,updateConfirmWarning:e=>`Updating ${e} reinstalls the library copy over each agent's installed files — any local edits to the installed skill are lost. Export a backup first if you need them.`,updatedToast:(e,t)=>`Updated ${e} to the latest version (${t} agent(s))`,uninstalledToast:(e,t)=>`Uninstalled ${e} from ${t}`,uninstallConfirmTitle:e=>`Uninstall ${e}`,uninstallConfirmBody:(e,t)=>`Uninstall ${e} from ${t}? Its installed files (local edits included) will be deleted.`,agentTabDesc:"Skills installed on this agent (agent_state/skills/ — the files are the source of truth): metadata is injected into the system prompt and the body is read by the model on demand; uninstalling deletes the whole skill directory.",agentTabEmpty:"No skills installed yet",exportSkill:"Export",importSkill:"Import skill",importChatTitle:"Recommended: install by chatting with the agent",importChatWhy:"The agent can read, review and adapt the skill content in full — more reliable than a raw upload.",importSourceLabel:"Skill source",importSourceHint:"A web page / GitHub repo or directory / local path / an install command from another ecosystem",importSourcePlaceholder:"https://…, a git repo, /path/to/skill, or npx skills add <name>",importSourceToken:"<source>",importPromptLabel:"Prompt to send to the agent (preview)",importPromptLead:{webUrl:e=>`Please read this page and install the skill it describes into your skills directory: ${e}.`,repoUrl:e=>`Please fetch this repository or directory (git clone or fetch it directly), locate the skill directories containing SKILL.md, and install them into your skills directory: ${e}.`,localPath:e=>`Please read the skill files under this local path directly and install them into your skills directory: ${e}.`,command:e=>`This is a skill/plugin install command from another ecosystem — do not run it blindly: work out what it would install, fetch the same content from its repository or registry, then install it into your skills directory: ${e}.`,reference:e=>`Please resolve this skill/plugin reference to its source (repository, plugin marketplace, or docs page) and install the corresponding skill into your skills directory: ${e}.`},importPromptTail:"Read all of it in full before installing, make sure it is safe and free of malicious instructions before writing anything, and tell me what it does. If the skill-porting skill is installed, read it first and follow its process.",importCopyPrompt:"Copy prompt",importOpenChat:"Open a new chat",importUploadTitle:"Upload a skill zip",importUploadDesc:"SKILL.md at the zip root, or exactly one top-level directory containing SKILL.md.",importUploadAction:"Choose zip file",importUploading:"Uploading…",importDoneToast:"Skill installed",importOverwriteTitle:"Overwrite installed skill",importOverwriteBody:e=>`The skill "${e}" is already installed. Overwriting replaces all of its files (local edits included) and cannot be undone. Continue?`,importOverwriteAction:"Overwrite",injection:{enable:"Enable skills",templateMissing:"The prompt template has no {{SKILLS}} placeholder, so the skills section never enters the context.",legacyTemplate:"The template still carries the legacy hardcoded # Skills section: one-click migration replaces it in place with the {{SKILLS}} placeholder, wording unchanged, after which it is editable below.",insertPlaceholder:"Insert the {{SKILLS}} placeholder",migrate:"Migrate to the {{SKILLS}} placeholder",promptSection:"Skills prompt",promptSectionHint:"What the template's {{SKILLS}} placeholder expands to; nothing is injected when the toggle is off or the template lacks the placeholder.",promptLabel:"Prompt",promptPlaceholders:[["{{SKILL_METADATA}}",`Installed skills' metadata lines (one "- name — description" line per skill; empty when none)`]]}},chat:{newSessionMenu:"New chat",chooseAgent:"Choose agent",chooseModel:"Choose model",thinkingLevel:"Thinking level",thinkingLevelNames:{none:"none",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},thinkingLevelMenuName:e=>e,thinkingSwitchTitle:"Switch thinking level",thinkingSwitchBody:e=>`Switch the thinking level to "${e}"? Switching mid-conversation lowers the prompt-cache hit rate and raises cost; compacting the context first is cheaper.`,thinkingSwitchBusyHint:"This conversation is still working — compaction has to wait for it.",thinkingSwitchCompactFirst:"Compact, then switch",thinkingSwitchConfirm:"Switch anyway",thinkingSwitchCompacting:"Compacting the context — the thinking level switches when it ends.",thinkingSwitchApplied:e=>`Context compacted; thinking level switched to "${e}".`,thinkingSwitchCompactFailed:"The compaction did not finish; the thinking level was switched anyway.",workspaceUseThis:"Use this dir",workspaceUp:"Parent dir",workspaceNoSubdirs:"No subdirectories",workspaceAuto:"Temporary workspace",workspaceClear:"Use a temporary workspace instead",workspaceDirInvalid:"Directory does not exist or is inaccessible; reverted",groupByWorkspace:"Group by workspace",groupByAgent:"Group by agent",groupByTime:"Group by time",timeGroups:{day:"Past day",month:"Past month",earlier:"Earlier"},searchSessions:"Search chats",searchSessionsPlaceholder:"Search chats…",searchClear:"Clear search",searchNoMatches:"No matches among loaded chats",listSettings:"List options",groupModeSection:"Group by",sortModeSection:"Sort by",sortManual:"Manual order",sortRecent:"Most recent",newWorkspaceEntity:"New workspace",workspaceMenu:"Workspace options",renameWorkspace:"Rename workspace",renameWorkspaceLabel:"Name",renameWorkspaceHint:"Leave empty to use the folder name",deleteWorkspace:"Remove workspace",deleteWorkspaceConfirm:e=>`Remove "${e}"? This only removes the workspace group from the sidebar — the directory on disk and existing chats are untouched, and it can be re-added anytime.`,tempWorkspaces:"Temporary workspaces",newSessionInWorkspace:"New chat in this workspace",draftSubtitle:"The self-evolving agent that excels at AI development tasks",exampleFolders:{webapps:"Build web apps",agents:"Build and optimize agents",schedules:"Create scheduled tasks"},exampleFillHint:"Click to fill the composer — edit it if you like, then send",shortcuts:{folder:"My shortcuts",new:"New shortcut",newFromComposer:"Starts from whatever is in the composer",createTitle:"New shortcut",editTitle:"Edit shortcut",titleLabel:"Name",titleHint:e=>`At most ${e} characters`,promptLabel:"Prompt",promptHint:e=>`At most ${e} characters`,promptInfo:"Clicking this shortcut puts the text into the composer verbatim and sends nothing; Skills stay a separate pick in the composer.",titleTooLong:e=>`The name may be at most ${e} characters`,promptTooLong:e=>`The prompt may be at most ${e} characters`,deleteTitle:"Delete shortcut",deleteConfirm:e=>`Delete "${e}"? The shortcut disappears from every device you use.`},exampleTasks:{game:{label:"2D penguin sled game",desc:"A cute Antarctic penguin sleds over rocks, easy start with a gentle difficulty ramp — a 2D pure-frontend mini game",prompt:"Build a cute Antarctic penguin sledding 2D game: press Space to jump over the rocks coming up on the ice; start easy and forgiving, with sled speed and obstacle density ramping up smoothly and gradually over time (no sudden spikes), live scoring, and hitting a rock ending the run with one-click restart. A 2D side-scroller with a cute cartoon look, pure frontend (a single HTML file is fine), styled per the web-design skill. When done, test it in a browser once, confirm the first few seconds are easy to clear, and tell me how to open it and how to play."},gamecenter:{label:"A mini-game center built by multiple agents",desc:"Ten pure-frontend games with no repeated mechanics, built in parallel behind one index page",prompt:`Build a web mini-game center with multiple agents working in parallel: 10 pure-frontend games with no two sharing the same mechanic, plus an index page.
|
|
69
69
|
|
|
70
70
|
## How to split the work
|
|
71
71
|
- First plan the 10 games (say snake, 2048, tetris, breakout, minesweeper, memory match, sokoban, space shooter, platform jumper, rhythm tap), confirm no two mechanics repeat, and fix a shared directory layout, palette and interaction spec.
|
|
@@ -123,7 +123,7 @@ Benchmark:
|
|
|
123
123
|
Scenarios:
|
|
124
124
|
1. Make football betting decisions from historical matches and current information.
|
|
125
125
|
2. Choose after-sales actions from policy and ticket facts.
|
|
126
|
-
3. Choose investment actions from a strategy, historical markets, and current indicators.`},agentOptimization:{label:"Improve the general-purpose decision agent's accuracy",desc:"Improve an Agent from existing evaluation results and verify that the new version is better",prompt:"Use `agent-optimization` to optimize a decision Agent against its frozen Benchmark.\n\n- test_agent_id: `finite_choice_agent`\n- benchmark_id: `contextual-choice-adaptation`\n- capability_direction: improve stability under incomplete information, conflicting rules, and finite choices\n- runs: `3`\n- desired_score: `>=95`\n- candidate_round_limit: `5`"},dailyPlan:{label:"A 9am daily planning check-in",desc:"09:00 every day: talk through the day's plan in this same chat, and review yesterday's progress",prompt:"Set up a scheduled task: every day at 9am, in this same conversation, plan today's work with me. Read back over the conversation first and say what yesterday's plan got done and where it stuck, then offer an ordered shortlist for today with a line of reasoning each, and write up what I confirm as a checklist."},githubDigest:{label:"Daily GitHub project digest",desc:"A daily pass over one repo's issues, PRs and CI, ending in prioritized recommendations",prompt:"Set up a scheduled task: every morning, use gh to digest one GitHub repo's issues, PRs and CI — surface what has stalled, what is waiting on review and what is failing — and end with recommendations ranked by priority, each saying why it sits where it does."},memoryReview:{label:"Friday memory review",desc:"Friday evening: go through what is worth remembering from the week and write it into Memory",prompt:"Set up a scheduled task: every Friday evening, in this same conversation, go through what is worth remembering from the week with me. Check the existing memory index first so nothing is duplicated, then take it item by item — what to record, what to revise — and write what I confirm into Memory."}},sessionList:"Sessions",defaultSessionTitle:"New chat",agent:"Agent",model:"Model",workspace:"Workspace",workspaceHint:"Leave empty for an auto-created temporary workspace; if set, it must be an existing directory on the server",workspaceHintShort:"Leave empty for a temporary workspace",approvalMode:"Approval mode",approvalModeNames:{"allow-all":"Approve everything","deny-all":"Deny everything","read-only":"Approve read-only","always-ask":"Ask every time"},approvalModes:{"allow-all":"Approve everything (allow-all)","deny-all":"Deny everything (deny-all)","read-only":"Approve read-only (read-only)","always-ask":"Ask every time (always-ask)"},statusRunning:"Running",statusCompacting:"Compacting",statusCompletedUnread:"Done, unread",pendingApprovals:e=>`${e} pending approval${e>1?"s":""}`,jumpToLatest:"Jump to latest",loadingEarlier:"Loading earlier messages…",loadEarlierRetry:"Failed to load earlier messages — click to retry",historyBeginning:"Beginning of conversation",outlineTitle:"Outline",outlineTickLabel:(e,t)=>`Turn ${e}: ${t}`,outlineNoText:"(image or attachment)",outlineAnswering:"Answering…",inputPlaceholder:"Type a message. Enter to send, Shift+Enter for newline, paste images",inputPlaceholderShort:"Type a message…",steerPlaceholder:"Message the running agent — delivered with the next turn",steerPlaceholderShort:"Message the running agent…",steerSend:"Send to the running agent",steerQueuedIndicator:"Steering queued — delivered with the next turn",steerQueuedItem:e=>`Steering queued — delivered with the next turn: ${e}`,userSteering:"User steering",steerModeLabel:"Mid-run send mode",steerModeSteer:"Steer",steerModeSteerHint:"Steer now: delivered to the running agent with the next turn",steerModeFollowUp:"Queue",steerModeFollowUpHint:"Queue a follow-up: sent automatically as a new message when this run finishes",followUpPlaceholder:"Queue as the next message — sent automatically when this run finishes",followUpPlaceholderShort:"Queue as the next message…",followUpSend:"Queue as the next message",followUpQueuedChip:e=>`${e} follow-up ${e===1?"message":"messages"} queued — sent when this run finishes`,followUpQueuedItem:e=>`Follow-up queued — sent when this run finishes: ${e}`,recallQueued:"Recall",recallQueuedTitle:"Recall to the input box to edit and resend",send:"Send",stop:"Stop",compact:"Compact context",approve:"Allow",deny:"Deny",decisionAllow:"Approved",decisionDeny:"Denied",decisionManual:"manual",decisionAuto:"auto",decisionPolicy:"policy",thinking:"Thinking",subagent:"Subagent",subagentRunning:"Running",aborted:e=>{const t=e?.errorCode==="user_abort"?"aborted by user":e?.errorCode==="backoff_interrupted"?"aborted during reconnect backoff":e?.errorCode==="compaction_interrupted"?"aborted during compaction":e?.errorCode??e?.reason??"",n=t?`${t}${e?.errorMessage?`: ${e.errorMessage}`:""}`:"";return`[Aborted]${n?`: ${n}`:""}`},reconnect:(e,t,n,s,o,c)=>{const u=c??e,f=u==="timeout"?"Connection timed out":u==="malformed"?"Response incomplete or unparseable":u==="network"?"Network or service temporarily unavailable":u==="failed"?"The model provider returned an error":"The request failed",p=t==="gaveUp"?`giving up after attempt ${n}${o?`: ${o}`:""}`:t==="retried"?`retry #${n} sent`:s!==void 0?`retry #${n} in ${s}s…`:`starting retry #${n}…`;return`[Retry] ${f}; ${p}`},llmError:e=>`[Error]: llm request error${e?`: ${e}`:""}`,reconnectRetryNow:"Retry now",reconnectGiveUp:"Give up",imageAlt:"Image uploaded by user",toolImageAlt:"Image from tool output",imagesAsPathHint:"This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via describe_image)",infoPanel:"Session info",sessionStats:"Stats",sessionIdLabel:"Session id",copySessionId:"Copy Session id",processList:"Processes",processStop:"Stop",processExited:"exited",processRemove:"Remove",processRemoveHint:"Remove this entry — the output captured from it is discarded too",runningServices:e=>e===1?"1 running service":`${e} running services`,statTokens:"Total Tokens",statTotalTokens:"Total Tokens",statCacheHit:e=>`cache hit rate ${e}`,statElapsed:"Elapsed",statInput:"Input tokens",statCached:"cached",statOutput:"Output tokens",statTps:"Output TPS",statParenOpen:" (",statParenClose:")",noSessions:"No Sessions yet",emptyStream:"Send a message to start the conversation",historyLoadFailed:"Failed to load history",statsLabel:"Stats",removeImage:"Remove image",openAgents:"Agents panel",workspacePanel:"Workspace",filesInMessage:e=>`${e} ${e===1?"file":"files"}`,imagesInMessage:e=>`${e} ${e===1?"image":"images"}`,openPreview:"Click to preview",showMoreFiles:e=>`Show ${e} more ${e===1?"file":"files"}`,showLess:"Show less",memoryChangesTitle:e=>`${e} memory ${e===1?"update":"updates"}`,memoryScopeWorkspace:e=>`Workspace memory (${e})`,memoryOpWrite:"Wrote",memoryOpEdit:"Edited",memoryViewTitle:"Memory",memoryChangedMark:"Changed in this conversation",memoryContentUnavailable:"Content unavailable (the file may have been moved or deleted)",memoryRowOpen:"View content",memoryBack:"Back to the list",memoryEmptyAll:"No memory yet — say “remember …” in a chat to have the agent save one",openAgentMemory:"Manage in agent settings",memoryShowMore:e=>`Show ${e} more`,prevGroupPage:"Previous groups",nextGroupPage:"Next groups",groupPagePosition:(e,t)=>`Page ${e} of ${t}`,contextUsage:"Context usage",contextUnknown:"Context usage: unknown until the next request reports it",contextComposition:"Context composition",contextPartSystemPrompt:"System prompt",contextPartToolDefs:"Tool definitions",contextPartUserMessages:"User messages",contextPartAssistantMessages:"Model messages",contextPartToolRequests:"Tool requests",contextPartToolResults:"Tool results",contextTopTools:"Top 5 tools",contextCompactAt:e=>`Compaction threshold ${e}`,contextTopToolsHint:"Ranked by the context each tool's calls and results occupy (definitions count under “Tool definitions”)",contextUnknownHint:"Just compacted — the next request reports the usage, and the composition with it",contextBreakdownEmpty:"Nothing in the current context to break down yet",contextBreakdownFailed:"Could not read the context composition",slashHint:"Type / for commands",switchAgent:"Hand off to another agent — opens a new session on send",switchAgentTitle:"Choose agent",agentSearchPlaceholder:"Search agents: id / name",agentsNoMatch:"No matching agents",handoffTargetTitle:e=>`Sending hands this conversation to ${e}`,handoffRemove:"Remove handoff target",skillsSelect:"Skills",skillRemove:"Remove skill",skillsSearchPlaceholder:"Search skills",skillsNoMatch:"No matching skills",skillsEmptyHint:"No skills installed yet — add some from the skill library",skillsAutoMessage:e=>e.length===1?`use the ${e[0]} skill`:`use the ${e.join(", ")} skills`,handoffFrom:e=>`Handed off from ${e}'s conversation`,handoffBack:e=>e?`Back to the original conversation: ${e}`:"Back to the original conversation",switchModel:"Switch model — on send, continues this conversation in a new session",switchModelTitle:"Switch model",modelSwitchTargetTitle:e=>`Sending continues this conversation on ${e}`,modelSwitchRemove:"Remove model switch",modelSwitchBusyHint:"The model switch waits for this turn to finish: the new session continues from this session's record",modelSwitchFrom:e=>e?`Switched model (was ${e}) — continued from the earlier conversation`:"Switched model — continued from the earlier conversation",modelSwitchAutoMessage:"Continue this conversation on the new model",modelLockedHint:"Type /model to switch models",scheduledFrom:e=>`Triggered by scheduled task "${e}"`,backgroundDone:(e,t)=>{const n=e==="command"?"Background command":"Background task";return t==="stopped"?`${n} stopped`:t==="completed"?`${n} finished`:`${n} failed`},emptyGreeting:"Start a new conversation",mcpConnectTitle:"MCP connect",mcpServerList:e=>e.join(", "),mcpConnectResult:(e,t)=>{const n=[];return(e>0||t.length===0)&&n.push(`${e} tool${e===1?"":"s"} discovered`),t.length>0&&n.push(`unavailable: ${t.join(", ")}`),n.join("; ")},mcpToolsCount:e=>`${e} tool${e===1?"":"s"}`,mcpServerFailed:"connection failed",mcpConnectAborted:"interrupted — reconnects on the next send",compactionTitle:e=>e==="discard"?"Clear":"Compaction",compactionFailed:(e,t)=>{if(e==="aborted")return"aborted, keeping current context";const n=t!==void 0?` (${t})`:"";return e==="retryable"?`failed${n}, keeping current context; retries at the next trigger`:e==="fatal"?`failed${n}, keeping current context; fix the model configuration to retry`:`failed${n}, keeping current context`},unknownTool:"(unknown tool)",workRunning:"Running",workDone:"Done",workGroupSteps:e=>`${e} ${e===1?"step":"steps"}`,approvalWaiting:"awaiting approval",copyCode:"Copy code",copyReply:"Copy reply",forkSession:"Fork chat from here",forkSessionConfirmBody:"This copies the conversation up to this reply into a new chat. The original chat stays unchanged.",forkSessionConfirmAction:"Fork",forkSessionFailed:"This reply could not be located. Refresh and try again.",copyMessage:"Copy message",deleteSession:"Delete chat",renameSession:"Rename chat",renameSessionLabel:"Title",deleteSessionConfirm:e=>`Delete "${e}"? Its messages and Trace will be removed permanently.`,draftGroup:"Drafts",draftUntitled:"(untitled draft)",deleteDraft:"Delete draft",deleteDraftConfirm:e=>`Delete draft "${e}"? Unsent content will be discarded.`,archiveSession:"Archive",unarchiveSession:"Unarchive",pinSession:"Pin",unpinSession:"Unpin",pinnedSession:"Pinned",moreActions:"More",loadMore:"More",expandRestSessions:e=>`Show ${e} more ${e===1?"chat":"chats"}`,loadMoreSessions:"Load more chats",folderGroups:{subagent:e=>`Subagents (${e})`,schedule:e=>`Scheduled (${e})`,archived:e=>`Archived (${e})`},skillsBanner:e=>`Using skill${e.length===1?"":"s"}: ${e.join(", ")}`,attachedFilesBanner:e=>`Attached file${e.length===1?"":"s"}: ${e.join(", ")}`,plusMenu:"More input options",uploadImage:"Upload image",uploadImageDesc:"Attach images to this message",uploadFile:"Upload file",uploadFileDesc:"Saved to the session scratchpad; the model reads them by path",removeFile:"Remove file",attachmentTooLarge:(e,t)=>`${e} exceeds the ${t}MB limit and was not attached.`,dropFilesTitle:"Drop files to attach",dropFilesDesc:"Images and files are added to the message draft",dropFilesGoalHint:"Goal mode takes images only; the files were not attached.",goalMode:"Goal mode",goalModeDesc:"Loop until the goal completes",goalBudgetLabel:"Token budget",goalBudgetUnlimited:"Budget unlimited",goalBudgetValue:e=>`Budget ${e}`,goalBudgetPlaceholder:"e.g. 500k",goalBudgetHint:"Use a k/m suffix; leave blank for no budget limit",goalBudgetInvalid:"Invalid budget: use a positive number with an optional k/m suffix (500k, 2m)",goalBudgetSave:"Save budget",goalRemove:"Exit goal mode",goalRoundBanner:e=>`Goal · round ${e}`,goalRoundImages:e=>e===1?"1 attached image":`${e} attached images`,goalProgress:(e,t)=>`round ${e} · tokens ${t}`,goalStatus:{active:"running",complete:"complete",blocked:"blocked",budget_limited:"budget exhausted",aborted:"interrupted"}},feishu:{intro:"Once bound, messages sent to the Feishu bot flow into this conversation, and the AI's replies are sent back to Feishu as plain text. You need a self-built Feishu app with the bot capability and the message-receive event subscribed in long-connection mode.",appId:"App ID",appSecret:"App Secret",appSecretKeepHint:"Leave empty to keep the saved App Secret",clearSecret:"Clear stored App Secret",baseDomain:"API domain",baseDomainHint:"https://open.feishu.cn for Feishu, https://open.larksuite.com for Lark",invalidDomain:"The domain must be an http(s) URL",testMessageNoChat:"Message the bot once in Feishu first, so it knows which chat to send to",setupSteps:["Create a self-built app in the Feishu developer console","Enable the bot capability for the app","Subscribe to the message-receive event, with the subscription mode set to long connection","Copy the App ID and App Secret from the credentials page into the form above","Publish an app version, get it approved, then message the bot once in Feishu"]},telegram:{intro:"Once bound, messages sent to the Telegram bot flow into this conversation, and the AI's replies are sent back to Telegram as plain text. Create a bot with @BotFather and paste its Bot Token — no public URL is needed.",botToken:"Bot Token",botTokenKeepHint:"Leave empty to keep the saved Bot Token",clearToken:"Clear stored Bot Token",invalidToken:"The Bot Token looks like <digits>:<secret>, as issued by @BotFather",testMessageNoChat:"Message the bot once in Telegram first, so it knows which chat to send to",setupSteps:["Open @BotFather in Telegram and send /newbot to create a bot","Name it as prompted, then copy the Bot Token @BotFather returns into the form above","Find the bot in Telegram and send it one message"]},messaging:{panelTitle:"Messaging",bindAction:"Messaging binding…",dialogTitle:"Messaging binding",channelLabel:"Channel",channelName:{feishu:"Feishu",telegram:"Telegram"},tutorial:"Open tutorial",console:"Open developer console",enabled:"Enable connection",saveBeforeEnable:"Save the credentials first, then enable the connection",test:"Test connection",testing:"Testing…",testOk:e=>`Connected (${e}ms)`,testOkAs:(e,t)=>`Connected as ${e} (${t}ms)`,testFail:e=>`Connection failed: ${e}`,sendTestMessage:"Send test message",sendingTestMessage:"Sending…",testMessageSent:"Test message sent",statusLabel:"Connection status",status:{disconnected:"Not connected",connecting:"Connecting",connected:"Connected",error:"Connection error"},otherEnabledHint:e=>`Only one channel can be enabled per conversation: turn off the ${e} connection first`,credentialMissingHint:"Enter and save the credential first, then enable the connection",disableBeforeClearHint:"Disable the connection before clearing the credential",enabledIndicator:{feishu:"Feishu connection enabled",telegram:"Telegram connection enabled"},faqSetupTitle:"Set up the bot",faqWhatTitle:"What binding does",faqTroubleTitle:"Troubleshooting",troubleNoChat:"“Send test message” disabled? The bot must have received one message first, so it knows which chat to send to.",troubleConnError:"Connection status shows an error? Check the credentials; for Feishu also confirm the API domain and the long-connection event subscription."},subagentPanel:{topologyLabel:"Call graph",mainSessionNote:"The main conversation stays in the chat area",empty:"No subagents in the current task yet",nodeRunning:"running",nodeDone:"done",openAsSession:"Jump to this session",subagentGone:"This subagent session no longer exists and could not be revived"},files:{title:"Files",upload:"Upload",download:"Download",openInNewTab:"Open in new tab",previewNotIsolatedHint:"This address has no separate preview origin, so the page opens sandboxed: localStorage, cookies and third-party embeds will not work. Reach the app over 127.0.0.1 or localhost, or set PENGUIN_PREVIEW_ORIGIN.",refresh:"Refresh",root:"Workspace root",empty:"Empty directory",previewUnsupported:"Preview not supported for this type; download instead",uploaded:"Uploaded",overwriteTitle:"Overwrite existing files",overwriteConfirm:e=>`The current directory already has ${e} file(s) with these names — uploading will overwrite:`,loadFailed:"Failed to load",previewTruncated:"File too large; preview truncated, download for the full file",details:"Details",workspacePath:"Workspace path",htmlRendered:"Rendered",htmlSource:"Source",backToList:"Back to list"},usage:{title:"Costs & usage",today:"Today",last7d:"Last 7 days",total:"Total",tokens:"Tokens",requests:"Requests",from:"From",to:"To",colCacheRead:"cache_read",colCacheWrite:"cache_write",colOutput:"output",uncostedNote:"* Only models with configured pricing count toward cost",filterAllAgents:"All agents",filterAllModels:"All models",rangeLabel:"Date range",rangeHour:"Last hour",rangeDay:"Last 24 hours",range7d:"Last 7 days",range30d:"Last 30 days",range90d:"Last 90 days",rangeCustom:"Custom",chartRequestsByAgent:"Requests & success rate by agent",chartRequestsByModel:"Requests & success rate by model",legendSuccessRate:"Success rate",chartTokenTrend:"Token trend",chartCostTrend:"Cost trend",legendOther:e=>`Other (${e})`,bucketTotal:"Total",legendHitRate:"Cache hit rate",empty:"No usage records",errors:"Errors",errorsTotal:"Total",errorsUnexpected:"Unexpected",errorsExpected:"Expected",errorsTopCode:"Most common",errorsColCode:"Source · code",errorsColKind:"Type",errorsColMessage:"Message",errorsEmpty:"No errors",errorsNewer:"Newer",errorsOlder:"Older",errorsPageOf:(e,t,n)=>`Page ${e} / ${t} · ${n} total`},traces:{timeline:"Execution timeline",laneLLM:"Model",kindThinking:"thinking",kindModelReply:"model reply",kindToolGen:"tool call gen",legendToolExec:"tool exec",legendOther:"Other",toolParams:"Parameter schema",requiredParam:"required",legendApprovalWait:"approval wait",task:e=>`Turn ${e}`,globalSummary:"Overall",tasksLabel:"Turns",messages:"Messages",truncatedNote:(e,t)=>`Showing first ${e} / ${t} messages`,zoom:"Zoom",zoomReset:"Double-click to reset zoom",zoomOut:"Zoom out",zoomIn:"Zoom in",linkHint:"Hover a timeline segment or event row to cross-highlight, click a segment to jump to its message; legend highlights its kind; drag the bar below to pan/zoom",filesTitle:"Trace files",toolCalls:"Tool calls",taskInput:"Input tokens this turn",taskOutput:"Output tokens this turn",cacheHit:"Cache hits",hitRate:"Hit rate",compactions:"compactions",inProgress:"in progress",systemPrompt:"System prompt",toolDefs:e=>`Tool definitions (${e})`,exportFile:"Export"},benchmark:{title:"Evaluation Center",selectBenchmark:"Select a Benchmark on the left",emptyAgent:"No Benchmarks for this agent",caseCount:e=>`${e} case${e===1?"":"s"}`,trendTitle:e=>`${e} over time`,cases:"Cases",viewCase:"View details",taskMaterials:"Task materials",rubric:"Scoring rubric",agentHidden:"Hidden from Target Agent",caseFileUnavailable:"Case files are unavailable",evaluations:"Evaluations",noEvaluations:"No evaluations yet",summaryLabel:"Summary",legendUnlabeled:"unlabeled model",colVersion:"Version",colModel:"Model ID",colThinkingLevel:"Thinking level",colScore:"Score",colDuration:"Duration",colCase:"Case",colRun:"Run",colSession:"Session"},errors:{networkError:"Network error, please check your connection",modelCredentialMissing:e=>`Model ${e} has no API key yet — configure it on the Models page first`,noDefaultModel:"This project has no default model yet — add one on the Models page first",byCode:{invalid_credentials:"Incorrect username or password.",too_many_attempts:"Too many failed sign-in attempts. Try again shortly.",password_mismatch:"The current password is incorrect.",invalid_password:"Password must be at least 8 characters.",admin_required:"Only an admin can perform this operation.",desktop_single_user:"The desktop app is single-user; user management is unavailable.",not_found:"This resource does not exist, or you do not have access.",internal:"The server hit an internal error. Please try again shortly.",agent_not_found:"This agent no longer exists.",unknown_agent:"That agent does not exist in this Project.",agent_exists:"This agent id is already taken.",agent_deleting:"This agent is being deleted.",project_exists:"This Project id is already taken.",project_not_found:"This Project no longer exists, or you do not have access.",cannot_delete_last_project:"This is the last Project and cannot be deleted.",user_exists:"This username is already taken.",user_not_found:"This user no longer exists.",cannot_delete_admin:"The built-in admin cannot be deleted.",member_not_found:"This user is not a member of the Project.",already_member:"This user is already a member of the Project.",already_owner:"This user is already an owner of the Project.",memory_import_confirm_required:"This import would overwrite or delete memories. Confirm it to continue.",schedule_exists:"A scheduled task with this name already exists.",schedule_not_found:"This scheduled task no longer exists.",unknown_skill:"This skill is not in the library.",skill_too_large:"This skill directory exceeds the import limits.",file_not_found:"This file no longer exists.",not_pending:"This message already went out and can no longer be recalled.",file_too_large:"The file is too large.",too_many_files:"Too many files attached to one message.",payload_too_large:"The request is too large.",image_too_large:"The image is too large to send inline.",dir_not_absolute:"The directory must be an absolute path.",dir_not_found:"That directory does not exist or is inaccessible.",not_a_dir:"That path is not a directory.",path_not_found:"That path does not exist.",workspace_missing:"This Session's Workspace no longer exists.",workspace_not_found:"That Workspace does not exist, or is not a directory.",session_not_found:"This Session no longer exists, or you do not have access.",session_deleting:"This Session is being deleted.",approval_not_found:"This approval request was already answered, or is no longer valid.",process_not_found:"This background process already exited, or was removed.",process_running:"This background process is still running — stop it before removing it.",memory_file_not_found:"This memory file no longer exists.",memory_scope_not_found:"This memory scope no longer exists.",task_in_progress:"This Session already has a task running.",compacting:"This Session is compacting its context and is not accepting new input.",shutting_down:"The server is shutting down. Please try again shortly.",compaction_not_configured:"This agent does not have context compaction configured.",nothing_to_compact:"There is nothing to compact in the current context yet (no completed conversation turn).",already_compacted:"The context was just compacted and nothing has been said since — no need to compact again.",version_conflict:"The snapshot's version is not newer than the current one.",invalid_title:"The title is invalid.",invalid_proxy_url:"Invalid proxy address — use an http(s):// or socks5:// proxy URL, or host[:port].",invalid_attachment_limit:"Invalid upload limit — use a whole number of MB inside the allowed range, with the total no lower than the per-file limit.",invalid_trace:"This file is not a valid Trace file.",trace_not_found:"This Trace file no longer exists.",trace_session_exists:"This agent already has a Session with that id; a duplicate Trace cannot be imported.",feishu_app_in_use:"This Feishu app is already bound to another Session — unbind it there or use a different app.",feishu_secret_required:"App Secret is required.",feishu_not_bound:"This Session has no Feishu binding yet.",feishu_no_chat:"No Feishu message received yet — message the bot once in Feishu first.",feishu_send_failed:"Sending the Feishu message failed.",telegram_bot_in_use:"This Telegram bot is already bound to another Session — unbind it there or use a different bot.",telegram_token_required:"Bot Token is required.",telegram_token_invalid:"The Bot Token is malformed: it looks like <digits>:<secret>.",telegram_not_bound:"This Session has no Telegram binding yet.",telegram_no_chat:"No Telegram message received yet — message the bot once in Telegram first.",telegram_send_failed:"Sending the Telegram message failed.",another_channel_enabled:"Another channel's connection is enabled on this conversation: disable it first.",messaging_disable_before_clear:"Disable this channel's connection before clearing its credential."}}},Pj="penguin.lang",zj=y.createContext(null);function Y3(e){return e?.toLowerCase().startsWith("zh")?"zh":"en"}function X3(){return Y3(navigator.language)}function Q3(e){return e==="system"?X3():e}function Z3(){const e=localStorage.getItem(Pj);return e==="zh"||e==="en"||e==="system"?e:"system"}function J3({children:e}){const[t,n]=y.useState(Z3),[,s]=y.useState(0),o=Q3(t);K3(o==="en"?W3:Uj),y.useEffect(()=>{if(t!=="system")return;const u=()=>s(f=>f+1);return window.addEventListener("languagechange",u),()=>window.removeEventListener("languagechange",u)},[t]);const c=y.useCallback(u=>{localStorage.setItem(Pj,u),n(u)},[]);return a.jsx(zj.Provider,{value:{lang:t,locale:o,setLang:c},children:e})}function eE({children:e}){const{locale:t}=Dr();return a.jsx("div",{className:"contents",children:e},t)}function Dr(){const e=y.useContext(zj);if(!e)throw new Error("useLocale must be used within a LocaleProvider");return e}const wx=7,Bj="penguin.theme",Hj="penguin.fontScale",Fj="penguin.accent",qj="penguin.currency",Vj="penguin.terminal.theme",tE={sm:"16px",md:"18px",lg:"20px"},Gj=y.createContext(null);function nE(){const e=localStorage.getItem(Bj);return e==="light"||e==="dark"||e==="system"?e:"system"}function rE(){const e=localStorage.getItem(Hj);return e==="sm"||e==="md"||e==="lg"?e:"md"}function aE(){const e=localStorage.getItem(Fj);return e==="neutral"||e==="blue"||e==="green"||e==="violet"||e==="rose"||e==="amber"?e:"neutral"}function sE(){const e=localStorage.getItem(Vj);return e==="light"||e==="dark"||e==="app"?e:"app"}function iE(){return localStorage.getItem(qj)==="CNY"?"CNY":"USD"}function oE(){return window.matchMedia("(prefers-color-scheme: dark)").matches}function lE({children:e}){const[t,n]=y.useState(nE),[s,o]=y.useState(oE),[c,u]=y.useState(rE),[f,p]=y.useState(aE),[h,x]=y.useState(iE),[g,v]=y.useState(sE),w=t==="system"?s:t==="dark",S=g==="app"?w:g==="dark";y.useEffect(()=>{document.documentElement.classList.toggle("dark",w)},[w]),y.useEffect(()=>{document.documentElement.style.fontSize=tE[c]},[c]),y.useEffect(()=>{f==="neutral"?delete document.documentElement.dataset.accent:document.documentElement.dataset.accent=f},[f]),y.useEffect(()=>{if(t!=="system")return;const D=window.matchMedia("(prefers-color-scheme: dark)"),z=E=>o(E.matches);return o(D.matches),D.addEventListener("change",z),()=>D.removeEventListener("change",z)},[t]);const C=y.useCallback(D=>{localStorage.setItem(Bj,D),n(D)},[]),N=y.useCallback(D=>{localStorage.setItem(Hj,D),u(D)},[]),T=y.useCallback(D=>{localStorage.setItem(Fj,D),p(D)},[]),_=y.useCallback(D=>{localStorage.setItem(qj,D),x(D)},[]),R=y.useCallback(D=>{localStorage.setItem(Vj,D),v(D)},[]);return a.jsx(Gj.Provider,{value:{mode:t,dark:w,setMode:C,fontScale:c,setFontScale:N,accent:f,setAccent:T,currency:h,setCurrency:_,terminalMode:g,setTerminalMode:R,terminalDark:S},children:e})}function as(){const e=y.useContext(Gj);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e}const cE=[{value:"neutral",color:"#6b7280"},{value:"blue",color:"#2563eb"},{value:"green",color:"#15803d"},{value:"violet",color:"#7c3aed"},{value:"rose",color:"#be123c"},{value:"amber",color:"#b45309"}];class xr extends Error{status;code;constructor(t,n,s){super(s),this.name="ApiError",this.status=t,this.code=n}}let Kj=null;function H1(e){Kj=e}function uE(e){return e.startsWith("/api/auth/")}async function Ee(e,t={}){return(await Wj(e,t)).data}async function Wj(e,t={}){let n=e;if(t.query){const f=new URLSearchParams;for(const[h,x]of Object.entries(t.query))x!==void 0&&f.set(h,String(x));const p=f.toString();p&&(n+=`?${p}`)}let s;try{s=await fetch(n,{method:t.method??"GET",credentials:"same-origin",...t.body!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)}:{}})}catch{throw new xr(0,"network_error",d.errors.networkError)}if(!s.ok){let f="http_error",p=d.common.unknownError;try{const h=await s.json();h.error?.code&&(f=h.error.code),h.error?.message&&(p=h.error.message)}catch{}throw s.status===401&&!uE(e)&&Kj?.(),new xr(s.status,f,p)}const o=Date.parse(s.headers.get("date")??""),c=Number.isFinite(o)?o:null;if(s.status===204)return{data:void 0,serverNowMs:c};const u=await s.text();return u?{data:JSON.parse(u),serverNowMs:c}:{data:void 0,serverNowMs:c}}const dE=e=>Ee("/api/auth/login",{method:"POST",body:e}),mE=()=>Ee("/api/auth/logout",{method:"POST",body:{}}),qm=()=>Ee("/api/me"),fE=e=>Ee("/api/me/password",{method:"PUT",body:e}),Sx=()=>Ee("/api/me/prefs"),Nf=e=>Ee("/api/me/prefs",{method:"PUT",body:e}),pE=()=>Ee("/api/admin/users"),hE=e=>Ee("/api/admin/users",{method:"POST",body:e}),gE=(e,t)=>Ee(`/api/admin/users/${encodeURIComponent(e)}/password`,{method:"POST",body:t}),xE=e=>Ee(`/api/admin/users/${encodeURIComponent(e)}`,{method:"DELETE"}),Yj=()=>Ee("/api/admin/settings"),Xj=e=>Ee("/api/admin/settings",{method:"PUT",body:e}),yE=()=>Ee("/api/projects"),bE=e=>Ee("/api/projects",{method:"POST",body:e}),vE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),kE=e=>Ee(`/api/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),mg=e=>Ee(`/api/projects/${encodeURIComponent(e)}/members`),wE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/members`,{method:"POST",body:t}),SE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:"DELETE"}),Qj=e=>Ee(`/api/projects/${encodeURIComponent(e)}/chat-defaults`),jE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/chat-defaults`,{method:"PUT",body:t}),CE=e=>Ee(`/api/projects/${encodeURIComponent(e)}/command-policy`),NE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/command-policy`,{method:"PUT",body:t}),Ml=e=>Ee(`/api/projects/${encodeURIComponent(e)}/models`),TE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models`,{method:"PUT",body:t}),ME=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/default`,{method:"PUT",body:t}),Zj=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/test`,{method:"POST",body:t}),Jj=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/detect`,{method:"POST",body:t}),EE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/list`,{method:"POST",body:t}),AE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/detect-vision`,{method:"POST",body:t}),_E=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/start`,{method:"POST",body:t}),RE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/${encodeURIComponent(t)}`),IE=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/${encodeURIComponent(t)}/code`,{method:"POST",body:{code:n}}),LE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault`),OE=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault`,{method:"PUT",body:n}),DE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault/template-placeholder`,{method:"POST",body:{}}),$E=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/template-placeholder`,{method:"POST",body:{}}),UE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/template-placeholder`,{method:"POST",body:{}}),Tf=(e,t)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/memory`,jx=(e,t,n)=>`${Tf(e,t)}/scopes/${encodeURIComponent(n)}/files`,eC=(e,t)=>Ee(Tf(e,t)),PE=(e,t)=>Ee(`${Tf(e,t)}/template-placeholder`,{method:"POST",body:{}}),tC=(e,t,n)=>Ee(jx(e,t,n)),nC=(e,t,n,s)=>Ee(`${jx(e,t,n)}/${encodeURIComponent(s)}`),zE=(e,t,n,s)=>Ee(`${jx(e,t,n)}/${encodeURIComponent(s)}`,{method:"DELETE"}),rC=(e,t,n)=>`${Tf(e,t)}/scopes/${encodeURIComponent(n)}`,BE=(e,t,n)=>Ee(`${rC(e,t,n)}/export`),HE=(e,t,n,s)=>Ee(`${rC(e,t,n)}/import`,{method:"POST",body:s}),aC=e=>Ee(`/api/projects/${encodeURIComponent(e)}/agents`),FE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents`,{method:"POST",body:t}),Ao=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config`),To=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config`,{method:"PUT",body:n}),F1=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/mcp-test`,{method:"POST",body:n}),qE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/reset`,{method:"POST"}),VE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/kernel-update`,{method:"POST"}),c0=(e,t,n)=>{const s=n?`?limit=${n.limit}&offset=${n.offset}`+(n.category?`&category=${n.category}`:"")+(n.workspaceGroup?`&workspaceGroup=${encodeURIComponent(n.workspaceGroup)}`:"")+(n.withCounts?"&counts=1":""):"";return Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/sessions${s}`)},GE=(e,t="")=>Ee(`/api/projects/${encodeURIComponent(e)}/dirs?path=${encodeURIComponent(t)}`),KE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/dir-skills?path=${encodeURIComponent(t)}`),u0=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/sessions`,{method:"POST",body:n}),WE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",body:t}),d0=e=>Ee(`/api/sessions/${encodeURIComponent(e)}`),tf=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),nf=e=>Ee(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"}),YE=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging`),XE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/feishu`,{method:"PUT",body:t}),QE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/telegram`,{method:"PUT",body:t}),ZE=(e,t,n)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/${t}/state`,{method:"POST",body:{enabled:n}}),JE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/feishu/test`,{method:"POST",body:t}),eA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/telegram/test`,{method:"POST",body:t}),tA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/${t}/test-message`,{method:"POST",body:{}}),sC=(e,t)=>{const n=t===void 0?"":t.kind==="tail"?`?tailLimit=${t.limit}`:`?before=${encodeURIComponent(t.cursor)}&limit=${t.limit}`;return Wj(`/api/sessions/${encodeURIComponent(e)}/messages${n}`).then(({data:s,serverNowMs:o})=>({...s,serverNowMs:o}))},su=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/tasks`,{method:"POST",body:t}),nA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/goal`),rA=(e,t,n)=>Ee(`/api/sessions/${encodeURIComponent(e)}/approvals/${encodeURIComponent(t)}`,{method:"POST",body:n}),aA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/abort`,{method:"POST",body:{}}),sA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/retry-now`,{method:"POST",body:{}}),q1=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes`),iA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}/kill`,{method:"POST",body:{}}),oA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}`,{method:"DELETE"}),lA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/steer`,{method:"POST",body:t}),cA=(e,t,n,s)=>Ee(`/api/sessions/${encodeURIComponent(e)}/subagents/${encodeURIComponent(t)}/message`,{method:"POST",body:{text:n,...s?{thinkingLevel:s}:{}}}),uA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/subagents/${encodeURIComponent(t)}/abort`,{method:"POST",body:{}}),dA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/steer/${encodeURIComponent(t)}`,{method:"DELETE"}),mA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/follow-ups/${encodeURIComponent(t)}`,{method:"DELETE"}),fA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/compact`,{method:"POST",body:{}}),pA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/context`),hA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/traces`),gA=(e,t,n,s,o,c)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}`,{query:{offset:o,limit:c}}),xA=(e,t,n,s)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}/analysis`),yA=(e,t,n,s)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}/download`,bA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/import`,{method:"POST",body:n}),vA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/usage/errors`,{query:{offset:String(t.offset),limit:String(t.limit),from:t.from,to:t.to,agentId:t.agentId}}),iC=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/usage`,{query:{from:t.from,to:t.to,fromTs:t.fromTs,toTs:t.toTs,groupBy:t.groupBy,granularity:t.granularity,agentId:t.agentId,provider:t.provider,modelId:t.modelId}}),kA=(e,t)=>Ee(`/api/projects/${e}/agents/${t}`,{method:"DELETE"}),wA=(e,t)=>Ee(`/api/sessions/${e}/files`,{query:{path:t}}),ji=(e,t,n=!1)=>`/api/sessions/${e}/files/content?path=${encodeURIComponent(t)}${n?"&download=1":""}`,V1=(e,t)=>`/api/sessions/${e}/files/preview-redirect?path=${encodeURIComponent(t)}`,SA=(e,t,n)=>Ee(`/api/sessions/${e}/files/content`,{method:"PUT",body:{dataBase64:n},query:{path:t}}),jA=(e,t)=>Ee(`/api/sessions/${e}/files/stat`,{method:"POST",body:{paths:t}}),CA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules`),NA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules`,{method:"POST",body:n}),G1=(e,t,n,s)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/${encodeURIComponent(n)}`,{method:"PUT",body:s}),TA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/${encodeURIComponent(n)}`,{method:"DELETE"}),oC=()=>Ee("/api/skills"),Bu=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills`),K1=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills`,{method:"POST",body:{names:n}}),MA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/archive`,{method:"POST",body:n}),EA=(e,t,n)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/archive`,lC=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}`,{method:"DELETE"}),AA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks`),_A=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks/${encodeURIComponent(n)}/cases`),cC=(e,t,n,s,o)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks/${encodeURIComponent(n)}/cases/${encodeURIComponent(s)}${o==="rubric"?"/rubric":""}/files`,RA=(e,t,n,s,o,c)=>Ee(cC(e,t,n,s,c),{query:{path:o}}),IA=(e,t,n,s,o,c,u)=>`${cC(e,t,n,s,c)}/content?path=${encodeURIComponent(o)}`+(u?.download?"&download=1":"")+(u?.preview&&!u.download?"&preview=1":""),LA=(e,t)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/export`,OA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/import`,{method:"POST",body:n}),DA=()=>Ee("/api/version"),uC=(e=!1)=>Ee(`/api/version/update-check${e?"?force=1":""}`),$A=()=>Ee("/api/version/update",{method:"POST",body:{}}),UA=()=>Ee("/api/desktop/update"),PA=()=>Ee("/api/desktop/update/check",{method:"POST",body:{}}),zA=()=>Ee("/api/desktop/update/install",{method:"POST",body:{}}),BA={attachmentMaxMb:100,attachmentTotalMb:120,attachmentMaxCount:20,imageMaxMb:20,attachmentLimitMinMb:1,attachmentLimitMaxMb:200},dC=y.createContext(null);function HA({children:e}){const[t,n]=y.useState(void 0),[s,o]=y.useState(!0),[c,u]=y.useState(!1),[f,p]=y.useState("password"),[h,x]=y.useState(BA);y.useEffect(()=>(H1(()=>n(null)),()=>H1(null)),[]),y.useEffect(()=>{let S=!1;return qm().then(C=>{S||(n(C.user),o(C.previewIsolated),u(C.desktopMode),p(C.sessionVia),x(C.uploadLimits))}).catch(C=>{S||(C instanceof xr&&C.status,n(null))}),()=>{S=!0}},[]);const g=y.useCallback(async(S,C)=>{const N=await dE({userId:S,password:C});n(N.user);try{const T=await qm();n(T.user),o(T.previewIsolated),u(T.desktopMode),p(T.sessionVia),x(T.uploadLimits)}catch{}},[]),v=y.useCallback(async()=>{try{await mE()}finally{n(null)}},[]),w=y.useCallback(async()=>{const S=await qm();n(S.user),o(S.previewIsolated),u(S.desktopMode),p(S.sessionVia),x(S.uploadLimits)},[]);return a.jsx(dC.Provider,{value:{user:t,previewIsolated:s,desktopMode:c,sessionVia:f,uploadLimits:h,login:g,logout:v,refresh:w},children:e})}function mn(){const e=y.useContext(dC);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const Cx=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,mC=/^[\\/]{2}/;function FA(e,t){return t+e.replace(/\\/g,"/")}const W1="popstate";function Y1(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function qA(e={}){function t(s,o){let c=o.state?.masked,{pathname:u,search:f,hash:p}=c||s.location;return m0("",{pathname:u,search:f,hash:p},o.state&&o.state.usr||null,o.state&&o.state.key||"default",c?{pathname:s.location.pathname,search:s.location.search,hash:s.location.hash}:void 0)}function n(s,o){return typeof o=="string"?o:bu(o)}return GA(t,n,null,e)}function wn(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Cs(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function VA(){return Math.random().toString(36).substring(2,10)}function X1(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function m0(e,t,n=null,s,o){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Ul(t):t,state:n,key:t&&t.key||s||VA(),mask:o}}function bu({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Ul(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let s=e.indexOf("?");s>=0&&(t.search=e.substring(s),e=e.substring(0,s)),e&&(t.pathname=e)}return t}function GA(e,t,n,s={}){let{window:o=document.defaultView,v5Compat:c=!1}=s,u=o.history,f="POP",p=null,h=x();h==null&&(h=0,u.replaceState({...u.state,idx:h},""));function x(){return(u.state||{idx:null}).idx}function g(){f="POP";let N=x(),T=N==null?null:N-h;h=N,p&&p({action:f,location:C.location,delta:T})}function v(N,T){f="PUSH";let _=Y1(N)?N:m0(C.location,N,T);h=x()+1;let R=X1(_,h),D=C.createHref(_.mask||_);try{u.pushState(R,"",D)}catch(z){if(z instanceof DOMException&&z.name==="DataCloneError")throw z;o.location.assign(D)}c&&p&&p({action:f,location:C.location,delta:1})}function w(N,T){f="REPLACE";let _=Y1(N)?N:m0(C.location,N,T);h=x();let R=X1(_,h),D=C.createHref(_.mask||_);u.replaceState(R,"",D),c&&p&&p({action:f,location:C.location,delta:0})}function S(N){return KA(o,N)}let C={get action(){return f},get location(){return e(o,u)},listen(N){if(p)throw new Error("A history only accepts one active listener");return o.addEventListener(W1,g),p=N,()=>{o.removeEventListener(W1,g),p=null}},createHref(N){return t(o,N)},createURL:S,encodeLocation(N){let T=S(N);return{pathname:T.pathname,search:T.search,hash:T.hash}},push:v,replace:w,go(N){return u.go(N)}};return C}function KA(e,t,n=!1){let s="http://localhost";e&&(s=e.location.origin!=="null"?e.location.origin:e.location.href),wn(s,"No window.location.(origin|href) available to create URL");let o=typeof t=="string"?t:bu(t);return o=o.replace(/ $/,"%20"),!n&&mC.test(o)&&(o=s+o),new URL(o,s)}function fC(e,t,n="/"){return WA(e,t,n,!1)}function WA(e,t,n,s,o){let c=Ri((typeof t=="string"?Ul(t):t).pathname||"/",n);if(c==null)return null;let u=YA(e),f=null,p=yC(c);for(let h=0;f==null&&h<u.length;++h)f=o_(u[h],p,s);return f}function YA(e){let t=pC(e);return XA(t),t}function pC(e,t=[],n=[],s="",o=!1){let c=(u,f,p=o,h)=>{let x={relativePath:h===void 0?u.path||"":h,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(x.relativePath.startsWith("/")){if(!x.relativePath.startsWith(s)&&p)return;wn(x.relativePath.startsWith(s),`Absolute route path "${x.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),x.relativePath=x.relativePath.slice(s.length)}let g=Za([s,x.relativePath]),v=n.concat(x);u.children&&u.children.length>0&&(wn(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),pC(u.children,t,v,g,p)),!(u.path==null&&!u.index)&&t.push({path:g,score:s_(g,u.index),routesMeta:v.map((w,S)=>{let[C,N]=xC(w.relativePath,w.caseSensitive,S===v.length-1);return{...w,matcher:C,compiledParams:N}})})};return e.forEach((u,f)=>{if(u.path===""||!u.path?.includes("?"))c(u,f);else for(let p of hC(u.path))c(u,f,!0,p)}),t}function hC(e){let t=e.split("/");if(t.length===0)return[];let[n,...s]=t,o=n.endsWith("?"),c=n.replace(/\?$/,"");if(s.length===0)return o?[c,""]:[c];let u=hC(s.join("/")),f=[];return f.push(...u.map(p=>p===""?c:[c,p].join("/"))),o&&f.push(...u),f.map(p=>e.startsWith("/")&&p===""?"/":p)}function XA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:i_(t.routesMeta.map(s=>s.childrenIndex),n.routesMeta.map(s=>s.childrenIndex)))}const QA=/^:[\w-]+$/,ZA=/^:[\w-]+/,JA=3.5,e_=3,t_=2,n_=1,r_=10,a_=-2,Q1=e=>e==="*";function s_(e,t){let n=e.split("/"),s=n.length;return n.some(Q1)&&(s+=a_),t&&(s+=t_),n.filter(o=>!Q1(o)).reduce((o,c)=>o+(QA.test(c)?e_:ZA.test(c)?JA:c===""?n_:r_),s)}function i_(e,t){return e.length===t.length&&e.slice(0,-1).every((n,s)=>n===t[s])?e[e.length-1]-t[t.length-1]:0}function o_(e,t,n=!1){let{routesMeta:s}=e,o={},c="/",u=[];for(let f=0;f<s.length;++f){let p=s[f],h=f===s.length-1,x=c==="/"?t:t.slice(c.length)||"/",g={path:p.relativePath,caseSensitive:p.caseSensitive,end:h},v=p.matcher&&p.compiledParams?gC(g,x,p.matcher,p.compiledParams):vu(g,x),w=p.route;if(!v&&h&&n&&!s[s.length-1].route.index&&(v=vu({path:p.relativePath,caseSensitive:p.caseSensitive,end:!1},x)),!v)return null;Object.assign(o,v.params),u.push({params:o,pathname:Za([c,v.pathname]),pathnameBase:u_(Za([c,v.pathnameBase])),route:w}),v.pathnameBase!=="/"&&(c=Za([c,v.pathnameBase]))}return u}function vu(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,s]=xC(e.path,e.caseSensitive,e.end);return gC(e,t,n,s)}function gC(e,t,n,s){let o=t.match(n);if(!o)return null;let c=o[0],u=c.replace(/(.)\/+$/,"$1"),f=o.slice(1);return{params:s.reduce((p,{paramName:h,isOptional:x},g)=>{if(h==="*"){let w=f[g]||"";u=c.slice(0,c.length-w.length).replace(/(.)\/+$/,"$1")}const v=f[g];return x&&!v?p[h]=void 0:p[h]=(v||"").replace(/%2F/g,"/"),p},{}),pathname:c,pathnameBase:u,pattern:e}}function xC(e,t=!1,n=!0){Cs(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let s=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,u,f,p,h)=>{if(s.push({paramName:u,isOptional:f!=null}),f){let x=h.charAt(p+c.length);return x&&x!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(?=\/|$|\()/g,"(?:/$1)?");return e.endsWith("*")?(s.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),s]}function yC(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Cs(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Ri(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,s=e.charAt(n);return s&&s!=="/"?null:e.slice(n)||"/"}function l_(e,t="/"){let{pathname:n,search:s="",hash:o=""}=typeof e=="string"?Ul(e):e,c;return n?(n=bC(n),n.startsWith("/")?c=Z1(n.substring(1),"/"):c=Z1(n,t)):c=t,{pathname:c,search:d_(s),hash:m_(o)}}function Z1(e,t){let n=vC(t).split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function fg(e,t,n,s){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function c_(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Nx(e){let t=c_(e);return t.map((n,s)=>s===t.length-1?n.pathname:n.pathnameBase)}function Mf(e,t,n,s=!1){let o;typeof e=="string"?o=Ul(e):(o={...e},wn(!o.pathname||!o.pathname.includes("?"),fg("?","pathname","search",o)),wn(!o.pathname||!o.pathname.includes("#"),fg("#","pathname","hash",o)),wn(!o.search||!o.search.includes("#"),fg("#","search","hash",o)));let c=e===""||o.pathname==="",u=c?"/":o.pathname,f;if(u==null)f=n;else{let g=t.length-1;if(!s&&u.startsWith("..")){let v=u.split("/");for(;v[0]==="..";)v.shift(),g-=1;o.pathname=v.join("/")}f=g>=0?t[g]:"/"}let p=l_(o,f),h=u&&u!=="/"&&u.endsWith("/"),x=(c||u===".")&&n.endsWith("/");return!p.pathname.endsWith("/")&&(h||x)&&(p.pathname+="/"),p}const bC=e=>e.replace(/[\\/]{2,}/g,"/"),Za=e=>bC(e.join("/")),vC=e=>e.replace(/\/+$/,""),u_=e=>vC(e).replace(/^\/*/,"/"),d_=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,m_=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;var f_=class{status;statusText;data;error;internal;constructor(e,t,n,s=!1){this.status=e,this.statusText=t||"",this.internal=s,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function p_(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function h_(e){return Za(e.map(t=>t.route.path).filter(Boolean))||"/"}const kC=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function wC(e,t){let n=e;if(typeof n!="string"||!Cx.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let s=n,o=!1;if(kC)try{let c=new URL(window.location.href),u=mC.test(n)?new URL(FA(n,c.protocol)):new URL(n),f=Ri(u.pathname,t);u.origin===c.origin&&f!=null?n=f+u.search+u.hash:o=!0}catch{Cs(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:s,isExternal:o,to:n}}const SC=["POST","PUT","PATCH","DELETE"];new Set(SC);const g_=["GET",...SC];new Set(g_);const x_=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function y_(e){try{return x_.includes(new URL(e).protocol)}catch{return!1}}const Pl=y.createContext(null);Pl.displayName="DataRouter";const Ef=y.createContext(null);Ef.displayName="DataRouterState";const jC=y.createContext(!1);function b_(){return y.useContext(jC)}const CC=y.createContext({isTransitioning:!1});CC.displayName="ViewTransition";const v_=y.createContext(new Map);v_.displayName="Fetchers";const k_=y.createContext(null);k_.displayName="Await";const qa=y.createContext(null);qa.displayName="Navigation";const Hu=y.createContext(null);Hu.displayName="Location";const Va=y.createContext({outlet:null,matches:[],isDataRoute:!1});Va.displayName="Route";const Tx=y.createContext(null);Tx.displayName="RouteError";const NC="REACT_ROUTER_ERROR",w_="REDIRECT",S_="ROUTE_ERROR_RESPONSE";function j_(e){if(e.startsWith(`${NC}:${w_}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function C_(e){if(e.startsWith(`${NC}:${S_}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new f_(t.status,t.statusText,t.data)}catch{}}function N_(e,{relative:t}={}){wn(_o(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:s}=y.useContext(qa),{hash:o,pathname:c,search:u}=Fu(e,{relative:t}),f=c;return n!=="/"&&(f=c==="/"?n:Za([n,c])),s.createHref({pathname:f,search:u,hash:o})}function _o(){return y.useContext(Hu)!=null}function $r(){return wn(_o(),"useLocation() may be used only in the context of a <Router> component."),y.useContext(Hu).location}function Mx(e){wn(_o(),"useMatch() may be used only in the context of a <Router> component.");let{pathname:t}=$r();return y.useMemo(()=>vu(e,yC(t)),[t,e])}const TC="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function yr(){let{isDataRoute:e}=y.useContext(Va);return e?H_():T_()}function T_(){wn(_o(),"useNavigate() may be used only in the context of a <Router> component.");let e=y.useContext(Pl),{basename:t,navigator:n}=y.useContext(qa),{matches:s}=y.useContext(Va),{pathname:o}=$r(),c=JSON.stringify(Nx(s)),u=y.useRef(!1);return y.useLayoutEffect(()=>{u.current=!0}),y.useCallback((f,p={})=>{if(Cs(u.current,TC),!u.current)return;if(typeof f=="number"){n.go(f);return}let h=Mf(f,JSON.parse(c),o,p.relative==="path");e==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:Za([t,h.pathname])),(p.replace?n.replace:n.push)(h,p.state,p)},[t,n,c,o,e])}const M_=y.createContext(null);function E_(e){let t=y.useContext(Va).outlet;return y.useMemo(()=>t&&y.createElement(M_.Provider,{value:e},t),[t,e])}function MC(){let{matches:e}=y.useContext(Va);return e[e.length-1]?.params??{}}function Fu(e,{relative:t}={}){let{matches:n}=y.useContext(Va),{pathname:s}=$r(),o=JSON.stringify(Nx(n));return y.useMemo(()=>Mf(e,JSON.parse(o),s,t==="path"),[e,o,s,t])}function A_(e,t){return EC(e,t)}function EC(e,t,n){wn(_o(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=y.useContext(qa),{matches:o}=y.useContext(Va),c=o[o.length-1],u=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let p=$r(),h;if(t){let S=typeof t=="string"?Ul(t):t;wn(f==="/"||S.pathname?.startsWith(f),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${f}" but pathname "${S.pathname}" was given in the \`location\` prop.`),h=S}else h=p;let x=h.pathname||"/",g=x;if(f!=="/"){let S=f.replace(/^\//,"").split("/");g="/"+x.replace(/^\//,"").split("/").slice(S.length).join("/")}let v=n&&n.state.matches.length?n.state.matches.map(S=>Object.assign(S,{route:n.manifest[S.route.id]||S.route})):fC(e,{pathname:g}),w=D_(v&&v.map(S=>Object.assign({},S,{params:Object.assign({},u,S.params),pathname:Za([f,s.encodeLocation?s.encodeLocation(S.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathname]),pathnameBase:S.pathnameBase==="/"?f:Za([f,s.encodeLocation?s.encodeLocation(S.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathnameBase])})),o,n);return t&&w?y.createElement(Hu.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...h},navigationType:"POP"}},w):w}function __(){let e=B_(),t=p_(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},t),n?y.createElement("pre",{style:{padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"}},n):null,null)}const R_=y.createElement(__,null);var I_=class extends y.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=jC;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=C_(e.digest);n&&(e=n)}let t=e!==void 0?y.createElement(Va.Provider,{value:this.props.routeContext},y.createElement(Tx.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?y.createElement(L_,{error:e},t):t}};const pg=new WeakMap;function L_({children:e,error:t}){let{basename:n}=y.useContext(qa);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let s=j_(t.digest);if(s){let o=pg.get(t);if(o)throw o;let c=wC(s.location,n),u=c.absoluteURL||c.to;if(y_(u))throw new Error("Invalid redirect location");if(kC&&!pg.get(t))if(c.isExternal||s.reloadDocument)window.location.href=u;else{const f=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(c.to,{replace:s.replace}));throw pg.set(t,f),f}return y.createElement("meta",{httpEquiv:"refresh",content:`0;url=${u}`})}}return e}function O_({routeContext:e,match:t,children:n}){let s=y.useContext(Pl);return s&&s.static&&s.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=t.route.id),y.createElement(Va.Provider,{value:e},n)}function D_(e,t=[],n){let s=n?.state;if(e==null){if(!s)return null;if(s.errors)e=s.matches;else if(t.length===0&&!s.initialized&&s.matches.length>0)e=s.matches;else return null}let o=e,c=s?.errors;if(c!=null){let x=o.findIndex(g=>g.route.id&&c?.[g.route.id]!==void 0);wn(x>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(c).join(",")}`),o=o.slice(0,Math.min(o.length,x+1))}let u=!1,f=-1;if(n&&s){u=s.renderFallback;for(let x=0;x<o.length;x++){let g=o[x];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(f=x),g.route.id){let{loaderData:v,errors:w}=s,S=g.route.loader&&!v.hasOwnProperty(g.route.id)&&(!w||w[g.route.id]===void 0);if(g.route.lazy||S){n.isStatic&&(u=!0),f>=0?o=o.slice(0,f+1):o=[o[0]];break}}}}let p=n?.onError,h=s&&p?(x,g)=>{p(x,{location:s.location,params:s.matches?.[0]?.params??{},pattern:h_(s.matches),errorInfo:g})}:void 0;return o.reduceRight((x,g,v)=>{let w,S=!1,C=null,N=null;s&&(w=c&&g.route.id?c[g.route.id]:void 0,C=g.route.errorElement||R_,u&&(f<0&&v===0?(F_("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,N=null):f===v&&(S=!0,N=g.route.hydrateFallbackElement||null)));let T=t.concat(o.slice(0,v+1)),_=()=>{let R;return w?R=C:S?R=N:g.route.Component?R=y.createElement(g.route.Component,null):g.route.element?R=g.route.element:R=x,y.createElement(O_,{match:g,routeContext:{outlet:x,matches:T,isDataRoute:s!=null},children:R})};return s&&(g.route.ErrorBoundary||g.route.errorElement||v===0)?y.createElement(I_,{location:s.location,revalidation:s.revalidation,component:C,error:w,children:_(),routeContext:{outlet:null,matches:T,isDataRoute:!0},onError:h}):_()},null)}function Ex(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function $_(e){let t=y.useContext(Pl);return wn(t,Ex(e)),t}function U_(e){let t=y.useContext(Ef);return wn(t,Ex(e)),t}function P_(e){let t=y.useContext(Va);return wn(t,Ex(e)),t}function Ax(e){let t=P_(e),n=t.matches[t.matches.length-1];return wn(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function z_(){return Ax("useRouteId")}function B_(){let e=y.useContext(Tx),t=U_("useRouteError"),n=Ax("useRouteError");return e!==void 0?e:t.errors?.[n]}function H_(){let{router:e}=$_("useNavigate"),t=Ax("useNavigate"),n=y.useRef(!1);return y.useLayoutEffect(()=>{n.current=!0}),y.useCallback(async(s,o={})=>{Cs(n.current,TC),n.current&&(typeof s=="number"?await e.navigate(s):await e.navigate(s,{fromRouteId:t,...o}))},[e,t])}const J1={};function F_(e,t,n){J1[e]||(J1[e]=!0,Cs(!1,n))}y.memo(q_);function q_({routes:e,manifest:t,future:n,state:s,isStatic:o,onError:c}){return EC(e,void 0,{manifest:t,state:s,isStatic:o,onError:c})}function ku({to:e,replace:t,state:n,relative:s}){wn(_o(),"<Navigate> may be used only in the context of a <Router> component.");let{static:o}=y.useContext(qa);Cs(!o,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:c}=y.useContext(Va),{pathname:u}=$r(),f=yr(),p=Mf(e,Nx(c),u,s==="path"),h=JSON.stringify(p);return y.useEffect(()=>{f(JSON.parse(h),{replace:t,state:n,relative:s})},[f,h,s,t,n]),null}function V_(e){return E_(e.context)}function da(e){wn(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function G_({basename:e="/",children:t=null,location:n,navigationType:s="POP",navigator:o,static:c=!1,useTransitions:u}){wn(!_o(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let f=e.replace(/^\/*/,"/"),p=y.useMemo(()=>({basename:f,navigator:o,static:c,useTransitions:u,future:{}}),[f,o,c,u]);typeof n=="string"&&(n=Ul(n));let{pathname:h="/",search:x="",hash:g="",state:v=null,key:w="default",mask:S}=n,C=y.useMemo(()=>{let N=Ri(h,f);return N==null?null:{location:{pathname:N,search:x,hash:g,state:v,key:w,mask:S},navigationType:s}},[f,h,x,g,v,w,s,S]);return Cs(C!=null,`<Router basename="${f}"> is not able to match the URL "${h}${x}${g}" because it does not start with the basename, so the <Router> won't render anything.`),C==null?null:y.createElement(qa.Provider,{value:p},y.createElement(Hu.Provider,{children:t,value:C}))}function K_({children:e,location:t}){return A_(f0(e),t)}function f0(e,t=[]){let n=[];return y.Children.forEach(e,(s,o)=>{if(!y.isValidElement(s))return;let c=[...t,o];if(s.type===y.Fragment){n.push.apply(n,f0(s.props.children,c));return}wn(s.type===da,`[${typeof s.type=="string"?s.type:s.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`);let u=s.props;wn(!u.index||!u.children,"An index route cannot have child routes.");let f={id:u.id||c.join("-"),caseSensitive:u.caseSensitive,element:u.element,Component:u.Component,index:u.index,path:u.path,middleware:u.middleware,loader:u.loader,action:u.action,hydrateFallbackElement:u.hydrateFallbackElement,HydrateFallback:u.HydrateFallback,errorElement:u.errorElement,ErrorBoundary:u.ErrorBoundary,shouldRevalidate:u.shouldRevalidate,handle:u.handle,lazy:u.lazy};u.children&&(f.children=f0(u.children,c)),n.push(f)}),n}const Vm="application/x-www-form-urlencoded";function Af(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function W_(e){return Af(e)&&e.tagName.toLowerCase()==="button"}function Y_(e){return Af(e)&&e.tagName.toLowerCase()==="form"}function X_(e){return Af(e)&&e.tagName.toLowerCase()==="input"}function Q_(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Z_(e,t){return e.button===0&&(!t||t==="_self")&&!Q_(e)}function p0(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let s=e[n];return t.concat(Array.isArray(s)?s.map(o=>[n,o]):[[n,s]])},[]))}function J_(e,t){let n=p0(e);return t&&t.forEach((s,o)=>{n.has(o)||t.getAll(o).forEach(c=>{n.append(o,c)})}),n}let gm=null;function eR(){if(gm===null)try{new FormData(document.createElement("form"),0),gm=!1}catch{gm=!0}return gm}const tR=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function hg(e){return e!=null&&!tR.has(e)?(Cs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Vm}"`),null):e}function nR(e,t){let n,s,o,c,u;if(Y_(e)){let f=e.getAttribute("action");s=f?Ri(f,t):null,n=e.getAttribute("method")||"get",o=hg(e.getAttribute("enctype"))||Vm,c=new FormData(e)}else if(W_(e)||X_(e)&&(e.type==="submit"||e.type==="image")){let f=e.form;if(f==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let p=e.getAttribute("formaction")||f.getAttribute("action");if(s=p?Ri(p,t):null,n=e.getAttribute("formmethod")||f.getAttribute("method")||"get",o=hg(e.getAttribute("formenctype"))||hg(f.getAttribute("enctype"))||Vm,c=new FormData(f,e),!eR()){let{name:h,type:x,value:g}=e;if(x==="image"){let v=h?`${h}.`:"";c.append(`${v}x`,"0"),c.append(`${v}y`,"0")}else h&&c.append(h,g)}}else{if(Af(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n="get",s=null,o=Vm,u=e}return c&&o==="text/plain"&&(u=c,c=void 0),{action:s,method:n.toLowerCase(),encType:o,formData:c,body:u}}function _x(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function AC(e,t){let n=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n.pathname.endsWith("/")?n.pathname=`${n.pathname}_.${t}`:n.pathname=`${n.pathname}.${t}`,n}async function rR(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function aR(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function sR(e,t,n){return cR((await Promise.all(e.map(async s=>{let o=t.routes[s.route.id];if(o){let c=await rR(o,n);return c.links?c.links():[]}return[]}))).flat(1).filter(aR).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function ew(e,t,n,s,o,c){let u=(p,h)=>n[h]?p.route.id!==n[h].route.id:!0,f=(p,h)=>n[h].pathname!==p.pathname||n[h].route.path?.endsWith("*")&&n[h].params["*"]!==p.params["*"];return c==="assets"?t.filter((p,h)=>u(p,h)||f(p,h)):c==="data"?t.filter((p,h)=>{let x=s.routes[p.route.id];if(!x||!x.hasLoader)return!1;if(u(p,h)||f(p,h))return!0;if(p.route.shouldRevalidate){let g=p.route.shouldRevalidate({currentUrl:new URL(o.pathname+o.search+o.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:p.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function iR(e,t,{includeHydrateFallback:n}={}){return oR(e.map(s=>{let o=t.routes[s.route.id];if(!o)return[];let c=[o.module];return o.clientActionModule&&(c=c.concat(o.clientActionModule)),o.clientLoaderModule&&(c=c.concat(o.clientLoaderModule)),n&&o.hydrateFallbackModule&&(c=c.concat(o.hydrateFallbackModule)),o.imports&&(c=c.concat(o.imports)),c}).flat(1))}function oR(e){return[...new Set(e)]}function lR(e){let t={},n=Object.keys(e).sort();for(let s of n)t[s]=e[s];return t}function cR(e,t){let n=new Set;return new Set(t),e.reduce((s,o)=>{let c=JSON.stringify(lR(o));return n.has(c)||(n.add(c),s.push({key:c,link:o})),s},[])}function uR(){let e=y.useContext(Pl);return _x(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function dR(){let e=y.useContext(Ef);return _x(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}const Rx=y.createContext(void 0);Rx.displayName="FrameworkContext";function Ix(){let e=y.useContext(Rx);return _x(e,"You must render this element inside a <HydratedRouter> element"),e}function mR(e,t){let n=y.useContext(Rx),[s,o]=y.useState(!1),[c,u]=y.useState(!1),{onFocus:f,onBlur:p,onMouseEnter:h,onMouseLeave:x,onTouchStart:g}=t,v=y.useRef(null);y.useEffect(()=>{if(e==="render"&&u(!0),e==="viewport"){let C=T=>{T.forEach(_=>{u(_.isIntersecting)})},N=new IntersectionObserver(C,{threshold:.5});return v.current&&N.observe(v.current),()=>{N.disconnect()}}},[e]),y.useEffect(()=>{if(s){let C=setTimeout(()=>{u(!0)},100);return()=>{clearTimeout(C)}}},[s]);let w=()=>{o(!0)},S=()=>{o(!1),u(!1)};return n?e!=="intent"?[c,v,{}]:[c,v,{onFocus:Pc(f,w),onBlur:Pc(p,S),onMouseEnter:Pc(h,w),onMouseLeave:Pc(x,S),onTouchStart:Pc(g,w)}]:[!1,v,{}]}function Pc(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function fR({page:e,...t}){let n=b_(),{nonce:s}=Ix(),{router:o}=uR(),c=y.useMemo(()=>fC(o.routes,e,o.basename),[o.routes,e,o.basename]);return c?(t.nonce==null&&s&&(t={...t,nonce:s}),n?y.createElement(hR,{page:e,matches:c,...t}):y.createElement(gR,{page:e,matches:c,...t})):null}function pR(e){let{manifest:t,routeModules:n}=Ix(),[s,o]=y.useState([]);return y.useEffect(()=>{let c=!1;return sR(e,t,n).then(u=>{c||o(u)}),()=>{c=!0}},[e,t,n]),s}function hR({page:e,matches:t,...n}){let s=$r(),o=y.useMemo(()=>{if(e===s.pathname+s.search+s.hash)return[];let c=AC(e,"rsc"),u=!1,f=[];for(let p of t)typeof p.route.shouldRevalidate=="function"?u=!0:f.push(p.route.id);return u&&f.length>0&&c.searchParams.set("_routes",f.join(",")),[c.pathname+c.search]},[e,s,t]);return y.createElement(y.Fragment,null,o.map(c=>y.createElement("link",{key:c,rel:"prefetch",as:"fetch",href:c,...n})))}function gR({page:e,matches:t,...n}){let s=$r(),{manifest:o,routeModules:c}=Ix(),{loaderData:u,matches:f}=dR(),p=y.useMemo(()=>ew(e,t,f,o,s,"data"),[e,t,f,o,s]),h=y.useMemo(()=>ew(e,t,f,o,s,"assets"),[e,t,f,o,s]),x=y.useMemo(()=>{if(e===s.pathname+s.search+s.hash)return[];let w=new Set,S=!1;if(t.forEach(N=>{let T=o.routes[N.route.id];!T||!T.hasLoader||(!p.some(_=>_.route.id===N.route.id)&&N.route.id in u&&c[N.route.id]?.shouldRevalidate||T.hasClientLoader?S=!0:w.add(N.route.id))}),w.size===0)return[];let C=AC(e,"data");return S&&w.size>0&&C.searchParams.set("_routes",t.filter(N=>w.has(N.route.id)).map(N=>N.route.id).join(",")),[C.pathname+C.search]},[u,s,o,p,t,e,c]),g=y.useMemo(()=>iR(h,o),[h,o]),v=pR(h);return y.createElement(y.Fragment,null,x.map(w=>y.createElement("link",{key:w,rel:"prefetch",as:"fetch",href:w,...n})),g.map(w=>y.createElement("link",{key:w,rel:"modulepreload",href:w,...n})),v.map(({key:w,link:S})=>y.createElement("link",{key:w,nonce:n.nonce,...S,crossOrigin:S.crossOrigin??n.crossOrigin})))}function xR(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}const yR=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{yR&&(window.__reactRouterVersion="8.3.0")}catch{}function bR({basename:e,children:t,useTransitions:n,window:s}){let o=y.useRef(null);o.current==null&&(o.current=qA({window:s,v5Compat:!0}));let c=o.current,[u,f]=y.useState({action:c.action,location:c.location}),p=y.useCallback(h=>{n===!1?f(h):y.startTransition(()=>f(h))},[n]);return y.useLayoutEffect(()=>c.listen(p),[c,p]),y.createElement(G_,{basename:e,children:t,location:u.location,navigationType:u.action,navigator:c,useTransitions:n})}const _C=y.forwardRef(function({onClick:t,discover:n="render",prefetch:s="none",relative:o,reloadDocument:c,replace:u,mask:f,state:p,target:h,to:x,preventScrollReset:g,viewTransition:v,defaultShouldRevalidate:w,...S},C){let{basename:N,navigator:T,useTransitions:_}=y.useContext(qa),R=typeof x=="string"&&Cx.test(x),D=wC(x,N);x=D.to;let z=N_(x,{relative:o}),E=$r(),L=null;if(f){let H=Mf(f,[],E.mask?E.mask.pathname:"/",!0);N!=="/"&&(H.pathname=H.pathname==="/"?N:Za([N,H.pathname])),L=T.createHref(H)}let[F,V,P]=mR(s,S),B=wR(x,{replace:u,mask:f,state:p,target:h,preventScrollReset:g,relative:o,viewTransition:v,defaultShouldRevalidate:w,useTransitions:_});function Y(H){t&&t(H),H.defaultPrevented||B(H)}let q=!(D.isExternal||c),K=y.createElement("a",{...S,...P,href:(q?L:void 0)||D.absoluteURL||z,onClick:q?Y:t,ref:xR(C,V),target:h,"data-discover":!R&&n==="render"?"true":void 0});return F&&!R?y.createElement(y.Fragment,null,K,y.createElement(fR,{page:z})):K});_C.displayName="Link";const Lx=y.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:s="",end:o=!1,style:c,to:u,viewTransition:f,children:p,...h},x){let g=Fu(u,{relative:h.relative}),v=$r(),w=y.useContext(Ef),{navigator:S,basename:C}=y.useContext(qa),N=w!=null&&TR(g)&&f===!0,T=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,_=v.pathname,R=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;n||(_=_.toLowerCase(),R=R?R.toLowerCase():null,T=T.toLowerCase()),R&&C&&(R=Ri(R,C)||R);const D=T!=="/"&&T.endsWith("/")?T.length-1:T.length;let z=_===T||!o&&_.startsWith(T)&&_.charAt(D)==="/",E=R!=null&&(R===T||!o&&R.startsWith(T)&&R.charAt(D)==="/"),L={isActive:z,isPending:E,isTransitioning:N},F=z?t:void 0,V;typeof s=="function"?V=s(L):V=[s,z?"active":null,E?"pending":null,N?"transitioning":null].filter(Boolean).join(" ");let P=typeof c=="function"?c(L):c;return y.createElement(_C,{...h,"aria-current":F,className:V,ref:x,style:P,to:u,viewTransition:f},typeof p=="function"?p(L):p)});Lx.displayName="NavLink";const vR=y.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:s,replace:o,state:c,method:u="get",action:f,onSubmit:p,relative:h,preventScrollReset:x,viewTransition:g,defaultShouldRevalidate:v,...w},S)=>{let{useTransitions:C}=y.useContext(qa),N=CR(),T=NR(f,{relative:h}),_=u.toLowerCase()==="get"?"get":"post",R=typeof f=="string"&&Cx.test(f),D=z=>{if(p&&p(z),z.defaultPrevented)return;z.preventDefault();let E=z.nativeEvent.submitter,L=E?.getAttribute("formmethod")||u,F=()=>N(E||z.currentTarget,{fetcherKey:t,method:L,navigate:n,replace:o,state:c,relative:h,preventScrollReset:x,viewTransition:g,defaultShouldRevalidate:v});C&&n!==!1?y.startTransition(()=>F()):F()};return y.createElement("form",{ref:S,method:_,action:T,onSubmit:s?p:D,...w,"data-discover":!R&&e==="render"?"true":void 0})});vR.displayName="Form";function kR(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function RC(e){let t=y.useContext(Pl);return wn(t,kR(e)),t}function wR(e,{target:t,replace:n,mask:s,state:o,preventScrollReset:c,relative:u,viewTransition:f,defaultShouldRevalidate:p,useTransitions:h}={}){let x=yr(),g=$r(),v=Fu(e,{relative:u});return y.useCallback(w=>{if(Z_(w,t)){w.preventDefault();let S=n!==void 0?n:bu(g)===bu(v),C=()=>x(e,{replace:S,mask:s,state:o,preventScrollReset:c,relative:u,viewTransition:f,defaultShouldRevalidate:p});h?y.startTransition(()=>C()):C()}},[g,x,v,n,s,o,t,e,c,u,f,p,h])}function Ox(e){Cs(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=y.useRef(p0(e)),n=y.useRef(!1),s=$r(),o=y.useMemo(()=>J_(s.search,n.current?null:t.current),[s.search]),c=yr();return[o,y.useCallback((u,f)=>{const p=p0(typeof u=="function"?u(new URLSearchParams(o)):u);n.current=!0,c("?"+p,f)},[c,o])]}let SR=0,jR=()=>`__${String(++SR)}__`;function CR(){let{router:e}=RC("useSubmit"),{basename:t}=y.useContext(qa),n=z_(),s=e.fetch,o=e.navigate;return y.useCallback(async(c,u={})=>{let{action:f,method:p,encType:h,formData:x,body:g}=nR(c,t);u.navigate===!1?await s(u.fetcherKey||jR(),n,u.action||f,{defaultShouldRevalidate:u.defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:x,body:g,formMethod:u.method||p,formEncType:u.encType||h,flushSync:u.flushSync}):await o(u.action||f,{defaultShouldRevalidate:u.defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:x,body:g,formMethod:u.method||p,formEncType:u.encType||h,replace:u.replace,state:u.state,fromRouteId:n,flushSync:u.flushSync,viewTransition:u.viewTransition})},[s,o,t,n])}function NR(e,{relative:t}={}){let{basename:n}=y.useContext(qa),s=y.useContext(Va);wn(s,"useFormAction must be used inside a RouteContext");let[o]=s.matches.slice(-1),c={...Fu(e||".",{relative:t})},u=$r();if(e==null){c.search=u.search;let f=new URLSearchParams(c.search),p=f.getAll("index");if(p.some(h=>h==="")){f.delete("index"),p.filter(x=>x).forEach(x=>f.append("index",x));let h=f.toString();c.search=h?`?${h}`:""}}return(!e||e===".")&&o.route.index&&(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(c.pathname=c.pathname==="/"?n:Za([n,c.pathname])),bu(c)}function TR(e,{relative:t}={}){let n=y.useContext(CC);wn(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:s}=RC("useViewTransitionState"),o=Fu(e,{relative:t});if(!n.isTransitioning)return!1;let c=Ri(n.currentLocation.pathname,s)||n.currentLocation.pathname,u=Ri(n.nextLocation.pathname,s)||n.nextLocation.pathname;return vu(o.pathname,u)!=null||vu(o.pathname,c)!=null}const tw=e=>{let t;const n=new Set,s=(h,x)=>{const g=typeof h=="function"?h(t):h;if(!Object.is(g,t)){const v=t;t=x??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(w=>w(t,v))}},o=()=>t,f={setState:s,getState:o,getInitialState:()=>p,subscribe:h=>(n.add(h),()=>n.delete(h))},p=t=e(s,o,f);return f},zl=(e=>e?tw(e):tw),MR=e=>e;function Bl(e,t=MR){const n=hm.useSyncExternalStore(e.subscribe,hm.useCallback(()=>t(e.getState()),[e,t]),hm.useCallback(()=>t(e.getInitialState()),[e,t]));return hm.useDebugValue(n),n}const nw="penguin.lastProjectId",rw=e=>`penguin.lastAgentId.${e}`,IC=y.createContext(null);function wu(e){return e.name??e.projectId}function _n(e){return e.name??e.agentId}function ER(){return zl((e,t)=>({projects:[],projectsLoading:!0,currentProjectId:null,agents:[],agentsLoading:!0,currentAgentId:null,reloadProjects:async()=>{e({projectsLoading:!0});try{const n=await yE(),s=t().currentProjectId??localStorage.getItem(nw),o=n.projects.find(c=>c.projectId===s);e({projects:n.projects,currentProjectId:(o??n.projects[0])?.projectId??null})}finally{e({projectsLoading:!1})}},setCurrentProjectId:n=>{n!==t().currentProjectId&&(localStorage.setItem(nw,n),e({currentProjectId:n,currentAgentId:null,agents:[],agentsLoading:!0}),Nf({lastProjectId:n}).catch(()=>{}))},reloadAgents:async()=>{const n=t().currentProjectId;if(n){e({agentsLoading:!0});try{const s=await aC(n),o=t().currentAgentId??localStorage.getItem(rw(n)),c=s.agents.find(f=>f.agentId===o),u=s.agents.find(f=>f.agentId==="default_agent")??s.agents[0]??null;e({agents:s.agents,currentAgentId:(c??u)?.agentId??null})}finally{e({agentsLoading:!1})}}},setCurrentAgentId:n=>{const s=t().currentProjectId;s&&localStorage.setItem(rw(s),n),e({currentAgentId:n})}}))}function AR({children:e}){const[t]=y.useState(ER),n=Bl(t);y.useEffect(()=>{t.getState().reloadProjects()},[t]);const{currentProjectId:s}=n;y.useEffect(()=>{t.setState({agents:[]}),t.getState().reloadAgents()},[t,s]);const o=y.useMemo(()=>{const c=n.projects.find(f=>f.projectId===n.currentProjectId)??null,u=n.agents.find(f=>f.agentId===n.currentAgentId)??null;return{projects:n.projects,projectsLoading:n.projectsLoading,currentProject:c,setCurrentProjectId:n.setCurrentProjectId,reloadProjects:n.reloadProjects,agents:n.agents,agentsLoading:n.agentsLoading,currentAgent:u,setCurrentAgentId:n.setCurrentAgentId,reloadAgents:n.reloadAgents}},[n]);return a.jsx(IC.Provider,{value:o,children:e})}function en(){const e=y.useContext(IC);if(!e)throw new Error("useProject must be used within a ProjectProvider");return e}function LC(e,t){const n=new EventSource(e);n.onmessage=o=>{try{t.onOmniMessage(JSON.parse(o.data),o.lastEventId||null)}catch{}},n.addEventListener("server_event",o=>{try{t.onServerEvent(JSON.parse(o.data),o.lastEventId||null)}catch{}}),t.onOpen&&(n.onopen=t.onOpen);const{onError:s}=t;return s&&(n.onerror=()=>s(n.readyState===EventSource.CLOSED)),{close:()=>n.close()}}function _R(e,t){return LC(`/api/sessions/${encodeURIComponent(e)}/stream`,t)}function RR(e){return LC("/api/events",e)}const Dx="\0temp-workspaces",IR=/[/\\]workspaces[/\\]tmp-[0-9a-f]{8}$/;function OC(e){const t=e.trim();return t===""||IR.test(t)}function vo(e){return OC(e)?Dx:e.trim()}function LR(e){return e===Dx?"temp":e}function $x(e){const t=e.trim().split(/[/\\]+/).filter(Boolean);return t[t.length-1]??"/"}const bs=10,_f=10;function DC(e,t=_f){return Math.max(1,Math.ceil(e/t))}function $C(e,t,n=_f){return Math.min(Math.max(e,0),DC(t,n)-1)}function OR(e,t=_f){return Math.floor(Math.max(e,0)/t)}function aw(e,t,n=_f){const s=$C(t,e.length,n)*n;return e.slice(s,s+n)}function DR({shown:e,loaded:t,total:n,fullyLoaded:s}){return Math.max((s?t:Math.max(n,t))-e,0)}function sw(e,t){return e.length>t?{items:e.slice(0,t),hasMore:!0}:{items:e,hasMore:!1}}function ha(e){return e.archived?"archived":e.source==="subagent"||e.source==="schedule"?e.source:"active"}function $R(e,t){const n=t.trim().toLowerCase();return n===""?!0:(e.title??"").toLowerCase().includes(n)}const rf=["subagent","schedule","archived"];function gg(e){const t={active:[],subagent:[],schedule:[],archived:[]};for(const n of e)t[ha(n)].push(n);return t}const UC=["active",...rf];function UR(e){const t=new Map;for(const[n,s]of e)for(const[o,c]of Object.entries(s)){const u=vo(o);let f=t.get(u);f||(f={totals:{active:0,subagent:0,schedule:0,archived:0},agents:{active:[],subagent:[],schedule:[],archived:[]}},t.set(u,f));for(const p of UC){const h=c[p];h>0&&(f.totals[p]+=h,f.agents[p].includes(n)||f.agents[p].push(n))}}return t}function PC(e){let t=null;for(const n of e){const s=ha(n);s!=="active"&&s!=="schedule"||(!t||n.createdAt>t.createdAt||n.createdAt===t.createdAt&&n.sessionId>t.sessionId)&&(t=n)}return t}function PR(e){const t=new Map;for(const o of e){const c=vo(o.workspace);let u=t.get(c);if(!u){const f=c===Dx;u={key:c,label:f?"":$x(o.workspace),fullPath:f?null:o.workspace.trim(),temp:f,sessions:[]},t.set(c,u)}u.sessions.push(o)}const n=(o,c)=>o<c?1:o>c?-1:0,s=[...t.values()];for(const o of s)o.sessions.sort((c,u)=>n(c.createdAt,u.createdAt));return s.sort((o,c)=>o.temp!==c.temp?o.temp?1:-1:n(o.sessions[0]?.createdAt??"",c.sessions[0]?.createdAt??"")),s}const zR=["day","month","earlier"],zC=1440*60*1e3,BR=30*zC,HR=e=>`\0time-${e}`,zc="\0time-folders";function FR(e,t){const n=Date.parse(e);if(!Number.isFinite(n))return"earlier";const s=t-n;return s<zC?"day":s<BR?"month":"earlier"}function qR(e,t){const n=new Map;for(const o of e){const c=FR(o.lastActiveAt,t),u=n.get(c);u?u.push(o):n.set(c,[o])}const s=[];for(const o of zR){const c=n.get(o);c!==void 0&&(c.sort((u,f)=>u.lastActiveAt<f.lastActiveAt?1:u.lastActiveAt>f.lastActiveAt?-1:0),s.push({key:HR(o),bucket:o,sessions:c}))}return s}function VR(e){const t={active:0,subagent:0,schedule:0,archived:0};for(const n of e.values())for(const s of UC){const o=n[s];o>0&&(t[s]+=o)}return t}function GR(e,t,n){if(n.size===0)return[...e];const s=[],o=[];for(const c of e)(n.has(t(c))?s:o).push(c);return[...s,...o]}const BC=y.createContext(null),po=(e,t,n="")=>`${e}\0${t}\0${n}`,KR=["active",...rf];function WR(e){const t=e.split("\0");if(t.length!==3)return null;const[n,s,o]=t;return KR.includes(s)?{agentId:n,category:s,scope:o}:null}const h0=e=>e===void 0||e===""?"":LR(e),YR=500;function XR(){let e=0;return zl((t,n)=>{const s=(o,c,u)=>{const{agentId:f,workspace:p}=o,h=n().countsByAgent,x=h.get(f);if(x){const w=new Map(h);w.set(f,{...x,[c]:Math.max(0,x[c]+u)}),t({countsByAgent:w})}const g=n().workspaceCountsByAgent,v=g.get(f);if(v){const w=v[p]??{active:0,subagent:0,schedule:0,archived:0},S=new Map(g);S.set(f,{...v,[p]:{...w,[c]:Math.max(0,w[c]+u)}}),t({workspaceCountsByAgent:S})}};return{projectId:null,agentIds:[],sessions:[],deletedSessionIds:new Set,pageState:new Map,countsByAgent:new Map,workspaceCountsByAgent:new Map,loading:!0,reload:async()=>{const{projectId:o,agentIds:c}=n();if(!o||c.length===0)return;const u=++e;t({loading:!0});try{const f=await Promise.all(c.map(async w=>{const S=[{category:"active",scope:""}];for(const C of n().pageState.keys()){const N=WR(C);N===null||N.agentId!==w||N.category==="active"&&N.scope===""||S.push({category:N.category,scope:N.scope})}try{const C=await Promise.all(S.map(async({category:N,scope:T})=>{const _=await c0(o,w,{offset:0,limit:bs+1,category:N,...T===""?{}:{workspaceGroup:T},...N==="active"&&T===""?{withCounts:!0}:{}});return{category:N,scope:T,counts:_.counts,workspaceCounts:_.workspaceCounts,...sw(_.sessions,bs)}}));return{agentId:w,pages:C}}catch{return{agentId:w,pages:[]}}}));if(u!==e)return;const p=[],h=new Set,x=new Map,g=new Map,v=new Map;for(const w of f)for(const S of w.pages){x.set(po(w.agentId,S.category,S.scope),{hasMore:S.hasMore,fetched:S.items.length}),S.counts&&g.set(w.agentId,S.counts),S.workspaceCounts&&v.set(w.agentId,S.workspaceCounts);for(const C of S.items)h.has(C.sessionId)||(h.add(C.sessionId),p.push(C))}t({sessions:p,pageState:x,countsByAgent:g,workspaceCountsByAgent:v})}finally{u===e&&t({loading:!1})}},loadMoreFor:async(o,c,u)=>{const{projectId:f}=n();if(!f)return;const p=h0(u),h=[...new Set(o)].filter(R=>{const D=n().pageState.get(po(R,c,p));return D===void 0?p!==""||(n().countsByAgent.get(R)?.[c]??0)>0:D.hasMore});if(h.length===0)return;const x=e,g=(R,D)=>n().sessions.filter(z=>z.agentId===R&&ha(z)===c&&vo(z.workspace)===D).length,v=await Promise.all(h.map(async R=>{const z=n().pageState.get(po(R,c,p))?.fetched??(u===void 0||u===""?0:g(R,u));try{const E=(await c0(f,R,{offset:z,limit:bs+1,category:c,...p===""?{}:{workspaceGroup:p}})).sessions;return{agentId:R,offset:z,...sw(E,bs)}}catch{return null}}));if(x!==e)return;const w=v.filter(R=>R!==null),S=n().sessions,C=new Set(S.map(R=>R.sessionId)),N=w.flatMap(R=>R.items.filter(D=>!C.has(D.sessionId))),T=n().pageState,_=new Map(T);for(const R of w){const D=po(R.agentId,c,p);_.set(D,{hasMore:R.hasMore,fetched:(T.get(D)?.fetched??R.offset)+R.items.length})}t({...N.length>0?{sessions:[...S,...N]}:{},pageState:_})},add:o=>{e+=1,!n().sessions.some(u=>u.sessionId===o.sessionId)&&n().pageState.get(po(o.agentId,ha(o)))?.hasMore===!1&&s(o,ha(o),1),t({sessions:[o,...n().sessions.filter(u=>u.sessionId!==o.sessionId)]})},remove:o=>{e+=1;const c=n().sessions.find(f=>f.sessionId===o);c&&s(c,ha(c),-1);const u=new Set(n().deletedSessionIds);for(u.add(o);u.size>YR;){const f=u.values().next();if(f.done)break;u.delete(f.value)}t({deletedSessionIds:u,sessions:n().sessions.filter(f=>f.sessionId!==o)})},replace:o=>{const c=n().sessions.find(u=>u.sessionId===o.sessionId);c&&ha(c)!==ha(o)&&(s(o,ha(c),-1),s(o,ha(o),1)),t({sessions:n().sessions.map(u=>u.sessionId===o.sessionId?o:u)})},setStatus:(o,c,u)=>{const f=n().sessions,p=f.find(v=>v.sessionId===o);if(!p)return;const h=u?.lastActiveAt??p.lastActiveAt,x=c==="running"||c==="compacting",g=p.hasTrace||u?.hasTrace===!0||x;p.status===c&&p.lastActiveAt===h&&p.hasTrace===g||t({sessions:f.map(v=>v.sessionId===o?{...v,status:c,lastActiveAt:h,hasTrace:g}:v)})},setTitle:(o,c)=>{const u=n().sessions,f=u.find(p=>p.sessionId===o);!f||f.title===c||t({sessions:u.map(p=>p.sessionId===o?{...p,title:c}:p)})}}})}function QR(e,t,n){if(t.type==="web_updated"){n();return}if(t.type==="session_state"){e.getState().setStatus(t.sessionId,t.state,{lastActiveAt:t.lastActiveAt,hasTrace:t.hasTrace});return}if(t.type==="session_title"){e.getState().setTitle(t.sessionId,t.title);return}if(t.type==="resync_required"){e.getState().reload();return}t.type==="schedule_fired"&&t.projectId===e.getState().projectId&&e.getState().reload()}function ZR({children:e}){const{currentProject:t,agents:n}=en(),s=t?.projectId??null,o=n.map(w=>w.agentId).join(","),[c]=y.useState(XR),u=Bl(c);y.useEffect(()=>{c.setState({projectId:s,agentIds:o===""?[]:o.split(","),sessions:[],pageState:new Map,countsByAgent:new Map,workspaceCountsByAgent:new Map}),c.getState().reload()},[c,s,o]),y.useEffect(()=>{const w=RR({onOmniMessage:()=>{},onServerEvent:S=>QR(c,S,()=>window.location.reload())});return()=>w.close()},[c]);const{pageState:f,countsByAgent:p}=u,h=y.useCallback((w,S,C)=>f.has(po(w,S,h0(C))),[f]),x=y.useCallback((w,S,C)=>{const N=h0(C),T=f.get(po(w,S,N));return T!==void 0?T.hasMore:(p.get(w)?.[S]??0)>0},[f,p]),g=y.useCallback(w=>c.getState().deletedSessionIds.has(w),[c]),v=y.useMemo(()=>{const w=new Map;for(const S of u.sessions){const C=w.get(S.agentId);C?C.push(S):w.set(S.agentId,[S])}for(const S of w.values())S.sort((C,N)=>N.createdAt.localeCompare(C.createdAt)||N.sessionId.localeCompare(C.sessionId));return{sessions:u.sessions,byAgent:w,countsByAgent:u.countsByAgent,workspaceCountsByAgent:u.workspaceCountsByAgent,isLoadedFor:h,hasMoreFor:x,loading:u.loading,reload:u.reload,loadMoreFor:u.loadMoreFor,add:u.add,remove:u.remove,isDeleted:g,replace:u.replace,setStatus:u.setStatus,setTitle:u.setTitle}},[u,h,x,g]);return a.jsx(BC.Provider,{value:v,children:e})}function Ii(){const e=y.useContext(BC);if(!e)throw new Error("useSessions must be used within a SessionsProvider");return e}function HC(e){return e.desktopMode&&e.sessionVia==="desktop"}const JR={check:{action:"check",busy:!1},checking:{action:"none",busy:!0},downloading:{action:"none",busy:!0},install:{action:"install",busy:!1},unsupported:{action:"none",busy:!1},unknown:{action:"none",busy:!1}};function oo(e,t,n={}){return{labelKind:e,...JR[e],version:null,percent:null,appVersion:t?.appVersion??null,unsupportedReason:null,...n}}function FC(e,t=!1){if(e===null)return oo("unknown",e);switch(e.state){case"unsupported":return oo("unsupported",e,{unsupportedReason:e.reason??null});case"checking":return oo("checking",e);case"downloading":return oo("downloading",e,{version:e.version??null,percent:e.percent??null});case"downloaded":return oo("install",e,{version:e.version??null});default:return oo(t?"checking":"check",e)}}const eI=6e4;function tI(e,t,n){const s=n>=eI;if(t===null)return s?{kind:"failed",message:null}:null;if(t.state==="checking")return null;if(!(t.seq!==void 0&&e!==null?t.seq!==e:n>=4e3))return s?{kind:"failed",message:null}:null;switch(t.state){case"up-to-date":return{kind:"up-to-date"};case"downloading":return{kind:"found",version:t.version??null};case"downloaded":return{kind:"ready",version:t.version??null};case"unsupported":return{kind:"unsupported",reason:t.reason??null};case"error":return{kind:"failed",message:t.message??null};default:return s?{kind:"failed",message:null}:null}}function Ae(e,t){return e instanceof xr?e.code==="model_credential_missing"?t?.modelId?d.errors.modelCredentialMissing(t.modelId):e.message:e.code==="no_default_model"?d.errors.noDefaultModel:d.errors.byCode[e.code]??e.message:d.common.unknownError}var ss=$j();const nI={success:2500,info:4e3,error:6e3},uu=zl(()=>({items:[]}));let rI=1;const aI=160;function qC(e){const t=uu.getState().items.find(n=>n.id===e);!t||t.leaving||(uu.setState(n=>({items:n.items.map(s=>s.id===e?{...s,leaving:!0}:s)})),setTimeout(()=>{uu.setState(n=>({items:n.items.filter(s=>s.id!==e)}))},aI))}function Ux(e,t){if(!t)return;const n=rI++;uu.setState(s=>({items:[...s.items,{id:n,kind:e,text:t}]})),setTimeout(()=>qC(n),nI[e])}const yt=e=>Ux("success",e),Be=e=>Ux("error",e),wr=e=>Ux("info",e),sI={success:"border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200",error:"border-red-200 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-200",info:"border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200"};function iI(){const e=Bl(uu,t=>t.items);return e.length===0?null:ss.createPortal(a.jsx("div",{className:"pointer-events-none fixed inset-x-0 top-3 z-[100] flex flex-col items-center gap-2 px-4",children:e.map(t=>a.jsx("button",{type:"button",onClick:()=>qC(t.id),className:`pointer-events-auto max-w-lg break-words rounded-md border px-3 py-2 text-left text-sm shadow-lg ${t.leaving?"anim-toast-out":"anim-toast-in"} ${sI[t.kind]}`,children:t.text},t.id))}),document.body)}const oI=1500,lI=8e3;let Sl=null,Bc=null,Ai=null;const g0=new Set;function x0(){for(const e of g0)e()}function cI(){if(Ai===null)return;const e=tI(Ai.atClickSeq,Sl,Date.now()-Ai.armedAt);if(e!==null)switch(Ai=null,e.kind){case"up-to-date":yt(d.update.upToDate);break;case"found":yt(d.update.clientFoundNew(e.version));break;case"ready":yt(d.update.clientDownloadReady(e.version));break;case"unsupported":wr(e.reason==="linux-not-appimage"?d.update.clientUnsupportedNonAppImage:d.update.clientUnsupportedDev);break;default:Be(e.message!==null?d.update.clientUpdateFailed(e.message):d.update.checkFailed)}}function af(){return Bc||(Bc=(async()=>{try{Sl=(await UA()).status}catch{}finally{Bc=null,cI(),x0()}})(),Bc)}function uI(){af()}async function dI(){if(Ai===null){Ai={atClickSeq:Sl?.seq??null,armedAt:Date.now()},x0();try{await PA(),af()}catch(e){Ai=null,x0(),Be(Ae(e))}}}async function mI(){try{await zA()}catch(e){Be(d.update.clientInstallFailed(Ae(e)))}}function VC(e,t){const[,n]=y.useReducer(u=>u+1,0);y.useEffect(()=>(g0.add(n),()=>{g0.delete(n)}),[]);const s=Ai!==null,o=s||Sl?.state==="checking"||Sl?.state==="downloading",c=e&&(t||s);return y.useEffect(()=>{if(!c)return;af();const u=setInterval(()=>{af()},o?oI:lI);return()=>clearInterval(u)},[c,o]),{status:Sl,checkPending:s}}let xg=null,yg=null,Gm=null,jl=null;const y0=new Set;function b0(){for(const e of y0)e()}function fI(e){return e.disabled===!0?{kind:"disabled"}:e.error!==void 0?{kind:"failed"}:e.updateAvailable&&e.latestVersion!==null?{kind:"found",latestVersion:e.latestVersion}:{kind:"up-to-date"}}function Px(e){const[t,n]=y.useState(xg),[s,o]=y.useState(Gm);return y.useEffect(()=>{const c=()=>{n(xg),o(Gm)};return y0.add(c),()=>{y0.delete(c)}},[]),y.useEffect(()=>{if(!e)return;let c=!1;return yg??=DA().then(u=>(xg=u,b0(),u)),yg.then(u=>{c||n(u)}).catch(()=>{yg=null}),jl??=uC().then(u=>(Gm=u,b0(),u)),jl.then(u=>{c||o(u)}).catch(()=>{jl=null}),()=>{c=!0}},[e]),{version:t,update:s}}async function iw(){const e=uC(!0).then(t=>(Gm=t,t));jl=e;try{return await e}catch(t){throw jl===e&&(jl=null),t}finally{b0()}}function GC(e){return e?.updateAvailable===!0?e.latestVersion??null:null}function pI(e){if(e.releaseRowOffered){const t=GC(e.update);if(t!==null)return{kind:"release",version:t}}if(e.clientRowOffered){const t=FC(e.clientStatus);if(t.action==="install")return{kind:"client",version:t.version}}return null}function hI(e){return e.some(t=>t.kernelOutdated)}function gI(e,t){return e!==null&&t?{kind:"mixed"}:e!==null?e:t?{kind:"kernel"}:{kind:"none"}}function zx(e=!1){const{desktopMode:t,sessionVia:n}=mn(),{agents:s}=en(),o=HC({desktopMode:t,sessionVia:n}),{update:c}=Px(e),{status:u}=VC(!1,!1);y.useEffect(()=>{e&&o&&uI()},[e,o]);const f=pI({releaseRowOffered:!t,clientRowOffered:o,update:c,clientStatus:u}),p=hI(s),h=p?d.agent.kernelOutdatedHint:null,x=f===null?null:ow(f);return{software:f,softwareNote:x,kernel:p,kernelNote:h,any:f!==null||p,note:ow(gI(f,p))}}function ow(e){switch(e.kind){case"none":return null;case"release":return d.update.newVersion(e.version);case"client":return d.update.clientRestartToInstall(e.version);case"kernel":return d.agent.kernelOutdatedHint;default:return d.update.updatesAvailable}}function xI(e){return e==="running"||e==="compacting"}const yI=1e4;function bI(e=yI){const t=new Map;return{observe(n,s=Date.now()){const o=[],c=new Set;for(const u of n){if(c.has(u.sessionId))continue;c.add(u.sessionId);const f=xI(u.status),p=t.get(u.sessionId);if(p===void 0){t.set(u.sessionId,{active:f,lastFiredAt:null});continue}p.active&&!f&&(p.lastFiredAt===null||s-p.lastFiredAt>=e)&&(o.push(u.sessionId),p.lastFiredAt=s),p.active=f}for(const u of[...t.keys()])c.has(u)||t.delete(u);return o}}}function vI(){const{sessionVia:e}=mn(),{sessions:t}=Ii(),{setCurrentAgentId:n}=en(),s=yr(),o=y.useRef(bI()),c=y.useRef(s);c.current=s;const u=y.useRef(n);u.current=n;const f=e==="desktop";y.useEffect(()=>{if(!f)return;const p=o.current.observe(t.map(h=>({sessionId:h.sessionId,status:h.status})));if(p.length!==0&&!(!document.hidden&&document.hasFocus())&&!(typeof Notification>"u"||Notification.permission!=="granted"))for(const h of p){const x=t.find(w=>w.sessionId===h),g=x?.title??d.chat.defaultSessionTitle,v=x?.agentId??null;try{const w=new Notification(d.notify.taskCompleteTitle,{body:d.notify.taskCompleteBody(g),tag:`penguin-task-${h}`,icon:"/penguin-logo.svg"});w.onclick=()=>{w.close(),window.focus(),v!==null&&u.current(v),c.current(`/chat/${h}`)}}catch{}}},[f,t])}function Zn({open:e,size:t=14,className:n=""}){return a.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:`block shrink-0 transition-transform duration-200 ${e?"rotate-90":""} ${n}`,children:a.jsx("path",{d:"M9 5l7 7-7 7"})})}const Ye={inlineGlyph:13,rowLead:14,iconButton:15,groupHeaderGlyph:15,groupHeaderAction:16,navRow:16,chevron:14,chevronDense:12,caretDense:10},Ro={tight:"gap-1",row:"gap-1.5",menu:"gap-2"};function Oe({d:e,size:t=Ye.inlineGlyph,className:n="",filled:s=!1}){return a.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:s?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:`block shrink-0 ${n}`,"aria-hidden":!0,children:a.jsx("path",{d:e})})}function vn({d:e,size:t=Ye.navRow}){return a.jsx(Oe,{d:e,size:t})}const El="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z",kI="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",Bx="M12 3v3m-6 4a6 6 0 0 1 12 0v5a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-5zm3 3h.01M15 13h.01",wI="M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0M12 6v6l4 2",SI="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",jI="m21 16-4 4-4-4M17 20V4M3 8l4-4 4 4M7 4v16",xm={workspace:El,agent:Bx,time:SI},lw={recent:wI,manual:jI},KC="penguin.sidebarGroupMode";function bg(){const e=localStorage.getItem(KC);return e==="agent"||e==="time"?e:"workspace"}function CI(e){return e==="agent"?"agent":e==="time"?"chat":"workspace"}function NI(e){localStorage.setItem(KC,e)}const WC="flex w-full items-center gap-1 rounded px-1.5 py-1 text-left text-[11px] font-medium text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 dark:text-gray-500 dark:hover:bg-gray-800/50";function Km({label:e,ariaLabel:t,pending:n=!1,onClick:s,className:o}){return a.jsxs("button",{type:"button","aria-label":t??d.chat.loadMore,disabled:n,onClick:s,className:`${WC}${o?` ${o}`:""} disabled:opacity-60`,children:[a.jsx("span",{className:"w-3","aria-hidden":!0}),n?d.common.loading:e]})}const TI="M15 18 9 12l6-6",MI="m9 18 6-6-6-6";function EI({page:e,pageCount:t,onChange:n}){const s=c=>{const u=e+c;u>=0&&u<t&&n(u)},o="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 hover:text-gray-700 disabled:pointer-events-none disabled:opacity-40 dark:text-gray-500 dark:hover:bg-gray-800/50 dark:hover:text-gray-300";return a.jsxs("div",{className:"mt-1 flex items-center justify-center gap-1.5 px-1.5 py-0.5",children:[a.jsx("button",{type:"button",title:d.chat.prevGroupPage,"aria-label":d.chat.prevGroupPage,disabled:e<=0,onClick:()=>s(-1),className:o,children:a.jsx(vn,{d:TI,size:12})}),a.jsxs("span",{"aria-live":"polite","aria-label":d.chat.groupPagePosition(e+1,t),className:"min-w-[2.5rem] text-center text-[11px] font-medium tabular-nums text-gray-400 dark:text-gray-500",children:[e+1,"/",t]}),a.jsx("button",{type:"button",title:d.chat.nextGroupPage,"aria-label":d.chat.nextGroupPage,disabled:e>=t-1,onClick:()=>s(1),className:o,children:a.jsx(vn,{d:MI,size:12})})]})}function AI({label:e,open:t,onToggle:n,more:s=!1,moreLabel:o,pending:c=!1,onMore:u,children:f}){return a.jsxs("div",{className:"mt-1",children:[a.jsxs("button",{type:"button",onClick:n,className:WC,children:[a.jsx(Zn,{open:t,size:12}),e]}),t&&f,t&&s&&a.jsx(Km,{label:o??d.chat.loadMore,...o!==void 0?{ariaLabel:o}:{},pending:c,onClick:()=>u?.()})]})}function ym({open:e,onToggle:t,icon:n,label:s,uppercase:o=!1,count:c,title:u,actions:f,draggable:p=!1,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}){return a.jsxs("div",{className:`group/header flex items-center gap-0.5 px-1 pb-0.5${p?" cursor-grab":""}`,...p?{draggable:!0,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}:{},children:[a.jsxs("button",{type:"button",onClick:t,"aria-expanded":e,"aria-label":e?d.nav.collapseGroup:d.nav.expandGroup,...u!==void 0?{title:u}:{},className:"flex min-w-0 flex-1 items-center gap-1 self-stretch rounded px-1 py-0.5 text-left transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/50",children:[n,a.jsx("span",{className:`min-w-0 truncate text-xs font-semibold ${o?"uppercase tracking-wide ":""}text-gray-500 dark:text-gray-400`,children:s}),c!==void 0&&a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400 dark:text-gray-500",children:c}),a.jsx(Zn,{open:e,size:12,className:"text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1"})]}),f]})}function ns({size:e=12,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M3 4.5l3 3 3-3",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function qu({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M5 12l4 4L19 6",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function _I({size:e=14,strokeWidth:t=1.7,className:n=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${n}`,children:a.jsx("path",{d:"M12 5v14M5 12h14",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"})})}function Hx({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M12 4v11m0 0l-5-5m5 5l5-5M4 20h16",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})}function YC({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M12 15V4m0 0L7 9m5-5l5 5M4 20h16",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})}function Hl({size:e=14,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`block shrink-0 ${t}`,children:a.jsx("path",{d:"M2 2l10 10M12 2L2 12",strokeWidth:"1.5",strokeLinecap:"round"})})}function Rf({onClose:e,className:t="",...n}){return a.jsx("button",{type:"button","aria-label":d.common.close,onClick:e,className:`rounded-md p-1.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300 ${t}`,...n,children:a.jsx(Hl,{})})}const RI="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01",XC="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",II="M22 2 11 13M22 2l-7 20-4-9-9-4z",If="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",vs={agents:Bx,skills:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",models:"M7 7h10v10H7zM4 10h3m10 0h3M4 14h3m10 0h3M10 4v3m4-3v3m-4 10v3m4-3v3",usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",traces:"M4 6h16M4 12h10M4 18h13",benchmark:"M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",terminal:"M3 5h18v14H3zM7 9l3 3-3 3M13 15h4"};function QC({open:e,side:t="left",title:n,onClose:s,children:o,widthClass:c}){return y.useEffect(()=>{if(!e)return;const u=f=>{f.key==="Escape"&&s()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e,s]),e?a.jsxs("div",{className:"fixed inset-0 z-50",children:[a.jsx("div",{className:"anim-fade absolute inset-0 bg-black/45",onMouseDown:s}),a.jsxs("div",{className:`absolute inset-y-0 flex w-[80vw] flex-col bg-white shadow-xl dark:bg-gray-900 ${c??"max-w-xs"} ${t==="left"?"anim-drawer-left left-0 border-r border-gray-200 dark:border-gray-800":"anim-drawer-right right-0 border-l border-gray-200 dark:border-gray-800"}`,children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("span",{className:"text-base font-semibold",children:n??""}),a.jsx(Rf,{onClose:s})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto pb-[env(safe-area-inset-bottom)]",children:o})]})]}):null}const LI={chrome:"h-2.5 w-2.5 border-2 border-gray-50 dark:border-gray-900",inline:"h-1.5 w-1.5"};function Mo({size:e="chrome",position:t="-right-0.5 -top-0.5"}){return a.jsx("span",{"aria-hidden":!0,className:`pointer-events-none absolute rounded-full bg-red-400 ${LI[e]} ${t}`})}function OI({onClick:e,children:t}){return a.jsx("button",{type:"button",onClick:e,className:"inline-flex shrink-0 items-center whitespace-nowrap rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-semibold text-red-800 transition-colors duration-150 hover:bg-red-200 dark:bg-red-950 dark:text-red-300 dark:hover:bg-red-900",children:t})}function ko(e){const t=e.toFixed(1);return t.endsWith(".0")?t.slice(0,-2):t}function It(e){const t=Math.abs(e);return t<1e3?`${e}`:t<1e6?`${ko(e/1e3)}k`:`${ko(e/1e6)}M`}function Pn(e,t){if(e<1e3)return`${Math.round(e)}ms`;const n=e/1e3;if(n<60&&!(t?.compact&&n>=10))return`${ko(n)}s`;const s=Math.round(n);return s<60?`${s}s`:`${Math.floor(s/60)}m${s%60}s`}function ZC(e){const t=Math.max(0,Math.floor(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`}function v0(e,t){return t>0?e/(t/1e3):null}function sf(e){return e==null||!Number.isFinite(e)?"—":`${Math.abs(e)<1e3?ko(e):It(e)} tok/s`}function JC(e,t){const n=e+t;return n>0?e/n:null}function Lf(e){return e==null||!Number.isFinite(e)?"—":`${Math.round(e*100)}%`}function rs(e,t="USD",n){if(e==null)return"—";const s=t==="CNY"?"¥":"$",o=t==="CNY"?e*7:e;if(o===0)return`${s}0`;const c=Math.abs(o);if(n?.compact&&c<1)return`${s}${Number(o.toPrecision(2))}`;const u=c>=100?0:c>=1?2:4;return`${s}${o.toFixed(u)}`}function Su(e){return Number.isInteger(e)?`${e}`:e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function cw(e){return Number(e.toFixed(1))<1024}function ju(e){if(e<1024)return`${e}B`;const t=e/1024;if(cw(t))return`${ko(t)}KB`;const n=t/1024;return cw(n)?`${ko(n)}MB`:`${ko(n/1024)}GB`}function yo(e){return e<10?`0${e}`:`${e}`}function Jr(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:`${t.getFullYear()}-${yo(t.getMonth()+1)}-${yo(t.getDate())} ${yo(t.getHours())}:${yo(t.getMinutes())}`}const DI=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k0(e,t){const n=/^\d{4}-(\d{2})-(\d{2})(?:$|T)/.exec(e);if(!n)return e;const s=Number(n[1]),o=Number(n[2]);return s<1||s>12||o<1||o>31?e:t==="en"?`${DI[s-1]} ${o}`:`${s} 月 ${o} 日`}function eN(e,t){const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleString(t==="en"?"en-US":"zh-CN",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function of(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function $I(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=Math.round((of(new Date)-of(n))/864e5);return s<0?Jr(e):s===0?t==="en"?"today":"今天":s===1?t==="en"?"yesterday":"昨天":t==="en"?`${s} days ago`:`${s} 天前`}function Al(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=Math.round((of(new Date)-of(n))/864e5);return s<0?e:s===0?t==="en"?"updated today":"今天更新":s===1?t==="en"?"updated yesterday":"昨天更新":t==="en"?`updated ${s} days ago`:`${s} 天前更新`}function UI(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return"";const s=Date.now()-n.getTime();if(s<0)return k0(e,t);const o=Math.floor(s/6e4);if(o<1)return t==="en"?"now":"刚刚";if(o<60)return t==="en"?`${o}m`:`${o} 分钟前`;const c=Math.floor(o/60);if(c<24)return t==="en"?`${c}h`:`${c} 小时前`;const u=Math.floor(c/24);return u<7?t==="en"?`${u}d`:`${u} 天前`:k0(e,t)}function PI(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:`${yo(t.getHours())}:${yo(t.getMinutes())}:${yo(t.getSeconds())}`}const Fx=e=>`penguin.sessionSeen.${e}`,uw=500,Cl={seededAt:0,seen:new Map};function tN(e){try{return localStorage}catch{return null}}function zI(e){if(e===null)return Cl;try{const t=JSON.parse(e);if(typeof t!="object"||t===null)return Cl;const n=t,s=typeof n.seededAt=="number"&&Number.isFinite(n.seededAt)?n.seededAt:0,o=new Map;if(typeof n.seen=="object"&&n.seen!==null)for(const[c,u]of Object.entries(n.seen))typeof u=="number"&&Number.isFinite(u)&&o.set(c,u);return{seededAt:s,seen:o}}catch{return Cl}}function BI(e){let t=[...e.seen];return t.length>uw&&(t.sort((n,s)=>s[1]-n[1]),t=t.slice(0,uw)),JSON.stringify({seededAt:e.seededAt,seen:Object.fromEntries(t)})}function HI(e,t,n,s=Date.now()){const o=Date.parse(n),c=Number.isNaN(o)?s:Math.max(s,o);return e.seen.get(t)===c?e:{seededAt:e.seededAt,seen:new Map(e.seen).set(t,c)}}function FI(e,t){if(!e.seen.has(t))return e;const n=new Map(e.seen);return n.delete(t),{seededAt:e.seededAt,seen:n}}function qI(e,t,n){const s=Date.parse(n);return Number.isNaN(s)?!1:s>(e.seen.get(t)??e.seededAt)}const qx=zl(()=>({cache:new Map}));function Vx(e,t){const{cache:n}=qx.getState(),s=n.get(e);if(s)return s;const o=tN();let c=Cl;if(o)try{c=zI(o.getItem(e))}catch{c=Cl}return n.set(e,c),c}function nN(e,t,n){const s=tN();if(s)try{s.setItem(e,BI(t))}catch{}qx.setState(o=>({cache:new Map(o.cache).set(e,t)}))}function VI(e){return Bl(qx,()=>e?Vx(Fx(e)):Cl)}function Gx(e,t,n,s){if(e===null)return;const o=Fx(e),c=Vx(o),u=c.seededAt===0?{seededAt:Date.now(),seen:c.seen}:c,f=HI(u,t,n);f!==c&&nN(o,f)}function GI(e,t,n){if(e===null)return;const s=Fx(e),o=Vx(s),c=FI(o,t);c!==o&&nN(s,c)}function rN(e,t,n){return e==="running"?"running":e==="compacting"?"compacting":t&&n?"completedUnread":null}function KI(e,t,n){const s=e.sessionId!==n&&qI(t,e.sessionId,e.lastActiveAt);return rN(e.status,e.hasTrace,s)}const WI=["agents","skills","models","usage","benchmark"],aN="penguin.sidebarNavGroupCollapsed";function YI(e){try{return(e??localStorage).getItem(aN)==="collapsed"}catch{return!1}}function XI(e,t){try{(t??localStorage).setItem(aN,e?"collapsed":"expanded")}catch{}}const sN=e=>`penguin.pinnedSessions.${e}`;function dw(e,t){if(e===null)return new Set;try{const n=t??localStorage,s=JSON.parse(n.getItem(sN(e))??"[]");return new Set(Array.isArray(s)?s.filter(o=>typeof o=="string"):[])}catch{return new Set}}function mw(e,t,n){if(e!==null)try{(n??localStorage).setItem(sN(e),JSON.stringify([...t]))}catch{}}function QI(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function ZI(e,t){if(!e.has(t))return e;const n=new Set(e);return n.delete(t),n}const iN=e=>`penguin.sidebarWorkspaces.${e}`;function w0(e){let t=e.trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"))&&!/^[A-Za-z]:[/\\]$/.test(t);)t=t.slice(0,-1);return t}function JI(e){if(typeof e=="string"){const t=w0(e);return t===""?null:{path:t}}if(typeof e=="object"&&e!==null&&typeof e.path=="string"){const t=w0(e.path);if(t==="")return null;const n=e.alias,s=typeof n=="string"?n.trim():"";return s===""?{path:t}:{path:t,alias:s}}return null}function fw(e,t){if(e===null)return[];try{const n=t??localStorage,s=JSON.parse(n.getItem(iN(e))??"[]");if(!Array.isArray(s))return[];const o=[];for(const c of s){const u=JI(c);u!==null&&!o.some(f=>f.path===u.path)&&o.push(u)}return o}catch{return[]}}function e6(e,t,n){if(e!==null)try{(n??localStorage).setItem(iN(e),JSON.stringify(t))}catch{}}function t6(e,t){const n=w0(t);return n===""||OC(n)||e.some(s=>s.path===n)?e:[{path:n},...e]}function n6(e,t,n){const s=n.trim(),o=e.find(c=>c.path===t);return!o||(o.alias??"")===s?e:e.map(c=>c.path===t?s===""?{path:c.path}:{path:c.path,alias:s}:c)}function r6(e,t){return e.some(n=>n.path===t)?e.filter(n=>n.path!==t):e}function a6(e,t){const n=new Map(t.filter(u=>u.alias!==void 0).map(u=>[u.path,u.alias])),s=new Set(e.map(u=>u.key)),o=[];for(const{path:u,alias:f}of t){const p=vo(u);s.has(p)||p!==u||(s.add(p),o.push({key:p,label:f??$x(u),fullPath:u,temp:!1,sessions:[]}))}const c=e.map(u=>{const f=n.get(u.key);return f===void 0?u:{...u,label:f}});return o.length===0?c:[...c,...o]}const oN="penguin.sidebarSortMode";function s6(e){try{return(e??localStorage).getItem(oN)==="manual"?"manual":"recent"}catch{return"recent"}}function i6(e,t){try{(t??localStorage).setItem(oN,e)}catch{}}const lN=(e,t)=>`penguin.sessionOrder.${e}.${t}`;function Kx(e,t){try{const n=t??localStorage,s=JSON.parse(n.getItem(e)??"[]");return Array.isArray(s)?s.filter(o=>typeof o=="string"):[]}catch{return[]}}function Wx(e,t,n){try{(n??localStorage).setItem(e,JSON.stringify(t))}catch{}}function vg(e,t,n){return e===null?[]:Kx(lN(e,t),n)}function pw(e,t,n,s){e!==null&&Wx(lN(e,t),n,s)}function hw(e,t,n){if(n.length===0)return[...e];const s=new Map(n.map((u,f)=>[u,f])),o=[],c=[];for(const u of e)(s.has(t(u))?c:o).push(u);return c.sort((u,f)=>(s.get(t(u))??0)-(s.get(t(f))??0)),[...o,...c]}function cN(e,t,n,s){if(s.length===0)return GR(e,t,n);const o=e.filter(u=>n.has(t(u))),c=e.filter(u=>!n.has(t(u)));return[...hw(o,t,s),...hw(c,t,s)]}function o6(e,t,n){const s=n.recencyOf,o=s?[...e].sort((c,u)=>s(u).localeCompare(s(c))||t(u).localeCompare(t(c))):e;return cN(o,t,n.pinned,n.sortMode==="manual"?n.order:[])}function Yx(e,t,n,s){if(t===n||!e.includes(t))return e;const o=e.filter(u=>u!==t),c=o.indexOf(n);return c<0?e:(o.splice(s?c+1:c,0,t),o.every((u,f)=>u===e[f])?e:o)}function l6(e,t){const n=new Set(t);return[...t,...e.filter(s=>!n.has(s))]}function c6(e,t){return e.includes(t)?e.filter(n=>n!==t):e}const u6=["workspace","agent"];function Xx(e){return u6.includes(e)}const uN=(e,t)=>`penguin.groupOrder.${e}.${t}`;function kg(e,t,n){return e===null||!Xx(t)?[]:Kx(uN(e,t),n)}function d6(e,t,n,s){e===null||!Xx(t)||Wx(uN(e,t),n,s)}function gw(e,t,n){return cN(e,t,n.pinned,n.order)}function m6(e,t,n,s,o){const c=new Set(e),u=[...t.filter(p=>!c.has(p)),...e],f=Yx(u,n,s,o);return f===u?e:f}const Cu=[];function dN(){const e=Symbol("esc-layer");return Cu.push(e),e}function mN(e){const t=Cu.lastIndexOf(e);t!==-1&&Cu.splice(t,1)}function fN(e){return Cu[Cu.length-1]===e}function Yt({open:e,title:t,onClose:n,children:s,footer:o,widthClass:c,headerless:u,bare:f}){const p=y.useRef(n);return p.current=n,y.useEffect(()=>{if(!e)return;const h=dN(),x=g=>{g.key==="Escape"&&fN(h)&&p.current()};return window.addEventListener("keydown",x),()=>{window.removeEventListener("keydown",x),mN(h)}},[e]),e?ss.createPortal(a.jsx("div",{className:"anim-fade fixed inset-0 z-50 flex items-end justify-center bg-black/45 p-0 sm:items-center sm:p-4",onMouseDown:h=>{h.target===h.currentTarget&&n()},children:a.jsxs("div",{...u?{role:"dialog","aria-label":t}:{},className:`anim-pop w-full ${c??"sm:max-w-md"} rounded-t-lg border border-gray-200 bg-white pb-[env(safe-area-inset-bottom)] shadow-xl sm:rounded-lg sm:pb-0 dark:border-gray-800 dark:bg-gray-900`,children:[!u&&a.jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("h2",{className:"text-base font-semibold",children:t}),a.jsx(Rf,{onClose:n})]}),f?s:a.jsx("div",{className:"max-h-[70vh] overflow-y-auto px-4 py-4",children:s}),o&&a.jsx("div",{className:"flex justify-end gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800",children:o})]})}),document.body):null}const bm=4,Hc=8;function Qn({button:e,open:t,setOpen:n,children:s,menuClass:o,menuStyle:c,className:u,portal:f,anchorRect:p,returnFocus:h,onEscape:x,focusOnOpen:g}){const v=y.useRef(null),w=y.useRef(null),[S,C]=y.useState(null),N=y.useCallback(()=>h?.()??v.current?.querySelector("button")??null,[h]),T=y.useCallback(()=>w.current?[...w.current.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')]:[],[]),_=y.useRef(g);_.current=g,y.useEffect(()=>{!t||_.current===!1||T()[0]?.focus()},[t,T]);const R=F=>{if(F.key!=="ArrowDown"&&F.key!=="ArrowUp"||F.defaultPrevented)return;const P=document.activeElement?.tagName;if(P==="INPUT"||P==="TEXTAREA"||P==="SELECT")return;const B=T();if(B.length===0)return;F.preventDefault();const Y=B.indexOf(document.activeElement),q=F.key==="ArrowDown"?1:-1,K=Y<0?q===1?0:B.length-1:(Y+q+B.length)%B.length;B[K]?.focus()},D=y.useRef(n);D.current=n;const z=y.useRef(x);z.current=x,y.useEffect(()=>{if(!t)return;const F=B=>{const Y=B.target;v.current?.contains(Y)||w.current?.contains(Y)||D.current(!1)},V=dN(),P=B=>{if(B.key!=="Escape"||!fN(V))return;N()?.focus();const Y=z.current;Y?Y():D.current(!1)};return window.addEventListener("mousedown",F),window.addEventListener("keydown",P),()=>{mN(V),window.removeEventListener("mousedown",F),window.removeEventListener("keydown",P)}},[t]);const E=y.useCallback(()=>{if(!t||!f||!v.current){C(null);return}const F=p??v.current.getBoundingClientRect(),V=w.current,P=V?.offsetWidth??0,B=V?.offsetHeight??0,Y=f.align==="right"?F.right-P:F.left,q=Math.max(Hc,Math.min(Y,window.innerWidth-P-Hc)),K=window.innerHeight-F.bottom-bm-Hc,H=F.top-bm-Hc,$=f.direction==="up",le=($?B<=H:B<=K)?$:H>K;C({left:q,maxHeight:Math.max(0,le?H:K),...le?{bottom:window.innerHeight-F.top+bm}:{top:F.bottom+bm}})},[t,f?.direction,f?.align,s,p?.top,p?.left,p?.bottom,p?.right]);y.useLayoutEffect(E,[E]),y.useEffect(()=>{if(!t||!f)return;const F=P=>{w.current?.contains(P.target)||(p?D.current(!1):E())},V=()=>{p?D.current(!1):E()};return window.addEventListener("scroll",F,!0),window.addEventListener("resize",V),()=>{window.removeEventListener("scroll",F,!0),window.removeEventListener("resize",V)}},[t,f,E,p]);const L=`anim-pop ${f?"z-[60]":"z-40"} overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900 ${f?"":"max-h-[70vh]"} ${o??"left-0 top-full mt-1 w-64 max-w-[calc(100vw-2rem)] origin-top-left"}`;return a.jsxs("div",{className:`relative ${u??""}`,ref:v,children:[e,t&&(f?ss.createPortal(a.jsx("div",{ref:w,onKeyDown:R,style:{position:"fixed",...S?{left:S.left,maxHeight:S.maxHeight,...S.top!==void 0?{top:S.top}:{},...S.bottom!==void 0?{bottom:S.bottom}:{}}:{left:0,top:0,visibility:"hidden"},maxWidth:`calc(100vw - ${Hc*2}px)`,...c},className:L,children:s}),document.body):a.jsx("div",{ref:w,onKeyDown:R,...c!==void 0?{style:c}:{},className:`absolute ${L}`,children:s}))]})}function pN(e,t){return{top:t,bottom:t,left:e,right:e}}function f6(e){return e.button===2&&!(e.clientX===0&&e.clientY===0)}function p6(e,t){return f6(e)?pN(e.clientX,e.clientY):t}function h6(e){return e.shiftKey&&e.key==="F10"}const g6=500,xw=10,x6=350;function hN(e){return e==="touch"||e==="pen"}function y6(e,t){return Math.abs(t.x-e.x)>xw||Math.abs(t.y-e.y)>xw}function b6(e,t){return t-e<x6}const v6={pointer:"",held:!1,settleFrom:0},xs={open:null,close:!1,swallow:!1};function k6(e,t){switch(t.kind){case"pointerdown":return{...xs,state:{...e,pointer:t.pointerType,held:!1}};case"hold":return{...xs,state:{...e,held:!0,settleFrom:t.at},open:"held"};case"nativemenu":return e.held?{...xs,state:e}:hN(e.pointer)?{...xs,state:{...e,held:!0,settleFrom:t.at},open:"event"}:{...xs,state:e,open:"event"};case"pointerup":return{...xs,state:{...e,pointer:"",settleFrom:e.held?t.at:e.settleFrom}};case"dismiss":return e.held&&b6(e.settleFrom,t.at)?{...xs,state:e}:{...xs,state:{...e,held:!1},close:!0};case"click":return e.held?{...xs,state:{...e,held:!1},swallow:!0}:{...xs,state:e}}}function w6(){const e=y.useRef(null),[t,n]=y.useState(null),s=y.useRef(null),o=y.useRef(null),c=y.useRef(v6),u=y.useCallback(()=>{s.current!==null&&(clearTimeout(s.current),s.current=null),o.current=null},[]);y.useEffect(()=>u,[u]);const f=y.useCallback(()=>{const v=e.current?.getBoundingClientRect();return v?{top:v.top,bottom:v.bottom,left:v.left,right:v.right}:{top:0,bottom:0,left:0,right:0}},[]),p=y.useCallback((v,w)=>{const S=k6(c.current,v);if(c.current=S.state,S.open==="held"){const C=o.current;C&&n(pN(C.x,C.y))}else S.open==="event"&&w&&n(w);return S.close&&n(null),S},[]),h=v=>{const w=v.currentTarget;return w instanceof Node&&w.contains(v.target)},x={onContextMenu:v=>{h(v)&&(v.preventDefault(),p({kind:"nativemenu",at:Date.now()},p6(v,f())),c.current.held&&u())},onKeyDown:v=>{h(v)&&h6(v)&&(v.preventDefault(),n(f()))},onPointerDown:v=>{if(!h(v)||(p({kind:"pointerdown",pointerType:v.pointerType}),!hN(v.pointerType)))return;const w=v.clientX,S=v.clientY;o.current={x:w,y:S},s.current=setTimeout(()=>{s.current=null,p({kind:"hold",at:Date.now()})},g6)},onPointerMove:v=>{const w=o.current;w!==null&&y6(w,{x:v.clientX,y:v.clientY})&&u()},onPointerUp:()=>{u(),p({kind:"pointerup",at:Date.now()})},onPointerCancel:()=>{u(),p({kind:"pointerup",at:Date.now()})}},g=y.useCallback(()=>{c.current={...c.current,held:!1},n(null)},[]);return{rowRef:y.useCallback(v=>{e.current=v},[]),rowProps:x,open:t!==null,setOpen:v=>{v||p({kind:"dismiss",at:Date.now()})},anchor:t,returnFocus:()=>e.current?.querySelector("button")??null,consumeLongPressClick:()=>p({kind:"click"}).swallow,openAt:n,close:g}}const Qx="M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z",Zx="M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",S6="M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M9.5 13.5 12 16l2.5-2.5",j6="M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M12 17v-5m-2.5 2L12 11l2.5 3",Jx="M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6",C6="M4.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM19.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",ey="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800",gN="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40",ty=e=>a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:e,size:13})}),N6=["archive"];function T6(e){return e?["pin","rename","messaging","archive","delete"]:["rename","messaging","archive","delete"]}function xN(e,t){switch(e){case"pin":return{label:t.pinned?d.chat.unpinSession:d.chat.pinSession,icon:Qx,danger:!1};case"rename":return{label:d.chat.renameSession,icon:Zx,danger:!1};case"messaging":return{label:d.messaging.bindAction,icon:XC,danger:!1};case"archive":return{label:t.archived?d.chat.unarchiveSession:d.chat.archiveSession,icon:t.archived?j6:S6,danger:!1};case"delete":return{label:d.chat.deleteSession,icon:Jx,danger:!0}}}function M6({actions:e,state:t,onRun:n}){return a.jsx(a.Fragment,{children:e.map(s=>{const o=xN(s,t);return a.jsxs("button",{type:"button",className:o.danger?gN:ey,onClick:()=>n(s),children:[o.danger?a.jsx("span",{className:"shrink-0",children:a.jsx(vn,{d:o.icon,size:13})}):ty(o.icon),o.label]},s)})})}const yw="pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100";function E6({actions:e,state:t,onRun:n,onMore:s}){const o=c=>{const u=c.currentTarget.getBoundingClientRect();s({top:u.top,bottom:u.bottom,left:u.left,right:u.right})};return a.jsxs(a.Fragment,{children:[e.map(c=>{const u=xN(c,t);return a.jsx("button",{type:"button",title:u.label,"aria-label":u.label,onClick:()=>n(c),className:`${yw} ${u.danger?"hover:text-red-600 dark:hover:text-red-400":"hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"}`,children:a.jsx(vn,{d:u.icon,size:14})},c)}),a.jsx("button",{type:"button",title:d.chat.moreActions,"aria-label":d.chat.moreActions,"aria-haspopup":"menu",onClick:o,className:`${yw} hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200`,children:a.jsx(Oe,{d:C6,size:14,filled:!0})})]})}function A6(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function _6(e){return A6(e)%360}function yN(e){const t=_6(e);return{bg:`hsl(${t} 55% 50% / 0.14)`,fg:`hsl(${t} 55% 28%)`,fgDark:`hsl(${t} 55% 73%)`}}const bw=typeof Intl<"u"&&typeof Intl.Segmenter=="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):void 0;function vw(e){if(e){if(!bw)return Array.from(e)[0];for(const t of bw.segment(e))return t.segment}}function bN(e,t){const n=vw(e.trim())??vw((t??"").trim());return n?n.toUpperCase():"?"}function Ha({id:e,name:t,size:n=18,className:s}){const o=yN(e);return a.jsxs("svg",{width:n,height:n,viewBox:"0 0 24 24",className:s,style:{"--tile-fg":o.fg,"--tile-fg-dark":o.fgDark},"aria-hidden":!0,role:"img",children:[a.jsx("rect",{x:"0",y:"0",width:"24",height:"24",rx:"5",fill:o.bg}),a.jsx("text",{x:"12",y:"12",textAnchor:"middle",dominantBaseline:"central",fontSize:"13",fontWeight:"700",className:"[fill:var(--tile-fg)] dark:[fill:var(--tile-fg-dark)]",children:bN(t??"",e)})]})}const R6=1,I6=60,L6=350,O6=4e3;function D6(e,t){const n=e-t;return n>R6?n:0}function $6(e){if(e<=0)return 0;const t=e/I6*1e3;return Math.round(Math.min(O6,Math.max(L6,t)))}function Of({text:e,className:t="",scrollReveal:n=!1}){const s=y.useRef(null),[o,c]=y.useState(0);y.useLayoutEffect(()=>{const p=s.current;if(!p)return;const h=()=>c(D6(p.scrollWidth,p.clientWidth));if(h(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(h);return x.observe(p),()=>x.disconnect()},[e,t]);const u=o>0,f=n&&u;return a.jsx("span",{ref:s,className:`truncate ${t}${f?" title-scroll":""}`,...f?{style:{"--title-scroll-shift":`-${o}px`,"--title-scroll-ms":`${$6(o)}ms`}}:{},...u?{title:e}:{},children:n?a.jsx("span",{className:"title-scroll-text",children:e}):e})}const Fc={emerald:"text-emerald-600 dark:text-emerald-400",amber:"text-amber-600 dark:text-amber-400",red:"text-red-600 dark:text-red-400",gray:"text-gray-400 dark:text-gray-500"},sn={busy:Fc.emerald,attention:Fc.amber,success:Fc.emerald,danger:Fc.red,muted:Fc.gray},vm={emerald:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",amber:"bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",red:"bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300",gray:"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"},bo={attention:vm.amber,success:vm.emerald,danger:vm.red,muted:vm.gray},Fl={busy:"bg-emerald-500",attention:"bg-amber-500",success:"bg-emerald-500"},Df={attention:"border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-300"},U6={gray:bo.muted,brand:"bg-gray-200/80 text-gray-700 dark:bg-gray-700/60 dark:text-gray-200",green:bo.success,yellow:"bg-yellow-50 text-yellow-700 dark:bg-yellow-950 dark:text-yellow-300",amber:bo.attention,red:bo.danger};function On({tone:e="gray",children:t}){return a.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ${U6[e]}`,children:t})}function P6(e){switch(e){case"completed":return"green";case"aborted":return"amber";default:return"red"}}const z6={running:"M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",compacting:"M4 12h16M8 7l4 3 4-3M8 17l4-3 4 3"},B6={running:`hourglass-turn ${sn.attention}`,compacting:`compact-squeeze ${sn.attention}`};function S0(e){return e==="running"?d.chat.statusRunning:e==="compacting"?d.chat.statusCompacting:d.chat.statusCompletedUnread}function vN({activity:e,size:t=12}){const n=S0(e);return e==="completedUnread"?a.jsx("span",{role:"img","aria-label":n,title:n,style:{width:t,height:t},className:"flex shrink-0 items-center justify-center",children:a.jsx("span",{className:`block h-1.5 w-1.5 rounded-full ${Fl.success}`})}):a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",role:"status","aria-label":n,className:`block shrink-0 ${B6[e]}`,children:[a.jsx("title",{children:n}),a.jsx("path",{d:z6[e]})]})}const H6={primary:"bg-[var(--accent-bg)] text-[var(--accent-fg)] border border-[var(--accent-bg)] transition-opacity hover:opacity-90 disabled:opacity-50",secondary:"bg-white text-gray-800 border border-gray-300 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-200 dark:border-gray-700 dark:hover:bg-gray-800",danger:"bg-white text-red-600 border border-gray-300 hover:border-red-300 hover:bg-red-50 dark:bg-gray-900 dark:text-red-400 dark:border-gray-700 dark:hover:bg-red-950",ghost:"bg-transparent text-gray-600 border border-transparent hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"},F6={sm:"px-2.5 py-1 text-xs rounded-md",md:"px-3 py-1.5 text-sm rounded-md",icon:"p-1.5 rounded-md"};function ge({variant:e="secondary",size:t="md",className:n,...s}){return a.jsx("button",{type:"button",className:`inline-flex items-center justify-center gap-1 font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-60 ${H6[e]} ${F6[t]} ${n??""}`,...s})}function q6({tone:e}){const t=e==="danger"?"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3zM12 9v4m0 4h.01":"M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";return a.jsx("span",{"aria-hidden":!0,className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${e==="danger"?"bg-red-100 text-red-600 dark:bg-red-950/60 dark:text-red-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"}`,children:a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:t})})})}function ln({open:e,title:t,onClose:n,onConfirm:s,confirmLabel:o,confirmDisabled:c=!1,secondaryLabel:u,onSecondary:f,tone:p="danger",busy:h=!1,children:x}){return a.jsxs(Yt,{open:e,title:t,onClose:n,headerless:!0,widthClass:"sm:max-w-sm",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(q6,{tone:p}),a.jsx("div",{className:"min-w-0 flex-1 pt-1.5",children:x})]}),a.jsxs("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:[a.jsx(ge,{size:"sm",onClick:n,disabled:h,children:d.common.cancel}),u!==void 0&&f!==void 0&&a.jsx(ge,{size:"sm",onClick:f,disabled:h,children:u}),a.jsx(ge,{size:"sm",variant:p,disabled:h||c,onClick:s,children:o??d.common.confirm})]})]})}function ql(){const[e,t]=y.useState(null),n=a.jsx(ln,{open:e!==null,title:d.common.confirmSaveTitle,tone:"primary",confirmLabel:d.common.save,onClose:()=>t(null),onConfirm:()=>{e?.(),t(null)},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.common.confirmSaveBody})});return{requestSave:s=>t(()=>s),element:n}}const kw=4,ww=16;function $f({open:e,onClose:t,estimatedHeight:n,panelWidth:s}){const o=y.useRef(null),c=y.useRef(null),[u,f]=y.useState(null),p=y.useRef(t);return p.current=t,y.useLayoutEffect(()=>{if(!e||!o.current)return;const h=o.current.getBoundingClientRect(),x=window.innerHeight-h.bottom,g=h.top,v=Math.min(n,window.innerHeight*.7),w=x<v&&g>x,S=s??h.width,C=Math.max(ww,Math.min(h.left,window.innerWidth-S-ww));f({topPx:w?void 0:h.bottom+kw,bottomPx:w?window.innerHeight-h.top+kw:void 0,left:C,triggerWidth:h.width})},[e,n,s]),y.useEffect(()=>{if(!e)return;const h=w=>{const S=w.target;o.current?.contains(S)||c.current?.contains(S)||p.current()},x=w=>{w.key==="Escape"&&(w.stopPropagation(),p.current())},g=w=>{c.current?.contains(w.target)||p.current()},v=()=>p.current();return window.addEventListener("mousedown",h),window.addEventListener("keydown",x,!0),window.addEventListener("scroll",g,!0),window.addEventListener("resize",v),()=>{window.removeEventListener("mousedown",h),window.removeEventListener("keydown",x,!0),window.removeEventListener("scroll",g,!0),window.removeEventListener("resize",v)}},[e]),{triggerRef:o,panelRef:c,position:u}}const V6="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.6 9.3a2.5 2.5 0 0 1 4.9.8c0 1.7-2.5 2.5-2.5 2.5M12 16.8h.01",G6=288;function ba({children:e,label:t,size:n=Ye.inlineGlyph,className:s=""}){const[o,c]=y.useState(!1),u=y.useId(),{triggerRef:f,panelRef:p,position:h}=$f({open:o,onClose:()=>c(!1),estimatedHeight:160,panelWidth:G6}),x=t!==void 0?d.common.moreInfoAbout(t):d.common.moreInfo;return a.jsxs(a.Fragment,{children:[a.jsx("button",{ref:f,type:"button","aria-label":x,title:x,"aria-expanded":o,"aria-controls":u,"aria-describedby":o?u:void 0,onClick:()=>c(g=>!g),className:`inline-flex shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 ${s}`,children:a.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"block shrink-0",children:a.jsx("path",{d:V6})})}),o&&h&&ss.createPortal(a.jsx("div",{ref:p,id:u,role:"tooltip",style:{position:"fixed",top:h.topPx,bottom:h.bottomPx,left:h.left},className:"anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white px-3 py-2 text-xs leading-relaxed text-gray-600 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300",children:e}),document.body)]})}const Uf="rounded-md border border-gray-300 bg-white text-gray-900 transition-[border-color,box-shadow] duration-200 hover:border-gray-400 focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100 dark:hover:border-gray-600 dark:focus:border-gray-400 dark:focus:ring-gray-500/30",ny="w-full px-3 py-1.5 text-left transition-colors duration-150";function kN({label:e}){return e===void 0?a.jsx("span",{className:"ml-0.5 text-red-500 dark:text-red-400","aria-hidden":!0,children:"*"}):a.jsxs("span",{className:"ml-0.5 text-red-500 dark:text-red-400",children:[a.jsx("span",{"aria-hidden":!0,children:"*"}),a.jsx("span",{className:"sr-only",children:e})]})}function Yn({children:e,required:t,htmlFor:n,block:s=!0}){const o=`text-xs font-semibold text-gray-600 dark:text-gray-400${s?" mb-1 block":""}`,c=a.jsxs(a.Fragment,{children:[e,t&&a.jsx(kN,{})]});return n!==void 0?a.jsx("label",{htmlFor:n,className:o,children:c}):a.jsx("span",{className:o,children:c})}function wo({children:e}){return a.jsx("span",{className:"mt-1 block text-xs text-gray-500 dark:text-gray-500",children:e})}function ga({id:e,children:t}){return a.jsx("span",{id:e,role:"alert",className:"mt-1 block text-xs text-red-600 dark:text-red-400",children:t})}function Vu({label:e,hint:t,error:n,errorId:s,required:o,info:c,infoLabel:u,controlId:f,children:p}){if(!e&&!t&&!n&&!c)return a.jsx(a.Fragment,{children:p});const h=n?a.jsx(ga,{id:s,children:n}):t?a.jsx(wo,{children:t}):null,x=e!=null&&e!=="";return c!=null&&f!==void 0?a.jsxs("div",{className:"block",children:[a.jsxs("span",{className:"mb-1 flex items-center gap-1",children:[x&&a.jsx(Yn,{required:o,htmlFor:f,block:!1,children:e}),a.jsx(ba,{...u!==void 0?{label:u}:{},children:c})]}),p,h]}):a.jsxs("label",{className:"block",children:[x&&a.jsx(Yn,{required:o,children:e}),p,h]})}const wN=`w-full ${Uf} placeholder:text-gray-400 disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500`,Pf={base:"px-3 py-2 text-base",sm:"px-2 py-1 text-xs"},zf="!border-red-400 !bg-red-50 hover:!border-red-500 focus:!border-red-500 focus:!ring-red-400/30 dark:!border-red-800 dark:!bg-red-950/40 dark:hover:!border-red-700 dark:focus:!border-red-600";function ry(e,t){return e!==void 0&&e!=="off"?{autoComplete:e}:{autoComplete:t?"new-password":"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"","data-form-type":"other"}}const Gu=ry(void 0,!1);function at({label:e,hint:t,info:n,infoLabel:s,error:o,invalid:c,required:u,size:f="base",className:p,autoComplete:h,id:x,...g}){const v=!!o||!!c,w=y.useId(),S=y.useId(),C=x??S;return a.jsx(Vu,{label:e,hint:t,error:o,errorId:w,required:u,info:n,infoLabel:s,controlId:C,children:a.jsx("input",{id:n!==void 0?C:x,className:`${wN} ${Pf[f]} ${v?zf:""} ${p??""}`,"aria-invalid":v?!0:void 0,"aria-required":u||void 0,"aria-describedby":o?w:void 0,...ry(h,g.type==="password"),...g})})}const ir=y.forwardRef(function({label:t,hint:n,info:s,infoLabel:o,error:c,invalid:u,required:f,mono:p,size:h="base",className:x,autoComplete:g,id:v,...w},S){const C=!!c||!!u,N=y.useId(),T=y.useId(),_=v??T;return a.jsx(Vu,{label:t,hint:n,error:c,errorId:N,required:f,info:s,infoLabel:o,controlId:_,children:a.jsx("textarea",{ref:S,id:s!==void 0?_:v,className:`${wN} px-3 py-2 ${h==="sm"?"text-xs leading-relaxed":"text-base"} ${p?"font-mono":""} ${C?zf:""} ${x??""}`,"aria-invalid":C?!0:void 0,"aria-required":f||void 0,"aria-describedby":c?N:void 0,...ry(g,!1),...w})})});function on({className:e}){return a.jsx("div",{className:`animate-pulse rounded bg-gray-200 dark:bg-gray-800 ${e??"h-4 w-full"}`})}function Sr({rows:e=3}){return a.jsx("div",{className:"space-y-2 p-2",children:Array.from({length:e},(t,n)=>a.jsx(on,{className:"h-8 w-full"},n))})}function SN({className:e,children:t}){return a.jsx("div",{className:`rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900 ${e??"p-4"}`,children:t??a.jsxs(a.Fragment,{children:[a.jsx(on,{className:"h-3 w-20"}),a.jsx(on,{className:"mt-2.5 h-6 w-28"}),a.jsx(on,{className:"mt-2.5 h-3 w-24"})]})})}function Li(e){y.useEffect(()=>{document.title=e?`${e} · ${d.appName}`:d.appName},[e])}var K6=["partial_text","partial_thinking","partial_tool_call","partial_tool_call_output"];function Nu(e){return K6.includes(e.type??"")}function ay(e){return e.type==="event_msg"}function jN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sy(e,t){return`[${e}]
|
|
126
|
+
3. Choose investment actions from a strategy, historical markets, and current indicators.`},agentOptimization:{label:"Improve the general-purpose decision agent's accuracy",desc:"Improve an Agent from existing evaluation results and verify that the new version is better",prompt:"Use `agent-optimization` to optimize a decision Agent against its frozen Benchmark.\n\n- test_agent_id: `finite_choice_agent`\n- benchmark_id: `contextual-choice-adaptation`\n- capability_direction: improve stability under incomplete information, conflicting rules, and finite choices\n- runs: `3`\n- desired_score: `>=95`\n- candidate_round_limit: `5`"},dailyPlan:{label:"A 9am daily planning check-in",desc:"09:00 every day: talk through the day's plan in this same chat, and review yesterday's progress",prompt:"Set up a scheduled task: every day at 9am, in this same conversation, plan today's work with me. Read back over the conversation first and say what yesterday's plan got done and where it stuck, then offer an ordered shortlist for today with a line of reasoning each, and write up what I confirm as a checklist."},githubDigest:{label:"Daily GitHub project digest",desc:"A daily pass over one repo's issues, PRs and CI, ending in prioritized recommendations",prompt:"Set up a scheduled task: every morning, use gh to digest one GitHub repo's issues, PRs and CI — surface what has stalled, what is waiting on review and what is failing — and end with recommendations ranked by priority, each saying why it sits where it does."},memoryReview:{label:"Friday memory review",desc:"Friday evening: go through what is worth remembering from the week and write it into Memory",prompt:"Set up a scheduled task: every Friday evening, in this same conversation, go through what is worth remembering from the week with me. Check the existing memory index first so nothing is duplicated, then take it item by item — what to record, what to revise — and write what I confirm into Memory."}},sessionList:"Sessions",defaultSessionTitle:"New chat",agent:"Agent",model:"Model",workspace:"Workspace",workspaceHint:"Leave empty for an auto-created temporary workspace; if set, it must be an existing directory on the server",workspaceHintShort:"Leave empty for a temporary workspace",approvalMode:"Approval mode",approvalModeNames:{"allow-all":"Approve everything","deny-all":"Deny everything","read-only":"Approve read-only","always-ask":"Ask every time"},approvalModes:{"allow-all":"Approve everything (allow-all)","deny-all":"Deny everything (deny-all)","read-only":"Approve read-only (read-only)","always-ask":"Ask every time (always-ask)"},statusRunning:"Running",statusCompacting:"Compacting",statusCompletedUnread:"Done, unread",pendingApprovals:e=>`${e} pending approval${e>1?"s":""}`,jumpToLatest:"Jump to latest",loadingEarlier:"Loading earlier messages…",loadEarlierRetry:"Failed to load earlier messages — click to retry",historyBeginning:"Beginning of conversation",outlineTitle:"Outline",outlineTickLabel:(e,t)=>`Turn ${e}: ${t}`,outlineNoText:"(image or attachment)",outlineAnswering:"Answering…",inputPlaceholder:"Type a message. Enter to send, Shift+Enter for newline, paste images",inputPlaceholderShort:"Type a message…",steerPlaceholder:"Message the running agent — delivered with the next turn",steerPlaceholderShort:"Message the running agent…",steerSend:"Send to the running agent",steerQueuedIndicator:"Steering queued — delivered with the next turn",steerQueuedItem:e=>`Steering queued — delivered with the next turn: ${e}`,userSteering:"User steering",steerModeLabel:"Mid-run send mode",steerModeSteer:"Steer",steerModeSteerHint:"Steer now: delivered to the running agent with the next turn",steerModeFollowUp:"Queue",steerModeFollowUpHint:"Queue a follow-up: sent automatically as a new message when this run finishes",followUpPlaceholder:"Queue as the next message — sent automatically when this run finishes",followUpPlaceholderShort:"Queue as the next message…",followUpSend:"Queue as the next message",followUpQueuedChip:e=>`${e} follow-up ${e===1?"message":"messages"} queued — sent when this run finishes`,followUpQueuedItem:e=>`Follow-up queued — sent when this run finishes: ${e}`,recallQueued:"Recall",recallQueuedTitle:"Recall to the input box to edit and resend",send:"Send",stop:"Stop",compact:"Compact context",approve:"Allow",deny:"Deny",decisionAllow:"Approved",decisionDeny:"Denied",decisionManual:"manual",decisionAuto:"auto",decisionPolicy:"policy",thinking:"Thinking",subagent:"Subagent",subagentRunning:"Running",aborted:e=>{const t=e?.errorCode==="user_abort"?"aborted by user":e?.errorCode==="backoff_interrupted"?"aborted during reconnect backoff":e?.errorCode==="compaction_interrupted"?"aborted during compaction":e?.errorCode??e?.reason??"",n=t?`${t}${e?.errorMessage?`: ${e.errorMessage}`:""}`:"";return`[Aborted]${n?`: ${n}`:""}`},reconnect:(e,t,n,s,o,c)=>{const u=c??e,f=u==="timeout"?"Connection timed out":u==="malformed"?"Response incomplete or unparseable":u==="network"?"Network or service temporarily unavailable":u==="failed"?"The model provider returned an error":"The request failed",p=t==="gaveUp"?`giving up after attempt ${n}${o?`: ${o}`:""}`:t==="retried"?`retry #${n} sent`:s!==void 0?`retry #${n} in ${s}s…`:`starting retry #${n}…`;return`[Retry] ${f}; ${p}`},llmError:e=>`[Error]: llm request error${e?`: ${e}`:""}`,reconnectRetryNow:"Retry now",reconnectGiveUp:"Give up",imageAlt:"Image uploaded by user",toolImageAlt:"Image from tool output",imagesAsPathHint:"This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via describe_image)",infoPanel:"Session info",sessionStats:"Stats",sessionIdLabel:"Session id",copySessionId:"Copy Session id",processList:"Processes",processStop:"Stop",processExited:"exited",processRemove:"Remove",processRemoveHint:"Remove this entry — the output captured from it is discarded too",runningServices:e=>e===1?"1 running service":`${e} running services`,statTokens:"Total Tokens",statTotalTokens:"Total Tokens",statCacheHit:e=>`cache hit rate ${e}`,statElapsed:"Elapsed",statInput:"Input tokens",statCached:"cached",statOutput:"Output tokens",statTps:"Output TPS",statParenOpen:" (",statParenClose:")",noSessions:"No Sessions yet",emptyStream:"Send a message to start the conversation",historyLoadFailed:"Failed to load history",statsLabel:"Stats",removeImage:"Remove image",openAgents:"Agents panel",workspacePanel:"Workspace",filesInMessage:e=>`${e} ${e===1?"file":"files"}`,imagesInMessage:e=>`${e} ${e===1?"image":"images"}`,openPreview:"Click to preview",showMoreFiles:e=>`Show ${e} more ${e===1?"file":"files"}`,showLess:"Show less",memoryChangesTitle:e=>`${e} memory ${e===1?"update":"updates"}`,memoryScopeWorkspace:e=>`Workspace memory (${e})`,memoryOpWrite:"Wrote",memoryOpEdit:"Edited",memoryViewTitle:"Memory",memoryChangedMark:"Changed in this conversation",memoryContentUnavailable:"Content unavailable (the file may have been moved or deleted)",memoryRowOpen:"View content",memoryBack:"Back to the list",memoryEmptyAll:"No memory yet — say “remember …” in a chat to have the agent save one",openAgentMemory:"Manage in agent settings",memoryShowMore:e=>`Show ${e} more`,prevGroupPage:"Previous groups",nextGroupPage:"Next groups",groupPagePosition:(e,t)=>`Page ${e} of ${t}`,contextUsage:"Context usage",contextUnknown:"Context usage: unknown until the next request reports it",contextComposition:"Context composition",contextPartSystemPrompt:"System prompt",contextPartToolDefs:"Tool definitions",contextPartUserMessages:"User messages",contextPartAssistantMessages:"Model messages",contextPartToolRequests:"Tool requests",contextPartToolResults:"Tool results",contextTopTools:"Top 5 tools",contextCompactAt:e=>`Compaction threshold ${e}`,contextTopToolsHint:"Ranked by the context each tool's calls and results occupy (definitions count under “Tool definitions”)",contextUnknownHint:"Just compacted — the next request reports the usage, and the composition with it",contextBreakdownEmpty:"Nothing in the current context to break down yet",contextBreakdownFailed:"Could not read the context composition",slashHint:"Type / for commands",switchAgent:"Hand off to another agent — opens a new session on send",switchAgentTitle:"Choose agent",agentSearchPlaceholder:"Search agents: id / name",agentsNoMatch:"No matching agents",handoffTargetTitle:e=>`Sending hands this conversation to ${e}`,handoffRemove:"Remove handoff target",skillsSelect:"Skills",skillRemove:"Remove skill",skillsSearchPlaceholder:"Search skills",skillsNoMatch:"No matching skills",skillsEmptyHint:"No skills installed yet — add some from the skill library",skillsAutoMessage:e=>e.length===1?`use the ${e[0]} skill`:`use the ${e.join(", ")} skills`,handoffFrom:e=>`Handed off from ${e}'s conversation`,handoffBack:e=>e?`Back to the original conversation: ${e}`:"Back to the original conversation",switchModel:"Switch model — on send, continues this conversation in a new session",switchModelTitle:"Switch model",modelSwitchTargetTitle:e=>`Sending continues this conversation on ${e}`,modelSwitchRemove:"Remove model switch",modelSwitchBusyHint:"The model switch waits for this turn to finish: the new session continues from this session's record",modelSwitchFrom:e=>e?`Switched model (was ${e}) — continued from the earlier conversation`:"Switched model — continued from the earlier conversation",modelSwitchAutoMessage:"Continue this conversation on the new model",modelLockedHint:"Type /model to switch models",scheduledFrom:e=>`Triggered by scheduled task "${e}"`,backgroundDone:(e,t)=>{const n=e==="command"?"Background command":"Background task";return t==="stopped"?`${n} stopped`:t==="completed"?`${n} finished`:`${n} failed`},emptyGreeting:"Start a new conversation",mcpConnectTitle:"MCP connect",mcpServerList:e=>e.join(", "),mcpConnectResult:(e,t)=>{const n=[];return(e>0||t.length===0)&&n.push(`${e} tool${e===1?"":"s"} discovered`),t.length>0&&n.push(`unavailable: ${t.join(", ")}`),n.join("; ")},mcpToolsCount:e=>`${e} tool${e===1?"":"s"}`,mcpServerFailed:"connection failed",mcpConnectAborted:"interrupted — reconnects on the next send",compactionTitle:e=>e==="discard"?"Clear":"Compaction",compactionFailed:(e,t)=>{if(e==="aborted")return"aborted, keeping current context";const n=t!==void 0?` (${t})`:"";return e==="retryable"?`failed${n}, keeping current context; retries at the next trigger`:e==="fatal"?`failed${n}, keeping current context; fix the model configuration to retry`:`failed${n}, keeping current context`},unknownTool:"(unknown tool)",workRunning:"Running",workDone:"Done",workGroupSteps:e=>`${e} ${e===1?"step":"steps"}`,approvalWaiting:"awaiting approval",copyCode:"Copy code",copyReply:"Copy reply",forkSession:"Fork chat from here",forkSessionConfirmBody:"This copies the conversation up to this reply into a new chat. The original chat stays unchanged.",forkSessionConfirmAction:"Fork",forkSessionFailed:"This reply could not be located. Refresh and try again.",copyMessage:"Copy message",deleteSession:"Delete chat",renameSession:"Rename chat",renameSessionLabel:"Title",deleteSessionConfirm:e=>`Delete "${e}"? Its messages and Trace will be removed permanently.`,draftGroup:"Drafts",draftUntitled:"(untitled draft)",deleteDraft:"Delete draft",deleteDraftConfirm:e=>`Delete draft "${e}"? Unsent content will be discarded.`,archiveSession:"Archive",unarchiveSession:"Unarchive",pinSession:"Pin",unpinSession:"Unpin",pinnedSession:"Pinned",moreActions:"More",loadMore:"More",expandRestSessions:e=>`Show ${e} more ${e===1?"chat":"chats"}`,loadMoreSessions:"Load more chats",folderGroups:{subagent:e=>`Subagents (${e})`,schedule:e=>`Scheduled (${e})`,archived:e=>`Archived (${e})`},skillsBanner:e=>`Using skill${e.length===1?"":"s"}: ${e.join(", ")}`,attachedFilesBanner:e=>`Attached file${e.length===1?"":"s"}: ${e.join(", ")}`,plusMenu:"More input options",uploadImage:"Upload image",uploadImageDesc:"Attach images to this message",uploadFile:"Upload file",uploadFileDesc:"Saved to the session scratchpad; the model reads them by path",removeFile:"Remove file",attachmentTooLarge:(e,t)=>`${e} exceeds the ${t}MB limit and was not attached.`,dropFilesTitle:"Drop files to attach",dropFilesDesc:"Images and files are added to the message draft",dropFilesGoalHint:"Goal mode takes images only; the files were not attached.",goalMode:"Goal mode",goalModeDesc:"Loop until the goal completes",goalBudgetLabel:"Token budget",goalBudgetUnlimited:"Budget unlimited",goalBudgetValue:e=>`Budget ${e}`,goalBudgetPlaceholder:"e.g. 500k",goalBudgetHint:"Use a k/m suffix; leave blank for no budget limit",goalBudgetInvalid:"Invalid budget: use a positive number with an optional k/m suffix (500k, 2m)",goalBudgetSave:"Save budget",goalRemove:"Exit goal mode",goalRoundBanner:e=>`Goal · round ${e}`,goalRoundImages:e=>e===1?"1 attached image":`${e} attached images`,goalProgress:(e,t)=>`round ${e} · tokens ${t}`,goalStatus:{active:"running",complete:"complete",blocked:"blocked",budget_limited:"budget exhausted",aborted:"interrupted"}},feishu:{intro:"Once bound, messages sent to the Feishu bot flow into this conversation, and the AI's replies are sent back to Feishu as plain text. You need a self-built Feishu app with the bot capability and the message-receive event subscribed in long-connection mode.",appId:"App ID",appSecret:"App Secret",appSecretKeepHint:"Leave empty to keep the saved App Secret",clearSecret:"Clear stored App Secret",baseDomain:"API domain",baseDomainHint:"https://open.feishu.cn for Feishu, https://open.larksuite.com for Lark",invalidDomain:"The domain must be an http(s) URL",testMessageNoChat:"Message the bot once in Feishu first, so it knows which chat to send to",setupSteps:["Create a self-built app in the Feishu developer console","Enable the bot capability for the app","Subscribe to the message-receive event, with the subscription mode set to long connection","Copy the App ID and App Secret from the credentials page into the form above","Publish an app version, get it approved, then message the bot once in Feishu"]},telegram:{intro:"Once bound, messages sent to the Telegram bot flow into this conversation, and the AI's replies are sent back to Telegram as plain text. Create a bot with @BotFather and paste its Bot Token — no public URL is needed.",botToken:"Bot Token",botTokenKeepHint:"Leave empty to keep the saved Bot Token",clearToken:"Clear stored Bot Token",invalidToken:"The Bot Token looks like <digits>:<secret>, as issued by @BotFather",testMessageNoChat:"Message the bot once in Telegram first, so it knows which chat to send to",setupSteps:["Open @BotFather in Telegram and send /newbot to create a bot","Name it as prompted, then copy the Bot Token @BotFather returns into the form above","Find the bot in Telegram and send it one message"]},messaging:{panelTitle:"Messaging",bindAction:"Messaging binding…",dialogTitle:"Messaging binding",channelLabel:"Channel",channelName:{feishu:"Feishu",telegram:"Telegram"},tutorial:"Open tutorial",console:"Open developer console",enabled:"Enable connection",saveBeforeEnable:"Save the credentials first, then enable the connection",test:"Test connection",testing:"Testing…",testOk:e=>`Connected (${e}ms)`,testOkAs:(e,t)=>`Connected as ${e} (${t}ms)`,testFail:e=>`Connection failed: ${e}`,sendTestMessage:"Send test message",sendingTestMessage:"Sending…",testMessageSent:"Test message sent",statusLabel:"Connection status",status:{disconnected:"Not connected",connecting:"Connecting",connected:"Connected",error:"Connection error"},otherEnabledHint:e=>`Only one channel can be enabled per conversation: turn off the ${e} connection first`,credentialMissingHint:"Enter and save the credential first, then enable the connection",disableBeforeClearHint:"Disable the connection before clearing the credential",enabledIndicator:{feishu:"Feishu connection enabled",telegram:"Telegram connection enabled"},faqSetupTitle:"Set up the bot",faqWhatTitle:"What binding does",faqTroubleTitle:"Troubleshooting",troubleNoChat:"“Send test message” disabled? The bot must have received one message first, so it knows which chat to send to.",troubleConnError:"Connection status shows an error? Check the credentials; for Feishu also confirm the API domain and the long-connection event subscription.",troubleOnePoller:"Telegram reports that another program is polling? A Bot Token serves exactly one program at a time — close the other PenguinHarness server or bot script using it, or give this conversation a bot of its own."},subagentPanel:{topologyLabel:"Call graph",mainSessionNote:"The main conversation stays in the chat area",empty:"No subagents in the current task yet",nodeRunning:"running",nodeDone:"done",openAsSession:"Jump to this session",subagentGone:"This subagent session no longer exists and could not be revived"},files:{title:"Files",upload:"Upload",download:"Download",openInNewTab:"Open in new tab",previewNotIsolatedHint:"This address has no separate preview origin, so the page opens sandboxed: localStorage, cookies and third-party embeds will not work. Reach the app over 127.0.0.1 or localhost, or set PENGUIN_PREVIEW_ORIGIN.",refresh:"Refresh",root:"Workspace root",empty:"Empty directory",previewUnsupported:"Preview not supported for this type; download instead",uploaded:"Uploaded",overwriteTitle:"Overwrite existing files",overwriteConfirm:e=>`The current directory already has ${e} file(s) with these names — uploading will overwrite:`,loadFailed:"Failed to load",previewTruncated:"File too large; preview truncated, download for the full file",details:"Details",workspacePath:"Workspace path",htmlRendered:"Rendered",htmlSource:"Source",backToList:"Back to list"},usage:{title:"Costs & usage",today:"Today",last7d:"Last 7 days",total:"Total",tokens:"Tokens",requests:"Requests",from:"From",to:"To",colCacheRead:"cache_read",colCacheWrite:"cache_write",colOutput:"output",uncostedNote:"* Only models with configured pricing count toward cost",filterAllAgents:"All agents",filterAllModels:"All models",rangeLabel:"Date range",rangeHour:"Last hour",rangeDay:"Last 24 hours",range7d:"Last 7 days",range30d:"Last 30 days",range90d:"Last 90 days",rangeCustom:"Custom",chartRequestsByAgent:"Requests & success rate by agent",chartRequestsByModel:"Requests & success rate by model",legendSuccessRate:"Success rate",chartTokenTrend:"Token trend",chartCostTrend:"Cost trend",legendOther:e=>`Other (${e})`,bucketTotal:"Total",legendHitRate:"Cache hit rate",empty:"No usage records",errors:"Errors",errorsTotal:"Total",errorsUnexpected:"Unexpected",errorsExpected:"Expected",errorsTopCode:"Most common",errorsColCode:"Source · code",errorsColKind:"Type",errorsColMessage:"Message",errorsEmpty:"No errors",errorsNewer:"Newer",errorsOlder:"Older",errorsPageOf:(e,t,n)=>`Page ${e} / ${t} · ${n} total`},traces:{timeline:"Execution timeline",laneLLM:"Model",kindThinking:"thinking",kindModelReply:"model reply",kindToolGen:"tool call gen",legendToolExec:"tool exec",legendOther:"Other",toolParams:"Parameter schema",requiredParam:"required",legendApprovalWait:"approval wait",task:e=>`Turn ${e}`,globalSummary:"Overall",tasksLabel:"Turns",messages:"Messages",truncatedNote:(e,t)=>`Showing first ${e} / ${t} messages`,zoom:"Zoom",zoomReset:"Double-click to reset zoom",zoomOut:"Zoom out",zoomIn:"Zoom in",linkHint:"Hover a timeline segment or event row to cross-highlight, click a segment to jump to its message; legend highlights its kind; drag the bar below to pan/zoom",filesTitle:"Trace files",toolCalls:"Tool calls",taskInput:"Input tokens this turn",taskOutput:"Output tokens this turn",cacheHit:"Cache hits",hitRate:"Hit rate",compactions:"compactions",inProgress:"in progress",systemPrompt:"System prompt",toolDefs:e=>`Tool definitions (${e})`,exportFile:"Export"},benchmark:{title:"Evaluation Center",selectBenchmark:"Select a Benchmark on the left",emptyAgent:"No Benchmarks for this agent",caseCount:e=>`${e} case${e===1?"":"s"}`,trendTitle:e=>`${e} over time`,cases:"Cases",viewCase:"View details",taskMaterials:"Task materials",rubric:"Scoring rubric",agentHidden:"Hidden from Target Agent",caseFileUnavailable:"Case files are unavailable",evaluations:"Evaluations",noEvaluations:"No evaluations yet",summaryLabel:"Summary",legendUnlabeled:"unlabeled model",colVersion:"Version",colModel:"Model ID",colThinkingLevel:"Thinking level",colScore:"Score",colDuration:"Duration",colCase:"Case",colRun:"Run",colSession:"Session"},errors:{networkError:"Network error, please check your connection",modelCredentialMissing:e=>`Model ${e} has no API key yet — configure it on the Models page first`,noDefaultModel:"This project has no default model yet — add one on the Models page first",byCode:{invalid_credentials:"Incorrect username or password.",too_many_attempts:"Too many failed sign-in attempts. Try again shortly.",password_mismatch:"The current password is incorrect.",invalid_password:"Password must be at least 8 characters.",admin_required:"Only an admin can perform this operation.",desktop_single_user:"The desktop app is single-user; user management is unavailable.",not_found:"This resource does not exist, or you do not have access.",internal:"The server hit an internal error. Please try again shortly.",agent_not_found:"This agent no longer exists.",unknown_agent:"That agent does not exist in this Project.",agent_exists:"This agent id is already taken.",agent_deleting:"This agent is being deleted.",project_exists:"This Project id is already taken.",project_not_found:"This Project no longer exists, or you do not have access.",cannot_delete_last_project:"This is the last Project and cannot be deleted.",user_exists:"This username is already taken.",user_not_found:"This user no longer exists.",cannot_delete_admin:"The built-in admin cannot be deleted.",member_not_found:"This user is not a member of the Project.",already_member:"This user is already a member of the Project.",already_owner:"This user is already an owner of the Project.",memory_import_confirm_required:"This import would overwrite or delete memories. Confirm it to continue.",schedule_exists:"A scheduled task with this name already exists.",schedule_not_found:"This scheduled task no longer exists.",unknown_skill:"This skill is not in the library.",skill_too_large:"This skill directory exceeds the import limits.",file_not_found:"This file no longer exists.",not_pending:"This steering message already reached the model and can no longer be recalled.",follow_up_started:"This follow-up already started and can no longer be recalled.",file_too_large:"The file is too large.",too_many_files:"Too many files attached to one message.",payload_too_large:"The request is too large.",image_too_large:"The image is too large to send inline.",dir_not_absolute:"The directory must be an absolute path.",dir_not_found:"That directory does not exist or is inaccessible.",not_a_dir:"That path is not a directory.",path_not_found:"That path does not exist.",workspace_missing:"This Session's Workspace no longer exists.",workspace_not_found:"That Workspace does not exist, or is not a directory.",session_not_found:"This Session no longer exists, or you do not have access.",session_deleting:"This Session is being deleted.",approval_not_found:"This approval request was already answered, or is no longer valid.",process_not_found:"This background process already exited, or was removed.",process_running:"This background process is still running — stop it before removing it.",memory_file_not_found:"This memory file no longer exists.",memory_scope_not_found:"This memory scope no longer exists.",task_in_progress:"This Session already has a task running.",compacting:"This Session is compacting its context and is not accepting new input.",shutting_down:"The server is shutting down. Please try again shortly.",compaction_not_configured:"This agent does not have context compaction configured.",nothing_to_compact:"There is nothing to compact in the current context yet (no completed conversation turn).",already_compacted:"The context was just compacted and nothing has been said since — no need to compact again.",version_conflict:"The snapshot's version is not newer than the current one.",invalid_title:"The title is invalid.",invalid_proxy_url:"Invalid proxy address — use an http(s):// or socks5:// proxy URL, or host[:port].",invalid_attachment_limit:"Invalid upload limit — use a whole number of MB inside the allowed range, with the total no lower than the per-file limit.",invalid_trace:"This file is not a valid Trace file.",trace_not_found:"This Trace file no longer exists.",trace_session_exists:"This agent already has a Session with that id; a duplicate Trace cannot be imported.",feishu_app_in_use:"This Feishu app is already bound to another Session — unbind it there or use a different app.",feishu_secret_required:"App Secret is required.",feishu_not_bound:"This Session has no Feishu binding yet.",feishu_no_chat:"No Feishu message received yet — message the bot once in Feishu first.",feishu_send_failed:"Sending the Feishu message failed.",telegram_bot_in_use:"This Telegram bot is already bound to another Session — unbind it there or use a different bot.",telegram_token_required:"Bot Token is required.",telegram_token_invalid:"The Bot Token is malformed: it looks like <digits>:<secret>.",telegram_not_bound:"This Session has no Telegram binding yet.",telegram_no_chat:"No Telegram message received yet — message the bot once in Telegram first.",telegram_send_failed:"Sending the Telegram message failed.",another_channel_enabled:"Another channel's connection is enabled on this conversation: disable it first.",messaging_disable_before_clear:"Disable this channel's connection before clearing its credential."}}},Pj="penguin.lang",zj=y.createContext(null);function Y3(e){return e?.toLowerCase().startsWith("zh")?"zh":"en"}function X3(){return Y3(navigator.language)}function Q3(e){return e==="system"?X3():e}function Z3(){const e=localStorage.getItem(Pj);return e==="zh"||e==="en"||e==="system"?e:"system"}function J3({children:e}){const[t,n]=y.useState(Z3),[,s]=y.useState(0),o=Q3(t);K3(o==="en"?W3:Uj),y.useEffect(()=>{if(t!=="system")return;const u=()=>s(f=>f+1);return window.addEventListener("languagechange",u),()=>window.removeEventListener("languagechange",u)},[t]);const c=y.useCallback(u=>{localStorage.setItem(Pj,u),n(u)},[]);return a.jsx(zj.Provider,{value:{lang:t,locale:o,setLang:c},children:e})}function eE({children:e}){const{locale:t}=Dr();return a.jsx("div",{className:"contents",children:e},t)}function Dr(){const e=y.useContext(zj);if(!e)throw new Error("useLocale must be used within a LocaleProvider");return e}const wx=7,Bj="penguin.theme",Hj="penguin.fontScale",Fj="penguin.accent",qj="penguin.currency",Vj="penguin.terminal.theme",tE={sm:"16px",md:"18px",lg:"20px"},Gj=y.createContext(null);function nE(){const e=localStorage.getItem(Bj);return e==="light"||e==="dark"||e==="system"?e:"system"}function rE(){const e=localStorage.getItem(Hj);return e==="sm"||e==="md"||e==="lg"?e:"md"}function aE(){const e=localStorage.getItem(Fj);return e==="neutral"||e==="blue"||e==="green"||e==="violet"||e==="rose"||e==="amber"?e:"neutral"}function sE(){const e=localStorage.getItem(Vj);return e==="light"||e==="dark"||e==="app"?e:"app"}function iE(){return localStorage.getItem(qj)==="CNY"?"CNY":"USD"}function oE(){return window.matchMedia("(prefers-color-scheme: dark)").matches}function lE({children:e}){const[t,n]=y.useState(nE),[s,o]=y.useState(oE),[c,u]=y.useState(rE),[f,p]=y.useState(aE),[h,x]=y.useState(iE),[g,v]=y.useState(sE),w=t==="system"?s:t==="dark",S=g==="app"?w:g==="dark";y.useEffect(()=>{document.documentElement.classList.toggle("dark",w)},[w]),y.useEffect(()=>{document.documentElement.style.fontSize=tE[c]},[c]),y.useEffect(()=>{f==="neutral"?delete document.documentElement.dataset.accent:document.documentElement.dataset.accent=f},[f]),y.useEffect(()=>{if(t!=="system")return;const D=window.matchMedia("(prefers-color-scheme: dark)"),z=E=>o(E.matches);return o(D.matches),D.addEventListener("change",z),()=>D.removeEventListener("change",z)},[t]);const C=y.useCallback(D=>{localStorage.setItem(Bj,D),n(D)},[]),N=y.useCallback(D=>{localStorage.setItem(Hj,D),u(D)},[]),T=y.useCallback(D=>{localStorage.setItem(Fj,D),p(D)},[]),_=y.useCallback(D=>{localStorage.setItem(qj,D),x(D)},[]),R=y.useCallback(D=>{localStorage.setItem(Vj,D),v(D)},[]);return a.jsx(Gj.Provider,{value:{mode:t,dark:w,setMode:C,fontScale:c,setFontScale:N,accent:f,setAccent:T,currency:h,setCurrency:_,terminalMode:g,setTerminalMode:R,terminalDark:S},children:e})}function as(){const e=y.useContext(Gj);if(!e)throw new Error("useTheme must be used within a ThemeProvider");return e}const cE=[{value:"neutral",color:"#6b7280"},{value:"blue",color:"#2563eb"},{value:"green",color:"#15803d"},{value:"violet",color:"#7c3aed"},{value:"rose",color:"#be123c"},{value:"amber",color:"#b45309"}];class xr extends Error{status;code;constructor(t,n,s){super(s),this.name="ApiError",this.status=t,this.code=n}}let Kj=null;function H1(e){Kj=e}function uE(e){return e.startsWith("/api/auth/")}async function Ee(e,t={}){return(await Wj(e,t)).data}async function Wj(e,t={}){let n=e;if(t.query){const f=new URLSearchParams;for(const[h,x]of Object.entries(t.query))x!==void 0&&f.set(h,String(x));const p=f.toString();p&&(n+=`?${p}`)}let s;try{s=await fetch(n,{method:t.method??"GET",credentials:"same-origin",...t.body!==void 0?{headers:{"Content-Type":"application/json"},body:JSON.stringify(t.body)}:{}})}catch{throw new xr(0,"network_error",d.errors.networkError)}if(!s.ok){let f="http_error",p=d.common.unknownError;try{const h=await s.json();h.error?.code&&(f=h.error.code),h.error?.message&&(p=h.error.message)}catch{}throw s.status===401&&!uE(e)&&Kj?.(),new xr(s.status,f,p)}const o=Date.parse(s.headers.get("date")??""),c=Number.isFinite(o)?o:null;if(s.status===204)return{data:void 0,serverNowMs:c};const u=await s.text();return u?{data:JSON.parse(u),serverNowMs:c}:{data:void 0,serverNowMs:c}}const dE=e=>Ee("/api/auth/login",{method:"POST",body:e}),mE=()=>Ee("/api/auth/logout",{method:"POST",body:{}}),qm=()=>Ee("/api/me"),fE=e=>Ee("/api/me/password",{method:"PUT",body:e}),Sx=()=>Ee("/api/me/prefs"),Nf=e=>Ee("/api/me/prefs",{method:"PUT",body:e}),pE=()=>Ee("/api/admin/users"),hE=e=>Ee("/api/admin/users",{method:"POST",body:e}),gE=(e,t)=>Ee(`/api/admin/users/${encodeURIComponent(e)}/password`,{method:"POST",body:t}),xE=e=>Ee(`/api/admin/users/${encodeURIComponent(e)}`,{method:"DELETE"}),Yj=()=>Ee("/api/admin/settings"),Xj=e=>Ee("/api/admin/settings",{method:"PUT",body:e}),yE=()=>Ee("/api/projects"),bE=e=>Ee("/api/projects",{method:"POST",body:e}),vE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),kE=e=>Ee(`/api/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),mg=e=>Ee(`/api/projects/${encodeURIComponent(e)}/members`),wE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/members`,{method:"POST",body:t}),SE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/members/${encodeURIComponent(t)}`,{method:"DELETE"}),Qj=e=>Ee(`/api/projects/${encodeURIComponent(e)}/chat-defaults`),jE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/chat-defaults`,{method:"PUT",body:t}),CE=e=>Ee(`/api/projects/${encodeURIComponent(e)}/command-policy`),NE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/command-policy`,{method:"PUT",body:t}),Ml=e=>Ee(`/api/projects/${encodeURIComponent(e)}/models`),TE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models`,{method:"PUT",body:t}),ME=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/default`,{method:"PUT",body:t}),Zj=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/test`,{method:"POST",body:t}),Jj=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/detect`,{method:"POST",body:t}),EE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/list`,{method:"POST",body:t}),AE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/models/detect-vision`,{method:"POST",body:t}),_E=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/start`,{method:"POST",body:t}),RE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/${encodeURIComponent(t)}`),IE=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/model-oauth/${encodeURIComponent(t)}/code`,{method:"POST",body:{code:n}}),LE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault`),OE=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault`,{method:"PUT",body:n}),DE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/vault/template-placeholder`,{method:"POST",body:{}}),$E=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/template-placeholder`,{method:"POST",body:{}}),UE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/template-placeholder`,{method:"POST",body:{}}),Tf=(e,t)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/memory`,jx=(e,t,n)=>`${Tf(e,t)}/scopes/${encodeURIComponent(n)}/files`,eC=(e,t)=>Ee(Tf(e,t)),PE=(e,t)=>Ee(`${Tf(e,t)}/template-placeholder`,{method:"POST",body:{}}),tC=(e,t,n)=>Ee(jx(e,t,n)),nC=(e,t,n,s)=>Ee(`${jx(e,t,n)}/${encodeURIComponent(s)}`),zE=(e,t,n,s)=>Ee(`${jx(e,t,n)}/${encodeURIComponent(s)}`,{method:"DELETE"}),rC=(e,t,n)=>`${Tf(e,t)}/scopes/${encodeURIComponent(n)}`,BE=(e,t,n)=>Ee(`${rC(e,t,n)}/export`),HE=(e,t,n,s)=>Ee(`${rC(e,t,n)}/import`,{method:"POST",body:s}),aC=e=>Ee(`/api/projects/${encodeURIComponent(e)}/agents`),FE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents`,{method:"POST",body:t}),Ao=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config`),To=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config`,{method:"PUT",body:n}),F1=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/mcp-test`,{method:"POST",body:n}),qE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/reset`,{method:"POST"}),VE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/config/kernel-update`,{method:"POST"}),c0=(e,t,n)=>{const s=n?`?limit=${n.limit}&offset=${n.offset}`+(n.category?`&category=${n.category}`:"")+(n.workspaceGroup?`&workspaceGroup=${encodeURIComponent(n.workspaceGroup)}`:"")+(n.withCounts?"&counts=1":""):"";return Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/sessions${s}`)},GE=(e,t="")=>Ee(`/api/projects/${encodeURIComponent(e)}/dirs?path=${encodeURIComponent(t)}`),KE=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/dir-skills?path=${encodeURIComponent(t)}`),u0=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/sessions`,{method:"POST",body:n}),WE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/fork`,{method:"POST",body:t}),d0=e=>Ee(`/api/sessions/${encodeURIComponent(e)}`),tf=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",body:t}),nf=e=>Ee(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"}),YE=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging`),XE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/feishu`,{method:"PUT",body:t}),QE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/telegram`,{method:"PUT",body:t}),ZE=(e,t,n)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/${t}/state`,{method:"POST",body:{enabled:n}}),JE=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/feishu/test`,{method:"POST",body:t}),eA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/telegram/test`,{method:"POST",body:t}),tA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/messaging/${t}/test-message`,{method:"POST",body:{}}),sC=(e,t)=>{const n=t===void 0?"":t.kind==="tail"?`?tailLimit=${t.limit}`:`?before=${encodeURIComponent(t.cursor)}&limit=${t.limit}`;return Wj(`/api/sessions/${encodeURIComponent(e)}/messages${n}`).then(({data:s,serverNowMs:o})=>({...s,serverNowMs:o}))},su=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/tasks`,{method:"POST",body:t}),nA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/goal`),rA=(e,t,n)=>Ee(`/api/sessions/${encodeURIComponent(e)}/approvals/${encodeURIComponent(t)}`,{method:"POST",body:n}),aA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/abort`,{method:"POST",body:{}}),sA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/retry-now`,{method:"POST",body:{}}),q1=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes`),iA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}/kill`,{method:"POST",body:{}}),oA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/processes/${encodeURIComponent(t)}`,{method:"DELETE"}),lA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/steer`,{method:"POST",body:t}),cA=(e,t,n,s)=>Ee(`/api/sessions/${encodeURIComponent(e)}/subagents/${encodeURIComponent(t)}/message`,{method:"POST",body:{text:n,...s?{thinkingLevel:s}:{}}}),uA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/subagents/${encodeURIComponent(t)}/abort`,{method:"POST",body:{}}),dA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/steer/${encodeURIComponent(t)}`,{method:"DELETE"}),mA=(e,t)=>Ee(`/api/sessions/${encodeURIComponent(e)}/follow-ups/${encodeURIComponent(t)}`,{method:"DELETE"}),fA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/compact`,{method:"POST",body:{}}),pA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/context`),hA=e=>Ee(`/api/sessions/${encodeURIComponent(e)}/traces`),gA=(e,t,n,s,o,c)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}`,{query:{offset:o,limit:c}}),xA=(e,t,n,s)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}/analysis`),yA=(e,t,n,s)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/${encodeURIComponent(n)}/${s}/download`,bA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/traces/import`,{method:"POST",body:n}),vA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/usage/errors`,{query:{offset:String(t.offset),limit:String(t.limit),from:t.from,to:t.to,agentId:t.agentId}}),iC=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/usage`,{query:{from:t.from,to:t.to,fromTs:t.fromTs,toTs:t.toTs,groupBy:t.groupBy,granularity:t.granularity,agentId:t.agentId,provider:t.provider,modelId:t.modelId}}),kA=(e,t)=>Ee(`/api/projects/${e}/agents/${t}`,{method:"DELETE"}),wA=(e,t)=>Ee(`/api/sessions/${e}/files`,{query:{path:t}}),ji=(e,t,n=!1)=>`/api/sessions/${e}/files/content?path=${encodeURIComponent(t)}${n?"&download=1":""}`,V1=(e,t)=>`/api/sessions/${e}/files/preview-redirect?path=${encodeURIComponent(t)}`,SA=(e,t,n)=>Ee(`/api/sessions/${e}/files/content`,{method:"PUT",body:{dataBase64:n},query:{path:t}}),jA=(e,t)=>Ee(`/api/sessions/${e}/files/stat`,{method:"POST",body:{paths:t}}),CA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules`),NA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules`,{method:"POST",body:n}),G1=(e,t,n,s)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/${encodeURIComponent(n)}`,{method:"PUT",body:s}),TA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/schedules/${encodeURIComponent(n)}`,{method:"DELETE"}),oC=()=>Ee("/api/skills"),Bu=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills`),K1=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills`,{method:"POST",body:{names:n}}),MA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/archive`,{method:"POST",body:n}),EA=(e,t,n)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}/archive`,lC=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/skills/${encodeURIComponent(n)}`,{method:"DELETE"}),AA=(e,t)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks`),_A=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks/${encodeURIComponent(n)}/cases`),cC=(e,t,n,s,o)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/benchmarks/${encodeURIComponent(n)}/cases/${encodeURIComponent(s)}${o==="rubric"?"/rubric":""}/files`,RA=(e,t,n,s,o,c)=>Ee(cC(e,t,n,s,c),{query:{path:o}}),IA=(e,t,n,s,o,c,u)=>`${cC(e,t,n,s,c)}/content?path=${encodeURIComponent(o)}`+(u?.download?"&download=1":"")+(u?.preview&&!u.download?"&preview=1":""),LA=(e,t)=>`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/export`,OA=(e,t,n)=>Ee(`/api/projects/${encodeURIComponent(e)}/agents/${encodeURIComponent(t)}/import`,{method:"POST",body:n}),DA=()=>Ee("/api/version"),uC=(e=!1)=>Ee(`/api/version/update-check${e?"?force=1":""}`),$A=()=>Ee("/api/version/update",{method:"POST",body:{}}),UA=()=>Ee("/api/desktop/update"),PA=()=>Ee("/api/desktop/update/check",{method:"POST",body:{}}),zA=()=>Ee("/api/desktop/update/install",{method:"POST",body:{}}),BA={attachmentMaxMb:100,attachmentTotalMb:120,attachmentMaxCount:20,imageMaxMb:20,attachmentLimitMinMb:1,attachmentLimitMaxMb:200},dC=y.createContext(null);function HA({children:e}){const[t,n]=y.useState(void 0),[s,o]=y.useState(!0),[c,u]=y.useState(!1),[f,p]=y.useState("password"),[h,x]=y.useState(BA);y.useEffect(()=>(H1(()=>n(null)),()=>H1(null)),[]),y.useEffect(()=>{let S=!1;return qm().then(C=>{S||(n(C.user),o(C.previewIsolated),u(C.desktopMode),p(C.sessionVia),x(C.uploadLimits))}).catch(C=>{S||(C instanceof xr&&C.status,n(null))}),()=>{S=!0}},[]);const g=y.useCallback(async(S,C)=>{const N=await dE({userId:S,password:C});n(N.user);try{const T=await qm();n(T.user),o(T.previewIsolated),u(T.desktopMode),p(T.sessionVia),x(T.uploadLimits)}catch{}},[]),v=y.useCallback(async()=>{try{await mE()}finally{n(null)}},[]),w=y.useCallback(async()=>{const S=await qm();n(S.user),o(S.previewIsolated),u(S.desktopMode),p(S.sessionVia),x(S.uploadLimits)},[]);return a.jsx(dC.Provider,{value:{user:t,previewIsolated:s,desktopMode:c,sessionVia:f,uploadLimits:h,login:g,logout:v,refresh:w},children:e})}function mn(){const e=y.useContext(dC);if(!e)throw new Error("useAuth must be used within an AuthProvider");return e}const Cx=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,mC=/^[\\/]{2}/;function FA(e,t){return t+e.replace(/\\/g,"/")}const W1="popstate";function Y1(e){return typeof e=="object"&&e!=null&&"pathname"in e&&"search"in e&&"hash"in e&&"state"in e&&"key"in e}function qA(e={}){function t(s,o){let c=o.state?.masked,{pathname:u,search:f,hash:p}=c||s.location;return m0("",{pathname:u,search:f,hash:p},o.state&&o.state.usr||null,o.state&&o.state.key||"default",c?{pathname:s.location.pathname,search:s.location.search,hash:s.location.hash}:void 0)}function n(s,o){return typeof o=="string"?o:bu(o)}return GA(t,n,null,e)}function wn(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function Cs(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function VA(){return Math.random().toString(36).substring(2,10)}function X1(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function m0(e,t,n=null,s,o){return{pathname:typeof e=="string"?e:e.pathname,search:"",hash:"",...typeof t=="string"?Ul(t):t,state:n,key:t&&t.key||s||VA(),mask:o}}function bu({pathname:e="/",search:t="",hash:n=""}){return t&&t!=="?"&&(e+=t.charAt(0)==="?"?t:"?"+t),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function Ul(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let s=e.indexOf("?");s>=0&&(t.search=e.substring(s),e=e.substring(0,s)),e&&(t.pathname=e)}return t}function GA(e,t,n,s={}){let{window:o=document.defaultView,v5Compat:c=!1}=s,u=o.history,f="POP",p=null,h=x();h==null&&(h=0,u.replaceState({...u.state,idx:h},""));function x(){return(u.state||{idx:null}).idx}function g(){f="POP";let N=x(),T=N==null?null:N-h;h=N,p&&p({action:f,location:C.location,delta:T})}function v(N,T){f="PUSH";let _=Y1(N)?N:m0(C.location,N,T);h=x()+1;let R=X1(_,h),D=C.createHref(_.mask||_);try{u.pushState(R,"",D)}catch(z){if(z instanceof DOMException&&z.name==="DataCloneError")throw z;o.location.assign(D)}c&&p&&p({action:f,location:C.location,delta:1})}function w(N,T){f="REPLACE";let _=Y1(N)?N:m0(C.location,N,T);h=x();let R=X1(_,h),D=C.createHref(_.mask||_);u.replaceState(R,"",D),c&&p&&p({action:f,location:C.location,delta:0})}function S(N){return KA(o,N)}let C={get action(){return f},get location(){return e(o,u)},listen(N){if(p)throw new Error("A history only accepts one active listener");return o.addEventListener(W1,g),p=N,()=>{o.removeEventListener(W1,g),p=null}},createHref(N){return t(o,N)},createURL:S,encodeLocation(N){let T=S(N);return{pathname:T.pathname,search:T.search,hash:T.hash}},push:v,replace:w,go(N){return u.go(N)}};return C}function KA(e,t,n=!1){let s="http://localhost";e&&(s=e.location.origin!=="null"?e.location.origin:e.location.href),wn(s,"No window.location.(origin|href) available to create URL");let o=typeof t=="string"?t:bu(t);return o=o.replace(/ $/,"%20"),!n&&mC.test(o)&&(o=s+o),new URL(o,s)}function fC(e,t,n="/"){return WA(e,t,n,!1)}function WA(e,t,n,s,o){let c=Ri((typeof t=="string"?Ul(t):t).pathname||"/",n);if(c==null)return null;let u=YA(e),f=null,p=yC(c);for(let h=0;f==null&&h<u.length;++h)f=o_(u[h],p,s);return f}function YA(e){let t=pC(e);return XA(t),t}function pC(e,t=[],n=[],s="",o=!1){let c=(u,f,p=o,h)=>{let x={relativePath:h===void 0?u.path||"":h,caseSensitive:u.caseSensitive===!0,childrenIndex:f,route:u};if(x.relativePath.startsWith("/")){if(!x.relativePath.startsWith(s)&&p)return;wn(x.relativePath.startsWith(s),`Absolute route path "${x.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),x.relativePath=x.relativePath.slice(s.length)}let g=Za([s,x.relativePath]),v=n.concat(x);u.children&&u.children.length>0&&(wn(u.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${g}".`),pC(u.children,t,v,g,p)),!(u.path==null&&!u.index)&&t.push({path:g,score:s_(g,u.index),routesMeta:v.map((w,S)=>{let[C,N]=xC(w.relativePath,w.caseSensitive,S===v.length-1);return{...w,matcher:C,compiledParams:N}})})};return e.forEach((u,f)=>{if(u.path===""||!u.path?.includes("?"))c(u,f);else for(let p of hC(u.path))c(u,f,!0,p)}),t}function hC(e){let t=e.split("/");if(t.length===0)return[];let[n,...s]=t,o=n.endsWith("?"),c=n.replace(/\?$/,"");if(s.length===0)return o?[c,""]:[c];let u=hC(s.join("/")),f=[];return f.push(...u.map(p=>p===""?c:[c,p].join("/"))),o&&f.push(...u),f.map(p=>e.startsWith("/")&&p===""?"/":p)}function XA(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:i_(t.routesMeta.map(s=>s.childrenIndex),n.routesMeta.map(s=>s.childrenIndex)))}const QA=/^:[\w-]+$/,ZA=/^:[\w-]+/,JA=3.5,e_=3,t_=2,n_=1,r_=10,a_=-2,Q1=e=>e==="*";function s_(e,t){let n=e.split("/"),s=n.length;return n.some(Q1)&&(s+=a_),t&&(s+=t_),n.filter(o=>!Q1(o)).reduce((o,c)=>o+(QA.test(c)?e_:ZA.test(c)?JA:c===""?n_:r_),s)}function i_(e,t){return e.length===t.length&&e.slice(0,-1).every((n,s)=>n===t[s])?e[e.length-1]-t[t.length-1]:0}function o_(e,t,n=!1){let{routesMeta:s}=e,o={},c="/",u=[];for(let f=0;f<s.length;++f){let p=s[f],h=f===s.length-1,x=c==="/"?t:t.slice(c.length)||"/",g={path:p.relativePath,caseSensitive:p.caseSensitive,end:h},v=p.matcher&&p.compiledParams?gC(g,x,p.matcher,p.compiledParams):vu(g,x),w=p.route;if(!v&&h&&n&&!s[s.length-1].route.index&&(v=vu({path:p.relativePath,caseSensitive:p.caseSensitive,end:!1},x)),!v)return null;Object.assign(o,v.params),u.push({params:o,pathname:Za([c,v.pathname]),pathnameBase:u_(Za([c,v.pathnameBase])),route:w}),v.pathnameBase!=="/"&&(c=Za([c,v.pathnameBase]))}return u}function vu(e,t){typeof e=="string"&&(e={path:e,caseSensitive:!1,end:!0});let[n,s]=xC(e.path,e.caseSensitive,e.end);return gC(e,t,n,s)}function gC(e,t,n,s){let o=t.match(n);if(!o)return null;let c=o[0],u=c.replace(/(.)\/+$/,"$1"),f=o.slice(1);return{params:s.reduce((p,{paramName:h,isOptional:x},g)=>{if(h==="*"){let w=f[g]||"";u=c.slice(0,c.length-w.length).replace(/(.)\/+$/,"$1")}const v=f[g];return x&&!v?p[h]=void 0:p[h]=(v||"").replace(/%2F/g,"/"),p},{}),pathname:c,pathnameBase:u,pattern:e}}function xC(e,t=!1,n=!0){Cs(e==="*"||!e.endsWith("*")||e.endsWith("/*"),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,"/*")}".`);let s=[],o="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,u,f,p,h)=>{if(s.push({paramName:u,isOptional:f!=null}),f){let x=h.charAt(p+c.length);return x&&x!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(?=\/|$|\()/g,"(?:/$1)?");return e.endsWith("*")?(s.push({paramName:"*"}),o+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?o+="\\/*$":e!==""&&e!=="/"&&(o+="(?:(?=\\/|$))"),[new RegExp(o,t?void 0:"i"),s]}function yC(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Cs(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Ri(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,s=e.charAt(n);return s&&s!=="/"?null:e.slice(n)||"/"}function l_(e,t="/"){let{pathname:n,search:s="",hash:o=""}=typeof e=="string"?Ul(e):e,c;return n?(n=bC(n),n.startsWith("/")?c=Z1(n.substring(1),"/"):c=Z1(n,t)):c=t,{pathname:c,search:d_(s),hash:m_(o)}}function Z1(e,t){let n=vC(t).split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function fg(e,t,n,s){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function c_(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function Nx(e){let t=c_(e);return t.map((n,s)=>s===t.length-1?n.pathname:n.pathnameBase)}function Mf(e,t,n,s=!1){let o;typeof e=="string"?o=Ul(e):(o={...e},wn(!o.pathname||!o.pathname.includes("?"),fg("?","pathname","search",o)),wn(!o.pathname||!o.pathname.includes("#"),fg("#","pathname","hash",o)),wn(!o.search||!o.search.includes("#"),fg("#","search","hash",o)));let c=e===""||o.pathname==="",u=c?"/":o.pathname,f;if(u==null)f=n;else{let g=t.length-1;if(!s&&u.startsWith("..")){let v=u.split("/");for(;v[0]==="..";)v.shift(),g-=1;o.pathname=v.join("/")}f=g>=0?t[g]:"/"}let p=l_(o,f),h=u&&u!=="/"&&u.endsWith("/"),x=(c||u===".")&&n.endsWith("/");return!p.pathname.endsWith("/")&&(h||x)&&(p.pathname+="/"),p}const bC=e=>e.replace(/[\\/]{2,}/g,"/"),Za=e=>bC(e.join("/")),vC=e=>e.replace(/\/+$/,""),u_=e=>vC(e).replace(/^\/*/,"/"),d_=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,m_=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;var f_=class{status;statusText;data;error;internal;constructor(e,t,n,s=!1){this.status=e,this.statusText=t||"",this.internal=s,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function p_(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}function h_(e){return Za(e.map(t=>t.route.path).filter(Boolean))||"/"}const kC=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function wC(e,t){let n=e;if(typeof n!="string"||!Cx.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let s=n,o=!1;if(kC)try{let c=new URL(window.location.href),u=mC.test(n)?new URL(FA(n,c.protocol)):new URL(n),f=Ri(u.pathname,t);u.origin===c.origin&&f!=null?n=f+u.search+u.hash:o=!0}catch{Cs(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:s,isExternal:o,to:n}}const SC=["POST","PUT","PATCH","DELETE"];new Set(SC);const g_=["GET",...SC];new Set(g_);const x_=["about:","blob:","chrome:","chrome-untrusted:","content:","data:","devtools:","file:","filesystem:","javascript:"];function y_(e){try{return x_.includes(new URL(e).protocol)}catch{return!1}}const Pl=y.createContext(null);Pl.displayName="DataRouter";const Ef=y.createContext(null);Ef.displayName="DataRouterState";const jC=y.createContext(!1);function b_(){return y.useContext(jC)}const CC=y.createContext({isTransitioning:!1});CC.displayName="ViewTransition";const v_=y.createContext(new Map);v_.displayName="Fetchers";const k_=y.createContext(null);k_.displayName="Await";const qa=y.createContext(null);qa.displayName="Navigation";const Hu=y.createContext(null);Hu.displayName="Location";const Va=y.createContext({outlet:null,matches:[],isDataRoute:!1});Va.displayName="Route";const Tx=y.createContext(null);Tx.displayName="RouteError";const NC="REACT_ROUTER_ERROR",w_="REDIRECT",S_="ROUTE_ERROR_RESPONSE";function j_(e){if(e.startsWith(`${NC}:${w_}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.location=="string"&&typeof t.reloadDocument=="boolean"&&typeof t.replace=="boolean")return t}catch{}}function C_(e){if(e.startsWith(`${NC}:${S_}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t=="object"&&t&&typeof t.status=="number"&&typeof t.statusText=="string")return new f_(t.status,t.statusText,t.data)}catch{}}function N_(e,{relative:t}={}){wn(_o(),"useHref() may be used only in the context of a <Router> component.");let{basename:n,navigator:s}=y.useContext(qa),{hash:o,pathname:c,search:u}=Fu(e,{relative:t}),f=c;return n!=="/"&&(f=c==="/"?n:Za([n,c])),s.createHref({pathname:f,search:u,hash:o})}function _o(){return y.useContext(Hu)!=null}function $r(){return wn(_o(),"useLocation() may be used only in the context of a <Router> component."),y.useContext(Hu).location}function Mx(e){wn(_o(),"useMatch() may be used only in the context of a <Router> component.");let{pathname:t}=$r();return y.useMemo(()=>vu(e,yC(t)),[t,e])}const TC="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function yr(){let{isDataRoute:e}=y.useContext(Va);return e?H_():T_()}function T_(){wn(_o(),"useNavigate() may be used only in the context of a <Router> component.");let e=y.useContext(Pl),{basename:t,navigator:n}=y.useContext(qa),{matches:s}=y.useContext(Va),{pathname:o}=$r(),c=JSON.stringify(Nx(s)),u=y.useRef(!1);return y.useLayoutEffect(()=>{u.current=!0}),y.useCallback((f,p={})=>{if(Cs(u.current,TC),!u.current)return;if(typeof f=="number"){n.go(f);return}let h=Mf(f,JSON.parse(c),o,p.relative==="path");e==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:Za([t,h.pathname])),(p.replace?n.replace:n.push)(h,p.state,p)},[t,n,c,o,e])}const M_=y.createContext(null);function E_(e){let t=y.useContext(Va).outlet;return y.useMemo(()=>t&&y.createElement(M_.Provider,{value:e},t),[t,e])}function MC(){let{matches:e}=y.useContext(Va);return e[e.length-1]?.params??{}}function Fu(e,{relative:t}={}){let{matches:n}=y.useContext(Va),{pathname:s}=$r(),o=JSON.stringify(Nx(n));return y.useMemo(()=>Mf(e,JSON.parse(o),s,t==="path"),[e,o,s,t])}function A_(e,t){return EC(e,t)}function EC(e,t,n){wn(_o(),"useRoutes() may be used only in the context of a <Router> component.");let{navigator:s}=y.useContext(qa),{matches:o}=y.useContext(Va),c=o[o.length-1],u=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let p=$r(),h;if(t){let S=typeof t=="string"?Ul(t):t;wn(f==="/"||S.pathname?.startsWith(f),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${f}" but pathname "${S.pathname}" was given in the \`location\` prop.`),h=S}else h=p;let x=h.pathname||"/",g=x;if(f!=="/"){let S=f.replace(/^\//,"").split("/");g="/"+x.replace(/^\//,"").split("/").slice(S.length).join("/")}let v=n&&n.state.matches.length?n.state.matches.map(S=>Object.assign(S,{route:n.manifest[S.route.id]||S.route})):fC(e,{pathname:g}),w=D_(v&&v.map(S=>Object.assign({},S,{params:Object.assign({},u,S.params),pathname:Za([f,s.encodeLocation?s.encodeLocation(S.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathname]),pathnameBase:S.pathnameBase==="/"?f:Za([f,s.encodeLocation?s.encodeLocation(S.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:S.pathnameBase])})),o,n);return t&&w?y.createElement(Hu.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",mask:void 0,...h},navigationType:"POP"}},w):w}function __(){let e=B_(),t=p_(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return y.createElement(y.Fragment,null,y.createElement("h2",null,"Unexpected Application Error!"),y.createElement("h3",{style:{fontStyle:"italic"}},t),n?y.createElement("pre",{style:{padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"}},n):null,null)}const R_=y.createElement(__,null);var I_=class extends y.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=jC;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:t.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error("React Router caught the following error during render",e)}render(){let e=this.state.error;if(this.context&&typeof e=="object"&&e&&"digest"in e&&typeof e.digest=="string"){const n=C_(e.digest);n&&(e=n)}let t=e!==void 0?y.createElement(Va.Provider,{value:this.props.routeContext},y.createElement(Tx.Provider,{value:e,children:this.props.component})):this.props.children;return this.context?y.createElement(L_,{error:e},t):t}};const pg=new WeakMap;function L_({children:e,error:t}){let{basename:n}=y.useContext(qa);if(typeof t=="object"&&t&&"digest"in t&&typeof t.digest=="string"){let s=j_(t.digest);if(s){let o=pg.get(t);if(o)throw o;let c=wC(s.location,n),u=c.absoluteURL||c.to;if(y_(u))throw new Error("Invalid redirect location");if(kC&&!pg.get(t))if(c.isExternal||s.reloadDocument)window.location.href=u;else{const f=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(c.to,{replace:s.replace}));throw pg.set(t,f),f}return y.createElement("meta",{httpEquiv:"refresh",content:`0;url=${u}`})}}return e}function O_({routeContext:e,match:t,children:n}){let s=y.useContext(Pl);return s&&s.static&&s.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=t.route.id),y.createElement(Va.Provider,{value:e},n)}function D_(e,t=[],n){let s=n?.state;if(e==null){if(!s)return null;if(s.errors)e=s.matches;else if(t.length===0&&!s.initialized&&s.matches.length>0)e=s.matches;else return null}let o=e,c=s?.errors;if(c!=null){let x=o.findIndex(g=>g.route.id&&c?.[g.route.id]!==void 0);wn(x>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(c).join(",")}`),o=o.slice(0,Math.min(o.length,x+1))}let u=!1,f=-1;if(n&&s){u=s.renderFallback;for(let x=0;x<o.length;x++){let g=o[x];if((g.route.HydrateFallback||g.route.hydrateFallbackElement)&&(f=x),g.route.id){let{loaderData:v,errors:w}=s,S=g.route.loader&&!v.hasOwnProperty(g.route.id)&&(!w||w[g.route.id]===void 0);if(g.route.lazy||S){n.isStatic&&(u=!0),f>=0?o=o.slice(0,f+1):o=[o[0]];break}}}}let p=n?.onError,h=s&&p?(x,g)=>{p(x,{location:s.location,params:s.matches?.[0]?.params??{},pattern:h_(s.matches),errorInfo:g})}:void 0;return o.reduceRight((x,g,v)=>{let w,S=!1,C=null,N=null;s&&(w=c&&g.route.id?c[g.route.id]:void 0,C=g.route.errorElement||R_,u&&(f<0&&v===0?(F_("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),S=!0,N=null):f===v&&(S=!0,N=g.route.hydrateFallbackElement||null)));let T=t.concat(o.slice(0,v+1)),_=()=>{let R;return w?R=C:S?R=N:g.route.Component?R=y.createElement(g.route.Component,null):g.route.element?R=g.route.element:R=x,y.createElement(O_,{match:g,routeContext:{outlet:x,matches:T,isDataRoute:s!=null},children:R})};return s&&(g.route.ErrorBoundary||g.route.errorElement||v===0)?y.createElement(I_,{location:s.location,revalidation:s.revalidation,component:C,error:w,children:_(),routeContext:{outlet:null,matches:T,isDataRoute:!0},onError:h}):_()},null)}function Ex(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function $_(e){let t=y.useContext(Pl);return wn(t,Ex(e)),t}function U_(e){let t=y.useContext(Ef);return wn(t,Ex(e)),t}function P_(e){let t=y.useContext(Va);return wn(t,Ex(e)),t}function Ax(e){let t=P_(e),n=t.matches[t.matches.length-1];return wn(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function z_(){return Ax("useRouteId")}function B_(){let e=y.useContext(Tx),t=U_("useRouteError"),n=Ax("useRouteError");return e!==void 0?e:t.errors?.[n]}function H_(){let{router:e}=$_("useNavigate"),t=Ax("useNavigate"),n=y.useRef(!1);return y.useLayoutEffect(()=>{n.current=!0}),y.useCallback(async(s,o={})=>{Cs(n.current,TC),n.current&&(typeof s=="number"?await e.navigate(s):await e.navigate(s,{fromRouteId:t,...o}))},[e,t])}const J1={};function F_(e,t,n){J1[e]||(J1[e]=!0,Cs(!1,n))}y.memo(q_);function q_({routes:e,manifest:t,future:n,state:s,isStatic:o,onError:c}){return EC(e,void 0,{manifest:t,state:s,isStatic:o,onError:c})}function ku({to:e,replace:t,state:n,relative:s}){wn(_o(),"<Navigate> may be used only in the context of a <Router> component.");let{static:o}=y.useContext(qa);Cs(!o,"<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.");let{matches:c}=y.useContext(Va),{pathname:u}=$r(),f=yr(),p=Mf(e,Nx(c),u,s==="path"),h=JSON.stringify(p);return y.useEffect(()=>{f(JSON.parse(h),{replace:t,state:n,relative:s})},[f,h,s,t,n]),null}function V_(e){return E_(e.context)}function da(e){wn(!1,"A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.")}function G_({basename:e="/",children:t=null,location:n,navigationType:s="POP",navigator:o,static:c=!1,useTransitions:u}){wn(!_o(),"You cannot render a <Router> inside another <Router>. You should never have more than one in your app.");let f=e.replace(/^\/*/,"/"),p=y.useMemo(()=>({basename:f,navigator:o,static:c,useTransitions:u,future:{}}),[f,o,c,u]);typeof n=="string"&&(n=Ul(n));let{pathname:h="/",search:x="",hash:g="",state:v=null,key:w="default",mask:S}=n,C=y.useMemo(()=>{let N=Ri(h,f);return N==null?null:{location:{pathname:N,search:x,hash:g,state:v,key:w,mask:S},navigationType:s}},[f,h,x,g,v,w,s,S]);return Cs(C!=null,`<Router basename="${f}"> is not able to match the URL "${h}${x}${g}" because it does not start with the basename, so the <Router> won't render anything.`),C==null?null:y.createElement(qa.Provider,{value:p},y.createElement(Hu.Provider,{children:t,value:C}))}function K_({children:e,location:t}){return A_(f0(e),t)}function f0(e,t=[]){let n=[];return y.Children.forEach(e,(s,o)=>{if(!y.isValidElement(s))return;let c=[...t,o];if(s.type===y.Fragment){n.push.apply(n,f0(s.props.children,c));return}wn(s.type===da,`[${typeof s.type=="string"?s.type:s.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`);let u=s.props;wn(!u.index||!u.children,"An index route cannot have child routes.");let f={id:u.id||c.join("-"),caseSensitive:u.caseSensitive,element:u.element,Component:u.Component,index:u.index,path:u.path,middleware:u.middleware,loader:u.loader,action:u.action,hydrateFallbackElement:u.hydrateFallbackElement,HydrateFallback:u.HydrateFallback,errorElement:u.errorElement,ErrorBoundary:u.ErrorBoundary,shouldRevalidate:u.shouldRevalidate,handle:u.handle,lazy:u.lazy};u.children&&(f.children=f0(u.children,c)),n.push(f)}),n}const Vm="application/x-www-form-urlencoded";function Af(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement}function W_(e){return Af(e)&&e.tagName.toLowerCase()==="button"}function Y_(e){return Af(e)&&e.tagName.toLowerCase()==="form"}function X_(e){return Af(e)&&e.tagName.toLowerCase()==="input"}function Q_(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Z_(e,t){return e.button===0&&(!t||t==="_self")&&!Q_(e)}function p0(e=""){return new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let s=e[n];return t.concat(Array.isArray(s)?s.map(o=>[n,o]):[[n,s]])},[]))}function J_(e,t){let n=p0(e);return t&&t.forEach((s,o)=>{n.has(o)||t.getAll(o).forEach(c=>{n.append(o,c)})}),n}let gm=null;function eR(){if(gm===null)try{new FormData(document.createElement("form"),0),gm=!1}catch{gm=!0}return gm}const tR=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function hg(e){return e!=null&&!tR.has(e)?(Cs(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${Vm}"`),null):e}function nR(e,t){let n,s,o,c,u;if(Y_(e)){let f=e.getAttribute("action");s=f?Ri(f,t):null,n=e.getAttribute("method")||"get",o=hg(e.getAttribute("enctype"))||Vm,c=new FormData(e)}else if(W_(e)||X_(e)&&(e.type==="submit"||e.type==="image")){let f=e.form;if(f==null)throw new Error('Cannot submit a <button> or <input type="submit"> without a <form>');let p=e.getAttribute("formaction")||f.getAttribute("action");if(s=p?Ri(p,t):null,n=e.getAttribute("formmethod")||f.getAttribute("method")||"get",o=hg(e.getAttribute("formenctype"))||hg(f.getAttribute("enctype"))||Vm,c=new FormData(f,e),!eR()){let{name:h,type:x,value:g}=e;if(x==="image"){let v=h?`${h}.`:"";c.append(`${v}x`,"0"),c.append(`${v}y`,"0")}else h&&c.append(h,g)}}else{if(Af(e))throw new Error('Cannot submit element that is not <form>, <button>, or <input type="submit|image">');n="get",s=null,o=Vm,u=e}return c&&o==="text/plain"&&(u=c,c=void 0),{action:s,method:n.toLowerCase(),encType:o,formData:c,body:u}}function _x(e,t){if(e===!1||e===null||typeof e>"u")throw new Error(t)}function AC(e,t){let n=typeof e=="string"?new URL(e,typeof window>"u"?"server://singlefetch/":window.location.origin):e;return n.pathname.endsWith("/")?n.pathname=`${n.pathname}_.${t}`:n.pathname=`${n.pathname}.${t}`,n}async function rR(e,t){if(e.id in t)return t[e.id];try{let n=await import(e.module);return t[e.id]=n,n}catch(n){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(n),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function aR(e){return e==null?!1:e.href==null?e.rel==="preload"&&typeof e.imageSrcSet=="string"&&typeof e.imageSizes=="string":typeof e.rel=="string"&&typeof e.href=="string"}async function sR(e,t,n){return cR((await Promise.all(e.map(async s=>{let o=t.routes[s.route.id];if(o){let c=await rR(o,n);return c.links?c.links():[]}return[]}))).flat(1).filter(aR).filter(s=>s.rel==="stylesheet"||s.rel==="preload").map(s=>s.rel==="stylesheet"?{...s,rel:"prefetch",as:"style"}:{...s,rel:"prefetch"}))}function ew(e,t,n,s,o,c){let u=(p,h)=>n[h]?p.route.id!==n[h].route.id:!0,f=(p,h)=>n[h].pathname!==p.pathname||n[h].route.path?.endsWith("*")&&n[h].params["*"]!==p.params["*"];return c==="assets"?t.filter((p,h)=>u(p,h)||f(p,h)):c==="data"?t.filter((p,h)=>{let x=s.routes[p.route.id];if(!x||!x.hasLoader)return!1;if(u(p,h)||f(p,h))return!0;if(p.route.shouldRevalidate){let g=p.route.shouldRevalidate({currentUrl:new URL(o.pathname+o.search+o.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:p.params,defaultShouldRevalidate:!0});if(typeof g=="boolean")return g}return!0}):[]}function iR(e,t,{includeHydrateFallback:n}={}){return oR(e.map(s=>{let o=t.routes[s.route.id];if(!o)return[];let c=[o.module];return o.clientActionModule&&(c=c.concat(o.clientActionModule)),o.clientLoaderModule&&(c=c.concat(o.clientLoaderModule)),n&&o.hydrateFallbackModule&&(c=c.concat(o.hydrateFallbackModule)),o.imports&&(c=c.concat(o.imports)),c}).flat(1))}function oR(e){return[...new Set(e)]}function lR(e){let t={},n=Object.keys(e).sort();for(let s of n)t[s]=e[s];return t}function cR(e,t){let n=new Set;return new Set(t),e.reduce((s,o)=>{let c=JSON.stringify(lR(o));return n.has(c)||(n.add(c),s.push({key:c,link:o})),s},[])}function uR(){let e=y.useContext(Pl);return _x(e,"You must render this element inside a <DataRouterContext.Provider> element"),e}function dR(){let e=y.useContext(Ef);return _x(e,"You must render this element inside a <DataRouterStateContext.Provider> element"),e}const Rx=y.createContext(void 0);Rx.displayName="FrameworkContext";function Ix(){let e=y.useContext(Rx);return _x(e,"You must render this element inside a <HydratedRouter> element"),e}function mR(e,t){let n=y.useContext(Rx),[s,o]=y.useState(!1),[c,u]=y.useState(!1),{onFocus:f,onBlur:p,onMouseEnter:h,onMouseLeave:x,onTouchStart:g}=t,v=y.useRef(null);y.useEffect(()=>{if(e==="render"&&u(!0),e==="viewport"){let C=T=>{T.forEach(_=>{u(_.isIntersecting)})},N=new IntersectionObserver(C,{threshold:.5});return v.current&&N.observe(v.current),()=>{N.disconnect()}}},[e]),y.useEffect(()=>{if(s){let C=setTimeout(()=>{u(!0)},100);return()=>{clearTimeout(C)}}},[s]);let w=()=>{o(!0)},S=()=>{o(!1),u(!1)};return n?e!=="intent"?[c,v,{}]:[c,v,{onFocus:Pc(f,w),onBlur:Pc(p,S),onMouseEnter:Pc(h,w),onMouseLeave:Pc(x,S),onTouchStart:Pc(g,w)}]:[!1,v,{}]}function Pc(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function fR({page:e,...t}){let n=b_(),{nonce:s}=Ix(),{router:o}=uR(),c=y.useMemo(()=>fC(o.routes,e,o.basename),[o.routes,e,o.basename]);return c?(t.nonce==null&&s&&(t={...t,nonce:s}),n?y.createElement(hR,{page:e,matches:c,...t}):y.createElement(gR,{page:e,matches:c,...t})):null}function pR(e){let{manifest:t,routeModules:n}=Ix(),[s,o]=y.useState([]);return y.useEffect(()=>{let c=!1;return sR(e,t,n).then(u=>{c||o(u)}),()=>{c=!0}},[e,t,n]),s}function hR({page:e,matches:t,...n}){let s=$r(),o=y.useMemo(()=>{if(e===s.pathname+s.search+s.hash)return[];let c=AC(e,"rsc"),u=!1,f=[];for(let p of t)typeof p.route.shouldRevalidate=="function"?u=!0:f.push(p.route.id);return u&&f.length>0&&c.searchParams.set("_routes",f.join(",")),[c.pathname+c.search]},[e,s,t]);return y.createElement(y.Fragment,null,o.map(c=>y.createElement("link",{key:c,rel:"prefetch",as:"fetch",href:c,...n})))}function gR({page:e,matches:t,...n}){let s=$r(),{manifest:o,routeModules:c}=Ix(),{loaderData:u,matches:f}=dR(),p=y.useMemo(()=>ew(e,t,f,o,s,"data"),[e,t,f,o,s]),h=y.useMemo(()=>ew(e,t,f,o,s,"assets"),[e,t,f,o,s]),x=y.useMemo(()=>{if(e===s.pathname+s.search+s.hash)return[];let w=new Set,S=!1;if(t.forEach(N=>{let T=o.routes[N.route.id];!T||!T.hasLoader||(!p.some(_=>_.route.id===N.route.id)&&N.route.id in u&&c[N.route.id]?.shouldRevalidate||T.hasClientLoader?S=!0:w.add(N.route.id))}),w.size===0)return[];let C=AC(e,"data");return S&&w.size>0&&C.searchParams.set("_routes",t.filter(N=>w.has(N.route.id)).map(N=>N.route.id).join(",")),[C.pathname+C.search]},[u,s,o,p,t,e,c]),g=y.useMemo(()=>iR(h,o),[h,o]),v=pR(h);return y.createElement(y.Fragment,null,x.map(w=>y.createElement("link",{key:w,rel:"prefetch",as:"fetch",href:w,...n})),g.map(w=>y.createElement("link",{key:w,rel:"modulepreload",href:w,...n})),v.map(({key:w,link:S})=>y.createElement("link",{key:w,nonce:n.nonce,...S,crossOrigin:S.crossOrigin??n.crossOrigin})))}function xR(...e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}const yR=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";try{yR&&(window.__reactRouterVersion="8.3.0")}catch{}function bR({basename:e,children:t,useTransitions:n,window:s}){let o=y.useRef(null);o.current==null&&(o.current=qA({window:s,v5Compat:!0}));let c=o.current,[u,f]=y.useState({action:c.action,location:c.location}),p=y.useCallback(h=>{n===!1?f(h):y.startTransition(()=>f(h))},[n]);return y.useLayoutEffect(()=>c.listen(p),[c,p]),y.createElement(G_,{basename:e,children:t,location:u.location,navigationType:u.action,navigator:c,useTransitions:n})}const _C=y.forwardRef(function({onClick:t,discover:n="render",prefetch:s="none",relative:o,reloadDocument:c,replace:u,mask:f,state:p,target:h,to:x,preventScrollReset:g,viewTransition:v,defaultShouldRevalidate:w,...S},C){let{basename:N,navigator:T,useTransitions:_}=y.useContext(qa),R=typeof x=="string"&&Cx.test(x),D=wC(x,N);x=D.to;let z=N_(x,{relative:o}),E=$r(),L=null;if(f){let H=Mf(f,[],E.mask?E.mask.pathname:"/",!0);N!=="/"&&(H.pathname=H.pathname==="/"?N:Za([N,H.pathname])),L=T.createHref(H)}let[F,V,P]=mR(s,S),B=wR(x,{replace:u,mask:f,state:p,target:h,preventScrollReset:g,relative:o,viewTransition:v,defaultShouldRevalidate:w,useTransitions:_});function Y(H){t&&t(H),H.defaultPrevented||B(H)}let q=!(D.isExternal||c),K=y.createElement("a",{...S,...P,href:(q?L:void 0)||D.absoluteURL||z,onClick:q?Y:t,ref:xR(C,V),target:h,"data-discover":!R&&n==="render"?"true":void 0});return F&&!R?y.createElement(y.Fragment,null,K,y.createElement(fR,{page:z})):K});_C.displayName="Link";const Lx=y.forwardRef(function({"aria-current":t="page",caseSensitive:n=!1,className:s="",end:o=!1,style:c,to:u,viewTransition:f,children:p,...h},x){let g=Fu(u,{relative:h.relative}),v=$r(),w=y.useContext(Ef),{navigator:S,basename:C}=y.useContext(qa),N=w!=null&&TR(g)&&f===!0,T=S.encodeLocation?S.encodeLocation(g).pathname:g.pathname,_=v.pathname,R=w&&w.navigation&&w.navigation.location?w.navigation.location.pathname:null;n||(_=_.toLowerCase(),R=R?R.toLowerCase():null,T=T.toLowerCase()),R&&C&&(R=Ri(R,C)||R);const D=T!=="/"&&T.endsWith("/")?T.length-1:T.length;let z=_===T||!o&&_.startsWith(T)&&_.charAt(D)==="/",E=R!=null&&(R===T||!o&&R.startsWith(T)&&R.charAt(D)==="/"),L={isActive:z,isPending:E,isTransitioning:N},F=z?t:void 0,V;typeof s=="function"?V=s(L):V=[s,z?"active":null,E?"pending":null,N?"transitioning":null].filter(Boolean).join(" ");let P=typeof c=="function"?c(L):c;return y.createElement(_C,{...h,"aria-current":F,className:V,ref:x,style:P,to:u,viewTransition:f},typeof p=="function"?p(L):p)});Lx.displayName="NavLink";const vR=y.forwardRef(({discover:e="render",fetcherKey:t,navigate:n,reloadDocument:s,replace:o,state:c,method:u="get",action:f,onSubmit:p,relative:h,preventScrollReset:x,viewTransition:g,defaultShouldRevalidate:v,...w},S)=>{let{useTransitions:C}=y.useContext(qa),N=CR(),T=NR(f,{relative:h}),_=u.toLowerCase()==="get"?"get":"post",R=typeof f=="string"&&Cx.test(f),D=z=>{if(p&&p(z),z.defaultPrevented)return;z.preventDefault();let E=z.nativeEvent.submitter,L=E?.getAttribute("formmethod")||u,F=()=>N(E||z.currentTarget,{fetcherKey:t,method:L,navigate:n,replace:o,state:c,relative:h,preventScrollReset:x,viewTransition:g,defaultShouldRevalidate:v});C&&n!==!1?y.startTransition(()=>F()):F()};return y.createElement("form",{ref:S,method:_,action:T,onSubmit:s?p:D,...w,"data-discover":!R&&e==="render"?"true":void 0})});vR.displayName="Form";function kR(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function RC(e){let t=y.useContext(Pl);return wn(t,kR(e)),t}function wR(e,{target:t,replace:n,mask:s,state:o,preventScrollReset:c,relative:u,viewTransition:f,defaultShouldRevalidate:p,useTransitions:h}={}){let x=yr(),g=$r(),v=Fu(e,{relative:u});return y.useCallback(w=>{if(Z_(w,t)){w.preventDefault();let S=n!==void 0?n:bu(g)===bu(v),C=()=>x(e,{replace:S,mask:s,state:o,preventScrollReset:c,relative:u,viewTransition:f,defaultShouldRevalidate:p});h?y.startTransition(()=>C()):C()}},[g,x,v,n,s,o,t,e,c,u,f,p,h])}function Ox(e){Cs(typeof URLSearchParams<"u","You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=y.useRef(p0(e)),n=y.useRef(!1),s=$r(),o=y.useMemo(()=>J_(s.search,n.current?null:t.current),[s.search]),c=yr();return[o,y.useCallback((u,f)=>{const p=p0(typeof u=="function"?u(new URLSearchParams(o)):u);n.current=!0,c("?"+p,f)},[c,o])]}let SR=0,jR=()=>`__${String(++SR)}__`;function CR(){let{router:e}=RC("useSubmit"),{basename:t}=y.useContext(qa),n=z_(),s=e.fetch,o=e.navigate;return y.useCallback(async(c,u={})=>{let{action:f,method:p,encType:h,formData:x,body:g}=nR(c,t);u.navigate===!1?await s(u.fetcherKey||jR(),n,u.action||f,{defaultShouldRevalidate:u.defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:x,body:g,formMethod:u.method||p,formEncType:u.encType||h,flushSync:u.flushSync}):await o(u.action||f,{defaultShouldRevalidate:u.defaultShouldRevalidate,preventScrollReset:u.preventScrollReset,formData:x,body:g,formMethod:u.method||p,formEncType:u.encType||h,replace:u.replace,state:u.state,fromRouteId:n,flushSync:u.flushSync,viewTransition:u.viewTransition})},[s,o,t,n])}function NR(e,{relative:t}={}){let{basename:n}=y.useContext(qa),s=y.useContext(Va);wn(s,"useFormAction must be used inside a RouteContext");let[o]=s.matches.slice(-1),c={...Fu(e||".",{relative:t})},u=$r();if(e==null){c.search=u.search;let f=new URLSearchParams(c.search),p=f.getAll("index");if(p.some(h=>h==="")){f.delete("index"),p.filter(x=>x).forEach(x=>f.append("index",x));let h=f.toString();c.search=h?`?${h}`:""}}return(!e||e===".")&&o.route.index&&(c.search=c.search?c.search.replace(/^\?/,"?index&"):"?index"),n!=="/"&&(c.pathname=c.pathname==="/"?n:Za([n,c.pathname])),bu(c)}function TR(e,{relative:t}={}){let n=y.useContext(CC);wn(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:s}=RC("useViewTransitionState"),o=Fu(e,{relative:t});if(!n.isTransitioning)return!1;let c=Ri(n.currentLocation.pathname,s)||n.currentLocation.pathname,u=Ri(n.nextLocation.pathname,s)||n.nextLocation.pathname;return vu(o.pathname,u)!=null||vu(o.pathname,c)!=null}const tw=e=>{let t;const n=new Set,s=(h,x)=>{const g=typeof h=="function"?h(t):h;if(!Object.is(g,t)){const v=t;t=x??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(w=>w(t,v))}},o=()=>t,f={setState:s,getState:o,getInitialState:()=>p,subscribe:h=>(n.add(h),()=>n.delete(h))},p=t=e(s,o,f);return f},zl=(e=>e?tw(e):tw),MR=e=>e;function Bl(e,t=MR){const n=hm.useSyncExternalStore(e.subscribe,hm.useCallback(()=>t(e.getState()),[e,t]),hm.useCallback(()=>t(e.getInitialState()),[e,t]));return hm.useDebugValue(n),n}const nw="penguin.lastProjectId",rw=e=>`penguin.lastAgentId.${e}`,IC=y.createContext(null);function wu(e){return e.name??e.projectId}function _n(e){return e.name??e.agentId}function ER(){return zl((e,t)=>({projects:[],projectsLoading:!0,currentProjectId:null,agents:[],agentsLoading:!0,currentAgentId:null,reloadProjects:async()=>{e({projectsLoading:!0});try{const n=await yE(),s=t().currentProjectId??localStorage.getItem(nw),o=n.projects.find(c=>c.projectId===s);e({projects:n.projects,currentProjectId:(o??n.projects[0])?.projectId??null})}finally{e({projectsLoading:!1})}},setCurrentProjectId:n=>{n!==t().currentProjectId&&(localStorage.setItem(nw,n),e({currentProjectId:n,currentAgentId:null,agents:[],agentsLoading:!0}),Nf({lastProjectId:n}).catch(()=>{}))},reloadAgents:async()=>{const n=t().currentProjectId;if(n){e({agentsLoading:!0});try{const s=await aC(n),o=t().currentAgentId??localStorage.getItem(rw(n)),c=s.agents.find(f=>f.agentId===o),u=s.agents.find(f=>f.agentId==="default_agent")??s.agents[0]??null;e({agents:s.agents,currentAgentId:(c??u)?.agentId??null})}finally{e({agentsLoading:!1})}}},setCurrentAgentId:n=>{const s=t().currentProjectId;s&&localStorage.setItem(rw(s),n),e({currentAgentId:n})}}))}function AR({children:e}){const[t]=y.useState(ER),n=Bl(t);y.useEffect(()=>{t.getState().reloadProjects()},[t]);const{currentProjectId:s}=n;y.useEffect(()=>{t.setState({agents:[]}),t.getState().reloadAgents()},[t,s]);const o=y.useMemo(()=>{const c=n.projects.find(f=>f.projectId===n.currentProjectId)??null,u=n.agents.find(f=>f.agentId===n.currentAgentId)??null;return{projects:n.projects,projectsLoading:n.projectsLoading,currentProject:c,setCurrentProjectId:n.setCurrentProjectId,reloadProjects:n.reloadProjects,agents:n.agents,agentsLoading:n.agentsLoading,currentAgent:u,setCurrentAgentId:n.setCurrentAgentId,reloadAgents:n.reloadAgents}},[n]);return a.jsx(IC.Provider,{value:o,children:e})}function en(){const e=y.useContext(IC);if(!e)throw new Error("useProject must be used within a ProjectProvider");return e}function LC(e,t){const n=new EventSource(e);n.onmessage=o=>{try{t.onOmniMessage(JSON.parse(o.data),o.lastEventId||null)}catch{}},n.addEventListener("server_event",o=>{try{t.onServerEvent(JSON.parse(o.data),o.lastEventId||null)}catch{}}),t.onOpen&&(n.onopen=t.onOpen);const{onError:s}=t;return s&&(n.onerror=()=>s(n.readyState===EventSource.CLOSED)),{close:()=>n.close()}}function _R(e,t){return LC(`/api/sessions/${encodeURIComponent(e)}/stream`,t)}function RR(e){return LC("/api/events",e)}const Dx="\0temp-workspaces",IR=/[/\\]workspaces[/\\]tmp-[0-9a-f]{8}$/;function OC(e){const t=e.trim();return t===""||IR.test(t)}function vo(e){return OC(e)?Dx:e.trim()}function LR(e){return e===Dx?"temp":e}function $x(e){const t=e.trim().split(/[/\\]+/).filter(Boolean);return t[t.length-1]??"/"}const bs=10,_f=10;function DC(e,t=_f){return Math.max(1,Math.ceil(e/t))}function $C(e,t,n=_f){return Math.min(Math.max(e,0),DC(t,n)-1)}function OR(e,t=_f){return Math.floor(Math.max(e,0)/t)}function aw(e,t,n=_f){const s=$C(t,e.length,n)*n;return e.slice(s,s+n)}function DR({shown:e,loaded:t,total:n,fullyLoaded:s}){return Math.max((s?t:Math.max(n,t))-e,0)}function sw(e,t){return e.length>t?{items:e.slice(0,t),hasMore:!0}:{items:e,hasMore:!1}}function ha(e){return e.archived?"archived":e.source==="subagent"||e.source==="schedule"?e.source:"active"}function $R(e,t){const n=t.trim().toLowerCase();return n===""?!0:(e.title??"").toLowerCase().includes(n)}const rf=["subagent","schedule","archived"];function gg(e){const t={active:[],subagent:[],schedule:[],archived:[]};for(const n of e)t[ha(n)].push(n);return t}const UC=["active",...rf];function UR(e){const t=new Map;for(const[n,s]of e)for(const[o,c]of Object.entries(s)){const u=vo(o);let f=t.get(u);f||(f={totals:{active:0,subagent:0,schedule:0,archived:0},agents:{active:[],subagent:[],schedule:[],archived:[]}},t.set(u,f));for(const p of UC){const h=c[p];h>0&&(f.totals[p]+=h,f.agents[p].includes(n)||f.agents[p].push(n))}}return t}function PC(e){let t=null;for(const n of e){const s=ha(n);s!=="active"&&s!=="schedule"||(!t||n.createdAt>t.createdAt||n.createdAt===t.createdAt&&n.sessionId>t.sessionId)&&(t=n)}return t}function PR(e){const t=new Map;for(const o of e){const c=vo(o.workspace);let u=t.get(c);if(!u){const f=c===Dx;u={key:c,label:f?"":$x(o.workspace),fullPath:f?null:o.workspace.trim(),temp:f,sessions:[]},t.set(c,u)}u.sessions.push(o)}const n=(o,c)=>o<c?1:o>c?-1:0,s=[...t.values()];for(const o of s)o.sessions.sort((c,u)=>n(c.createdAt,u.createdAt));return s.sort((o,c)=>o.temp!==c.temp?o.temp?1:-1:n(o.sessions[0]?.createdAt??"",c.sessions[0]?.createdAt??"")),s}const zR=["day","month","earlier"],zC=1440*60*1e3,BR=30*zC,HR=e=>`\0time-${e}`,zc="\0time-folders";function FR(e,t){const n=Date.parse(e);if(!Number.isFinite(n))return"earlier";const s=t-n;return s<zC?"day":s<BR?"month":"earlier"}function qR(e,t){const n=new Map;for(const o of e){const c=FR(o.lastActiveAt,t),u=n.get(c);u?u.push(o):n.set(c,[o])}const s=[];for(const o of zR){const c=n.get(o);c!==void 0&&(c.sort((u,f)=>u.lastActiveAt<f.lastActiveAt?1:u.lastActiveAt>f.lastActiveAt?-1:0),s.push({key:HR(o),bucket:o,sessions:c}))}return s}function VR(e){const t={active:0,subagent:0,schedule:0,archived:0};for(const n of e.values())for(const s of UC){const o=n[s];o>0&&(t[s]+=o)}return t}function GR(e,t,n){if(n.size===0)return[...e];const s=[],o=[];for(const c of e)(n.has(t(c))?s:o).push(c);return[...s,...o]}const BC=y.createContext(null),po=(e,t,n="")=>`${e}\0${t}\0${n}`,KR=["active",...rf];function WR(e){const t=e.split("\0");if(t.length!==3)return null;const[n,s,o]=t;return KR.includes(s)?{agentId:n,category:s,scope:o}:null}const h0=e=>e===void 0||e===""?"":LR(e),YR=500;function XR(){let e=0;return zl((t,n)=>{const s=(o,c,u)=>{const{agentId:f,workspace:p}=o,h=n().countsByAgent,x=h.get(f);if(x){const w=new Map(h);w.set(f,{...x,[c]:Math.max(0,x[c]+u)}),t({countsByAgent:w})}const g=n().workspaceCountsByAgent,v=g.get(f);if(v){const w=v[p]??{active:0,subagent:0,schedule:0,archived:0},S=new Map(g);S.set(f,{...v,[p]:{...w,[c]:Math.max(0,w[c]+u)}}),t({workspaceCountsByAgent:S})}};return{projectId:null,agentIds:[],sessions:[],deletedSessionIds:new Set,pageState:new Map,countsByAgent:new Map,workspaceCountsByAgent:new Map,loading:!0,reload:async()=>{const{projectId:o,agentIds:c}=n();if(!o||c.length===0)return;const u=++e;t({loading:!0});try{const f=await Promise.all(c.map(async w=>{const S=[{category:"active",scope:""}];for(const C of n().pageState.keys()){const N=WR(C);N===null||N.agentId!==w||N.category==="active"&&N.scope===""||S.push({category:N.category,scope:N.scope})}try{const C=await Promise.all(S.map(async({category:N,scope:T})=>{const _=await c0(o,w,{offset:0,limit:bs+1,category:N,...T===""?{}:{workspaceGroup:T},...N==="active"&&T===""?{withCounts:!0}:{}});return{category:N,scope:T,counts:_.counts,workspaceCounts:_.workspaceCounts,...sw(_.sessions,bs)}}));return{agentId:w,pages:C}}catch{return{agentId:w,pages:[]}}}));if(u!==e)return;const p=[],h=new Set,x=new Map,g=new Map,v=new Map;for(const w of f)for(const S of w.pages){x.set(po(w.agentId,S.category,S.scope),{hasMore:S.hasMore,fetched:S.items.length}),S.counts&&g.set(w.agentId,S.counts),S.workspaceCounts&&v.set(w.agentId,S.workspaceCounts);for(const C of S.items)h.has(C.sessionId)||(h.add(C.sessionId),p.push(C))}t({sessions:p,pageState:x,countsByAgent:g,workspaceCountsByAgent:v})}finally{u===e&&t({loading:!1})}},loadMoreFor:async(o,c,u)=>{const{projectId:f}=n();if(!f)return;const p=h0(u),h=[...new Set(o)].filter(R=>{const D=n().pageState.get(po(R,c,p));return D===void 0?p!==""||(n().countsByAgent.get(R)?.[c]??0)>0:D.hasMore});if(h.length===0)return;const x=e,g=(R,D)=>n().sessions.filter(z=>z.agentId===R&&ha(z)===c&&vo(z.workspace)===D).length,v=await Promise.all(h.map(async R=>{const z=n().pageState.get(po(R,c,p))?.fetched??(u===void 0||u===""?0:g(R,u));try{const E=(await c0(f,R,{offset:z,limit:bs+1,category:c,...p===""?{}:{workspaceGroup:p}})).sessions;return{agentId:R,offset:z,...sw(E,bs)}}catch{return null}}));if(x!==e)return;const w=v.filter(R=>R!==null),S=n().sessions,C=new Set(S.map(R=>R.sessionId)),N=w.flatMap(R=>R.items.filter(D=>!C.has(D.sessionId))),T=n().pageState,_=new Map(T);for(const R of w){const D=po(R.agentId,c,p);_.set(D,{hasMore:R.hasMore,fetched:(T.get(D)?.fetched??R.offset)+R.items.length})}t({...N.length>0?{sessions:[...S,...N]}:{},pageState:_})},add:o=>{e+=1,!n().sessions.some(u=>u.sessionId===o.sessionId)&&n().pageState.get(po(o.agentId,ha(o)))?.hasMore===!1&&s(o,ha(o),1),t({sessions:[o,...n().sessions.filter(u=>u.sessionId!==o.sessionId)]})},remove:o=>{e+=1;const c=n().sessions.find(f=>f.sessionId===o);c&&s(c,ha(c),-1);const u=new Set(n().deletedSessionIds);for(u.add(o);u.size>YR;){const f=u.values().next();if(f.done)break;u.delete(f.value)}t({deletedSessionIds:u,sessions:n().sessions.filter(f=>f.sessionId!==o)})},replace:o=>{const c=n().sessions.find(u=>u.sessionId===o.sessionId);c&&ha(c)!==ha(o)&&(s(o,ha(c),-1),s(o,ha(o),1)),t({sessions:n().sessions.map(u=>u.sessionId===o.sessionId?o:u)})},setStatus:(o,c,u)=>{const f=n().sessions,p=f.find(v=>v.sessionId===o);if(!p)return;const h=u?.lastActiveAt??p.lastActiveAt,x=c==="running"||c==="compacting",g=p.hasTrace||u?.hasTrace===!0||x;p.status===c&&p.lastActiveAt===h&&p.hasTrace===g||t({sessions:f.map(v=>v.sessionId===o?{...v,status:c,lastActiveAt:h,hasTrace:g}:v)})},setTitle:(o,c)=>{const u=n().sessions,f=u.find(p=>p.sessionId===o);!f||f.title===c||t({sessions:u.map(p=>p.sessionId===o?{...p,title:c}:p)})}}})}function QR(e,t,n){if(t.type==="web_updated"){n();return}if(t.type==="session_state"){e.getState().setStatus(t.sessionId,t.state,{lastActiveAt:t.lastActiveAt,hasTrace:t.hasTrace});return}if(t.type==="session_title"){e.getState().setTitle(t.sessionId,t.title);return}if(t.type==="resync_required"){e.getState().reload();return}t.type==="schedule_fired"&&t.projectId===e.getState().projectId&&e.getState().reload()}function ZR({children:e}){const{currentProject:t,agents:n}=en(),s=t?.projectId??null,o=n.map(w=>w.agentId).join(","),[c]=y.useState(XR),u=Bl(c);y.useEffect(()=>{c.setState({projectId:s,agentIds:o===""?[]:o.split(","),sessions:[],pageState:new Map,countsByAgent:new Map,workspaceCountsByAgent:new Map}),c.getState().reload()},[c,s,o]),y.useEffect(()=>{const w=RR({onOmniMessage:()=>{},onServerEvent:S=>QR(c,S,()=>window.location.reload())});return()=>w.close()},[c]);const{pageState:f,countsByAgent:p}=u,h=y.useCallback((w,S,C)=>f.has(po(w,S,h0(C))),[f]),x=y.useCallback((w,S,C)=>{const N=h0(C),T=f.get(po(w,S,N));return T!==void 0?T.hasMore:(p.get(w)?.[S]??0)>0},[f,p]),g=y.useCallback(w=>c.getState().deletedSessionIds.has(w),[c]),v=y.useMemo(()=>{const w=new Map;for(const S of u.sessions){const C=w.get(S.agentId);C?C.push(S):w.set(S.agentId,[S])}for(const S of w.values())S.sort((C,N)=>N.createdAt.localeCompare(C.createdAt)||N.sessionId.localeCompare(C.sessionId));return{sessions:u.sessions,byAgent:w,countsByAgent:u.countsByAgent,workspaceCountsByAgent:u.workspaceCountsByAgent,isLoadedFor:h,hasMoreFor:x,loading:u.loading,reload:u.reload,loadMoreFor:u.loadMoreFor,add:u.add,remove:u.remove,isDeleted:g,replace:u.replace,setStatus:u.setStatus,setTitle:u.setTitle}},[u,h,x,g]);return a.jsx(BC.Provider,{value:v,children:e})}function Ii(){const e=y.useContext(BC);if(!e)throw new Error("useSessions must be used within a SessionsProvider");return e}function HC(e){return e.desktopMode&&e.sessionVia==="desktop"}const JR={check:{action:"check",busy:!1},checking:{action:"none",busy:!0},downloading:{action:"none",busy:!0},install:{action:"install",busy:!1},unsupported:{action:"none",busy:!1},unknown:{action:"none",busy:!1}};function oo(e,t,n={}){return{labelKind:e,...JR[e],version:null,percent:null,appVersion:t?.appVersion??null,unsupportedReason:null,...n}}function FC(e,t=!1){if(e===null)return oo("unknown",e);switch(e.state){case"unsupported":return oo("unsupported",e,{unsupportedReason:e.reason??null});case"checking":return oo("checking",e);case"downloading":return oo("downloading",e,{version:e.version??null,percent:e.percent??null});case"downloaded":return oo("install",e,{version:e.version??null});default:return oo(t?"checking":"check",e)}}const eI=6e4;function tI(e,t,n){const s=n>=eI;if(t===null)return s?{kind:"failed",message:null}:null;if(t.state==="checking")return null;if(!(t.seq!==void 0&&e!==null?t.seq!==e:n>=4e3))return s?{kind:"failed",message:null}:null;switch(t.state){case"up-to-date":return{kind:"up-to-date"};case"downloading":return{kind:"found",version:t.version??null};case"downloaded":return{kind:"ready",version:t.version??null};case"unsupported":return{kind:"unsupported",reason:t.reason??null};case"error":return{kind:"failed",message:t.message??null};default:return s?{kind:"failed",message:null}:null}}function Ae(e,t){return e instanceof xr?e.code==="model_credential_missing"?t?.modelId?d.errors.modelCredentialMissing(t.modelId):e.message:e.code==="no_default_model"?d.errors.noDefaultModel:d.errors.byCode[e.code]??e.message:d.common.unknownError}var ss=$j();const nI={success:2500,info:4e3,error:6e3},uu=zl(()=>({items:[]}));let rI=1;const aI=160;function qC(e){const t=uu.getState().items.find(n=>n.id===e);!t||t.leaving||(uu.setState(n=>({items:n.items.map(s=>s.id===e?{...s,leaving:!0}:s)})),setTimeout(()=>{uu.setState(n=>({items:n.items.filter(s=>s.id!==e)}))},aI))}function Ux(e,t){if(!t)return;const n=rI++;uu.setState(s=>({items:[...s.items,{id:n,kind:e,text:t}]})),setTimeout(()=>qC(n),nI[e])}const yt=e=>Ux("success",e),Be=e=>Ux("error",e),wr=e=>Ux("info",e),sI={success:"border-emerald-200 bg-emerald-50 text-emerald-800 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-200",error:"border-red-200 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-200",info:"border-sky-200 bg-sky-50 text-sky-800 dark:border-sky-900 dark:bg-sky-950 dark:text-sky-200"};function iI(){const e=Bl(uu,t=>t.items);return e.length===0?null:ss.createPortal(a.jsx("div",{className:"pointer-events-none fixed inset-x-0 top-3 z-[100] flex flex-col items-center gap-2 px-4",children:e.map(t=>a.jsx("button",{type:"button",onClick:()=>qC(t.id),className:`pointer-events-auto max-w-lg break-words rounded-md border px-3 py-2 text-left text-sm shadow-lg ${t.leaving?"anim-toast-out":"anim-toast-in"} ${sI[t.kind]}`,children:t.text},t.id))}),document.body)}const oI=1500,lI=8e3;let Sl=null,Bc=null,Ai=null;const g0=new Set;function x0(){for(const e of g0)e()}function cI(){if(Ai===null)return;const e=tI(Ai.atClickSeq,Sl,Date.now()-Ai.armedAt);if(e!==null)switch(Ai=null,e.kind){case"up-to-date":yt(d.update.upToDate);break;case"found":yt(d.update.clientFoundNew(e.version));break;case"ready":yt(d.update.clientDownloadReady(e.version));break;case"unsupported":wr(e.reason==="linux-not-appimage"?d.update.clientUnsupportedNonAppImage:d.update.clientUnsupportedDev);break;default:Be(e.message!==null?d.update.clientUpdateFailed(e.message):d.update.checkFailed)}}function af(){return Bc||(Bc=(async()=>{try{Sl=(await UA()).status}catch{}finally{Bc=null,cI(),x0()}})(),Bc)}function uI(){af()}async function dI(){if(Ai===null){Ai={atClickSeq:Sl?.seq??null,armedAt:Date.now()},x0();try{await PA(),af()}catch(e){Ai=null,x0(),Be(Ae(e))}}}async function mI(){try{await zA()}catch(e){Be(d.update.clientInstallFailed(Ae(e)))}}function VC(e,t){const[,n]=y.useReducer(u=>u+1,0);y.useEffect(()=>(g0.add(n),()=>{g0.delete(n)}),[]);const s=Ai!==null,o=s||Sl?.state==="checking"||Sl?.state==="downloading",c=e&&(t||s);return y.useEffect(()=>{if(!c)return;af();const u=setInterval(()=>{af()},o?oI:lI);return()=>clearInterval(u)},[c,o]),{status:Sl,checkPending:s}}let xg=null,yg=null,Gm=null,jl=null;const y0=new Set;function b0(){for(const e of y0)e()}function fI(e){return e.disabled===!0?{kind:"disabled"}:e.error!==void 0?{kind:"failed"}:e.updateAvailable&&e.latestVersion!==null?{kind:"found",latestVersion:e.latestVersion}:{kind:"up-to-date"}}function Px(e){const[t,n]=y.useState(xg),[s,o]=y.useState(Gm);return y.useEffect(()=>{const c=()=>{n(xg),o(Gm)};return y0.add(c),()=>{y0.delete(c)}},[]),y.useEffect(()=>{if(!e)return;let c=!1;return yg??=DA().then(u=>(xg=u,b0(),u)),yg.then(u=>{c||n(u)}).catch(()=>{yg=null}),jl??=uC().then(u=>(Gm=u,b0(),u)),jl.then(u=>{c||o(u)}).catch(()=>{jl=null}),()=>{c=!0}},[e]),{version:t,update:s}}async function iw(){const e=uC(!0).then(t=>(Gm=t,t));jl=e;try{return await e}catch(t){throw jl===e&&(jl=null),t}finally{b0()}}function GC(e){return e?.updateAvailable===!0?e.latestVersion??null:null}function pI(e){if(e.releaseRowOffered){const t=GC(e.update);if(t!==null)return{kind:"release",version:t}}if(e.clientRowOffered){const t=FC(e.clientStatus);if(t.action==="install")return{kind:"client",version:t.version}}return null}function hI(e){return e.some(t=>t.kernelOutdated)}function gI(e,t){return e!==null&&t?{kind:"mixed"}:e!==null?e:t?{kind:"kernel"}:{kind:"none"}}function zx(e=!1){const{desktopMode:t,sessionVia:n}=mn(),{agents:s}=en(),o=HC({desktopMode:t,sessionVia:n}),{update:c}=Px(e),{status:u}=VC(!1,!1);y.useEffect(()=>{e&&o&&uI()},[e,o]);const f=pI({releaseRowOffered:!t,clientRowOffered:o,update:c,clientStatus:u}),p=hI(s),h=p?d.agent.kernelOutdatedHint:null,x=f===null?null:ow(f);return{software:f,softwareNote:x,kernel:p,kernelNote:h,any:f!==null||p,note:ow(gI(f,p))}}function ow(e){switch(e.kind){case"none":return null;case"release":return d.update.newVersion(e.version);case"client":return d.update.clientRestartToInstall(e.version);case"kernel":return d.agent.kernelOutdatedHint;default:return d.update.updatesAvailable}}function xI(e){return e==="running"||e==="compacting"}const yI=1e4;function bI(e=yI){const t=new Map;return{observe(n,s=Date.now()){const o=[],c=new Set;for(const u of n){if(c.has(u.sessionId))continue;c.add(u.sessionId);const f=xI(u.status),p=t.get(u.sessionId);if(p===void 0){t.set(u.sessionId,{active:f,lastFiredAt:null});continue}p.active&&!f&&(p.lastFiredAt===null||s-p.lastFiredAt>=e)&&(o.push(u.sessionId),p.lastFiredAt=s),p.active=f}for(const u of[...t.keys()])c.has(u)||t.delete(u);return o}}}function vI(){const{sessionVia:e}=mn(),{sessions:t}=Ii(),{setCurrentAgentId:n}=en(),s=yr(),o=y.useRef(bI()),c=y.useRef(s);c.current=s;const u=y.useRef(n);u.current=n;const f=e==="desktop";y.useEffect(()=>{if(!f)return;const p=o.current.observe(t.map(h=>({sessionId:h.sessionId,status:h.status})));if(p.length!==0&&!(!document.hidden&&document.hasFocus())&&!(typeof Notification>"u"||Notification.permission!=="granted"))for(const h of p){const x=t.find(w=>w.sessionId===h),g=x?.title??d.chat.defaultSessionTitle,v=x?.agentId??null;try{const w=new Notification(d.notify.taskCompleteTitle,{body:d.notify.taskCompleteBody(g),tag:`penguin-task-${h}`,icon:"/penguin-logo.svg"});w.onclick=()=>{w.close(),window.focus(),v!==null&&u.current(v),c.current(`/chat/${h}`)}}catch{}}},[f,t])}function Zn({open:e,size:t=14,className:n=""}){return a.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:`block shrink-0 transition-transform duration-200 ${e?"rotate-90":""} ${n}`,children:a.jsx("path",{d:"M9 5l7 7-7 7"})})}const Ye={inlineGlyph:13,rowLead:14,iconButton:15,groupHeaderGlyph:15,groupHeaderAction:16,navRow:16,chevron:14,chevronDense:12,caretDense:10},Ro={tight:"gap-1",row:"gap-1.5",menu:"gap-2"};function Oe({d:e,size:t=Ye.inlineGlyph,className:n="",filled:s=!1}){return a.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:s?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:`block shrink-0 ${n}`,"aria-hidden":!0,children:a.jsx("path",{d:e})})}function vn({d:e,size:t=Ye.navRow}){return a.jsx(Oe,{d:e,size:t})}const El="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z",kI="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",Bx="M12 3v3m-6 4a6 6 0 0 1 12 0v5a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-5zm3 3h.01M15 13h.01",wI="M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0M12 6v6l4 2",SI="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",jI="m21 16-4 4-4-4M17 20V4M3 8l4-4 4 4M7 4v16",xm={workspace:El,agent:Bx,time:SI},lw={recent:wI,manual:jI},KC="penguin.sidebarGroupMode";function bg(){const e=localStorage.getItem(KC);return e==="agent"||e==="time"?e:"workspace"}function CI(e){return e==="agent"?"agent":e==="time"?"chat":"workspace"}function NI(e){localStorage.setItem(KC,e)}const WC="flex w-full items-center gap-1 rounded px-1.5 py-1 text-left text-[11px] font-medium text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 dark:text-gray-500 dark:hover:bg-gray-800/50";function Km({label:e,ariaLabel:t,pending:n=!1,onClick:s,className:o}){return a.jsxs("button",{type:"button","aria-label":t??d.chat.loadMore,disabled:n,onClick:s,className:`${WC}${o?` ${o}`:""} disabled:opacity-60`,children:[a.jsx("span",{className:"w-3","aria-hidden":!0}),n?d.common.loading:e]})}const TI="M15 18 9 12l6-6",MI="m9 18 6-6-6-6";function EI({page:e,pageCount:t,onChange:n}){const s=c=>{const u=e+c;u>=0&&u<t&&n(u)},o="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 hover:text-gray-700 disabled:pointer-events-none disabled:opacity-40 dark:text-gray-500 dark:hover:bg-gray-800/50 dark:hover:text-gray-300";return a.jsxs("div",{className:"mt-1 flex items-center justify-center gap-1.5 px-1.5 py-0.5",children:[a.jsx("button",{type:"button",title:d.chat.prevGroupPage,"aria-label":d.chat.prevGroupPage,disabled:e<=0,onClick:()=>s(-1),className:o,children:a.jsx(vn,{d:TI,size:12})}),a.jsxs("span",{"aria-live":"polite","aria-label":d.chat.groupPagePosition(e+1,t),className:"min-w-[2.5rem] text-center text-[11px] font-medium tabular-nums text-gray-400 dark:text-gray-500",children:[e+1,"/",t]}),a.jsx("button",{type:"button",title:d.chat.nextGroupPage,"aria-label":d.chat.nextGroupPage,disabled:e>=t-1,onClick:()=>s(1),className:o,children:a.jsx(vn,{d:MI,size:12})})]})}function AI({label:e,open:t,onToggle:n,more:s=!1,moreLabel:o,pending:c=!1,onMore:u,children:f}){return a.jsxs("div",{className:"mt-1",children:[a.jsxs("button",{type:"button",onClick:n,className:WC,children:[a.jsx(Zn,{open:t,size:12}),e]}),t&&f,t&&s&&a.jsx(Km,{label:o??d.chat.loadMore,...o!==void 0?{ariaLabel:o}:{},pending:c,onClick:()=>u?.()})]})}function ym({open:e,onToggle:t,icon:n,label:s,uppercase:o=!1,count:c,title:u,actions:f,draggable:p=!1,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}){return a.jsxs("div",{className:`group/header flex items-center gap-0.5 px-1 pb-0.5${p?" cursor-grab":""}`,...p?{draggable:!0,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}:{},children:[a.jsxs("button",{type:"button",onClick:t,"aria-expanded":e,"aria-label":e?d.nav.collapseGroup:d.nav.expandGroup,...u!==void 0?{title:u}:{},className:"flex min-w-0 flex-1 items-center gap-1 self-stretch rounded px-1 py-0.5 text-left transition-colors duration-150 hover:bg-gray-200/50 dark:hover:bg-gray-800/50",children:[n,a.jsx("span",{className:`min-w-0 truncate text-xs font-semibold ${o?"uppercase tracking-wide ":""}text-gray-500 dark:text-gray-400`,children:s}),c!==void 0&&a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400 dark:text-gray-500",children:c}),a.jsx(Zn,{open:e,size:12,className:"text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1"})]}),f]})}function ns({size:e=12,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 12 12",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M3 4.5l3 3 3-3",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function qu({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M5 12l4 4L19 6",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function _I({size:e=14,strokeWidth:t=1.7,className:n=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${n}`,children:a.jsx("path",{d:"M12 5v14M5 12h14",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round"})})}function Hx({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M12 4v11m0 0l-5-5m5 5l5-5M4 20h16",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})}function YC({size:e=13,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`shrink-0 ${t}`,children:a.jsx("path",{d:"M12 15V4m0 0L7 9m5-5l5 5M4 20h16",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})}function Hl({size:e=14,className:t=""}){return a.jsx("svg",{width:e,height:e,viewBox:"0 0 14 14",fill:"none",stroke:"currentColor","aria-hidden":!0,className:`block shrink-0 ${t}`,children:a.jsx("path",{d:"M2 2l10 10M12 2L2 12",strokeWidth:"1.5",strokeLinecap:"round"})})}function Rf({onClose:e,className:t="",...n}){return a.jsx("button",{type:"button","aria-label":d.common.close,onClick:e,className:`rounded-md p-1.5 text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300 ${t}`,...n,children:a.jsx(Hl,{})})}const RI="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11v5m0-8h.01",XC="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",II="M22 2 11 13M22 2l-7 20-4-9-9-4z",If="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",vs={agents:Bx,skills:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2zM22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",models:"M7 7h10v10H7zM4 10h3m10 0h3M4 14h3m10 0h3M10 4v3m4-3v3m-4 10v3m4-3v3",usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",traces:"M4 6h16M4 12h10M4 18h13",benchmark:"M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",terminal:"M3 5h18v14H3zM7 9l3 3-3 3M13 15h4"};function QC({open:e,side:t="left",title:n,onClose:s,children:o,widthClass:c}){return y.useEffect(()=>{if(!e)return;const u=f=>{f.key==="Escape"&&s()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e,s]),e?a.jsxs("div",{className:"fixed inset-0 z-50",children:[a.jsx("div",{className:"anim-fade absolute inset-0 bg-black/45",onMouseDown:s}),a.jsxs("div",{className:`absolute inset-y-0 flex w-[80vw] flex-col bg-white shadow-xl dark:bg-gray-900 ${c??"max-w-xs"} ${t==="left"?"anim-drawer-left left-0 border-r border-gray-200 dark:border-gray-800":"anim-drawer-right right-0 border-l border-gray-200 dark:border-gray-800"}`,children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("span",{className:"text-base font-semibold",children:n??""}),a.jsx(Rf,{onClose:s})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto pb-[env(safe-area-inset-bottom)]",children:o})]})]}):null}const LI={chrome:"h-2.5 w-2.5 border-2 border-gray-50 dark:border-gray-900",inline:"h-1.5 w-1.5"};function Mo({size:e="chrome",position:t="-right-0.5 -top-0.5"}){return a.jsx("span",{"aria-hidden":!0,className:`pointer-events-none absolute rounded-full bg-red-400 ${LI[e]} ${t}`})}function OI({onClick:e,children:t}){return a.jsx("button",{type:"button",onClick:e,className:"inline-flex shrink-0 items-center whitespace-nowrap rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-semibold text-red-800 transition-colors duration-150 hover:bg-red-200 dark:bg-red-950 dark:text-red-300 dark:hover:bg-red-900",children:t})}function ko(e){const t=e.toFixed(1);return t.endsWith(".0")?t.slice(0,-2):t}function It(e){const t=Math.abs(e);return t<1e3?`${e}`:t<1e6?`${ko(e/1e3)}k`:`${ko(e/1e6)}M`}function Pn(e,t){if(e<1e3)return`${Math.round(e)}ms`;const n=e/1e3;if(n<60&&!(t?.compact&&n>=10))return`${ko(n)}s`;const s=Math.round(n);return s<60?`${s}s`:`${Math.floor(s/60)}m${s%60}s`}function ZC(e){const t=Math.max(0,Math.floor(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`}function v0(e,t){return t>0?e/(t/1e3):null}function sf(e){return e==null||!Number.isFinite(e)?"—":`${Math.abs(e)<1e3?ko(e):It(e)} tok/s`}function JC(e,t){const n=e+t;return n>0?e/n:null}function Lf(e){return e==null||!Number.isFinite(e)?"—":`${Math.round(e*100)}%`}function rs(e,t="USD",n){if(e==null)return"—";const s=t==="CNY"?"¥":"$",o=t==="CNY"?e*7:e;if(o===0)return`${s}0`;const c=Math.abs(o);if(n?.compact&&c<1)return`${s}${Number(o.toPrecision(2))}`;const u=c>=100?0:c>=1?2:4;return`${s}${o.toFixed(u)}`}function Su(e){return Number.isInteger(e)?`${e}`:e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function cw(e){return Number(e.toFixed(1))<1024}function ju(e){if(e<1024)return`${e}B`;const t=e/1024;if(cw(t))return`${ko(t)}KB`;const n=t/1024;return cw(n)?`${ko(n)}MB`:`${ko(n/1024)}GB`}function yo(e){return e<10?`0${e}`:`${e}`}function Jr(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:`${t.getFullYear()}-${yo(t.getMonth()+1)}-${yo(t.getDate())} ${yo(t.getHours())}:${yo(t.getMinutes())}`}const DI=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k0(e,t){const n=/^\d{4}-(\d{2})-(\d{2})(?:$|T)/.exec(e);if(!n)return e;const s=Number(n[1]),o=Number(n[2]);return s<1||s>12||o<1||o>31?e:t==="en"?`${DI[s-1]} ${o}`:`${s} 月 ${o} 日`}function eN(e,t){const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleString(t==="en"?"en-US":"zh-CN",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function of(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function $I(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=Math.round((of(new Date)-of(n))/864e5);return s<0?Jr(e):s===0?t==="en"?"today":"今天":s===1?t==="en"?"yesterday":"昨天":t==="en"?`${s} days ago`:`${s} 天前`}function Al(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=Math.round((of(new Date)-of(n))/864e5);return s<0?e:s===0?t==="en"?"updated today":"今天更新":s===1?t==="en"?"updated yesterday":"昨天更新":t==="en"?`updated ${s} days ago`:`${s} 天前更新`}function UI(e,t){const n=new Date(e);if(Number.isNaN(n.getTime()))return"";const s=Date.now()-n.getTime();if(s<0)return k0(e,t);const o=Math.floor(s/6e4);if(o<1)return t==="en"?"now":"刚刚";if(o<60)return t==="en"?`${o}m`:`${o} 分钟前`;const c=Math.floor(o/60);if(c<24)return t==="en"?`${c}h`:`${c} 小时前`;const u=Math.floor(c/24);return u<7?t==="en"?`${u}d`:`${u} 天前`:k0(e,t)}function PI(e){const t=new Date(e);return Number.isNaN(t.getTime())?e:`${yo(t.getHours())}:${yo(t.getMinutes())}:${yo(t.getSeconds())}`}const Fx=e=>`penguin.sessionSeen.${e}`,uw=500,Cl={seededAt:0,seen:new Map};function tN(e){try{return localStorage}catch{return null}}function zI(e){if(e===null)return Cl;try{const t=JSON.parse(e);if(typeof t!="object"||t===null)return Cl;const n=t,s=typeof n.seededAt=="number"&&Number.isFinite(n.seededAt)?n.seededAt:0,o=new Map;if(typeof n.seen=="object"&&n.seen!==null)for(const[c,u]of Object.entries(n.seen))typeof u=="number"&&Number.isFinite(u)&&o.set(c,u);return{seededAt:s,seen:o}}catch{return Cl}}function BI(e){let t=[...e.seen];return t.length>uw&&(t.sort((n,s)=>s[1]-n[1]),t=t.slice(0,uw)),JSON.stringify({seededAt:e.seededAt,seen:Object.fromEntries(t)})}function HI(e,t,n,s=Date.now()){const o=Date.parse(n),c=Number.isNaN(o)?s:Math.max(s,o);return e.seen.get(t)===c?e:{seededAt:e.seededAt,seen:new Map(e.seen).set(t,c)}}function FI(e,t){if(!e.seen.has(t))return e;const n=new Map(e.seen);return n.delete(t),{seededAt:e.seededAt,seen:n}}function qI(e,t,n){const s=Date.parse(n);return Number.isNaN(s)?!1:s>(e.seen.get(t)??e.seededAt)}const qx=zl(()=>({cache:new Map}));function Vx(e,t){const{cache:n}=qx.getState(),s=n.get(e);if(s)return s;const o=tN();let c=Cl;if(o)try{c=zI(o.getItem(e))}catch{c=Cl}return n.set(e,c),c}function nN(e,t,n){const s=tN();if(s)try{s.setItem(e,BI(t))}catch{}qx.setState(o=>({cache:new Map(o.cache).set(e,t)}))}function VI(e){return Bl(qx,()=>e?Vx(Fx(e)):Cl)}function Gx(e,t,n,s){if(e===null)return;const o=Fx(e),c=Vx(o),u=c.seededAt===0?{seededAt:Date.now(),seen:c.seen}:c,f=HI(u,t,n);f!==c&&nN(o,f)}function GI(e,t,n){if(e===null)return;const s=Fx(e),o=Vx(s),c=FI(o,t);c!==o&&nN(s,c)}function rN(e,t,n){return e==="running"?"running":e==="compacting"?"compacting":t&&n?"completedUnread":null}function KI(e,t,n){const s=e.sessionId!==n&&qI(t,e.sessionId,e.lastActiveAt);return rN(e.status,e.hasTrace,s)}const WI=["agents","skills","models","usage","benchmark"],aN="penguin.sidebarNavGroupCollapsed";function YI(e){try{return(e??localStorage).getItem(aN)==="collapsed"}catch{return!1}}function XI(e,t){try{(t??localStorage).setItem(aN,e?"collapsed":"expanded")}catch{}}const sN=e=>`penguin.pinnedSessions.${e}`;function dw(e,t){if(e===null)return new Set;try{const n=t??localStorage,s=JSON.parse(n.getItem(sN(e))??"[]");return new Set(Array.isArray(s)?s.filter(o=>typeof o=="string"):[])}catch{return new Set}}function mw(e,t,n){if(e!==null)try{(n??localStorage).setItem(sN(e),JSON.stringify([...t]))}catch{}}function QI(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function ZI(e,t){if(!e.has(t))return e;const n=new Set(e);return n.delete(t),n}const iN=e=>`penguin.sidebarWorkspaces.${e}`;function w0(e){let t=e.trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"))&&!/^[A-Za-z]:[/\\]$/.test(t);)t=t.slice(0,-1);return t}function JI(e){if(typeof e=="string"){const t=w0(e);return t===""?null:{path:t}}if(typeof e=="object"&&e!==null&&typeof e.path=="string"){const t=w0(e.path);if(t==="")return null;const n=e.alias,s=typeof n=="string"?n.trim():"";return s===""?{path:t}:{path:t,alias:s}}return null}function fw(e,t){if(e===null)return[];try{const n=t??localStorage,s=JSON.parse(n.getItem(iN(e))??"[]");if(!Array.isArray(s))return[];const o=[];for(const c of s){const u=JI(c);u!==null&&!o.some(f=>f.path===u.path)&&o.push(u)}return o}catch{return[]}}function e6(e,t,n){if(e!==null)try{(n??localStorage).setItem(iN(e),JSON.stringify(t))}catch{}}function t6(e,t){const n=w0(t);return n===""||OC(n)||e.some(s=>s.path===n)?e:[{path:n},...e]}function n6(e,t,n){const s=n.trim(),o=e.find(c=>c.path===t);return!o||(o.alias??"")===s?e:e.map(c=>c.path===t?s===""?{path:c.path}:{path:c.path,alias:s}:c)}function r6(e,t){return e.some(n=>n.path===t)?e.filter(n=>n.path!==t):e}function a6(e,t){const n=new Map(t.filter(u=>u.alias!==void 0).map(u=>[u.path,u.alias])),s=new Set(e.map(u=>u.key)),o=[];for(const{path:u,alias:f}of t){const p=vo(u);s.has(p)||p!==u||(s.add(p),o.push({key:p,label:f??$x(u),fullPath:u,temp:!1,sessions:[]}))}const c=e.map(u=>{const f=n.get(u.key);return f===void 0?u:{...u,label:f}});return o.length===0?c:[...c,...o]}const oN="penguin.sidebarSortMode";function s6(e){try{return(e??localStorage).getItem(oN)==="manual"?"manual":"recent"}catch{return"recent"}}function i6(e,t){try{(t??localStorage).setItem(oN,e)}catch{}}const lN=(e,t)=>`penguin.sessionOrder.${e}.${t}`;function Kx(e,t){try{const n=t??localStorage,s=JSON.parse(n.getItem(e)??"[]");return Array.isArray(s)?s.filter(o=>typeof o=="string"):[]}catch{return[]}}function Wx(e,t,n){try{(n??localStorage).setItem(e,JSON.stringify(t))}catch{}}function vg(e,t,n){return e===null?[]:Kx(lN(e,t),n)}function pw(e,t,n,s){e!==null&&Wx(lN(e,t),n,s)}function hw(e,t,n){if(n.length===0)return[...e];const s=new Map(n.map((u,f)=>[u,f])),o=[],c=[];for(const u of e)(s.has(t(u))?c:o).push(u);return c.sort((u,f)=>(s.get(t(u))??0)-(s.get(t(f))??0)),[...o,...c]}function cN(e,t,n,s){if(s.length===0)return GR(e,t,n);const o=e.filter(u=>n.has(t(u))),c=e.filter(u=>!n.has(t(u)));return[...hw(o,t,s),...hw(c,t,s)]}function o6(e,t,n){const s=n.recencyOf,o=s?[...e].sort((c,u)=>s(u).localeCompare(s(c))||t(u).localeCompare(t(c))):e;return cN(o,t,n.pinned,n.sortMode==="manual"?n.order:[])}function Yx(e,t,n,s){if(t===n||!e.includes(t))return e;const o=e.filter(u=>u!==t),c=o.indexOf(n);return c<0?e:(o.splice(s?c+1:c,0,t),o.every((u,f)=>u===e[f])?e:o)}function l6(e,t){const n=new Set(t);return[...t,...e.filter(s=>!n.has(s))]}function c6(e,t){return e.includes(t)?e.filter(n=>n!==t):e}const u6=["workspace","agent"];function Xx(e){return u6.includes(e)}const uN=(e,t)=>`penguin.groupOrder.${e}.${t}`;function kg(e,t,n){return e===null||!Xx(t)?[]:Kx(uN(e,t),n)}function d6(e,t,n,s){e===null||!Xx(t)||Wx(uN(e,t),n,s)}function gw(e,t,n){return cN(e,t,n.pinned,n.order)}function m6(e,t,n,s,o){const c=new Set(e),u=[...t.filter(p=>!c.has(p)),...e],f=Yx(u,n,s,o);return f===u?e:f}const Cu=[];function dN(){const e=Symbol("esc-layer");return Cu.push(e),e}function mN(e){const t=Cu.lastIndexOf(e);t!==-1&&Cu.splice(t,1)}function fN(e){return Cu[Cu.length-1]===e}function Yt({open:e,title:t,onClose:n,children:s,footer:o,widthClass:c,headerless:u,bare:f}){const p=y.useRef(n);return p.current=n,y.useEffect(()=>{if(!e)return;const h=dN(),x=g=>{g.key==="Escape"&&fN(h)&&p.current()};return window.addEventListener("keydown",x),()=>{window.removeEventListener("keydown",x),mN(h)}},[e]),e?ss.createPortal(a.jsx("div",{className:"anim-fade fixed inset-0 z-50 flex items-end justify-center bg-black/45 p-0 sm:items-center sm:p-4",onMouseDown:h=>{h.target===h.currentTarget&&n()},children:a.jsxs("div",{...u?{role:"dialog","aria-label":t}:{},className:`anim-pop w-full ${c??"sm:max-w-md"} rounded-t-lg border border-gray-200 bg-white pb-[env(safe-area-inset-bottom)] shadow-xl sm:rounded-lg sm:pb-0 dark:border-gray-800 dark:bg-gray-900`,children:[!u&&a.jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("h2",{className:"text-base font-semibold",children:t}),a.jsx(Rf,{onClose:n})]}),f?s:a.jsx("div",{className:"max-h-[70vh] overflow-y-auto px-4 py-4",children:s}),o&&a.jsx("div",{className:"flex justify-end gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800",children:o})]})}),document.body):null}const bm=4,Hc=8;function Qn({button:e,open:t,setOpen:n,children:s,menuClass:o,menuStyle:c,className:u,portal:f,anchorRect:p,returnFocus:h,onEscape:x,focusOnOpen:g}){const v=y.useRef(null),w=y.useRef(null),[S,C]=y.useState(null),N=y.useCallback(()=>h?.()??v.current?.querySelector("button")??null,[h]),T=y.useCallback(()=>w.current?[...w.current.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')]:[],[]),_=y.useRef(g);_.current=g,y.useEffect(()=>{!t||_.current===!1||T()[0]?.focus()},[t,T]);const R=F=>{if(F.key!=="ArrowDown"&&F.key!=="ArrowUp"||F.defaultPrevented)return;const P=document.activeElement?.tagName;if(P==="INPUT"||P==="TEXTAREA"||P==="SELECT")return;const B=T();if(B.length===0)return;F.preventDefault();const Y=B.indexOf(document.activeElement),q=F.key==="ArrowDown"?1:-1,K=Y<0?q===1?0:B.length-1:(Y+q+B.length)%B.length;B[K]?.focus()},D=y.useRef(n);D.current=n;const z=y.useRef(x);z.current=x,y.useEffect(()=>{if(!t)return;const F=B=>{const Y=B.target;v.current?.contains(Y)||w.current?.contains(Y)||D.current(!1)},V=dN(),P=B=>{if(B.key!=="Escape"||!fN(V))return;N()?.focus();const Y=z.current;Y?Y():D.current(!1)};return window.addEventListener("mousedown",F),window.addEventListener("keydown",P),()=>{mN(V),window.removeEventListener("mousedown",F),window.removeEventListener("keydown",P)}},[t]);const E=y.useCallback(()=>{if(!t||!f||!v.current){C(null);return}const F=p??v.current.getBoundingClientRect(),V=w.current,P=V?.offsetWidth??0,B=V?.offsetHeight??0,Y=f.align==="right"?F.right-P:F.left,q=Math.max(Hc,Math.min(Y,window.innerWidth-P-Hc)),K=window.innerHeight-F.bottom-bm-Hc,H=F.top-bm-Hc,$=f.direction==="up",le=($?B<=H:B<=K)?$:H>K;C({left:q,maxHeight:Math.max(0,le?H:K),...le?{bottom:window.innerHeight-F.top+bm}:{top:F.bottom+bm}})},[t,f?.direction,f?.align,s,p?.top,p?.left,p?.bottom,p?.right]);y.useLayoutEffect(E,[E]),y.useEffect(()=>{if(!t||!f)return;const F=P=>{w.current?.contains(P.target)||(p?D.current(!1):E())},V=()=>{p?D.current(!1):E()};return window.addEventListener("scroll",F,!0),window.addEventListener("resize",V),()=>{window.removeEventListener("scroll",F,!0),window.removeEventListener("resize",V)}},[t,f,E,p]);const L=`anim-pop ${f?"z-[60]":"z-40"} overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900 ${f?"":"max-h-[70vh]"} ${o??"left-0 top-full mt-1 w-64 max-w-[calc(100vw-2rem)] origin-top-left"}`;return a.jsxs("div",{className:`relative ${u??""}`,ref:v,children:[e,t&&(f?ss.createPortal(a.jsx("div",{ref:w,onKeyDown:R,style:{position:"fixed",...S?{left:S.left,maxHeight:S.maxHeight,...S.top!==void 0?{top:S.top}:{},...S.bottom!==void 0?{bottom:S.bottom}:{}}:{left:0,top:0,visibility:"hidden"},maxWidth:`calc(100vw - ${Hc*2}px)`,...c},className:L,children:s}),document.body):a.jsx("div",{ref:w,onKeyDown:R,...c!==void 0?{style:c}:{},className:`absolute ${L}`,children:s}))]})}function pN(e,t){return{top:t,bottom:t,left:e,right:e}}function f6(e){return e.button===2&&!(e.clientX===0&&e.clientY===0)}function p6(e,t){return f6(e)?pN(e.clientX,e.clientY):t}function h6(e){return e.shiftKey&&e.key==="F10"}const g6=500,xw=10,x6=350;function hN(e){return e==="touch"||e==="pen"}function y6(e,t){return Math.abs(t.x-e.x)>xw||Math.abs(t.y-e.y)>xw}function b6(e,t){return t-e<x6}const v6={pointer:"",held:!1,settleFrom:0},xs={open:null,close:!1,swallow:!1};function k6(e,t){switch(t.kind){case"pointerdown":return{...xs,state:{...e,pointer:t.pointerType,held:!1}};case"hold":return{...xs,state:{...e,held:!0,settleFrom:t.at},open:"held"};case"nativemenu":return e.held?{...xs,state:e}:hN(e.pointer)?{...xs,state:{...e,held:!0,settleFrom:t.at},open:"event"}:{...xs,state:e,open:"event"};case"pointerup":return{...xs,state:{...e,pointer:"",settleFrom:e.held?t.at:e.settleFrom}};case"dismiss":return e.held&&b6(e.settleFrom,t.at)?{...xs,state:e}:{...xs,state:{...e,held:!1},close:!0};case"click":return e.held?{...xs,state:{...e,held:!1},swallow:!0}:{...xs,state:e}}}function w6(){const e=y.useRef(null),[t,n]=y.useState(null),s=y.useRef(null),o=y.useRef(null),c=y.useRef(v6),u=y.useCallback(()=>{s.current!==null&&(clearTimeout(s.current),s.current=null),o.current=null},[]);y.useEffect(()=>u,[u]);const f=y.useCallback(()=>{const v=e.current?.getBoundingClientRect();return v?{top:v.top,bottom:v.bottom,left:v.left,right:v.right}:{top:0,bottom:0,left:0,right:0}},[]),p=y.useCallback((v,w)=>{const S=k6(c.current,v);if(c.current=S.state,S.open==="held"){const C=o.current;C&&n(pN(C.x,C.y))}else S.open==="event"&&w&&n(w);return S.close&&n(null),S},[]),h=v=>{const w=v.currentTarget;return w instanceof Node&&w.contains(v.target)},x={onContextMenu:v=>{h(v)&&(v.preventDefault(),p({kind:"nativemenu",at:Date.now()},p6(v,f())),c.current.held&&u())},onKeyDown:v=>{h(v)&&h6(v)&&(v.preventDefault(),n(f()))},onPointerDown:v=>{if(!h(v)||(p({kind:"pointerdown",pointerType:v.pointerType}),!hN(v.pointerType)))return;const w=v.clientX,S=v.clientY;o.current={x:w,y:S},s.current=setTimeout(()=>{s.current=null,p({kind:"hold",at:Date.now()})},g6)},onPointerMove:v=>{const w=o.current;w!==null&&y6(w,{x:v.clientX,y:v.clientY})&&u()},onPointerUp:()=>{u(),p({kind:"pointerup",at:Date.now()})},onPointerCancel:()=>{u(),p({kind:"pointerup",at:Date.now()})}},g=y.useCallback(()=>{c.current={...c.current,held:!1},n(null)},[]);return{rowRef:y.useCallback(v=>{e.current=v},[]),rowProps:x,open:t!==null,setOpen:v=>{v||p({kind:"dismiss",at:Date.now()})},anchor:t,returnFocus:()=>e.current?.querySelector("button")??null,consumeLongPressClick:()=>p({kind:"click"}).swallow,openAt:n,close:g}}const Qx="M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z",Zx="M4 20h4L18.5 9.5a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",S6="M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M9.5 13.5 12 16l2.5-2.5",j6="M3 8h18M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M4 8l1.5-3h13L20 8M12 17v-5m-2.5 2L12 11l2.5 3",Jx="M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6",C6="M4.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM12 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4zM19.5 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4z",ey="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800",gN="flex w-full items-center gap-2 px-2.5 py-1.5 text-left text-xs text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40",ty=e=>a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:e,size:13})}),N6=["archive"];function T6(e){return e?["pin","rename","messaging","archive","delete"]:["rename","messaging","archive","delete"]}function xN(e,t){switch(e){case"pin":return{label:t.pinned?d.chat.unpinSession:d.chat.pinSession,icon:Qx,danger:!1};case"rename":return{label:d.chat.renameSession,icon:Zx,danger:!1};case"messaging":return{label:d.messaging.bindAction,icon:XC,danger:!1};case"archive":return{label:t.archived?d.chat.unarchiveSession:d.chat.archiveSession,icon:t.archived?j6:S6,danger:!1};case"delete":return{label:d.chat.deleteSession,icon:Jx,danger:!0}}}function M6({actions:e,state:t,onRun:n}){return a.jsx(a.Fragment,{children:e.map(s=>{const o=xN(s,t);return a.jsxs("button",{type:"button",className:o.danger?gN:ey,onClick:()=>n(s),children:[o.danger?a.jsx("span",{className:"shrink-0",children:a.jsx(vn,{d:o.icon,size:13})}):ty(o.icon),o.label]},s)})})}const yw="pointer-events-none flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 focus:pointer-events-auto focus:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100";function E6({actions:e,state:t,onRun:n,onMore:s}){const o=c=>{const u=c.currentTarget.getBoundingClientRect();s({top:u.top,bottom:u.bottom,left:u.left,right:u.right})};return a.jsxs(a.Fragment,{children:[e.map(c=>{const u=xN(c,t);return a.jsx("button",{type:"button",title:u.label,"aria-label":u.label,onClick:()=>n(c),className:`${yw} ${u.danger?"hover:text-red-600 dark:hover:text-red-400":"hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"}`,children:a.jsx(vn,{d:u.icon,size:14})},c)}),a.jsx("button",{type:"button",title:d.chat.moreActions,"aria-label":d.chat.moreActions,"aria-haspopup":"menu",onClick:o,className:`${yw} hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200`,children:a.jsx(Oe,{d:C6,size:14,filled:!0})})]})}function A6(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function _6(e){return A6(e)%360}function yN(e){const t=_6(e);return{bg:`hsl(${t} 55% 50% / 0.14)`,fg:`hsl(${t} 55% 28%)`,fgDark:`hsl(${t} 55% 73%)`}}const bw=typeof Intl<"u"&&typeof Intl.Segmenter=="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):void 0;function vw(e){if(e){if(!bw)return Array.from(e)[0];for(const t of bw.segment(e))return t.segment}}function bN(e,t){const n=vw(e.trim())??vw((t??"").trim());return n?n.toUpperCase():"?"}function Ha({id:e,name:t,size:n=18,className:s}){const o=yN(e);return a.jsxs("svg",{width:n,height:n,viewBox:"0 0 24 24",className:s,style:{"--tile-fg":o.fg,"--tile-fg-dark":o.fgDark},"aria-hidden":!0,role:"img",children:[a.jsx("rect",{x:"0",y:"0",width:"24",height:"24",rx:"5",fill:o.bg}),a.jsx("text",{x:"12",y:"12",textAnchor:"middle",dominantBaseline:"central",fontSize:"13",fontWeight:"700",className:"[fill:var(--tile-fg)] dark:[fill:var(--tile-fg-dark)]",children:bN(t??"",e)})]})}const R6=1,I6=60,L6=350,O6=4e3;function D6(e,t){const n=e-t;return n>R6?n:0}function $6(e){if(e<=0)return 0;const t=e/I6*1e3;return Math.round(Math.min(O6,Math.max(L6,t)))}function Of({text:e,className:t="",scrollReveal:n=!1}){const s=y.useRef(null),[o,c]=y.useState(0);y.useLayoutEffect(()=>{const p=s.current;if(!p)return;const h=()=>c(D6(p.scrollWidth,p.clientWidth));if(h(),typeof ResizeObserver>"u")return;const x=new ResizeObserver(h);return x.observe(p),()=>x.disconnect()},[e,t]);const u=o>0,f=n&&u;return a.jsx("span",{ref:s,className:`truncate ${t}${f?" title-scroll":""}`,...f?{style:{"--title-scroll-shift":`-${o}px`,"--title-scroll-ms":`${$6(o)}ms`}}:{},...u?{title:e}:{},children:n?a.jsx("span",{className:"title-scroll-text",children:e}):e})}const Fc={emerald:"text-emerald-600 dark:text-emerald-400",amber:"text-amber-600 dark:text-amber-400",red:"text-red-600 dark:text-red-400",gray:"text-gray-400 dark:text-gray-500"},sn={busy:Fc.emerald,attention:Fc.amber,success:Fc.emerald,danger:Fc.red,muted:Fc.gray},vm={emerald:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300",amber:"bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",red:"bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300",gray:"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"},bo={attention:vm.amber,success:vm.emerald,danger:vm.red,muted:vm.gray},Fl={busy:"bg-emerald-500",attention:"bg-amber-500",success:"bg-emerald-500"},Df={attention:"border-amber-300 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-300"},U6={gray:bo.muted,brand:"bg-gray-200/80 text-gray-700 dark:bg-gray-700/60 dark:text-gray-200",green:bo.success,yellow:"bg-yellow-50 text-yellow-700 dark:bg-yellow-950 dark:text-yellow-300",amber:bo.attention,red:bo.danger};function On({tone:e="gray",children:t}){return a.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ${U6[e]}`,children:t})}function P6(e){switch(e){case"completed":return"green";case"aborted":return"amber";default:return"red"}}const z6={running:"M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",compacting:"M4 12h16M8 7l4 3 4-3M8 17l4-3 4 3"},B6={running:`hourglass-turn ${sn.attention}`,compacting:`compact-squeeze ${sn.attention}`};function S0(e){return e==="running"?d.chat.statusRunning:e==="compacting"?d.chat.statusCompacting:d.chat.statusCompletedUnread}function vN({activity:e,size:t=12}){const n=S0(e);return e==="completedUnread"?a.jsx("span",{role:"img","aria-label":n,title:n,style:{width:t,height:t},className:"flex shrink-0 items-center justify-center",children:a.jsx("span",{className:`block h-1.5 w-1.5 rounded-full ${Fl.success}`})}):a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",role:"status","aria-label":n,className:`block shrink-0 ${B6[e]}`,children:[a.jsx("title",{children:n}),a.jsx("path",{d:z6[e]})]})}const H6={primary:"bg-[var(--accent-bg)] text-[var(--accent-fg)] border border-[var(--accent-bg)] transition-opacity hover:opacity-90 disabled:opacity-50",secondary:"bg-white text-gray-800 border border-gray-300 hover:bg-gray-50 dark:bg-gray-900 dark:text-gray-200 dark:border-gray-700 dark:hover:bg-gray-800",danger:"bg-white text-red-600 border border-gray-300 hover:border-red-300 hover:bg-red-50 dark:bg-gray-900 dark:text-red-400 dark:border-gray-700 dark:hover:bg-red-950",ghost:"bg-transparent text-gray-600 border border-transparent hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100"},F6={sm:"px-2.5 py-1 text-xs rounded-md",md:"px-3 py-1.5 text-sm rounded-md",icon:"p-1.5 rounded-md"};function ge({variant:e="secondary",size:t="md",className:n,...s}){return a.jsx("button",{type:"button",className:`inline-flex items-center justify-center gap-1 font-medium transition-colors duration-150 disabled:cursor-not-allowed disabled:opacity-60 ${H6[e]} ${F6[t]} ${n??""}`,...s})}function q6({tone:e}){const t=e==="danger"?"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3zM12 9v4m0 4h.01":"M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";return a.jsx("span",{"aria-hidden":!0,className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${e==="danger"?"bg-red-100 text-red-600 dark:bg-red-950/60 dark:text-red-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"}`,children:a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:t})})})}function ln({open:e,title:t,onClose:n,onConfirm:s,confirmLabel:o,confirmDisabled:c=!1,secondaryLabel:u,onSecondary:f,tone:p="danger",busy:h=!1,children:x}){return a.jsxs(Yt,{open:e,title:t,onClose:n,headerless:!0,widthClass:"sm:max-w-sm",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(q6,{tone:p}),a.jsx("div",{className:"min-w-0 flex-1 pt-1.5",children:x})]}),a.jsxs("div",{className:"mt-4 flex flex-wrap justify-end gap-2",children:[a.jsx(ge,{size:"sm",onClick:n,disabled:h,children:d.common.cancel}),u!==void 0&&f!==void 0&&a.jsx(ge,{size:"sm",onClick:f,disabled:h,children:u}),a.jsx(ge,{size:"sm",variant:p,disabled:h||c,onClick:s,children:o??d.common.confirm})]})]})}function ql(){const[e,t]=y.useState(null),n=a.jsx(ln,{open:e!==null,title:d.common.confirmSaveTitle,tone:"primary",confirmLabel:d.common.save,onClose:()=>t(null),onConfirm:()=>{e?.(),t(null)},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.common.confirmSaveBody})});return{requestSave:s=>t(()=>s),element:n}}const kw=4,ww=16;function $f({open:e,onClose:t,estimatedHeight:n,panelWidth:s}){const o=y.useRef(null),c=y.useRef(null),[u,f]=y.useState(null),p=y.useRef(t);return p.current=t,y.useLayoutEffect(()=>{if(!e||!o.current)return;const h=o.current.getBoundingClientRect(),x=window.innerHeight-h.bottom,g=h.top,v=Math.min(n,window.innerHeight*.7),w=x<v&&g>x,S=s??h.width,C=Math.max(ww,Math.min(h.left,window.innerWidth-S-ww));f({topPx:w?void 0:h.bottom+kw,bottomPx:w?window.innerHeight-h.top+kw:void 0,left:C,triggerWidth:h.width})},[e,n,s]),y.useEffect(()=>{if(!e)return;const h=w=>{const S=w.target;o.current?.contains(S)||c.current?.contains(S)||p.current()},x=w=>{w.key==="Escape"&&(w.stopPropagation(),p.current())},g=w=>{c.current?.contains(w.target)||p.current()},v=()=>p.current();return window.addEventListener("mousedown",h),window.addEventListener("keydown",x,!0),window.addEventListener("scroll",g,!0),window.addEventListener("resize",v),()=>{window.removeEventListener("mousedown",h),window.removeEventListener("keydown",x,!0),window.removeEventListener("scroll",g,!0),window.removeEventListener("resize",v)}},[e]),{triggerRef:o,panelRef:c,position:u}}const V6="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.6 9.3a2.5 2.5 0 0 1 4.9.8c0 1.7-2.5 2.5-2.5 2.5M12 16.8h.01",G6=288;function ba({children:e,label:t,size:n=Ye.inlineGlyph,className:s=""}){const[o,c]=y.useState(!1),u=y.useId(),{triggerRef:f,panelRef:p,position:h}=$f({open:o,onClose:()=>c(!1),estimatedHeight:160,panelWidth:G6}),x=t!==void 0?d.common.moreInfoAbout(t):d.common.moreInfo;return a.jsxs(a.Fragment,{children:[a.jsx("button",{ref:f,type:"button","aria-label":x,title:x,"aria-expanded":o,"aria-controls":u,"aria-describedby":o?u:void 0,onClick:()=>c(g=>!g),className:`inline-flex shrink-0 items-center justify-center rounded-full text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 ${s}`,children:a.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"block shrink-0",children:a.jsx("path",{d:V6})})}),o&&h&&ss.createPortal(a.jsx("div",{ref:p,id:u,role:"tooltip",style:{position:"fixed",top:h.topPx,bottom:h.bottomPx,left:h.left},className:"anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white px-3 py-2 text-xs leading-relaxed text-gray-600 shadow-lg dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300",children:e}),document.body)]})}const Uf="rounded-md border border-gray-300 bg-white text-gray-900 transition-[border-color,box-shadow] duration-200 hover:border-gray-400 focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100 dark:hover:border-gray-600 dark:focus:border-gray-400 dark:focus:ring-gray-500/30",ny="w-full px-3 py-1.5 text-left transition-colors duration-150";function kN({label:e}){return e===void 0?a.jsx("span",{className:"ml-0.5 text-red-500 dark:text-red-400","aria-hidden":!0,children:"*"}):a.jsxs("span",{className:"ml-0.5 text-red-500 dark:text-red-400",children:[a.jsx("span",{"aria-hidden":!0,children:"*"}),a.jsx("span",{className:"sr-only",children:e})]})}function Yn({children:e,required:t,htmlFor:n,block:s=!0}){const o=`text-xs font-semibold text-gray-600 dark:text-gray-400${s?" mb-1 block":""}`,c=a.jsxs(a.Fragment,{children:[e,t&&a.jsx(kN,{})]});return n!==void 0?a.jsx("label",{htmlFor:n,className:o,children:c}):a.jsx("span",{className:o,children:c})}function wo({children:e}){return a.jsx("span",{className:"mt-1 block text-xs text-gray-500 dark:text-gray-500",children:e})}function ga({id:e,children:t}){return a.jsx("span",{id:e,role:"alert",className:"mt-1 block text-xs text-red-600 dark:text-red-400",children:t})}function Vu({label:e,hint:t,error:n,errorId:s,required:o,info:c,infoLabel:u,controlId:f,children:p}){if(!e&&!t&&!n&&!c)return a.jsx(a.Fragment,{children:p});const h=n?a.jsx(ga,{id:s,children:n}):t?a.jsx(wo,{children:t}):null,x=e!=null&&e!=="";return c!=null&&f!==void 0?a.jsxs("div",{className:"block",children:[a.jsxs("span",{className:"mb-1 flex items-center gap-1",children:[x&&a.jsx(Yn,{required:o,htmlFor:f,block:!1,children:e}),a.jsx(ba,{...u!==void 0?{label:u}:{},children:c})]}),p,h]}):a.jsxs("label",{className:"block",children:[x&&a.jsx(Yn,{required:o,children:e}),p,h]})}const wN=`w-full ${Uf} placeholder:text-gray-400 disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500`,Pf={base:"px-3 py-2 text-base",sm:"px-2 py-1 text-xs"},zf="!border-red-400 !bg-red-50 hover:!border-red-500 focus:!border-red-500 focus:!ring-red-400/30 dark:!border-red-800 dark:!bg-red-950/40 dark:hover:!border-red-700 dark:focus:!border-red-600";function ry(e,t){return e!==void 0&&e!=="off"?{autoComplete:e}:{autoComplete:t?"new-password":"off","data-1p-ignore":"","data-lpignore":"true","data-bwignore":"","data-form-type":"other"}}const Gu=ry(void 0,!1);function at({label:e,hint:t,info:n,infoLabel:s,error:o,invalid:c,required:u,size:f="base",className:p,autoComplete:h,id:x,...g}){const v=!!o||!!c,w=y.useId(),S=y.useId(),C=x??S;return a.jsx(Vu,{label:e,hint:t,error:o,errorId:w,required:u,info:n,infoLabel:s,controlId:C,children:a.jsx("input",{id:n!==void 0?C:x,className:`${wN} ${Pf[f]} ${v?zf:""} ${p??""}`,"aria-invalid":v?!0:void 0,"aria-required":u||void 0,"aria-describedby":o?w:void 0,...ry(h,g.type==="password"),...g})})}const ir=y.forwardRef(function({label:t,hint:n,info:s,infoLabel:o,error:c,invalid:u,required:f,mono:p,size:h="base",className:x,autoComplete:g,id:v,...w},S){const C=!!c||!!u,N=y.useId(),T=y.useId(),_=v??T;return a.jsx(Vu,{label:t,hint:n,error:c,errorId:N,required:f,info:s,infoLabel:o,controlId:_,children:a.jsx("textarea",{ref:S,id:s!==void 0?_:v,className:`${wN} px-3 py-2 ${h==="sm"?"text-xs leading-relaxed":"text-base"} ${p?"font-mono":""} ${C?zf:""} ${x??""}`,"aria-invalid":C?!0:void 0,"aria-required":f||void 0,"aria-describedby":c?N:void 0,...ry(g,!1),...w})})});function on({className:e}){return a.jsx("div",{className:`animate-pulse rounded bg-gray-200 dark:bg-gray-800 ${e??"h-4 w-full"}`})}function Sr({rows:e=3}){return a.jsx("div",{className:"space-y-2 p-2",children:Array.from({length:e},(t,n)=>a.jsx(on,{className:"h-8 w-full"},n))})}function SN({className:e,children:t}){return a.jsx("div",{className:`rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900 ${e??"p-4"}`,children:t??a.jsxs(a.Fragment,{children:[a.jsx(on,{className:"h-3 w-20"}),a.jsx(on,{className:"mt-2.5 h-6 w-28"}),a.jsx(on,{className:"mt-2.5 h-3 w-24"})]})})}function Li(e){y.useEffect(()=>{document.title=e?`${e} · ${d.appName}`:d.appName},[e])}var K6=["partial_text","partial_thinking","partial_tool_call","partial_tool_call_output"];function Nu(e){return K6.includes(e.type??"")}function ay(e){return e.type==="event_msg"}function jN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function sy(e,t){return`[${e}]
|
|
127
127
|
${t}
|
|
128
128
|
[/${e}]`}function Vl(e,t,n=""){const s=jN(e);return[new RegExp(`\\[${s}\\]${t}\\[/${s}\\]`,n),new RegExp(`<${s}>${t}</${s}>`,n)]}function Ku(e,t){return e[0].exec(t)??e[1].exec(t)}function Sw(e,t){const n=jN(t);return e.replace(new RegExp(`\\[${n}\\][\\s\\S]*?\\[/${n}\\]`,"g"),"").replace(new RegExp(`\\[/?${n}\\]`,"g"),"").replace(new RegExp(`<${n}>[\\s\\S]*?</${n}>`,"g"),"").replace(new RegExp(`</?${n}>`,"g"),"")}var va={summary:"summary",userSteering:"user_steering",useSkills:"use_skills",handoffFrom:"handoff_from",scheduledTask:"scheduled_task",backgroundTaskDone:"background_task_done",modelSwitchFrom:"model_switch_from"},W6="[attached image: ",Y6="[attached file: ",X6=/^\[attached image: (.+)\]$/,Q6=/^\[attached file: (.+)\]$/;function Z6(e){return X6.exec(e)?.[1]??null}function J6(e){return Q6.exec(e)?.[1]??null}var eL=Vl(va.summary,"([\\s\\S]*?)","g");function tL(e){for(const t of eL)for(const n of e.matchAll(t)){const s=Sw(n[1],va.summary).trim();if(s!=="")return s}return Sw(e,va.summary).trim()}function jw(e,t){if(e.length===0)return t;const n=sy(va.useSkills,`skills: ${e.join(", ")}`);return t?`${n}
|
|
129
129
|
|
|
@@ -162,7 +162,7 @@ ${t}`:n}var nL=Vl(va.useSkills,"\\nskills: ([^\\n]+)\\n");function CN(e){const t
|
|
|
162
162
|
`))+1))}const u="#".repeat(o),f=n.enter("headingAtx"),p=n.enter("phrasing");c.move(u+" ");let h=n.containerPhrasing(e,{before:"# ",after:`
|
|
163
163
|
`,...c.current()});return/^[\t ]/.test(h)&&(h=Eu(h.charCodeAt(0))+h.slice(1)),h=h?u+" "+h:u,n.options.closeAtx&&(h+=" "+u),p(),f(),h}T5.peek=o9;function T5(e){return e.value||""}function o9(){return"<"}M5.peek=l9;function M5(e,t,n,s){const o=wy(n),c=o==='"'?"Quote":"Apostrophe",u=n.enter("image");let f=n.enter("label");const p=n.createTracker(s);let h=p.move("![");return h+=p.move(n.safe(e.alt,{before:h,after:"]",...p.current()})),h+=p.move("]("),f(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(f=n.enter("destinationLiteral"),h+=p.move("<"),h+=p.move(n.safe(e.url,{before:h,after:">",...p.current()})),h+=p.move(">")):(f=n.enter("destinationRaw"),h+=p.move(n.safe(e.url,{before:h,after:e.title?" ":")",...p.current()}))),f(),e.title&&(f=n.enter(`title${c}`),h+=p.move(" "+o),h+=p.move(n.safe(e.title,{before:h,after:o,...p.current()})),h+=p.move(o),f()),h+=p.move(")"),u(),h}function l9(){return"!"}E5.peek=c9;function E5(e,t,n,s){const o=e.referenceType,c=n.enter("imageReference");let u=n.enter("label");const f=n.createTracker(s);let p=f.move("![");const h=n.safe(e.alt,{before:p,after:"]",...f.current()});p+=f.move(h+"]["),u();const x=n.stack;n.stack=[],u=n.enter("reference");const g=n.safe(n.associationId(e),{before:p,after:"]",...f.current()});return u(),n.stack=x,c(),o==="full"||!h||h!==g?p+=f.move(g+"]"):o==="shortcut"?p=p.slice(0,-1):p+=f.move("]"),p}function c9(){return"!"}A5.peek=u9;function A5(e,t,n){let s=e.value||"",o="`",c=-1;for(;new RegExp("(^|[^`])"+o+"([^`]|$)").test(s);)o+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++c<n.unsafe.length;){const u=n.unsafe[c],f=n.compilePattern(u);let p;if(u.atBreak)for(;p=f.exec(s);){let h=p.index;s.charCodeAt(h)===10&&s.charCodeAt(h-1)===13&&h--,s=s.slice(0,h)+" "+s.slice(p.index+1)}}return o+s+o}function u9(){return"`"}function _5(e,t){const n=fy(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}R5.peek=d9;function R5(e,t,n,s){const o=wy(n),c=o==='"'?"Quote":"Apostrophe",u=n.createTracker(s);let f,p;if(_5(e,n)){const x=n.stack;n.stack=[],f=n.enter("autolink");let g=u.move("<");return g+=u.move(n.containerPhrasing(e,{before:g,after:">",...u.current()})),g+=u.move(">"),f(),n.stack=x,g}f=n.enter("link"),p=n.enter("label");let h=u.move("[");return h+=u.move(n.containerPhrasing(e,{before:h,after:"](",...u.current()})),h+=u.move("]("),p(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(p=n.enter("destinationLiteral"),h+=u.move("<"),h+=u.move(n.safe(e.url,{before:h,after:">",...u.current()})),h+=u.move(">")):(p=n.enter("destinationRaw"),h+=u.move(n.safe(e.url,{before:h,after:e.title?" ":")",...u.current()}))),p(),e.title&&(p=n.enter(`title${c}`),h+=u.move(" "+o),h+=u.move(n.safe(e.title,{before:h,after:o,...u.current()})),h+=u.move(o),p()),h+=u.move(")"),f(),h}function d9(e,t,n){return _5(e,n)?"<":"["}I5.peek=m9;function I5(e,t,n,s){const o=e.referenceType,c=n.enter("linkReference");let u=n.enter("label");const f=n.createTracker(s);let p=f.move("[");const h=n.containerPhrasing(e,{before:p,after:"]",...f.current()});p+=f.move(h+"]["),u();const x=n.stack;n.stack=[],u=n.enter("reference");const g=n.safe(n.associationId(e),{before:p,after:"]",...f.current()});return u(),n.stack=x,c(),o==="full"||!h||h!==g?p+=f.move(g+"]"):o==="shortcut"?p=p.slice(0,-1):p+=f.move("]"),p}function m9(){return"["}function Sy(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function f9(e){const t=Sy(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function p9(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function L5(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function h9(e,t,n,s){const o=n.enter("list"),c=n.bulletCurrent;let u=e.ordered?p9(n):Sy(n);const f=e.ordered?u==="."?")":".":f9(n);let p=t&&n.bulletLastUsed?u===n.bulletLastUsed:!1;if(!e.ordered){const x=e.children?e.children[0]:void 0;if((u==="*"||u==="-")&&x&&(!x.children||!x.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(p=!0),L5(n)===u&&x){let g=-1;for(;++g<e.children.length;){const v=e.children[g];if(v&&v.type==="listItem"&&v.children&&v.children[0]&&v.children[0].type==="thematicBreak"){p=!0;break}}}}p&&(u=f),n.bulletCurrent=u;const h=n.containerFlow(e,s);return n.bulletLastUsed=u,n.bulletCurrent=c,o(),h}function g9(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function x9(e,t,n,s){const o=g9(n);let c=n.bulletCurrent||Sy(n);t&&t.type==="list"&&t.ordered&&(c=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+c);let u=c.length+1;(o==="tab"||o==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(u=Math.ceil(u/4)*4);const f=n.createTracker(s);f.move(c+" ".repeat(u-c.length)),f.shift(u);const p=n.enter("listItem"),h=n.indentLines(n.containerFlow(e,f.current()),x);return p(),h;function x(g,v,w){return v?(w?"":" ".repeat(u))+g:(w?c:c+" ".repeat(u-c.length))+g}}function y9(e,t,n,s){const o=n.enter("paragraph"),c=n.enter("phrasing"),u=n.containerPhrasing(e,s);return c(),o(),u}const b9=Kf(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function v9(e,t,n,s){return(e.children.some(function(u){return b9(u)})?n.containerPhrasing:n.containerFlow).call(n,e,s)}function k9(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}O5.peek=w9;function O5(e,t,n,s){const o=k9(n),c=n.enter("strong"),u=n.createTracker(s),f=u.move(o+o);let p=u.move(n.containerPhrasing(e,{after:o,before:f,...u.current()}));const h=p.charCodeAt(0),x=hf(s.before.charCodeAt(s.before.length-1),h,o);x.inside&&(p=Eu(h)+p.slice(1));const g=p.charCodeAt(p.length-1),v=hf(s.after.charCodeAt(0),g,o);v.inside&&(p=p.slice(0,-1)+Eu(g));const w=u.move(o+o);return c(),n.attentionEncodeSurroundingInfo={after:v.outside,before:x.outside},f+p+w}function w9(e,t,n){return n.options.strong||"*"}function S9(e,t,n,s){return n.safe(e.value,s)}function j9(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function C9(e,t,n){const s=(L5(n)+(n.options.ruleSpaces?" ":"")).repeat(j9(n));return n.options.ruleSpaces?s.slice(0,-1):s}const D5={blockquote:W7,break:gS,code:e9,definition:n9,emphasis:N5,hardBreak:gS,heading:i9,html:T5,image:M5,imageReference:E5,inlineCode:A5,link:R5,linkReference:I5,list:h9,listItem:x9,paragraph:y9,root:v9,strong:O5,text:S9,thematicBreak:C9};function N9(){return{enter:{table:T9,tableData:xS,tableHeader:xS,tableRow:E9},exit:{codeText:A9,table:M9,tableData:Pg,tableHeader:Pg,tableRow:Pg}}}function T9(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function M9(e){this.exit(e),this.data.inTable=void 0}function E9(e){this.enter({type:"tableRow",children:[]},e)}function Pg(e){this.exit(e)}function xS(e){this.enter({type:"tableCell",children:[]},e)}function A9(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,_9));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function _9(e,t){return t==="|"?t:e}function R9(e){const t=e||{},n=t.tableCellPadding,s=t.tablePipeAlign,o=t.stringLength,c=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
164
164
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:v,table:u,tableCell:p,tableRow:f}};function u(w,S,C,N){return h(x(w,C,N),w.align)}function f(w,S,C,N){const T=g(w,C,N),_=h([T]);return _.slice(0,_.indexOf(`
|
|
165
|
-
`))}function p(w,S,C,N){const T=C.enter("tableCell"),_=C.enter("phrasing"),R=C.containerPhrasing(w,{...N,before:c,after:c});return _(),T(),R}function h(w,S){return G7(w,{align:S,alignDelimiters:s,padding:n,stringLength:o})}function x(w,S,C){const N=w.children;let T=-1;const _=[],R=S.enter("table");for(;++T<N.length;)_[T]=g(N[T],S,C);return R(),_}function g(w,S,C){const N=w.children;let T=-1;const _=[],R=S.enter("tableRow");for(;++T<N.length;)_[T]=p(N[T],w,S,C);return R(),_}function v(w,S,C){let N=D5.inlineCode(w,S,C);return C.stack.includes("tableCell")&&(N=N.replace(/\|/g,"\\$&")),N}}function I9(){return{exit:{taskListCheckValueChecked:yS,taskListCheckValueUnchecked:yS,paragraph:O9}}}function L9(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:D9}}}function yS(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function O9(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const o=t.children;let c=-1,u;for(;++c<o.length;){const f=o[c];if(f.type==="paragraph"){u=f;break}}u===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function D9(e,t,n,s){const o=e.children[0],c=typeof e.checked=="boolean"&&o&&o.type==="paragraph",u="["+(e.checked?"x":" ")+"] ",f=n.createTracker(s);c&&f.move(u);let p=D5.listItem(e,t,n,{...s,...f.current()});return c&&(p=p.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,h)),p;function h(x){return x+u}}function $9(){return[h7(),D7(),z7(),N9(),I9()]}function U9(e){return{extensions:[g7(),$7(e),B7(),R9(e),L9()]}}const P9={tokenize:V9,partial:!0},$5={tokenize:G9,partial:!0},U5={tokenize:K9,partial:!0},P5={tokenize:W9,partial:!0},z9={tokenize:Y9,partial:!0},z5={name:"wwwAutolink",tokenize:F9,previous:H5},B5={name:"protocolAutolink",tokenize:q9,previous:F5},Zs={name:"emailAutolink",tokenize:H9,previous:q5},Ns={};function B9(){return{text:Ns}}let lo=48;for(;lo<123;)Ns[lo]=Zs,lo++,lo===58?lo=65:lo===91&&(lo=97);Ns[43]=Zs;Ns[45]=Zs;Ns[46]=Zs;Ns[95]=Zs;Ns[72]=[Zs,B5];Ns[104]=[Zs,B5];Ns[87]=[Zs,z5];Ns[119]=[Zs,z5];function H9(e,t,n){const s=this;let o,c;return u;function u(g){return!P0(g)||!q5.call(s,s.previous)||jy(s.events)?n(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return P0(g)?(e.consume(g),f):g===64?(e.consume(g),p):n(g)}function p(g){return g===46?e.check(z9,x,h)(g):g===45||g===95||kr(g)?(c=!0,e.consume(g),p):x(g)}function h(g){return e.consume(g),o=!0,p}function x(g){return c&&o&&Or(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):n(g)}}function F9(e,t,n){const s=this;return o;function o(u){return u!==87&&u!==119||!H5.call(s,s.previous)||jy(s.events)?n(u):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(P9,e.attempt($5,e.attempt(U5,c),n),n)(u))}function c(u){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(u)}}function q9(e,t,n){const s=this;let o="",c=!1;return u;function u(g){return(g===72||g===104)&&F5.call(s,s.previous)&&!jy(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),o+=String.fromCodePoint(g),e.consume(g),f):n(g)}function f(g){if(Or(g)&&o.length<5)return o+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const v=o.toLowerCase();if(v==="http"||v==="https")return e.consume(g),p}return n(g)}function p(g){return g===47?(e.consume(g),c?h:(c=!0,p)):n(g)}function h(g){return g===null||mf(g)||dn(g)||Eo(g)||qf(g)?n(g):e.attempt($5,e.attempt(U5,x),n)(g)}function x(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function V9(e,t,n){let s=0;return o;function o(u){return(u===87||u===119)&&s<3?(s++,e.consume(u),o):u===46&&s===3?(e.consume(u),c):n(u)}function c(u){return u===null?n(u):t(u)}}function G9(e,t,n){let s,o,c;return u;function u(h){return h===46||h===95?e.check(P5,p,f)(h):h===null||dn(h)||Eo(h)||h!==45&&qf(h)?p(h):(c=!0,e.consume(h),u)}function f(h){return h===95?s=!0:(o=s,s=void 0),e.consume(h),u}function p(h){return o||s||!c?n(h):t(h)}}function K9(e,t){let n=0,s=0;return o;function o(u){return u===40?(n++,e.consume(u),o):u===41&&s<n?c(u):u===33||u===34||u===38||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===60||u===63||u===93||u===95||u===126?e.check(P5,t,c)(u):u===null||dn(u)||Eo(u)?t(u):(e.consume(u),o)}function c(u){return u===41&&s++,e.consume(u),o}}function W9(e,t,n){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),c):f===93?(e.consume(f),o):f===60||f===null||dn(f)||Eo(f)?t(f):n(f)}function o(f){return f===null||f===40||f===91||dn(f)||Eo(f)?t(f):s(f)}function c(f){return Or(f)?u(f):n(f)}function u(f){return f===59?(e.consume(f),s):Or(f)?(e.consume(f),u):n(f)}}function Y9(e,t,n){return s;function s(c){return e.consume(c),o}function o(c){return kr(c)?n(c):t(c)}}function H5(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||dn(e)}function F5(e){return!Or(e)}function q5(e){return!(e===47||P0(e))}function P0(e){return e===43||e===45||e===46||e===95||kr(e)}function jy(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const X9={tokenize:aU,partial:!0};function Q9(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:tU,continuation:{tokenize:nU},exit:rU}},text:{91:{name:"gfmFootnoteCall",tokenize:eU},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Z9,resolveTo:J9}}}}function Z9(e,t,n){const s=this;let o=s.events.length;const c=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u;for(;o--;){const p=s.events[o][1];if(p.type==="labelImage"){u=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return f;function f(p){if(!u||!u._balanced)return n(p);const h=Ja(s.sliceSerialize({start:u.end,end:s.now()}));return h.codePointAt(0)!==94||!c.includes(h.slice(1))?n(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function J9(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;const c={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},e[e.length-1][1].start)},u={type:"chunkString",contentType:"string",start:Object.assign({},c.start),end:Object.assign({},c.end)},f=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",o,t],["exit",o,t],["enter",c,t],["enter",u,t],["exit",u,t],["exit",c,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...f),e}function eU(e,t,n){const s=this,o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c=0,u;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),p}function p(g){return g!==94?n(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",h)}function h(g){if(c>999||g===93&&!u||g===null||g===91||dn(g))return n(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteCallString");return o.includes(Ja(s.sliceSerialize(v)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(g)}return dn(g)||(u=!0),c++,e.consume(g),g===92?x:h}function x(g){return g===91||g===92||g===93?(e.consume(g),c++,h):h(g)}}function tU(e,t,n){const s=this,o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c,u=0,f;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),h}function h(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",x):n(S)}function x(S){if(u>999||S===93&&!f||S===null||S===91||dn(S))return n(S);if(S===93){e.exit("chunkString");const C=e.exit("gfmFootnoteDefinitionLabelString");return c=Ja(s.sliceSerialize(C)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),v}return dn(S)||(f=!0),u++,e.consume(S),S===92?g:x}function g(S){return S===91||S===92||S===93?(e.consume(S),u++,x):x(S)}function v(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),o.includes(c)||o.push(c),Ut(e,w,"gfmFootnoteDefinitionWhitespace")):n(S)}function w(S){return t(S)}}function nU(e,t,n){return e.check(Xu,t,e.attempt(X9,t,n))}function rU(e){e.exit("gfmFootnoteDefinition")}function aU(e,t,n){const s=this;return Ut(e,o,"gfmFootnoteDefinitionIndent",5);function o(c){const u=s.events[s.events.length-1];return u&&u[1].type==="gfmFootnoteDefinitionIndent"&&u[2].sliceSerialize(u[1],!0).length===4?t(c):n(c)}}function sU(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:c,resolveAll:o};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function o(u,f){let p=-1;for(;++p<u.length;)if(u[p][0]==="enter"&&u[p][1].type==="strikethroughSequenceTemporary"&&u[p][1]._close){let h=p;for(;h--;)if(u[h][0]==="exit"&&u[h][1].type==="strikethroughSequenceTemporary"&&u[h][1]._open&&u[p][1].end.offset-u[p][1].start.offset===u[h][1].end.offset-u[h][1].start.offset){u[p][1].type="strikethroughSequence",u[h][1].type="strikethroughSequence";const x={type:"strikethrough",start:Object.assign({},u[h][1].start),end:Object.assign({},u[p][1].end)},g={type:"strikethroughText",start:Object.assign({},u[h][1].end),end:Object.assign({},u[p][1].start)},v=[["enter",x,f],["enter",u[h][1],f],["exit",u[h][1],f],["enter",g,f]],w=f.parser.constructs.insideSpan.null;w&&xa(v,v.length,0,Vf(w,u.slice(h+1,p),f)),xa(v,v.length,0,[["exit",g,f],["enter",u[p][1],f],["exit",u[p][1],f],["exit",x,f]]),xa(u,h-1,p-h+3,v),p=h+v.length-2;break}}for(p=-1;++p<u.length;)u[p][1].type==="strikethroughSequenceTemporary"&&(u[p][1].type="data");return u}function c(u,f,p){const h=this.previous,x=this.events;let g=0;return v;function v(S){return h===126&&x[x.length-1][1].type!=="characterEscape"?p(S):(u.enter("strikethroughSequenceTemporary"),w(S))}function w(S){const C=Il(h);if(S===126)return g>1?p(S):(u.consume(S),g++,w);if(g<2&&!n)return p(S);const N=u.exit("strikethroughSequenceTemporary"),T=Il(S);return N._open=!T||T===2&&!!C,N._close=!C||C===2&&!!T,f(S)}}}class iU{constructor(){this.map=[]}add(t,n,s){oU(this,t,n,s)}consume(t){if(this.map.sort(function(c,u){return c[0]-u[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let o=s.pop();for(;o;){for(const c of o)t.push(c);o=s.pop()}this.map.length=0}}function oU(e,t,n,s){let o=0;if(!(n===0&&s.length===0)){for(;o<e.map.length;){if(e.map[o][0]===t){e.map[o][1]+=n,e.map[o][2].push(...s);return}o+=1}e.map.push([t,n,s])}}function lU(e,t){let n=!1;const s=[];for(;t<e.length;){const o=e[t];if(n){if(o[0]==="enter")o[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(o[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const c=s.length-1;s[c]=s[c]==="left"?"center":"right"}}else if(o[1].type==="tableDelimiterRow")break}else o[0]==="enter"&&o[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function cU(){return{flow:{null:{name:"table",tokenize:uU,resolveAll:dU}}}}function uU(e,t,n){const s=this;let o=0,c=0,u;return f;function f(P){let B=s.events.length-1;for(;B>-1;){const K=s.events[B][1].type;if(K==="lineEnding"||K==="linePrefix")B--;else break}const Y=B>-1?s.events[B][1].type:null,q=Y==="tableHead"||Y==="tableRow"?E:p;return q===E&&s.parser.lazy[s.now().line]?n(P):q(P)}function p(P){return e.enter("tableHead"),e.enter("tableRow"),h(P)}function h(P){return P===124||(u=!0,c+=1),x(P)}function x(P){return P===null?n(P):ot(P)?c>1?(c=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),w):n(P):Rt(P)?Ut(e,x,"whitespace")(P):(c+=1,u&&(u=!1,o+=1),P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),u=!0,x):(e.enter("data"),g(P)))}function g(P){return P===null||P===124||dn(P)?(e.exit("data"),x(P)):(e.consume(P),P===92?v:g)}function v(P){return P===92||P===124?(e.consume(P),g):g(P)}function w(P){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(P):(e.enter("tableDelimiterRow"),u=!1,Rt(P)?Ut(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):S(P))}function S(P){return P===45||P===58?N(P):P===124?(u=!0,e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),C):z(P)}function C(P){return Rt(P)?Ut(e,N,"whitespace")(P):N(P)}function N(P){return P===58?(c+=1,u=!0,e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),T):P===45?(c+=1,T(P)):P===null||ot(P)?D(P):z(P)}function T(P){return P===45?(e.enter("tableDelimiterFiller"),_(P)):z(P)}function _(P){return P===45?(e.consume(P),_):P===58?(u=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),R):(e.exit("tableDelimiterFiller"),R(P))}function R(P){return Rt(P)?Ut(e,D,"whitespace")(P):D(P)}function D(P){return P===124?S(P):P===null||ot(P)?!u||o!==c?z(P):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(P)):z(P)}function z(P){return n(P)}function E(P){return e.enter("tableRow"),L(P)}function L(P){return P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),L):P===null||ot(P)?(e.exit("tableRow"),t(P)):Rt(P)?Ut(e,L,"whitespace")(P):(e.enter("data"),F(P))}function F(P){return P===null||P===124||dn(P)?(e.exit("data"),L(P)):(e.consume(P),P===92?V:F)}function V(P){return P===92||P===124?(e.consume(P),F):F(P)}}function dU(e,t){let n=-1,s=!0,o=0,c=[0,0,0,0],u=[0,0,0,0],f=!1,p=0,h,x,g;const v=new iU;for(;++n<e.length;){const w=e[n],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,p!==0&&(bS(v,t,p,h,x),x=void 0,p=0),h={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},v.add(n,0,[["enter",h,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,c=[0,0,0,0],u=[0,n+1,0,0],f&&(f=!1,x={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},v.add(n,0,[["enter",x,t]])),o=S.type==="tableDelimiterRow"?2:x?3:1):o&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,u[2]===0&&(c[1]!==0&&(u[0]=u[1],g=Cm(v,t,c,o,void 0,g),c=[0,0,0,0]),u[2]=n)):S.type==="tableCellDivider"&&(s?s=!1:(c[1]!==0&&(u[0]=u[1],g=Cm(v,t,c,o,void 0,g)),c=u,u=[c[1],n,0,0])):S.type==="tableHead"?(f=!0,p=n):S.type==="tableRow"||S.type==="tableDelimiterRow"?(p=n,c[1]!==0?(u[0]=u[1],g=Cm(v,t,c,o,n,g)):u[1]!==0&&(g=Cm(v,t,u,o,n,g)),o=0):o&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(u[3]=n)}for(p!==0&&bS(v,t,p,h,x),v.consume(t.events),n=-1;++n<t.events.length;){const w=t.events[n];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=lU(t.events,n))}return e}function Cm(e,t,n,s,o,c){const u=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";n[0]!==0&&(c.end=Object.assign({},hl(t.events,n[0])),e.add(n[0],0,[["exit",c,t]]));const p=hl(t.events,n[1]);if(c={type:u,start:Object.assign({},p),end:Object.assign({},p)},e.add(n[1],0,[["enter",c,t]]),n[2]!==0){const h=hl(t.events,n[2]),x=hl(t.events,n[3]),g={type:f,start:Object.assign({},h),end:Object.assign({},x)};if(e.add(n[2],0,[["enter",g,t]]),s!==2){const v=t.events[n[2]],w=t.events[n[3]];if(v[1].end=Object.assign({},w[1].end),v[1].type="chunkText",v[1].contentType="text",n[3]>n[2]+1){const S=n[2]+1,C=n[3]-n[2]-1;e.add(S,C,[])}}e.add(n[3]+1,0,[["exit",g,t]])}return o!==void 0&&(c.end=Object.assign({},hl(t.events,o)),e.add(o,0,[["exit",c,t]]),c=void 0),c}function bS(e,t,n,s,o){const c=[],u=hl(t.events,n);o&&(o.end=Object.assign({},u),c.push(["exit",o,t])),s.end=Object.assign({},u),c.push(["exit",s,t]),e.add(n+1,0,c)}function hl(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const mU={name:"tasklistCheck",tokenize:pU};function fU(){return{text:{91:mU}}}function pU(e,t,n){const s=this;return o;function o(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),c)}function c(p){return dn(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),u):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),u):n(p)}function u(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):n(p)}function f(p){return ot(p)?t(p):Rt(p)?e.check({tokenize:hU},t,n)(p):n(p)}}function hU(e,t,n){return Ut(e,s,"whitespace");function s(o){return o===null?n(o):t(o)}}function gU(e){return t5([B9(),Q9(),sU(e),cU(),fU()])}const xU={};function yU(e){const t=this,n=e||xU,s=t.data(),o=s.micromarkExtensions||(s.micromarkExtensions=[]),c=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),u=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);o.push(gU(n)),c.push($9()),u.push(U9(n))}const bU=/[^\x00-\x7F]+$/;function vU(e){if(e.children.length!==1)return!1;const t=e.children[0];if(!t||t.type!=="text")return!1;const{value:n}=t;return e.url===n||e.url===`http://${n}`}function kU(e){if(!vU(e))return null;const t=e.children[0],n=bU.exec(t.value);if(!n)return null;const s=t.value.slice(0,n.index);return!s.includes("://")&&!s.startsWith("www.")?null:(t.value=s,e.url=e.url.startsWith("http://")&&!s.startsWith("http")?`http://${s}`:s,{type:"text",value:n[0]})}function V5(e){for(let t=0;t<e.children.length;t+=1){const n=e.children[t];if(n.type==="link"){const o=kU(n);o&&e.children.splice(t+1,0,o)}const s=n.children;Array.isArray(s)&&V5(n)}}function wU(){return e=>V5(e)}const Ju=[yU,wU],SU="modulepreload",jU=function(e){return"/"+e},vS={},an=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){let p=function(h){return Promise.all(h.map(x=>Promise.resolve(x).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),f=u?.nonce||u?.getAttribute("nonce");o=p(n.map(h=>{if(h=jU(h),h in vS)return;vS[h]=!0;const x=h.endsWith(".css"),g=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${g}`))return;const v=document.createElement("link");if(v.rel=x?"stylesheet":SU,x||(v.as="script"),v.crossOrigin="",v.href=h,f&&v.setAttribute("nonce",f),document.head.appendChild(v),x)return new Promise((w,S)=>{v.addEventListener("load",w),v.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function c(u){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=u,window.dispatchEvent(f),!f.defaultPrevented)throw u}return o.then(u=>{for(const f of u||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})};function Cy({language:e,code:t,highlight:n=!0}){const[s,o]=y.useState();return y.useEffect(()=>{if(!n){o(void 0);return}let c=!0;return an(()=>import("./highlighter-DpnM5FfD.js"),[]).then(u=>u.highlightToHtml(t,e)).then(u=>{c&&o(u)}).catch(()=>{c&&o(void 0)}),()=>{c=!1}},[t,e,n]),a.jsxs("div",{className:"code-block my-2 overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 bg-gray-50 px-3 py-1 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("span",{className:"font-mono text-xs lowercase text-gray-500 dark:text-gray-400",children:e||"text"}),a.jsx(Wu,{text:t,label:d.chat.copyCode})]}),a.jsx("div",{className:"overflow-x-auto bg-white text-[13px] leading-relaxed dark:bg-gray-950",children:s?a.jsx("div",{dangerouslySetInnerHTML:{__html:s}}):a.jsx("pre",{className:"m-0 px-3 py-2.5 font-mono text-gray-800 dark:text-gray-200",children:a.jsx("code",{children:t})})})]})}function CU(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):""}function G5({children:e,streaming:t}){if(y.isValidElement(e)){const n=e.props,s=/language-([\w+-]+)/.exec(n.className??"")?.[1]??"";return a.jsx(Cy,{language:s,code:CU(n.children).replace(/\n$/,""),highlight:!t})}return a.jsx("pre",{children:e})}function K5({node:e,children:t,...n}){return a.jsx("a",{...n,target:"_blank",rel:"noreferrer",children:t})}const NU={pre:e=>a.jsx(G5,{streaming:!0,children:e.children}),a:K5},TU={pre:e=>a.jsx(G5,{streaming:!1,children:e.children}),a:K5},ed=y.memo(function({text:t,streaming:n=!1}){return a.jsx(Zu,{remarkPlugins:Ju,components:n?NU:TU,children:t})});function Ys({src:e,alt:t,className:n}){const[s,o]=y.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"block cursor-zoom-in",onClick:()=>o(!0),children:a.jsx("img",{src:e,alt:t,className:n})}),s&&a.jsx(MU,{src:e,alt:t,onClose:()=>o(!1)})]})}function MU({src:e,alt:t,onClose:n}){return y.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]),ss.createPortal(a.jsx("div",{className:"anim-fade fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-10",onMouseDown:s=>{s.target===s.currentTarget&&n()},children:a.jsxs("div",{className:"anim-pop relative",children:[a.jsx("button",{type:"button","aria-label":d.common.close,onClick:n,className:"absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/50 text-white transition-colors duration-150 hover:bg-black/70",children:a.jsx(Hl,{})}),a.jsx("img",{src:e,alt:t,className:"max-h-[85vh] max-w-[88vw] rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900"})]})}),document.body)}const EU=new Set(["txt","md","json","js","mjs","cjs","ts","tsx","jsx","py","sh","bash","yaml","yml","toml","css","html","htm","csv","log","xml","ini","conf","rs","go","java","c","h","cpp","hpp","sql","rb","php","png","jpg","jpeg","gif","webp","svg","pdf","doc","docx","xls","xlsx","ppt","pptx","zip","tar","gz","mp4","mp3","wav"]),AU=/^[a-z][a-z0-9+.-]*:\/\//i;function _U(e){const t=e.trim();if(t.length===0||t.length>200||/\s/.test(t)||AU.test(t)||t.startsWith("www."))return!1;const n=/\.([A-Za-z0-9]{1,8})$/.exec(t);if(!n)return!1;const s=n[1].toLowerCase();return/^\d+$/.test(s)?!1:EU.has(s)}function Ym(e,t){return e===""?t:`${e}/${t}`}const RU=512;function IU(e,t){const n=e.trim();if(n.length===0||n.length>RU||n.startsWith("~"))return null;const s=t!==null&&t.length>0?t:null,o=s!==null&&(s.includes("\\")||/^[A-Za-z]:/.test(s)),c=g=>{if(!o)return g;const v=g.replaceAll("\\","/");return/^[A-Za-z]:/.test(v)?v[0].toLowerCase()+v.slice(1):v},u=c(n),f=s===null?null:c(s),p=u.startsWith("/")||o&&/^[a-z]:/.test(u);let h=u;if(p){if(f===null||!u.startsWith(`${f}/`))return null;h=u.slice(f.length+1)}const x=[];for(const g of h.split("/"))if(!(g===""||g===".")){if(g===".."){if(x.length===0)return null;x.pop();continue}x.push(g)}return x.length>0?x.join("/"):null}const kS="M6 3h8l4 4v14H6zM14 3v4h4",wS=3;function LU(e){const t=[],n=new Set;for(const s of e.matchAll(/`([^`\n]+)`/g)){const o=s[1].trim();!_U(o)||n.has(o)||(n.add(o),t.push(o))}return t}function W5({path:e}){const t=e.lastIndexOf("/"),n=t>=0?e.slice(0,t+1):"",s=t>=0?e.slice(t+1):e;return a.jsxs("span",{className:"flex min-w-0 items-baseline font-mono text-sm",children:[n&&a.jsx("span",{className:"min-w-0 shrink-[9999] truncate text-gray-400 dark:text-gray-500",children:n}),a.jsx("span",{className:"min-w-0 truncate font-semibold text-gray-800 dark:text-gray-100",children:s})]})}function SS({text:e,workspace:t,statFiles:n,onOpenFile:s}){const o=y.useMemo(()=>{const g=[],v=new Set;for(const w of LU(e)){const S=IU(w,t);S===null||v.has(S)||(v.add(S),g.push(S))}return g},[e,t]),[c,u]=y.useState(null);y.useEffect(()=>{if(u(null),o.length===0)return;let g=!1;return n(o).then(v=>{g||u(o.filter(w=>v.has(w)))}).catch(()=>{}),()=>{g=!0}},[o,n]);const[f,p]=y.useState(!1);if(c===null||c.length===0)return null;const h=f?c:c.slice(0,wS),x=c.length-h.length;return a.jsxs("div",{className:"anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40",children:[a.jsx(Oe,{d:kS,size:Ye.rowLead,className:"text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:d.chat.filesInMessage(c.length)})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[h.map(g=>a.jsxs("button",{type:"button",title:g,onClick:()=>s(g),className:"group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[a.jsx(Oe,{d:kS,size:Ye.rowLead,className:"text-gray-400"}),a.jsx(W5,{path:g}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300",children:d.chat.openPreview})]},g)),(x>0||f)&&c.length>wS&&a.jsxs("button",{type:"button",onClick:()=>p(g=>!g),className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50",children:[f?d.chat.showLess:d.chat.showMoreFiles(x),a.jsx(Zn,{open:f,size:Ye.chevronDense})]})]})]})}function Y5(e){return e.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---\r?\n?/,"")}function OU(e){return e?.target!=null?{kind:"detail",target:e.target}:{kind:"list"}}function DU(){return{kind:"list"}}function z0(e,t){return e.scope==="user"?{scope:"user",file:t}:{scope:"workspace",scopeKey:e.scopeKey,file:t}}function $U(e,t){if(e===null){const s=[];for(const o of t){const c=o.scope==="user"?"user":o.scopeKey??"";let u=s.find(f=>f.scope===o.scope&&f.scopeKey===c);u===void 0&&(u={scope:o.scope,scopeKey:c,rows:[]},o.scope==="user"?s.unshift(u):s.push(u)),u.rows.push({target:z0(u,o.file),title:o.file,changed:o.op})}return s}const n=new Map(t.map(s=>[Qa(s),s.op]));return e.map(({info:s,files:o})=>{const c={scope:s.kind,scopeKey:s.scopeKey,...s.workspacePath!==void 0?{workspacePath:s.workspacePath}:{},rows:[]};for(const u of o){const f=z0(c,u.name),p=n.get(Qa(f));c.rows.push({target:f,title:u.title,...u.description!==""?{description:u.description}:{},...u.updatedAt!==void 0?{updatedAt:u.updatedAt}:{},modifiedAt:u.modifiedAt,...p!==void 0?{changed:p}:{}})}return c})}function UU(e,t){if(e===null)return null;const n=new Set;for(const{info:o,files:c}of e){const u={scope:o.kind,scopeKey:o.scopeKey};for(const f of c)n.add(Qa(z0(u,f.name)))}const s=new Set;for(const o of t){const c=Qa(o);n.has(c)||s.add(c)}return s}const X5="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z",Q5="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",PU="M14 4h6v6M20 4 10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3",zU="M19 12H5m6-6-6 6 6 6";function Z5(e,t){return{d:e==="user"?X5:Q5,title:e==="user"?d.memory.userScope:d.chat.memoryScopeWorkspace(t??"")}}function BU(e){return e.scope==="user"?d.memory.userScope:e.workspacePath?.split(/[\\/]/).filter(Boolean).at(-1)??e.scopeKey}function HU({session:e,changes:t,scopes:n,listingError:s,request:o,active:c,onOpenSettings:u}){const{locale:f}=Dr(),[p,h]=y.useState({kind:"list"});y.useEffect(()=>{o!==null&&h(OU(o))},[o]);const x=p.kind==="detail"?Qa(p.target):null,[g,v]=y.useState(null);y.useEffect(()=>{if(!c||p.kind!=="detail")return;const S=p.target,C=Qa(S);let N=!1;return v({key:C,content:null,failed:!1}),nC(e.projectId,e.agentId,S.scope==="user"?"user":S.scopeKey??"",S.file).then(T=>{N||v({key:C,content:T.content,failed:!1})}).catch(()=>{N||v({key:C,content:null,failed:!0})}),()=>{N=!0}},[c,x,e.projectId,e.agentId,t]);const w=$U(n,t);if(p.kind==="detail"){const S=p.target,C=w.flatMap(_=>_.rows).find(_=>Qa(_.target)===x),N=g!==null&&g.key===x,T=Z5(S.scope,S.scopeKey);return a.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-gray-100 px-3 py-2 dark:border-gray-800/60",children:[a.jsxs("button",{type:"button",onClick:()=>h(DU()),title:d.chat.memoryBack,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:zU,size:Ye.iconButton}),a.jsx("span",{className:"sr-only",children:d.chat.memoryBack})]}),a.jsxs("span",{title:T.title,className:"shrink-0 text-gray-400",children:[a.jsx(Oe,{d:T.d,size:Ye.rowLead}),a.jsx("span",{className:"sr-only",children:T.title})]}),a.jsx("p",{className:"min-w-0 flex-1 truncate font-mono text-[13px] font-semibold",children:C?.title??S.file}),C&&(C.updatedAt!==void 0||C.modifiedAt!==void 0)&&a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:C.updatedAt??(C.modifiedAt!==void 0?Al(C.modifiedAt,f):"")})]}),a.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-3.5 py-3",children:[C?.description!==void 0&&a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:C.description}),!N||!g.failed&&g.content===null?a.jsx(Sr,{rows:3}):g.failed?a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.chat.memoryContentUnavailable}):a.jsx("div",{className:"md-body text-sm",children:a.jsx(ed,{text:Y5(g.content??"")})})]})]})}return a.jsxs("div",{className:"h-full min-h-0 overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center gap-1 px-3.5 pb-1 pt-2",children:[a.jsx("span",{className:"min-w-0 flex-1"}),u&&a.jsxs("button",{type:"button",onClick:u,title:d.chat.openAgentMemory,className:"flex min-w-0 cursor-pointer items-center gap-1 rounded-md px-1.5 py-1 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:PU,size:Ye.inlineGlyph}),a.jsx("span",{className:"truncate",children:d.chat.openAgentMemory})]})]}),s!==null&&w.length===0?a.jsx("p",{className:"px-3.5 py-2 text-xs text-gray-500 dark:text-gray-400",children:s}):n===null&&w.length===0?a.jsx("div",{className:"px-3.5 py-2",children:a.jsx(Sr,{rows:3})}):w.every(S=>S.rows.length===0)?a.jsx("p",{className:"px-3.5 py-2 text-xs text-gray-400 dark:text-gray-500",children:d.chat.memoryEmptyAll}):w.map(S=>S.rows.length===0?null:a.jsxs("div",{className:"pb-2",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3.5 py-1.5",children:[a.jsx("span",{className:"shrink-0 text-gray-400",children:a.jsx(Oe,{d:S.scope==="user"?X5:Q5,size:Ye.inlineGlyph})}),a.jsx("p",{className:"min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400",title:S.workspacePath,children:BU(S)}),a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:d.memory.itemCount(S.rows.length)})]}),a.jsx("ul",{children:S.rows.map(C=>a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>h({kind:"detail",target:C.target}),className:"flex w-full cursor-pointer items-center gap-3 px-3.5 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("p",{className:"flex items-center gap-1.5 truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200",children:[C.changed!==void 0&&a.jsx("span",{title:d.chat.memoryChangedMark,className:"h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500",children:a.jsx("span",{className:"sr-only",children:d.chat.memoryChangedMark})}),a.jsx("span",{className:"min-w-0 truncate",children:C.title})]}),C.description!==void 0&&a.jsx("p",{className:"truncate text-xs text-gray-500 dark:text-gray-400",children:C.description})]}),(C.updatedAt!==void 0||C.modifiedAt!==void 0)&&a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:C.updatedAt??(C.modifiedAt!==void 0?Al(C.modifiedAt,f):"")})]})},Qa(C.target)))})]},`${S.scope} ${S.scopeKey}`))]})}const jS=3,CS="M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z",FU="M6 3h8l4 4v14H6zM12 11v6M9 14h6",qU="M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";function VU({rows:e,deletedKeys:t,onLocateChange:n,onOpenPanel:s}){const[o,c]=y.useState(!1),u=t?e.filter(x=>!t.has(Qa(x))):e;if(u.length===0)return null;const f=o?u:u.slice(0,jS),p=u.length-f.length,h=x=>{const g=Z5(x.scope,x.scopeKey);return a.jsxs(a.Fragment,{children:[a.jsxs("span",{title:g.title,className:"shrink-0 text-gray-400",children:[a.jsx(Oe,{d:g.d,size:Ye.rowLead}),a.jsx("span",{className:"sr-only",children:g.title})]}),a.jsx(W5,{path:x.file}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("span",{title:x.op==="write"?d.chat.memoryOpWrite:d.chat.memoryOpEdit,className:"shrink-0 text-gray-400",children:a.jsx(Oe,{d:x.op==="write"?FU:qU,size:Ye.inlineGlyph})})]})};return a.jsxs("div",{className:"anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40",children:[a.jsx(Oe,{d:CS,size:Ye.rowLead,className:"shrink-0 text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:d.chat.memoryChangesTitle(u.length)}),s&&a.jsxs("button",{type:"button",title:d.chat.memoryViewTitle,onClick:s,className:"flex h-6 w-6 shrink-0 cursor-pointer items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300",children:[a.jsx(Oe,{d:CS,size:Ye.inlineGlyph}),a.jsx("span",{className:"sr-only",children:d.chat.memoryViewTitle})]})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[f.map(x=>{const g=Qa(x);return n?a.jsxs("button",{type:"button",title:d.chat.memoryRowOpen,onClick:()=>n(x),className:"group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[h(x),a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300",children:d.chat.memoryRowOpen})]},g):a.jsx("div",{className:"flex w-full items-center gap-2 px-3 py-2",children:h(x)},g)}),(p>0||o)&&u.length>jS&&a.jsxs("button",{type:"button",onClick:()=>c(x=>!x),className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50",children:[o?d.chat.showLess:d.chat.memoryShowMore(p),a.jsx(Zn,{open:o,className:"text-gray-400",size:Ye.chevronDense})]})]})]})}const GU={waiting:"M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",done:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm-3.5-9.2 2.4 2.5 4.6-4.8",failed:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9 9l6 6m0-6-6 6",stopped:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM8.5 8.5h7v7h-7z"},NS={running:sn.busy,waiting:sn.attention,done:sn.muted,failed:sn.danger,stopped:sn.muted};function Di({state:e,size:t=13,label:n}){return e==="running"?a.jsx("span",{...n?{title:n,"aria-label":n,role:"status"}:{"aria-hidden":!0},style:{width:t,height:t},className:`inline-block shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent ${NS.running}`}):a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",...n?{role:"img","aria-label":n}:{"aria-hidden":!0},className:`block shrink-0 ${NS[e]}`,children:[n&&a.jsx("title",{children:n}),a.jsx("path",{d:GU[e]})]})}const J5="flex w-full items-center gap-2 bg-white px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800",eT="sticky top-4 z-[4]",KU="shrink-0 text-xs text-gray-500 dark:text-gray-400",tT="flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800",nT="sticky -top-4 z-[5]",rT="shrink-0 text-[11px] font-semibold uppercase tracking-wide",aT="max-h-72 overflow-auto whitespace-pre-wrap border-t border-gray-100 px-3 py-2 text-xs leading-5 text-gray-600 dark:border-gray-800 dark:text-gray-300",sT="anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900";function iT({icon:e,label:t,trailing:n,variant:s="row",sticky:o=!1,defaultOpen:c=!1,children:u}){const[f,p]=y.useState(c),h=y.useRef(null),x=s==="header",g=x?tT:J5,v=x?nT:eT,w=x?`${rT} text-gray-500 dark:text-gray-400`:KU;return a.jsxs("div",{ref:h,children:[a.jsxs("button",{type:"button",onClick:()=>{const S=f;p(C=>!C),S&&requestAnimationFrame(()=>h.current?.scrollIntoView({block:"nearest"}))},"aria-expanded":f,className:`${o?`${v} `:""}${g}`,children:[e,a.jsx("span",{className:w,children:t}),n,a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx(Zn,{open:f,className:"text-gray-400"})]}),f&&u]})}function Ll({sinceMs:e,offsetMs:t=0}){const[n,s]=y.useState(()=>Date.now());return y.useEffect(()=>{const o=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(o)},[]),e===void 0?a.jsx("span",{className:"animate-pulse",children:"…"}):a.jsx(a.Fragment,{children:ZC(Math.max(0,t)+Math.max(0,n-e))})}function WU({item:e}){const t=e.stopReason!==void 0&&e.stopReason!=="completed",n=e.streaming?"running":t?"failed":"done",s=e.streaming?d.chat.workRunning:t?e.stopReason:d.chat.workDone;return a.jsx(iT,{sticky:!0,icon:a.jsx(Di,{state:n,label:s}),label:d.chat.thinking,trailing:a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400",children:e.streaming?a.jsx(Ll,{sinceMs:e.startedAtMs}):e.durationMs!==void 0?Pn(e.durationMs):null}),t&&a.jsxs("span",{className:"font-mono text-xs text-gray-400",children:["[",e.stopReason,"]"]})]}),children:a.jsx("div",{className:"md-body anim-fade mx-3 mb-2 rounded-md bg-gray-50 px-3 py-2 text-sm leading-relaxed text-gray-600 dark:bg-gray-900/60 dark:text-gray-400",children:a.jsx(ed,{text:e.thinking,streaming:e.streaming})})})}const YU=/\x1b(?:\[[0-9:;<=>?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\^_])/g,XU=/\x1b(?:\[[0-9:;<=>?]*[ -/]*|\][^\x07]*)?$/;function oT(e){return e.includes("\x1B")?e.replace(YU,"").replace(XU,""):e}function QU({onDecide:e}){const[t,n]=y.useState(!1),s=async o=>{n(!0);try{await e(o)}finally{n(!1)}};return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ge,{size:"sm",variant:"primary",disabled:t,onClick:()=>{s("allow")},children:d.chat.approve}),a.jsx(ge,{size:"sm",disabled:t,onClick:()=>{s("deny")},children:d.chat.deny})]})}const ZU=rL,JU=iL;function eP(e,t){const n=t.trim().toLowerCase();return n?e.filter(s=>s.agentId.toLowerCase().includes(n)||(s.name??"").toLowerCase().includes(n)):e}function tP({handoffTarget:e,pendingModel:t,canSwitchModel:n,sessionBusy:s}){return e?"handoff":!t||!n?"post":s?"blocked":"model"}const nP="background_task_done";function Au(e){return e.kind==="user_image"?!0:e.kind!=="user_text"?!1:e.text.includes(`[${nP}]`)?_l(e.text)===null:!0}function lT(e){for(let t=e.length-1;t>=0;t--)if(Au(e[t]))return t;return 0}function rP(e){let t=0;for(const n of e)(n.kind==="user_text"||n.kind==="user_image")&&(t+=1);return t}function aP(e){let t=0;for(const n of e)Au(n)&&(t+=1);return t}function Ny(e,t){try{const n=JSON.parse(e);if(n!==null&&typeof n=="object"){const s=n[t];if(typeof s=="string"&&s.length>0)return s}}catch{}return null}function cT(e){return Ny(e,"agent_id")}function sP(e){return Ny(e,"description")}function TS(e,t,n){for(let s=t;s<n;s++){const o=e[s];if(o.kind==="tool_call"&&o.subagent!==void 0||o.kind==="subagent")return!0}return!1}function iP(e,t,n,s){const o=e.items;let c=lT(o),u=o.length;if(!TS(o,c,u))for(let f=c;f>0;){let p=0;for(let h=f-1;h>=0;h--)if(Au(o[h])){p=h;break}if(TS(o,p,f)){c=p,u=f;break}if(p===0)break;f=p}return uT(o.slice(c,u),t,{running:u===o.length&&n},s)}function oP(e,t,n,s,o){const c=e.items,u=c.findIndex(h=>h.kind==="tool_call"&&h.subagentSessionId===s||h.kind==="subagent"&&h.sessionId===s);if(u===-1)return null;let f=0;for(let h=u;h>=0;h--)if(Au(c[h])){f=h;break}let p=c.length;for(let h=u+1;h<c.length;h++)if(Au(c[h])){p=h;break}return uT(c.slice(f,p),t,{running:p===c.length&&n},o)}const lP=/\[subagent running in background with subagent_id (subagent-[0-9a-f]+)/;function cP(e){const t=new Map;for(const n of e){if(n.kind==="user_text"||n.kind==="background_notice"){const s=_l(n.text);s!==null&&s.done.kind==="subagent"&&t.set(s.done.id,"done");continue}if(!(n.kind!=="tool_call"||n.output.length===0)){for(const s of n.output.matchAll(/\[subagent (?:running in background|still running) with subagent_id (subagent-[0-9a-f]+)/g))t.set(s[1],"running");for(const s of n.output.matchAll(/\[subagent idle with subagent_id (subagent-[0-9a-f]+)|\[subagent (subagent-[0-9a-f]+) (?:aborted and removed|was idle; session removed)/g))t.set(s[1]??s[2],"done")}}return t}function uT(e,t,n,s){const o=[{sessionId:t,agentId:null,description:null,spawnThinkingLevel:null,running:n.running,depth:0,origin:[],parentId:null}],c=new Set([t]),u=(h,x,g,v,w,S,C,N)=>{if(c.has(h))return;c.add(h);const T=[...w,h],_=x.firstTsMs??x.firstSeenLocalMs,R=x.firstTsMs!==void 0&&x.lastActivityTsMs!==void 0?Math.max(0,x.lastActivityTsMs-x.firstTsMs):x.firstSeenLocalMs!==void 0&&x.lastActivityLocalMs!==void 0?Math.max(0,x.lastActivityLocalMs-x.firstSeenLocalMs):void 0;o.push({sessionId:h,agentId:x.meta?.agentId??S,description:C,spawnThinkingLevel:N,running:s?.get(h)??g,depth:T.length,origin:T,parentId:v,..._!==void 0?{startedMs:_}:{},...R!==void 0?{elapsedMs:R}:{}}),p(x.items,h,T)},f=cP(e),p=(h,x,g)=>{for(const v of h)if(v.kind==="tool_call"&&v.subagent&&v.subagentSessionId){const w=lP.exec(v.output)?.[1]??null;u(v.subagentSessionId,v.subagent,w!==null?f.get(w)!=="done":!v.outputComplete,x,g,cT(v.argumentsText),sP(v.argumentsText),Ny(v.argumentsText,"thinking_level"))}else v.kind==="subagent"&&u(v.sessionId,v.model,!1,x,g,null,null,null)};return p(e,t,[]),o}function uP(e){const t=e.items;for(let n=lT(t);n<t.length;n++){const s=t[n];if(s.kind==="tool_call"&&s.subagent!==void 0||s.kind==="subagent")return!0}return!1}function dP(e,t){if(t.length===0)return null;let n=e;for(const s of t){const o=n.subagents.get(s);if(!o)return null;n=o}return n}const Xm=200,iu=46,zg=32,MS=10,Nm=6;function mP(e){const t=new Map;for(const x of e){if(x.parentId===null)continue;const g=t.get(x.parentId);g?g.push(x):t.set(x.parentId,[x])}const n=new Map;let s=0;const o=x=>{const g=t.get(x.sessionId)??[];let v;if(g.length===0)v=s++;else{const w=g.map(o);v=(w[0]+w[w.length-1])/2}return n.set(x.sessionId,v),v};for(const x of e)x.parentId===null&&o(x);const c=e.map(x=>({node:x,x:Nm+x.depth*(Xm+zg),y:Nm+(n.get(x.sessionId)??0)*(iu+MS)})),u=new Map(c.map(x=>[x.node.sessionId,x])),f=[];for(const x of c){if(x.node.parentId===null)continue;const g=u.get(x.node.parentId);if(!g)continue;const v=g.x+Xm,w=g.y+iu/2,S=x.x,C=x.y+iu/2,N=v+zg/2;f.push({fromId:g.node.sessionId,toId:x.node.sessionId,path:w===C?`M ${v} ${w} H ${S}`:`M ${v} ${w} H ${N} V ${C} H ${S}`})}const p=e.reduce((x,g)=>Math.max(x,g.depth),0),h=Math.max(1,s);return{width:Nm*2+(p+1)*Xm+p*zg,height:Nm*2+h*iu+(h-1)*MS,nodes:c,edges:f}}function B0(e,t,n){const s=n.find(c=>c.sessionId===e.sessionId),o=e.agentId??s?.agentId??null;if(o!==null){const c=t.find(u=>u.agentId===o);return c?c.name?.length?c.name:c.agentId:o}return s?.title??null}function H0(e){return e.length>8?e.slice(-8):e}function dT({sessionId:e,model:t,running:n,ctx:s,agentId:o=null}){const{agents:c}=en(),{sessions:u}=Ii(),f=B0({sessionId:e,agentId:t.meta?.agentId??o},c,u)??d.chat.subagent,p=ML(s.pendingApprovals.keys(),[...s.origin,e]),h=`${d.chat.subagent} ${f}${p?` · ${d.chat.approvalWaiting}`:""}`;return a.jsxs("button",{type:"button","aria-label":h,title:h,onClick:()=>s.onOpenSubagent?.(e,s.origin),className:"flex w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-900/60 dark:hover:bg-gray-800/60",children:[a.jsx(Ha,{id:t.meta?.agentId??o??e,name:f,size:16}),a.jsx("span",{className:"min-w-0 truncate text-xs font-medium text-gray-700 dark:text-gray-300",children:f}),e&&a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:H0(e)}),n&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-gray-400 border-t-transparent"}),p&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${Fl.attention}`}),a.jsx("span",{className:"min-w-0 flex-1"})]})}const ES=new Set(["exec_command","input_command","run_subagent","input_subagent"]),gf=new Set(["read_file","edit_file","write_file"]);function mT(e){const t=e.split("/").filter(n=>n.length>0);return t.length<=2?e:`…/${t[t.length-2]}/${t[t.length-1]}`}function fP(e,t){if(e==="exec_command"){const n=xf(t,"cmd");if(n!==null)return`$ ${n.value.replace(/\s+/g," ").trim()}`}if(gf.has(e)){const n=xf(t,"file_path");if(n!==null)return mT(n.value.replace(/\s+/g," ").trim())}return t.replace(/\s+/g," ").trim()}function pP(e,t,n=!0){if(ES.has(e)||gf.has(e)){const s=xf(t,"description");if(s!==null){if(!s.complete&&!n)return null;const o=s.value.replace(/\s+/g," ").trim();if(o)return o}if(ES.has(e))return null}if(gf.has(e)){const s=xf(t,"file_path");if(s!==null){if(!s.complete&&!n)return null;const o=s.value.replace(/\s+/g," ").trim();if(o)return mT(o)}}return null}function hP(e,t){if(!gf.has(e))return null;let n;try{n=JSON.parse(t)}catch{return null}if(n===null||typeof n!="object")return null;const s=n,o=[],c=(u,f)=>{f!==void 0&&(typeof f=="string"&&f.includes(`
|
|
165
|
+
`))}function p(w,S,C,N){const T=C.enter("tableCell"),_=C.enter("phrasing"),R=C.containerPhrasing(w,{...N,before:c,after:c});return _(),T(),R}function h(w,S){return G7(w,{align:S,alignDelimiters:s,padding:n,stringLength:o})}function x(w,S,C){const N=w.children;let T=-1;const _=[],R=S.enter("table");for(;++T<N.length;)_[T]=g(N[T],S,C);return R(),_}function g(w,S,C){const N=w.children;let T=-1;const _=[],R=S.enter("tableRow");for(;++T<N.length;)_[T]=p(N[T],w,S,C);return R(),_}function v(w,S,C){let N=D5.inlineCode(w,S,C);return C.stack.includes("tableCell")&&(N=N.replace(/\|/g,"\\$&")),N}}function I9(){return{exit:{taskListCheckValueChecked:yS,taskListCheckValueUnchecked:yS,paragraph:O9}}}function L9(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:D9}}}function yS(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function O9(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const s=n.children[0];if(s&&s.type==="text"){const o=t.children;let c=-1,u;for(;++c<o.length;){const f=o[c];if(f.type==="paragraph"){u=f;break}}u===n&&(s.value=s.value.slice(1),s.value.length===0?n.children.shift():n.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,n.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function D9(e,t,n,s){const o=e.children[0],c=typeof e.checked=="boolean"&&o&&o.type==="paragraph",u="["+(e.checked?"x":" ")+"] ",f=n.createTracker(s);c&&f.move(u);let p=D5.listItem(e,t,n,{...s,...f.current()});return c&&(p=p.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,h)),p;function h(x){return x+u}}function $9(){return[h7(),D7(),z7(),N9(),I9()]}function U9(e){return{extensions:[g7(),$7(e),B7(),R9(e),L9()]}}const P9={tokenize:V9,partial:!0},$5={tokenize:G9,partial:!0},U5={tokenize:K9,partial:!0},P5={tokenize:W9,partial:!0},z9={tokenize:Y9,partial:!0},z5={name:"wwwAutolink",tokenize:F9,previous:H5},B5={name:"protocolAutolink",tokenize:q9,previous:F5},Zs={name:"emailAutolink",tokenize:H9,previous:q5},Ns={};function B9(){return{text:Ns}}let lo=48;for(;lo<123;)Ns[lo]=Zs,lo++,lo===58?lo=65:lo===91&&(lo=97);Ns[43]=Zs;Ns[45]=Zs;Ns[46]=Zs;Ns[95]=Zs;Ns[72]=[Zs,B5];Ns[104]=[Zs,B5];Ns[87]=[Zs,z5];Ns[119]=[Zs,z5];function H9(e,t,n){const s=this;let o,c;return u;function u(g){return!P0(g)||!q5.call(s,s.previous)||jy(s.events)?n(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return P0(g)?(e.consume(g),f):g===64?(e.consume(g),p):n(g)}function p(g){return g===46?e.check(z9,x,h)(g):g===45||g===95||kr(g)?(c=!0,e.consume(g),p):x(g)}function h(g){return e.consume(g),o=!0,p}function x(g){return c&&o&&Or(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):n(g)}}function F9(e,t,n){const s=this;return o;function o(u){return u!==87&&u!==119||!H5.call(s,s.previous)||jy(s.events)?n(u):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(P9,e.attempt($5,e.attempt(U5,c),n),n)(u))}function c(u){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(u)}}function q9(e,t,n){const s=this;let o="",c=!1;return u;function u(g){return(g===72||g===104)&&F5.call(s,s.previous)&&!jy(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),o+=String.fromCodePoint(g),e.consume(g),f):n(g)}function f(g){if(Or(g)&&o.length<5)return o+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const v=o.toLowerCase();if(v==="http"||v==="https")return e.consume(g),p}return n(g)}function p(g){return g===47?(e.consume(g),c?h:(c=!0,p)):n(g)}function h(g){return g===null||mf(g)||dn(g)||Eo(g)||qf(g)?n(g):e.attempt($5,e.attempt(U5,x),n)(g)}function x(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function V9(e,t,n){let s=0;return o;function o(u){return(u===87||u===119)&&s<3?(s++,e.consume(u),o):u===46&&s===3?(e.consume(u),c):n(u)}function c(u){return u===null?n(u):t(u)}}function G9(e,t,n){let s,o,c;return u;function u(h){return h===46||h===95?e.check(P5,p,f)(h):h===null||dn(h)||Eo(h)||h!==45&&qf(h)?p(h):(c=!0,e.consume(h),u)}function f(h){return h===95?s=!0:(o=s,s=void 0),e.consume(h),u}function p(h){return o||s||!c?n(h):t(h)}}function K9(e,t){let n=0,s=0;return o;function o(u){return u===40?(n++,e.consume(u),o):u===41&&s<n?c(u):u===33||u===34||u===38||u===39||u===41||u===42||u===44||u===46||u===58||u===59||u===60||u===63||u===93||u===95||u===126?e.check(P5,t,c)(u):u===null||dn(u)||Eo(u)?t(u):(e.consume(u),o)}function c(u){return u===41&&s++,e.consume(u),o}}function W9(e,t,n){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),c):f===93?(e.consume(f),o):f===60||f===null||dn(f)||Eo(f)?t(f):n(f)}function o(f){return f===null||f===40||f===91||dn(f)||Eo(f)?t(f):s(f)}function c(f){return Or(f)?u(f):n(f)}function u(f){return f===59?(e.consume(f),s):Or(f)?(e.consume(f),u):n(f)}}function Y9(e,t,n){return s;function s(c){return e.consume(c),o}function o(c){return kr(c)?n(c):t(c)}}function H5(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||dn(e)}function F5(e){return!Or(e)}function q5(e){return!(e===47||P0(e))}function P0(e){return e===43||e===45||e===46||e===95||kr(e)}function jy(e){let t=e.length,n=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){n=!0;break}if(s._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const X9={tokenize:aU,partial:!0};function Q9(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:tU,continuation:{tokenize:nU},exit:rU}},text:{91:{name:"gfmFootnoteCall",tokenize:eU},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Z9,resolveTo:J9}}}}function Z9(e,t,n){const s=this;let o=s.events.length;const c=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u;for(;o--;){const p=s.events[o][1];if(p.type==="labelImage"){u=p;break}if(p.type==="gfmFootnoteCall"||p.type==="labelLink"||p.type==="label"||p.type==="image"||p.type==="link")break}return f;function f(p){if(!u||!u._balanced)return n(p);const h=Ja(s.sliceSerialize({start:u.end,end:s.now()}));return h.codePointAt(0)!==94||!c.includes(h.slice(1))?n(p):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(p),e.exit("gfmFootnoteCallLabelMarker"),t(p))}}function J9(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},o={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};o.end.column++,o.end.offset++,o.end._bufferIndex++;const c={type:"gfmFootnoteCallString",start:Object.assign({},o.end),end:Object.assign({},e[e.length-1][1].start)},u={type:"chunkString",contentType:"string",start:Object.assign({},c.start),end:Object.assign({},c.end)},f=[e[n+1],e[n+2],["enter",s,t],e[n+3],e[n+4],["enter",o,t],["exit",o,t],["enter",c,t],["enter",u,t],["exit",u,t],["exit",c,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(n,e.length-n+1,...f),e}function eU(e,t,n){const s=this,o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c=0,u;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),p}function p(g){return g!==94?n(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",h)}function h(g){if(c>999||g===93&&!u||g===null||g===91||dn(g))return n(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteCallString");return o.includes(Ja(s.sliceSerialize(v)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(g)}return dn(g)||(u=!0),c++,e.consume(g),g===92?x:h}function x(g){return g===91||g===92||g===93?(e.consume(g),c++,h):h(g)}}function tU(e,t,n){const s=this,o=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c,u=0,f;return p;function p(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),h}function h(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",x):n(S)}function x(S){if(u>999||S===93&&!f||S===null||S===91||dn(S))return n(S);if(S===93){e.exit("chunkString");const C=e.exit("gfmFootnoteDefinitionLabelString");return c=Ja(s.sliceSerialize(C)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),v}return dn(S)||(f=!0),u++,e.consume(S),S===92?g:x}function g(S){return S===91||S===92||S===93?(e.consume(S),u++,x):x(S)}function v(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),o.includes(c)||o.push(c),Ut(e,w,"gfmFootnoteDefinitionWhitespace")):n(S)}function w(S){return t(S)}}function nU(e,t,n){return e.check(Xu,t,e.attempt(X9,t,n))}function rU(e){e.exit("gfmFootnoteDefinition")}function aU(e,t,n){const s=this;return Ut(e,o,"gfmFootnoteDefinitionIndent",5);function o(c){const u=s.events[s.events.length-1];return u&&u[1].type==="gfmFootnoteDefinitionIndent"&&u[2].sliceSerialize(u[1],!0).length===4?t(c):n(c)}}function sU(e){let n=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:c,resolveAll:o};return n==null&&(n=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function o(u,f){let p=-1;for(;++p<u.length;)if(u[p][0]==="enter"&&u[p][1].type==="strikethroughSequenceTemporary"&&u[p][1]._close){let h=p;for(;h--;)if(u[h][0]==="exit"&&u[h][1].type==="strikethroughSequenceTemporary"&&u[h][1]._open&&u[p][1].end.offset-u[p][1].start.offset===u[h][1].end.offset-u[h][1].start.offset){u[p][1].type="strikethroughSequence",u[h][1].type="strikethroughSequence";const x={type:"strikethrough",start:Object.assign({},u[h][1].start),end:Object.assign({},u[p][1].end)},g={type:"strikethroughText",start:Object.assign({},u[h][1].end),end:Object.assign({},u[p][1].start)},v=[["enter",x,f],["enter",u[h][1],f],["exit",u[h][1],f],["enter",g,f]],w=f.parser.constructs.insideSpan.null;w&&xa(v,v.length,0,Vf(w,u.slice(h+1,p),f)),xa(v,v.length,0,[["exit",g,f],["enter",u[p][1],f],["exit",u[p][1],f],["exit",x,f]]),xa(u,h-1,p-h+3,v),p=h+v.length-2;break}}for(p=-1;++p<u.length;)u[p][1].type==="strikethroughSequenceTemporary"&&(u[p][1].type="data");return u}function c(u,f,p){const h=this.previous,x=this.events;let g=0;return v;function v(S){return h===126&&x[x.length-1][1].type!=="characterEscape"?p(S):(u.enter("strikethroughSequenceTemporary"),w(S))}function w(S){const C=Il(h);if(S===126)return g>1?p(S):(u.consume(S),g++,w);if(g<2&&!n)return p(S);const N=u.exit("strikethroughSequenceTemporary"),T=Il(S);return N._open=!T||T===2&&!!C,N._close=!C||C===2&&!!T,f(S)}}}class iU{constructor(){this.map=[]}add(t,n,s){oU(this,t,n,s)}consume(t){if(this.map.sort(function(c,u){return c[0]-u[0]}),this.map.length===0)return;let n=this.map.length;const s=[];for(;n>0;)n-=1,s.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];s.push(t.slice()),t.length=0;let o=s.pop();for(;o;){for(const c of o)t.push(c);o=s.pop()}this.map.length=0}}function oU(e,t,n,s){let o=0;if(!(n===0&&s.length===0)){for(;o<e.map.length;){if(e.map[o][0]===t){e.map[o][1]+=n,e.map[o][2].push(...s);return}o+=1}e.map.push([t,n,s])}}function lU(e,t){let n=!1;const s=[];for(;t<e.length;){const o=e[t];if(n){if(o[0]==="enter")o[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(o[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const c=s.length-1;s[c]=s[c]==="left"?"center":"right"}}else if(o[1].type==="tableDelimiterRow")break}else o[0]==="enter"&&o[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return s}function cU(){return{flow:{null:{name:"table",tokenize:uU,resolveAll:dU}}}}function uU(e,t,n){const s=this;let o=0,c=0,u;return f;function f(P){let B=s.events.length-1;for(;B>-1;){const K=s.events[B][1].type;if(K==="lineEnding"||K==="linePrefix")B--;else break}const Y=B>-1?s.events[B][1].type:null,q=Y==="tableHead"||Y==="tableRow"?E:p;return q===E&&s.parser.lazy[s.now().line]?n(P):q(P)}function p(P){return e.enter("tableHead"),e.enter("tableRow"),h(P)}function h(P){return P===124||(u=!0,c+=1),x(P)}function x(P){return P===null?n(P):ot(P)?c>1?(c=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),w):n(P):Rt(P)?Ut(e,x,"whitespace")(P):(c+=1,u&&(u=!1,o+=1),P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),u=!0,x):(e.enter("data"),g(P)))}function g(P){return P===null||P===124||dn(P)?(e.exit("data"),x(P)):(e.consume(P),P===92?v:g)}function v(P){return P===92||P===124?(e.consume(P),g):g(P)}function w(P){return s.interrupt=!1,s.parser.lazy[s.now().line]?n(P):(e.enter("tableDelimiterRow"),u=!1,Rt(P)?Ut(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):S(P))}function S(P){return P===45||P===58?N(P):P===124?(u=!0,e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),C):z(P)}function C(P){return Rt(P)?Ut(e,N,"whitespace")(P):N(P)}function N(P){return P===58?(c+=1,u=!0,e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),T):P===45?(c+=1,T(P)):P===null||ot(P)?D(P):z(P)}function T(P){return P===45?(e.enter("tableDelimiterFiller"),_(P)):z(P)}function _(P){return P===45?(e.consume(P),_):P===58?(u=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(P),e.exit("tableDelimiterMarker"),R):(e.exit("tableDelimiterFiller"),R(P))}function R(P){return Rt(P)?Ut(e,D,"whitespace")(P):D(P)}function D(P){return P===124?S(P):P===null||ot(P)?!u||o!==c?z(P):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(P)):z(P)}function z(P){return n(P)}function E(P){return e.enter("tableRow"),L(P)}function L(P){return P===124?(e.enter("tableCellDivider"),e.consume(P),e.exit("tableCellDivider"),L):P===null||ot(P)?(e.exit("tableRow"),t(P)):Rt(P)?Ut(e,L,"whitespace")(P):(e.enter("data"),F(P))}function F(P){return P===null||P===124||dn(P)?(e.exit("data"),L(P)):(e.consume(P),P===92?V:F)}function V(P){return P===92||P===124?(e.consume(P),F):F(P)}}function dU(e,t){let n=-1,s=!0,o=0,c=[0,0,0,0],u=[0,0,0,0],f=!1,p=0,h,x,g;const v=new iU;for(;++n<e.length;){const w=e[n],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,p!==0&&(bS(v,t,p,h,x),x=void 0,p=0),h={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},v.add(n,0,[["enter",h,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,c=[0,0,0,0],u=[0,n+1,0,0],f&&(f=!1,x={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},v.add(n,0,[["enter",x,t]])),o=S.type==="tableDelimiterRow"?2:x?3:1):o&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,u[2]===0&&(c[1]!==0&&(u[0]=u[1],g=Cm(v,t,c,o,void 0,g),c=[0,0,0,0]),u[2]=n)):S.type==="tableCellDivider"&&(s?s=!1:(c[1]!==0&&(u[0]=u[1],g=Cm(v,t,c,o,void 0,g)),c=u,u=[c[1],n,0,0])):S.type==="tableHead"?(f=!0,p=n):S.type==="tableRow"||S.type==="tableDelimiterRow"?(p=n,c[1]!==0?(u[0]=u[1],g=Cm(v,t,c,o,n,g)):u[1]!==0&&(g=Cm(v,t,u,o,n,g)),o=0):o&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(u[3]=n)}for(p!==0&&bS(v,t,p,h,x),v.consume(t.events),n=-1;++n<t.events.length;){const w=t.events[n];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=lU(t.events,n))}return e}function Cm(e,t,n,s,o,c){const u=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";n[0]!==0&&(c.end=Object.assign({},hl(t.events,n[0])),e.add(n[0],0,[["exit",c,t]]));const p=hl(t.events,n[1]);if(c={type:u,start:Object.assign({},p),end:Object.assign({},p)},e.add(n[1],0,[["enter",c,t]]),n[2]!==0){const h=hl(t.events,n[2]),x=hl(t.events,n[3]),g={type:f,start:Object.assign({},h),end:Object.assign({},x)};if(e.add(n[2],0,[["enter",g,t]]),s!==2){const v=t.events[n[2]],w=t.events[n[3]];if(v[1].end=Object.assign({},w[1].end),v[1].type="chunkText",v[1].contentType="text",n[3]>n[2]+1){const S=n[2]+1,C=n[3]-n[2]-1;e.add(S,C,[])}}e.add(n[3]+1,0,[["exit",g,t]])}return o!==void 0&&(c.end=Object.assign({},hl(t.events,o)),e.add(o,0,[["exit",c,t]]),c=void 0),c}function bS(e,t,n,s,o){const c=[],u=hl(t.events,n);o&&(o.end=Object.assign({},u),c.push(["exit",o,t])),s.end=Object.assign({},u),c.push(["exit",s,t]),e.add(n+1,0,c)}function hl(e,t){const n=e[t],s=n[0]==="enter"?"start":"end";return n[1][s]}const mU={name:"tasklistCheck",tokenize:pU};function fU(){return{text:{91:mU}}}function pU(e,t,n){const s=this;return o;function o(p){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?n(p):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),c)}function c(p){return dn(p)?(e.enter("taskListCheckValueUnchecked"),e.consume(p),e.exit("taskListCheckValueUnchecked"),u):p===88||p===120?(e.enter("taskListCheckValueChecked"),e.consume(p),e.exit("taskListCheckValueChecked"),u):n(p)}function u(p){return p===93?(e.enter("taskListCheckMarker"),e.consume(p),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):n(p)}function f(p){return ot(p)?t(p):Rt(p)?e.check({tokenize:hU},t,n)(p):n(p)}}function hU(e,t,n){return Ut(e,s,"whitespace");function s(o){return o===null?n(o):t(o)}}function gU(e){return t5([B9(),Q9(),sU(e),cU(),fU()])}const xU={};function yU(e){const t=this,n=e||xU,s=t.data(),o=s.micromarkExtensions||(s.micromarkExtensions=[]),c=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),u=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);o.push(gU(n)),c.push($9()),u.push(U9(n))}const bU=/[^\x00-\x7F]+$/;function vU(e){if(e.children.length!==1)return!1;const t=e.children[0];if(!t||t.type!=="text")return!1;const{value:n}=t;return e.url===n||e.url===`http://${n}`}function kU(e){if(!vU(e))return null;const t=e.children[0],n=bU.exec(t.value);if(!n)return null;const s=t.value.slice(0,n.index);return!s.includes("://")&&!s.startsWith("www.")?null:(t.value=s,e.url=e.url.startsWith("http://")&&!s.startsWith("http")?`http://${s}`:s,{type:"text",value:n[0]})}function V5(e){for(let t=0;t<e.children.length;t+=1){const n=e.children[t];if(n.type==="link"){const o=kU(n);o&&e.children.splice(t+1,0,o)}const s=n.children;Array.isArray(s)&&V5(n)}}function wU(){return e=>V5(e)}const Ju=[yU,wU],SU="modulepreload",jU=function(e){return"/"+e},vS={},an=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){let p=function(h){return Promise.all(h.map(x=>Promise.resolve(x).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),f=u?.nonce||u?.getAttribute("nonce");o=p(n.map(h=>{if(h=jU(h),h in vS)return;vS[h]=!0;const x=h.endsWith(".css"),g=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${g}`))return;const v=document.createElement("link");if(v.rel=x?"stylesheet":SU,x||(v.as="script"),v.crossOrigin="",v.href=h,f&&v.setAttribute("nonce",f),document.head.appendChild(v),x)return new Promise((w,S)=>{v.addEventListener("load",w),v.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function c(u){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=u,window.dispatchEvent(f),!f.defaultPrevented)throw u}return o.then(u=>{for(const f of u||[])f.status==="rejected"&&c(f.reason);return t().catch(c)})};function Cy({language:e,code:t,highlight:n=!0}){const[s,o]=y.useState();return y.useEffect(()=>{if(!n){o(void 0);return}let c=!0;return an(()=>import("./highlighter-B3HctNDB.js"),[]).then(u=>u.highlightToHtml(t,e)).then(u=>{c&&o(u)}).catch(()=>{c&&o(void 0)}),()=>{c=!1}},[t,e,n]),a.jsxs("div",{className:"code-block my-2 overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-gray-200 bg-gray-50 px-3 py-1 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("span",{className:"font-mono text-xs lowercase text-gray-500 dark:text-gray-400",children:e||"text"}),a.jsx(Wu,{text:t,label:d.chat.copyCode})]}),a.jsx("div",{className:"overflow-x-auto bg-white text-[13px] leading-relaxed dark:bg-gray-950",children:s?a.jsx("div",{dangerouslySetInnerHTML:{__html:s}}):a.jsx("pre",{className:"m-0 px-3 py-2.5 font-mono text-gray-800 dark:text-gray-200",children:a.jsx("code",{children:t})})})]})}function CU(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string").join(""):""}function G5({children:e,streaming:t}){if(y.isValidElement(e)){const n=e.props,s=/language-([\w+-]+)/.exec(n.className??"")?.[1]??"";return a.jsx(Cy,{language:s,code:CU(n.children).replace(/\n$/,""),highlight:!t})}return a.jsx("pre",{children:e})}function K5({node:e,children:t,...n}){return a.jsx("a",{...n,target:"_blank",rel:"noreferrer",children:t})}const NU={pre:e=>a.jsx(G5,{streaming:!0,children:e.children}),a:K5},TU={pre:e=>a.jsx(G5,{streaming:!1,children:e.children}),a:K5},ed=y.memo(function({text:t,streaming:n=!1}){return a.jsx(Zu,{remarkPlugins:Ju,components:n?NU:TU,children:t})});function Ys({src:e,alt:t,className:n}){const[s,o]=y.useState(!1);return a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"block cursor-zoom-in",onClick:()=>o(!0),children:a.jsx("img",{src:e,alt:t,className:n})}),s&&a.jsx(MU,{src:e,alt:t,onClose:()=>o(!1)})]})}function MU({src:e,alt:t,onClose:n}){return y.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]),ss.createPortal(a.jsx("div",{className:"anim-fade fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-10",onMouseDown:s=>{s.target===s.currentTarget&&n()},children:a.jsxs("div",{className:"anim-pop relative",children:[a.jsx("button",{type:"button","aria-label":d.common.close,onClick:n,className:"absolute right-2 top-2 flex h-7 w-7 items-center justify-center rounded-full bg-black/50 text-white transition-colors duration-150 hover:bg-black/70",children:a.jsx(Hl,{})}),a.jsx("img",{src:e,alt:t,className:"max-h-[85vh] max-w-[88vw] rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900"})]})}),document.body)}const EU=new Set(["txt","md","json","js","mjs","cjs","ts","tsx","jsx","py","sh","bash","yaml","yml","toml","css","html","htm","csv","log","xml","ini","conf","rs","go","java","c","h","cpp","hpp","sql","rb","php","png","jpg","jpeg","gif","webp","svg","pdf","doc","docx","xls","xlsx","ppt","pptx","zip","tar","gz","mp4","mp3","wav"]),AU=/^[a-z][a-z0-9+.-]*:\/\//i;function _U(e){const t=e.trim();if(t.length===0||t.length>200||/\s/.test(t)||AU.test(t)||t.startsWith("www."))return!1;const n=/\.([A-Za-z0-9]{1,8})$/.exec(t);if(!n)return!1;const s=n[1].toLowerCase();return/^\d+$/.test(s)?!1:EU.has(s)}function Ym(e,t){return e===""?t:`${e}/${t}`}const RU=512;function IU(e,t){const n=e.trim();if(n.length===0||n.length>RU||n.startsWith("~"))return null;const s=t!==null&&t.length>0?t:null,o=s!==null&&(s.includes("\\")||/^[A-Za-z]:/.test(s)),c=g=>{if(!o)return g;const v=g.replaceAll("\\","/");return/^[A-Za-z]:/.test(v)?v[0].toLowerCase()+v.slice(1):v},u=c(n),f=s===null?null:c(s),p=u.startsWith("/")||o&&/^[a-z]:/.test(u);let h=u;if(p){if(f===null||!u.startsWith(`${f}/`))return null;h=u.slice(f.length+1)}const x=[];for(const g of h.split("/"))if(!(g===""||g===".")){if(g===".."){if(x.length===0)return null;x.pop();continue}x.push(g)}return x.length>0?x.join("/"):null}const kS="M6 3h8l4 4v14H6zM14 3v4h4",wS=3;function LU(e){const t=[],n=new Set;for(const s of e.matchAll(/`([^`\n]+)`/g)){const o=s[1].trim();!_U(o)||n.has(o)||(n.add(o),t.push(o))}return t}function W5({path:e}){const t=e.lastIndexOf("/"),n=t>=0?e.slice(0,t+1):"",s=t>=0?e.slice(t+1):e;return a.jsxs("span",{className:"flex min-w-0 items-baseline font-mono text-sm",children:[n&&a.jsx("span",{className:"min-w-0 shrink-[9999] truncate text-gray-400 dark:text-gray-500",children:n}),a.jsx("span",{className:"min-w-0 truncate font-semibold text-gray-800 dark:text-gray-100",children:s})]})}function SS({text:e,workspace:t,statFiles:n,onOpenFile:s}){const o=y.useMemo(()=>{const g=[],v=new Set;for(const w of LU(e)){const S=IU(w,t);S===null||v.has(S)||(v.add(S),g.push(S))}return g},[e,t]),[c,u]=y.useState(null);y.useEffect(()=>{if(u(null),o.length===0)return;let g=!1;return n(o).then(v=>{g||u(o.filter(w=>v.has(w)))}).catch(()=>{}),()=>{g=!0}},[o,n]);const[f,p]=y.useState(!1);if(c===null||c.length===0)return null;const h=f?c:c.slice(0,wS),x=c.length-h.length;return a.jsxs("div",{className:"anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40",children:[a.jsx(Oe,{d:kS,size:Ye.rowLead,className:"text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:d.chat.filesInMessage(c.length)})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[h.map(g=>a.jsxs("button",{type:"button",title:g,onClick:()=>s(g),className:"group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[a.jsx(Oe,{d:kS,size:Ye.rowLead,className:"text-gray-400"}),a.jsx(W5,{path:g}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300",children:d.chat.openPreview})]},g)),(x>0||f)&&c.length>wS&&a.jsxs("button",{type:"button",onClick:()=>p(g=>!g),className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50",children:[f?d.chat.showLess:d.chat.showMoreFiles(x),a.jsx(Zn,{open:f,size:Ye.chevronDense})]})]})]})}function Y5(e){return e.replace(/^\ufeff?---\r?\n[\s\S]*?\r?\n---\r?\n?/,"")}function OU(e){return e?.target!=null?{kind:"detail",target:e.target}:{kind:"list"}}function DU(){return{kind:"list"}}function z0(e,t){return e.scope==="user"?{scope:"user",file:t}:{scope:"workspace",scopeKey:e.scopeKey,file:t}}function $U(e,t){if(e===null){const s=[];for(const o of t){const c=o.scope==="user"?"user":o.scopeKey??"";let u=s.find(f=>f.scope===o.scope&&f.scopeKey===c);u===void 0&&(u={scope:o.scope,scopeKey:c,rows:[]},o.scope==="user"?s.unshift(u):s.push(u)),u.rows.push({target:z0(u,o.file),title:o.file,changed:o.op})}return s}const n=new Map(t.map(s=>[Qa(s),s.op]));return e.map(({info:s,files:o})=>{const c={scope:s.kind,scopeKey:s.scopeKey,...s.workspacePath!==void 0?{workspacePath:s.workspacePath}:{},rows:[]};for(const u of o){const f=z0(c,u.name),p=n.get(Qa(f));c.rows.push({target:f,title:u.title,...u.description!==""?{description:u.description}:{},...u.updatedAt!==void 0?{updatedAt:u.updatedAt}:{},modifiedAt:u.modifiedAt,...p!==void 0?{changed:p}:{}})}return c})}function UU(e,t){if(e===null)return null;const n=new Set;for(const{info:o,files:c}of e){const u={scope:o.kind,scopeKey:o.scopeKey};for(const f of c)n.add(Qa(z0(u,f.name)))}const s=new Set;for(const o of t){const c=Qa(o);n.has(c)||s.add(c)}return s}const X5="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z",Q5="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",PU="M14 4h6v6M20 4 10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3",zU="M19 12H5m6-6-6 6 6 6";function Z5(e,t){return{d:e==="user"?X5:Q5,title:e==="user"?d.memory.userScope:d.chat.memoryScopeWorkspace(t??"")}}function BU(e){return e.scope==="user"?d.memory.userScope:e.workspacePath?.split(/[\\/]/).filter(Boolean).at(-1)??e.scopeKey}function HU({session:e,changes:t,scopes:n,listingError:s,request:o,active:c,onOpenSettings:u}){const{locale:f}=Dr(),[p,h]=y.useState({kind:"list"});y.useEffect(()=>{o!==null&&h(OU(o))},[o]);const x=p.kind==="detail"?Qa(p.target):null,[g,v]=y.useState(null);y.useEffect(()=>{if(!c||p.kind!=="detail")return;const S=p.target,C=Qa(S);let N=!1;return v({key:C,content:null,failed:!1}),nC(e.projectId,e.agentId,S.scope==="user"?"user":S.scopeKey??"",S.file).then(T=>{N||v({key:C,content:T.content,failed:!1})}).catch(()=>{N||v({key:C,content:null,failed:!0})}),()=>{N=!0}},[c,x,e.projectId,e.agentId,t]);const w=$U(n,t);if(p.kind==="detail"){const S=p.target,C=w.flatMap(_=>_.rows).find(_=>Qa(_.target)===x),N=g!==null&&g.key===x,T=Z5(S.scope,S.scopeKey);return a.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-gray-100 px-3 py-2 dark:border-gray-800/60",children:[a.jsxs("button",{type:"button",onClick:()=>h(DU()),title:d.chat.memoryBack,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:zU,size:Ye.iconButton}),a.jsx("span",{className:"sr-only",children:d.chat.memoryBack})]}),a.jsxs("span",{title:T.title,className:"shrink-0 text-gray-400",children:[a.jsx(Oe,{d:T.d,size:Ye.rowLead}),a.jsx("span",{className:"sr-only",children:T.title})]}),a.jsx("p",{className:"min-w-0 flex-1 truncate font-mono text-[13px] font-semibold",children:C?.title??S.file}),C&&(C.updatedAt!==void 0||C.modifiedAt!==void 0)&&a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:C.updatedAt??(C.modifiedAt!==void 0?Al(C.modifiedAt,f):"")})]}),a.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-3.5 py-3",children:[C?.description!==void 0&&a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:C.description}),!N||!g.failed&&g.content===null?a.jsx(Sr,{rows:3}):g.failed?a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.chat.memoryContentUnavailable}):a.jsx("div",{className:"md-body text-sm",children:a.jsx(ed,{text:Y5(g.content??"")})})]})]})}return a.jsxs("div",{className:"h-full min-h-0 overflow-y-auto",children:[a.jsxs("div",{className:"flex items-center gap-1 px-3.5 pb-1 pt-2",children:[a.jsx("span",{className:"min-w-0 flex-1"}),u&&a.jsxs("button",{type:"button",onClick:u,title:d.chat.openAgentMemory,className:"flex min-w-0 cursor-pointer items-center gap-1 rounded-md px-1.5 py-1 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:PU,size:Ye.inlineGlyph}),a.jsx("span",{className:"truncate",children:d.chat.openAgentMemory})]})]}),s!==null&&w.length===0?a.jsx("p",{className:"px-3.5 py-2 text-xs text-gray-500 dark:text-gray-400",children:s}):n===null&&w.length===0?a.jsx("div",{className:"px-3.5 py-2",children:a.jsx(Sr,{rows:3})}):w.every(S=>S.rows.length===0)?a.jsx("p",{className:"px-3.5 py-2 text-xs text-gray-400 dark:text-gray-500",children:d.chat.memoryEmptyAll}):w.map(S=>S.rows.length===0?null:a.jsxs("div",{className:"pb-2",children:[a.jsxs("div",{className:"flex items-center gap-2 px-3.5 py-1.5",children:[a.jsx("span",{className:"shrink-0 text-gray-400",children:a.jsx(Oe,{d:S.scope==="user"?X5:Q5,size:Ye.inlineGlyph})}),a.jsx("p",{className:"min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400",title:S.workspacePath,children:BU(S)}),a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:d.memory.itemCount(S.rows.length)})]}),a.jsx("ul",{children:S.rows.map(C=>a.jsx("li",{children:a.jsxs("button",{type:"button",onClick:()=>h({kind:"detail",target:C.target}),className:"flex w-full cursor-pointer items-center gap-3 px-3.5 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("p",{className:"flex items-center gap-1.5 truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200",children:[C.changed!==void 0&&a.jsx("span",{title:d.chat.memoryChangedMark,className:"h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500",children:a.jsx("span",{className:"sr-only",children:d.chat.memoryChangedMark})}),a.jsx("span",{className:"min-w-0 truncate",children:C.title})]}),C.description!==void 0&&a.jsx("p",{className:"truncate text-xs text-gray-500 dark:text-gray-400",children:C.description})]}),(C.updatedAt!==void 0||C.modifiedAt!==void 0)&&a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:C.updatedAt??(C.modifiedAt!==void 0?Al(C.modifiedAt,f):"")})]})},Qa(C.target)))})]},`${S.scope} ${S.scopeKey}`))]})}const jS=3,CS="M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z",FU="M6 3h8l4 4v14H6zM12 11v6M9 14h6",qU="M12 20h9M16.5 3.5a2.85 2.85 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z";function VU({rows:e,deletedKeys:t,onLocateChange:n,onOpenPanel:s}){const[o,c]=y.useState(!1),u=t?e.filter(x=>!t.has(Qa(x))):e;if(u.length===0)return null;const f=o?u:u.slice(0,jS),p=u.length-f.length,h=x=>{const g=Z5(x.scope,x.scopeKey);return a.jsxs(a.Fragment,{children:[a.jsxs("span",{title:g.title,className:"shrink-0 text-gray-400",children:[a.jsx(Oe,{d:g.d,size:Ye.rowLead}),a.jsx("span",{className:"sr-only",children:g.title})]}),a.jsx(W5,{path:x.file}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("span",{title:x.op==="write"?d.chat.memoryOpWrite:d.chat.memoryOpEdit,className:"shrink-0 text-gray-400",children:a.jsx(Oe,{d:x.op==="write"?FU:qU,size:Ye.inlineGlyph})})]})};return a.jsxs("div",{className:"anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40",children:[a.jsx(Oe,{d:CS,size:Ye.rowLead,className:"shrink-0 text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:d.chat.memoryChangesTitle(u.length)}),s&&a.jsxs("button",{type:"button",title:d.chat.memoryViewTitle,onClick:s,className:"flex h-6 w-6 shrink-0 cursor-pointer items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300",children:[a.jsx(Oe,{d:CS,size:Ye.inlineGlyph}),a.jsx("span",{className:"sr-only",children:d.chat.memoryViewTitle})]})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[f.map(x=>{const g=Qa(x);return n?a.jsxs("button",{type:"button",title:d.chat.memoryRowOpen,onClick:()=>n(x),className:"group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[h(x),a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300",children:d.chat.memoryRowOpen})]},g):a.jsx("div",{className:"flex w-full items-center gap-2 px-3 py-2",children:h(x)},g)}),(p>0||o)&&u.length>jS&&a.jsxs("button",{type:"button",onClick:()=>c(x=>!x),className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50",children:[o?d.chat.showLess:d.chat.memoryShowMore(p),a.jsx(Zn,{open:o,className:"text-gray-400",size:Ye.chevronDense})]})]})]})}const GU={waiting:"M6 3h12M6 21h12M8 3v3.5L12 10l4-3.5V3M8 21v-3.5L12 14l4 3.5V21",done:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm-3.5-9.2 2.4 2.5 4.6-4.8",failed:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9 9l6 6m0-6-6 6",stopped:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM8.5 8.5h7v7h-7z"},NS={running:sn.busy,waiting:sn.attention,done:sn.muted,failed:sn.danger,stopped:sn.muted};function Di({state:e,size:t=13,label:n}){return e==="running"?a.jsx("span",{...n?{title:n,"aria-label":n,role:"status"}:{"aria-hidden":!0},style:{width:t,height:t},className:`inline-block shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent ${NS.running}`}):a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",...n?{role:"img","aria-label":n}:{"aria-hidden":!0},className:`block shrink-0 ${NS[e]}`,children:[n&&a.jsx("title",{children:n}),a.jsx("path",{d:GU[e]})]})}const J5="flex w-full items-center gap-2 bg-white px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800",eT="sticky top-4 z-[4]",KU="shrink-0 text-xs text-gray-500 dark:text-gray-400",tT="flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800",nT="sticky -top-4 z-[5]",rT="shrink-0 text-[11px] font-semibold uppercase tracking-wide",aT="max-h-72 overflow-auto whitespace-pre-wrap border-t border-gray-100 px-3 py-2 text-xs leading-5 text-gray-600 dark:border-gray-800 dark:text-gray-300",sT="anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900";function iT({icon:e,label:t,trailing:n,variant:s="row",sticky:o=!1,defaultOpen:c=!1,children:u}){const[f,p]=y.useState(c),h=y.useRef(null),x=s==="header",g=x?tT:J5,v=x?nT:eT,w=x?`${rT} text-gray-500 dark:text-gray-400`:KU;return a.jsxs("div",{ref:h,children:[a.jsxs("button",{type:"button",onClick:()=>{const S=f;p(C=>!C),S&&requestAnimationFrame(()=>h.current?.scrollIntoView({block:"nearest"}))},"aria-expanded":f,className:`${o?`${v} `:""}${g}`,children:[e,a.jsx("span",{className:w,children:t}),n,a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx(Zn,{open:f,className:"text-gray-400"})]}),f&&u]})}function Ll({sinceMs:e,offsetMs:t=0}){const[n,s]=y.useState(()=>Date.now());return y.useEffect(()=>{const o=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(o)},[]),e===void 0?a.jsx("span",{className:"animate-pulse",children:"…"}):a.jsx(a.Fragment,{children:ZC(Math.max(0,t)+Math.max(0,n-e))})}function WU({item:e}){const t=e.stopReason!==void 0&&e.stopReason!=="completed",n=e.streaming?"running":t?"failed":"done",s=e.streaming?d.chat.workRunning:t?e.stopReason:d.chat.workDone;return a.jsx(iT,{sticky:!0,icon:a.jsx(Di,{state:n,label:s}),label:d.chat.thinking,trailing:a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400",children:e.streaming?a.jsx(Ll,{sinceMs:e.startedAtMs}):e.durationMs!==void 0?Pn(e.durationMs):null}),t&&a.jsxs("span",{className:"font-mono text-xs text-gray-400",children:["[",e.stopReason,"]"]})]}),children:a.jsx("div",{className:"md-body anim-fade mx-3 mb-2 rounded-md bg-gray-50 px-3 py-2 text-sm leading-relaxed text-gray-600 dark:bg-gray-900/60 dark:text-gray-400",children:a.jsx(ed,{text:e.thinking,streaming:e.streaming})})})}const YU=/\x1b(?:\[[0-9:;<=>?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\^_])/g,XU=/\x1b(?:\[[0-9:;<=>?]*[ -/]*|\][^\x07]*)?$/;function oT(e){return e.includes("\x1B")?e.replace(YU,"").replace(XU,""):e}function QU({onDecide:e}){const[t,n]=y.useState(!1),s=async o=>{n(!0);try{await e(o)}finally{n(!1)}};return a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ge,{size:"sm",variant:"primary",disabled:t,onClick:()=>{s("allow")},children:d.chat.approve}),a.jsx(ge,{size:"sm",disabled:t,onClick:()=>{s("deny")},children:d.chat.deny})]})}const ZU=rL,JU=iL;function eP(e,t){const n=t.trim().toLowerCase();return n?e.filter(s=>s.agentId.toLowerCase().includes(n)||(s.name??"").toLowerCase().includes(n)):e}function tP({handoffTarget:e,pendingModel:t,canSwitchModel:n,sessionBusy:s}){return e?"handoff":!t||!n?"post":s?"blocked":"model"}const nP="background_task_done";function Au(e){return e.kind==="user_image"?!0:e.kind!=="user_text"?!1:e.text.includes(`[${nP}]`)?_l(e.text)===null:!0}function lT(e){for(let t=e.length-1;t>=0;t--)if(Au(e[t]))return t;return 0}function rP(e){let t=0;for(const n of e)(n.kind==="user_text"||n.kind==="user_image")&&(t+=1);return t}function aP(e){let t=0;for(const n of e)Au(n)&&(t+=1);return t}function Ny(e,t){try{const n=JSON.parse(e);if(n!==null&&typeof n=="object"){const s=n[t];if(typeof s=="string"&&s.length>0)return s}}catch{}return null}function cT(e){return Ny(e,"agent_id")}function sP(e){return Ny(e,"description")}function TS(e,t,n){for(let s=t;s<n;s++){const o=e[s];if(o.kind==="tool_call"&&o.subagent!==void 0||o.kind==="subagent")return!0}return!1}function iP(e,t,n,s){const o=e.items;let c=lT(o),u=o.length;if(!TS(o,c,u))for(let f=c;f>0;){let p=0;for(let h=f-1;h>=0;h--)if(Au(o[h])){p=h;break}if(TS(o,p,f)){c=p,u=f;break}if(p===0)break;f=p}return uT(o.slice(c,u),t,{running:u===o.length&&n},s)}function oP(e,t,n,s,o){const c=e.items,u=c.findIndex(h=>h.kind==="tool_call"&&h.subagentSessionId===s||h.kind==="subagent"&&h.sessionId===s);if(u===-1)return null;let f=0;for(let h=u;h>=0;h--)if(Au(c[h])){f=h;break}let p=c.length;for(let h=u+1;h<c.length;h++)if(Au(c[h])){p=h;break}return uT(c.slice(f,p),t,{running:p===c.length&&n},o)}const lP=/\[subagent running in background with subagent_id (subagent-[0-9a-f]+)/;function cP(e){const t=new Map;for(const n of e){if(n.kind==="user_text"||n.kind==="background_notice"){const s=_l(n.text);s!==null&&s.done.kind==="subagent"&&t.set(s.done.id,"done");continue}if(!(n.kind!=="tool_call"||n.output.length===0)){for(const s of n.output.matchAll(/\[subagent (?:running in background|still running) with subagent_id (subagent-[0-9a-f]+)/g))t.set(s[1],"running");for(const s of n.output.matchAll(/\[subagent idle with subagent_id (subagent-[0-9a-f]+)|\[subagent (subagent-[0-9a-f]+) (?:aborted and removed|was idle; session removed)/g))t.set(s[1]??s[2],"done")}}return t}function uT(e,t,n,s){const o=[{sessionId:t,agentId:null,description:null,spawnThinkingLevel:null,running:n.running,depth:0,origin:[],parentId:null}],c=new Set([t]),u=(h,x,g,v,w,S,C,N)=>{if(c.has(h))return;c.add(h);const T=[...w,h],_=x.firstTsMs??x.firstSeenLocalMs,R=x.firstTsMs!==void 0&&x.lastActivityTsMs!==void 0?Math.max(0,x.lastActivityTsMs-x.firstTsMs):x.firstSeenLocalMs!==void 0&&x.lastActivityLocalMs!==void 0?Math.max(0,x.lastActivityLocalMs-x.firstSeenLocalMs):void 0;o.push({sessionId:h,agentId:x.meta?.agentId??S,description:C,spawnThinkingLevel:N,running:s?.get(h)??g,depth:T.length,origin:T,parentId:v,..._!==void 0?{startedMs:_}:{},...R!==void 0?{elapsedMs:R}:{}}),p(x.items,h,T)},f=cP(e),p=(h,x,g)=>{for(const v of h)if(v.kind==="tool_call"&&v.subagent&&v.subagentSessionId){const w=lP.exec(v.output)?.[1]??null;u(v.subagentSessionId,v.subagent,w!==null?f.get(w)!=="done":!v.outputComplete,x,g,cT(v.argumentsText),sP(v.argumentsText),Ny(v.argumentsText,"thinking_level"))}else v.kind==="subagent"&&u(v.sessionId,v.model,!1,x,g,null,null,null)};return p(e,t,[]),o}function uP(e){const t=e.items;for(let n=lT(t);n<t.length;n++){const s=t[n];if(s.kind==="tool_call"&&s.subagent!==void 0||s.kind==="subagent")return!0}return!1}function dP(e,t){if(t.length===0)return null;let n=e;for(const s of t){const o=n.subagents.get(s);if(!o)return null;n=o}return n}const Xm=200,iu=46,zg=32,MS=10,Nm=6;function mP(e){const t=new Map;for(const x of e){if(x.parentId===null)continue;const g=t.get(x.parentId);g?g.push(x):t.set(x.parentId,[x])}const n=new Map;let s=0;const o=x=>{const g=t.get(x.sessionId)??[];let v;if(g.length===0)v=s++;else{const w=g.map(o);v=(w[0]+w[w.length-1])/2}return n.set(x.sessionId,v),v};for(const x of e)x.parentId===null&&o(x);const c=e.map(x=>({node:x,x:Nm+x.depth*(Xm+zg),y:Nm+(n.get(x.sessionId)??0)*(iu+MS)})),u=new Map(c.map(x=>[x.node.sessionId,x])),f=[];for(const x of c){if(x.node.parentId===null)continue;const g=u.get(x.node.parentId);if(!g)continue;const v=g.x+Xm,w=g.y+iu/2,S=x.x,C=x.y+iu/2,N=v+zg/2;f.push({fromId:g.node.sessionId,toId:x.node.sessionId,path:w===C?`M ${v} ${w} H ${S}`:`M ${v} ${w} H ${N} V ${C} H ${S}`})}const p=e.reduce((x,g)=>Math.max(x,g.depth),0),h=Math.max(1,s);return{width:Nm*2+(p+1)*Xm+p*zg,height:Nm*2+h*iu+(h-1)*MS,nodes:c,edges:f}}function B0(e,t,n){const s=n.find(c=>c.sessionId===e.sessionId),o=e.agentId??s?.agentId??null;if(o!==null){const c=t.find(u=>u.agentId===o);return c?c.name?.length?c.name:c.agentId:o}return s?.title??null}function H0(e){return e.length>8?e.slice(-8):e}function dT({sessionId:e,model:t,running:n,ctx:s,agentId:o=null}){const{agents:c}=en(),{sessions:u}=Ii(),f=B0({sessionId:e,agentId:t.meta?.agentId??o},c,u)??d.chat.subagent,p=ML(s.pendingApprovals.keys(),[...s.origin,e]),h=`${d.chat.subagent} ${f}${p?` · ${d.chat.approvalWaiting}`:""}`;return a.jsxs("button",{type:"button","aria-label":h,title:h,onClick:()=>s.onOpenSubagent?.(e,s.origin),className:"flex w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-900/60 dark:hover:bg-gray-800/60",children:[a.jsx(Ha,{id:t.meta?.agentId??o??e,name:f,size:16}),a.jsx("span",{className:"min-w-0 truncate text-xs font-medium text-gray-700 dark:text-gray-300",children:f}),e&&a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:H0(e)}),n&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-2.5 w-2.5 shrink-0 animate-spin rounded-full border border-gray-400 border-t-transparent"}),p&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${Fl.attention}`}),a.jsx("span",{className:"min-w-0 flex-1"})]})}const ES=new Set(["exec_command","input_command","run_subagent","input_subagent"]),gf=new Set(["read_file","edit_file","write_file"]);function mT(e){const t=e.split("/").filter(n=>n.length>0);return t.length<=2?e:`…/${t[t.length-2]}/${t[t.length-1]}`}function fP(e,t){if(e==="exec_command"){const n=xf(t,"cmd");if(n!==null)return`$ ${n.value.replace(/\s+/g," ").trim()}`}if(gf.has(e)){const n=xf(t,"file_path");if(n!==null)return mT(n.value.replace(/\s+/g," ").trim())}return t.replace(/\s+/g," ").trim()}function pP(e,t,n=!0){if(ES.has(e)||gf.has(e)){const s=xf(t,"description");if(s!==null){if(!s.complete&&!n)return null;const o=s.value.replace(/\s+/g," ").trim();if(o)return o}if(ES.has(e))return null}if(gf.has(e)){const s=xf(t,"file_path");if(s!==null){if(!s.complete&&!n)return null;const o=s.value.replace(/\s+/g," ").trim();if(o)return mT(o)}}return null}function hP(e,t){if(!gf.has(e))return null;let n;try{n=JSON.parse(t)}catch{return null}if(n===null||typeof n!="object")return null;const s=n,o=[],c=(u,f)=>{f!==void 0&&(typeof f=="string"&&f.includes(`
|
|
166
166
|
`)?o.push(`${u}:
|
|
167
167
|
${f}`):o.push(`${u}: ${typeof f=="string"?f:JSON.stringify(f)}`))};return c("file_path",s.file_path),e==="read_file"?(c("offset",s.offset),c("limit",s.limit)):e==="edit_file"?(c("old_string",s.old_string),c("new_string",s.new_string),s.replace_all===!0&&c("replace_all",!0)):e==="write_file"&&c("content",s.content),o.join(`
|
|
168
168
|
`)}function xf(e,t){const n=`"${t}"`,s=e.indexOf(n);if(s===-1)return null;let o=s+n.length;for(;/\s/.test(e[o]??"");)o+=1;if(e[o]!==":")return null;for(o+=1;/\s/.test(e[o]??"");)o+=1;if(e[o]!=='"')return null;o+=1;let c="",u=!1;for(;o<e.length;o+=1){const f=e[o];if(u){c+=f==="n"?`
|
|
@@ -170,14 +170,14 @@ ${f}`):o.push(`${u}: ${typeof f=="string"?f:JSON.stringify(f)}`))};return c("fil
|
|
|
170
170
|
${t}`:e.id})})})}function Wc({icon:e,value:t,compactValue:n,label:s,display:o="flex"}){return a.jsxs("span",{title:s,"aria-label":s,className:`${o} items-center gap-1`,children:[a.jsx(Oe,{d:e}),n!==void 0&&n!==t?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"sm:hidden",children:n}),a.jsx("span",{className:"hidden sm:inline",children:t})]}):t]})}function LP({stats:e,assistantText:t,cost:n,atMs:s,forkPosition:o,onFork:c}){const{currency:u}=as(),{locale:f}=Dr(),[p,h]=y.useState(!1),[x,g]=y.useState(!1),v=e?.tokensByBucket,w=v?v.cacheRead+v.cacheWrite:0,S=()=>t?.trim()||e===null?t??"":kL(e,{stats:d.chat.statsLabel,input:d.chat.statInput,cached:d.chat.statCached,output:d.chat.statOutput,parenOpen:d.chat.statParenOpen,parenClose:d.chat.statParenClose});return a.jsxs("div",{className:"-mt-2 flex h-5 items-center justify-start gap-x-2 overflow-hidden whitespace-nowrap text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:gap-x-3 sm:opacity-0 dark:text-gray-500",children:[a.jsxs("span",{className:"no-scrollbar flex min-w-0 items-center gap-x-2 overflow-x-auto sm:gap-x-3",children:[s!==void 0&&a.jsx("span",{children:eN(s,f)}),e&&v&&a.jsxs(a.Fragment,{children:[a.jsx(Wc,{icon:Xn.input,value:It(w),label:d.chat.statInput}),a.jsx(Wc,{icon:Xn.output,value:It(v.output),label:d.chat.statOutput}),a.jsx(Wc,{icon:Xn.tps,value:sf(e.outputTps),label:d.chat.statTps,display:"hidden sm:flex"}),n!=null&&a.jsx(Wc,{icon:Xn.cost,value:rs(n,u),compactValue:rs(n,u,{compact:!0}),label:`${d.common.cost}(${u})`}),a.jsx(Wc,{icon:Xn.elapsed,value:Pn(e.elapsedDeltaMs),compactValue:Pn(e.elapsedDeltaMs,{compact:!0}),label:d.chat.statElapsed})]})]}),a.jsx(Wu,{text:S,label:d.chat.copyReply,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"}),c&&t?.trim()&&a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",disabled:p,title:d.chat.forkSession,"aria-label":d.chat.forkSession,onClick:()=>g(!0),className:"flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 disabled:cursor-wait disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:text-gray-300",children:a.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:p?"animate-pulse":"",children:[a.jsx("circle",{cx:"6",cy:"5",r:"2"}),a.jsx("circle",{cx:"18",cy:"7",r:"2"}),a.jsx("circle",{cx:"6",cy:"19",r:"2"}),a.jsx("path",{d:"M6 7v8M8 11h4a6 6 0 0 0 6-2"})]})}),a.jsx(ln,{open:x,title:d.chat.forkSession,tone:"primary",confirmLabel:d.chat.forkSessionConfirmAction,busy:p,onClose:()=>g(!1),onConfirm:()=>{g(!1),h(!0),c({assistantText:t,...s!==void 0?{atMs:s}:{},...o!==void 0?{position:o}:{}}).finally(()=>h(!1))},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.chat.forkSessionConfirmBody})})]})]})}const OP="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0";function Yc({atMs:e,text:t,align:n="left"}){const{locale:s}=Dr();return a.jsxs("div",{className:`flex h-5 items-center gap-2 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:opacity-0 ${n==="right"?"justify-end":"justify-start"}`,children:[e!==void 0&&a.jsx("span",{className:"text-[11px] text-gray-400",children:eN(e,s)}),t!==void 0&&a.jsx(Wu,{text:t,label:d.chat.copyMessage})]})}const DP=2e3;function $P({item:e,ctx:t}){const n=e.gaveUp?"gaveUp":e.retrying?"retried":"waiting",s=n==="waiting"&&e.plannedDelayMs!==void 0&&e.plannedDelayMs>=DP&&e.arrivedAtMs!==void 0?e.arrivedAtMs+e.plannedDelayMs:null,[o,c]=y.useState(()=>Date.now()),[u,f]=y.useState(!1);y.useEffect(()=>{if(s===null||Date.now()>=s)return;const v=setInterval(()=>{c(Date.now()),Date.now()>=s&&clearInterval(v)},250);return()=>clearInterval(v)},[s]);const p=s!==null?s-o:0,h=s!==null&&p>0,x=h?Math.ceil(p/1e3):void 0,g=h&&t.origin.length===0&&(t.onRetryNow!==void 0||t.onGiveUp!==void 0);return a.jsxs("p",{className:`anim-msg my-1 flex flex-wrap items-center gap-x-2 gap-y-1 font-mono text-xs ${sn.attention}`,children:[a.jsx("span",{children:d.chat.reconnect(e.status,n,e.attempt,x,e.errorMessage,e.errorCode)}),g&&a.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[t.onRetryNow&&a.jsx("button",{type:"button",disabled:u,onClick:()=>{f(!0),t.onRetryNow()},className:"rounded border border-amber-300 px-1.5 py-0.5 text-[11px] font-medium text-amber-700 transition-colors duration-150 hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-amber-700 dark:text-amber-400 dark:hover:bg-amber-950/40",children:d.chat.reconnectRetryNow}),t.onGiveUp&&a.jsx("button",{type:"button",disabled:u,onClick:()=>{f(!0),t.onGiveUp()},className:"rounded border border-gray-300 px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-800",children:d.chat.reconnectGiveUp})]})]})}function fT({item:e,ctx:t}){switch(e.kind){case"user_text":{const n=TN(e.text);if(n)return a.jsx(MP,{origin:n});const s=EN(e.text);if(s)return a.jsx(EP,{origin:s});const o=_l(e.text);if(o)return a.jsx(RS,{done:o.done,body:o.rest});const c=AN(e.text),u=c?c.rest:e.text,f=MN(u),p=f?f.rest:u,h=CN(p),{text:x,images:g,files:v}=df(h?h.rest:p);return c?a.jsxs(a.Fragment,{children:[h&&a.jsx(AS,{names:h.skills}),a.jsx(CP,{round:c.round,objective:x,images:g})]}):a.jsxs(a.Fragment,{children:[f&&a.jsx(AP,{origin:f.origin}),h&&a.jsx(AS,{names:h.skills}),x&&a.jsxs("div",{className:"anim-msg group my-4 flex flex-col items-end",children:[a.jsx("div",{className:"max-w-[88%] rounded-lg bg-gray-100 px-4 py-2.5 md:max-w-[75%] dark:bg-gray-800",children:a.jsx("p",{className:"wrap-anywhere whitespace-pre-wrap text-base leading-relaxed text-gray-900 dark:text-gray-100",children:x})}),a.jsx(Yc,{...e.atMs!==void 0?{atMs:e.atMs}:{},text:x,align:"right"})]}),v.length>0&&a.jsxs("div",{className:"anim-msg group my-4 flex flex-col items-end",children:[a.jsx(_S,{files:v}),a.jsx(Yc,{...e.atMs!==void 0?{atMs:e.atMs}:{},align:"right"})]}),g.map((w,S)=>a.jsxs("div",{className:"anim-msg group my-4 flex flex-col items-end",children:[a.jsx("div",{className:"max-w-[88%] rounded-lg bg-gray-100 p-1.5 md:max-w-[75%] dark:bg-gray-800",children:a.jsx(Ys,{src:w,alt:d.chat.imageAlt,className:"max-h-48 max-w-full rounded-md"})}),a.jsx(Yc,{...e.atMs!==void 0?{atMs:e.atMs}:{},align:"right"})]},S))]})}case"background_notice":{const n=_l(e.text);return n?a.jsx(RS,{done:n.done,body:n.rest}):null}case"user_steering":{const{text:n,images:s,files:o}=df(e.text),c=[...s,...e.images??[]];return a.jsxs("div",{className:"anim-msg group my-2 flex flex-col items-end",children:[a.jsxs("div",{className:"flex max-w-[88%] flex-col gap-1.5 rounded-md border border-gray-200 bg-gray-100 px-3 py-1.5 md:max-w-[75%] dark:border-gray-700 dark:bg-gray-800",children:[a.jsxs("div",{className:"flex items-start gap-1.5",children:[a.jsx(Oe,{d:OP,className:"mt-1 shrink-0 text-gray-400 dark:text-gray-500"}),a.jsxs("p",{className:"wrap-anywhere whitespace-pre-wrap text-sm leading-relaxed text-gray-800 dark:text-gray-100",children:[a.jsx("span",{className:"mr-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400",children:d.chat.userSteering}),n]})]}),c.length>0&&a.jsx("div",{className:"flex flex-wrap justify-end gap-1.5",children:c.map((u,f)=>a.jsx(Ys,{src:u,alt:d.chat.imageAlt,className:"max-h-28 max-w-full rounded-md"},f))}),o.length>0&&a.jsx("div",{className:"flex justify-end",children:a.jsx(_S,{files:o})})]}),a.jsx(Yc,{...e.atMs!==void 0?{atMs:e.atMs}:{},text:n,align:"right"})]})}case"user_image":return a.jsxs("div",{className:"anim-msg group my-4 flex flex-col items-end",children:[a.jsx("div",{className:"max-w-[88%] rounded-lg bg-gray-100 p-1.5 md:max-w-[75%] dark:bg-gray-800",children:a.jsx(Ys,{src:e.imageUrl,alt:d.chat.imageAlt,className:"max-h-48 max-w-full rounded-md"})}),a.jsx(Yc,{...e.atMs!==void 0?{atMs:e.atMs}:{},align:"right"})]});case"assistant_text":return a.jsxs("div",{className:"md-body anim-msg my-3 text-base leading-relaxed text-gray-800 dark:text-gray-100",children:[a.jsx(ed,{text:e.text,streaming:e.streaming}),e.streaming&&a.jsx("span",{className:"animate-pulse text-gray-400",children:"▌"}),e.stopReason&&e.stopReason!=="completed"&&a.jsxs("span",{className:"ml-1 font-mono text-xs text-gray-400",children:["[",e.stopReason,"]"]}),t.origin.length>0&&!e.streaming&&t.onOpenFile&&t.statFiles&&a.jsx(SS,{text:e.text,workspace:t.workspace??null,statFiles:t.statFiles,onOpenFile:t.onOpenFile})]});case"thinking":return a.jsx(WU,{item:e});case"tool_call":return a.jsx(gP,{item:e,ctx:t});case"subagent":return a.jsx("div",{className:"anim-msg my-2",children:a.jsx(dT,{sessionId:e.sessionId,model:e.model,running:!1,ctx:t})});case"abort":return a.jsx("p",{className:"anim-msg my-1 font-mono text-xs text-gray-500 dark:text-gray-400",children:d.chat.aborted(e)});case"llm_error":return a.jsx("p",{className:"anim-msg my-1 font-mono text-xs text-gray-500 dark:text-gray-400",children:d.chat.llmError(e.errorMessage)});case"reconnect":return a.jsx($P,{item:e,ctx:t});case"compaction":return a.jsx(bP,{item:e});case"mcp_connect":return a.jsx(wP,{item:e});case"task_stats":return a.jsxs(a.Fragment,{children:[t.origin.length===0&&t.onOpenFile&&t.statFiles&&e.assistantText.trim()!==""&&a.jsx(SS,{text:e.assistantText,workspace:t.workspace??null,statFiles:t.statFiles,onOpenFile:t.onOpenFile}),t.origin.length===0&&e.memoryChanges!==void 0&&a.jsx(VU,{rows:e.memoryChanges,...t.deletedMemoryKeys?{deletedKeys:t.deletedMemoryKeys}:{},...t.onLocateMemoryChange?{onLocateChange:t.onLocateMemoryChange}:{},...t.onOpenMemory?{onOpenPanel:t.onOpenMemory}:{}}),a.jsx(LP,{stats:e.stats,assistantText:e.assistantText,cost:e.stats?t.taskCost?.(e.stats)??null:null,...e.atMs!==void 0?{atMs:e.atMs}:{},...t.origin.length===0&&e.forkable&&t.onFork?{onFork:t.onFork}:{},...e.forkPosition!==void 0?{forkPosition:e.forkPosition}:{}})]})}}function UP(e){let t=0,n=0,s,o;const c=p=>{p!==void 0&&(s===void 0||p<s)&&(s=p)},u=(p,h)=>{if(h<=0)return;if(p===void 0){n+=h;return}c(p);const x=p+h;(o===void 0||x>o)&&(o=x)};for(const p of e){if(p.kind==="thinking"){c(p.startedAtMs),p.durationMs!==void 0&&u(p.startedAtMs,p.durationMs);continue}if(p.kind!=="tool_call"||(t+=1,c(p.argStartedAtMs??p.callStartedAtMs??p.approvalAtMs),p.durationMs===void 0))continue;const h=p.argStartedAtMs!==void 0&&p.callStartedAtMs!==void 0?Math.min(p.durationMs,Math.max(0,p.callStartedAtMs-p.argStartedAtMs)):0;u(p.argStartedAtMs,h),u(p.approvalAtMs??p.callStartedAtMs,p.durationMs-h)}const f=s!==void 0&&o!==void 0?o-s:0;return{steps:t,durationMs:f+n,...s!==void 0?{startMs:s}:{}}}function PP(e){return e.kind==="thinking"||e.kind==="tool_call"}function zP(e,t){return e.kind==="thinking"?e.streaming:e.kind==="tool_call"?e.callStreaming||e.outputStreaming||e.callComplete&&!e.outputComplete?!0:t.pendingApprovals.has(Rl(t.origin,e.toolCallId)):!1}function BP(e,t){return e.some(n=>n.kind==="tool_call"&&t.pendingApprovals.has(Rl(t.origin,n.toolCallId)))}function HP({items:e,ctx:t,isLast:n}){const s=e.some(S=>zP(S,t)),o=n&&t.taskRunning||s,c=BP(e,t),[u,f]=y.useState(n),p=y.useRef(!1),h=y.useRef(null);y.useEffect(()=>{p.current||f(n)},[n]);const x=u||c,{steps:g,durationMs:v,startMs:w}=UP(e);return a.jsxs("div",{ref:h,className:sT,children:[a.jsxs("button",{type:"button","data-group-header":!0,"aria-expanded":x,onClick:()=>{p.current=!0;const S=u&&!c;f(C=>!C),S&&requestAnimationFrame(()=>h.current?.scrollIntoView({block:"nearest"}))},className:`${nT} ${tT}`,children:[a.jsx(Di,{state:o?"running":"done"}),a.jsx("span",{className:`${rT} ${o?sn.busy:"text-gray-500 dark:text-gray-400"}`,children:o?d.chat.workRunning:d.chat.workDone}),g>0&&a.jsx("span",{className:"hidden shrink-0 font-mono text-xs text-gray-400 sm:inline",children:d.chat.workGroupSteps(g)}),s?w!==void 0&&a.jsx("span",{className:"shrink-0 font-mono text-xs text-gray-400",children:a.jsx(Ll,{sinceMs:w})}):v>0&&a.jsx("span",{className:"shrink-0 font-mono text-xs text-gray-400",children:Pn(v)}),c&&!x&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`hidden shrink-0 rounded px-1 text-[10px] font-medium sm:inline ${bo.attention}`,children:d.chat.approvalWaiting}),a.jsx("span",{role:"img",title:d.chat.approvalWaiting,"aria-label":d.chat.approvalWaiting,className:`h-1.5 w-1.5 shrink-0 rounded-full sm:hidden ${Fl.attention}`})]}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx(Zn,{open:x,className:"text-gray-400"})]}),x&&a.jsx("div",{className:"anim-fade divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800/60 dark:border-gray-800",children:e.map(S=>a.jsx(fT,{item:S,ctx:t},S.id))})]})}function FP(){let e=!0,t=null,n=null;return{get stick(){return e},wheel(s){s<0&&(e=!1)},touchStart(s){n=s},touchMove(s){n!==null&&s>n&&(e=!1),n=s},touchEnd(){n=null},scrolled(s){const o=s.scrollHeight-s.scrollTop-s.clientHeight,c=t;if(t=s.scrollTop,c===null){e=o<80;return}if(s.scrollTop<c&&o>1){e=!1;return}o<80&&(e=!0)},resume(){e=!0,t=null}}}function Mm(e,t){e.scrollTop=e.scrollHeight,t.scrolled({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function qP({items:e,ctx:t}){const n=[];let s=[];const o=()=>{s.length>0&&(n.push({type:"group",items:s}),s=[])};for(const h of e)PP(h)?s.push(h):(o(),n.push({type:"single",item:h}));o();const c=(h,x)=>h.type==="group"?a.jsx(HP,{items:h.items,ctx:t,isLast:x===n.length-1},`wg-${h.items[0].id}`):a.jsx(fT,{item:h.item,ctx:t},h.item.id),u=[];let f=[];const p=()=>{if(f.length===0)return;const h=f[0].seg,x=h.type==="group"?h.items[0].id:h.item.id,g=f;f=[],u.push(a.jsx("div",{className:"group",children:g.map(v=>c(v.seg,v.i))},`turn-${x}`))};for(let h=0;h<n.length;h++){const x=n[h];if(x.type==="single"&&(x.item.kind==="user_text"||x.item.kind==="user_image")){p(),u.push(t.origin.length===0?a.jsx("div",{"data-outline-anchor":x.item.id,children:c(x,h)},`anchor-${x.item.id}`):c(x,h));continue}f.push({seg:x,i:h}),x.type==="single"&&x.item.kind==="task_stats"&&p()}return p(),a.jsx(a.Fragment,{children:u})}const VP=300;function pT({items:e,version:t,ctx:n,scrollElRef:s,outline:o,older:c}){const u=y.useRef(null),f=y.useRef(null),p=f.current??=FP(),[h,x]=y.useState(!1),g=y.useRef(!1),v=y.useRef(null),w=()=>{v.current!==null&&(cancelAnimationFrame(v.current),v.current=null),g.current=!1};y.useEffect(()=>()=>w(),[]);const S=y.useRef(null),C=()=>{const E=u.current;x(!g.current&&!p.stick&&E!==null&&E.scrollHeight-E.scrollTop-E.clientHeight>1)},N=y.useRef(c);N.current=c;const T=y.useRef(c?.prependedCount??0),_=y.useRef(0),R=E=>{const L=N.current;!L||!L.hasMore||L.loading||L.error!==null||E.scrollTop<VP&&L.onLoad()},D=()=>{const E=u.current;if(!E)return;const L=S.current;S.current=E.scrollTop,g.current&&L!==null&&E.scrollTop<L-1&&w(),p.scrolled({scrollTop:E.scrollTop,scrollHeight:E.scrollHeight,clientHeight:E.clientHeight}),R(E),C()};y.useLayoutEffect(()=>{const E=u.current,L=c?.prependedCount??0;E&&L>T.current&&!p.stick&&!g.current&&(E.scrollTop+=E.scrollHeight-_.current),T.current=L,E&&(_.current=E.scrollHeight),E&&p.stick&&!g.current&&Mm(E,p),C()},[t,p,c?.prependedCount]),y.useEffect(()=>{const E=u.current;if(!E||typeof ResizeObserver>"u")return;const L=new ResizeObserver(()=>{_.current=E.scrollHeight,p.stick&&!g.current&&Mm(E,p),C()});return L.observe(E),E.firstElementChild&&L.observe(E.firstElementChild),()=>L.disconnect()},[p]);const z=()=>{const E=u.current;if(!E)return;if(window.matchMedia("(prefers-reduced-motion: reduce)").matches){p.resume(),Mm(E,p),C();return}w(),g.current=!0,E.scrollHeight-E.clientHeight-E.scrollTop>3*E.clientHeight&&(E.scrollTop=E.scrollHeight-4*E.clientHeight);let F=performance.now();const V=P=>{v.current=null;const B=u.current;if(!B||!g.current)return;const Y=Math.min(.05,Math.max(.001,(P-F)/1e3));F=P;const q=B.scrollHeight-B.clientHeight-B.scrollTop;if(q<=1){g.current=!1,p.resume(),Mm(B,p),C();return}const K=Math.max(q*Math.min(1,Y*10),3200*Y);B.scrollTop+=Math.min(K,q),v.current=requestAnimationFrame(V)};v.current=requestAnimationFrame(V),C()};return a.jsxs("div",{className:"relative h-full min-h-0",children:[a.jsx("div",{ref:E=>{u.current=E,s&&(s.current=E)},onScroll:D,onWheel:E=>{p.wheel(E.deltaY),E.deltaY<0&&w(),C()},onTouchStart:E=>{const L=E.touches[0];L&&p.touchStart(L.clientY)},onTouchMove:E=>{const L=E.touches[0];L&&p.touchMove(L.clientY),g.current&&w(),C()},onTouchEnd:()=>p.touchEnd(),className:"anim-fade h-full overflow-y-auto px-4 py-4 md:px-6",children:a.jsxs("div",{className:"mx-auto max-w-3xl",children:[c&&e.length>0&&a.jsx("div",{className:"flex justify-center pb-2",children:c.loading?a.jsxs("span",{className:"flex items-center gap-2 py-1 text-xs text-gray-400 dark:text-gray-500",children:[a.jsx("span",{className:"inline-block h-3 w-3 animate-spin rounded-full border-2 border-gray-400 border-t-transparent"}),d.chat.loadingEarlier]}):c.error!==null?a.jsx("button",{type:"button",onClick:c.onLoad,className:"py-1 text-xs text-red-600 transition-colors duration-150 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300",children:d.chat.loadEarlierRetry}):!c.hasMore&&c.prependedCount>0?a.jsx("span",{className:"py-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.historyBeginning}):null}),e.length===0?a.jsx(Fa,{title:d.chat.emptyStream}):a.jsx(qP,{items:e,ctx:n})]})}),o,h&&a.jsx("button",{type:"button","aria-label":d.chat.jumpToLatest,title:d.chat.jumpToLatest,onClick:z,className:"anim-pop absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-full border border-gray-300 bg-white p-1.5 text-gray-500 shadow-sm transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","aria-hidden":!0,children:a.jsx("path",{d:"M12 5v14M6 13l6 6 6-6",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}const GP=/[\s"'/]on[a-z]+\s*=/i,KP=/href\s*=/i;function WP(e){if(!e)return null;const t=e.trim();if(!/^<svg[\s>]/i.test(t))return null;const n=t.toLowerCase();return n.includes("<script")||n.includes("foreignobject")||KP.test(t)||GP.test(t)?null:t}const Bg=["bg-sky-50 text-sky-600 dark:bg-sky-950/60 dark:text-sky-400","bg-emerald-50 text-emerald-600 dark:bg-emerald-950/60 dark:text-emerald-400","bg-violet-50 text-violet-600 dark:bg-violet-950/60 dark:text-violet-400","bg-amber-50 text-amber-600 dark:bg-amber-950/60 dark:text-amber-400","bg-rose-50 text-rose-600 dark:bg-rose-950/60 dark:text-rose-400","bg-cyan-50 text-cyan-600 dark:bg-cyan-950/60 dark:text-cyan-400","bg-indigo-50 text-indigo-600 dark:bg-indigo-950/60 dark:text-indigo-400","bg-teal-50 text-teal-600 dark:bg-teal-950/60 dark:text-teal-400"],YP={firecrawl:3,"data-analysis":1,"web-design":2,"penguin-sdk":0};function hT(e){const t=YP[e];if(t!==void 0)return Bg[t];let n=0;for(let s=0;s<e.length;s++)n=n*31+e.charCodeAt(s)>>>0;return Bg[n%Bg.length]}function Yf({icon:e,size:t=20,className:n=""}){const s=WP(e);return s?a.jsx("span",{"aria-hidden":!0,style:{width:t,height:t},className:`block shrink-0 [&>svg]:block [&>svg]:h-full [&>svg]:w-full ${n}`,dangerouslySetInnerHTML:{__html:s}}):a.jsx(Oe,{d:My,size:t,className:n})}const IS="rounded px-1 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200";function q0({skills:e,selected:t,onToggle:n,onSelectAll:s,onSelectNone:o,emptyHint:c}){const{locale:u}=Dr(),[f,p]=y.useState(""),h=RP(e,u,f),x=s!==void 0&&o!==void 0;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"border-b border-gray-100 px-2 pb-1.5 pt-0.5 dark:border-gray-800",children:a.jsx("input",{autoFocus:!0,value:f,onChange:g=>p(g.target.value),placeholder:d.chat.skillsSearchPlaceholder,"aria-label":d.chat.skillsSearchPlaceholder,...Gu,className:"w-full rounded border border-transparent bg-transparent px-1 py-0.5 text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"})}),x&&e.length>0&&a.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-gray-100 px-3 py-1 dark:border-gray-800",children:[a.jsx("span",{className:"min-w-0 truncate text-xs text-gray-400 dark:text-gray-500",children:d.skills.selectedCount(t.length)}),a.jsxs("span",{className:"flex shrink-0 items-center gap-0.5",children:[a.jsx("button",{type:"button",className:IS,onClick:()=>s(h.map(g=>g.name)),children:d.skills.selectAll}),a.jsx("button",{type:"button",className:IS,onClick:()=>o(h.map(g=>g.name)),children:d.skills.selectNone})]})]}),a.jsx("div",{className:"max-h-56 overflow-y-auto",children:e.length===0?a.jsx("p",{className:"px-3 py-1.5 text-xs text-gray-400",children:c}):h.length===0?a.jsx("p",{className:"px-3 py-1.5 text-xs text-gray-400",children:d.chat.skillsNoMatch}):h.map(g=>{const v=t.includes(g.name);return a.jsxs("button",{type:"button","aria-pressed":v,onClick:()=>n(g.name),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${v?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx(Yf,{icon:g.icon,size:Ye.inlineGlyph,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"shrink-0 font-mono",children:g.name}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:Wl(u,g)}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:v?"✓":""})]},g.name)})})]})}function V0(e,t){return e.includes(t)?e.filter(n=>n!==t):[...e,t]}function LS(e,t){return[...e,...t.filter(n=>!e.includes(n))]}function OS(e,t){return e.filter(n=>!t.includes(n))}const DS={viewBox:"-0.76 -0.47 28.6 28.6",path:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M26.59,15.92L22.82,13.75C22.92,13.59,22.97,13.4,22.97,13.21L22.97,12.05C22.97,11.66,22.76,11.31,22.43,11.12L21.42,10.54C21.09,10.34,20.68,10.34,20.35,10.54L17.26,12.32C16.93,12.51,16.73,12.86,16.73,13.25L16.73,14.41C16.73,14.79,16.93,15.15,17.26,15.34L24.51,19.53C24.84,19.72,25.25,19.72,25.58,19.53L26.59,18.94C26.92,18.75,27.13,18.4,27.13,18.01L27.13,16.85C27.13,16.47,26.92,16.11,26.59,15.92L26.59,15.92Z"}),a.jsx("path",{d:"M21.88,3.58L18.11,5.75C18.02,5.59,17.89,5.46,17.72,5.36L16.71,4.78C16.38,4.59,15.97,4.59,15.64,4.78L14.63,5.36C14.3,5.55,14.09,5.9,14.09,6.29L14.09,9.86C14.09,10.24,14.3,10.59,14.63,10.78L15.64,11.37C15.97,11.56,16.38,11.56,16.71,11.37L23.96,7.18C24.29,6.99,24.5,6.64,24.5,6.25L24.5,5.09C24.5,4.71,24.29,4.35,23.96,4.16L22.95,3.58C22.62,3.39,22.21,3.39,21.88,3.58L21.88,3.58Z"}),a.jsx("path",{d:"M8.83,1.48L8.83,5.83C8.65,5.83,8.46,5.88,8.3,5.98L7.29,6.56C6.95,6.75,6.75,7.11,6.75,7.49L6.75,8.65C6.75,9.04,6.95,9.39,7.29,9.58L10.37,11.37C10.71,11.56,11.11,11.56,11.45,11.37L12.45,10.78C12.79,10.59,12.99,10.24,12.99,9.85L12.99,1.48C12.99,1.1,12.79,0.75,12.45,0.56L11.45,-0.03C11.11,-0.22,10.71,-0.22,10.37,-0.03L9.37,0.56C9.03,0.75,8.83,1.1,8.83,1.48L8.83,1.48Z"}),a.jsx("path",{d:"M0.5,11.74L4.26,13.91C4.17,14.07,4.12,14.26,4.12,14.45L4.12,15.61C4.12,16,4.32,16.35,4.65,16.54L5.66,17.13C6,17.32,6.4,17.32,6.73,17.13L9.82,15.34C10.15,15.15,10.36,14.8,10.36,14.41L10.36,13.25C10.36,12.87,10.15,12.51,9.82,12.32L2.57,8.14C2.24,7.94,1.84,7.94,1.5,8.14L0.5,8.72C0.16,8.91,-0.04,9.26,-0.04,9.65L-0.04,10.81C-0.04,11.19,0.16,11.55,0.5,11.74Z"}),a.jsx("path",{d:"M5.21,24.08L8.97,21.91C9.07,22.07,9.2,22.21,9.37,22.3L10.38,22.88C10.71,23.08,11.11,23.08,11.45,22.88L12.46,22.3C12.79,22.11,12.99,21.76,12.99,21.37L12.99,17.81C12.99,17.42,12.79,17.07,12.46,16.88L11.45,16.29C11.11,16.1,10.71,16.1,10.38,16.29L3.13,20.48C2.8,20.67,2.59,21.02,2.59,21.41L2.59,22.57C2.59,22.95,2.8,23.31,3.13,23.5L4.14,24.08C4.47,24.28,4.88,24.28,5.21,24.08L5.21,24.08Z"}),a.jsx("path",{d:"M18.26,26.18L18.26,21.83C18.44,21.83,18.63,21.78,18.79,21.68L19.8,21.1C20.13,20.91,20.34,20.56,20.34,20.17L20.34,19.01C20.34,18.62,20.13,18.27,19.8,18.08L16.71,16.3C16.38,16.1,15.97,16.1,15.64,16.3L14.63,16.88C14.3,17.07,14.1,17.42,14.1,17.81L14.1,26.18C14.1,26.56,14.3,26.91,14.63,27.11L15.64,27.69C15.97,27.88,16.38,27.88,16.71,27.69L17.72,27.11C18.05,26.91,18.26,26.56,18.26,26.18L18.26,26.18Z"})]})},XP={anthropic:{path:a.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z"})},openai:{path:a.jsx("path",{d:"M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9108 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.7475-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3685v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3655-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"})},google:{path:a.jsx("path",{d:"M12 24A14.304 14.304 0 0 0 0 12 14.304 14.304 0 0 0 12 0a14.305 14.305 0 0 0 12 12 14.305 14.305 0 0 0-12 12"})},deepseek:{path:a.jsx("path",{d:"M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.328.14a5.526 5.526 0 0 1-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 0 0-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 0 1-.465.137 9.597 9.597 0 0 0-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.034-.237.23-.256a4.173 4.173 0 0 0 1.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 0 1 1.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.615zm1-6.44a.306.306 0 0 1 .415-.287.302.302 0 0 1 .2.288.306.306 0 0 1-.31.307.303.303 0 0 1-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 0 1-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 0 1 .016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 0 1-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.191-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.196-.02.354-.25.452z"})},zhipu:{path:a.jsx("path",{d:"M4.6 3.2h14.8a.9.9 0 0 1 .73 1.43L9.9 18.6h9.2a.9.9 0 0 1 0 1.8H4.6a.9.9 0 0 1-.73-1.43L14.1 5.4H4.6a1.1 1.1 0 0 1 0-2.2Z"})},moonshot:{path:a.jsx("path",{d:"m1.053 16.91 9.538 2.55a21 20.981 0 0 0 .06 2.031l5.956 1.592a12 11.99 0 0 1-15.554-6.172m-1.02-5.79 11.352 3.035a21 20.981 0 0 0-.469 2.01l10.817 2.89a12 11.99 0 0 1-1.845 2.004L.658 15.918a12 11.99 0 0 1-.625-4.796m1.593-5.146L13.573 9.17a21 20.981 0 0 0-1.01 1.874l11.297 3.02a21 20.981 0 0 1-.67 2.362l-11.55-3.087L.125 10.26a12 11.99 0 0 1 1.499-4.285ZM6.067 1.58l11.285 3.016a21 20.981 0 0 0-1.688 1.719l7.824 2.091a21 20.981 0 0 1 .513 2.664L2.107 5.218a12 11.99 0 0 1 3.96-3.638M21.68 4.866 7.222 1.003A12 11.99 0 0 1 21.68 4.866"})},openrouter:{path:a.jsx("path",{d:"M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.396.223-1.342.574-2.185.798-.841.225-1.753.333-1.751.333v4.229s.768.108 1.61.333c.842.224 1.789.575 2.185.799 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918l7.222-4.168-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z"})},siliconflow:{viewBox:"0 0 53.021 25.354",path:a.jsx("path",{d:"M50.7172 0H27.6622C26.3877 0 25.3586 1.03397 25.3586 2.30358V9.21911C25.3586 10.4935 24.3294 11.5227 23.055 11.5227H2.30357C1.02914 11.5227 0 12.5567 0 13.8263V23.0502C0 24.3246 1.03395 25.3538 2.30357 25.3538H25.3586C26.633 25.3538 27.6622 24.3198 27.6622 23.0502V16.1347C27.6622 14.8602 28.6913 13.8311 29.9657 13.8311H50.7172C51.9916 13.8311 53.0207 12.7971 53.0207 11.5275V2.30358C53.0207 1.02916 51.9868 0 50.7172 0Z"})},tokendance:{viewBox:"50.79 100 378.72 280.5",path:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M159 162H52.789C51.4198 162 50.4555 160.655 50.8947 159.358L66.8591 112.225C69.3344 104.918 76.192 100 83.9077 100H321.388C324.459 100 327.524 100.21 330.551 100.726C336.545 101.747 347.179 103.791 354.5 106.5C395.04 121.504 418.5 160 426 191C433.5 222 432 274.5 390.5 327C349 379.5 284 380.5 282 380.5H175.767C174.399 380.5 173.451 379.159 173.886 377.863L192.567 322.275C193.123 320.623 194.677 319.52 196.42 319.545C207.729 319.703 230.558 319.865 251 319.5C279 319 286 318.5 310 305.5C334 292.5 360.5 252.5 352 209.5C345.2 175.1 315.5 163.5 301.5 162H228.992C221.236 162 214.351 166.969 211.908 174.331L147.592 368.169C145.149 375.531 138.264 380.5 130.508 380.5H73.7532C72.3943 380.5 71.4179 379.214 71.8379 377.922C89.6259 323.19 124.669 214.961 129 200C133.4 184.8 150.833 168.333 159 162Z"}),a.jsx("path",{d:"M233 264L248 216",fill:"none",stroke:"currentColor",strokeWidth:25,strokeLinecap:"round"}),a.jsx("path",{d:"M280 264L295 216",fill:"none",stroke:"currentColor",strokeWidth:25,strokeLinecap:"round"})]})},"qwen-token-plan":DS,"qwen-pay-as-you-go":DS,minimax:{path:a.jsx("path",{fillRule:"evenodd",d:"M16.278 2c1.156 0 2.093.927 2.093 2.07v12.501a.74.74 0 00.744.709.74.74 0 00.743-.709V9.099a2.06 2.06 0 012.071-2.049A2.06 2.06 0 0124 9.1v6.561a.649.649 0 01-.652.645.649.649 0 01-.653-.645V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v7.472a2.037 2.037 0 01-2.048 2.026 2.037 2.037 0 01-2.048-2.026v-12.5a.785.785 0 00-.788-.753.785.785 0 00-.789.752l-.001 15.904A2.037 2.037 0 0113.441 22a2.037 2.037 0 01-2.048-2.026V18.04c0-.356.292-.645.652-.645.36 0 .652.289.652.645v1.934c0 .263.142.506.372.638.23.131.514.131.744 0a.734.734 0 00.372-.638V4.07c0-1.143.937-2.07 2.093-2.07zm-5.674 0c1.156 0 2.093.927 2.093 2.07v11.523a.648.648 0 01-.652.645.648.648 0 01-.652-.645V4.07a.785.785 0 00-.789-.78.785.785 0 00-.789.78v14.013a2.06 2.06 0 01-2.07 2.048 2.06 2.06 0 01-2.071-2.048V9.1a.762.762 0 00-.766-.758.762.762 0 00-.766.758v3.8a2.06 2.06 0 01-2.071 2.049A2.06 2.06 0 010 12.9v-1.378c0-.357.292-.646.652-.646.36 0 .653.29.653.646V12.9c0 .418.343.757.766.757s.766-.339.766-.757V9.099a2.06 2.06 0 012.07-2.048 2.06 2.06 0 012.071 2.048v8.984c0 .419.343.758.767.758.423 0 .766-.339.766-.758V4.07c0-1.143.937-2.07 2.093-2.07z"})},fireworks:{viewBox:"0 0 638 315",path:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M318.563 221.755C300.863 221.755 284.979 211.247 278.206 194.978L196.549 0H244.342L318.842 178.361L393.273 0H441.066L358.92 195.048C352.112 211.247 336.263 221.755 318.563 221.755Z"}),a.jsx("path",{d:"M425.111 314.933C407.481 314.933 391.667 304.494 384.824 288.366C377.947 272.097 381.507 253.524 393.936 240.921L542.657 90.2803L561.229 134.094L425.076 271.748L619.147 270.666L637.72 314.479L425.146 315.003L425.076 314.933H425.111Z"}),a.jsx("path",{d:"M0 314.408L18.5727 270.595L212.643 271.677L76.525 133.988L95.0977 90.1748L243.819 240.816C256.247 253.384 259.843 272.026 252.93 288.26C246.088 304.424 230.203 314.827 212.643 314.827L0.0698221 314.339L0 314.408Z"})]})},custom:{stroke:!0,path:a.jsxs(a.Fragment,{children:[a.jsx("path",{d:"M12 2.8 20.5 7.4v9.2L12 21.2 3.5 16.6V7.4L12 2.8Z"}),a.jsx("path",{d:"M3.5 7.4 12 12l8.5-4.6M12 12v9.2"})]})}};function jo({provider:e,className:t}){const n=XP[e];if(!n){const s=yN(e);return a.jsxs("svg",{viewBox:"0 0 24 24",className:t,style:{"--tile-fg":s.fg,"--tile-fg-dark":s.fgDark},"aria-hidden":!0,children:[a.jsx("rect",{x:"0",y:"0",width:"24",height:"24",rx:"5",fill:s.bg}),a.jsx("text",{x:"12",y:"12",textAnchor:"middle",dominantBaseline:"central",fontSize:"13",fontWeight:"700",className:"[fill:var(--tile-fg)] dark:[fill:var(--tile-fg-dark)]",children:bN(e)})]})}return a.jsx("svg",{viewBox:n.viewBox??"0 0 24 24",className:t,"aria-hidden":!0,...n.stroke?{fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinejoin:"round"}:{fill:"currentColor"},children:n.path})}var Tt="https://openrouter.ai/api/v1",Mi="https://api.siliconflow.cn/v1",gl="https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",fo="https://dashscope.aliyuncs.com/compatible-mode/v1",Ks="https://api.fireworks.ai/inference/v1",Ei="https://tokendance.space/gateway/v1",QP="https://api.minimax.io/v1",es=[{id:"deepseek",label:"DeepSeek",envKey:"DEEPSEEK_API_KEY",envBaseUrlKey:"DEEPSEEK_BASE_URL",apiKeyUrl:"https://platform.deepseek.com/api_keys",modelsUrl:"https://api-docs.deepseek.com/quick_start/pricing"},{id:"openrouter",label:"OpenRouter",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://openrouter.ai/workspaces/default/keys",modelsUrl:"https://openrouter.ai/models",gatewayBaseUrl:Tt},{id:"fireworks",label:"Fireworks AI",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://app.fireworks.ai/settings/users/api-keys",modelsUrl:"https://app.fireworks.ai/models",gatewayBaseUrl:Ks},{id:"google",label:"Google Gemini",envKey:"GEMINI_API_KEY",envBaseUrlKey:"GEMINI_BASE_URL",apiKeyUrl:"https://aistudio.google.com/api-keys",modelsUrl:"https://ai.google.dev/gemini-api/docs/models"},{id:"openai",label:"OpenAI",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://platform.openai.com/api-keys",modelsUrl:"https://platform.openai.com/docs/models"},{id:"anthropic",label:"Anthropic",envKey:"ANTHROPIC_API_KEY",envBaseUrlKey:"ANTHROPIC_BASE_URL",apiKeyUrl:"https://platform.claude.com/settings/keys",modelsUrl:"https://docs.claude.com/en/docs/about-claude/models/overview"},{id:"siliconflow",label:"SiliconFlow",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://cloud.siliconflow.cn/me/account/ak",modelsUrl:"https://cloud.siliconflow.cn/models",gatewayBaseUrl:Mi},{id:"tokendance",label:"TokenDance",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://tokendance.space/keys",modelsUrl:"https://tokendance.space/models",gatewayBaseUrl:Ei,oauth:{authorizeUrl:"https://tokendance.space/auth",exchangeUrl:"https://tokendance.space/portal/api/v1/auth/keys",keyName:"PenguinHarness"}},{id:"zhipu",label:"Z.AI (GLM)",envKey:"ZAI_API_KEY",envBaseUrlKey:"ZAI_BASE_URL",apiKeyUrl:"https://open.bigmodel.cn/apikey/platform",modelsUrl:"https://docs.z.ai/guides/overview/pricing"},{id:"moonshot",label:"Moonshot (Kimi)",envKey:"MOONSHOT_API_KEY",envBaseUrlKey:"MOONSHOT_BASE_URL",apiKeyUrl:"https://platform.kimi.com/console/api-keys",modelsUrl:"https://platform.kimi.com/docs/pricing"},{id:"minimax",label:"MiniMax",envKey:"MINIMAX_API_KEY",envBaseUrlKey:"MINIMAX_BASE_URL",apiKeyUrl:"https://platform.minimax.io/user-center/basic-information/interface-key",modelsUrl:"https://platform.minimax.io/docs/guides/models-intro"},{id:"qwen-pay-as-you-go",label:"Qwen Pay-As-You-Go",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://platform.qianwenai.com/docs/api-reference/preparation/api-key",modelsUrl:"https://www.qianwenai.com/models",gatewayBaseUrl:fo},{id:"qwen-token-plan",label:"Qwen Token Plan",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL",apiKeyUrl:"https://platform.qianwenai.com/pricing/token-plan",modelsUrl:"https://platform.qianwenai.com/docs/token-plan/personal/token-plan-personal-overview",gatewayBaseUrl:gl},{id:"custom",label:"Custom",envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL"}];function Kt(e,t,n){const s=o=>Math.round(o/7*1e6)/1e6;return Fe(s(e),s(t),s(n))}function Fe(e,t,n){return{unit:"usd_per_mtok",cache_read:e,cache_write:t,output:n}}var gT=[{modelId:"deepseek-v4-flash",displayName:"DeepSeek V4 Flash",provider:"deepseek",contextWindow:1e6,pricing:Kt(.05,1.5,4.5),supportsVision:!1},{modelId:"deepseek-v4-flash-vision-exp",displayName:"DeepSeek V4 Flash Vision Exp",provider:"deepseek",contextWindow:1e6,pricing:Kt(.05,1.5,4.5),supportsVision:!0},{modelId:"deepseek-v4-pro",displayName:"DeepSeek V4 Pro",provider:"deepseek",contextWindow:1e6,pricing:Kt(.15,4.5,13.5),supportsVision:!1},{modelId:"anthropic/claude-fable-5",displayName:"Claude Fable 5",provider:"openrouter",contextWindow:1e6,pricing:Fe(1,12.5,50),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"anthropic/claude-opus-5",displayName:"Claude Opus 5",provider:"openrouter",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"anthropic/claude-opus-4.8",displayName:"Claude Opus 4.8",provider:"openrouter",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"anthropic/claude-opus-4.7",displayName:"Claude Opus 4.7",provider:"openrouter",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"anthropic/claude-sonnet-5",displayName:"Claude Sonnet 5",provider:"openrouter",contextWindow:1e6,pricing:Fe(.2,2.5,10),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"deepseek/deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",provider:"openrouter",contextWindow:1e6,pricing:Fe(.0157192,.078596,.157192),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"deepseek/deepseek-v4-flash",displayName:"DeepSeek V4 Flash",provider:"openrouter",contextWindow:1e6,pricing:Fe(.0168,.0679,.168),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"deepseek/deepseek-v4-flash-vision-exp",displayName:"DeepSeek V4 Flash Vision Exp",provider:"openrouter",contextWindow:1048576,pricing:Fe(.007,.22,.66),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"deepseek/deepseek-v4-pro-0813",displayName:"DeepSeek V4 Pro 0813",provider:"openrouter",contextWindow:1048576,pricing:Fe(.022,.66,1.98),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"deepseek/deepseek-v4-pro",displayName:"DeepSeek V4 Pro",provider:"openrouter",contextWindow:1e6,pricing:Fe(.022,.66,1.98),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"google/gemini-3.7-flash",displayName:"Gemini 3.7 Flash",provider:"openrouter",contextWindow:1048576,pricing:Fe(.0375,.375,1.875),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"google/gemini-3.6-flash",displayName:"Gemini 3.6 Flash",provider:"openrouter",contextWindow:1048576,pricing:Fe(.15,1.5,7.5),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"google/gemini-3.5-flash",displayName:"Gemini 3.5 Flash",provider:"openrouter",contextWindow:1048576,pricing:Fe(.15,1.5,9),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"google/gemini-3.5-flash-lite",displayName:"Gemini 3.5 Flash-Lite",provider:"openrouter",contextWindow:1048576,pricing:Fe(.03,.3,2.5),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"minimax/minimax-m3",displayName:"MiniMax M3",provider:"openrouter",contextWindow:1048576,pricing:Fe(.06,.3,1.2),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"moonshotai/kimi-k3",displayName:"Kimi K3",provider:"openrouter",contextWindow:1e6,pricing:Fe(.3,3,15),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"moonshotai/kimi-k2.6",displayName:"Kimi K2.6",provider:"openrouter",contextWindow:262144,pricing:Fe(.0992,.589,2.48),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"nvidia/nemotron-3-ultra-550b-a55b:free",displayName:"Nemotron 3 Ultra (free)",provider:"openrouter",contextWindow:1e6,pricing:Fe(0,0,0),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"openai/gpt-5.6-luna",displayName:"GPT-5.6 Luna",provider:"openrouter",contextWindow:105e4,pricing:Fe(.02,.25,1.2),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.6-sol",displayName:"GPT-5.6 Sol",provider:"openrouter",contextWindow:105e4,pricing:Fe(.25,3.125,15),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.6-terra",displayName:"GPT-5.6 Terra",provider:"openrouter",contextWindow:105e4,pricing:Fe(.2,2.5,12),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.5",displayName:"GPT-5.5",provider:"openrouter",contextWindow:105e4,pricing:Fe(.5,5,30),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.5-pro",displayName:"GPT-5.5 Pro",provider:"openrouter",contextWindow:105e4,pricing:Fe(30,30,180),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.4",displayName:"GPT-5.4",provider:"openrouter",contextWindow:105e4,pricing:Fe(.25,2.5,15),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.4-mini",displayName:"GPT-5.4 mini",provider:"openrouter",contextWindow:4e5,pricing:Fe(.075,.75,4.5),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.4-nano",displayName:"GPT-5.4 nano",provider:"openrouter",contextWindow:4e5,pricing:Fe(.02,.2,1.25),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openai/gpt-5.4-pro",displayName:"GPT-5.4 Pro",provider:"openrouter",contextWindow:105e4,pricing:Fe(30,30,180),supportsVision:!0,clientType:"openai-responses",baseUrl:Tt},{modelId:"openrouter/free",displayName:"Free Models Router",provider:"openrouter",contextWindow:128e3,pricing:Fe(0,0,0),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"qwen/qwen3.8-max",displayName:"Qwen 3.8 Max",provider:"openrouter",contextWindow:1e6,pricing:Fe(.25,2.5,6),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"qwen/qwen3.6-35b-a3b",displayName:"Qwen 3.6 35B A3B",provider:"openrouter",contextWindow:262144,pricing:Fe(.05,.14,1),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"stepfun/step-3.7-flash",displayName:"Step 3.7 Flash",provider:"openrouter",contextWindow:256e3,pricing:Fe(.04,.2,1.15),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"tencent/hy3",displayName:"Hy3",provider:"openrouter",contextWindow:262144,pricing:Fe(.033,.132,.528),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"thinkingmachines/inkling",displayName:"Inkling",provider:"openrouter",contextWindow:1e6,pricing:Fe(.17,1,4.05),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"x-ai/grok-4.6",displayName:"Grok 4.6",provider:"openrouter",contextWindow:5e5,pricing:Fe(.5,2,6),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"x-ai/grok-4.5",displayName:"Grok 4.5",provider:"openrouter",contextWindow:5e5,pricing:Fe(.3,2,6),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"xiaomi/mimo-v2.5",displayName:"MiMo-V2.5",provider:"openrouter",contextWindow:1048576,pricing:Fe(.0028,.14,.28),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"z-ai/glm-5.3",displayName:"GLM-5.3",provider:"openrouter",contextWindow:1048576,pricing:Fe(.26,1.4,4.4),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"z-ai/glm-5.3-flash",displayName:"GLM-5.3 Flash",provider:"openrouter",contextWindow:1048576,pricing:Fe(.015,.075,.25),supportsVision:!0,clientType:"openai-chat",baseUrl:Tt},{modelId:"z-ai/glm-5.2",displayName:"GLM-5.2",provider:"openrouter",contextWindow:1e6,pricing:Fe(.1261,.679,2.134),supportsVision:!1,clientType:"openai-chat",baseUrl:Tt},{modelId:"accounts/fireworks/models/deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",provider:"fireworks",contextWindow:1e6,pricing:Fe(.028,.14,.28),supportsVision:!1,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/deepseek-v4-flash",displayName:"DeepSeek V4 Flash",provider:"fireworks",contextWindow:1e6,pricing:Fe(.03,.14,.28),supportsVision:!1,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/deepseek-v4-pro",displayName:"DeepSeek V4 Pro",provider:"fireworks",contextWindow:1e6,pricing:Fe(.15,1.74,3.48),supportsVision:!1,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/glm-5p2",displayName:"GLM-5.2",provider:"fireworks",contextWindow:1e6,pricing:Fe(.14,1.4,4.4),supportsVision:!1,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/inkling",displayName:"Inkling",provider:"fireworks",contextWindow:1e6,pricing:Fe(.17,1,4.05),supportsVision:!0,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/kimi-k3",displayName:"Kimi K3",provider:"fireworks",contextWindow:1e6,pricing:Fe(.3,3,15),supportsVision:!0,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/kimi-k2p7-code",displayName:"Kimi K2.7 Code",provider:"fireworks",contextWindow:262144,pricing:Fe(.19,.95,4),supportsVision:!0,clientType:"openai-chat",baseUrl:Ks},{modelId:"accounts/fireworks/models/minimax-m3",displayName:"MiniMax M3",provider:"fireworks",contextWindow:524288,pricing:Fe(.06,.3,1.2),supportsVision:!0,clientType:"openai-chat",baseUrl:Ks},{modelId:"deepseek-ai/DeepSeek-V4-Flash",displayName:"DeepSeek V4 Flash",provider:"siliconflow",contextWindow:1e6,pricing:Kt(.02,1,2),supportsVision:!1,clientType:"openai-chat",baseUrl:Mi},{modelId:"deepseek-ai/DeepSeek-V4-Pro",displayName:"DeepSeek V4 Pro",provider:"siliconflow",contextWindow:1e6,pricing:Kt(.1,12,24),supportsVision:!1,clientType:"openai-chat",baseUrl:Mi},{modelId:"meituan-longcat/LongCat-2.0",displayName:"LongCat 2.0",provider:"siliconflow",contextWindow:1e6,pricing:Kt(.1,5,20),supportsVision:!1,clientType:"openai-chat",baseUrl:Mi},{modelId:"moonshotai/Kimi-K2.7-Code",displayName:"Kimi K2.7 Code",provider:"siliconflow",contextWindow:262144,pricing:Kt(1.3,6.5,27),supportsVision:!0,clientType:"openai-chat",baseUrl:Mi},{modelId:"Pro/moonshotai/Kimi-K2.6",displayName:"Kimi K2.6",provider:"siliconflow",contextWindow:262144,pricing:Kt(1.1,6.5,27),supportsVision:!0,clientType:"openai-chat",baseUrl:Mi},{modelId:"Qwen/Qwen3.6-35B-A3B",displayName:"Qwen 3.6 35B A3B",provider:"siliconflow",contextWindow:262144,pricing:Kt(1.8,1.8,10.8),supportsVision:!0,clientType:"openai-chat",baseUrl:Mi},{modelId:"zai-org/GLM-5.2",displayName:"GLM-5.2",provider:"siliconflow",contextWindow:1e6,pricing:Kt(2,8,28),supportsVision:!1,clientType:"openai-chat",baseUrl:Mi},{modelId:"deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",provider:"tokendance",contextWindow:1048576,pricing:Kt(.05,1.5,4.5),supportsVision:!1,clientType:"openai-chat",baseUrl:Ei},{modelId:"deepseek-v4-flash-vision-exp",displayName:"DeepSeek V4 Flash Vision Exp",provider:"tokendance",contextWindow:1e6,pricing:Kt(.05,1.5,4.5),supportsVision:!0,clientType:"openai-chat",baseUrl:Ei},{modelId:"deepseek-v4-pro-0813",displayName:"DeepSeek V4 Pro 0813",provider:"tokendance",contextWindow:1e6,pricing:Kt(.15,4.5,13.5),supportsVision:!1,clientType:"openai-chat",baseUrl:Ei},{modelId:"glm-5.3",displayName:"GLM-5.3",provider:"tokendance",contextWindow:1e6,pricing:Kt(2,8,28),supportsVision:!1,clientType:"openai-chat",baseUrl:Ei},{modelId:"glm-5.3-flash",displayName:"GLM-5.3 Flash",provider:"tokendance",contextWindow:1e6,pricing:Kt(.23,.8,2.8),supportsVision:!0,clientType:"openai-chat",baseUrl:Ei},{modelId:"kimi-k3",displayName:"Kimi K3",provider:"tokendance",contextWindow:1048576,pricing:Kt(2,20,100),supportsVision:!0,clientType:"openai-chat",baseUrl:Ei},{modelId:"qwen3.8-max",displayName:"Qwen 3.8 Max",provider:"tokendance",contextWindow:1e6,pricing:Kt(1.5,12,36),supportsVision:!0,clientType:"openai-chat",baseUrl:Ei},{modelId:"deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",provider:"qwen-token-plan",contextWindow:1e6,pricing:Kt(.2,1,2),supportsVision:!1,clientType:"openai-chat",baseUrl:gl},{modelId:"deepseek-v4-pro",displayName:"DeepSeek V4 Pro",provider:"qwen-token-plan",contextWindow:1e6,pricing:Kt(1,12,24),supportsVision:!1,clientType:"openai-chat",baseUrl:gl},{modelId:"glm-5.2",displayName:"GLM-5.2",provider:"qwen-token-plan",contextWindow:1048576,pricing:Kt(2,8,28),supportsVision:!1,clientType:"openai-chat",baseUrl:gl},{modelId:"qwen3.8-max",displayName:"Qwen 3.8 Max",provider:"qwen-token-plan",contextWindow:1e6,pricing:Kt(1.5,12,36),supportsVision:!0,clientType:"openai-chat",baseUrl:gl},{modelId:"qwen3.7-plus",displayName:"Qwen 3.7 Plus",provider:"qwen-token-plan",contextWindow:1e6,pricing:Kt(.4,2,8),supportsVision:!0,clientType:"openai-chat",baseUrl:gl},{modelId:"deepseek-v4-flash-0731",displayName:"DeepSeek V4 Flash 0731",provider:"qwen-pay-as-you-go",contextWindow:1e6,pricing:Kt(.2,1,2),supportsVision:!1,clientType:"openai-chat",baseUrl:fo},{modelId:"kimi/kimi-k3",displayName:"Kimi K3",provider:"qwen-pay-as-you-go",contextWindow:1048576,pricing:Kt(2,20,100),supportsVision:!0,clientType:"openai-chat",baseUrl:fo},{modelId:"qwen3.8-flash",displayName:"Qwen 3.8 Flash",provider:"qwen-pay-as-you-go",contextWindow:1e6,pricing:Kt(.1,1,3),supportsVision:!0,clientType:"openai-chat",baseUrl:fo},{modelId:"qwen3.8-max",displayName:"Qwen 3.8 Max",provider:"qwen-pay-as-you-go",contextWindow:1e6,pricing:Kt(1.5,12,36),supportsVision:!0,clientType:"openai-chat",baseUrl:fo},{modelId:"qwen3.7-plus",displayName:"Qwen 3.7 Plus",provider:"qwen-pay-as-you-go",contextWindow:1e6,pricing:Kt(.4,2,8),supportsVision:!0,clientType:"openai-chat",baseUrl:fo},{modelId:"ZHIPU/GLM-5.2",displayName:"GLM-5.2",provider:"qwen-pay-as-you-go",contextWindow:1048576,pricing:Kt(2,8,28),supportsVision:!1,clientType:"openai-chat",baseUrl:fo},{modelId:"MiniMax-M3",displayName:"MiniMax M3",provider:"minimax",contextWindow:1e6,pricing:Fe(.06,.3,1.2),supportsVision:!0,clientType:"minimax-m3",baseUrl:QP},{modelId:"gemini-3.7-flash",displayName:"Gemini 3.7 Flash",provider:"google",contextWindow:1048576,pricing:Fe(.15,1.5,7.5),supportsVision:!0},{modelId:"gemini-3.6-flash",displayName:"Gemini 3.6 Flash",provider:"google",contextWindow:1048576,pricing:Fe(.15,1.5,7.5),supportsVision:!0},{modelId:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",provider:"google",contextWindow:1048576,pricing:Fe(.15,1.5,9),supportsVision:!0},{modelId:"gemini-3.5-flash-lite",displayName:"Gemini 3.5 Flash-Lite",provider:"google",contextWindow:1048576,pricing:Fe(.03,.3,2.5),supportsVision:!0},{modelId:"gemini-3.1-flash-lite",displayName:"Gemini 3.1 Flash-Lite",provider:"google",contextWindow:1048576,pricing:Fe(.025,.25,1.5),supportsVision:!0},{modelId:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro (Preview)",provider:"google",contextWindow:1048576,pricing:Fe(.2,2,12),supportsVision:!0},{modelId:"gemini-3-flash-preview",displayName:"Gemini 3 Flash (Preview)",provider:"google",contextWindow:1048576,pricing:Fe(.05,.5,3),supportsVision:!0},{modelId:"claude-fable-5",displayName:"Claude Fable 5",provider:"anthropic",contextWindow:1e6,pricing:Fe(1,12.5,50),supportsVision:!0},{modelId:"claude-opus-5",displayName:"Claude Opus 5",provider:"anthropic",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0},{modelId:"claude-opus-4-8",displayName:"Claude Opus 4.8",provider:"anthropic",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0},{modelId:"claude-opus-4-7",displayName:"Claude Opus 4.7",provider:"anthropic",contextWindow:1e6,pricing:Fe(.5,6.25,25),supportsVision:!0},{modelId:"claude-sonnet-5",displayName:"Claude Sonnet 5",provider:"anthropic",contextWindow:1e6,pricing:Fe(.2,2.5,10),supportsVision:!0},{modelId:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",provider:"anthropic",contextWindow:1e6,pricing:Fe(.3,3.75,15),supportsVision:!0},{modelId:"gpt-5.6",displayName:"GPT-5.6 Sol",provider:"openai",contextWindow:105e4,pricing:Fe(.5,5,30),supportsVision:!0},{modelId:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",provider:"openai",contextWindow:105e4,pricing:Fe(.02,.2,1.2),supportsVision:!0},{modelId:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",provider:"openai",contextWindow:105e4,pricing:Fe(.2,2,12),supportsVision:!0},{modelId:"gpt-5.5",displayName:"GPT-5.5",provider:"openai",contextWindow:105e4,pricing:Fe(.5,5,30),supportsVision:!0},{modelId:"gpt-5.5-pro",displayName:"GPT-5.5 Pro",provider:"openai",contextWindow:105e4,pricing:Fe(30,30,180),supportsVision:!0},{modelId:"gpt-5.4",displayName:"GPT-5.4",provider:"openai",contextWindow:105e4,pricing:Fe(.25,2.5,15),supportsVision:!0},{modelId:"gpt-5.4-mini",displayName:"GPT-5.4 mini",provider:"openai",contextWindow:4e5,pricing:Fe(.075,.75,4.5),supportsVision:!0},{modelId:"gpt-5.4-nano",displayName:"GPT-5.4 nano",provider:"openai",contextWindow:4e5,pricing:Fe(.02,.2,1.25),supportsVision:!0},{modelId:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",provider:"openai",contextWindow:105e4,pricing:Fe(30,30,180),supportsVision:!0},{modelId:"glm-5.3",displayName:"GLM-5.3",provider:"zhipu",contextWindow:1e6,pricing:Fe(.26,1.4,4.4),supportsVision:!1},{modelId:"glm-5.3-flash",displayName:"GLM-5.3 Flash",provider:"zhipu",contextWindow:1e6,pricing:Fe(.03,.15,.5),supportsVision:!0},{modelId:"glm-5.2",displayName:"GLM-5.2",provider:"zhipu",contextWindow:1e6,pricing:Fe(.26,1.4,4.4),supportsVision:!1},{modelId:"glm-5.1",displayName:"GLM-5.1",provider:"zhipu",contextWindow:2e5,pricing:Fe(.26,1.4,4.4),supportsVision:!1},{modelId:"glm-5",displayName:"GLM-5",provider:"zhipu",contextWindow:2e5,pricing:Fe(.2,1,3.2),supportsVision:!1},{modelId:"kimi-k3",displayName:"Kimi K3",provider:"moonshot",contextWindow:1048576,pricing:Kt(2,20,100),supportsVision:!0},{modelId:"kimi-k2.6",displayName:"Kimi K2.6",provider:"moonshot",contextWindow:262144,pricing:Kt(1.1,6.5,27),supportsVision:!0},{modelId:"kimi-k2.5",displayName:"Kimi K2.5",provider:"moonshot",contextWindow:262144,pricing:Kt(.7,4,21),supportsVision:!0}];function ZP(e){if(e!==void 0)return e.trim().toLowerCase()==="openai"?"openai-chat":e}function G0(e,t){return gT.find(n=>n.provider===e&&n.modelId===t)}function Ws(e){return es.find(t=>t.id===e)}function JP(e,t){const s=t?.toLowerCase()||e.toLowerCase(),o=c=>({envKey:`${c}_API_KEY`,envBaseUrlKey:`${c}_BASE_URL`});if(s.includes("gemini-3")||s.includes("gemini-embedding"))return o("GEMINI");if(s.includes("claude")&&(s.includes("4-7")||s.includes("4-8")||s.includes("-5")||s.includes("4-6")))return o("ANTHROPIC");if(s.includes("gpt-5.4")||s.includes("gpt-5.5")||s.includes("gpt-5.6"))return o("OPENAI");if(s.includes("glm-5"))return o("ZAI");if(s.includes("kimi-k3")||s.includes("kimi-k2.5")||s.includes("kimi-k2.6"))return o("MOONSHOT");if(s==="minimax-m3"&&e.toLowerCase()==="minimax-m3")return o("MINIMAX");if(s.includes("deepseek-v4"))return o("DEEPSEEK");if(s.includes("ant-messages"))return o("ANTHROPIC");if(s.includes("openai"))return o("OPENAI")}function ez(e,t,n){const s=t?.toLowerCase()||e.toLowerCase();if(s==="minimax-m3")return"openai";if(!(s.includes("gemini-3")||s.includes("gemini-embedding"))){if(s.includes("claude")&&(s.includes("4-6")||s.includes("4-7")||s.includes("4-8")||s.includes("-5")))return n?.startsWith("bedrock://")||e.includes("4-6")?void 0:"anthropic";if(s.includes("gpt-5.4")||s.includes("gpt-5.5")||s.includes("gpt-5.6"))return"openai";if(!s.includes("glm-5")&&!(s.includes("kimi-k3")||s.includes("kimi-k2.5")||s.includes("kimi-k2.6"))&&!s.includes("deepseek-v4")){if(s.includes("ant-messages"))return"anthropic";if(s.includes("openai-responses"))return"openai";if(!(s.includes("openai")&&s.includes("embedding"))&&s.includes("openai"))return"openai"}}}function tz(){return gT.map(e=>({provider:e.provider,model_id:e.modelId,...e.contextWindow!==void 0?{context_window:e.contextWindow}:{},...e.clientType!==void 0?{client_type:e.clientType}:{},...e.pricing?{pricing:{...e.pricing}}:{},...e.supportsVision?{}:{vision:!1},...e.baseUrl!==void 0?{base_url:e.baseUrl}:{}}))}function $S(e,t){if(e==="openrouter")return`https://openrouter.ai/${t}`;if(e==="qwen-token-plan")return`https://www.qianwenai.com/models/${t}`;if(e==="fireworks"){const n=/^accounts\/([^/]+)\/models\/(.+)$/.exec(t);return n?`https://app.fireworks.ai/models/${n[1]}/${n[2]}`:Ws(e)?.modelsUrl}if(e==="tokendance")return`https://tokendance.space/models/${t}`;if(e==="qwen-pay-as-you-go")return`https://www.qianwenai.com/models/${encodeURIComponent(t)}`;if(e==="zhipu")return`https://docs.z.ai/guides/llm/${t}`;if(e==="moonshot"){const n=/^kimi-k(\d+)\.(\d+)$/.exec(t);return n?`https://platform.kimi.com/docs/pricing/chat-k${n[1]}${n[2]}`:Ws(e)?.modelsUrl}if(e!=="custom")return Ws(e)?.modelsUrl}const xT=e=>`penguin.modelsGroupOrder.${e}`;function K0(e,t){return e===null?[]:Kx(xT(e),t)}function nz(e,t,n){e!==null&&Wx(xT(e),t,n)}function rz(e,t,n){if(n.length===0)return[...e];const s=new Map(n.map((u,f)=>[u,f])),o=[],c=[];for(const u of e)(s.has(t(u))?o:c).push(u);return o.sort((u,f)=>(s.get(t(u))??0)-(s.get(t(f))??0)),[...o,...c]}function az(e,t,n,s,o){const c=new Set(e),u=[...e,...t.filter(p=>!c.has(p))],f=Yx(u,n,s,o);return f===u?e:f}function zt(e,t){return!!e&&!!t&&e.provider===t.provider&&e.modelId===t.modelId}function Qm(e){return{id:e,label:e,envKey:"OPENAI_API_KEY",envBaseUrlKey:"OPENAI_BASE_URL"}}function yT(e,t){const n=t.trim().toLowerCase();if(!n)return!0;const s=es.find(o=>o.id===e.provider);return e.modelId.toLowerCase().includes(n)||(e.displayName??"").toLowerCase().includes(n)||e.provider.toLowerCase().includes(n)||(s?.label??"").toLowerCase().includes(n)}function bT(e){return[...new Set(e.map(t=>t.provider).filter(t=>!es.some(n=>n.id===t)))].sort()}function sz(e){return[...es.map(t=>t.id),...bT(e)]}function vT(e,t,n=[]){const s=t.trim()!=="",o=e.filter(p=>yT(p,t)),c=es.map(p=>({provider:p,rows:o.filter(h=>h.provider===p.id)})),u=bT(o).map(p=>({provider:Qm(p),rows:o.filter(h=>h.provider===p)}));return rz([...c,...u],p=>p.provider.id,n).filter(p=>p.rows.length>0||!s&&p.provider.id==="custom")}function iz(e,t=[]){return vT(e,"",t).flatMap(n=>n.rows)}function Ol(e){return!!e.credential?.apiKeyMasked||!!e.envKeyMasked}function kT(e){return e?[e.cacheRead,e.cacheWrite,e.output].every(t=>typeof t=="string"?t.trim()!==""&&Number(t)===0:t===0):!1}function US(e,{showAll:t,query:n,selected:s,defaultModel:o,groupOrder:c}){const u=iz(e,c);return(t||!u.some(Ol)?u:u.filter(p=>Ol(p)||zt(p,s)||zt(p,o))).filter(p=>yT(p,n))}function Ru({open:e,setOpen:t,leading:n,label:s,labelClassName:o="",muted:c=!1,title:u,ariaLabel:f,ariaHaspopup:p="listbox",disabled:h=!1,menuClass:x,children:g}){return a.jsx(Qn,{open:e,setOpen:t,menuClass:x,portal:{direction:"down",align:"left"},button:a.jsxs("button",{type:"button",title:u,"aria-label":f,"aria-haspopup":p,"aria-expanded":e,disabled:h,onClick:()=>t(!e),className:`flex w-full items-center gap-2 text-left ${Uf} ${Pf.sm} disabled:cursor-not-allowed disabled:opacity-60`,children:[n,a.jsx("span",{className:`min-w-0 flex-1 truncate ${c?"text-gray-400":""} ${o}`,children:s}),a.jsx(ns,{className:"text-gray-400"})]}),children:g})}function hu(e){return e.displayName??e.modelId}const oz="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4M2 2l20 20";function Ey({items:e,itemKey:t,isCurrent:n,query:s,onQueryChange:o,searchPlaceholder:c,emptyText:u,onPick:f,renderRow:p,footer:h}){const[x,g]=y.useState(-1),v=x>=0&&x<e.length?t(e[x]):null,w=S=>{if(e.length!==0){if(S.key==="ArrowDown"){S.preventDefault(),g(C=>(C+1)%e.length);return}if(S.key==="ArrowUp"){S.preventDefault(),g(C=>C<=0?e.length-1:C-1);return}(S.key==="Enter"&&!S.shiftKey||S.key==="Tab")&&!S.nativeEvent.isComposing&&(S.preventDefault(),f(e[x>=0?x:0]))}};return a.jsxs("div",{className:"contents",onKeyDown:w,children:[a.jsx("div",{className:"border-b border-gray-100 px-2 pb-1.5 pt-0.5 dark:border-gray-800",children:a.jsx("input",{autoFocus:!0,value:s,onChange:S=>{o(S.target.value),g(-1)},placeholder:c,"aria-label":c,...Gu,className:"w-full rounded border border-transparent bg-transparent px-1 py-0.5 text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"})}),a.jsxs("div",{className:"max-h-56 overflow-y-auto",children:[e.length===0&&a.jsx("p",{className:"px-3 py-1.5 text-xs text-gray-400",children:u}),e.map(S=>{const C=t(S),N=n?.(S)??!1;return a.jsxs("button",{type:"button",ref:C===v?T=>T?.scrollIntoView({block:"nearest"}):void 0,onClick:()=>f(S),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${N?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}${C===v?" bg-gray-100 dark:bg-gray-800":""}`,children:[p(S),a.jsx("span",{className:"w-3 shrink-0 text-center text-xs",children:N?"✓":""})]},C)})]}),h]})}function wT({models:e,value:t,defaultModel:n,onPick:s}){const[o,c]=y.useState(""),[u,f]=y.useState(!1),{currentProject:p}=en(),h=p?.projectId??null,x=y.useMemo(()=>K0(h),[h]),g=US(e,{showAll:u,query:o,selected:t,defaultModel:n,groupOrder:x}),v=u?0:US(e,{showAll:!0,query:o,selected:t,defaultModel:n,groupOrder:x}).length-g.length;return a.jsx(Ey,{items:g,itemKey:w=>`${w.provider}:${w.modelId}`,isCurrent:w=>zt(w,t),query:o,onQueryChange:c,searchPlaceholder:d.models.searchPlaceholder,emptyText:d.models.noSearchResults,onPick:s,renderRow:w=>a.jsxs(a.Fragment,{children:[a.jsx(jo,{provider:w.provider,className:"h-4 w-4 shrink-0"}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:hu(w)}),kT(w.pricing)&&a.jsx("span",{className:"shrink-0",children:a.jsx(On,{tone:"yellow",children:d.models.freeBadge})}),!Ol(w)&&a.jsx("span",{role:"img",title:d.models.noKey,"aria-label":d.models.noKey,className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(Oe,{d:oz,size:13})}),zt(w,n)&&a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:d.models.default})]}),...v>0?{footer:a.jsx("div",{className:"border-t border-gray-100 dark:border-gray-800",children:a.jsx("button",{type:"button",onClick:()=>f(!0),className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300",children:d.models.showModelsWithoutKey(v)})})}:{}})}function Ay({models:e,value:t,defaultModel:n,onChange:s,disabled:o,variant:c="pill"}){const[u,f]=y.useState(!1),p=e.find(v=>zt(v,t)),h=p?hu(p):t?.modelId??"…",x=a.jsx(jo,{provider:p?.provider??t?.provider??"custom",className:"h-4 w-4 shrink-0"}),g=a.jsx(wT,{models:e,value:t,...n!==void 0?{defaultModel:n}:{},onPick:v=>{s({provider:v.provider,modelId:v.modelId}),f(!1)}});return c==="form"?a.jsx(Ru,{open:u,setOpen:f,leading:x,label:h,title:`${d.chat.chooseModel}:${h}`,ariaLabel:d.chat.chooseModel,ariaHaspopup:"listbox",disabled:o||e.length===0,menuClass:"w-max min-w-56 origin-top-left",children:g}):a.jsx(Qn,{open:u,setOpen:f,menuClass:"w-max min-w-56 origin-top-right",portal:{direction:"down",align:"right"},button:a.jsxs("button",{type:"button",title:`${d.chat.chooseModel}:${h}`,"aria-label":d.chat.chooseModel,disabled:o||e.length===0,onClick:()=>f(!u),className:"flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[x,a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:h}),a.jsx(ns,{size:Ye.caretDense})]}),children:g})}const lz=/^[\w-]*$/;function PS(e,t){const n=e.slice(0,t),s=n.lastIndexOf("/");if(s<0||s>0&&!/\s/.test(n[s-1]))return null;const o=n.slice(s+1);if(!lz.test(o))return null;const c=/^[\w-]*/.exec(e.slice(t))[0];return{start:s,end:t+c.length,query:o}}function cz(e,t){const n=e.slice(0,t.start),s=e.slice(t.end),o=n.endsWith(" ")&&s.startsWith(" ")?n+s.slice(1):n+s;return/^\s*$/.test(o)?"":o}const uz=["none","low","medium","high","xhigh","max"],ST=["low","medium","high","xhigh","max"];function dz(e,t){return e||(t??"medium")}function W0(e,t){return t&&uz.includes(t)?e[t]??t:null}function Hg(e,t){return e||t}function mz(e,t,n){const s=e.filter(([o])=>o!=="").map(([o,c])=>({value:o,triggerLabel:o,label:o,description:c}));return n==="none"&&s.push({value:"none",triggerLabel:"none",label:"none",description:t}),s}function fz(e){let t=e.length-1,n=!1;for(;t>=0&&e[t].kind==="compaction";){const s=e[t];!s.running&&s.status==="completed"&&(n=!0),t--}return t<0?!1:!n}function pz(e,t,n){return t!==""&&n===t?!1:fz(e)}function jT(e){let t=0,n=0;for(const s of e)s.kind!=="compaction"||s.running===!0||(t++,s.status==="completed"&&n++);return{settled:t,completed:n}}function hz(e,t){const n=jT(e);return n.completed>t.completed?"completed":n.settled>t.settled?"failed":"pending"}function gz(e,t){if(e.phase==="ask")return{act:"wait"};if(e.phase==="settle")return{act:"apply",level:e.level,notice:"none"};const n=hz(t,e.baseline);return n==="pending"?{act:"wait"}:{act:"apply",level:e.level,notice:n==="completed"?"compacted":"compaction-failed"}}function xz(e){const t=e.currentText;return{text:t.trim()?e.recalledText?`${e.recalledText}
|
|
171
171
|
${t}`:t:e.recalledText,dropGoal:e.goalOn&&e.recalledFiles>0}}function yz(e){const t=e.exampleSkills.filter(n=>e.installedSkills.includes(n)&&!e.selectedSkills.includes(n));return{text:e.prompt,skills:[...e.selectedSkills,...t]}}function CT(e){if(TN(e)||EN(e))return null;const t=_l(e);if(t)return{body:t.rest.trim(),scheduled:!1,backgroundDone:!0};const n=AN(e),s=n?n.rest:e,o=MN(s),c=o?o.rest:s,u=CN(c),{text:f}=df(u?u.rest:c);return{body:f.trim(),...n?{goalRound:n.round}:{},scheduled:o!==null}}function bz(e){const t=[],n=s=>{s!==""&&t[t.length-1]!==s&&t.push(s)};for(const s of e)if(s.kind==="user_text"){const o=CT(s.text);if(!o||o.scheduled||o.backgroundDone||o.goalRound!==void 0&&o.goalRound>1)continue;n(o.body)}else s.kind==="user_steering"&&n(df(s.text).text.trim());return t}function vz(e,t,n){if(e.length===0)return null;if(t===null){if(n.trim()!=="")return null;const c=e.length-1,u=e[c];return{nav:{index:c,stash:n,recalled:u},text:u}}if(n!==t.recalled)return null;if(t.index===0)return{nav:t,text:t.recalled};const s=t.index-1,o=e[s];return{nav:{...t,index:s,recalled:o},text:o}}function kz(e,t,n){if(t===null||n!==t.recalled)return null;if(t.index>=e.length-1)return{nav:null,text:t.stash};const s=t.index+1,o=e[s];return{nav:{...t,index:s,recalled:o},text:o}}function wz(e,t){return!e.slice(0,t).includes(`
|
|
172
172
|
`)}function Sz(e,t){return!e.slice(t).includes(`
|
|
173
|
-
`)}function jz(e){if(e.sending)return"disabled";const t=!e.goalOn;return t&&e.canSteerChannel&&!e.hasHandoffTarget&&!e.hasPendingModel&&(e.hasText||e.hasImages||e.hasFiles)&&!e.followUpMode?"steer":t&&e.canQueueChannel&&e.stagedRoute!=="blocked"&&e.hasContent?"queue":"stop"}function Cz(e,t){return e==="compacting"?!0:e==="running"&&t==="stop"}function _y(e){return e!=null&&e.includes("Files")}function Nz(e,t,n){const s=t&&n;switch(e){case"over":return{active:s,claim:s,accept:!1};case"leave":return{active:s,claim:!1,accept:!1};case"drop":return{active:!1,claim:s,accept:s};case"end":return{active:!1,claim:!1,accept:!1}}}function Tz(e){const t=[],n=[];for(const s of e)(s.type.startsWith("image/")?t:n).push(s);return{images:t,files:n}}function zS(e){e.defaultPrevented||!_y(e.dataTransfer?.types)||(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="none"))}function BS(e){e.defaultPrevented||!_y(e.dataTransfer?.types)||e.preventDefault()}const NT=y.createContext(null);function Mz({className:e,children:t}){const[n,s]=y.useState(null);return a.jsx("div",{className:e,ref:s,children:a.jsx(NT.Provider,{value:n,children:t})})}function Ez({onFiles:e}){const t=y.useContext(NT),[n,s]=y.useState(!1),o=y.useRef(!1),c=y.useRef(e);return y.useEffect(()=>{c.current=e}),y.useEffect(()=>{if(!t)return;const u=v=>v instanceof Node&&t.contains(v),f=(v,w,S)=>{const C=Nz(v,_y(w.dataTransfer?.types),S);return o.current!==C.active&&(o.current=C.active,s(C.active)),C.claim&&(w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="copy")),C},p=v=>{f("over",v,u(v.target))},h=v=>{f("leave",v,u(v.relatedTarget))},x=v=>{if(!f("drop",v,u(v.target)).accept||!v.dataTransfer)return;const S=Array.from(v.dataTransfer.files);S.length>0&&c.current(S)},g=v=>{f("end",v,!1)};return window.addEventListener("dragover",p),window.addEventListener("dragleave",h),window.addEventListener("drop",x),window.addEventListener("dragend",g),()=>{window.removeEventListener("dragover",p),window.removeEventListener("dragleave",h),window.removeEventListener("drop",x),window.removeEventListener("dragend",g),o.current=!1,s(!1)}},[t]),!n||!t?null:ss.createPortal(a.jsx("div",{"aria-hidden":!0,className:"anim-fade pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-white/70 p-6 backdrop-blur-sm dark:bg-gray-950/70",children:a.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-gray-400 bg-white/80 px-10 py-8 text-center dark:border-gray-500 dark:bg-gray-900/80",children:[a.jsx(Oe,{d:bf,size:28,className:"text-gray-400 dark:text-gray-500"}),a.jsx("p",{className:"text-base font-medium text-gray-800 dark:text-gray-100",children:d.chat.dropFilesTitle}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.chat.dropFilesDesc})]})}),t)}const Az=128e3;function TT(e){const t=typeof e=="string"?Number(e):e;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:Az}const Y0=[{text:"text-violet-500",swatch:"bg-violet-500"},{text:"text-amber-500 dark:text-amber-600",swatch:"bg-amber-500 dark:bg-amber-600"},{text:"text-sky-500 dark:text-sky-600",swatch:"bg-sky-500 dark:bg-sky-600"},{text:"text-rose-500",swatch:"bg-rose-500"}];function Ry(e){return Y0[e%Y0.length]}const _z=["bg-sky-500 dark:bg-sky-600","bg-amber-500 dark:bg-amber-600","bg-fuchsia-500 dark:bg-fuchsia-600","bg-rose-500","bg-violet-500","bg-emerald-500 dark:bg-emerald-600"],Xf={text:"text-gray-400 dark:text-gray-500",swatch:"bg-gray-400 dark:bg-gray-500"},HS=["systemPrompt","toolDefs","userMessages","assistantMessages","toolRequests","toolResults"];function Rz(e,t){if(e.contextClosed||e.total<=0)return null;const n=HS.map(c=>e[c]),s=FS(n,t),o=FS(n,100);return{parts:HS.map((c,u)=>({key:c,color:_z[u]??"",tokens:s[u]??0,percent:o[u]??0})),tools:e.topTools.map(c=>({name:c.name,tokens:Math.round(c.tokens/e.total*t),percent:Math.round(c.tokens/e.total*100)}))}}function FS(e,t){const n=e.reduce((f,p)=>f+p,0);if(n<=0)return e.map(()=>0);const s=e.map(f=>f/n*t),o=s.map(f=>Math.floor(f));let c=Math.round(t)-o.reduce((f,p)=>f+p,0);const u=s.map((f,p)=>({i:p,frac:f-Math.floor(f)})).sort((f,p)=>p.frac-f.frac||f.i-p.i);for(const{i:f}of u){if(c<=0)break;o[f]=(o[f]??0)+1,c-=1}return o}const qS=300,Iz="calc(100vw - 32px)",Lz=264,Oz=2,Fg=4;function Dz({now:e,window:t,unknown:n=!1,sessionId:s}){const o=TT(t),c=n?0:Math.min(1,e/o),[u,f]=y.useState(!1),p=y.useId(),{triggerRef:h,panelRef:x,position:g}=$f({open:u,onClose:()=>f(!1),estimatedHeight:Lz,panelWidth:qS}),v=n||c<=.8?"text-gray-400 dark:text-gray-500":c>.95?sn.danger:sn.attention,w=n?d.chat.contextUnknown:`${d.chat.contextUsage} ${Math.round(c*100)}% · ${It(e)}/${It(o)}`,S=5,C=2*Math.PI*S,N=a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14","aria-hidden":!0,className:"block shrink-0",children:[a.jsx("circle",{cx:"7",cy:"7",r:S,fill:"none",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"2"}),a.jsx("circle",{cx:"7",cy:"7",r:S,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeDasharray:`${C*c} ${C}`,transform:"rotate(-90 7 7)"})]}),T=`flex h-8 w-8 shrink-0 items-center justify-center ${v}`;return s===void 0?a.jsx("span",{title:w,"aria-label":w,role:"img",className:T,children:N}):a.jsxs(a.Fragment,{children:[a.jsx("button",{ref:h,type:"button",title:w,"aria-label":w,"aria-expanded":u,"aria-controls":p,onClick:()=>f(_=>!_),className:`${T} rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`,children:N}),u&&g&&ss.createPortal(a.jsx("div",{ref:x,id:p,role:"group","aria-label":d.chat.contextComposition,style:{position:"fixed",top:g.topPx,bottom:g.bottomPx,left:g.left,width:qS,maxWidth:Iz},className:"anim-pop z-[60] rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900",children:a.jsx($z,{sessionId:s,now:e,max:o,pct:c,unknown:n})}),document.body)]})}function $z({sessionId:e,now:t,max:n,pct:s,unknown:o}){const[c,u]=y.useState({status:"loading"}),[f,p]=y.useState(null);y.useEffect(()=>{let S=!1;return u({status:"loading"}),pA(e).then(C=>{S||u({status:"ready",data:C})},()=>{S||u({status:"failed"})}),()=>{S=!0}},[e]);const h=c.status==="ready"?c.data:null,x=o||h?.contextClosed===!0,g=h===null?null:Rz(h,t),v=g?.parts.some(S=>S.key===f)?f:null,w=h!==null&&h.compactionThreshold!==null&&h.compactionThreshold<n?h.compactionThreshold:null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[a.jsxs("span",{className:"flex items-baseline gap-1.5",children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:d.chat.contextUsage}),a.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:x?"—":Lf(s)})]}),a.jsxs("span",{className:"font-mono text-gray-500 dark:text-gray-400",children:[x?"—":It(t)," / ",It(n)]})]}),x?a.jsx("p",{className:"mt-2 leading-relaxed text-gray-400 dark:text-gray-500",children:d.chat.contextUnknownHint}):c.status==="loading"?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.common.loading}):c.status==="failed"?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.chat.contextBreakdownFailed}):g===null?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.chat.contextBreakdownEmpty}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{"aria-hidden":!0,className:"relative mt-2 h-2 bg-gray-200 dark:bg-gray-800",style:{marginBottom:Fg},children:[a.jsx("div",{className:"absolute inset-y-0 left-0 flex overflow-hidden",style:{width:`${t/n*100}%`,minWidth:t>0?Oz:0},children:g.parts.map(S=>S.tokens>0?a.jsx("span",{title:`${VS[S.key]()} ~${It(S.tokens)} · ${S.percent}%`,onMouseEnter:()=>p(S.key),onMouseLeave:()=>p(null),style:{flexGrow:S.tokens,flexBasis:0},className:`h-full transition-opacity duration-150 ${S.color} ${v!==null&&v!==S.key?"opacity-25":""}`},S.key):null)}),w!==null&&a.jsx("span",{title:d.chat.contextCompactAt(It(w)),style:{left:`${w/n*100}%`,top:-Fg,bottom:-Fg},className:"absolute border-l border-dashed border-gray-500 dark:border-gray-400"})]}),a.jsx("ul",{className:"mt-2 space-y-0.5",children:g.parts.map(S=>a.jsx(GS,{label:VS[S.key](),swatch:S.color,tokens:S.tokens,percent:S.percent,highlighted:f===S.key,onHover:C=>p(C?S.key:null)},S.key))}),g.tools.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("p",{title:d.chat.contextTopToolsHint,className:"mt-2 border-t border-gray-100 pt-1.5 text-gray-400 dark:border-gray-800 dark:text-gray-500",children:d.chat.contextTopTools}),a.jsx("ul",{className:"mt-1 space-y-0.5",children:g.tools.map(S=>a.jsx(GS,{label:S.name,mono:!0,tokens:S.tokens,percent:S.percent,highlighted:f===`tool:${S.name}`,onHover:C=>p(C?`tool:${S.name}`:null)},S.name))})]})]})]})}const VS={systemPrompt:()=>d.chat.contextPartSystemPrompt,toolDefs:()=>d.chat.contextPartToolDefs,userMessages:()=>d.chat.contextPartUserMessages,assistantMessages:()=>d.chat.contextPartAssistantMessages,toolRequests:()=>d.chat.contextPartToolRequests,toolResults:()=>d.chat.contextPartToolResults};function GS({label:e,swatch:t,tokens:n,percent:s,mono:o=!1,highlighted:c=!1,onHover:u}){return a.jsxs("li",{onMouseEnter:()=>u?.(!0),onMouseLeave:()=>u?.(!1),className:`-mx-1 flex items-center gap-1.5 rounded px-1 py-px transition-colors duration-150 ${c?"bg-gray-100 dark:bg-gray-800":""}`,children:[t!==void 0&&a.jsx("span",{"aria-hidden":!0,className:`h-2 w-2 shrink-0 rounded-[2px] ${t}`}),a.jsx("span",{title:e,className:`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${o?"font-mono":""}`,children:e}),a.jsxs("span",{className:"shrink-0 font-mono font-medium text-gray-900 dark:text-gray-100",children:["~",It(n)]}),a.jsxs("span",{className:"w-8 shrink-0 text-right font-mono text-gray-400 dark:text-gray-500",children:[s,"%"]})]})}const Uz=1024*1024;function KS(e,t){const n=t*Uz,s=[],o=[];for(const c of e)c.size>n?o.push(c):s.push(c);return{accepted:s,rejected:o}}const Pz=["always-ask","read-only","allow-all","deny-all"],WS={"allow-all":"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4m0 4h.01","deny-all":"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM5.64 5.64l12.72 12.72","read-only":"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z","always-ask":"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.1 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3m.07 4h.01"};function zz({value:e,onChange:t,disabled:n,direction:s="up"}){const[o,c]=y.useState(!1);return a.jsx(Qn,{open:o,setOpen:c,menuClass:"w-max",portal:{direction:s,align:"left"},button:a.jsxs("button",{type:"button","aria-label":d.chat.approvalMode,title:`${d.chat.approvalMode}:${d.chat.approvalModeNames[e]??e}`,disabled:n,onClick:()=>c(u=>!u),className:"flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:WS[e]}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:d.chat.approvalModeNames[e]??e}),a.jsx(ns,{size:Ye.caretDense})]}),children:Pz.map(u=>a.jsxs("button",{type:"button",onClick:()=>{t(u),c(!1)},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${u===e?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx("path",{d:WS[u]})}),a.jsx("span",{className:"min-w-0 flex-1 truncate whitespace-nowrap",children:d.chat.approvalModes[u]??u}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:u===e?"✓":""})]},u))})}function Bz({agents:e,currentAgentId:t,onPick:n}){const[s,o]=y.useState("");return a.jsx(Ey,{items:eP(e,s),itemKey:c=>c.agentId,isCurrent:c=>c.agentId===t,query:s,onQueryChange:o,searchPlaceholder:d.chat.agentSearchPlaceholder,emptyText:d.chat.agentsNoMatch,onPick:n,renderRow:c=>a.jsxs(a.Fragment,{children:[a.jsx(Ha,{id:c.agentId,name:_n(c),size:16,className:"shrink-0 rounded"}),a.jsx("span",{className:"shrink-0 font-mono text-gray-800 dark:text-gray-200",children:c.agentId}),c.name&&c.name!==c.agentId&&a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:c.name})]})})}function YS({panelRef:e,maxHeight:t,title:n,children:s}){return a.jsxs("div",{ref:e,style:{maxHeight:t},className:"anim-pop absolute bottom-full left-0 z-40 mb-1.5 flex w-80 max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:[a.jsx("div",{className:"border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400",children:n}),s]})}const Hz="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z";function XS({value:e,onChange:t,disabled:n,direction:s="down"}){const[o,c]=y.useState(!1),u=e===null?"…":W0(d.chat.thinkingLevelNames,e)??"—";return a.jsxs(Qn,{open:o,setOpen:c,menuClass:"w-max min-w-36",portal:{direction:s,align:"right"},button:a.jsxs("button",{type:"button",title:`${d.chat.thinkingLevel}:${u}`,"aria-label":d.chat.thinkingLevel,disabled:n||e===null,onClick:()=>c(!o),className:"flex h-8 max-w-36 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:Hz,className:"shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:u}),a.jsx(ns,{size:Ye.caretDense})]}),children:[a.jsx("div",{className:"border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400",children:d.chat.thinkingLevel}),ST.map(f=>a.jsxs("button",{type:"button",onClick:()=>{t(f),c(!1)},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${f===e?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.chat.thinkingLevelMenuName(d.chat.thinkingLevelNames[f]??f,f)}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:f===e?"✓":""})]},f))]})}const MT="penguin.steerMode";function Fz(){return localStorage.getItem(MT)==="followup"?"followup":"steer"}const qz="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6";function Vz({steerMode:e,onChangeSteerMode:t}){const n=(s,o,c)=>a.jsx("button",{type:"button",title:c,"aria-pressed":e===s,onClick:()=>t(s),className:`h-5 rounded px-1.5 text-xs transition-colors duration-150 ${e===s?"bg-gray-200 font-medium text-gray-800 dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"}`,children:o});return a.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-1 text-xs",children:[a.jsx(Oe,{d:qz,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-600 dark:text-gray-400",children:d.chat.steerModeLabel}),a.jsxs("div",{role:"group","aria-label":d.chat.steerModeLabel,className:"flex shrink-0 items-center gap-0.5",children:[n("steer",d.chat.steerModeSteer,d.chat.steerModeSteerHint),n("followup",d.chat.steerModeFollowUp,d.chat.steerModeFollowUpHint)]})]})}function Gz({skills:e,selected:t,onToggle:n,disabled:s,direction:o="up"}){const[c,u]=y.useState(!1);return a.jsx(Qn,{open:c,setOpen:u,menuClass:"w-[26rem]",portal:{direction:o,align:"left"},button:a.jsxs("button",{type:"button","aria-label":d.chat.skillsSelect,title:d.chat.skillsSelect,disabled:s,onClick:()=>u(!c),className:"flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:My,className:"shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:d.chat.skillsSelect}),t.length>0&&a.jsx("span",{className:"shrink-0 rounded-full bg-gray-200/80 px-1.5 py-px font-mono text-[10px] font-semibold text-gray-700 dark:bg-gray-700/60 dark:text-gray-200",children:t.length}),a.jsx(ns,{size:Ye.caretDense})]}),children:a.jsx(q0,{skills:e,selected:t,onToggle:n,emptyHint:d.chat.skillsEmptyHint})})}const Kz="M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM3 15l5-5 4 4 3-3 6 6";function Wz({items:e,footer:t,direction:n="up"}){const[s,o]=y.useState(!1);return a.jsxs(Qn,{open:s,setOpen:o,menuClass:"w-72",portal:{direction:n,align:"left"},button:a.jsx("button",{type:"button","aria-label":d.chat.plusMenu,title:d.chat.plusMenu,onClick:()=>o(!s),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:"M12 5v14M5 12h14",size:15,className:"shrink-0"})}),children:[e.map(c=>a.jsxs("button",{type:"button","aria-pressed":c.active,disabled:c.disabled,onClick:()=>{o(!1),c.onSelect()},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-gray-800 dark:disabled:hover:bg-transparent ${c.active?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx(Oe,{d:c.icon,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"shrink-0",children:c.label}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:c.desc}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:c.active?"✓":""})]},c.key)),t&&a.jsx("div",{className:"mt-1 border-t border-gray-100 pt-1 dark:border-gray-800",children:t})]})}function Yz(e){return new Promise(t=>{const n=new FileReader;n.onload=()=>t(typeof n.result=="string"?n.result:null),n.onerror=()=>t(null),n.readAsDataURL(e)})}function Xz(e){const t=e.slice(e.indexOf(",")+1).replace(/[=\s]+/g,"");return Math.floor(t.length*3/4)}function QS(e){const t=[],n=e.text.replace(/\s+/g," ").trim();return n&&t.push(n),e.images>0&&t.push(d.chat.imagesInMessage(e.images)),e.files>0&&t.push(d.chat.filesInMessage(e.files)),t.join(" · ")}const Qz="M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11";function ZS({label:e,onRecall:t,disabled:n}){return a.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[a.jsx("p",{className:"min-w-0 truncate text-xs text-gray-400 dark:text-gray-500",children:e}),t&&a.jsx("button",{type:"button","aria-label":d.chat.recallQueued,title:d.chat.recallQueuedTitle,disabled:n,onClick:t,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:Qz,size:13})})]})}function Zz(e,t,n){for(const s of t)e.push({type:"image_url",imageUrl:s});for(const s of n)e.push({type:"file",fileName:s.name,dataUrl:s.dataUrl})}function Iy({status:e,onSend:t,onSteer:n,steeringDeliveredCount:s,pendingSteering:o=[],onRecallSteering:c,onQueueFollowUp:u,queuedFollowUps:f=0,pendingFollowUps:p=[],onRecallFollowUp:h,onStop:x,onCompact:g,modelRef:v,models:w,onChangeModel:S,onSwitchModel:C,defaultModel:N,thinkingLevel:T,onChangeThinkingLevel:_,turnThinkingLevel:R,onChangeTurnThinkingLevel:D,contextWindow:z,contextNow:E,contextStale:L=!1,sessionId:F,vision:V,approvalMode:P,onChangeApprovalMode:B,modeSaving:Y,autoFocus:q,agents:K,currentAgentId:H,skills:$,initialSkills:X,onSkillsChange:le,onHandoff:ie,initialText:I,onTextChange:A,history:Q=[],initialHandoffTargetId:j,onHandoffTargetChange:U,initialPendingModelRef:ee,onPendingModelChange:re,controlRef:ke,variant:be="session"}){const{locale:ye}=Dr(),{uploadLimits:Se}=mn(),[Me,ze]=y.useState(I??""),De=y.useRef(Me);De.current=Me;const[ct,bt]=y.useState([]),[he,ne]=y.useState([]),[oe,J]=y.useState(!1),[ht,ve]=y.useState(0),[Xe,Ge]=y.useState(null),[He,Pe]=y.useState(!1),W=y.useRef(null),[me,Ue]=y.useState(!1),pe=y.useRef(null),$e=y.useRef(null),[nt,gt]=y.useState(),[Ke,dt]=y.useState(null),[pt,wt]=y.useState(null),[st,Bt]=y.useState(X??[]),[Sn,Dn]=y.useState(0),Vt=y.useRef(null),ar=y.useRef(null),[zn]=y.useState(()=>window.matchMedia("(max-width: 767px)").matches),Xt=e==="running",Cn=e==="compacting",lr=Me.trim().length>0||ct.length>0||he.length>0||Ke!==null||pt!==null||st.length>0,[Mt,Pr]=y.useState(!1),[Bn,Nr]=y.useState(""),[Tr,Te]=y.useState(!1),[Ie,ut]=y.useState(""),St=Mt?Tm(Bn):null,Nn=Tm(Ie)===null,Hn=St!==null&&St!==Ty?d.chat.goalBudgetValue(It(St)):d.chat.goalBudgetUnlimited,Dt=tP({handoffTarget:Ke!==null,pendingModel:pt!==null,canSwitchModel:C!==void 0,sessionBusy:Xt||Cn}),Rn=!Xt&&!Cn&&!oe&&(Mt?Me.trim().length>0&&he.length===0&&St!==null&&!(Tr&&Nn):lr),zr=y.useCallback(ae=>{if(ae){ut(Bn),Te(!0);return}Tm(Ie)!==null&&(Nr(Ie.trim()),Te(!1))},[Bn,Ie]),cr=y.useCallback(()=>{Te(!1),Vt.current?.focus()},[]),Js=y.useCallback(()=>{Tm(Ie)!==null&&(Nr(Ie.trim()),Te(!1),Vt.current?.focus())},[Ie]),Mr=y.useCallback(ae=>{Pr(ae),Te(!1),ut(""),ae&&(Nr(""),dt(null),U?.(null),wt(null),re?.(null),ne([]))},[U,re]),[ta,Br]=y.useState(Fz),is=ae=>{Br(ae),localStorage.setItem(MT,ae)},Hr=ta==="followup"&&u!==void 0,fn=jz({sending:oe,goalOn:Mt,canSteerChannel:n!==void 0,canQueueChannel:u!==void 0,followUpMode:Hr,stagedRoute:Dt,hasHandoffTarget:Ke!==null,hasPendingModel:pt!==null,hasText:Me.trim().length>0,hasImages:ct.length>0,hasFiles:he.length>0,hasContent:lr}),Fr=Xt&&fn==="steer",qr=Xt&&fn==="queue",pn=Fr||qr,na=fn==="queue"?d.chat.followUpSend:d.chat.steerSend,Jn=Cz(e,fn),Er=(()=>{const ae=w?.find(_e=>zt(_e,v));return ae?hu(ae):v?.modelId??"…"})(),[ur,os]=y.useState(!1),ls=y.useRef(0);y.useEffect(()=>{ur&&(!Xt||(s??0)>ls.current||o.length>0)&&os(!1)},[ur,Xt,s,o.length]);const[ra,cs]=y.useState(null),ka=ae=>{const{text:_e,dropGoal:et}=xz({recalledText:ae.text,currentText:Vt.current?.value??Me,recalledFiles:ae.files.length,goalOn:Mt});ze(_e),A?.(_e),Dn(_e.length),ae.images.length>0&&bt(qe=>[...ae.images,...qe]),ae.files.length>0&&(et&&Mr(!1),ne(qe=>[...ae.files.map(vt=>({name:vt.fileName,size:Xz(vt.dataUrl),dataUrl:vt.dataUrl})),...qe])),requestAnimationFrame(()=>{const qe=Vt.current;qe&&(qe.focus(),qe.setSelectionRange(qe.value.length,qe.value.length),qe.scrollTop=qe.scrollHeight)})},Ar=async(ae,_e)=>{if(!(ra!==null||oe)){cs(ae);try{const et=await _e(ae);et&&(os(!1),ka(et))}finally{cs(null)}}},er=y.useCallback(ae=>{const _e=V0(st,ae);Bt(_e),le?.(_e)},[st,le]),Tn=y.useCallback((ae,_e)=>{const et=yz({prompt:ae,exampleSkills:_e,installedSkills:$.map(qe=>qe.name),selectedSkills:st});ze(et.text),A?.(et.text),Dn(0),et.skills.length!==st.length&&(Bt(et.skills),le?.(et.skills)),requestAnimationFrame(()=>{const qe=Vt.current;qe&&(qe.focus(),qe.setSelectionRange(0,0),qe.scrollTop=0)})},[$,st,A,le]);y.useImperativeHandle(ke,()=>({fillExample:Tn}),[Tn]);const Vr=y.useRef(null),wa=y.useMemo(()=>{const ae=()=>{const _e=Vr.current,et=_e?cz(De.current,_e):"";ze(et),A?.(et)};return[...g?[{cmd:"/compact",desc:d.chat.compact,run:()=>{ae(),g()}}]:[],...be==="session"?[{cmd:"/goal",desc:d.chat.goalModeDesc,run:()=>{ae(),Mr(!Mt)}}]:[],...C&&w&&w.length>0?[{cmd:"/model",desc:d.chat.switchModel,run:()=>{ae(),Pe(!0)}}]:[],...ie&&K.length>0?[{cmd:"/agent",desc:d.chat.switchAgent,run:()=>{ae(),Ue(!0)}}]:[],...IP($,ye).map(_e=>({cmd:_e.cmd,desc:_e.desc,run:()=>{ae(),er(_e.name)}}))]},[g,C,w,K,A,$,ye,er,Mr,Mt]),Mn=!Xt&&!Cn&&!He&&!me?PS(Me,Sn):null;Vr.current=Mn;const Gr=Mn&&Mn.start!==Xe?wa.filter(ae=>ae.cmd.startsWith(`/${Mn.query}`)):[],En=Gr.length>0,us=Gr[Math.min(ht,Gr.length-1)];y.useEffect(()=>{if(!He&&!me)return;const ae=()=>{Pe(!1),Ue(!1),Vt.current?.focus()},_e=qe=>{const vt=He?W.current:pe.current;vt&&!vt.contains(qe.target)&&ae()},et=qe=>{qe.key==="Escape"&&!qe.isComposing&&ae()};return window.addEventListener("mousedown",_e),window.addEventListener("keydown",et),()=>{window.removeEventListener("mousedown",_e),window.removeEventListener("keydown",et)}},[He,me]);const hn=ae=>{wt(ae),re?.(ae?{provider:ae.provider,modelId:ae.modelId}:null)},Sa=ae=>{if(Pe(!1),Vt.current?.focus(),zt(ae,v)){hn(null);return}hn(ae),dt(null),U?.(null),Pr(!1)},Ts=ae=>{Ue(!1),dt(ae),U?.(ae.agentId),hn(null),Pr(!1),Vt.current?.focus()},Ga=()=>{Ke!==null&&(dt(null),U?.(null)),hn(null)};y.useEffect(()=>{if(!En&&!He&&!me)return;const ae=()=>{const _e=$e.current;if(!_e)return;let et=0;for(let vt=_e.parentElement;vt;vt=vt.parentElement)if(getComputedStyle(vt).overflowY!=="visible"){et=vt.getBoundingClientRect().top;break}const qe=_e.getBoundingClientRect().top-et-14;gt(Math.max(96,Math.min(320,Math.round(qe))))};return ae(),window.addEventListener("resize",ae),()=>window.removeEventListener("resize",ae)},[En,He,me]);const Ct=()=>{const ae=Vt.current;ae&&(ae.style.height="auto",ae.style.height=`${Math.min(ae.scrollHeight,176)}px`)};y.useLayoutEffect(Ct,[Me]),y.useEffect(()=>{const ae=ar.current;ae&&Me!==ae.recalled&&(ar.current=null)},[Me]),y.useEffect(()=>{const ae=Vt.current;if(ae&&ae.value.length>0){const _e=ae.value.length;ae.setSelectionRange(_e,_e),ae.scrollTop=ae.scrollHeight,Dn(_e)}},[]);const ds=y.useRef(!1);y.useEffect(()=>{if(!ds.current&&(ds.current=!0,$.length===0))return;const ae=st.filter(_e=>$.some(et=>et.name===_e));ae.length!==st.length&&(Bt(ae),le?.(ae))},[$,st,le]);const ja=Ke!==null||pt!==null||Mt,br=y.useRef(!1);y.useEffect(()=>{if(br.current||!j||K.length===0||(br.current=!0,ja))return;const ae=K.find(_e=>_e.agentId===j);ae&&dt(ae)},[K,j,ja]);const Ca=y.useRef(!1);y.useEffect(()=>{if(Ca.current||!ee||!w||w.length===0||(Ca.current=!0,ja||!C))return;const ae=w.find(_e=>zt(_e,ee));ae&&!zt(ae,v)&&wt(ae)},[w,ee,v,C,ja]);const de=async(ae=t)=>{const _e=Me.trim();if(Mt){J(!0);try{const tr=[{type:"text",text:jw(st,_e)}];for(const ei of ct)tr.push({type:"image_url",imageUrl:ei});await t(tr,{budget:St})&&(ze(""),bt([]),Bt([]),Mr(!1))}finally{J(!1),Vt.current?.focus()}return}if(Dt==="blocked")return;const et=Dt==="model"?pt:null,qe=_e!==""?_e:st.length>0?d.chat.skillsAutoMessage(st):et?d.chat.modelSwitchAutoMessage:_e,vt=jw(st,qe),xn=[];vt&&xn.push({type:"text",text:vt}),Zz(xn,ct,he),J(!0);try{(Ke?await ie(Ke,xn):et?await C({provider:et.provider,modelId:et.modelId},xn):await ae(xn,null))&&(ze(""),bt([]),ne([]),dt(null),wt(null),Bt([]))}finally{J(!1),Vt.current?.focus()}},Re=async()=>{if(Xt){if(qr){await de(u);return}if(!Fr)return;const ae=Me.trim(),_e=ct,et=he.map(vt=>({fileName:vt.name,dataUrl:vt.dataUrl}));J(!0);let qe="failed";try{qe=await n(ae,_e,et),qe==="queued"&&(ls.current=s??0,os(!0),ze(""),bt([]),ne([]))}finally{J(!1),Vt.current?.focus()}qe==="not_running"&&await de(u??t);return}Rn&&await de()},Qe=ae=>{ar.current=ae.nav,ze(ae.text),A?.(ae.text),Dn(ae.text.length),requestAnimationFrame(()=>{const _e=Vt.current;_e&&(_e.setSelectionRange(_e.value.length,_e.value.length),_e.scrollTop=_e.scrollHeight)})},mt=ae=>{if(En){if(ae.key==="ArrowDown"){ae.preventDefault(),ve(_e=>(_e+1)%Gr.length);return}if(ae.key==="ArrowUp"){ae.preventDefault(),ve(_e=>(_e-1+Gr.length)%Gr.length);return}if((ae.key==="Enter"&&!ae.shiftKey||ae.key==="Tab")&&!ae.nativeEvent.isComposing){ae.preventDefault(),us?.run();return}if(ae.key==="Escape"){Ge(Mn?.start??null);return}}if((ae.key==="ArrowUp"||ae.key==="ArrowDown")&&!ae.nativeEvent.isComposing){const _e=ae.currentTarget.selectionStart??0,et=ae.currentTarget.selectionEnd??_e,qe=ae.key==="ArrowUp"?wz(Me,_e)?vz(Q,ar.current,Me):null:Sz(Me,et)?kz(Q,ar.current,Me):null;if(qe){ae.preventDefault(),Qe(qe);return}}if(ae.key==="Backspace"&&(Ke!==null||pt!==null)&&ae.currentTarget.selectionStart===0&&ae.currentTarget.selectionEnd===0){ae.preventDefault(),Ga();return}ae.key==="Enter"&&!ae.shiftKey&&!ae.nativeEvent.isComposing&&(ae.preventDefault(),Re())},Et=ae=>{const _e=[];for(const vt of ae)vt.type.startsWith("image/")&&_e.push(vt);const{accepted:et,rejected:qe}=KS(_e,Se.imageMaxMb);for(const vt of qe)Be(d.chat.attachmentTooLarge(vt.name,Se.imageMaxMb));for(const vt of et){const xn=new FileReader;xn.onload=()=>{typeof xn.result=="string"&&bt(tr=>[...tr,xn.result])},xn.readAsDataURL(vt)}},Pt=ae=>{if(be!=="session")return;const _e=[];for(const et of ae.clipboardData.items)if(et.kind==="file"){const qe=et.getAsFile();qe&&_e.push(qe)}_e.length>0&&(ae.preventDefault(),Et(_e))},Wt=ae=>{ae.target.files&&Et(ae.target.files),ae.target.value=""},Ka=ae=>{if(Mt)return;const{accepted:_e,rejected:et}=KS(ae,Se.attachmentMaxMb);for(const qe of et)Be(d.chat.attachmentTooLarge(qe.name,Se.attachmentMaxMb));_e.length!==0&&Promise.all(_e.map(Yz)).then(qe=>{const vt=_e.flatMap((xn,tr)=>qe[tr]?[{name:xn.name,size:xn.size,dataUrl:qe[tr]}]:[]);vt.length>0&&ne(xn=>[...xn,...vt])})},_r=ae=>{ae.target.files&&Ka(ae.target.files),ae.target.value=""},Rr=ae=>{if(be!=="session")return;const _e=Tz(ae);_e.images.length>0&&Et(_e.images),_e.files.length>0&&(Mt?wr(d.chat.dropFilesGoalHint):Ka(_e.files))},Ir=y.useRef(null),Ui=y.useRef(null);return a.jsxs("div",{className:"relative",ref:$e,children:[be==="session"&&a.jsx(Ez,{onFiles:Rr}),En&&a.jsx("div",{style:{maxHeight:nt},className:"anim-pop absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:Gr.map((ae,_e)=>a.jsxs("button",{type:"button",ref:ae===us?et=>et?.scrollIntoView({block:"nearest"}):void 0,onMouseEnter:()=>ve(_e),onClick:()=>ae.run(),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${ae===us?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsx("span",{className:"shrink-0 font-mono text-gray-800 dark:text-gray-200",children:ae.cmd}),a.jsx("span",{title:ae.desc,className:"min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400",children:ae.desc})]},ae.cmd))}),He&&w&&a.jsx(YS,{panelRef:W,maxHeight:nt,title:d.chat.switchModelTitle,children:a.jsx(wT,{models:w,value:v,...N!==void 0?{defaultModel:N}:{},onPick:Sa})}),me&&a.jsx(YS,{panelRef:pe,maxHeight:nt,title:d.chat.switchAgentTitle,children:a.jsx(Bz,{agents:K,...H!==void 0?{currentAgentId:H}:{},onPick:Ts})}),ct.length>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:ct.map((ae,_e)=>a.jsxs("div",{className:"anim-pop relative",children:[a.jsx(Ys,{src:ae,alt:d.chat.imageAlt,className:"h-16 w-16 rounded-md border border-gray-200 object-cover dark:border-gray-700"}),a.jsx("button",{type:"button","aria-label":d.chat.removeImage,onClick:()=>bt(et=>et.filter((qe,vt)=>vt!==_e)),className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-gray-700 text-[10px] text-white transition-colors duration-150 hover:bg-gray-900",children:"×"})]},_e))}),he.length>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:he.map((ae,_e)=>a.jsxs("span",{title:ae.name,className:`anim-pop flex max-w-56 items-center ${Ro.tight} rounded-md border border-gray-200 bg-gray-50 py-1 pl-2 pr-1 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200`,children:[a.jsx(Oe,{d:bf,size:13,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"min-w-0 truncate",children:ae.name}),a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:ju(ae.size)}),a.jsx("button",{type:"button","aria-label":`${d.chat.removeFile} ${ae.name}`,onClick:()=>ne(et=>et.filter((qe,vt)=>vt!==_e)),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]},_e))}),!V&&ct.length>0&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.imagesAsPathHint}),Dt==="blocked"&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.modelSwitchBusyHint}),o.length>0?a.jsx("div",{className:"anim-fade mb-1",children:o.map((ae,_e)=>a.jsx(ZS,{label:d.chat.steerQueuedItem(QS(ae)),disabled:ra!==null||oe,...c&&ae.id?{onRecall:()=>{Ar(ae.id,c)}}:{}},ae.id??_e))}):ur&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.steerQueuedIndicator}),p.length>0?a.jsx("div",{className:"anim-fade mb-1",children:p.map(ae=>a.jsx(ZS,{label:d.chat.followUpQueuedItem(QS(ae)),disabled:ra!==null||oe,...h?{onRecall:()=>{Ar(ae.id,h)}}:{}},ae.id))}):f>0&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.followUpQueuedChip(f)}),a.jsxs("div",{className:"@container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400",children:[(Ke!==null||pt!==null||st.length>0||Mt)&&a.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[Mt&&a.jsxs("span",{className:"anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsxs("span",{className:"flex shrink-0 items-center gap-1",title:d.chat.goalModeDesc,children:[a.jsx(Oe,{d:_u,size:13,className:"text-gray-500 dark:text-gray-400"}),a.jsx("span",{children:d.chat.goalMode})]}),a.jsx("span",{"aria-hidden":!0,className:"mx-0.5 h-4 w-px shrink-0 bg-gray-300 dark:bg-gray-600"}),a.jsx(Qn,{open:Tr,setOpen:zr,onEscape:cr,className:"min-w-0",menuClass:"bottom-full left-1/2 -ml-32 mb-2 w-64 max-w-[calc(100vw-2rem)] origin-bottom",button:a.jsxs("button",{type:"button","aria-label":Hn,"aria-expanded":Tr,onClick:()=>zr(!Tr),className:"flex h-5 min-w-0 items-center gap-1 rounded px-1.5 text-xs text-gray-600 transition-colors duration-150 hover:bg-white/80 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white",children:[a.jsx("span",{className:"truncate",children:Hn}),a.jsx(ns,{size:Ye.caretDense})]}),children:a.jsxs("div",{className:"px-3 py-2",children:[a.jsx("label",{htmlFor:"goal-budget-input",className:"block text-xs font-medium text-gray-700 dark:text-gray-200",children:d.chat.goalBudgetLabel}),a.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[a.jsx("input",{id:"goal-budget-input",autoFocus:!0,value:Ie,onChange:ae=>ut(ae.target.value),onFocus:ae=>ae.currentTarget.select(),onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),ae.stopPropagation(),Js())},placeholder:d.chat.goalBudgetPlaceholder,"aria-invalid":Nn,"aria-describedby":"goal-budget-hint",...Gu,title:Nn?d.chat.goalBudgetInvalid:d.chat.goalBudgetHint,className:`min-w-0 flex-1 rounded-md border bg-white px-2 py-1 font-mono text-sm leading-5 placeholder:text-gray-400 focus:outline-none focus:ring-2 dark:bg-gray-950 dark:placeholder:text-gray-500 ${Nn?"border-red-400 text-red-600 focus:border-red-500 focus:ring-red-400/20 dark:border-red-500 dark:text-red-400":"border-gray-300 text-gray-800 focus:border-gray-500 focus:ring-gray-400/20 dark:border-gray-700 dark:text-gray-100 dark:focus:border-gray-500"}`}),a.jsx("button",{type:"button","aria-label":d.chat.goalBudgetSave,title:d.chat.goalBudgetSave,disabled:Nn,onClick:Js,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-35 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white",children:a.jsx(qu,{size:14})})]}),a.jsx("p",{id:"goal-budget-hint",className:`mt-1.5 text-[11px] leading-4 ${Nn?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-gray-500"}`,children:Nn?d.chat.goalBudgetInvalid:d.chat.goalBudgetHint})]})}),a.jsx("button",{type:"button","aria-label":d.chat.goalRemove,onClick:()=>Mr(!1),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),Ke!==null&&a.jsxs("span",{title:d.chat.handoffTargetTitle(_n(Ke)),className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsx(Ha,{id:Ke.agentId,name:_n(Ke),size:13,className:"shrink-0 rounded-sm"}),a.jsx("span",{className:"truncate",children:Ke.agentId}),a.jsx("button",{type:"button","aria-label":d.chat.handoffRemove,onClick:()=>{dt(null),U?.(null),Vt.current?.focus()},className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),pt!==null&&a.jsxs("span",{title:d.chat.modelSwitchTargetTitle(hu(pt)),className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsx(jo,{provider:pt.provider,className:"h-3.5 w-3.5 shrink-0"}),a.jsx("span",{className:"truncate",children:hu(pt)}),a.jsx("button",{type:"button","aria-label":d.chat.modelSwitchRemove,onClick:()=>{hn(null),Vt.current?.focus()},className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),st.map(ae=>{const _e=$.find(et=>et.name===ae);return a.jsxs("span",{className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",..._e?{title:Wl(ye,_e)}:{},children:[a.jsx(Yf,{icon:_e?.icon,size:13,className:"shrink-0 text-gray-500 dark:text-gray-400"}),a.jsx("span",{className:"truncate",children:ae}),a.jsx("button",{type:"button","aria-label":`${d.chat.skillRemove} ${ae}`,onClick:()=>er(ae),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]},ae)})]}),a.jsx("textarea",{ref:Vt,rows:2,value:Me,autoFocus:q,onChange:ae=>{const _e=ae.target.value,et=ae.target.selectionStart??_e.length;ze(_e),A?.(_e),Dn(et),ve(0),Ge(qe=>{if(qe===null)return null;const vt=PS(_e,et);return vt&&vt.start===qe?qe:null})},onSelect:ae=>Dn(ae.currentTarget.selectionStart??0),onKeyDown:mt,onPaste:Pt,placeholder:Xt&&Hr?zn?d.chat.followUpPlaceholderShort:d.chat.followUpPlaceholder:Xt&&n?zn?d.chat.steerPlaceholderShort:d.chat.steerPlaceholder:zn?d.chat.inputPlaceholderShort:d.chat.inputPlaceholder,className:"block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 text-base leading-6 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500"}),a.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs",children:[a.jsxs("div",{className:"no-scrollbar flex min-w-0 flex-1 items-center gap-2 overflow-x-auto",children:[a.jsx("input",{ref:Ir,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Wt}),a.jsx("input",{ref:Ui,type:"file",multiple:!0,disabled:Mt,className:"hidden",onChange:_r}),be==="session"&&a.jsx(Wz,{items:[{key:"image",icon:Kz,label:d.chat.uploadImage,desc:V&&!Mt?d.chat.uploadImageDesc:d.chat.imagesAsPathHint,active:ct.length>0,onSelect:()=>Ir.current?.click()},{key:"file",icon:bf,label:d.chat.uploadFile,desc:d.chat.uploadFileDesc,active:he.length>0,disabled:Mt,onSelect:()=>Ui.current?.click()},{key:"goal",icon:_u,label:d.chat.goalMode,desc:d.chat.goalModeDesc,active:Mt,disabled:Xt||Cn||oe,onSelect:()=>Mr(!Mt)}],footer:a.jsx(Vz,{steerMode:ta,onChangeSteerMode:is}),direction:w&&S?"down":"up"}),a.jsx(zz,{value:P,onChange:B,disabled:Y,direction:w&&S?"down":"up"}),a.jsx(Gz,{skills:$,selected:st,onToggle:er,disabled:Xt||Cn||oe,direction:w&&S?"down":"up"}),a.jsx("span",{title:d.chat.slashHint,className:"hidden min-w-0 truncate text-gray-300 @lg:block dark:text-gray-600",children:d.chat.slashHint})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[!S&&a.jsx(Dz,{now:E,unknown:L,...z!==void 0?{window:z}:{},...F!==void 0?{sessionId:F}:{}}),w&&S&&_&&a.jsx(XS,{value:T??null,onChange:_,disabled:oe}),!S&&D&&a.jsx(XS,{value:R??"",onChange:D,disabled:oe,direction:"up"}),w&&S?a.jsx(Ay,{models:w,value:v,...N!==void 0?{defaultModel:N}:{},onChange:S,disabled:oe}):be==="subagent"?a.jsxs("span",{title:v?.modelId??"",className:"flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 rounded-md px-1 text-gray-400 dark:text-gray-500",children:[a.jsx(jo,{provider:v?.provider??"custom",className:"h-4 w-4 shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:Er})]}):a.jsxs("button",{type:"button",title:v?.modelId??"","aria-label":`${d.chat.model} ${v?.modelId??""}`,onClick:()=>wr(d.chat.modelLockedHint),className:"flex h-8 min-w-0 max-w-44 shrink cursor-pointer items-center gap-1.5 rounded-md px-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300",children:[a.jsx(jo,{provider:v?.provider??"custom",className:"h-4 w-4 shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:Er})]}),a.jsx("button",{type:"button",title:Jn?d.chat.stop:Xt?na:d.chat.send,"aria-label":Jn?d.chat.stop:Xt?na:d.chat.send,disabled:Jn?!1:Xt?!pn:!Rn,onClick:()=>Jn?void x():void Re(),className:Jn?"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 transition-colors duration-150 hover:bg-red-100 dark:bg-red-950/60 dark:text-red-400 dark:hover:bg-red-950":"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300 dark:disabled:bg-gray-800 dark:disabled:text-gray-600",children:Jn?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14","aria-hidden":!0,className:"block",children:a.jsx("rect",{x:"2",y:"2",width:"10",height:"10",rx:"2",fill:"currentColor"})}):a.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"block",children:a.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})})})]})]})]})]})}const JS=500,Jz=5;function eB(e,t){return e+t+1}function X0(e,t){return e+t>=Jz}const ET=20,tB=20;function nB(e,t,n=ET,s=tB){const o=n+1+s;if(e<=o)return{start:0,end:e};if(t===null||t<0||t>=e)return{start:e-o,end:e};const c=Math.min(Math.max(0,t-n),e-o);return{start:c,end:c+o}}const rB=12,AT=5,_T=48;function aB(e,t){return Math.max(AT,Math.min(rB,Math.floor((e-_T)/Math.max(1,t))))}function sB(e){const t=Math.floor((e-_T)/AT);return Math.min(ET,Math.max(0,Math.floor((t-1)/2)))}function iB(e){const t=[];let n=null,s=!1;for(const o of e){if(o.kind==="user_text"||o.kind==="user_image"){let c="";if(o.kind==="user_text"){const u=CT(o.text);if(!u||u.goalRound!==void 0&&u.goalRound>1){s=!1;continue}c=u.body}s&&n?n.question===""&&c!==""&&(n.question=c):(n={anchorId:o.id,question:c,answer:""},t.push(n)),s=!0;continue}if(s=!1,o.kind==="assistant_text"&&n&&n.answer.length<JS){const c=o.text.trim();c!==""&&(n.answer=(n.answer===""?c:`${n.answer} ${c}`).slice(0,JS))}}return t}function oB(e,t){let n=e.replace(/```[^\n]*/g,"").replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^[ \t]*(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d+[.)][ \t]+)/gm,"").replace(/[*_`~]/g,"").replace(/\s+/g," ").trim();return n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}const lB="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm4 0v16M12 9h5m-5 4h5",cB=96,uB=1e3,dB=56,mB=48,e2="(hover: hover) and (pointer: fine)";function fB(e,t){const[n,s]=y.useState(()=>window.matchMedia(e2).matches),[o,c]=y.useState({gutterOk:!1,height:0});return y.useEffect(()=>{const u=window.matchMedia(e2),f=p=>s(p.matches);return u.addEventListener("change",f),()=>u.removeEventListener("change",f)},[]),y.useEffect(()=>{const u=e.current;if(!u)return;const f=()=>{const h=parseFloat(getComputedStyle(document.documentElement).fontSize)||16,x=(u.clientWidth-mB*h)/2;c({gutterOk:x>=dB,height:u.clientHeight})};f();const p=new ResizeObserver(f);return p.observe(u),()=>p.disconnect()},[e,t]),{shown:n&&o.gutterOk,height:o.height}}function RT(e,t){const n=e.querySelectorAll("[data-outline-anchor]");if(n.length===0)return null;let s=null,o=null;const c=e.scrollTop+cB;for(const f of n){const p=Number(f.dataset.outlineAnchor);t.has(p)&&(s=p,f.offsetTop<=c&&(o=p))}return e.scrollHeight-e.scrollTop-e.clientHeight<2?s:o}let t2=null,n2;function IT(e,t){const n=e?.querySelector(`[data-outline-anchor="${t}"]`);!e||!n||(e.scrollTo({top:Math.max(0,n.offsetTop-8)}),window.clearTimeout(n2),t2?.classList.remove("outline-flash"),t2=n,n.classList.remove("outline-flash"),n.offsetWidth,n.classList.add("outline-flash"),n2=window.setTimeout(()=>n.classList.remove("outline-flash"),uB))}function r2({edge:e}){return a.jsx("div",{"data-outline-overflow":e,"aria-hidden":!0,className:`flex w-10 flex-col items-start gap-[3px] pl-4 ${e==="above"?"pb-1.5":"pt-1.5"}`,children:[0,1,2].map(t=>a.jsx("span",{className:"h-[2px] w-[2px] rounded-full bg-gray-300 dark:bg-gray-700"},t))})}function LT(e,t,n,s){return e.answer?oB(e.answer,s):n&&e===t[t.length-1]?d.chat.outlineAnswering:""}function pB({entries:e,turnOffset:t=0,version:n,scrollRef:s,running:o,fit:c}){const[u,f]=y.useState(null),[p,h]=y.useState(null),x=y.useRef(null);if(y.useEffect(()=>{const R=s.current;if(!c.shown||!R||!X0(t,e.length))return;const D=new Set(e.map(F=>F.anchorId));let z=null;const E=()=>{z=null;const F=s.current;F&&f(RT(F,D))},L=()=>{z??=requestAnimationFrame(E)};return E(),R.addEventListener("scroll",L,{passive:!0}),()=>{R.removeEventListener("scroll",L),z!==null&&cancelAnimationFrame(z)}},[c.shown,s,e.length,t,n]),!c.shown||!X0(t,e.length))return null;const g=R=>{const D=R.currentTarget.getBoundingClientRect();return D.top+D.height/2-(x.current?.getBoundingClientRect().top??0)},v=sB(c.height),{start:w,end:S}=nB(e.length,e.findIndex(R=>R.anchorId===u),v,v),C=e.slice(w,S),N=aB(c.height,C.length),T=p===null?null:C.find(R=>R.anchorId===p.id)??null,_=T===null?"":LT(T,e,o,160);return a.jsxs("nav",{ref:x,"aria-label":d.chat.outlineTitle,className:"pointer-events-none absolute inset-y-0 left-0 z-10 flex flex-col items-start justify-center",children:[a.jsxs("div",{className:"max-h-full overflow-hidden",children:[(w>0||t>0)&&a.jsx(r2,{edge:"above"}),C.map((R,D)=>{const z=R.anchorId===u;return a.jsx("button",{type:"button","data-outline-tick":R.anchorId,"aria-current":z||void 0,"aria-label":d.chat.outlineTickLabel(eB(t,w+D),R.question||d.chat.outlineNoText),style:{height:N},onMouseEnter:E=>h({id:R.anchorId,top:g(E)}),onMouseLeave:()=>h(null),onFocus:E=>h({id:R.anchorId,top:g(E)}),onBlur:()=>h(null),onClick:()=>{IT(s.current,R.anchorId),f(R.anchorId)},className:"group/tick pointer-events-auto flex w-10 items-center pl-2.5",children:a.jsx("span",{className:`h-[2px] rounded-full transition-all duration-150 ${z?"w-5 bg-gray-800 dark:bg-gray-200":"w-3.5 bg-gray-300 group-hover/tick:bg-gray-500 dark:bg-gray-700 dark:group-hover/tick:bg-gray-400"}`})},R.anchorId)}),S<e.length&&a.jsx(r2,{edge:"below"})]}),T&&a.jsxs("div",{"data-outline-card":!0,"aria-hidden":!0,className:"anim-pop pointer-events-none absolute left-10 w-80 -translate-y-1/2 rounded-xl border border-gray-200 bg-white px-4 py-3 shadow-lg dark:border-gray-700 dark:bg-gray-900",style:{top:Math.min(Math.max(p.top,56),Math.max(56,c.height-56))},children:[a.jsx("p",{className:`truncate text-sm ${T.question===""?"italic text-gray-500 dark:text-gray-400":"font-semibold text-gray-900 dark:text-gray-100"}`,children:T.question||d.chat.outlineNoText}),_!==""&&a.jsx("p",{className:`mt-1 line-clamp-3 text-sm leading-snug text-gray-500 dark:text-gray-400 ${T.answer===""?"animate-pulse":""}`,children:_})]})]})}function hB({entries:e,turnOffset:t=0,scrollRef:n,running:s}){const[o,c]=y.useState(!1),[u,f]=y.useState(null);if(!X0(t,e.length))return null;const p=h=>{h&&n.current&&f(RT(n.current,new Set(e.map(x=>x.anchorId)))),c(h)};return a.jsx(Qn,{open:o,setOpen:p,menuClass:"right-0 top-full mt-1 w-72 max-w-[calc(100vw-1.5rem)] origin-top-right",button:a.jsx("button",{type:"button",title:d.chat.outlineTitle,"aria-label":d.chat.outlineTitle,onClick:()=>p(!o),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:lB,size:15})}),children:a.jsx("div",{className:"max-h-[60vh] overflow-y-auto py-1",children:e.map(h=>{const x=LT(h,e,s,80),g=h.anchorId===u;return a.jsxs("button",{type:"button","data-outline-menu-entry":h.anchorId,"aria-current":g||void 0,onClick:()=>{IT(n.current,h.anchorId),c(!1)},className:`block w-full px-3 py-1.5 text-left transition-colors duration-150 ${g?"bg-gray-100 dark:bg-gray-800":"hover:bg-gray-50 dark:hover:bg-gray-800/60"}`,children:[a.jsx("span",{className:`block truncate text-sm ${h.question===""?"italic text-gray-500 dark:text-gray-400":"font-medium text-gray-800 dark:text-gray-200"}`,children:h.question||d.chat.outlineNoText}),x!==""&&a.jsx("span",{className:`mt-0.5 block truncate text-xs text-gray-500 dark:text-gray-400 ${h.answer===""?"animate-pulse":""}`,children:x})]},h.anchorId)})})})}function OT({className:e}){return a.jsx("img",{src:"/penguin-logo.svg",alt:"","aria-hidden":!0,draggable:!1,className:`select-none ${e??"h-9 w-9 rounded-lg"}`})}const Ly="penguin.dock.layout",a2=40,DT=["agents","workspace","memory","trace","messaging"];function kn(e){return e.kind==="panel"?e.panel:`terminal:${e.terminalId}`}function gB(e){return DT.includes(e)?{kind:"panel",panel:e}:e.startsWith("terminal:")&&e.length>9?{kind:"terminal",terminalId:e.slice(9)}:null}const $T=.4,xB=.15,Oy=.85,UT=140;function PT(e){return Number.isFinite(e)?Math.min(Oy,Math.max(xB,e)):$T}function s2(){return{tabs:[],active:null,open:!1}}function Dy(){return{right:s2(),bottom:s2(),focus:"bottom"}}const Q0="~none";function yB(e,t){try{const n=localStorage.getItem(e);if(n===null)return t;const s=JSON.parse(n);return typeof s=="object"&&s!==null?s:t}catch{return t}}function zT(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}function i2(e){const t=e??{},n=(Array.isArray(t.tabs)?t.tabs:[]).map(u=>typeof u=="string"?gB(u):null).filter(u=>u!==null),s=new Set,o=n.filter(u=>{const f=kn(u);return s.has(f)?!1:(s.add(f),!0)}),c=typeof t.active=="string"&&o.some(u=>kn(u)===t.active)?t.active:o.length>0?kn(o[o.length-1]):null;return{tabs:o,active:c,open:t.open===!0}}function bB(e){const t=e??{},n=i2(t.right),s=i2(t.bottom),o=new Set(n.tabs.map(kn));return s.tabs=s.tabs.filter(c=>!o.has(kn(c))),s.active!==null&&!s.tabs.some(c=>kn(c)===s.active)&&(s.active=s.tabs.length>0?kn(s.tabs[s.tabs.length-1]):null),{right:n,bottom:s,focus:t.focus==="right"?"right":"bottom"}}function vB(){const e=yB(Ly,{}),t={};if(typeof e.scopes=="object"&&e.scopes!==null)for(const[n,s]of Object.entries(e.scopes))t[n]=bB(s);return{scopes:t,bottomRatio:PT(typeof e.bottomRatio=="number"?e.bottomRatio:NaN)}}let{scopes:Wn,bottomRatio:Dl}=vB(),za=Q0,Jt=Wn[za]??Dy();function kB(e){return e.right.tabs.length===0&&e.bottom.tabs.length===0&&!e.right.open&&!e.bottom.open}function Ur(){if(kB(Jt)){const{[za]:t,...n}=Wn;Wn=n}else{const{[za]:t,...n}=Wn;Wn={...n,[za]:Jt}}const e=Object.keys(Wn);e.length>a2&&(Wn=Object.fromEntries(e.slice(e.length-a2).map(t=>[t,Wn[t]]))),zT(Ly,{scopes:Object.fromEntries(Object.entries(Wn).map(([t,n])=>[t,{right:{...n.right,tabs:n.right.tabs.map(kn)},bottom:{...n.bottom,tabs:n.bottom.tabs.map(kn)},focus:n.focus}])),bottomRatio:Dl})}const Z0=new Set;let BT=0,Qf=0;function Cr(){BT+=1;for(const e of[...Z0])e()}function $y(){return BT}function wB(){return Qf}function Zf(e){return Z0.add(e),()=>Z0.delete(e)}function SB(e){FT(e??Q0,za===Q0)}function HT(e){FT(e,!0)}function FT(e,t){if(e===za)return;Qf+=1,Ur();const n=Wn[za];if(t&&n!==void 0&&Wn[e]===void 0){const{[za]:o,...c}=Wn;Wn={...c,[e]:n},zT(Ly,{scopes:Object.fromEntries(Object.entries(Wn).map(([u,f])=>[u,{right:{...f.right,tabs:f.right.tabs.map(kn)},bottom:{...f.bottom,tabs:f.bottom.tabs.map(kn)},focus:f.focus}])),bottomRatio:Dl})}za=e,Jt=Wn[za]??Dy(),Cr()}function jB(){return za}let Iu=!1;if(typeof window<"u"&&typeof window.matchMedia=="function"){const e=window.matchMedia("(max-width: 1023.98px)");Iu=e.matches,e.addEventListener("change",t=>{Iu=t.matches,Cr()})}function or(e){return Jt[e]}function td(e){for(const t of["right","bottom"]){const n=Jt[t].tabs.findIndex(s=>kn(s)===e);if(n!==-1)return{position:t,index:n}}return null}function Lu(e){return td(e)?.position??null}function Ba(e){return or(e).open}function CB(e){return or(e).active}function Uy(){const e=Jt.focus,t=e==="right"?"bottom":"right";return Ba(e)&&or(e).active!==null?or(e).active:Ba(t)?or(t).active:null}function NB(){return Iu?!Ba("right")&&!Ba("bottom")?[]:[{position:"bottom",merged:!0,tabs:[...Ba("bottom")?Jt.bottom.tabs:[],...Ba("right")?Jt.right.tabs:[]],activeKey:Uy()}]:["right","bottom"].filter(Ba).map(t=>({position:t,merged:!1,tabs:or(t).tabs,activeKey:or(t).active}))}function TB(e){const t=Lu(e);return t===null||!Ba(t)?!1:Iu?Uy()===e:or(t).active===e}function Py(e,t){const n=or(e);n.active=t,n.open=!0,Jt.focus=e}function qg(e){const t=td(e);t&&(Py(t.position,e),Ur(),Cr())}function zy(e,t){const n=kn(e),s=td(n);if(s&&s.position!==t&&(Jt[s.position].tabs=Jt[s.position].tabs.filter(o=>kn(o)!==n),Jt[s.position].active===n)){const o=Jt[s.position].tabs;Jt[s.position].active=o.length>0?kn(o[o.length-1]):null}(!s||s.position!==t)&&(Jt[t].tabs=[...Jt[t].tabs,e]),Py(t,n)}function J0(e){const t=td(e);if(!t)return;const n=or(t.position);n.tabs=n.tabs.filter(s=>kn(s)!==e),n.active===e&&(n.active=n.tabs.length>0?kn(n.tabs[n.tabs.length-1]):null),n.tabs.length===0&&(n.open=!1),Ur(),Cr()}function MB(e,t){const n=td(e);if(!n)return;Qf+=1;const s=Jt[n.position].tabs[n.index];zy(s,t),Jt[n.position].tabs.length===0&&(Jt[n.position].open=!1),Ur(),Cr()}function o2(e,t){if(e===t)return;const n=or(e);if(n.tabs.length===0)return;Qf+=1;const s=n.active,o=or(t);o.tabs=[...o.tabs,...n.tabs],n.tabs=[],n.active=null,n.open=!1,s!==null?Py(t,s):Jt.focus=t,o.open=!0,Ur(),Cr()}function EB(e,t){const n=or(e),s=new Map(n.tabs.map(c=>[kn(c),c])),o=t.map(c=>s.get(c)).filter(c=>c!==void 0);o.length===n.tabs.length&&(o.every((c,u)=>c===n.tabs[u])||(n.tabs=o,Ur(),Cr()))}function AB(e){const t=or(e);t.open=!t.open,t.open&&(Jt.focus=e),Ur(),Cr()}function _B(e){e.merged?(Jt.right.open=!1,Jt.bottom.open=!1):or(e.position).open=!1,Ur(),Cr()}function vl(e){return Lu(e)}function ho(e,t){const n=t??vl(e)??"right";zy({kind:"panel",panel:e},n),Ur(),Cr()}function qT(e){return`terminal:${e}`}function RB(e){return Lu(qT(e))}function IB(){return[...Jt.bottom.tabs,...Jt.right.tabs].filter(e=>e.kind==="terminal").map(e=>e.terminalId)}function By(e){const t=new Set;for(const n of[Jt,...Object.values(Wn)])for(const s of[...n.right.tabs,...n.bottom.tabs])s.kind==="terminal"&&t.add(s.terminalId);return e.filter(n=>!t.has(n))}function nd(e,t){zy({kind:"terminal",terminalId:e},t??RB(e)??"bottom"),Ur(),Cr()}function LB(e){nd(e)}function OB(e,t,n){if(By([t]).length===0)return;if(e===za){nd(t,n);return}const s=Wn[e]??Dy(),o=s[n];o.tabs=[...o.tabs,{kind:"terminal",terminalId:t}],o.active=qT(t),o.open=!0;const{[e]:c,...u}=Wn;Wn={...u,[e]:s},Ur(),Cr()}function DB(e){let t=!1;const n=s=>{const o=s.tabs.filter(c=>c.kind!=="terminal"||e.has(c.terminalId));return o.length===s.tabs.length?!1:(s.tabs=o,s.active!==null&&!o.some(c=>kn(c)===s.active)&&(s.active=o.length>0?kn(o[o.length-1]):null),o.length===0&&(s.open=!1),!0)};for(const s of Object.values(Wn))s!==Jt&&(n(s.right)&&(t=!0),n(s.bottom)&&(t=!0));n(Jt.right)&&(t=!0),n(Jt.bottom)&&(t=!0),t&&(Ur(),Cr())}function $B(){const e=IB();if(e.length===0)return!1;const t=["right","bottom"].filter(s=>or(s).tabs.some(o=>o.kind==="terminal"));if(t.some(s=>Ba(s)&&(Iu?Uy()?.startsWith("terminal:")===!0:or(s).active?.startsWith("terminal:")===!0))){for(const s of t)or(s).open=!1;return Ur(),Cr(),!0}return LB(e[e.length-1]),!0}function VT(){return Dl}function UB(e){const t=PT(e);t!==Dl&&(Dl=t,Ur(),Cr())}function PB(){Dl=$T,Ur(),Cr()}const ou={Output:1,Input:2,Resize:3,Restore:5,Exit:6},zB=new TextEncoder,BB=new TextDecoder;function GT(e,t=""){const n=typeof t=="string"?zB.encode(t):t,s=new Uint8Array(2+n.byteLength);return s[0]=e,s[1]=0,s.set(n,2),s}function HB(e){if(e.byteLength<2)return null;const t=new Uint8Array(e,0,2);return{opcode:t[0],slot:t[1],text:BB.decode(new Uint8Array(e,2))}}function l2(e,t,n){return GT(ou.Resize,JSON.stringify({cols:e,rows:t,intent:n}))}function FB(){return Promise.all([an(()=>import("./xterm-BjU-ZsL5.js").then(e=>e.x),[]),an(()=>import("./addon-fit-CE-3eCvv.js").then(e=>e.a),[]),an(()=>import("./addon-web-links-DeODgawX.js").then(e=>e.a),[])])}const qB={background:"#000000",foreground:"#f3f4f6",cursor:"#f3f4f6",cursorAccent:"#000000",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"},VB={background:"#ffffff",foreground:"#111827",cursor:"#111827",cursorAccent:"#ffffff",selectionBackground:"rgba(0, 0, 0, 0.12)",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"};function c2(e){return e?qB:VB}async function KT(e,t){return fetch(e,{credentials:"same-origin",...t,headers:{"Content-Type":"application/json",...t?.headers??{}}})}class Hy extends Error{constructor(t,n){super(n),this.status=t,this.name="HttpStatusError"}status}function WT(e,t,n,s){const o=t?.method??"GET",c=s.trim()===""?n.statusText:s.trim();return new Hy(n.status,`${o} ${e} → ${n.status} ${c}`)}async function Fy(e,t){const n=await KT(e,t);if(!n.ok)throw WT(e,t,n,await n.text());return await n.json()}async function vf(e,t){const n=await KT(e,t);if(n.status===404)return null;if(!n.ok)throw WT(e,t,n,await n.text());return await n.json()}function GB(e,t,n){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/terminals/${e}/stream?cols=${t}&rows=${n}`}function YT({ensure:e,onStatus:t,onInfo:n,onTitle:s,className:o}){const c=y.useRef(null),{terminalDark:u}=as(),f=y.useRef(u);f.current=u;const p=y.useRef(null);y.useEffect(()=>{p.current&&(p.current.options.theme=c2(u))},[u]);const h=y.useRef({ensure:e,onStatus:t,onInfo:n,onTitle:s});return h.current={ensure:e,onStatus:t,onInfo:n,onTitle:s},y.useEffect(()=>{const x=c.current;if(!x)return;let g=!1,v=null;const w=setTimeout(()=>{g||S(x).then(C=>{g?C():v=C})},0);return()=>{g=!0,clearTimeout(w),v?.()};async function S(C){const[{Terminal:N},{FitAddon:T},{WebLinksAddon:_}]=await FB();let R=!1,D=null,z=!1;const E=(H,$="")=>{R||h.current.onStatus?.(H,$)},L=new N({allowProposedApi:!0,cursorBlink:!0,fontFamily:'"JetBrains Mono", "Fira Code", Menlo, Monaco, "DejaVu Sans Mono", Consolas, monospace',fontSize:13,lineHeight:1.2,scrollback:5e3,theme:c2(f.current)}),F=new T;L.loadAddon(F),L.loadAddon(new _),p.current=L,L.open(C),F.fit();const V=()=>{const H=L.getSelection();H&&(navigator.clipboard?.writeText(H).catch(()=>{}),L.clearSelection())},P=()=>{navigator.clipboard?.readText().then(H=>H&&L.paste(H)).catch(()=>{})};L.attachCustomKeyEventHandler(H=>{if(H.type!=="keydown")return!0;const $=H.key.toLowerCase();return H.ctrlKey&&H.shiftKey&&$==="c"||H.ctrlKey&&!H.shiftKey&&H.key==="Insert"||H.ctrlKey&&!H.shiftKey&&!H.altKey&&$==="c"&&L.hasSelection()?(V(),!1):!(H.ctrlKey&&!H.altKey&&$==="v"||!H.ctrlKey&&H.shiftKey&&H.key==="Insert")});const B=new AbortController,{signal:Y}=B,q=()=>L.modes.mouseTrackingMode!=="none";C.addEventListener("contextmenu",H=>{H.preventDefault(),!q()&&(L.hasSelection()?V():P())},{signal:Y}),C.addEventListener("mousedown",H=>{H.button===1&&!q()&&(H.preventDefault(),P())},{signal:Y}),C.addEventListener("mouseup",()=>L.focus(),{signal:Y}),C.addEventListener("focusin",()=>{D?.readyState===WebSocket.OPEN&&D.send(l2(L.cols,L.rows,"claim"))},{signal:Y}),L.onData(H=>{D?.readyState===WebSocket.OPEN&&D.send(GT(ou.Input,H))}),L.onTitleChange(H=>{R||h.current.onTitle?.(H)}),(async()=>{try{const H=await h.current.ensure(L.cols,L.rows);if(R)return;h.current.onInfo?.(H),D=new WebSocket(GB(H.id,L.cols,L.rows)),D.binaryType="arraybuffer",D.onopen=()=>E("ready"),D.onmessage=$=>{if(!($.data instanceof ArrayBuffer))return;const X=HB($.data);if(X)switch(X.opcode){case ou.Restore:case ou.Output:L.write(X.text);break;case ou.Exit:{const{exitCode:le}=JSON.parse(X.text);z=!0,E("exited",String(le));break}default:break}},D.onerror=()=>E("error","stream error"),D.onclose=()=>{z||E("error","stream closed")}}catch(H){E("error",H instanceof Error?H.message:String(H))}})();const K=new ResizeObserver(()=>{R||(F.fit(),D?.readyState===WebSocket.OPEN&&D.send(l2(L.cols,L.rows,"update")))});return K.observe(C),L.focus(),()=>{R=!0,p.current=null,B.abort(),K.disconnect(),D?.close(),L.dispose()}}},[]),a.jsx("div",{ref:c,className:o??"min-h-0 flex-1 overflow-hidden"})}function KB(e){return(e??"").trim().replace(/^[^@\s]+@[^:\s]+:?\s*/,"").trim()}const WB=3e4;let $l=[],XT=[],u2="",Xc=null;const kl=new Set;let Em=null,Zm=!1;const Ou=new Map;function YB(e){const t=Ou.get(e);return t===void 0?!1:Date.now()>t?(Ou.delete(e),!1):!0}function Jf(e){$l=e;const t=JSON.stringify(e);if(t!==u2){XT=e,u2=t;for(const n of[...kl])n()}}function XB(e,t){$l.some(n=>n.id===e&&(n.title??"")!==t)&&Jf($l.map(n=>n.id===e?{...n,title:t}:n))}function QT(){return XT}function d2(){return!Zm}function Xs(){return Xc||(Xc=(async()=>{try{const e=await fetch("/api/terminals",{credentials:"same-origin"});if(e.status===404&&!Zm){Zm=!0;for(const o of[...kl])o();return}if(!e.ok)return;Zm=!1;const t=await e.json(),n=new Set(t.terminals.map(o=>o.id));for(const o of Ou.keys())n.has(o)||Ou.delete(o);const s=t.terminals.filter(o=>o.alive&&!YB(o.id));DB(new Set(s.map(o=>o.id))),Jf(s)}catch{}finally{Xc=null}})(),Xc)}const m2=()=>{Xs()};function ZT(e){return kl.size===0&&(Xs(),Em=setInterval(()=>{Xs()},WB),window.addEventListener("focus",m2)),kl.add(e),()=>{kl.delete(e),kl.size===0&&Em!==null&&(clearInterval(Em),Em=null,window.removeEventListener("focus",m2))}}function QB(e){$l.some(t=>t.id===e.id)||Jf([...$l,e])}async function ZB(e){Ou.set(e,Date.now()+1e4),Jf($l.filter(t=>t.id!==e));try{await fetch(`/api/terminals/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"same-origin"})}catch{}for(const t of[300,1500])setTimeout(()=>{Xs()},t)}const Vg="~";let ex=null;function JT(e){ex=e!==null&&e.trim()!==""?e:null}function JB(e){return e instanceof Hy&&e.status===400&&e.message.includes("cwd_not_")}async function eM(e){const t=n=>Fy("/api/terminals",{method:"POST",body:JSON.stringify({cwd:n})});try{let n;try{n=await t(ex??Vg)}catch(s){if(ex===null||!JB(s))throw s;console.warn(`[terminal] Workspace unusable as cwd, opening in ${Vg}:`,s),n=await t(Vg)}QB(n),nd(n.id,e)}catch(n){const s=n instanceof Error?n.message:String(n),o=n instanceof Hy&&n.status===404?`${s} — ${d.terminal.noTerminalApi}`:s;console.error("[terminal] create failed:",o),Be(`${d.terminal.createFailed}: ${o}`)}finally{Xs()}}async function tM(e){const n=((await Fy("/api/terminals").catch(()=>null))?.terminals??QT()).filter(o=>o.alive),s=By(n.map(o=>o.id)).at(-1);if(s!==void 0){nd(s,e),Xs();return}await eM(e)}function eH(e,t){const n=jB(),s=window.open(`/terminal?id=${encodeURIComponent(e)}`,"_blank");if(J0(`terminal:${e}`),!s)return;const o=window.setInterval(()=>{s.closed&&(window.clearInterval(o),(async()=>(await vf(`/api/terminals/${encodeURIComponent(e)}`).catch(()=>null))?.alive===!0&&(OB(n,e,t),Xs()))())},600)}function tH(){$B()||tM()}typeof window<"u"&&window.addEventListener("keydown",e=>{!e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.key!=="`"&&e.code!=="Backquote"||(e.preventDefault(),tH())});const tx=[{id:"webapps",tasks:[{id:"game",skills:["web-design"]},{id:"gamecenter",skills:["web-design"]},{id:"lol",skills:["web-design"]},{id:"rhythmRunner",skills:["web-design"]}]},{id:"agents",tasks:[{id:"investmentCopilot",skills:["penguin-sdk","web-design"]},{id:"rag",skills:["penguin-sdk","web-design"]},{id:"agentBenchmarkBuild",skills:[]},{id:"agentOptimization",skills:[]}]},{id:"schedules",tasks:[{id:"dailyPlan",skills:[]},{id:"githubDigest",skills:[]},{id:"memoryReview",skills:[]}]}];tx.flatMap(e=>[...e.tasks]);function nM({open:e,glyph:t,label:n,count:s,onOpen:o}){return a.jsxs("button",{type:"button","aria-expanded":e,onClick:o,className:`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left transition-colors duration-150 ${e?"bg-gray-100 dark:bg-gray-800/70":"hover:bg-gray-100 dark:hover:bg-gray-800/70"}`,children:[a.jsx("span",{className:"shrink-0 text-brand-500 dark:text-brand-400",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a.jsx("path",{d:t})})}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-700 dark:text-gray-300",children:n}),a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:s}),a.jsx(Zn,{open:e,size:Ye.chevron,className:"text-gray-400"})]})}const nx="rounded-md px-2 py-1.5 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200",qy=3,Nl=40,gu=4e3;function nH(){return`sc-${crypto.randomUUID().replace(/-/g,"").slice(0,12)}`}function Gg(e,t){if(typeof e!="string")return null;const n=e.trim();return n===""?null:n.slice(0,t)}function rH(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const s of e){if(t.length>=qy)break;if(s===null||typeof s!="object"||Array.isArray(s))continue;const o=s,c=Gg(o.id,64),u=Gg(o.title,Nl),f=Gg(o.prompt,gu);c===null||u===null||f===null||n.has(c)||(n.add(c),t.push({id:c,title:u,prompt:f}))}return t}function f2(e){const t=e.title.trim(),n=e.prompt.trim();return t===""?"titleRequired":t.length>Nl?"titleTooLong":n===""?"promptRequired":n.length>gu?"promptTooLong":null}function rM(e){return e.length<qy}function aH(e,t){const n={id:t.id??nH(),title:t.title.trim(),prompt:t.prompt.trim()},s=e.findIndex(o=>o.id===n.id);return s!==-1?e.map((o,c)=>c===s?n:o):rM(e)?[...e,n]:[...e]}function sH(e,t){return e.filter(n=>n.id!==t)}function iH(e){const t=e.split(`
|
|
173
|
+
`)}function jz(e){if(e.sending)return"disabled";const t=!e.goalOn;return t&&e.canSteerChannel&&!e.hasHandoffTarget&&!e.hasPendingModel&&(e.hasText||e.hasImages||e.hasFiles)&&!e.followUpMode?"steer":t&&e.canQueueChannel&&e.stagedRoute!=="blocked"&&e.hasContent?"queue":"stop"}function Cz(e,t){return e==="compacting"?!0:e==="running"&&t==="stop"}function _y(e){return e!=null&&e.includes("Files")}function Nz(e,t,n){const s=t&&n;switch(e){case"over":return{active:s,claim:s,accept:!1};case"leave":return{active:s,claim:!1,accept:!1};case"drop":return{active:!1,claim:s,accept:s};case"end":return{active:!1,claim:!1,accept:!1}}}function Tz(e){const t=[],n=[];for(const s of e)(s.type.startsWith("image/")?t:n).push(s);return{images:t,files:n}}function zS(e){e.defaultPrevented||!_y(e.dataTransfer?.types)||(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="none"))}function BS(e){e.defaultPrevented||!_y(e.dataTransfer?.types)||e.preventDefault()}const NT=y.createContext(null);function Mz({className:e,children:t}){const[n,s]=y.useState(null);return a.jsx("div",{className:e,ref:s,children:a.jsx(NT.Provider,{value:n,children:t})})}function Ez({onFiles:e}){const t=y.useContext(NT),[n,s]=y.useState(!1),o=y.useRef(!1),c=y.useRef(e);return y.useEffect(()=>{c.current=e}),y.useEffect(()=>{if(!t)return;const u=v=>v instanceof Node&&t.contains(v),f=(v,w,S)=>{const C=Nz(v,_y(w.dataTransfer?.types),S);return o.current!==C.active&&(o.current=C.active,s(C.active)),C.claim&&(w.preventDefault(),w.dataTransfer&&(w.dataTransfer.dropEffect="copy")),C},p=v=>{f("over",v,u(v.target))},h=v=>{f("leave",v,u(v.relatedTarget))},x=v=>{if(!f("drop",v,u(v.target)).accept||!v.dataTransfer)return;const S=Array.from(v.dataTransfer.files);S.length>0&&c.current(S)},g=v=>{f("end",v,!1)};return window.addEventListener("dragover",p),window.addEventListener("dragleave",h),window.addEventListener("drop",x),window.addEventListener("dragend",g),()=>{window.removeEventListener("dragover",p),window.removeEventListener("dragleave",h),window.removeEventListener("drop",x),window.removeEventListener("dragend",g),o.current=!1,s(!1)}},[t]),!n||!t?null:ss.createPortal(a.jsx("div",{"aria-hidden":!0,className:"anim-fade pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-white/70 p-6 backdrop-blur-sm dark:bg-gray-950/70",children:a.jsxs("div",{className:"flex flex-col items-center gap-2 rounded-xl border-2 border-dashed border-gray-400 bg-white/80 px-10 py-8 text-center dark:border-gray-500 dark:bg-gray-900/80",children:[a.jsx(Oe,{d:bf,size:28,className:"text-gray-400 dark:text-gray-500"}),a.jsx("p",{className:"text-base font-medium text-gray-800 dark:text-gray-100",children:d.chat.dropFilesTitle}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.chat.dropFilesDesc})]})}),t)}const Az=128e3;function TT(e){const t=typeof e=="string"?Number(e):e;return typeof t=="number"&&Number.isFinite(t)&&t>0?t:Az}const Y0=[{text:"text-violet-500",swatch:"bg-violet-500"},{text:"text-amber-500 dark:text-amber-600",swatch:"bg-amber-500 dark:bg-amber-600"},{text:"text-sky-500 dark:text-sky-600",swatch:"bg-sky-500 dark:bg-sky-600"},{text:"text-rose-500",swatch:"bg-rose-500"}];function Ry(e){return Y0[e%Y0.length]}const _z=["bg-sky-500 dark:bg-sky-600","bg-amber-500 dark:bg-amber-600","bg-fuchsia-500 dark:bg-fuchsia-600","bg-rose-500","bg-violet-500","bg-emerald-500 dark:bg-emerald-600"],Xf={text:"text-gray-400 dark:text-gray-500",swatch:"bg-gray-400 dark:bg-gray-500"},HS=["systemPrompt","toolDefs","userMessages","assistantMessages","toolRequests","toolResults"];function Rz(e,t){if(e.contextClosed||e.total<=0)return null;const n=HS.map(c=>e[c]),s=FS(n,t),o=FS(n,100);return{parts:HS.map((c,u)=>({key:c,color:_z[u]??"",tokens:s[u]??0,percent:o[u]??0})),tools:e.topTools.map(c=>({name:c.name,tokens:Math.round(c.tokens/e.total*t),percent:Math.round(c.tokens/e.total*100)}))}}function FS(e,t){const n=e.reduce((f,p)=>f+p,0);if(n<=0)return e.map(()=>0);const s=e.map(f=>f/n*t),o=s.map(f=>Math.floor(f));let c=Math.round(t)-o.reduce((f,p)=>f+p,0);const u=s.map((f,p)=>({i:p,frac:f-Math.floor(f)})).sort((f,p)=>p.frac-f.frac||f.i-p.i);for(const{i:f}of u){if(c<=0)break;o[f]=(o[f]??0)+1,c-=1}return o}const qS=300,Iz="calc(100vw - 32px)",Lz=264,Oz=2,Fg=4;function Dz({now:e,window:t,unknown:n=!1,sessionId:s}){const o=TT(t),c=n?0:Math.min(1,e/o),[u,f]=y.useState(!1),p=y.useId(),{triggerRef:h,panelRef:x,position:g}=$f({open:u,onClose:()=>f(!1),estimatedHeight:Lz,panelWidth:qS}),v=n||c<=.8?"text-gray-400 dark:text-gray-500":c>.95?sn.danger:sn.attention,w=n?d.chat.contextUnknown:`${d.chat.contextUsage} ${Math.round(c*100)}% · ${It(e)}/${It(o)}`,S=5,C=2*Math.PI*S,N=a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14","aria-hidden":!0,className:"block shrink-0",children:[a.jsx("circle",{cx:"7",cy:"7",r:S,fill:"none",stroke:"currentColor",strokeOpacity:"0.25",strokeWidth:"2"}),a.jsx("circle",{cx:"7",cy:"7",r:S,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeDasharray:`${C*c} ${C}`,transform:"rotate(-90 7 7)"})]}),T=`flex h-8 w-8 shrink-0 items-center justify-center ${v}`;return s===void 0?a.jsx("span",{title:w,"aria-label":w,role:"img",className:T,children:N}):a.jsxs(a.Fragment,{children:[a.jsx("button",{ref:h,type:"button",title:w,"aria-label":w,"aria-expanded":u,"aria-controls":p,onClick:()=>f(_=>!_),className:`${T} rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`,children:N}),u&&g&&ss.createPortal(a.jsx("div",{ref:x,id:p,role:"group","aria-label":d.chat.contextComposition,style:{position:"fixed",top:g.topPx,bottom:g.bottomPx,left:g.left,width:qS,maxWidth:Iz},className:"anim-pop z-[60] rounded-md border border-gray-200 bg-white p-2.5 text-xs shadow-lg dark:border-gray-700 dark:bg-gray-900",children:a.jsx($z,{sessionId:s,now:e,max:o,pct:c,unknown:n})}),document.body)]})}function $z({sessionId:e,now:t,max:n,pct:s,unknown:o}){const[c,u]=y.useState({status:"loading"}),[f,p]=y.useState(null);y.useEffect(()=>{let S=!1;return u({status:"loading"}),pA(e).then(C=>{S||u({status:"ready",data:C})},()=>{S||u({status:"failed"})}),()=>{S=!0}},[e]);const h=c.status==="ready"?c.data:null,x=o||h?.contextClosed===!0,g=h===null?null:Rz(h,t),v=g?.parts.some(S=>S.key===f)?f:null,w=h!==null&&h.compactionThreshold!==null&&h.compactionThreshold<n?h.compactionThreshold:null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[a.jsxs("span",{className:"flex items-baseline gap-1.5",children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:d.chat.contextUsage}),a.jsx("span",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:x?"—":Lf(s)})]}),a.jsxs("span",{className:"font-mono text-gray-500 dark:text-gray-400",children:[x?"—":It(t)," / ",It(n)]})]}),x?a.jsx("p",{className:"mt-2 leading-relaxed text-gray-400 dark:text-gray-500",children:d.chat.contextUnknownHint}):c.status==="loading"?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.common.loading}):c.status==="failed"?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.chat.contextBreakdownFailed}):g===null?a.jsx("p",{className:"mt-2 text-gray-400 dark:text-gray-500",children:d.chat.contextBreakdownEmpty}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{"aria-hidden":!0,className:"relative mt-2 h-2 bg-gray-200 dark:bg-gray-800",style:{marginBottom:Fg},children:[a.jsx("div",{className:"absolute inset-y-0 left-0 flex overflow-hidden",style:{width:`${t/n*100}%`,minWidth:t>0?Oz:0},children:g.parts.map(S=>S.tokens>0?a.jsx("span",{title:`${VS[S.key]()} ~${It(S.tokens)} · ${S.percent}%`,onMouseEnter:()=>p(S.key),onMouseLeave:()=>p(null),style:{flexGrow:S.tokens,flexBasis:0},className:`h-full transition-opacity duration-150 ${S.color} ${v!==null&&v!==S.key?"opacity-25":""}`},S.key):null)}),w!==null&&a.jsx("span",{title:d.chat.contextCompactAt(It(w)),style:{left:`${w/n*100}%`,top:-Fg,bottom:-Fg},className:"absolute border-l border-dashed border-gray-500 dark:border-gray-400"})]}),a.jsx("ul",{className:"mt-2 space-y-0.5",children:g.parts.map(S=>a.jsx(GS,{label:VS[S.key](),swatch:S.color,tokens:S.tokens,percent:S.percent,highlighted:f===S.key,onHover:C=>p(C?S.key:null)},S.key))}),g.tools.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("p",{title:d.chat.contextTopToolsHint,className:"mt-2 border-t border-gray-100 pt-1.5 text-gray-400 dark:border-gray-800 dark:text-gray-500",children:d.chat.contextTopTools}),a.jsx("ul",{className:"mt-1 space-y-0.5",children:g.tools.map(S=>a.jsx(GS,{label:S.name,mono:!0,tokens:S.tokens,percent:S.percent,highlighted:f===`tool:${S.name}`,onHover:C=>p(C?`tool:${S.name}`:null)},S.name))})]})]})]})}const VS={systemPrompt:()=>d.chat.contextPartSystemPrompt,toolDefs:()=>d.chat.contextPartToolDefs,userMessages:()=>d.chat.contextPartUserMessages,assistantMessages:()=>d.chat.contextPartAssistantMessages,toolRequests:()=>d.chat.contextPartToolRequests,toolResults:()=>d.chat.contextPartToolResults};function GS({label:e,swatch:t,tokens:n,percent:s,mono:o=!1,highlighted:c=!1,onHover:u}){return a.jsxs("li",{onMouseEnter:()=>u?.(!0),onMouseLeave:()=>u?.(!1),className:`-mx-1 flex items-center gap-1.5 rounded px-1 py-px transition-colors duration-150 ${c?"bg-gray-100 dark:bg-gray-800":""}`,children:[t!==void 0&&a.jsx("span",{"aria-hidden":!0,className:`h-2 w-2 shrink-0 rounded-[2px] ${t}`}),a.jsx("span",{title:e,className:`min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300 ${o?"font-mono":""}`,children:e}),a.jsxs("span",{className:"shrink-0 font-mono font-medium text-gray-900 dark:text-gray-100",children:["~",It(n)]}),a.jsxs("span",{className:"w-8 shrink-0 text-right font-mono text-gray-400 dark:text-gray-500",children:[s,"%"]})]})}const Uz=1024*1024;function KS(e,t){const n=t*Uz,s=[],o=[];for(const c of e)c.size>n?o.push(c):s.push(c);return{accepted:s,rejected:o}}const Pz=["always-ask","read-only","allow-all","deny-all"],WS={"allow-all":"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4m0 4h.01","deny-all":"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM5.64 5.64l12.72 12.72","read-only":"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z","always-ask":"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM9.1 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3m.07 4h.01"};function zz({value:e,onChange:t,disabled:n,direction:s="up"}){const[o,c]=y.useState(!1);return a.jsx(Qn,{open:o,setOpen:c,menuClass:"w-max",portal:{direction:s,align:"left"},button:a.jsxs("button",{type:"button","aria-label":d.chat.approvalMode,title:`${d.chat.approvalMode}:${d.chat.approvalModeNames[e]??e}`,disabled:n,onClick:()=>c(u=>!u),className:"flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:WS[e]}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:d.chat.approvalModeNames[e]??e}),a.jsx(ns,{size:Ye.caretDense})]}),children:Pz.map(u=>a.jsxs("button",{type:"button",onClick:()=>{t(u),c(!1)},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${u===e?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx("path",{d:WS[u]})}),a.jsx("span",{className:"min-w-0 flex-1 truncate whitespace-nowrap",children:d.chat.approvalModes[u]??u}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:u===e?"✓":""})]},u))})}function Bz({agents:e,currentAgentId:t,onPick:n}){const[s,o]=y.useState("");return a.jsx(Ey,{items:eP(e,s),itemKey:c=>c.agentId,isCurrent:c=>c.agentId===t,query:s,onQueryChange:o,searchPlaceholder:d.chat.agentSearchPlaceholder,emptyText:d.chat.agentsNoMatch,onPick:n,renderRow:c=>a.jsxs(a.Fragment,{children:[a.jsx(Ha,{id:c.agentId,name:_n(c),size:16,className:"shrink-0 rounded"}),a.jsx("span",{className:"shrink-0 font-mono text-gray-800 dark:text-gray-200",children:c.agentId}),c.name&&c.name!==c.agentId&&a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:c.name})]})})}function YS({panelRef:e,maxHeight:t,title:n,children:s}){return a.jsxs("div",{ref:e,style:{maxHeight:t},className:"anim-pop absolute bottom-full left-0 z-40 mb-1.5 flex w-80 max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:[a.jsx("div",{className:"border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400",children:n}),s]})}const Hz="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z";function XS({value:e,onChange:t,disabled:n,direction:s="down"}){const[o,c]=y.useState(!1),u=e===null?"…":W0(d.chat.thinkingLevelNames,e)??"—";return a.jsxs(Qn,{open:o,setOpen:c,menuClass:"w-max min-w-36",portal:{direction:s,align:"right"},button:a.jsxs("button",{type:"button",title:`${d.chat.thinkingLevel}:${u}`,"aria-label":d.chat.thinkingLevel,disabled:n||e===null,onClick:()=>c(!o),className:"flex h-8 max-w-36 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:Hz,className:"shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:u}),a.jsx(ns,{size:Ye.caretDense})]}),children:[a.jsx("div",{className:"border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400",children:d.chat.thinkingLevel}),ST.map(f=>a.jsxs("button",{type:"button",onClick:()=>{t(f),c(!1)},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${f===e?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.chat.thinkingLevelMenuName(d.chat.thinkingLevelNames[f]??f,f)}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:f===e?"✓":""})]},f))]})}const MT="penguin.steerMode";function Fz(){return localStorage.getItem(MT)==="followup"?"followup":"steer"}const qz="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6";function Vz({steerMode:e,onChangeSteerMode:t}){const n=(s,o,c)=>a.jsx("button",{type:"button",title:c,"aria-pressed":e===s,onClick:()=>t(s),className:`h-5 rounded px-1.5 text-xs transition-colors duration-150 ${e===s?"bg-gray-200 font-medium text-gray-800 dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"}`,children:o});return a.jsxs("div",{className:"flex w-full items-center gap-2 px-3 py-1 text-xs",children:[a.jsx(Oe,{d:qz,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-600 dark:text-gray-400",children:d.chat.steerModeLabel}),a.jsxs("div",{role:"group","aria-label":d.chat.steerModeLabel,className:"flex shrink-0 items-center gap-0.5",children:[n("steer",d.chat.steerModeSteer,d.chat.steerModeSteerHint),n("followup",d.chat.steerModeFollowUp,d.chat.steerModeFollowUpHint)]})]})}function Gz({skills:e,selected:t,onToggle:n,disabled:s,direction:o="up"}){const[c,u]=y.useState(!1);return a.jsx(Qn,{open:c,setOpen:u,menuClass:"w-[26rem]",portal:{direction:o,align:"left"},button:a.jsxs("button",{type:"button","aria-label":d.chat.skillsSelect,title:d.chat.skillsSelect,disabled:s,onClick:()=>u(!c),className:"flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:My,className:"shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:d.chat.skillsSelect}),t.length>0&&a.jsx("span",{className:"shrink-0 rounded-full bg-gray-200/80 px-1.5 py-px font-mono text-[10px] font-semibold text-gray-700 dark:bg-gray-700/60 dark:text-gray-200",children:t.length}),a.jsx(ns,{size:Ye.caretDense})]}),children:a.jsx(q0,{skills:e,selected:t,onToggle:n,emptyHint:d.chat.skillsEmptyHint})})}const Kz="M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM3 15l5-5 4 4 3-3 6 6";function Wz({items:e,footer:t,direction:n="up"}){const[s,o]=y.useState(!1);return a.jsxs(Qn,{open:s,setOpen:o,menuClass:"w-72",portal:{direction:n,align:"left"},button:a.jsx("button",{type:"button","aria-label":d.chat.plusMenu,title:d.chat.plusMenu,onClick:()=>o(!s),className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:"M12 5v14M5 12h14",size:15,className:"shrink-0"})}),children:[e.map(c=>a.jsxs("button",{type:"button","aria-pressed":c.active,disabled:c.disabled,onClick:()=>{o(!1),c.onSelect()},className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-gray-800 dark:disabled:hover:bg-transparent ${c.active?"font-medium text-gray-900 dark:text-gray-100":"text-gray-600 dark:text-gray-400"}`,children:[a.jsx(Oe,{d:c.icon,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"shrink-0",children:c.label}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:c.desc}),a.jsx("span",{className:"w-3 shrink-0 text-center",children:c.active?"✓":""})]},c.key)),t&&a.jsx("div",{className:"mt-1 border-t border-gray-100 pt-1 dark:border-gray-800",children:t})]})}function Yz(e){return new Promise(t=>{const n=new FileReader;n.onload=()=>t(typeof n.result=="string"?n.result:null),n.onerror=()=>t(null),n.readAsDataURL(e)})}function Xz(e){const t=e.slice(e.indexOf(",")+1).replace(/[=\s]+/g,"");return Math.floor(t.length*3/4)}function QS(e){const t=[],n=e.text.replace(/\s+/g," ").trim();return n&&t.push(n),e.images>0&&t.push(d.chat.imagesInMessage(e.images)),e.files>0&&t.push(d.chat.filesInMessage(e.files)),t.join(" · ")}const Qz="M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11";function ZS({label:e,onRecall:t,disabled:n}){return a.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[a.jsx("p",{className:"min-w-0 truncate text-xs text-gray-400 dark:text-gray-500",children:e}),t&&a.jsx("button",{type:"button","aria-label":d.chat.recallQueued,title:d.chat.recallQueuedTitle,disabled:n,onClick:t,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:Qz,size:13})})]})}function Zz(e,t,n){for(const s of t)e.push({type:"image_url",imageUrl:s});for(const s of n)e.push({type:"file",fileName:s.name,dataUrl:s.dataUrl})}function Iy({status:e,onSend:t,onSteer:n,steeringDeliveredCount:s,pendingSteering:o=[],onRecallSteering:c,onQueueFollowUp:u,queuedFollowUps:f=0,pendingFollowUps:p=[],onRecallFollowUp:h,onStop:x,onCompact:g,modelRef:v,models:w,onChangeModel:S,onSwitchModel:C,defaultModel:N,thinkingLevel:T,onChangeThinkingLevel:_,turnThinkingLevel:R,onChangeTurnThinkingLevel:D,contextWindow:z,contextNow:E,contextStale:L=!1,sessionId:F,vision:V,approvalMode:P,onChangeApprovalMode:B,modeSaving:Y,autoFocus:q,agents:K,currentAgentId:H,skills:$,initialSkills:X,onSkillsChange:le,onHandoff:ie,initialText:I,onTextChange:A,history:Q=[],initialHandoffTargetId:j,onHandoffTargetChange:U,initialPendingModelRef:ee,onPendingModelChange:re,controlRef:ke,variant:be="session"}){const{locale:ye}=Dr(),{uploadLimits:Se}=mn(),[Me,ze]=y.useState(I??""),De=y.useRef(Me);De.current=Me;const[ct,bt]=y.useState([]),[he,ne]=y.useState([]),[oe,J]=y.useState(!1),[ht,ve]=y.useState(0),[Xe,Ge]=y.useState(null),[He,Pe]=y.useState(!1),W=y.useRef(null),[me,Ue]=y.useState(!1),pe=y.useRef(null),$e=y.useRef(null),[nt,gt]=y.useState(),[Ke,dt]=y.useState(null),[pt,wt]=y.useState(null),[st,Bt]=y.useState(X??[]),[Sn,Dn]=y.useState(0),Vt=y.useRef(null),ar=y.useRef(null),[zn]=y.useState(()=>window.matchMedia("(max-width: 767px)").matches),Xt=e==="running",Cn=e==="compacting",lr=Me.trim().length>0||ct.length>0||he.length>0||Ke!==null||pt!==null||st.length>0,[Mt,Pr]=y.useState(!1),[Bn,Nr]=y.useState(""),[Tr,Te]=y.useState(!1),[Ie,ut]=y.useState(""),St=Mt?Tm(Bn):null,Nn=Tm(Ie)===null,Hn=St!==null&&St!==Ty?d.chat.goalBudgetValue(It(St)):d.chat.goalBudgetUnlimited,Dt=tP({handoffTarget:Ke!==null,pendingModel:pt!==null,canSwitchModel:C!==void 0,sessionBusy:Xt||Cn}),Rn=!Xt&&!Cn&&!oe&&(Mt?Me.trim().length>0&&he.length===0&&St!==null&&!(Tr&&Nn):lr),zr=y.useCallback(ae=>{if(ae){ut(Bn),Te(!0);return}Tm(Ie)!==null&&(Nr(Ie.trim()),Te(!1))},[Bn,Ie]),cr=y.useCallback(()=>{Te(!1),Vt.current?.focus()},[]),Js=y.useCallback(()=>{Tm(Ie)!==null&&(Nr(Ie.trim()),Te(!1),Vt.current?.focus())},[Ie]),Mr=y.useCallback(ae=>{Pr(ae),Te(!1),ut(""),ae&&(Nr(""),dt(null),U?.(null),wt(null),re?.(null),ne([]))},[U,re]),[ta,Br]=y.useState(Fz),is=ae=>{Br(ae),localStorage.setItem(MT,ae)},Hr=ta==="followup"&&u!==void 0,fn=jz({sending:oe,goalOn:Mt,canSteerChannel:n!==void 0,canQueueChannel:u!==void 0,followUpMode:Hr,stagedRoute:Dt,hasHandoffTarget:Ke!==null,hasPendingModel:pt!==null,hasText:Me.trim().length>0,hasImages:ct.length>0,hasFiles:he.length>0,hasContent:lr}),Fr=Xt&&fn==="steer",qr=Xt&&fn==="queue",pn=Fr||qr,na=fn==="queue"?d.chat.followUpSend:d.chat.steerSend,Jn=Cz(e,fn),Er=(()=>{const ae=w?.find(_e=>zt(_e,v));return ae?hu(ae):v?.modelId??"…"})(),[ur,os]=y.useState(!1),ls=y.useRef(0);y.useEffect(()=>{ur&&(!Xt||(s??0)>ls.current||o.length>0)&&os(!1)},[ur,Xt,s,o.length]);const[ra,cs]=y.useState(null),ka=ae=>{const{text:_e,dropGoal:et}=xz({recalledText:ae.text,currentText:Vt.current?.value??Me,recalledFiles:ae.files.length,goalOn:Mt});ze(_e),A?.(_e),Dn(_e.length),ae.images.length>0&&bt(qe=>[...ae.images,...qe]),ae.files.length>0&&(et&&Mr(!1),ne(qe=>[...ae.files.map(vt=>({name:vt.fileName,size:Xz(vt.dataUrl),dataUrl:vt.dataUrl})),...qe])),requestAnimationFrame(()=>{const qe=Vt.current;qe&&(qe.focus(),qe.setSelectionRange(qe.value.length,qe.value.length),qe.scrollTop=qe.scrollHeight)})},Ar=async(ae,_e)=>{if(!(ra!==null||oe)){cs(ae);try{const et=await _e(ae);et&&(os(!1),ka(et))}finally{cs(null)}}},er=y.useCallback(ae=>{const _e=V0(st,ae);Bt(_e),le?.(_e)},[st,le]),Tn=y.useCallback((ae,_e)=>{const et=yz({prompt:ae,exampleSkills:_e,installedSkills:$.map(qe=>qe.name),selectedSkills:st});ze(et.text),A?.(et.text),Dn(0),et.skills.length!==st.length&&(Bt(et.skills),le?.(et.skills)),requestAnimationFrame(()=>{const qe=Vt.current;qe&&(qe.focus(),qe.setSelectionRange(0,0),qe.scrollTop=0)})},[$,st,A,le]);y.useImperativeHandle(ke,()=>({fillExample:Tn}),[Tn]);const Vr=y.useRef(null),wa=y.useMemo(()=>{const ae=()=>{const _e=Vr.current,et=_e?cz(De.current,_e):"";ze(et),A?.(et)};return[...g?[{cmd:"/compact",desc:d.chat.compact,run:()=>{ae(),g()}}]:[],...be==="session"?[{cmd:"/goal",desc:d.chat.goalModeDesc,run:()=>{ae(),Mr(!Mt)}}]:[],...C&&w&&w.length>0?[{cmd:"/model",desc:d.chat.switchModel,run:()=>{ae(),Pe(!0)}}]:[],...ie&&K.length>0?[{cmd:"/agent",desc:d.chat.switchAgent,run:()=>{ae(),Ue(!0)}}]:[],...IP($,ye).map(_e=>({cmd:_e.cmd,desc:_e.desc,run:()=>{ae(),er(_e.name)}}))]},[g,C,w,K,A,$,ye,er,Mr,Mt]),Mn=!Xt&&!Cn&&!He&&!me?PS(Me,Sn):null;Vr.current=Mn;const Gr=Mn&&Mn.start!==Xe?wa.filter(ae=>ae.cmd.startsWith(`/${Mn.query}`)):[],En=Gr.length>0,us=Gr[Math.min(ht,Gr.length-1)];y.useEffect(()=>{if(!He&&!me)return;const ae=()=>{Pe(!1),Ue(!1),Vt.current?.focus()},_e=qe=>{const vt=He?W.current:pe.current;vt&&!vt.contains(qe.target)&&ae()},et=qe=>{qe.key==="Escape"&&!qe.isComposing&&ae()};return window.addEventListener("mousedown",_e),window.addEventListener("keydown",et),()=>{window.removeEventListener("mousedown",_e),window.removeEventListener("keydown",et)}},[He,me]);const hn=ae=>{wt(ae),re?.(ae?{provider:ae.provider,modelId:ae.modelId}:null)},Sa=ae=>{if(Pe(!1),Vt.current?.focus(),zt(ae,v)){hn(null);return}hn(ae),dt(null),U?.(null),Pr(!1)},Ts=ae=>{Ue(!1),dt(ae),U?.(ae.agentId),hn(null),Pr(!1),Vt.current?.focus()},Ga=()=>{Ke!==null&&(dt(null),U?.(null)),hn(null)};y.useEffect(()=>{if(!En&&!He&&!me)return;const ae=()=>{const _e=$e.current;if(!_e)return;let et=0;for(let vt=_e.parentElement;vt;vt=vt.parentElement)if(getComputedStyle(vt).overflowY!=="visible"){et=vt.getBoundingClientRect().top;break}const qe=_e.getBoundingClientRect().top-et-14;gt(Math.max(96,Math.min(320,Math.round(qe))))};return ae(),window.addEventListener("resize",ae),()=>window.removeEventListener("resize",ae)},[En,He,me]);const Ct=()=>{const ae=Vt.current;ae&&(ae.style.height="auto",ae.style.height=`${Math.min(ae.scrollHeight,176)}px`)};y.useLayoutEffect(Ct,[Me]),y.useEffect(()=>{const ae=ar.current;ae&&Me!==ae.recalled&&(ar.current=null)},[Me]),y.useEffect(()=>{const ae=Vt.current;if(ae&&ae.value.length>0){const _e=ae.value.length;ae.setSelectionRange(_e,_e),ae.scrollTop=ae.scrollHeight,Dn(_e)}},[]);const ds=y.useRef(!1);y.useEffect(()=>{if(!ds.current&&(ds.current=!0,$.length===0))return;const ae=st.filter(_e=>$.some(et=>et.name===_e));ae.length!==st.length&&(Bt(ae),le?.(ae))},[$,st,le]);const ja=Ke!==null||pt!==null||Mt,br=y.useRef(!1);y.useEffect(()=>{if(br.current||!j||K.length===0||(br.current=!0,ja))return;const ae=K.find(_e=>_e.agentId===j);ae&&dt(ae)},[K,j,ja]);const Ca=y.useRef(!1);y.useEffect(()=>{if(Ca.current||!ee||!w||w.length===0||(Ca.current=!0,ja||!C))return;const ae=w.find(_e=>zt(_e,ee));ae&&!zt(ae,v)&&wt(ae)},[w,ee,v,C,ja]);const de=async(ae=t)=>{const _e=Me.trim();if(Mt){J(!0);try{const tr=[{type:"text",text:jw(st,_e)}];for(const ei of ct)tr.push({type:"image_url",imageUrl:ei});await t(tr,{budget:St})&&(ze(""),bt([]),Bt([]),Mr(!1))}finally{J(!1),Vt.current?.focus()}return}if(Dt==="blocked")return;const et=Dt==="model"?pt:null,qe=_e!==""?_e:st.length>0?d.chat.skillsAutoMessage(st):et?d.chat.modelSwitchAutoMessage:_e,vt=jw(st,qe),xn=[];vt&&xn.push({type:"text",text:vt}),Zz(xn,ct,he),J(!0);try{(Ke?await ie(Ke,xn):et?await C({provider:et.provider,modelId:et.modelId},xn):await ae(xn,null))&&(ze(""),bt([]),ne([]),dt(null),wt(null),Bt([]))}finally{J(!1),Vt.current?.focus()}},Re=async()=>{if(Xt){if(qr){await de(u);return}if(!Fr)return;const ae=Me.trim(),_e=ct,et=he.map(vt=>({fileName:vt.name,dataUrl:vt.dataUrl}));J(!0);let qe="failed";try{qe=await n(ae,_e,et),qe==="queued"&&(ls.current=s??0,os(!0),ze(""),bt([]),ne([]))}finally{J(!1),Vt.current?.focus()}qe==="not_running"&&await de(u??t);return}Rn&&await de()},Qe=ae=>{ar.current=ae.nav,ze(ae.text),A?.(ae.text),Dn(ae.text.length),requestAnimationFrame(()=>{const _e=Vt.current;_e&&(_e.setSelectionRange(_e.value.length,_e.value.length),_e.scrollTop=_e.scrollHeight)})},mt=ae=>{if(En){if(ae.key==="ArrowDown"){ae.preventDefault(),ve(_e=>(_e+1)%Gr.length);return}if(ae.key==="ArrowUp"){ae.preventDefault(),ve(_e=>(_e-1+Gr.length)%Gr.length);return}if((ae.key==="Enter"&&!ae.shiftKey||ae.key==="Tab")&&!ae.nativeEvent.isComposing){ae.preventDefault(),us?.run();return}if(ae.key==="Escape"){Ge(Mn?.start??null);return}}if((ae.key==="ArrowUp"||ae.key==="ArrowDown")&&!ae.nativeEvent.isComposing){const _e=ae.currentTarget.selectionStart??0,et=ae.currentTarget.selectionEnd??_e,qe=ae.key==="ArrowUp"?wz(Me,_e)?vz(Q,ar.current,Me):null:Sz(Me,et)?kz(Q,ar.current,Me):null;if(qe){ae.preventDefault(),Qe(qe);return}}if(ae.key==="Backspace"&&(Ke!==null||pt!==null)&&ae.currentTarget.selectionStart===0&&ae.currentTarget.selectionEnd===0){ae.preventDefault(),Ga();return}ae.key==="Enter"&&!ae.shiftKey&&!ae.nativeEvent.isComposing&&(ae.preventDefault(),Re())},Et=ae=>{const _e=[];for(const vt of ae)vt.type.startsWith("image/")&&_e.push(vt);const{accepted:et,rejected:qe}=KS(_e,Se.imageMaxMb);for(const vt of qe)Be(d.chat.attachmentTooLarge(vt.name,Se.imageMaxMb));for(const vt of et){const xn=new FileReader;xn.onload=()=>{typeof xn.result=="string"&&bt(tr=>[...tr,xn.result])},xn.readAsDataURL(vt)}},Pt=ae=>{if(be!=="session")return;const _e=[];for(const et of ae.clipboardData.items)if(et.kind==="file"){const qe=et.getAsFile();qe&&_e.push(qe)}_e.length>0&&(ae.preventDefault(),Et(_e))},Wt=ae=>{ae.target.files&&Et(ae.target.files),ae.target.value=""},Ka=ae=>{if(Mt)return;const{accepted:_e,rejected:et}=KS(ae,Se.attachmentMaxMb);for(const qe of et)Be(d.chat.attachmentTooLarge(qe.name,Se.attachmentMaxMb));_e.length!==0&&Promise.all(_e.map(Yz)).then(qe=>{const vt=_e.flatMap((xn,tr)=>qe[tr]?[{name:xn.name,size:xn.size,dataUrl:qe[tr]}]:[]);vt.length>0&&ne(xn=>[...xn,...vt])})},_r=ae=>{ae.target.files&&Ka(ae.target.files),ae.target.value=""},Rr=ae=>{if(be!=="session")return;const _e=Tz(ae);_e.images.length>0&&Et(_e.images),_e.files.length>0&&(Mt?wr(d.chat.dropFilesGoalHint):Ka(_e.files))},Ir=y.useRef(null),Ui=y.useRef(null);return a.jsxs("div",{className:"relative",ref:$e,children:[be==="session"&&a.jsx(Ez,{onFiles:Rr}),En&&a.jsx("div",{style:{maxHeight:nt},className:"anim-pop absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:Gr.map((ae,_e)=>a.jsxs("button",{type:"button",ref:ae===us?et=>et?.scrollIntoView({block:"nearest"}):void 0,onMouseEnter:()=>ve(_e),onClick:()=>ae.run(),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${ae===us?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsx("span",{className:"shrink-0 font-mono text-gray-800 dark:text-gray-200",children:ae.cmd}),a.jsx("span",{title:ae.desc,className:"min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400",children:ae.desc})]},ae.cmd))}),He&&w&&a.jsx(YS,{panelRef:W,maxHeight:nt,title:d.chat.switchModelTitle,children:a.jsx(wT,{models:w,value:v,...N!==void 0?{defaultModel:N}:{},onPick:Sa})}),me&&a.jsx(YS,{panelRef:pe,maxHeight:nt,title:d.chat.switchAgentTitle,children:a.jsx(Bz,{agents:K,...H!==void 0?{currentAgentId:H}:{},onPick:Ts})}),ct.length>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:ct.map((ae,_e)=>a.jsxs("div",{className:"anim-pop relative",children:[a.jsx(Ys,{src:ae,alt:d.chat.imageAlt,className:"h-16 w-16 rounded-md border border-gray-200 object-cover dark:border-gray-700"}),a.jsx("button",{type:"button","aria-label":d.chat.removeImage,onClick:()=>bt(et=>et.filter((qe,vt)=>vt!==_e)),className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-gray-700 text-[10px] text-white transition-colors duration-150 hover:bg-gray-900",children:"×"})]},_e))}),he.length>0&&a.jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:he.map((ae,_e)=>a.jsxs("span",{title:ae.name,className:`anim-pop flex max-w-56 items-center ${Ro.tight} rounded-md border border-gray-200 bg-gray-50 py-1 pl-2 pr-1 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200`,children:[a.jsx(Oe,{d:bf,size:13,className:"shrink-0 text-gray-400 dark:text-gray-500"}),a.jsx("span",{className:"min-w-0 truncate",children:ae.name}),a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:ju(ae.size)}),a.jsx("button",{type:"button","aria-label":`${d.chat.removeFile} ${ae.name}`,onClick:()=>ne(et=>et.filter((qe,vt)=>vt!==_e)),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]},_e))}),!V&&ct.length>0&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.imagesAsPathHint}),Dt==="blocked"&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.modelSwitchBusyHint}),o.length>0?a.jsx("div",{className:"anim-fade mb-1",children:o.map((ae,_e)=>a.jsx(ZS,{label:d.chat.steerQueuedItem(QS(ae)),disabled:ra!==null||oe,...c&&ae.id?{onRecall:()=>{Ar(ae.id,c)}}:{}},ae.id??_e))}):ur&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.steerQueuedIndicator}),p.length>0?a.jsx("div",{className:"anim-fade mb-1",children:p.map(ae=>a.jsx(ZS,{label:d.chat.followUpQueuedItem(QS(ae)),disabled:ra!==null||oe,...h?{onRecall:()=>{Ar(ae.id,h)}}:{}},ae.id))}):f>0&&a.jsx("p",{className:"anim-fade mb-1 text-xs text-gray-400 dark:text-gray-500",children:d.chat.followUpQueuedChip(f)}),a.jsxs("div",{className:"@container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400",children:[(Ke!==null||pt!==null||st.length>0||Mt)&&a.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[Mt&&a.jsxs("span",{className:"anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsxs("span",{className:"flex shrink-0 items-center gap-1",title:d.chat.goalModeDesc,children:[a.jsx(Oe,{d:_u,size:13,className:"text-gray-500 dark:text-gray-400"}),a.jsx("span",{children:d.chat.goalMode})]}),a.jsx("span",{"aria-hidden":!0,className:"mx-0.5 h-4 w-px shrink-0 bg-gray-300 dark:bg-gray-600"}),a.jsx(Qn,{open:Tr,setOpen:zr,onEscape:cr,className:"min-w-0",menuClass:"bottom-full left-1/2 -ml-32 mb-2 w-64 max-w-[calc(100vw-2rem)] origin-bottom",button:a.jsxs("button",{type:"button","aria-label":Hn,"aria-expanded":Tr,onClick:()=>zr(!Tr),className:"flex h-5 min-w-0 items-center gap-1 rounded px-1.5 text-xs text-gray-600 transition-colors duration-150 hover:bg-white/80 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white",children:[a.jsx("span",{className:"truncate",children:Hn}),a.jsx(ns,{size:Ye.caretDense})]}),children:a.jsxs("div",{className:"px-3 py-2",children:[a.jsx("label",{htmlFor:"goal-budget-input",className:"block text-xs font-medium text-gray-700 dark:text-gray-200",children:d.chat.goalBudgetLabel}),a.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[a.jsx("input",{id:"goal-budget-input",autoFocus:!0,value:Ie,onChange:ae=>ut(ae.target.value),onFocus:ae=>ae.currentTarget.select(),onKeyDown:ae=>{ae.key==="Enter"&&(ae.preventDefault(),ae.stopPropagation(),Js())},placeholder:d.chat.goalBudgetPlaceholder,"aria-invalid":Nn,"aria-describedby":"goal-budget-hint",...Gu,title:Nn?d.chat.goalBudgetInvalid:d.chat.goalBudgetHint,className:`min-w-0 flex-1 rounded-md border bg-white px-2 py-1 font-mono text-sm leading-5 placeholder:text-gray-400 focus:outline-none focus:ring-2 dark:bg-gray-950 dark:placeholder:text-gray-500 ${Nn?"border-red-400 text-red-600 focus:border-red-500 focus:ring-red-400/20 dark:border-red-500 dark:text-red-400":"border-gray-300 text-gray-800 focus:border-gray-500 focus:ring-gray-400/20 dark:border-gray-700 dark:text-gray-100 dark:focus:border-gray-500"}`}),a.jsx("button",{type:"button","aria-label":d.chat.goalBudgetSave,title:d.chat.goalBudgetSave,disabled:Nn,onClick:Js,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-35 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white",children:a.jsx(qu,{size:14})})]}),a.jsx("p",{id:"goal-budget-hint",className:`mt-1.5 text-[11px] leading-4 ${Nn?"text-red-500 dark:text-red-400":"text-gray-400 dark:text-gray-500"}`,children:Nn?d.chat.goalBudgetInvalid:d.chat.goalBudgetHint})]})}),a.jsx("button",{type:"button","aria-label":d.chat.goalRemove,onClick:()=>Mr(!1),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),Ke!==null&&a.jsxs("span",{title:d.chat.handoffTargetTitle(_n(Ke)),className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsx(Ha,{id:Ke.agentId,name:_n(Ke),size:13,className:"shrink-0 rounded-sm"}),a.jsx("span",{className:"truncate",children:Ke.agentId}),a.jsx("button",{type:"button","aria-label":d.chat.handoffRemove,onClick:()=>{dt(null),U?.(null),Vt.current?.focus()},className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),pt!==null&&a.jsxs("span",{title:d.chat.modelSwitchTargetTitle(hu(pt)),className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",children:[a.jsx(jo,{provider:pt.provider,className:"h-3.5 w-3.5 shrink-0"}),a.jsx("span",{className:"truncate",children:hu(pt)}),a.jsx("button",{type:"button","aria-label":d.chat.modelSwitchRemove,onClick:()=>{hn(null),Vt.current?.focus()},className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]}),st.map(ae=>{const _e=$.find(et=>et.name===ae);return a.jsxs("span",{className:"anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-sm text-gray-800 dark:bg-gray-800 dark:text-gray-200",..._e?{title:Wl(ye,_e)}:{},children:[a.jsx(Yf,{icon:_e?.icon,size:13,className:"shrink-0 text-gray-500 dark:text-gray-400"}),a.jsx("span",{className:"truncate",children:ae}),a.jsx("button",{type:"button","aria-label":`${d.chat.skillRemove} ${ae}`,onClick:()=>er(ae),className:"shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200",children:"×"})]},ae)})]}),a.jsx("textarea",{ref:Vt,rows:2,value:Me,autoFocus:q,onChange:ae=>{const _e=ae.target.value,et=ae.target.selectionStart??_e.length;ze(_e),A?.(_e),Dn(et),ve(0),Ge(qe=>{if(qe===null)return null;const vt=PS(_e,et);return vt&&vt.start===qe?qe:null})},onSelect:ae=>Dn(ae.currentTarget.selectionStart??0),onKeyDown:mt,onPaste:Pt,placeholder:Xt&&Hr?zn?d.chat.followUpPlaceholderShort:d.chat.followUpPlaceholder:Xt&&n?zn?d.chat.steerPlaceholderShort:d.chat.steerPlaceholder:zn?d.chat.inputPlaceholderShort:d.chat.inputPlaceholder,className:"block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 text-base leading-6 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500"}),a.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs",children:[a.jsxs("div",{className:"no-scrollbar flex min-w-0 flex-1 items-center gap-2 overflow-x-auto",children:[a.jsx("input",{ref:Ir,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Wt}),a.jsx("input",{ref:Ui,type:"file",multiple:!0,disabled:Mt,className:"hidden",onChange:_r}),be==="session"&&a.jsx(Wz,{items:[{key:"image",icon:Kz,label:d.chat.uploadImage,desc:V&&!Mt?d.chat.uploadImageDesc:d.chat.imagesAsPathHint,active:ct.length>0,onSelect:()=>Ir.current?.click()},{key:"file",icon:bf,label:d.chat.uploadFile,desc:d.chat.uploadFileDesc,active:he.length>0,disabled:Mt,onSelect:()=>Ui.current?.click()},{key:"goal",icon:_u,label:d.chat.goalMode,desc:d.chat.goalModeDesc,active:Mt,disabled:Xt||Cn||oe,onSelect:()=>Mr(!Mt)}],footer:a.jsx(Vz,{steerMode:ta,onChangeSteerMode:is}),direction:w&&S?"down":"up"}),a.jsx(zz,{value:P,onChange:B,disabled:Y,direction:w&&S?"down":"up"}),a.jsx(Gz,{skills:$,selected:st,onToggle:er,disabled:Xt||Cn||oe,direction:w&&S?"down":"up"}),a.jsx("span",{title:d.chat.slashHint,className:"hidden min-w-0 truncate text-gray-300 @lg:block dark:text-gray-600",children:d.chat.slashHint})]}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[!S&&a.jsx(Dz,{now:E,unknown:L,...z!==void 0?{window:z}:{},...F!==void 0?{sessionId:F}:{}}),w&&S&&_&&a.jsx(XS,{value:T??null,onChange:_,disabled:oe}),!S&&D&&a.jsx(XS,{value:R??"",onChange:D,disabled:oe,direction:"up"}),w&&S?a.jsx(Ay,{models:w,value:v,...N!==void 0?{defaultModel:N}:{},onChange:S,disabled:oe}):be==="subagent"?a.jsxs("span",{title:v?.modelId??"",className:"flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 rounded-md px-1 text-gray-400 dark:text-gray-500",children:[a.jsx(jo,{provider:v?.provider??"custom",className:"h-4 w-4 shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:Er})]}):a.jsxs("button",{type:"button",title:v?.modelId??"","aria-label":`${d.chat.model} ${v?.modelId??""}`,onClick:()=>wr(d.chat.modelLockedHint),className:"flex h-8 min-w-0 max-w-44 shrink cursor-pointer items-center gap-1.5 rounded-md px-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300",children:[a.jsx(jo,{provider:v?.provider??"custom",className:"h-4 w-4 shrink-0"}),a.jsx("span",{className:"hidden min-w-0 truncate @md:block",children:Er})]}),a.jsx("button",{type:"button",title:Jn?d.chat.stop:Xt?na:d.chat.send,"aria-label":Jn?d.chat.stop:Xt?na:d.chat.send,disabled:Jn?!1:Xt?!pn:!Rn,onClick:()=>Jn?void x():void Re(),className:Jn?"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 transition-colors duration-150 hover:bg-red-100 dark:bg-red-950/60 dark:text-red-400 dark:hover:bg-red-950":"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300 dark:disabled:bg-gray-800 dark:disabled:text-gray-600",children:Jn?a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14","aria-hidden":!0,className:"block",children:a.jsx("rect",{x:"2",y:"2",width:"10",height:"10",rx:"2",fill:"currentColor"})}):a.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"block",children:a.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})})})]})]})]})]})}const JS=500,Jz=5;function eB(e,t){return e+t+1}function X0(e,t){return e+t>=Jz}const ET=20,tB=20;function nB(e,t,n=ET,s=tB){const o=n+1+s;if(e<=o)return{start:0,end:e};if(t===null||t<0||t>=e)return{start:e-o,end:e};const c=Math.min(Math.max(0,t-n),e-o);return{start:c,end:c+o}}const rB=12,AT=5,_T=48;function aB(e,t){return Math.max(AT,Math.min(rB,Math.floor((e-_T)/Math.max(1,t))))}function sB(e){const t=Math.floor((e-_T)/AT);return Math.min(ET,Math.max(0,Math.floor((t-1)/2)))}function iB(e){const t=[];let n=null,s=!1;for(const o of e){if(o.kind==="user_text"||o.kind==="user_image"){let c="";if(o.kind==="user_text"){const u=CT(o.text);if(!u||u.goalRound!==void 0&&u.goalRound>1){s=!1;continue}c=u.body}s&&n?n.question===""&&c!==""&&(n.question=c):(n={anchorId:o.id,question:c,answer:""},t.push(n)),s=!0;continue}if(s=!1,o.kind==="assistant_text"&&n&&n.answer.length<JS){const c=o.text.trim();c!==""&&(n.answer=(n.answer===""?c:`${n.answer} ${c}`).slice(0,JS))}}return t}function oB(e,t){let n=e.replace(/```[^\n]*/g,"").replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^[ \t]*(?:#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d+[.)][ \t]+)/gm,"").replace(/[*_`~]/g,"").replace(/\s+/g," ").trim();return n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}const lB="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm4 0v16M12 9h5m-5 4h5",cB=96,uB=1e3,dB=56,mB=48,e2="(hover: hover) and (pointer: fine)";function fB(e,t){const[n,s]=y.useState(()=>window.matchMedia(e2).matches),[o,c]=y.useState({gutterOk:!1,height:0});return y.useEffect(()=>{const u=window.matchMedia(e2),f=p=>s(p.matches);return u.addEventListener("change",f),()=>u.removeEventListener("change",f)},[]),y.useEffect(()=>{const u=e.current;if(!u)return;const f=()=>{const h=parseFloat(getComputedStyle(document.documentElement).fontSize)||16,x=(u.clientWidth-mB*h)/2;c({gutterOk:x>=dB,height:u.clientHeight})};f();const p=new ResizeObserver(f);return p.observe(u),()=>p.disconnect()},[e,t]),{shown:n&&o.gutterOk,height:o.height}}function RT(e,t){const n=e.querySelectorAll("[data-outline-anchor]");if(n.length===0)return null;let s=null,o=null;const c=e.scrollTop+cB;for(const f of n){const p=Number(f.dataset.outlineAnchor);t.has(p)&&(s=p,f.offsetTop<=c&&(o=p))}return e.scrollHeight-e.scrollTop-e.clientHeight<2?s:o}let t2=null,n2;function IT(e,t){const n=e?.querySelector(`[data-outline-anchor="${t}"]`);!e||!n||(e.scrollTo({top:Math.max(0,n.offsetTop-8)}),window.clearTimeout(n2),t2?.classList.remove("outline-flash"),t2=n,n.classList.remove("outline-flash"),n.offsetWidth,n.classList.add("outline-flash"),n2=window.setTimeout(()=>n.classList.remove("outline-flash"),uB))}function r2({edge:e}){return a.jsx("div",{"data-outline-overflow":e,"aria-hidden":!0,className:`flex w-10 flex-col items-start gap-[3px] pl-4 ${e==="above"?"pb-1.5":"pt-1.5"}`,children:[0,1,2].map(t=>a.jsx("span",{className:"h-[2px] w-[2px] rounded-full bg-gray-300 dark:bg-gray-700"},t))})}function LT(e,t,n,s){return e.answer?oB(e.answer,s):n&&e===t[t.length-1]?d.chat.outlineAnswering:""}function pB({entries:e,turnOffset:t=0,version:n,scrollRef:s,running:o,fit:c}){const[u,f]=y.useState(null),[p,h]=y.useState(null),x=y.useRef(null);if(y.useEffect(()=>{const R=s.current;if(!c.shown||!R||!X0(t,e.length))return;const D=new Set(e.map(F=>F.anchorId));let z=null;const E=()=>{z=null;const F=s.current;F&&f(RT(F,D))},L=()=>{z??=requestAnimationFrame(E)};return E(),R.addEventListener("scroll",L,{passive:!0}),()=>{R.removeEventListener("scroll",L),z!==null&&cancelAnimationFrame(z)}},[c.shown,s,e.length,t,n]),!c.shown||!X0(t,e.length))return null;const g=R=>{const D=R.currentTarget.getBoundingClientRect();return D.top+D.height/2-(x.current?.getBoundingClientRect().top??0)},v=sB(c.height),{start:w,end:S}=nB(e.length,e.findIndex(R=>R.anchorId===u),v,v),C=e.slice(w,S),N=aB(c.height,C.length),T=p===null?null:C.find(R=>R.anchorId===p.id)??null,_=T===null?"":LT(T,e,o,160);return a.jsxs("nav",{ref:x,"aria-label":d.chat.outlineTitle,className:"pointer-events-none absolute inset-y-0 left-0 z-10 flex flex-col items-start justify-center",children:[a.jsxs("div",{className:"max-h-full overflow-hidden",children:[(w>0||t>0)&&a.jsx(r2,{edge:"above"}),C.map((R,D)=>{const z=R.anchorId===u;return a.jsx("button",{type:"button","data-outline-tick":R.anchorId,"aria-current":z||void 0,"aria-label":d.chat.outlineTickLabel(eB(t,w+D),R.question||d.chat.outlineNoText),style:{height:N},onMouseEnter:E=>h({id:R.anchorId,top:g(E)}),onMouseLeave:()=>h(null),onFocus:E=>h({id:R.anchorId,top:g(E)}),onBlur:()=>h(null),onClick:()=>{IT(s.current,R.anchorId),f(R.anchorId)},className:"group/tick pointer-events-auto flex w-10 items-center pl-2.5",children:a.jsx("span",{className:`h-[2px] rounded-full transition-all duration-150 ${z?"w-5 bg-gray-800 dark:bg-gray-200":"w-3.5 bg-gray-300 group-hover/tick:bg-gray-500 dark:bg-gray-700 dark:group-hover/tick:bg-gray-400"}`})},R.anchorId)}),S<e.length&&a.jsx(r2,{edge:"below"})]}),T&&a.jsxs("div",{"data-outline-card":!0,"aria-hidden":!0,className:"anim-pop pointer-events-none absolute left-10 w-80 -translate-y-1/2 rounded-xl border border-gray-200 bg-white px-4 py-3 shadow-lg dark:border-gray-700 dark:bg-gray-900",style:{top:Math.min(Math.max(p.top,56),Math.max(56,c.height-56))},children:[a.jsx("p",{className:`truncate text-sm ${T.question===""?"italic text-gray-500 dark:text-gray-400":"font-semibold text-gray-900 dark:text-gray-100"}`,children:T.question||d.chat.outlineNoText}),_!==""&&a.jsx("p",{className:`mt-1 line-clamp-3 text-sm leading-snug text-gray-500 dark:text-gray-400 ${T.answer===""?"animate-pulse":""}`,children:_})]})]})}function hB({entries:e,turnOffset:t=0,scrollRef:n,running:s}){const[o,c]=y.useState(!1),[u,f]=y.useState(null);if(!X0(t,e.length))return null;const p=h=>{h&&n.current&&f(RT(n.current,new Set(e.map(x=>x.anchorId)))),c(h)};return a.jsx(Qn,{open:o,setOpen:p,menuClass:"right-0 top-full mt-1 w-72 max-w-[calc(100vw-1.5rem)] origin-top-right",button:a.jsx("button",{type:"button",title:d.chat.outlineTitle,"aria-label":d.chat.outlineTitle,onClick:()=>p(!o),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:lB,size:15})}),children:a.jsx("div",{className:"max-h-[60vh] overflow-y-auto py-1",children:e.map(h=>{const x=LT(h,e,s,80),g=h.anchorId===u;return a.jsxs("button",{type:"button","data-outline-menu-entry":h.anchorId,"aria-current":g||void 0,onClick:()=>{IT(n.current,h.anchorId),c(!1)},className:`block w-full px-3 py-1.5 text-left transition-colors duration-150 ${g?"bg-gray-100 dark:bg-gray-800":"hover:bg-gray-50 dark:hover:bg-gray-800/60"}`,children:[a.jsx("span",{className:`block truncate text-sm ${h.question===""?"italic text-gray-500 dark:text-gray-400":"font-medium text-gray-800 dark:text-gray-200"}`,children:h.question||d.chat.outlineNoText}),x!==""&&a.jsx("span",{className:`mt-0.5 block truncate text-xs text-gray-500 dark:text-gray-400 ${h.answer===""?"animate-pulse":""}`,children:x})]},h.anchorId)})})})}function OT({className:e}){return a.jsx("img",{src:"/penguin-logo.svg",alt:"","aria-hidden":!0,draggable:!1,className:`select-none ${e??"h-9 w-9 rounded-lg"}`})}const Ly="penguin.dock.layout",a2=40,DT=["agents","workspace","memory","trace","messaging"];function kn(e){return e.kind==="panel"?e.panel:`terminal:${e.terminalId}`}function gB(e){return DT.includes(e)?{kind:"panel",panel:e}:e.startsWith("terminal:")&&e.length>9?{kind:"terminal",terminalId:e.slice(9)}:null}const $T=.4,xB=.15,Oy=.85,UT=140;function PT(e){return Number.isFinite(e)?Math.min(Oy,Math.max(xB,e)):$T}function s2(){return{tabs:[],active:null,open:!1}}function Dy(){return{right:s2(),bottom:s2(),focus:"bottom"}}const Q0="~none";function yB(e,t){try{const n=localStorage.getItem(e);if(n===null)return t;const s=JSON.parse(n);return typeof s=="object"&&s!==null?s:t}catch{return t}}function zT(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch{}}function i2(e){const t=e??{},n=(Array.isArray(t.tabs)?t.tabs:[]).map(u=>typeof u=="string"?gB(u):null).filter(u=>u!==null),s=new Set,o=n.filter(u=>{const f=kn(u);return s.has(f)?!1:(s.add(f),!0)}),c=typeof t.active=="string"&&o.some(u=>kn(u)===t.active)?t.active:o.length>0?kn(o[o.length-1]):null;return{tabs:o,active:c,open:t.open===!0}}function bB(e){const t=e??{},n=i2(t.right),s=i2(t.bottom),o=new Set(n.tabs.map(kn));return s.tabs=s.tabs.filter(c=>!o.has(kn(c))),s.active!==null&&!s.tabs.some(c=>kn(c)===s.active)&&(s.active=s.tabs.length>0?kn(s.tabs[s.tabs.length-1]):null),{right:n,bottom:s,focus:t.focus==="right"?"right":"bottom"}}function vB(){const e=yB(Ly,{}),t={};if(typeof e.scopes=="object"&&e.scopes!==null)for(const[n,s]of Object.entries(e.scopes))t[n]=bB(s);return{scopes:t,bottomRatio:PT(typeof e.bottomRatio=="number"?e.bottomRatio:NaN)}}let{scopes:Wn,bottomRatio:Dl}=vB(),za=Q0,Jt=Wn[za]??Dy();function kB(e){return e.right.tabs.length===0&&e.bottom.tabs.length===0&&!e.right.open&&!e.bottom.open}function Ur(){if(kB(Jt)){const{[za]:t,...n}=Wn;Wn=n}else{const{[za]:t,...n}=Wn;Wn={...n,[za]:Jt}}const e=Object.keys(Wn);e.length>a2&&(Wn=Object.fromEntries(e.slice(e.length-a2).map(t=>[t,Wn[t]]))),zT(Ly,{scopes:Object.fromEntries(Object.entries(Wn).map(([t,n])=>[t,{right:{...n.right,tabs:n.right.tabs.map(kn)},bottom:{...n.bottom,tabs:n.bottom.tabs.map(kn)},focus:n.focus}])),bottomRatio:Dl})}const Z0=new Set;let BT=0,Qf=0;function Cr(){BT+=1;for(const e of[...Z0])e()}function $y(){return BT}function wB(){return Qf}function Zf(e){return Z0.add(e),()=>Z0.delete(e)}function SB(e){FT(e??Q0,za===Q0)}function HT(e){FT(e,!0)}function FT(e,t){if(e===za)return;Qf+=1,Ur();const n=Wn[za];if(t&&n!==void 0&&Wn[e]===void 0){const{[za]:o,...c}=Wn;Wn={...c,[e]:n},zT(Ly,{scopes:Object.fromEntries(Object.entries(Wn).map(([u,f])=>[u,{right:{...f.right,tabs:f.right.tabs.map(kn)},bottom:{...f.bottom,tabs:f.bottom.tabs.map(kn)},focus:f.focus}])),bottomRatio:Dl})}za=e,Jt=Wn[za]??Dy(),Cr()}function jB(){return za}let Iu=!1;if(typeof window<"u"&&typeof window.matchMedia=="function"){const e=window.matchMedia("(max-width: 1023.98px)");Iu=e.matches,e.addEventListener("change",t=>{Iu=t.matches,Cr()})}function or(e){return Jt[e]}function td(e){for(const t of["right","bottom"]){const n=Jt[t].tabs.findIndex(s=>kn(s)===e);if(n!==-1)return{position:t,index:n}}return null}function Lu(e){return td(e)?.position??null}function Ba(e){return or(e).open}function CB(e){return or(e).active}function Uy(){const e=Jt.focus,t=e==="right"?"bottom":"right";return Ba(e)&&or(e).active!==null?or(e).active:Ba(t)?or(t).active:null}function NB(){return Iu?!Ba("right")&&!Ba("bottom")?[]:[{position:"bottom",merged:!0,tabs:[...Ba("bottom")?Jt.bottom.tabs:[],...Ba("right")?Jt.right.tabs:[]],activeKey:Uy()}]:["right","bottom"].filter(Ba).map(t=>({position:t,merged:!1,tabs:or(t).tabs,activeKey:or(t).active}))}function TB(e){const t=Lu(e);return t===null||!Ba(t)?!1:Iu?Uy()===e:or(t).active===e}function Py(e,t){const n=or(e);n.active=t,n.open=!0,Jt.focus=e}function qg(e){const t=td(e);t&&(Py(t.position,e),Ur(),Cr())}function zy(e,t){const n=kn(e),s=td(n);if(s&&s.position!==t&&(Jt[s.position].tabs=Jt[s.position].tabs.filter(o=>kn(o)!==n),Jt[s.position].active===n)){const o=Jt[s.position].tabs;Jt[s.position].active=o.length>0?kn(o[o.length-1]):null}(!s||s.position!==t)&&(Jt[t].tabs=[...Jt[t].tabs,e]),Py(t,n)}function J0(e){const t=td(e);if(!t)return;const n=or(t.position);n.tabs=n.tabs.filter(s=>kn(s)!==e),n.active===e&&(n.active=n.tabs.length>0?kn(n.tabs[n.tabs.length-1]):null),n.tabs.length===0&&(n.open=!1),Ur(),Cr()}function MB(e,t){const n=td(e);if(!n)return;Qf+=1;const s=Jt[n.position].tabs[n.index];zy(s,t),Jt[n.position].tabs.length===0&&(Jt[n.position].open=!1),Ur(),Cr()}function o2(e,t){if(e===t)return;const n=or(e);if(n.tabs.length===0)return;Qf+=1;const s=n.active,o=or(t);o.tabs=[...o.tabs,...n.tabs],n.tabs=[],n.active=null,n.open=!1,s!==null?Py(t,s):Jt.focus=t,o.open=!0,Ur(),Cr()}function EB(e,t){const n=or(e),s=new Map(n.tabs.map(c=>[kn(c),c])),o=t.map(c=>s.get(c)).filter(c=>c!==void 0);o.length===n.tabs.length&&(o.every((c,u)=>c===n.tabs[u])||(n.tabs=o,Ur(),Cr()))}function AB(e){const t=or(e);t.open=!t.open,t.open&&(Jt.focus=e),Ur(),Cr()}function _B(e){e.merged?(Jt.right.open=!1,Jt.bottom.open=!1):or(e.position).open=!1,Ur(),Cr()}function vl(e){return Lu(e)}function ho(e,t){const n=t??vl(e)??"right";zy({kind:"panel",panel:e},n),Ur(),Cr()}function qT(e){return`terminal:${e}`}function RB(e){return Lu(qT(e))}function IB(){return[...Jt.bottom.tabs,...Jt.right.tabs].filter(e=>e.kind==="terminal").map(e=>e.terminalId)}function By(e){const t=new Set;for(const n of[Jt,...Object.values(Wn)])for(const s of[...n.right.tabs,...n.bottom.tabs])s.kind==="terminal"&&t.add(s.terminalId);return e.filter(n=>!t.has(n))}function nd(e,t){zy({kind:"terminal",terminalId:e},t??RB(e)??"bottom"),Ur(),Cr()}function LB(e){nd(e)}function OB(e,t,n){if(By([t]).length===0)return;if(e===za){nd(t,n);return}const s=Wn[e]??Dy(),o=s[n];o.tabs=[...o.tabs,{kind:"terminal",terminalId:t}],o.active=qT(t),o.open=!0;const{[e]:c,...u}=Wn;Wn={...u,[e]:s},Ur(),Cr()}function DB(e){let t=!1;const n=s=>{const o=s.tabs.filter(c=>c.kind!=="terminal"||e.has(c.terminalId));return o.length===s.tabs.length?!1:(s.tabs=o,s.active!==null&&!o.some(c=>kn(c)===s.active)&&(s.active=o.length>0?kn(o[o.length-1]):null),o.length===0&&(s.open=!1),!0)};for(const s of Object.values(Wn))s!==Jt&&(n(s.right)&&(t=!0),n(s.bottom)&&(t=!0));n(Jt.right)&&(t=!0),n(Jt.bottom)&&(t=!0),t&&(Ur(),Cr())}function $B(){const e=IB();if(e.length===0)return!1;const t=["right","bottom"].filter(s=>or(s).tabs.some(o=>o.kind==="terminal"));if(t.some(s=>Ba(s)&&(Iu?Uy()?.startsWith("terminal:")===!0:or(s).active?.startsWith("terminal:")===!0))){for(const s of t)or(s).open=!1;return Ur(),Cr(),!0}return LB(e[e.length-1]),!0}function VT(){return Dl}function UB(e){const t=PT(e);t!==Dl&&(Dl=t,Ur(),Cr())}function PB(){Dl=$T,Ur(),Cr()}const ou={Output:1,Input:2,Resize:3,Restore:5,Exit:6},zB=new TextEncoder,BB=new TextDecoder;function GT(e,t=""){const n=typeof t=="string"?zB.encode(t):t,s=new Uint8Array(2+n.byteLength);return s[0]=e,s[1]=0,s.set(n,2),s}function HB(e){if(e.byteLength<2)return null;const t=new Uint8Array(e,0,2);return{opcode:t[0],slot:t[1],text:BB.decode(new Uint8Array(e,2))}}function l2(e,t,n){return GT(ou.Resize,JSON.stringify({cols:e,rows:t,intent:n}))}function FB(){return Promise.all([an(()=>import("./xterm-fEUfDV0F.js").then(e=>e.x),[]),an(()=>import("./addon-fit-BXTX0Xqu.js").then(e=>e.a),[]),an(()=>import("./addon-web-links-KebkunbU.js").then(e=>e.a),[])])}const qB={background:"#000000",foreground:"#f3f4f6",cursor:"#f3f4f6",cursorAccent:"#000000",selectionBackground:"rgba(255, 255, 255, 0.18)",black:"#000000",red:"#cd3131",green:"#0dbc79",yellow:"#e5e510",blue:"#2472c8",magenta:"#bc3fbc",cyan:"#11a8cd",white:"#e5e5e5",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"},VB={background:"#ffffff",foreground:"#111827",cursor:"#111827",cursorAccent:"#ffffff",selectionBackground:"rgba(0, 0, 0, 0.12)",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"};function c2(e){return e?qB:VB}async function KT(e,t){return fetch(e,{credentials:"same-origin",...t,headers:{"Content-Type":"application/json",...t?.headers??{}}})}class Hy extends Error{constructor(t,n){super(n),this.status=t,this.name="HttpStatusError"}status}function WT(e,t,n,s){const o=t?.method??"GET",c=s.trim()===""?n.statusText:s.trim();return new Hy(n.status,`${o} ${e} → ${n.status} ${c}`)}async function Fy(e,t){const n=await KT(e,t);if(!n.ok)throw WT(e,t,n,await n.text());return await n.json()}async function vf(e,t){const n=await KT(e,t);if(n.status===404)return null;if(!n.ok)throw WT(e,t,n,await n.text());return await n.json()}function GB(e,t,n){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}/api/terminals/${e}/stream?cols=${t}&rows=${n}`}function YT({ensure:e,onStatus:t,onInfo:n,onTitle:s,className:o}){const c=y.useRef(null),{terminalDark:u}=as(),f=y.useRef(u);f.current=u;const p=y.useRef(null);y.useEffect(()=>{p.current&&(p.current.options.theme=c2(u))},[u]);const h=y.useRef({ensure:e,onStatus:t,onInfo:n,onTitle:s});return h.current={ensure:e,onStatus:t,onInfo:n,onTitle:s},y.useEffect(()=>{const x=c.current;if(!x)return;let g=!1,v=null;const w=setTimeout(()=>{g||S(x).then(C=>{g?C():v=C})},0);return()=>{g=!0,clearTimeout(w),v?.()};async function S(C){const[{Terminal:N},{FitAddon:T},{WebLinksAddon:_}]=await FB();let R=!1,D=null,z=!1;const E=(H,$="")=>{R||h.current.onStatus?.(H,$)},L=new N({allowProposedApi:!0,cursorBlink:!0,fontFamily:'"JetBrains Mono", "Fira Code", Menlo, Monaco, "DejaVu Sans Mono", Consolas, monospace',fontSize:13,lineHeight:1.2,scrollback:5e3,theme:c2(f.current)}),F=new T;L.loadAddon(F),L.loadAddon(new _),p.current=L,L.open(C),F.fit();const V=()=>{const H=L.getSelection();H&&(navigator.clipboard?.writeText(H).catch(()=>{}),L.clearSelection())},P=()=>{navigator.clipboard?.readText().then(H=>H&&L.paste(H)).catch(()=>{})};L.attachCustomKeyEventHandler(H=>{if(H.type!=="keydown")return!0;const $=H.key.toLowerCase();return H.ctrlKey&&H.shiftKey&&$==="c"||H.ctrlKey&&!H.shiftKey&&H.key==="Insert"||H.ctrlKey&&!H.shiftKey&&!H.altKey&&$==="c"&&L.hasSelection()?(V(),!1):!(H.ctrlKey&&!H.altKey&&$==="v"||!H.ctrlKey&&H.shiftKey&&H.key==="Insert")});const B=new AbortController,{signal:Y}=B,q=()=>L.modes.mouseTrackingMode!=="none";C.addEventListener("contextmenu",H=>{H.preventDefault(),!q()&&(L.hasSelection()?V():P())},{signal:Y}),C.addEventListener("mousedown",H=>{H.button===1&&!q()&&(H.preventDefault(),P())},{signal:Y}),C.addEventListener("mouseup",()=>L.focus(),{signal:Y}),C.addEventListener("focusin",()=>{D?.readyState===WebSocket.OPEN&&D.send(l2(L.cols,L.rows,"claim"))},{signal:Y}),L.onData(H=>{D?.readyState===WebSocket.OPEN&&D.send(GT(ou.Input,H))}),L.onTitleChange(H=>{R||h.current.onTitle?.(H)}),(async()=>{try{const H=await h.current.ensure(L.cols,L.rows);if(R)return;h.current.onInfo?.(H),D=new WebSocket(GB(H.id,L.cols,L.rows)),D.binaryType="arraybuffer",D.onopen=()=>E("ready"),D.onmessage=$=>{if(!($.data instanceof ArrayBuffer))return;const X=HB($.data);if(X)switch(X.opcode){case ou.Restore:case ou.Output:L.write(X.text);break;case ou.Exit:{const{exitCode:le}=JSON.parse(X.text);z=!0,E("exited",String(le));break}default:break}},D.onerror=()=>E("error","stream error"),D.onclose=()=>{z||E("error","stream closed")}}catch(H){E("error",H instanceof Error?H.message:String(H))}})();const K=new ResizeObserver(()=>{R||(F.fit(),D?.readyState===WebSocket.OPEN&&D.send(l2(L.cols,L.rows,"update")))});return K.observe(C),L.focus(),()=>{R=!0,p.current=null,B.abort(),K.disconnect(),D?.close(),L.dispose()}}},[]),a.jsx("div",{ref:c,className:o??"min-h-0 flex-1 overflow-hidden"})}function KB(e){return(e??"").trim().replace(/^[^@\s]+@[^:\s]+:?\s*/,"").trim()}const WB=3e4;let $l=[],XT=[],u2="",Xc=null;const kl=new Set;let Em=null,Zm=!1;const Ou=new Map;function YB(e){const t=Ou.get(e);return t===void 0?!1:Date.now()>t?(Ou.delete(e),!1):!0}function Jf(e){$l=e;const t=JSON.stringify(e);if(t!==u2){XT=e,u2=t;for(const n of[...kl])n()}}function XB(e,t){$l.some(n=>n.id===e&&(n.title??"")!==t)&&Jf($l.map(n=>n.id===e?{...n,title:t}:n))}function QT(){return XT}function d2(){return!Zm}function Xs(){return Xc||(Xc=(async()=>{try{const e=await fetch("/api/terminals",{credentials:"same-origin"});if(e.status===404&&!Zm){Zm=!0;for(const o of[...kl])o();return}if(!e.ok)return;Zm=!1;const t=await e.json(),n=new Set(t.terminals.map(o=>o.id));for(const o of Ou.keys())n.has(o)||Ou.delete(o);const s=t.terminals.filter(o=>o.alive&&!YB(o.id));DB(new Set(s.map(o=>o.id))),Jf(s)}catch{}finally{Xc=null}})(),Xc)}const m2=()=>{Xs()};function ZT(e){return kl.size===0&&(Xs(),Em=setInterval(()=>{Xs()},WB),window.addEventListener("focus",m2)),kl.add(e),()=>{kl.delete(e),kl.size===0&&Em!==null&&(clearInterval(Em),Em=null,window.removeEventListener("focus",m2))}}function QB(e){$l.some(t=>t.id===e.id)||Jf([...$l,e])}async function ZB(e){Ou.set(e,Date.now()+1e4),Jf($l.filter(t=>t.id!==e));try{await fetch(`/api/terminals/${encodeURIComponent(e)}`,{method:"DELETE",credentials:"same-origin"})}catch{}for(const t of[300,1500])setTimeout(()=>{Xs()},t)}const Vg="~";let ex=null;function JT(e){ex=e!==null&&e.trim()!==""?e:null}function JB(e){return e instanceof Hy&&e.status===400&&e.message.includes("cwd_not_")}async function eM(e){const t=n=>Fy("/api/terminals",{method:"POST",body:JSON.stringify({cwd:n})});try{let n;try{n=await t(ex??Vg)}catch(s){if(ex===null||!JB(s))throw s;console.warn(`[terminal] Workspace unusable as cwd, opening in ${Vg}:`,s),n=await t(Vg)}QB(n),nd(n.id,e)}catch(n){const s=n instanceof Error?n.message:String(n),o=n instanceof Hy&&n.status===404?`${s} — ${d.terminal.noTerminalApi}`:s;console.error("[terminal] create failed:",o),Be(`${d.terminal.createFailed}: ${o}`)}finally{Xs()}}async function tM(e){const n=((await Fy("/api/terminals").catch(()=>null))?.terminals??QT()).filter(o=>o.alive),s=By(n.map(o=>o.id)).at(-1);if(s!==void 0){nd(s,e),Xs();return}await eM(e)}function eH(e,t){const n=jB(),s=window.open(`/terminal?id=${encodeURIComponent(e)}`,"_blank");if(J0(`terminal:${e}`),!s)return;const o=window.setInterval(()=>{s.closed&&(window.clearInterval(o),(async()=>(await vf(`/api/terminals/${encodeURIComponent(e)}`).catch(()=>null))?.alive===!0&&(OB(n,e,t),Xs()))())},600)}function tH(){$B()||tM()}typeof window<"u"&&window.addEventListener("keydown",e=>{!e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.key!=="`"&&e.code!=="Backquote"||(e.preventDefault(),tH())});const tx=[{id:"webapps",tasks:[{id:"game",skills:["web-design"]},{id:"gamecenter",skills:["web-design"]},{id:"lol",skills:["web-design"]},{id:"rhythmRunner",skills:["web-design"]}]},{id:"agents",tasks:[{id:"investmentCopilot",skills:["penguin-sdk","web-design"]},{id:"rag",skills:["penguin-sdk","web-design"]},{id:"agentBenchmarkBuild",skills:[]},{id:"agentOptimization",skills:[]}]},{id:"schedules",tasks:[{id:"dailyPlan",skills:[]},{id:"githubDigest",skills:[]},{id:"memoryReview",skills:[]}]}];tx.flatMap(e=>[...e.tasks]);function nM({open:e,glyph:t,label:n,count:s,onOpen:o}){return a.jsxs("button",{type:"button","aria-expanded":e,onClick:o,className:`flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left transition-colors duration-150 ${e?"bg-gray-100 dark:bg-gray-800/70":"hover:bg-gray-100 dark:hover:bg-gray-800/70"}`,children:[a.jsx("span",{className:"shrink-0 text-brand-500 dark:text-brand-400",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a.jsx("path",{d:t})})}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-gray-700 dark:text-gray-300",children:n}),a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:s}),a.jsx(Zn,{open:e,size:Ye.chevron,className:"text-gray-400"})]})}const nx="rounded-md px-2 py-1.5 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 disabled:cursor-default disabled:opacity-60 disabled:hover:bg-transparent dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200",qy=3,Nl=40,gu=4e3;function nH(){return`sc-${crypto.randomUUID().replace(/-/g,"").slice(0,12)}`}function Gg(e,t){if(typeof e!="string")return null;const n=e.trim();return n===""?null:n.slice(0,t)}function rH(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const s of e){if(t.length>=qy)break;if(s===null||typeof s!="object"||Array.isArray(s))continue;const o=s,c=Gg(o.id,64),u=Gg(o.title,Nl),f=Gg(o.prompt,gu);c===null||u===null||f===null||n.has(c)||(n.add(c),t.push({id:c,title:u,prompt:f}))}return t}function f2(e){const t=e.title.trim(),n=e.prompt.trim();return t===""?"titleRequired":t.length>Nl?"titleTooLong":n===""?"promptRequired":n.length>gu?"promptTooLong":null}function rM(e){return e.length<qy}function aH(e,t){const n={id:t.id??nH(),title:t.title.trim(),prompt:t.prompt.trim()},s=e.findIndex(o=>o.id===n.id);return s!==-1?e.map((o,c)=>c===s?n:o):rM(e)?[...e,n]:[...e]}function sH(e,t){return e.filter(n=>n.id!==t)}function iH(e){const t=e.split(`
|
|
174
174
|
`).find(n=>n.trim()!=="");return t===void 0?"":t.trim().replace(/\s+/g," ").slice(0,Nl)}const p2="shortcuts",oH="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z";function h2({label:e,glyph:t,danger:n=!1,onClick:s}){return a.jsx("button",{type:"button",title:e,"aria-label":e,onClick:s,className:`flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 dark:text-gray-500 ${n?"hover:text-red-600 dark:hover:text-red-400":"hover:text-gray-700 dark:hover:text-gray-200"}`,children:a.jsx(Oe,{d:t,size:Ye.rowLead})})}function lH({open:e,onOpen:t,readComposerText:n,onFill:s}){const[o,c]=y.useState([]),[u,f]=y.useState(!1),[p,h]=y.useState(null),[x,g]=y.useState(null);y.useEffect(()=>{let _=!1;return Sx().then(R=>{_||c(rH(R.prefs.draftShortcuts))}).catch(()=>{}).finally(()=>{_||f(!0)}),()=>{_=!0}},[]);const v=y.useRef(o);v.current=o;const w=y.useCallback(_=>{const R=v.current;c(_),Nf({draftShortcuts:_}).catch(D=>{c(R),Be(Ae(D))})},[]),S=()=>{const _=n().trim();h({id:null,title:iH(_),prompt:_})},C=()=>{p===null||f2(p)!==null||(w(aH(o,p)),h(null))},N=p===null?null:f2(p),T=p!==null&&p.id!==null;return a.jsxs("div",{children:[a.jsx(nM,{open:e,glyph:oH,label:d.chat.shortcuts.folder,count:`${o.length}/${qy}`,onOpen:t}),e&&a.jsx("div",{className:"mt-0.5 pl-4",children:u&&a.jsxs("ul",{className:"space-y-0.5",children:[o.map(_=>a.jsxs("li",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",title:`${_.title}
|
|
175
175
|
${d.chat.exampleFillHint}`,onClick:()=>s(_.prompt),className:`flex min-w-0 flex-1 items-center gap-2 ${nx}`,children:a.jsx("span",{className:"min-w-0 flex-1 truncate",children:_.title})}),a.jsx(h2,{label:d.common.edit,glyph:Zx,onClick:()=>h({..._})}),a.jsx(h2,{label:d.common.delete,glyph:Jx,danger:!0,onClick:()=>g(_)})]},_.id)),rM(o)&&a.jsx("li",{children:a.jsxs("button",{type:"button",title:d.chat.shortcuts.newFromComposer,onClick:S,className:`flex w-full items-center gap-2 ${nx}`,children:[a.jsx(_I,{size:Ye.inlineGlyph}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.chat.shortcuts.new})]})})]})}),a.jsx(Yt,{open:p!==null,title:T?d.chat.shortcuts.editTitle:d.chat.shortcuts.createTitle,onClose:()=>h(null),widthClass:"sm:max-w-lg",footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>h(null),children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:N!==null,onClick:C,children:d.common.save})]}),children:p!==null&&a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{label:d.chat.shortcuts.titleLabel,hint:d.chat.shortcuts.titleHint(Nl),error:N==="titleTooLong"?d.chat.shortcuts.titleTooLong(Nl):void 0,value:p.title,autoFocus:!0,maxLength:Nl,onChange:_=>h({...p,title:_.target.value}),onKeyDown:_=>{_.key==="Enter"&&!_.nativeEvent.isComposing&&C()}}),a.jsx(ir,{label:d.chat.shortcuts.promptLabel,info:d.chat.shortcuts.promptInfo,infoLabel:d.common.moreInfoAbout(d.chat.shortcuts.promptLabel),hint:d.chat.shortcuts.promptHint(gu),error:N==="promptTooLong"?d.chat.shortcuts.promptTooLong(gu):void 0,value:p.prompt,rows:8,size:"sm",maxLength:gu,onChange:_=>h({...p,prompt:_.target.value})})]})}),a.jsx(ln,{open:x!==null,title:d.chat.shortcuts.deleteTitle,confirmLabel:d.common.delete,onClose:()=>g(null),onConfirm:()=>{x!==null&&w(sH(o,x.id)),g(null)},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:x!==null?d.chat.shortcuts.deleteConfirm(x.title):""})})]})}const cH=["always-ask","read-only","allow-all","deny-all"],ks=(e,t)=>`penguin.chatDraft.${e}.${t}`,aM=(e,t)=>`penguin.chatDraft.session.${e}.${t}`;function g2(e){if(typeof e!="object"||e===null)return;const t=e;if(!(typeof t.provider!="string"||typeof t.modelId!="string"))return{provider:t.provider,modelId:t.modelId}}function uH(e){if(!e)return{};try{return sM(JSON.parse(e))}catch{return{}}}function sM(e){if(typeof e!="object"||e===null)return{};const t=e,n={};typeof t.text=="string"&&(n.text=t.text),typeof t.agentId=="string"&&(n.agentId=t.agentId),typeof t.workspace=="string"&&(n.workspace=t.workspace);const s=g2(t.modelRef);s&&(n.modelRef=s),typeof t.handoffAgentId=="string"&&(n.handoffAgentId=t.handoffAgentId);const o=g2(t.switchModelRef);if(o&&(n.switchModelRef=o),Array.isArray(t.skills)){const c=t.skills.filter(u=>typeof u=="string");c.length>0&&(n.skills=c)}return typeof t.approvalMode=="string"&&cH.includes(t.approvalMode)&&(n.approvalMode=t.approvalMode),n}function $i(e,t=localStorage){try{return uH(t.getItem(e))}catch{return{}}}function Qs(e,t,n=localStorage){try{n.setItem(e,JSON.stringify(t))}catch{}}function Du(e,t=localStorage){try{t.removeItem(e)}catch{}}function iM(e,t,n=localStorage){const s=ks(e,t),o=$i(s,n);o.modelRef&&Qs(s,{...o,modelRef:void 0},n)}function dH(e,t,n=localStorage){const s=ks(e,t),o=$i(s,n);(o.agentId!==void 0||o.workspace!==void 0||o.approvalMode!==void 0)&&Qs(s,{...o,agentId:void 0,workspace:void 0,approvalMode:void 0},n)}const rd=(e,t)=>`penguin.chatDrafts.${e}.${t}`,mH=50,rx="penguin:draft-flush";function fH(e){if(!e)return[];try{const t=JSON.parse(e);if(!Array.isArray(t))return[];const n=[];for(const s of t){if(typeof s!="object"||s===null)continue;const o=s;typeof o.id!="string"||!o.id.startsWith("draft-")||n.push({id:o.id,savedAt:typeof o.savedAt=="string"?o.savedAt:"",draft:sM(o.draft)})}return n}catch{return[]}}const Vy=zl(()=>({cache:new Map})),ax=[];function oM(e){try{return localStorage}catch{return null}}function ad(e,t){const{cache:n}=Vy.getState(),s=n.get(e);if(s)return s;const o=oM();let c=ax;if(o)try{c=fH(o.getItem(e))}catch{c=ax}return n.set(e,c),c}function Gy(e,t,n){const s=oM();if(s)try{t.length===0?s.removeItem(e):s.setItem(e,JSON.stringify(t))}catch{}Vy.setState(o=>({cache:new Map(o.cache).set(e,t)}))}function pH(e,t){return Bl(Vy,()=>e&&t?ad(rd(e,t)):ax)}const hH=()=>`draft-${crypto.randomUUID().replace(/-/g,"").slice(0,8)}`;function Yl(e,t,n){typeof window<"u"&&window.dispatchEvent(new Event(rx));const s=ks(e,t),o=$i(s,n);if(!o.text||o.text.trim()==="")return null;const c=rd(e,t),u={id:hH(),savedAt:new Date().toISOString(),draft:o};return Gy(c,[u,...ad(c)].slice(0,mH)),o.modelRef?Qs(s,{modelRef:o.modelRef},n):Du(s,n),u.id}function x2(e,t,n,s){return ad(rd(e,t)).find(o=>o.id===n)??null}function gH(e,t,n,s,o){const c=rd(e,t),u=ad(c);u.some(f=>f.id===n)&&Gy(c,u.map(f=>f.id===n?{...f,draft:s}:f))}function lM(e,t,n,s){const o=rd(e,t),c=ad(o);c.some(u=>u.id===n)&&Gy(o,c.filter(u=>u.id!==n))}function sx(e){return((e.draft.text??"").split(`
|
|
176
176
|
`).map(n=>n.trim()).find(n=>n!=="")??"").slice(0,80)}const $u="penguin:chat-defaults-changed";function xH(e){window.dispatchEvent(new CustomEvent($u,{detail:e}))}function cM(e,t){const n=e.detail;return n&&n.projectId===t?n:null}const uM="flex max-w-64 items-center gap-1.5 rounded-full border border-gray-300 bg-white py-1 pl-1.5 pr-2 text-xs text-gray-600 transition-colors duration-150 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";function sd({projectId:e,workspace:t,onChange:n,variant:s="pill",trigger:o,fieldLabel:c,emptyLabel:u,menuHint:f,clearLabel:p}){const h=c??d.chat.workspace,[x,g]=y.useState(!1),[v,w]=y.useState({right:!1}),S=y.useRef(!1),[C,N]=y.useState(null),[T,_]=y.useState(!1),[R,D]=y.useState(null),[z,E]=y.useState("");y.useEffect(()=>{E(C?.path??"")},[C]);const L=y.useRef(0),F=y.useCallback((ie,I)=>{const A=++L.current;_(!0),D(null),GE(e,ie).then(Q=>{A===L.current&&N(Q)}).catch(Q=>{A===L.current&&(I?.onError?I.onError():D(Ae(Q)))}).finally(()=>{A===L.current&&_(!1)})},[e]),V=ie=>{if(ie&&!S.current){S.current=!0;const I=t.trim();F(I.startsWith("/")?I:"")}},P=ie=>{g(ie),V(ie)},B=ie=>{const I=!x;if(I){const A=ie.currentTarget.getBoundingClientRect(),Q=parseFloat(getComputedStyle(document.documentElement).fontSize),j=12,U=Math.min(20*Q,window.innerWidth-2*Q),ee=window.innerWidth-j-A.left,re=A.right-j;ee>=U?w({right:!1}):re>ee?w({right:!0,...re<U?{maxWidth:re}:{}}):w({right:!1,maxWidth:ee})}g(I),V(I)},Y=()=>{const ie=z.trim();if(!ie||ie===C?.path){E(C?.path??"");return}F(ie,{onError:()=>{Be(d.chat.workspaceDirInvalid),E(C?.path??"")}})},q=t.trim(),K=q?q.split("/").filter(Boolean).pop()??"/":u??d.chat.workspaceAuto,H=C?.parent??null,$=(C?.entries??[]).filter(ie=>!ie.name.startsWith(".")),X=ie=>a.jsx(Oe,{d:El,size:Ye.rowLead,className:`text-gray-400 ${ie}`}),le=a.jsxs("div",{className:"space-y-1.5 px-2.5 pb-2.5 pt-2",children:[a.jsxs("div",{className:"rounded-md border border-gray-200 dark:border-gray-800",children:[a.jsxs("div",{className:"flex items-center gap-1.5 border-b border-gray-100 px-1.5 py-1 dark:border-gray-800",children:[a.jsx("input",{value:z,placeholder:"…","aria-label":h,...Gu,onChange:ie=>E(ie.target.value),onBlur:Y,onKeyDown:ie=>{ie.key==="Enter"&&!ie.nativeEvent.isComposing?(ie.preventDefault(),Y()):ie.key==="Escape"&&E(C?.path??"")},className:"min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 font-mono text-xs text-gray-600 focus:border-gray-300 focus:outline-none dark:text-gray-300 dark:focus:border-gray-600"}),a.jsx("button",{type:"button",disabled:!C,onClick:()=>{C&&(n(C.path),g(!1))},className:"shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800",children:d.chat.workspaceUseThis})]}),a.jsxs("ul",{className:"max-h-40 overflow-y-auto py-1",children:[H!==null&&a.jsx("li",{children:a.jsxs("button",{type:"button",disabled:T,onClick:()=>F(H),className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800",children:["↰ ",d.chat.workspaceUp]})}),$.map(ie=>a.jsx("li",{children:a.jsxs("button",{type:"button",disabled:T,onClick:()=>F(ie.path),className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800",children:[a.jsx(Oe,{d:El,className:"text-gray-400"}),a.jsx("span",{className:"min-w-0 flex-1 truncate",title:ie.name,children:ie.name})]})},ie.path)),C&&$.length===0&&a.jsx("li",{className:"px-2.5 py-1.5 text-xs text-gray-400",children:d.chat.workspaceNoSubdirs}),T&&a.jsx("li",{className:"px-2.5 py-1.5 text-xs text-gray-400",children:d.common.loading}),R&&a.jsxs("li",{className:"flex items-center justify-between gap-2 px-2.5 py-1.5 text-xs text-red-500",children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",title:R,children:R}),a.jsx("button",{type:"button",disabled:T,onClick:()=>F(""),className:"shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800",children:d.common.retry})]})]})]}),q&&a.jsx("button",{type:"button",onClick:()=>{n(""),g(!1)},className:"text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200",children:p??d.chat.workspaceClear}),a.jsx("p",{className:"px-0.5 text-xs leading-5 text-gray-400 dark:text-gray-500",children:f??d.chat.workspaceHint})]});return o?a.jsx(Qn,{open:x,setOpen:P,portal:{direction:"down",align:"right"},menuClass:"w-64",button:o(x,()=>P(!x)),children:le}):s==="form"?a.jsx(Ru,{open:x,setOpen:P,leading:X(""),label:K,...q?{labelClassName:"font-mono"}:{},title:q?`${h}:${q}`:f??d.chat.workspaceHint,ariaLabel:h,ariaHaspopup:"dialog",menuClass:"w-80",children:le}):a.jsx(Qn,{open:x,setOpen:g,menuClass:`top-full mt-1 w-80 max-w-[calc(100vw-2rem)] ${v.right?"right-0 origin-top-right":"left-0 origin-top-left"}`,...v.maxWidth!==void 0?{menuStyle:{maxWidth:v.maxWidth}}:{},button:a.jsxs("button",{type:"button",title:q?`${h}:${q}`:f??d.chat.workspaceHint,"aria-label":h,onClick:B,className:uM,children:[X("ml-0.5"),a.jsx("span",{className:`min-w-0 truncate ${q?"font-mono":""}`,children:K}),a.jsx(Zn,{open:x,size:12,className:"shrink-0 text-gray-400"})]}),children:le})}const yH=300;function y2(e){try{return sessionStorage.getItem(`penguin.chatRouteApplied.${e}`)}catch{return null}}function b2(e,t){try{sessionStorage.setItem(`penguin.chatRouteApplied.${e}`,t)}catch{}}const bH={webapps:"M3 6a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6zM3 9h18M6 6.5h.01M9 6.5h.01",agents:"M12 3v3m-6 4a6 6 0 0 1 12 0v5a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-5zm3 3h.01M15 13h.01",schedules:"M12 2a10 10 0 1 0 0 20 10 10 0 1 0 0-20M12 6.5V12l3.5 2"};function vH({projectId:e,models:t,draftId:n}){const s=yr(),o=$r(),{agents:c,currentAgent:u,setCurrentAgentId:f}=en(),{add:p}=Ii(),h=mn().user?.userId??null,[x]=y.useState(()=>n!==void 0&&(!h||x2(h,e,n)===null)),[g]=y.useState(()=>h?n!==void 0?x2(h,e,n)?.draft??{}:$i(ks(h,e)):{});y.useEffect(()=>{x&&s("/chat/new",{replace:!0})},[x,s]);const[v,w]=y.useState(g.agentId??u?.agentId??null),[S,C]=y.useState(g.workspace??"");y.useEffect(()=>{JT(S||null)},[S]);const[N,T]=y.useState(g.approvalMode??"allow-all"),[_,R]=y.useState(g.modelRef??null),D=y.useRef(g.text??""),z=y.useRef(g.skills??[]),[E,L]=y.useState(null),F=y.useRef(!1);y.useEffect(()=>{let pe=!1;return Qj(e).then($e=>{!pe&&!F.current&&L($e)}).catch(()=>{!pe&&!F.current&&L({})}),()=>{pe=!0}},[e]);const V=y.useRef({agent:!1,workspace:!1,approval:!1}),P=o.state,B=P?.agentId,Y=y.useRef(null),q=y.useRef(!1);y.useEffect(()=>{if(c.length===0)return;const pe=$e=>!!$e&&c.some(nt=>nt.agentId===$e);if(B&&Y.current!==o.key&&y2("agentId")!==o.key&&(Y.current=o.key,b2("agentId",o.key),pe(B))){w(B);return}if(E?.agentId!==void 0&&!q.current&&(q.current=!0,Y.current===null&&g.agentId===void 0&&!V.current.agent&&pe(E.agentId))){w(E.agentId);return}pe(v)||w((c.find($e=>$e.agentId==="default_agent")??c[0])?.agentId??null)},[c,v,o.key,B,E,g.agentId]);const K=P?.workspace,H=y.useRef(null);y.useEffect(()=>{K===void 0||H.current===o.key||y2("workspace")===o.key||(H.current=o.key,b2("workspace",o.key),C(K))},[o.key,K]);const $=y.useRef(!1);y.useEffect(()=>{E===null||$.current||($.current=!0,E.workspace!==void 0&&K===void 0&&g.workspace===void 0&&!V.current.workspace&&C(E.workspace),E.approvalMode!==void 0&&g.approvalMode===void 0&&!V.current.approval&&T(E.approvalMode))},[E,K,g.workspace,g.approvalMode]),y.useEffect(()=>{if(!t||_&&t.models.some($e=>zt($e,_)))return;const pe=t.models[0];R(t.defaultModel??(pe?{provider:pe.provider,modelId:pe.modelId}:null))},[t,_]);const X=y.useCallback(pe=>{if(pe.defaults){const $e=pe.defaults;F.current=!0,L($e),V.current={agent:!1,workspace:!1,approval:!1},C($e.workspace??""),T($e.approvalMode??"allow-all"),(gt=>gt!==void 0&&c.some(Ke=>Ke.agentId===gt))($e.agentId)?w($e.agentId):c.length>0&&w(u?.agentId??(c.find(gt=>gt.agentId==="default_agent")??c[0])?.agentId??null)}pe.defaultModel!==void 0&&R(pe.defaultModel)},[c,u]),le=y.useRef(X);le.current=X,y.useEffect(()=>{const pe=$e=>{const nt=cM($e,e);nt&&le.current(nt)};return window.addEventListener($u,pe),()=>window.removeEventListener($u,pe)},[e]);const[ie,I]=y.useState(null);y.useEffect(()=>{if(I(null),!v)return;let pe=!1;return Ao(e,v).then($e=>{pe||I($e.config.model?.thinkingLevel??"")}).catch(()=>{}),()=>{pe=!0}},[e,v]);const A=ie===null||E===null?null:dz(ie,E.thinkingLevel),Q=y.useRef(null);Q.current=ie;const j=y.useCallback(pe=>{if(!v||!pe)return;const $e=Q.current;I(pe),To(e,v,{config:{model:{thinkingLevel:pe}}}).catch(nt=>{I($e),Be(Ae(nt))})},[e,v]),[U,ee]=y.useState([]),[re,ke]=y.useState(!1);y.useEffect(()=>{if(ee($e=>$e.length>0?[]:$e),ke(!1),!v)return;let pe=!1;return Bu(e,v).then($e=>{pe||ee($e.skills)}).catch(()=>{}).finally(()=>{pe||ke(!0)}),()=>{pe=!0}},[e,v]);const be=y.useRef(null),ye=y.useCallback(()=>{be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),Se=y.useCallback(()=>{if(ye(),!h)return;const pe={text:D.current,workspace:S,approvalMode:N};v&&(pe.agentId=v),_&&(pe.modelRef=_),z.current.length>0&&(pe.skills=z.current),n!==void 0?gH(h,e,n,pe):Qs(ks(h,e),pe)},[ye,h,e,n,v,S,N,_]),Me=y.useRef(Se);y.useEffect(()=>{Me.current=Se,Se()},[Se]);const ze=y.useCallback(pe=>{D.current=pe,ye(),be.current=window.setTimeout(()=>{be.current=null,Me.current()},yH)},[ye]),De=y.useCallback(pe=>{z.current=pe,Me.current()},[]);y.useEffect(()=>()=>{be.current!==null&&(window.clearTimeout(be.current),Me.current())},[]),y.useEffect(()=>{const pe=()=>{be.current!==null&&(window.clearTimeout(be.current),be.current=null,Me.current())};return window.addEventListener(rx,pe),()=>window.removeEventListener(rx,pe)},[]);const ct=y.useCallback(()=>{if(ye(),z.current=[],D.current="",!!h){if(n!==void 0){lM(h,e,n);return}_?Qs(ks(h,e),{modelRef:_}):Du(ks(h,e))}},[ye,h,e,n,_]),bt=pe=>{V.current.agent=!0,w(pe.agentId),f(pe.agentId)},he=y.useCallback(pe=>{V.current.workspace=!0,C(pe)},[]),ne=y.useCallback(pe=>{V.current.approval=!0,T(pe)},[]),oe=y.useRef(!1),J=y.useCallback(async(pe,$e=null)=>{if(!v||oe.current)return!1;oe.current=!0;let nt=null;try{const gt={approvalMode:N};_&&(gt.modelId=_.modelId,gt.provider=_.provider),S.trim()&&(gt.workspace=S.trim());const Ke=await u0(e,v,gt);nt=Ke.session.sessionId;const dt=await su(nt,{input:pe,...$e?{goal:$e}:{}}),pt=await d0(dt.sessionId).catch(()=>null);return p(pt?.session??Ke.session),ct(),HT(dt.sessionId),s(`/chat/${dt.sessionId}`,{replace:!0}),!0}catch(gt){return nt&&nf(nt).catch(()=>{}),Be(Ae(gt,_?{modelId:_.modelId}:{})),!1}finally{oe.current=!1}},[e,v,N,_,S,p,ct,s]),ht=y.useRef(null),ve=y.useCallback(pe=>{ht.current?.fillExample(d.chat.exampleTasks[pe.id].prompt,pe.skills)},[]),Xe=y.useCallback(pe=>{ht.current?.fillExample(pe,[])},[]),[Ge,He]=y.useState(tx[0].id),Pe=c.find(pe=>pe.agentId===v)??null,W=t?.models.find(pe=>zt(pe,_)),me=W?.contextWindow,Ue=W?.vision!==!1;return a.jsxs("div",{className:"anim-fade flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 md:px-4",children:[a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"mx-auto w-full max-w-3xl",children:[a.jsxs("div",{className:"mb-10 text-center",children:[a.jsx(OT,{className:"mx-auto mb-1 h-36 w-36 rounded-3xl"}),a.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-gray-900 dark:text-gray-100",children:d.appName}),a.jsx("p",{className:"mt-2 text-base text-gray-400 dark:text-gray-500",children:d.chat.draftSubtitle}),a.jsx(kH,{})]}),a.jsx(Iy,{status:"idle",controlRef:ht,onSend:J,onStop:async()=>{},onCompact:async()=>{},modelRef:_,models:t?.models??[],onChangeModel:R,thinkingLevel:A,onChangeThinkingLevel:j,...t?.defaultModel!==void 0?{defaultModel:t.defaultModel}:{},...me!==void 0?{contextWindow:me}:{},contextNow:0,vision:Ue,approvalMode:N,onChangeApprovalMode:ne,modeSaving:!1,autoFocus:!0,agents:c,...v?{currentAgentId:v}:{},skills:U,...g.skills&&g.skills.length>0?{initialSkills:g.skills}:{},onSkillsChange:De,initialText:g.text??"",onTextChange:ze}),a.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[a.jsx(wH,{agents:c,selected:Pe,onSelect:bt}),a.jsx(sd,{projectId:e,workspace:S,onChange:he})]}),a.jsxs("div",{className:"mt-6 space-y-1",children:[tx.map(pe=>{const $e=pe.id===Ge;return a.jsxs("div",{children:[a.jsx(nM,{open:$e,glyph:bH[pe.id],label:d.chat.exampleFolders[pe.id],count:pe.tasks.length,onOpen:()=>He(pe.id)}),$e&&a.jsx("ul",{className:"mt-0.5 space-y-0.5 pl-4",children:pe.tasks.map(nt=>{const gt=d.chat.exampleTasks[nt.id];return a.jsx("li",{children:a.jsx("button",{type:"button",title:`${gt.desc}
|
|
177
177
|
${d.chat.exampleFillHint}`,disabled:!re,onClick:()=>ve(nt),className:`flex w-full items-center gap-2 ${nx}`,children:a.jsx("span",{className:"min-w-0 flex-1 truncate",children:gt.label})})},nt.id)})})]},pe.id)}),a.jsx(lH,{open:Ge===p2,onOpen:()=>He(p2),readComposerText:()=>D.current,onFill:Xe})]})]}),a.jsx("div",{className:"flex-1"})]})}const v2="ml-1.5 inline-block align-super text-[10px] leading-4 text-gray-400 dark:text-gray-500";function kH(){const{locale:e}=Dr(),{version:t,update:n}=Px(!0);if(t===null)return null;const s=t.buildDate;return a.jsxs("p",{className:"mt-1.5 text-xs text-gray-400 dark:text-gray-500",children:[`v${t.version}${s!==null?` · ${d.update.lastUpdated(k0(s,e))}`:""}`,n!==null&&n.updateAvailable&&n.latestVersion!==null&&(n.releaseUrl!==null?a.jsx("a",{href:n.releaseUrl,target:"_blank",rel:"noopener noreferrer",title:d.update.newVersion(n.latestVersion),"aria-label":d.update.newVersion(n.latestVersion),className:`${v2} hover:underline`,children:d.update.newVersionBadge}):a.jsx("span",{className:v2,children:d.update.newVersionBadge}))]})}function wH({agents:e,selected:t,onSelect:n}){const[s,o]=y.useState(!1);return a.jsx(Qn,{open:s,setOpen:o,menuClass:"left-0 top-full mt-1 w-72 max-w-[calc(100vw-2rem)] origin-top-left",button:a.jsxs("button",{type:"button",title:d.chat.chooseAgent,"aria-label":d.chat.chooseAgent,onClick:()=>o(!s),className:uM,children:[t?a.jsx(Ha,{id:t.agentId,name:_n(t),size:16,className:"shrink-0 rounded"}):null,a.jsx("span",{className:"min-w-0 truncate",children:t?_n(t):d.common.loading}),a.jsx(Zn,{open:s,size:12,className:"shrink-0 text-gray-400"})]}),children:a.jsxs("div",{className:"max-h-56 overflow-y-auto",children:[e.length===0&&a.jsx("p",{className:"px-3 py-1.5 text-xs text-gray-400",children:d.common.loading}),e.map(c=>{const u=c.agentId===t?.agentId;return a.jsxs("button",{type:"button","aria-pressed":u,onClick:()=>{n(c),o(!1)},className:`flex w-full items-center ${Ro.menu} px-3 py-1.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`,children:[a.jsx(Ha,{id:c.agentId,name:_n(c),size:20,className:"shrink-0 rounded"}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:`block truncate text-xs ${u?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"}`,children:_n(c)}),c.description&&a.jsx("span",{className:"block truncate text-[11px] text-gray-400 dark:text-gray-500",children:c.description})]}),a.jsx("span",{className:"w-4 shrink-0 text-center text-xs text-gray-500 dark:text-gray-400",children:u?"✓":""})]},c.agentId)})]})})}function SH(e,t){return e.projectId===t?e:null}function jH(e,t){return`${e}:${t}`}function dM(){return{sessionId:null,taskCount:0,sessionCost:null,costUncosted:!1,settledUsd:0,lastLiveUsd:0,liveAtFetchUsd:0,pendingFetchSnapshot:!1,shownUsd:null,shownUncosted:!1}}function CH(e,t,n){e.sessionId===t&&n!==null&&(e.costUncosted=n.hasUncosted,n.cost!=null&&(e.sessionCost=n.cost,e.settledUsd=0,e.pendingFetchSnapshot=!0))}function k2(e){return e.sessionCost!=null||e.settledUsd>0?(e.sessionCost??0)+e.settledUsd:null}function w2(e,t,n,s){return t!=null&&(e.shownUsd=t,e.shownUncosted=n),{costText:t!=null?rs(t,s):null,costUncosted:n}}function NH(e,t){if(t.sessionId!==e.sessionId&&Object.assign(e,dM(),{sessionId:t.sessionId}),t.loading){const f=e.shownUsd??k2(e),p=e.shownUsd!=null?e.shownUncosted:e.costUncosted;return w2(e,f,p,t.currency)}if(t.taskCount<e.taskCount&&(e.taskCount=t.taskCount,e.lastLiveUsd=0,e.liveAtFetchUsd=0),e.pendingFetchSnapshot&&(!t.taskOpen||t.liveUsd!=null)){e.pendingFetchSnapshot=!1;const f=t.taskOpen?t.liveUsd??0:0;e.liveAtFetchUsd=f,e.lastLiveUsd=f}(t.taskCount>e.taskCount||!t.taskOpen&&(e.lastLiveUsd>0||e.liveAtFetchUsd>0))&&(e.settledUsd+=Math.max(0,e.lastLiveUsd-e.liveAtFetchUsd),e.lastLiveUsd=0,e.liveAtFetchUsd=0),e.taskCount=t.taskCount,t.taskOpen&&t.liveUsd!=null&&(e.lastLiveUsd=t.liveUsd);const n=k2(e),s=t.taskOpen&&t.liveUsd!=null?Math.max(0,t.liveUsd-e.liveAtFetchUsd):null,o=s!=null&&(s>0||n!=null)?(n??0)+s:n;let c;o==null||t.taskOpen&&e.shownUsd!=null&&o<e.shownUsd?c=e.shownUsd:c=o;const u=o==null?e.shownUncosted:e.costUncosted;return w2(e,c,u,t.currency)}function Xl(e){return a.jsx("span",{className:"absolute",children:a.jsx("input",{type:"file",className:"sr-only",...e})})}const mM=new Set(["text","plaintext","txt"]),TH=new Map(Object.entries({c:()=>an(()=>import("./c-BIGW1oBm.js"),[]),cpp:()=>an(()=>import("./cpp-DIPi6g--.js"),__vite__mapDeps([0,1,2])),css:()=>an(()=>import("./css-CLj8gQPS.js"),[]),diff:()=>an(()=>import("./diff-D97Zzqfu.js"),[]),go:()=>an(()=>import("./go-C27-OAKa.js"),[]),html:()=>an(()=>import("./html-pp8916En.js"),__vite__mapDeps([3,4,5])),ini:()=>an(()=>import("./ini-BEwlwnbL.js"),[]),java:()=>an(()=>import("./java-CylS5w8V.js"),[]),javascript:()=>an(()=>import("./javascript-wDzz0qaB.js"),[]),json:()=>an(()=>import("./json-Cp-IABpG.js"),[]),jsx:()=>an(()=>import("./jsx-g9-lgVsj.js"),[]),log:()=>an(()=>import("./log-2UxHyX5q.js"),[]),markdown:()=>an(()=>import("./markdown-Cvjx9yec.js"),[]),php:()=>an(()=>import("./php-Csjmro_R.js"),__vite__mapDeps([6,3,4,5,7,8,2,9])),python:()=>an(()=>import("./python-B6aJPvgy.js"),[]),ruby:()=>an(()=>import("./ruby-B13GW9FM.js"),__vite__mapDeps([10,3,4,5,7,8,2,11,12,13,0,1,14,15])),rust:()=>an(()=>import("./rust-B1yitclQ.js"),[]),shellscript:()=>an(()=>import("./shellscript-Yzrsuije.js"),[]),sql:()=>an(()=>import("./sql-CRqJ_cUM.js"),[]),toml:()=>an(()=>import("./toml-vGWfd6FD.js"),[]),tsx:()=>an(()=>import("./tsx-COt5Ahok.js"),[]),typescript:()=>an(()=>import("./typescript-BPQ3VLAy.js"),[]),xml:()=>an(()=>import("./xml-sdJ4AIDG.js"),__vite__mapDeps([7,8])),yaml:()=>an(()=>import("./yaml-Buea-lGh.js"),[])})),MH=new Map(Object.entries({"c++":"cpp",bash:"shellscript",cjs:"javascript",cts:"typescript",js:"javascript",md:"markdown",mjs:"javascript",mts:"typescript",properties:"ini",py:"python",rb:"ruby",rs:"rust",sh:"shellscript",shell:"shellscript",ts:"typescript",yml:"yaml",zsh:"shellscript"})),EH=new Map(Object.entries({html:"html",htm:"html",css:"css",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",json:"json",md:"markdown",py:"python",rb:"ruby",php:"php",go:"go",rs:"rust",java:"java",c:"c",h:"c",cpp:"cpp",hpp:"cpp",sh:"shellscript",bash:"shellscript",yml:"yaml",yaml:"yaml",toml:"toml",ini:"ini",conf:"ini",xml:"xml",sql:"sql",log:"log"})),fM="text";function AH(e){return EH.get(e.toLowerCase())??fM}function $W(e){const t=e.trim().toLowerCase();if(!t||mM.has(t))return fM;const n=MH.get(t)??t;return TH.has(n)?n:void 0}function UW(e){return mM.has(e)}const _H=new Set(["txt","md","json","js","mjs","cjs","ts","tsx","jsx","py","sh","bash","yaml","yml","toml","css","html","htm","csv","log","xml","ini","conf","rs","go","java","c","h","cpp","hpp","sql","rb","php","gitignore","env"]),RH=new Set(["png","jpg","jpeg","gif","webp","svg"]),IH=new Set(["html","htm"]),Am=256*1024,S2=64*1024;function j2(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():e.toLowerCase()}function C2(e){return e.includes("/")?e.slice(0,e.lastIndexOf("/")):""}const N2=/^[a-z][a-z0-9+.-]*:/i;function T2(e,t){const n=t.startsWith("/")||e===""?[]:e.split("/");for(const s of t.split("/"))s===""||s==="."||(s===".."?n.pop():n.push(s));return n.join("/")}const Kg="<script>(function(){function mk(){var m={};return{getItem:function(k){return k in m?m[k]:null},setItem:function(k,v){m[k]=String(v)},removeItem:function(k){delete m[k]},clear:function(){m={}},key:function(i){return Object.keys(m)[i]||null},get length(){return Object.keys(m).length}}}['localStorage','sessionStorage'].forEach(function(n){try{window[n].length}catch(e){Object.defineProperty(window,n,{value:mk(),configurable:true})}})})();<\/script>";function LH(e){return/<head[^>]*>/i.test(e)?e.replace(/<head[^>]*>/i,t=>t+Kg):/<html[^>]*>/i.test(e)?e.replace(/<html[^>]*>/i,t=>t+Kg):Kg+e}let _m=0;function OH({session:e,openRequest:t,active:n,onPreviewOpen:s,reloadSignal:o}){const{previewIsolated:c}=mn(),[u,f]=y.useState(""),[p,h]=y.useState(null),[x,g]=y.useState(null),[v,w]=y.useState(null),[S,C]=y.useState(!1),[N,T]=y.useState(null),[_,R]=y.useState(0),[D,z]=y.useState(!1),[E,L]=y.useState("rendered"),[F,V]=y.useState(null),P=y.useRef(c);P.current=c,y.useEffect(()=>{let j=!1;return g(null),wA(e.sessionId,u).then(U=>{j||h({base:u,res:U})}).catch(U=>{j||g(U instanceof xr?U.message:d.files.loadFailed)}),()=>{j=!0}},[e.sessionId,u,_,o]);const[B,Y]=y.useState(e.sessionId);B!==e.sessionId&&(Y(e.sessionId),f(""),w(null),h(null),V(null),_m++);const q=y.useRef(n);y.useEffect(()=>{n&&!q.current&&R(j=>j+1),q.current=n},[n]);const K=y.useRef(s);K.current=s;const H=y.useCallback(async(j,U)=>{const ee=U?.refresh===!0;ee||K.current?.();const re=j.includes("/")?j.slice(j.lastIndexOf("/")+1):j,ke=j2(re),be=++_m,ye=ze=>{be===_m&&w(ze)};if(ee||(L("rendered"),V(null)),RH.has(ke)){ye({path:j,name:re,kind:"image",nonce:be});return}if(ke==="pdf"){ye({path:j,name:re,kind:"pdf",nonce:be});return}const Se=IH.has(ke),Me=ke==="md";if(!Se&&!_H.has(ke)){ye({path:j,name:re,kind:"unsupported",nonce:be});return}if(Se&&P.current){ye({path:j,name:re,kind:"html",nonce:be});return}try{const ze=await fetch(ji(e.sessionId,j),{credentials:"same-origin"});if(!ze.ok)throw new Error(String(ze.status));const De=await ze.text(),ct=De.length>Am;!ee&&Me&&De.length>S2&&be===_m&&L("source"),ye({path:j,name:re,kind:Se?"html":Me?"md":"text",content:ct?De.slice(0,Am):De,truncated:ct,nonce:be})}catch{ee||ye({path:j,name:re,kind:"unsupported",nonce:be})}},[e.sessionId]);y.useEffect(()=>{if(v?.kind!=="html"||v.content!==void 0||E!=="source"&&c)return;const j=v.path;let U=!1;return V(null),(async()=>{try{const ee=await fetch(ji(e.sessionId,j),{credentials:"same-origin"});if(!ee.ok)throw new Error(String(ee.status));const re=await ee.text();if(U)return;const ke=re.length>Am;w(be=>be!==null&&be.kind==="html"&&be.path===j&&be.content===void 0?{...be,content:ke?re.slice(0,Am):re,truncated:ke}:be)}catch{U||V(d.files.loadFailed)}})(),()=>{U=!0}},[v,E,c,e.sessionId]);const $=y.useRef(null);$.current=v?.path??null;const X=y.useRef(o);y.useEffect(()=>{if(o===X.current)return;X.current=o;const j=$.current;j!==null&&H(j,{refresh:!0})},[o,H]);const le=y.useRef(null);y.useEffect(()=>{if(!t||le.current===t)return;le.current=t;const j=t.path,U=j.includes("/")?j.slice(0,j.lastIndexOf("/")):"";f(U),R(ee=>ee+1),H(j)},[t,H]);const ie=j=>{C(!0),g(null),(async()=>{try{for(const U of j){const ee=await new Promise((re,ke)=>{const be=new FileReader;be.onload=()=>{const ye=be.result;re(ye.slice(ye.indexOf(",")+1))},be.onerror=()=>ke(new Error("read failed")),be.readAsDataURL(U)});await SA(e.sessionId,Ym(u,U.name),ee)}yt(d.files.uploaded),R(U=>U+1)}catch(U){Be(Ae(U))}finally{C(!1)}})()},I=j=>{const U=j.target.files?[...j.target.files]:[];if(j.target.value="",U.length===0)return;const ee=new Set((p?.res.entries??[]).map(ke=>ke.name)),re=U.filter(ke=>ee.has(ke.name)).map(ke=>ke.name);re.length>0?T({files:U,clashes:re}):ie(U)},A=u===""?[]:u.split("/"),Q=x===null&&p!==null&&p.base!==u;return v!==null?a.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800",children:[a.jsxs("button",{type:"button",onClick:()=>{w(null),R(j=>j+1)},title:d.files.backToList,className:"flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-sm text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx(Oe,{d:"M15 18l-6-6 6-6",size:Ye.rowLead}),d.files.backToList]}),a.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-sm font-semibold",title:v.path,children:v.name}),(v.kind==="html"||v.kind==="md")&&a.jsx("div",{className:"flex shrink-0 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800",children:[["rendered",d.files.htmlRendered],["source",d.files.htmlSource]].map(([j,U])=>a.jsx("button",{type:"button",onClick:()=>L(j),className:`rounded px-2 py-0.5 text-xs transition-colors duration-150 ${E===j?"bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"}`,children:U},j))}),/\.html?$/i.test(v.name)&&a.jsxs("a",{href:V1(e.sessionId,v.path),target:"_blank",rel:"noopener noreferrer",title:c?void 0:d.files.previewNotIsolatedHint,className:"inline-flex shrink-0 items-center gap-1 rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[d.files.openInNewTab,!c&&a.jsx("span",{"aria-label":d.files.previewNotIsolatedHint,className:sn.attention,children:"⚠"})]}),a.jsx("a",{href:ji(e.sessionId,v.path,!0),download:v.name,className:"inline-flex shrink-0 items-center rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:d.files.download})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3 [scrollbar-gutter:stable]",children:v.kind==="image"?a.jsx("img",{src:ji(e.sessionId,v.path),alt:v.name,className:"max-w-full rounded-md border border-gray-200 dark:border-gray-800"},v.nonce):v.kind==="pdf"?a.jsx("iframe",{src:ji(e.sessionId,v.path),title:v.name,className:"h-full min-h-[60vh] w-full rounded-md border border-gray-200 dark:border-gray-800"},v.nonce):v.kind==="html"&&E==="rendered"?c?a.jsx("iframe",{src:V1(e.sessionId,v.path),title:v.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads",className:"h-full min-h-[60vh] w-full rounded-md border border-gray-200 bg-white dark:border-gray-800"},v.nonce):v.content===void 0?F!==null?a.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:F}):a.jsx(Sr,{rows:6}):a.jsx("iframe",{srcDoc:LH(v.content),title:v.name,sandbox:"allow-scripts",className:"h-full min-h-[60vh] w-full rounded-md border border-gray-200 bg-white dark:border-gray-800"}):v.kind==="md"&&E==="rendered"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"md-body text-base leading-relaxed text-gray-800 dark:text-gray-100",children:a.jsx(Zu,{remarkPlugins:Ju,components:{img:({src:j,alt:U})=>a.jsx("img",{src:typeof j=="string"&&!N2.test(j)?`${ji(e.sessionId,T2(C2(v.path),j))}&v=${v.nonce}`:j,alt:U??"",loading:"lazy",className:"max-w-full"}),a:({href:j,children:U})=>{if(typeof j!="string"||j.startsWith("#"))return a.jsx("a",{href:j,children:U});if(N2.test(j))return a.jsx("a",{href:j,target:"_blank",rel:"noreferrer",children:U});const ee=T2(C2(v.path),j);return a.jsx("a",{href:ji(e.sessionId,ee),onClick:re=>{re.preventDefault(),H(ee)},children:U})}},children:v.content??""})}),v.truncated&&a.jsxs("p",{className:"mt-1 text-xs text-gray-400",children:["… ",d.files.previewTruncated]})]}):v.kind==="text"||v.kind==="html"||v.kind==="md"?v.content===void 0?F!==null?a.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:F}):a.jsx(Sr,{rows:6}):a.jsxs(a.Fragment,{children:[a.jsx(Cy,{language:AH(j2(v.name)),code:v.content,highlight:v.content.length<=S2}),v.truncated&&a.jsxs("p",{className:"mt-1 text-xs text-gray-400",children:["… ",d.files.previewTruncated]})]}):a.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:d.files.previewUnsupported})})]}):a.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-1 border-b border-gray-200 px-3 py-2 dark:border-gray-800",children:[a.jsx("button",{type:"button",disabled:Q,onClick:()=>{f("")},className:"rounded px-1.5 py-0.5 text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800",children:d.files.root}),A.map((j,U)=>a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"text-gray-300 dark:text-gray-700",children:"/"}),a.jsx("button",{type:"button",disabled:Q,onClick:()=>f(A.slice(0,U+1).join("/")),className:"max-w-32 truncate rounded px-1 py-0.5 text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800",children:j})]},U)),a.jsx("span",{className:"flex-1"}),a.jsx(Qn,{open:D,setOpen:z,menuClass:"right-0 top-full mt-1 w-max max-w-72 origin-top-right",button:a.jsx(ge,{size:"sm",variant:D?"primary":"ghost",onClick:()=>z(j=>!j),children:d.files.details}),children:a.jsxs("div",{className:"px-3.5 py-2.5",children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.files.workspacePath}),a.jsx("p",{className:"mt-1 break-all font-mono text-xs leading-5",children:e.workspace})]})}),a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>R(j=>j+1),children:d.files.refresh}),a.jsxs("label",{className:"inline-flex cursor-pointer items-center rounded-md border border-transparent bg-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 focus-within:ring-2 focus-within:ring-gray-400/30 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[a.jsx(Xl,{multiple:!0,onChange:I,disabled:S}),S?d.common.saving:d.files.upload]})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:x?a.jsx("p",{className:"px-3 py-3 text-sm text-red-600 dark:text-red-400",children:x}):p===null?a.jsx(Sr,{rows:6}):p.res.entries.length===0?a.jsx("p",{className:"px-3 py-3 text-sm text-gray-400",children:d.files.empty}):a.jsx("ul",{"aria-busy":Q,className:`divide-y divide-gray-100 dark:divide-gray-800/60 ${Q?"opacity-60":""}`,children:p.res.entries.map(j=>a.jsx("li",{children:a.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50",children:[a.jsxs("button",{type:"button",disabled:Q,onClick:()=>{const U=Ym(p.base,j.name);j.kind==="dir"?f(U):H(U)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:j.name,children:[a.jsx("span",{className:"shrink-0 text-gray-400","aria-hidden":!0,children:j.kind==="dir"?a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",children:a.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"})}):a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",children:a.jsx("path",{d:"M6 3h8l4 4v14H6zM14 3v4h4"})})}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:j.name})]}),a.jsx("span",{className:"shrink-0 font-mono text-xs text-gray-400 dark:text-gray-500",children:j.kind==="file"?ju(j.sizeBytes):""}),a.jsx("span",{className:"hidden shrink-0 font-mono text-xs text-gray-400 sm:block dark:text-gray-500",children:j.mtime?Jr(j.mtime):""}),j.kind==="file"&&a.jsx("a",{href:ji(e.sessionId,Ym(p.base,j.name),!0),download:j.name,title:d.files.download,className:"shrink-0 rounded p-1 text-gray-300 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 group-hover:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a.jsx("path",{d:"M12 3v12m0 0l-4-4m4 4l4-4M4 21h16"})})})]})},j.name))})}),a.jsx(ln,{open:N!==null,title:d.files.overwriteTitle,tone:"primary",confirmLabel:d.files.upload,onClose:()=>T(null),onConfirm:()=>{N&&ie(N.files),T(null)},children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.files.overwriteConfirm(N?.clashes.length??0)}),a.jsx("ul",{className:"max-h-40 overflow-y-auto rounded-md border border-gray-200 px-3 py-1.5 dark:border-gray-800",children:(N?.clashes??[]).map(j=>a.jsx("li",{className:"truncate py-0.5 font-mono text-xs",title:j,children:j},j))})]})})]})}function DH(e,t,n,s){const[o,c]=y.useState({forAgent:null,scopes:null,error:null});return y.useEffect(()=>{if(!n||e===null||t===null)return;let u=!1;return(async()=>{try{const f=await eC(e,t),p=await Promise.all(f.scopes.map(async h=>({info:h,files:(await tC(e,t,h.scopeKey)).files})));u||c({forAgent:t,scopes:p,error:null})}catch(f){u||c({forAgent:t,scopes:null,error:Ae(f)})}})(),()=>{u=!0}},[n,e,t,s]),o.forAgent!==t?{scopes:null,error:null}:{scopes:o.scopes,error:o.error}}function $H({nodes:e,selectedId:t,labelFor:n,onSelect:s}){const o=mP(e);return a.jsx("div",{role:"group","aria-label":d.subagentPanel.topologyLabel,className:"overflow-x-auto",children:a.jsxs("div",{className:"relative",style:{width:o.width,height:o.height},children:[a.jsx("svg",{width:o.width,height:o.height,className:"absolute inset-0 text-gray-300 dark:text-gray-700","aria-hidden":!0,children:o.edges.map(c=>a.jsx("path",{d:c.path,fill:"none",stroke:"currentColor",strokeWidth:"1.5"},`${c.fromId}>${c.toId}`))}),o.nodes.map(({node:c,x:u,y:f})=>{const p=n(c),h=c.sessionId===t,x=c.running?d.subagentPanel.nodeRunning:d.subagentPanel.nodeDone,g=c.description!==null?`${p} · ${x}
|
|
178
178
|
${c.description}`:`${p} · ${x}`;return a.jsxs("button",{type:"button","aria-label":`${p} · ${x}`,"aria-pressed":h,title:g,onClick:()=>s(c),style:{left:u,top:f,width:Xm,height:iu},className:`absolute flex flex-col justify-center gap-0.5 rounded-md border bg-white px-2 text-left transition-colors duration-150 dark:bg-gray-900 ${h?"border-brand-500 ring-1 ring-brand-500":"border-gray-200 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-700 dark:hover:border-gray-600 dark:hover:bg-gray-800/60"}`,children:[a.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[a.jsx(Ha,{id:c.agentId??c.sessionId,name:p,size:18}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-xs font-medium text-gray-700 dark:text-gray-300",children:p}),c.running?c.startedMs!==void 0&&a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:a.jsx(Ll,{sinceMs:c.startedMs})}):c.elapsedMs!==void 0&&a.jsx("span",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:Pn(c.elapsedMs)}),a.jsx(Di,{state:c.running?"running":"done",size:10})]}),c.description!==null&&a.jsx("span",{className:"w-full truncate pl-[24px] text-[10px] leading-tight text-gray-400 dark:text-gray-500",children:c.description})]},c.sessionId)})]})})}function UH({session:e,model:t,version:n,taskRunning:s,ctx:o,focusRequest:c,taskScope:u,subagents:f,models:p,approvalMode:h,onChangeApprovalMode:x,modeSaving:g,parentThinkingLevel:v}){const{agents:w,setCurrentAgentId:S}=en(),{sessions:C}=Ii(),N=yr(),[T,_]=y.useState(null);y.useEffect(()=>{c&&_({sessionId:c.sessionId,origin:c.origin})},[c]);const R=y.useMemo(()=>new Map(f.map(H=>[H.sessionId,H.running])),[f]),D=y.useMemo(()=>(u?oP(t,e.sessionId,s,u.anchorSessionId,R):null)??iP(t,e.sessionId,s,R),[t,n,e.sessionId,s,u,R]),z=D.find(H=>H.depth>0)??null,E=T??(z?{sessionId:z.sessionId,origin:z.origin}:null),L=H=>{if(H.depth===0){const $=w.find(X=>X.agentId===e.agentId);return $?$.name?.length?$.name:$.agentId:e.agentId}return B0(H,w,C)??H0(H.sessionId)},F=E!==null&&E.origin.length===0,V=E?D.find(H=>H.sessionId===E.sessionId)??null:null,P=E&&!F?dP(t,E.origin):null,B=V?L(V):E?B0({sessionId:E.sessionId,agentId:P?.meta?.agentId??null},w,C)??d.chat.subagent:"",Y=V?.running??!1,q=E?{...o,origin:E.origin,taskRunning:Y}:null,K=()=>{if(!E)return;const H=C.find(X=>X.sessionId===E.sessionId);H&&Gx(H.projectId,H.sessionId,H.lastActiveAt);const $=H?.agentId??P?.meta?.agentId??null;$!==null&&S($),N(`/chat/${E.sessionId}`)};return a.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a.jsxs("div",{className:"shrink-0 border-b border-gray-200 px-3 pb-2 pt-1.5 dark:border-gray-800",children:[a.jsx("p",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400",children:d.subagentPanel.topologyLabel}),D.length>1?a.jsx("div",{className:"max-h-48 overflow-y-auto",children:a.jsx($H,{nodes:D,selectedId:E?.sessionId??null,labelFor:L,onSelect:H=>_({sessionId:H.sessionId,origin:H.origin})})}):a.jsx("p",{className:"py-1 text-xs text-gray-400 dark:text-gray-500",children:d.subagentPanel.empty})]}),E===null?a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(Fa,{title:d.subagentPanel.empty})}):F?a.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center p-4",children:a.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500",children:d.subagentPanel.mainSessionNote})}):P===null?a.jsx("div",{className:"min-h-0 flex-1",children:a.jsx(Fa,{title:d.subagentPanel.empty})}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-gray-100 px-3 py-1.5 dark:border-gray-800/60",children:[a.jsx(Ha,{id:P.meta?.agentId??E.sessionId,name:B,size:16}),a.jsx("span",{className:"min-w-0 truncate text-xs font-semibold text-gray-700 dark:text-gray-300",children:B}),a.jsx("span",{title:E.sessionId,className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:H0(E.sessionId)}),Y&&a.jsx(Di,{state:"running",size:10,label:d.chat.subagentRunning}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("button",{type:"button",title:d.subagentPanel.openAsSession,"aria-label":d.subagentPanel.openAsSession,"data-testid":"subagent-open-session",onClick:K,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:"M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5",size:Ye.rowLead})})]}),a.jsx("div",{className:"min-h-0 flex-1",children:q&&a.jsx(pT,{items:P.items,version:n,ctx:q},E.sessionId)}),a.jsx(zH,{sessionId:e.sessionId,childSessionId:E.sessionId,running:Y,meta:P.meta,contextNow:P.stats.contextNow,deliveredInputs:PH(P),models:p,approvalMode:h,onChangeApprovalMode:x,modeSaving:g,fallbackThinkingLevel:V?.spawnThinkingLevel??v},`composer-${E.sessionId}`)]})]})}function PH(e){let t=0;for(const n of e.items)(n.kind==="user_text"||n.kind==="user_steering")&&(t+=1);return t}function zH({sessionId:e,childSessionId:t,running:n,meta:s,contextNow:o,deliveredInputs:c,models:u,approvalMode:f,onChangeApprovalMode:p,modeSaving:h,fallbackThinkingLevel:x}){const{currentProject:g}=en(),v=g?.projectId??null,[w,S]=y.useState([]);y.useEffect(()=>{let z=!1;S([]);const E=s?.agentId;if(!(!v||!E))return Bu(v,E).then(L=>{z||S(L.skills)}).catch(()=>{}),()=>{z=!0}},[v,s?.agentId]);const[C,N]=y.useState(""),T=s?{provider:s.provider,modelId:s.modelId}:null,_=T?u.find(z=>z.provider===T.provider&&z.modelId===T.modelId)?.contextWindow:void 0,R=z=>cA(e,t,z,C||void 0),D=z=>{Be(z instanceof xr&&z.code==="subagent_gone"?d.subagentPanel.subagentGone:z instanceof Error?z.message:String(z))};return a.jsx("div",{className:"shrink-0 border-t border-gray-100 px-2 pb-2 pt-2 dark:border-gray-800/60",children:a.jsx(Iy,{variant:"subagent",status:n?"running":"idle",onSend:async z=>{const E=z.filter(L=>L.type==="text").map(L=>L.text).join(`
|
|
179
179
|
|
|
180
|
-
`).trim();if(!E)return!1;try{return await R(E),!0}catch(L){return D(L),!1}},onSteer:async z=>{try{return await R(z),"queued"}catch(E){return D(E),"failed"}},steeringDeliveredCount:c,onStop:async()=>{await uA(e,t).catch(()=>{})},modelRef:T,models:u,turnThinkingLevel:C||x,onChangeTurnThinkingLevel:N,..._!==void 0?{contextWindow:_}:{},contextNow:o,vision:!1,approvalMode:f,onChangeApprovalMode:p,modeSaving:h,agents:[],skills:w})})}const Tl={cacheRead:"#7dd3fc",cacheWrite:"#0ea5e9",output:"#0369a1"};function BH({cacheRead:e,cacheWrite:t,output:n,max:s,size:o=44}){const c=e+t+n,u=Math.max(2,Math.round(o*.16)),f=o/2,p=(o-u)/2,h=2*Math.PI*p,x=Math.max(s,c,1),g=s>0?c/s:0,v=g>.95?sn.danger:g>.8?sn.attention:"text-gray-300 dark:text-gray-700",w=[{key:"cacheRead",value:e,color:Tl.cacheRead,label:d.usage.colCacheRead},{key:"cacheWrite",value:t,color:Tl.cacheWrite,label:d.usage.colCacheWrite},{key:"output",value:n,color:Tl.output,label:d.usage.colOutput}],S=`${d.chat.contextUsage} ${It(c)}/${It(s)}`+w.map(N=>` · ${N.label} ${It(N.value)}`).join("");let C=0;return a.jsxs("svg",{width:o,height:o,viewBox:`0 0 ${o} ${o}`,className:`block shrink-0 ${v}`,role:"img","aria-label":S,children:[a.jsx("title",{children:S}),a.jsx("circle",{cx:f,cy:f,r:p,fill:"none",stroke:"currentColor",strokeOpacity:.35,strokeWidth:u}),w.map(N=>{if(N.value<=0)return null;const T=N.value/x*h,_=-(C/x)*h;return C+=N.value,a.jsx("circle",{cx:f,cy:f,r:p,fill:"none",stroke:N.color,strokeWidth:u,strokeDasharray:`${T} ${h}`,strokeDashoffset:_,transform:`rotate(-90 ${f} ${f})`},N.key)})]})}function HH(e,t){const n=Math.min(e.callMs,e.approvalMs??e.callMs),s=Math.max(n,e.approvalMs??n,e.outputMs??t);return{startMs:n,endMs:s}}function FH(e){const t=new Map,n=[...e].sort((o,c)=>o.startMs-c.startMs||o.endMs-c.endMs);for(const o of n){let c=t.get(o.name);c||(c=[],t.set(o.name,c));const u=c.find(f=>o.startMs>=f.lastEnd);u?(u.spans.push(o),u.lastEnd=Math.max(u.lastEnd,o.endMs)):c.push({spans:[o],lastEnd:o.endMs})}const s=[];for(const[o,c]of t)for(const u of c)s.push({name:o,spans:u.spans});return s}const fa={thinking:"bg-violet-500 dark:bg-violet-400",text:"bg-sky-500 dark:bg-sky-400",toolgen:"bg-amber-500 dark:bg-amber-400",approvalWait:"bg-rose-400 dark:bg-rose-300",exec:"bg-emerald-500 dark:bg-emerald-400",other:"bg-gray-400 dark:bg-gray-500"},kf="sticky left-0 z-10 flex h-4 w-[5.5rem] shrink-0 items-center justify-end bg-white pr-2 dark:bg-gray-950",ix="truncate font-mono text-[11px]",M2=.25,ox=24,qH=1/ox,qs=(e,t,n)=>Math.min(n,Math.max(t,e));function VH(e){return e==="thinking"?fa.thinking:e==="text"?fa.text:fa.toolgen}function GH(e){return e==="thinking"?d.traces.kindThinking:e==="text"?d.traces.kindModelReply:d.traces.kindToolGen}function KH(e){return e==="thinking"?"thinking":e==="text"?"text":"toolgen"}function co(e){if(e===void 0)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function WH(e,t,n){const s=new Map,o=u=>{let f=s.get(u);return f||(f={segs:[],spans:[],others:[]},s.set(u,f)),f};for(const u of e){const f=co(u.startTs),p=co(u.endTs);f===null||p===null||o(u.taskIndex).segs.push({kind:u.kind,...u.name!==void 0?{name:u.name}:{},ts:u.endTs,startMs:f,endMs:p})}for(const u of t){const f=co(u.callTs);f!==null&&o(u.taskIndex).spans.push({name:u.name||u.toolCallId,toolCallId:u.toolCallId,callTs:u.callTs,...u.approvalTs!==void 0?{approvalTsRaw:u.approvalTs}:{},...u.outputTs!==void 0?{outputTsRaw:u.outputTs}:{},callMs:f,approvalMs:co(u.approvalTs),outputMs:co(u.outputTs),failed:u.stopReason!==void 0&&u.stopReason!=="completed",...u.stopReason!==void 0?{status:u.stopReason}:{},...u.decision!==void 0?{decision:u.decision}:{}})}for(const u of n){const f=co(u.startTs),p=co(u.endTs);f===null||p===null||o(u.taskIndex).others.push({key:u.key,name:u.name,ts:u.endTs,startMs:f,endMs:p,failed:u.failed===!0})}const c=[];for(const[u,{segs:f,spans:p,others:h}]of[...s.entries()].sort((x,g)=>x[0]-g[0])){if(f.length===0&&p.length===0&&h.length===0)continue;const x=[...f.map(N=>N.startMs),...p.map(N=>N.callMs),...h.map(N=>N.startMs)],g=[...f.map(N=>N.endMs),...p.map(N=>N.outputMs??N.approvalMs??N.callMs),...h.map(N=>N.endMs)],v=Math.min(...x),w=Math.max(...g,...x),S=Math.max(1,w-v);p.sort((N,T)=>N.callMs-T.callMs),h.sort((N,T)=>N.startMs-T.startMs);const C=FH(p.map(N=>({...N,...HH(N,v+S)})));c.push({taskIndex:u,segs:f,others:h,t0:v,total:S,toolRows:C})}return c}function lx({children:e}){return a.jsx("div",{className:"relative h-4 min-w-0 flex-1 overflow-hidden bg-gray-100 dark:bg-gray-800/60",children:e})}function YH({label:e,children:t}){return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-400 dark:text-gray-500`,title:e,children:a.jsx("span",{className:ix,children:e})}),a.jsx(lx,{children:t})]})}function XH({total:e}){const t=[0,.25,.5,.75,1];return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:kf}),a.jsx("div",{className:"relative h-4 min-w-0 flex-1",children:t.map((n,s)=>a.jsx("span",{className:`absolute top-0 font-mono text-[11px] text-gray-400 dark:text-gray-500 ${s===0?"":s===t.length-1?"-translate-x-full":"-translate-x-1/2"}`,style:{left:`${n*100}%`},children:Pn(n*e)},s))})]})}function QH({segments:e,toolSpans:t,otherSpans:n=[],highlight:s,onHighlight:o,onJump:c,hideTaskLabel:u=!1}){const f=y.useMemo(()=>WH(e,t,n),[e,t,n]),{firstBarKeyByTs:p,barKeys:h}=y.useMemo(()=>{const j=new Map,U=new Set,ee=(re,ke)=>{U.add(ke),j.has(re)||j.set(re,ke)};for(const re of f){re.segs.forEach((ke,be)=>ee(ke.ts,`s-${re.taskIndex}-${be}`));for(const ke of re.toolRows)for(const be of ke.spans)be.approvalMs!==null&&be.approvalMs>be.callMs&&ee(be.approvalTsRaw??be.callTs,`w-${be.toolCallId}`),be.approvalMs===null&&be.outputMs===null?ee(be.callTs,`p-${be.toolCallId}`):ee(be.outputTsRaw??be.callTs,`e-${be.toolCallId}`);for(const ke of re.others)ee(ke.ts,`o-${ke.key}`)}return{firstBarKeyByTs:j,barKeys:U}},[f]),[x,g]=y.useState(null),[v,w]=y.useState(1),[S,C]=y.useState({left:0,width:1}),N=y.useRef(null),T=y.useRef(null),_=y.useRef(S);_.current=S;const R=y.useRef(v);R.current=v;const D=y.useRef(null),z=y.useRef(null),E=y.useCallback(()=>{const j=N.current;if(!j)return;const U=j.scrollWidth||1;C({left:j.scrollLeft/U,width:Math.min(1,j.clientWidth/U)})},[]);if(y.useLayoutEffect(()=>{const j=N.current;if(j){if(D.current){const U=j.scrollWidth-j.clientWidth;j.scrollLeft=qs(D.current(j),0,Math.max(0,U)),D.current=null}E()}},[v,f,E]),y.useLayoutEffect(()=>{const j=N.current;if(!j||typeof ResizeObserver>"u")return;const U=new ResizeObserver(()=>E());return U.observe(j),()=>U.disconnect()},[E]),y.useLayoutEffect(()=>()=>z.current?.(),[]),f.length===0)return a.jsx("p",{className:"text-xs text-gray-400",children:d.common.none});const L=s?.ts,F=s?.key,V=(j,U)=>o?.(U?{ts:U,key:j}:null),P=()=>o?.(null),B=F??(L!==void 0?p.get(L):void 0),Y=B!==void 0&&h.has(B)?B:void 0,q=Y!==void 0,K=j=>Y===j,H=(j,U)=>x!==null&&!U||q&&!j?"opacity-15":"",$=(j,U,ee,re)=>{const ke=qs((j-ee)/re*100,0,100),be=qs((U-j)/re*100,0,100-ke);return ke>=100?{left:"100%",width:"0%",marginLeft:"-2px"}:{left:`${ke}%`,width:`${be}%`}},X=[{key:"thinking",className:fa.thinking,label:d.traces.kindThinking},{key:"text",className:fa.text,label:d.traces.kindModelReply},{key:"toolgen",className:fa.toolgen,label:d.traces.kindToolGen},{key:"approvalWait",className:fa.approvalWait,label:d.traces.legendApprovalWait},{key:"exec",className:fa.exec,label:d.traces.legendToolExec},{key:"other",className:fa.other,label:d.traces.legendOther}],le=(j,U)=>{const ee=qs(U,qH,1),re=qs(1/ee,M2,ox),ke=qs(j,0,1-ee);D.current=be=>ke*be.scrollWidth,w(re)},ie=j=>{j.preventDefault();const U=T.current,ee=N.current;if(!U||!ee)return;const re=U.getBoundingClientRect().width||1,ke=j.clientX,be=ee.scrollLeft,ye=Math.max(0,ee.scrollWidth-ee.clientWidth),Se=ze=>{const De=(ze.clientX-ke)/re;ee.scrollLeft=qs(be+De*ee.scrollWidth,0,ye),E()},Me=()=>{window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",Me),window.removeEventListener("pointercancel",Me),z.current=null};window.addEventListener("pointermove",Se),window.addEventListener("pointerup",Me),window.addEventListener("pointercancel",Me),z.current=Me},I=j=>U=>{U.preventDefault(),U.stopPropagation();const ee=T.current;if(!ee)return;const re=ee.getBoundingClientRect(),ke=ye=>{const Se=qs((ye.clientX-re.left)/(re.width||1),0,1),Me=_.current;if(j==="right")le(Me.left,Se-Me.left);else{const ze=Me.left+Me.width;le(Se,ze-Se)}},be=()=>{window.removeEventListener("pointermove",ke),window.removeEventListener("pointerup",be),window.removeEventListener("pointercancel",be),z.current=null};window.addEventListener("pointermove",ke),window.addEventListener("pointerup",be),window.addEventListener("pointercancel",be),z.current=be},A=()=>{D.current=()=>0,w(1)},Q=j=>{const U=N.current,ee=qs(R.current*j,M2,ox);if(ee!==R.current){if(U){const re=U.clientWidth/2,ke=(U.scrollLeft+re)/(U.scrollWidth||1);D.current=be=>ke*be.scrollWidth-re}w(ee)}};return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{ref:N,className:"no-scrollbar overflow-x-auto overflow-y-hidden",children:a.jsx("div",{className:"space-y-4",style:{width:`${v*100}%`},children:f.map(j=>a.jsxs("div",{className:"space-y-1",children:[!u&&a.jsxs("div",{className:"flex items-center gap-2 pl-[5.5rem]",children:[a.jsx("span",{className:"rounded bg-gray-100 px-1.5 py-0.5 text-[11px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400",children:d.traces.task(j.taskIndex+1)}),a.jsx("span",{className:"font-mono text-[11px] text-gray-400",children:Pn(j.total)})]}),a.jsx(YH,{label:d.traces.laneLLM,children:j.segs.map((U,ee)=>{const re=KH(U.kind),ke=x===null||x===re,be=`s-${j.taskIndex}-${ee}`,ye=K(be);return a.jsx("span",{onMouseEnter:()=>V(be,U.ts),onMouseLeave:P,onClick:()=>c?.(U.ts),title:`${GH(U.kind)}${U.name?` ${U.name}`:""} · ${Pn(U.endMs-U.startMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${VH(U.kind)} ${H(ye,ke)}`,style:$(U.startMs,U.endMs,j.t0,j.total)},ee)})}),j.toolRows.map((U,ee)=>a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-500 dark:text-gray-400`,title:U.name,children:a.jsx("span",{className:ix,children:U.name})}),a.jsx(lx,{children:U.spans.map(re=>{const ke=re.approvalMs??re.callMs,be=re.outputMs===null,ye=re.outputMs??j.t0+j.total,Se=re.approvalTsRaw??re.callTs,Me=re.outputTsRaw??re.callTs;return a.jsxs(y.Fragment,{children:[re.approvalMs!==null&&re.approvalMs>re.callMs&&a.jsx("span",{onMouseEnter:()=>V(`w-${re.toolCallId}`,Se),onMouseLeave:P,onClick:()=>c?.(Se),title:`${re.name} · ${d.traces.legendApprovalWait}${re.decision?` (${re.decision})`:""} · ${Pn(re.approvalMs-re.callMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.approvalWait} ${H(K(`w-${re.toolCallId}`),x===null||x==="approvalWait")}`,style:$(re.callMs,re.approvalMs,j.t0,j.total)}),re.approvalMs===null&&be?(()=>{const ze=H(K(`p-${re.toolCallId}`),x===null||x==="approvalWait");return a.jsx("span",{onMouseEnter:()=>V(`p-${re.toolCallId}`,re.callTs),onMouseLeave:P,onClick:()=>c?.(re.callTs),title:`${re.name} · ${d.traces.legendApprovalWait} · ${d.traces.inProgress}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.approvalWait} ${ze||"animate-pulse"}`,style:$(re.callMs,ye,j.t0,j.total)})})():(()=>{const ze=H(K(`e-${re.toolCallId}`),x===null||x==="exec"),De=be&&!ze;return a.jsx("span",{onMouseEnter:()=>V(`e-${re.toolCallId}`,Me),onMouseLeave:P,onClick:()=>c?.(Me),title:`${re.name} · ${d.traces.legendToolExec} · ${be?d.traces.inProgress:Pn(ye-ke)}${re.failed?` · ${re.status}`:""}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.exec} ${re.failed?"ring-1 ring-red-500":""} ${De?"animate-pulse opacity-70":ze}`,style:$(ke,ye,j.t0,j.total)})})()]},re.toolCallId)})})]},`${ee}-${U.name}`)),j.others.map(U=>{const ee=H(K(`o-${U.key}`),x===null||x==="other");return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-500 dark:text-gray-400`,title:U.name,children:a.jsx("span",{className:ix,children:U.name})}),a.jsx(lx,{children:a.jsx("span",{onMouseEnter:()=>V(`o-${U.key}`,U.ts),onMouseLeave:P,onClick:()=>c?.(U.ts),title:`${U.name} · ${d.traces.legendOther} · ${Pn(U.endMs-U.startMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.other} ${U.failed?"ring-1 ring-red-500":""} ${ee}`,style:$(U.startMs,U.endMs,j.t0,j.total)})})]},U.key)}),a.jsx(XH,{total:j.total})]},j.taskIndex))})}),a.jsx("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-gray-100 pt-2.5 dark:border-gray-800",children:X.map(j=>a.jsxs("button",{type:"button",onMouseEnter:()=>g(j.key),onMouseLeave:()=>g(null),className:`flex items-center gap-1 px-1 font-mono text-[11px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${x!==null&&x!==j.key?"opacity-30":""}`,children:[a.jsx("span",{className:`inline-block h-2 w-3 rounded-sm ${j.className}`}),j.label]},j.key))}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400",children:d.traces.zoom}),a.jsx("button",{type:"button","aria-label":d.traces.zoomOut,title:d.traces.zoomOut,onClick:()=>Q(1/1.4),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800",children:a.jsx("span",{className:"text-[11px] leading-none",children:"−"})}),a.jsx("div",{ref:T,onDoubleClick:A,title:d.traces.zoomReset,className:"relative h-3 min-w-0 flex-1 rounded bg-gray-100 dark:bg-gray-800",children:a.jsxs("div",{role:"scrollbar","aria-label":d.traces.zoom,onPointerDown:ie,className:"absolute inset-y-0 flex cursor-grab items-center justify-between rounded bg-gray-400/70 active:cursor-grabbing dark:bg-gray-500/70",style:{left:`${S.left*100}%`,width:`${Math.max(S.width*100,3)}%`},children:[a.jsx("span",{onPointerDown:I("left"),className:"h-full w-1.5 shrink-0 cursor-ew-resize rounded-l bg-gray-500/80 dark:bg-gray-400/80"}),a.jsx("span",{onPointerDown:I("right"),className:"h-full w-1.5 shrink-0 cursor-ew-resize rounded-r bg-gray-500/80 dark:bg-gray-400/80"})]})}),a.jsx("button",{type:"button","aria-label":d.traces.zoomIn,title:d.traces.zoomIn,onClick:()=>Q(1.4),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800",children:a.jsx("span",{className:"text-[11px] leading-none",children:"+"})}),a.jsxs("span",{className:"w-9 shrink-0 text-right font-mono text-[11px] tabular-nums text-gray-400",children:[v.toFixed(2),"×"]})]}),o&&a.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-600",children:d.traces.linkHint})]})}function ZH(e){return e==="session_meta"?"brand":e==="model_msg"?"gray":"amber"}const JH={text:"M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",thinking:"M9 18h6M10 21h4M12 3a6 6 0 0 0-3 11v2h6v-2a6 6 0 0 0-3-11z",image_url:"M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",inline_data:"M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",tool_call:"M14.7 6.3a4 4 0 0 0-5 5L4 17v3h3l5.7-5.7a4 4 0 0 0 5-5l-2.5 2.5-2-2 2.5-2.5z",tool_call_output:"M4 6l4 4-4 4M12 18h8",token_usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",request_begin:"M5 12h14M13 6l6 6-6 6",request_end:"M19 12H5M11 6l-6 6 6 6",approval_decision:"M9 12l2 2 4-4M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z",compaction_begin:"M8 3H4v4M16 3h4v4M8 21H4v-4M16 21h4v-4M9 12h6",compaction_end:"M8 3H4v4M16 3h4v4M8 21H4v-4M16 21h4v-4M9 12h6",abort:"M6 6h12v12H6z",subagent:"M12 3v6m0 0l-5 4v8m5-12l5 4v8M4 21h16",mcp_connect_begin:"M9 7V3m6 4V3M7 7h10v4a5 5 0 0 1-10 0zM12 16v5",mcp_connect_end:"M9 7V3m6 4V3M7 7h10v4a5 5 0 0 1-10 0zM12 16v5",tool_list_ready:"M14.7 6.3a4 4 0 0 0-5 5L4 17v3h3l5.7-5.7a4 4 0 0 0 5-5l-2.5 2.5-2-2 2.5-2.5z"},eF="M12 8v5m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z";function tF({type:e}){return a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-gray-400 dark:text-gray-500","aria-hidden":!0,children:a.jsx("path",{d:JH[e]??eF})})}function nF(e){const t=e.payload;switch(t.type){case void 0:return"";case"text":return`${String(t.role)}: ${String(t.text??"").slice(0,120)}`;case"thinking":return String(t.thinking??"").slice(0,120);case"image_url":return"[image]";case"inline_data":return`[image] ${String(t.mime_type??"")}`;case"tool_call":return`${String(t.name)} ${String(t.arguments??"").slice(0,100)}`;case"tool_call_output":{const n=String(t.output??"").slice(0,120);return Array.isArray(t.images)&&t.images.length>0?`[image] ${n}`:n}case"token_usage":{const n=t.request,s=t.session;return`request.total=${n?.total??0} session.total=${s?.total??0}`}case"request_end":return`status=${String(t.status)}`;case"approval_decision":return`${String(t.decision)} · ${String(t.tool_call_id)}`;case"compaction_begin":case"compaction_end":return`${String(t.mode)} (${String(t.reason)})${t.status?` · ${String(t.status)}`:""}`;case"mcp_connect_begin":return Array.isArray(t.servers)?t.servers.map(String).join(", "):"";case"mcp_connect_end":{const s=(Array.isArray(t.results)?t.results:[]).map(o=>`${String(o.server)}:${String(o.status)}(${String(o.duration_ms)}ms)`);return[String(t.status??""),s.join(" ")].filter(Boolean).join(" · ")}case"tool_list_ready":return Array.isArray(t.tools)?d.traces.toolDefs(t.tools.length):"";case"abort":{const n=t.error_code!=null?String(t.error_code):"",s=t.error_message!=null?String(t.error_message):"",o=t.reason!=null?String(t.reason):"";return[n||o,s].filter(Boolean).join(" · ")}case"goal_finished":return`${String(t.outcome)} · rounds=${String(t.rounds)} · tokens=${String(t.tokens_used)}`;case"subagent":return String(t.session_id??"");default:return e.type==="session_meta"?`${String(t.session_id??"")} · ${String(t.model_id??"")}`:""}}function rF(e){const t=e.payload;return t.stop_reason??t.status}const lu="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-100 px-2.5 py-2 text-xs dark:bg-gray-800/70";function aF({p:e}){const t=e.request??{},n=e.session??{},s=(o,c)=>a.jsxs("tr",{children:[a.jsx("td",{className:"pr-3 text-gray-400",children:o}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.cache_read??0)}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.cache_write??0)}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.output??0)}),a.jsx("td",{className:"text-right font-mono",children:It(c.total??0)})]});return a.jsxs("table",{className:"text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-gray-400",children:[a.jsx("th",{}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"cacheRead"}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"cacheWrite"}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"output"}),a.jsx("th",{className:"text-right font-normal",children:"total"})]})}),a.jsxs("tbody",{children:[s("request",t),s("session",n)]})]})}const pM="cursor-pointer text-xs font-medium text-gray-500 marker:text-gray-400 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200";function sF({p:e}){const t=[["session_id",String(e.session_id??"")],["source",String(e.source??"")],["model_id",String(e.model_id??"")],["context_window",String(e.model_context_window??"")],...typeof e.thinking_level=="string"&&e.thinking_level?[["thinking_level",e.thinking_level]]:[],["agent_state",String(e.agent_state??"")],["workspace",String(e.workspace??"")]],n=String(e.system_prompt??"");return a.jsxs("div",{className:"space-y-2.5",children:[a.jsx("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-xs",children:t.map(([s,o])=>a.jsxs(y.Fragment,{children:[a.jsx("dt",{className:"text-gray-400",children:s}),a.jsx("dd",{className:"min-w-0 break-all font-mono text-gray-700 dark:text-gray-300",children:o||"—"})]},s))}),n.trim()&&a.jsxs("details",{children:[a.jsx("summary",{className:pM,children:d.traces.systemPrompt}),a.jsx("div",{className:"md-body mt-1.5 max-h-96 overflow-auto rounded bg-gray-100 px-2.5 py-2 text-sm leading-relaxed text-gray-700 dark:bg-gray-800/70 dark:text-gray-300",children:a.jsx(Zu,{remarkPlugins:Ju,children:n})})]})]})}function iF({schema:e}){const t=e.properties!==null&&typeof e.properties=="object"?e.properties:null;if(!t||Object.keys(t).length===0)return a.jsx("pre",{className:`${lu} mt-1`,children:JSON.stringify(e,null,2)});const n=new Set(Array.isArray(e.required)?e.required.map(String):[]),s=o=>{if(Array.isArray(o.enum))return o.enum.map(String).join(" | ");const c=typeof o.type=="string"?o.type:"object";if(c==="array"){const u=o.items;return`${u!==null&&typeof u=="object"?s(u):"unknown"}[]`}return c};return a.jsx("table",{className:"mt-1 w-full text-xs",children:a.jsx("tbody",{children:Object.entries(t).map(([o,c])=>a.jsxs("tr",{className:"align-top",children:[a.jsxs("td",{className:"whitespace-nowrap pr-3 font-mono text-gray-700 dark:text-gray-300",children:[o,n.has(o)&&a.jsx(kN,{label:d.traces.requiredParam})]}),a.jsx("td",{className:"whitespace-nowrap pr-3 font-mono text-gray-400 dark:text-gray-500",children:s(c)}),a.jsx("td",{className:"text-gray-500 dark:text-gray-400",children:typeof c.description=="string"?c.description:""})]},o))})})}function oF({p:e}){const t=Array.isArray(e.tools)?e.tools:[];return t.length===0?a.jsx("p",{className:"text-xs text-gray-400",children:"—"}):a.jsx("ul",{className:"divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800",children:t.map((n,s)=>a.jsxs("li",{className:"px-2.5 py-1.5 text-xs",children:[a.jsx("span",{className:"font-mono font-semibold text-gray-700 dark:text-gray-300",children:n.name??"—"}),n.description&&a.jsx("p",{className:"mt-0.5 text-gray-500 dark:text-gray-400",children:n.description}),n.parameters!==null&&typeof n.parameters=="object"&&a.jsxs("details",{className:"mt-1",children:[a.jsx("summary",{className:pM,children:d.traces.toolParams}),a.jsx(iF,{schema:n.parameters})]})]},s))})}function lF({msg:e}){const t=e.payload;if(e.type==="session_meta")return a.jsx(sF,{p:t});if(t.type==="tool_list_ready")return a.jsx(oF,{p:t});switch(t.type){case"text":case"thinking":{const n=String(t.text??t.thinking??"");return n.trim()?a.jsx("div",{className:"md-body text-sm leading-relaxed text-gray-700 dark:text-gray-300",children:a.jsx(Zu,{remarkPlugins:Ju,children:n})}):a.jsx("p",{className:"text-xs text-gray-400",children:"—"})}case"image_url":return a.jsx(Ys,{src:String(t.image_url??""),alt:"trace",className:"max-h-48 max-w-full rounded-md"});case"inline_data":return a.jsx(Ys,{src:`data:${String(t.mime_type??"")};base64,${String(t.data??"")}`,alt:"trace",className:"max-h-48 max-w-full rounded-md"});case"tool_call":return a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("p",{className:"font-mono text-xs font-semibold text-gray-700 dark:text-gray-300",children:String(t.name??"")}),a.jsx("pre",{className:lu,children:String(t.arguments??"")})]});case"tool_call_output":{const n=Array.isArray(t.images)?t.images:[];return n.length===0?a.jsx("pre",{className:lu,children:String(t.output??"")}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("pre",{className:lu,children:String(t.output??"")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:n.map((s,o)=>a.jsx(Ys,{src:s,alt:"trace",className:"max-h-48 max-w-full rounded-md"},o))})]})}case"token_usage":return a.jsx(aF,{p:t});default:return a.jsx("pre",{className:lu,children:JSON.stringify(t,null,2)})}}function cF({msg:e,rowKey:t,matched:n,onHighlight:s}){const[o,c]=y.useState(!1),u=e.payload.type??e.type,f=rF(e);return a.jsxs("li",{"data-trace-row":t,children:[a.jsxs("button",{type:"button",onClick:()=>c(p=>!p),onMouseEnter:()=>s?.({ts:e.timestamp,rowKey:t}),onMouseLeave:()=>s?.(null),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left transition-colors duration-150 ${n?"bg-amber-50 dark:bg-amber-950/40":"hover:bg-gray-50 dark:hover:bg-gray-800/50"}`,children:[a.jsx("span",{className:"shrink-0 font-mono text-[11px] text-gray-400",children:PI(e.timestamp)}),a.jsx(tF,{type:u}),a.jsx(On,{tone:ZH(e.type),children:u}),e.origin&&e.origin.length>0&&a.jsx(On,{tone:"brand",children:"origin"}),a.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-gray-500 dark:text-gray-400",children:nF(e)})]}),o&&a.jsxs("div",{className:"border-t border-gray-100 bg-gray-50/60 px-3 py-2 dark:border-gray-800 dark:bg-gray-900/40",children:[a.jsx(lF,{msg:e}),f&&a.jsx("div",{className:"mt-1.5 flex justify-end",children:a.jsx(On,{tone:P6(f),children:f})})]})]})}function uF(e){return e?.compaction!==!0?null:d.chat.compactionTitle(e.compactionMode??"summarize")}const E2=()=>({cacheRead:0,cacheWrite:0,output:0}),dF=2500,A2=(e,t)=>`${e}-${t}`;function Vs({label:e,value:t}){return a.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-0.5",children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400",children:e}),a.jsx("span",{className:"truncate font-mono text-sm font-semibold tabular-nums",children:t})]})}const hM=e=>e.cacheRead+e.cacheWrite,gM=e=>JC(e.cacheRead,e.cacheWrite),xM="flex shrink-0 items-center font-mono text-[11px] tabular-nums text-gray-500 dark:text-gray-400";function Qc({icon:e,value:t,label:n}){return a.jsxs("span",{title:n,"aria-label":n,className:`${xM} gap-1`,children:[a.jsx(Oe,{d:e,className:"text-gray-400"}),t]})}function mF({buckets:e}){const t=hM(e),n=`${d.traces.cacheHit} ${It(e.cacheRead)} · ${d.traces.hitRate} ${Lf(gM(e))}`;return a.jsxs("span",{"aria-label":`${d.traces.taskInput} ${It(t)} · ${n}`,className:xM,children:[a.jsxs("span",{title:d.traces.taskInput,className:"flex items-center gap-1",children:[a.jsx(Oe,{d:Xn.input,className:"text-gray-400"}),It(t)]}),a.jsxs("span",{title:n,className:"ml-1 flex items-center gap-0.5 text-gray-400",children:[a.jsx("span",{children:"("}),a.jsx(Oe,{d:Xn.cacheHit}),a.jsx("span",{children:It(e.cacheRead)}),a.jsx("span",{children:")"})]})]})}function fF({projectId:e,agentId:t,sessionId:n,index:s,highlight:o,onHighlight:c}){const{currency:u}=as(),[f,p]=y.useState(null),[h,x]=y.useState([]),[g,v]=y.useState(0),[w,S]=y.useState(0),[C,N]=y.useState(null),[T,_]=y.useState(null),[R,D]=y.useState(new Set),[z,E]=y.useState(null),L=y.useRef(null),F=y.useRef(null);y.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]),y.useEffect(()=>{p(null),x([]),_(null),D(new Set),E(null);let A=!1;return Promise.all([xA(e,t,n,s),gA(e,t,n,s,0,1e3),Ml(e).catch(()=>null)]).then(([Q,j,U])=>{A||(p(Q),x(j.events),v(j.offset),S(j.total),N(U))}).catch(Q=>{A||_(Ae(Q))}),()=>{A=!0}},[e,t,n,s]);const V=y.useMemo(()=>{const A=h.find(j=>j.type==="session_meta"),Q=A?A.payload:void 0;if(!(!Q?.model_id||!Q.provider))return C?.models.find(j=>j.modelId===Q.model_id&&j.provider===Q.provider)?.pricing},[h,C]),P=A=>V?(A.cacheRead*V.cacheRead+A.cacheWrite*V.cacheWrite+A.output*V.output)/1e6:null,B=y.useMemo(()=>{const A=h.find(Q=>Q.type==="session_meta");return TT(A?A.payload.model_context_window:void 0)},[h]),{tasks:Y,global:q,statsByTask:K,globalLlmMs:H}=y.useMemo(()=>{const A={buckets:E2(),toolCalls:0},Q=new Map;if(!f)return{tasks:[],global:A,statsByTask:Q,globalLlmMs:0};const j=new Map;for(const Se of f.tasks){const Me=Date.parse(Se.startTs),ze=Date.parse(Se.endTs);Number.isFinite(Me)&&Number.isFinite(ze)&&j.set(Se.taskIndex,{min:Me,max:ze})}const U=new Map,ee=Se=>{let Me=U.get(Se);if(!Me){const ze=j.get(Se);Me={taskIndex:Se,segments:[],spans:[],otherSpans:[],messages:[],toolCalls:0,durationMs:ze?Math.max(0,ze.max-ze.min):0},U.set(Se,Me)}return Me};for(const Se of f.tasks)ee(Se.taskIndex);for(const Se of f.modelSegments)ee(Se.taskIndex).segments.push(Se);for(const Se of f.toolSpans){const Me=ee(Se.taskIndex);Me.spans.push(Se),Me.toolCalls+=1}for(const Se of f.otherSpans??[])ee(Se.taskIndex).otherSpans.push(Se);const re=Se=>{for(const Me of f.tasks)if(Se>=Me.messageFrom&&Se<=Me.messageTo)return Me.taskIndex;return null};for(let Se=0;Se<h.length;Se++){const Me=h[Se];if(Me.origin&&Me.origin.length>0)continue;const ze=re(g+Se);ze!==null&&ee(ze).messages.push(Me)}A.toolCalls=f.toolSpans.length;const ke=new Map(f.tasks.map(Se=>[Se.taskIndex,Se]));for(const Se of f.tasks)A.buckets.cacheRead+=Se.tokens.cacheRead,A.buckets.cacheWrite+=Se.tokens.cacheWrite,A.buckets.output+=Se.tokens.output;const be=f.tasks.reduce((Se,Me)=>Se+Me.llmMs,0);return{tasks:[...U.values()].sort((Se,Me)=>Se.taskIndex-Me.taskIndex),global:A,statsByTask:ke,globalLlmMs:be}},[f,h,g]);if(T)return a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:T});if(!f)return a.jsx(on,{className:"h-40"});const $=f.elapsedMs,X=A=>D(Q=>{const j=new Set(Q);return j.has(A)?j.delete(A):j.add(A),j}),le=A=>{for(const Q of Y){const j=Q.messages.findIndex(U=>U.timestamp===A);if(j>=0)return A2(Q.taskIndex,j)}return null},ie=o?.rowKey??(o?.ts!==void 0?le(o.ts):null),I=A=>{const Q=le(A);Q!==null&&(E(Q),requestAnimationFrame(()=>{L.current?.querySelector(`[data-trace-row="${Q}"]`)?.scrollIntoView({block:"center",behavior:"smooth"})}),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>E(null),dF))};return a.jsxs("div",{ref:L,className:"space-y-4",children:[a.jsxs("div",{className:"rounded-md border border-gray-200 p-3 dark:border-gray-800",children:[a.jsx("p",{className:"mb-2 text-xs font-semibold text-gray-500",children:d.traces.globalSummary}),a.jsxs("div",{className:"grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-3",children:[a.jsxs("div",{children:[a.jsx(Vs,{label:d.traces.tasksLabel,value:String(f.tasks.length)}),a.jsx(Vs,{label:d.traces.toolCalls,value:String(q.toolCalls)}),a.jsx(Vs,{label:d.traces.compactions,value:String(f.compactionCount)})]}),a.jsxs("div",{children:[a.jsx(Vs,{label:d.chat.statInput,value:It(hM(q.buckets))}),a.jsx(Vs,{label:d.traces.cacheHit,value:`${It(q.buckets.cacheRead)} · ${Lf(gM(q.buckets))}`}),a.jsx(Vs,{label:d.chat.statOutput,value:It(q.buckets.output)})]}),a.jsxs("div",{children:[a.jsx(Vs,{label:d.common.cost,value:rs(P(q.buckets),u)}),a.jsx(Vs,{label:d.chat.statElapsed,value:Pn(Math.max(0,$))}),a.jsx(Vs,{label:d.chat.statTps,value:sf(v0(q.buckets.output,H))})]})]})]}),Y.map(A=>{const Q=!R.has(A.taskIndex),j=K.get(A.taskIndex),U=j?.context,ee=j?.tokens??E2(),re=uF(j);return a.jsxs("div",{className:"overflow-hidden rounded-md border border-gray-200 dark:border-gray-800",children:[a.jsxs("button",{type:"button",onClick:()=>X(A.taskIndex),"aria-expanded":Q,className:"flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800/60",children:[a.jsx(Zn,{open:Q,size:13,className:"text-gray-400"}),a.jsx("span",{className:"shrink-0 text-sm font-semibold",children:d.traces.task(A.taskIndex+1)}),re!==null&&a.jsx("span",{className:"shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400",children:re}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-1",children:[a.jsx(Qc,{icon:Xn.toolCalls,value:String(A.toolCalls),label:d.traces.toolCalls}),a.jsx(mF,{buckets:ee}),a.jsx(Qc,{icon:Xn.output,value:It(ee.output),label:d.traces.taskOutput}),a.jsx(Qc,{icon:Xn.cost,value:rs(P(ee),u),label:`${d.common.cost}(${u})`}),a.jsx(Qc,{icon:Xn.elapsed,value:Pn(A.durationMs),label:d.chat.statElapsed}),a.jsx(Qc,{icon:Xn.tps,value:sf(v0(ee.output,j?.llmMs??0)),label:d.chat.statTps})]}),U&&a.jsx(BH,{cacheRead:U.cacheRead,cacheWrite:U.cacheWrite,output:U.output,max:B,size:22})]}),Q&&a.jsxs("div",{className:"space-y-3 p-3",children:[(A.segments.length>0||A.spans.length>0||A.otherSpans.length>0)&&a.jsxs("div",{className:"rounded-md border border-gray-100 p-2 dark:border-gray-800/60",children:[a.jsx("p",{className:"mb-1.5 text-[11px] font-medium text-gray-500",children:d.traces.timeline}),a.jsx(QH,{segments:A.segments,toolSpans:A.spans,otherSpans:A.otherSpans,highlight:o,onHighlight:c,onJump:I,hideTaskLabel:!0})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"mb-1.5 text-[11px] font-medium text-gray-500",children:[d.traces.messages,"(",A.messages.length,")"]}),A.messages.length===0?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.none}):a.jsx("ul",{className:"divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800",children:A.messages.map((ke,be)=>{const ye=A2(A.taskIndex,be);return a.jsx(cF,{msg:ke,rowKey:ye,matched:ye===ie||ye===z,onHighlight:Se=>c(Se)},be)})})]})]})]},A.taskIndex)}),h.length<w&&a.jsx("p",{className:"text-xs text-gray-400",children:d.traces.truncatedNote(h.length,w)})]})}const Wg=6;function pF({session:e,active:t}){const[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(null),[p,h]=y.useState(!1),[x,g]=y.useState(null),[v,w]=y.useState(0),S=y.useRef(t);if(y.useEffect(()=>{t&&!S.current&&w(T=>T+1),S.current=t},[t]),y.useEffect(()=>{if(!t)return;let T=!1;return hA(e.sessionId).then(_=>{T||(s([..._.files].sort((R,D)=>D.index-R.index)),c(null))}).catch(_=>{T||(s([]),c(Ae(_)))}),()=>{T=!0}},[t,v,e.sessionId]),n===null)return a.jsxs("div",{className:"space-y-3 p-4",children:[a.jsx(on,{className:"h-5 w-2/3"}),a.jsx(on,{className:"h-5 w-1/2"})]});if(o!==null)return a.jsx(Fa,{title:d.tracePanel.loadFailed,description:o});if(n.length===0)return a.jsx(Fa,{title:d.tracePanel.empty,description:d.tracePanel.emptyHint});const C=n.find(T=>T.index===u)??n[0],N=p?n:n.slice(0,Wg);return a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[a.jsx("span",{className:"mr-1 text-xs text-gray-400",children:d.traces.filesTitle}),N.map(T=>a.jsxs("button",{type:"button",onClick:()=>f(T.index),title:`${T.date} · ${ju(T.sizeBytes)}`,className:`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${T.index===C.index?"border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100":"border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"}`,children:["#",String(T.index).padStart(3,"0")]},T.index)),!p&&n.length>Wg&&a.jsxs("button",{type:"button",title:d.chat.loadMore,"aria-label":d.chat.loadMore,onClick:()=>h(!0),className:"rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60",children:["+",n.length-Wg]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("p",{className:"min-w-0 flex-1 truncate font-mono text-xs text-gray-400",children:[C.date," · ",ju(C.sizeBytes)]}),a.jsxs("a",{href:yA(e.projectId,e.agentId,e.sessionId,C.index),download:!0,className:"inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60",children:[a.jsx(Hx,{size:Ye.rowLead}),d.traces.exportFile]})]}),a.jsx(fF,{projectId:e.projectId,agentId:e.agentId,sessionId:e.sessionId,index:C.index,highlight:x,onHighlight:g})]})})}function Co({children:e,label:t,title:n,className:s=""}){const[o,c]=y.useState(!1),u=y.useId();return a.jsxs("div",{className:s,children:[a.jsxs("button",{type:"button","aria-expanded":o,"aria-controls":u,...n===void 0&&t!==void 0?{"aria-label":d.common.moreInfoAbout(t)}:{},onClick:()=>c(f=>!f),className:`flex items-center ${Ro.tight} rounded text-xs text-gray-500 transition-colors duration-150 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200`,children:[a.jsx(Zn,{open:o,size:Ye.chevronDense}),n??d.common.moreInfo]}),a.jsx("div",{id:u,hidden:!o,className:"mt-1.5 pl-4.5 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:e})]})}const hF="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z",gF="M3 3l18 18M10.6 5.1A11 11 0 0 1 12 5c6.4 0 10 7 10 7a17.6 17.6 0 0 1-3.2 3.9M6.6 6.6C4 8.3 2 12 2 12s3.6 7 10 7a10 10 0 0 0 4.8-1.2M9.9 9.9a3 3 0 0 0 4.2 4.2";function ts({label:e,hint:t,info:n,infoLabel:s,error:o,invalid:c,required:u,size:f="base",className:p,id:h,...x}){const[g,v]=y.useState(!1),w=g?d.auth.hidePassword:d.auth.showPassword,S=y.useId(),C=y.useId(),N=h??C;return a.jsx(Vu,{label:e,hint:t,error:o,errorId:S,required:u,info:n,infoLabel:s,controlId:N,children:a.jsxs("div",{className:"relative",children:[a.jsx(at,{...x,id:n!==void 0?N:h,required:u,size:f,type:g?"text":"password",invalid:!!o||!!c,"aria-describedby":o?S:void 0,className:`${f==="sm"?"pr-8":"pr-10"} ${p??""}`}),a.jsx("button",{type:"button","aria-label":w,title:w,tabIndex:-1,onClick:()=>v(T=>!T),className:`absolute inset-y-0 right-0 flex items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300 ${f==="sm"?"w-8":"w-10"}`,children:a.jsx("svg",{width:f==="sm"?14:16,height:f==="sm"?14:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a.jsx("path",{d:g?gF:hF})})})]})})}function ws({options:e,value:t,onChange:n,cols:s=3}){return a.jsx("div",{className:`grid ${s===2?"grid-cols-2":"grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`,children:e.map(o=>a.jsx("button",{type:"button",onClick:()=>n(o.value),className:`rounded px-1 py-1 text-xs transition-colors duration-150 ${t===o.value?"bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"}`,children:o.label},o.value))})}function js({checked:e,onChange:t,disabled:n,className:s,...o}){return a.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:n,onClick:()=>t(!e),className:"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full inset-ring inset-ring-black/10 dark:inset-ring-white/10 transition-colors duration-200 ease-out focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-bg)]/40 disabled:cursor-not-allowed disabled:opacity-60 "+(e?"bg-[var(--accent-bg)]":"bg-gray-200 dark:bg-gray-700")+` ${s??""}`,...o,children:a.jsx("span",{"aria-hidden":!0,className:`inline-block size-4 rounded-full border border-black/10 bg-white transition-transform duration-200 ease-out ${e?"translate-x-[18px]":"translate-x-0.5"}`})})}const yM="https://open.feishu.cn",xF=/^\d+:[A-Za-z0-9_-]{5,}$/;function yF(e="feishu"){return{channel:e,feishu:{appId:"",appSecret:"",baseDomain:yM,clearSecret:!1},telegram:{botToken:"",clearToken:!1}}}function _2(e){const t=e.find(s=>s.enabled)?.channel,n=yF(t??e[0]?.channel??"feishu");for(const s of e)s.channel==="feishu"&&(n.feishu={appId:s.appId,appSecret:"",baseDomain:s.baseDomain,clearSecret:!1});return n}function bF(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function vF(e,t){const n={};if(e.channel==="telegram"){const f=e.telegram.botToken.trim(),p=f===""&&e.telegram.clearToken&&t;return f===""&&!t?n.botToken="required":f!==""&&!xF.test(f)&&(n.botToken="token_invalid"),Object.keys(n).length>0?{ok:!1,errors:n}:{ok:!0,channel:"telegram",body:{...f!==""?{botToken:f}:{},...p?{clearBotToken:!0}:{}}}}const s=e.feishu.appId.trim();s===""&&(n.appId="required");const o=e.feishu.appSecret.trim(),c=o===""&&e.feishu.clearSecret&&t;o===""&&!t&&(n.appSecret="required");const u=e.feishu.baseDomain.trim()||yM;return bF(u)||(n.baseDomain="url_invalid"),Object.keys(n).length>0?{ok:!1,errors:n}:{ok:!0,channel:"feishu",body:{appId:s,...o!==""?{appSecret:o}:{},...c?{clearAppSecret:!0}:{},baseDomain:u}}}function kF(e){if(e.channel==="telegram"){const o=e.telegram.botToken.trim();return{channel:"telegram",body:{...o!==""?{botToken:o}:{}}}}const t=e.feishu.appId.trim(),n=e.feishu.appSecret.trim(),s=e.feishu.baseDomain.trim();return{channel:"feishu",body:{...t!==""?{appId:t}:{},...n!==""?{appSecret:n}:{},...s!==""?{baseDomain:s}:{}}}}function wF(e,t){return e.channel==="telegram"?e.telegram.botToken.trim()!==""||e.telegram.clearToken:e.feishu.appId!==t.feishu.appId||e.feishu.baseDomain!==t.feishu.baseDomain||e.feishu.appSecret.trim()!==""||e.feishu.clearSecret}function SF(e,t){return e.channel==="telegram"?e.telegram.botToken.trim()!==""||t:e.feishu.appId.trim()!==""&&e.feishu.appSecret.trim()!==""||t}const jF=3e3,bM={feishu:{tutorial:"https://open.feishu.cn/document/develop-an-echo-bot/introduction",console:"https://open.feishu.cn/app"},telegram:{tutorial:"https://core.telegram.org/bots/tutorial",console:"https://core.telegram.org/bots/api"}},CF={disconnected:"muted",connecting:"busy",connected:"success",error:"danger"};function Rm(e){if(e!==void 0)return e==="required"?d.common.requiredField:e==="token_invalid"?d.telegram.invalidToken:d.feishu.invalidDomain}const Uu={secretConfigured:!1,secretMasked:null,enabled:!1,status:{state:"disconnected"},lastChatKnown:!1};function vM(e,t){if(e===null)return{...Uu,status:t};const n=e.channel==="telegram"?e.botTokenMasked:e.appSecretMasked;return{secretConfigured:n!==void 0,secretMasked:n??null,enabled:e.enabled,status:t,lastChatKnown:e.lastChatKnown}}function NF(e){const t={feishu:Uu,telegram:Uu};for(const n of e.bindings)t[n.binding.channel]=vM(n.binding,n.status);return t}function kM(e,t){const{poll:n,onChanged:s,onLoadFailed:o}=t,[c,u]=y.useState(null),[f,p]=y.useState(null),[h,x]=y.useState({feishu:Uu,telegram:Uu}),[g,v]=y.useState({}),[w,S]=y.useState(!1),[C,N]=y.useState(!1),[T,_]=y.useState(!1),[R,D]=y.useState(!1),z=y.useRef(null);y.useEffect(()=>{let I=!1,A=z.current===e;const Q=async U=>{try{const ee=await YE(e);if(I)return;if(x(NF(ee)),U){const re=_2(ee.bindings.map(ke=>ke.binding));u(re),p(re),A=!0}}catch(ee){if(I)return;U&&(A=!0,Be(Ae(ee)),o?.())}};z.current!==e&&(z.current=e,u(null),p(null),Q(!0));const j=n?setInterval(()=>{Q(!1)},jF):null;return()=>{I=!0,j!==null&&clearInterval(j),!A&&z.current===e&&(z.current=null)}},[e,n]);const E=I=>{u(A=>A&&{...A,...I}),v({})},L=I=>{E({channel:I})},F=c?.channel??"feishu",V=h[F],P=h.feishu.enabled?"feishu":h.telegram.enabled?"telegram":null,B=P!==null&&P!==F,Y=c!==null&&f!==null&&wF(c,f),q=(I,A,Q)=>{if(x(j=>({...j,[I]:vM(A,Q)})),A!==null){const j=_2([A]),U=I==="feishu"?{feishu:j.feishu}:{telegram:j.telegram};u(ee=>ee&&{...ee,...U}),p(ee=>ee&&{...ee,...U})}},K=async()=>{if(c){_(!0);try{const I=kF(c);if(I.channel==="telegram"){const A=await eA(e,I.body);if(A.ok){const Q=A.latencyMs??0;yt(A.botUsername!==void 0?d.messaging.testOkAs(A.botUsername,Q):d.messaging.testOk(Q))}else Be(d.messaging.testFail(A.error??d.common.unknownError))}else{const A=await JE(e,I.body);A.ok?yt(d.messaging.testOk(A.latencyMs??0)):Be(d.messaging.testFail(A.error??d.common.unknownError))}}catch(I){Be(d.messaging.testFail(Ae(I)))}finally{_(!1)}}},H=async()=>{D(!0);try{await tA(e,F),yt(d.messaging.testMessageSent)}catch(I){Be(Ae(I))}finally{D(!1)}},$=async()=>{if(!c)return;const I=vF(c,h[c.channel].secretConfigured);if(!I.ok){v(I.errors);return}S(!0);try{const A=I.channel==="telegram"?await QE(e,I.body):await XE(e,I.body);q(I.channel,A.binding,A.status),yt(d.common.saved)}catch(A){Be(Ae(A))}finally{S(!1)}},X=async I=>{N(!0);try{const A=await ZE(e,F,I);q(F,A.binding,A.status),s?.(e,I&&A.binding?.enabled===!0?F:null)}catch(A){Be(Ae(A))}finally{N(!1)}},le=!V.enabled&&(B||!V.secretConfigured||Y),ie=!V.enabled&&P!==null&&B?d.messaging.otherEnabledHint(d.messaging.channelName[P]):!V.enabled&&!V.secretConfigured?d.messaging.credentialMissingHint:!V.enabled&&Y?d.messaging.saveBeforeEnable:null;return{form:c,patchForm:E,selectChannel:L,channels:h,fieldErrors:g,dirty:Y,busy:w,toggling:C,testing:T,sendingTest:R,testable:c!==null&&SF(c,V.secretConfigured),toggleBlocked:le||C||w,toggleHint:ie,save:$,toggleEnabled:X,testConnection:K,sendTestMessage:H}}function cx({href:e,label:t}){return a.jsxs("a",{href:e,target:"_blank",rel:"noreferrer noopener",className:"shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300",children:[t," ↗"]})}function R2({label:e,required:t,link:n,children:s}){return a.jsxs("div",{className:"block",children:[a.jsxs("span",{className:"mb-1 flex items-baseline justify-between gap-2",children:[a.jsx(Yn,{block:!1,...t?{required:!0}:{},children:e}),n]}),s]})}function I2({masked:e,clearLabel:t,checked:n,enabled:s,onChange:o}){return a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400",children:[a.jsx("span",{className:"font-mono",children:e}),a.jsxs("label",{className:`flex items-center gap-1.5 ${s?"cursor-not-allowed opacity-60":""}`,children:[a.jsx("input",{type:"checkbox",checked:n,disabled:s,onChange:c=>o(c.target.checked)}),t]}),s&&a.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:d.messaging.disableBeforeClearHint})]})}function wM({b:e}){const{form:t}=e;if(!t)return null;const n=t.channel,s=e.channels[n],o=bM[n];return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{role:"group","aria-label":d.messaging.channelLabel,children:a.jsx(ws,{cols:2,options:[{value:"feishu",label:d.messaging.channelName.feishu},{value:"telegram",label:d.messaging.channelName.telegram}],value:n,onChange:c=>e.selectChannel(c)})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[a.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[a.jsx(js,{checked:s.enabled,disabled:e.toggleBlocked,onChange:c=>{e.toggleEnabled(c)}}),d.messaging.enabled]}),a.jsx("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:d.messaging.statusLabel}),a.jsx("span",{...s.status.lastError!==void 0?{title:s.status.lastError}:{},className:`font-medium ${sn[CF[s.status.state]]}`,children:d.messaging.status[s.status.state]}),s.status.state==="error"&&s.status.lastError!==void 0&&a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500",children:s.status.lastError})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(ge,{size:"sm",disabled:e.testing||e.busy||!e.testable,onClick:()=>{e.testConnection()},children:e.testing?d.messaging.testing:d.messaging.test}),a.jsx(ge,{size:"sm",disabled:e.sendingTest||e.busy||s.status.state!=="connected"||!s.lastChatKnown,...s.lastChatKnown?{}:{title:n==="telegram"?d.telegram.testMessageNoChat:d.feishu.testMessageNoChat},onClick:()=>{e.sendTestMessage()},children:e.sendingTest?d.messaging.sendingTestMessage:d.messaging.sendTestMessage})]}),e.toggleHint!==null&&a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:e.toggleHint}),n==="telegram"?a.jsxs(a.Fragment,{children:[a.jsx(R2,{label:d.telegram.botToken,required:!s.secretConfigured,link:a.jsx(cx,{href:o.console,label:d.messaging.console}),children:a.jsx(ts,{size:"sm","aria-label":d.telegram.botToken,...s.secretConfigured?{placeholder:d.telegram.botTokenKeepHint}:{},error:Rm(e.fieldErrors.botToken),value:t.telegram.botToken,onChange:c=>e.patchForm({telegram:{botToken:c.target.value,clearToken:!1}}),autoComplete:"off"})}),s.secretMasked!==null&&t.telegram.botToken===""&&a.jsx(I2,{masked:s.secretMasked,clearLabel:d.telegram.clearToken,checked:t.telegram.clearToken,enabled:s.enabled,onChange:c=>e.patchForm({telegram:{...t.telegram,clearToken:c}})})]}):a.jsxs(a.Fragment,{children:[a.jsx(R2,{label:d.feishu.appId,required:!0,link:a.jsx(cx,{href:o.console,label:d.messaging.console}),children:a.jsx(at,{size:"sm","aria-label":d.feishu.appId,error:Rm(e.fieldErrors.appId),value:t.feishu.appId,onChange:c=>e.patchForm({feishu:{...t.feishu,appId:c.target.value}}),className:"font-mono",placeholder:"cli_xxxxxxxxxxxxxxxx",autoComplete:"off"})}),a.jsx(ts,{size:"sm",label:d.feishu.appSecret,...s.secretConfigured?{placeholder:d.feishu.appSecretKeepHint}:{required:!0},error:Rm(e.fieldErrors.appSecret),value:t.feishu.appSecret,onChange:c=>e.patchForm({feishu:{...t.feishu,appSecret:c.target.value,clearSecret:!1}}),autoComplete:"off"}),s.secretMasked!==null&&t.feishu.appSecret===""&&a.jsx(I2,{masked:s.secretMasked,clearLabel:d.feishu.clearSecret,checked:t.feishu.clearSecret,enabled:s.enabled,onChange:c=>e.patchForm({feishu:{...t.feishu,clearSecret:c}})}),a.jsx(at,{size:"sm",label:d.feishu.baseDomain,hint:d.feishu.baseDomainHint,error:Rm(e.fieldErrors.baseDomain),value:t.feishu.baseDomain,onChange:c=>e.patchForm({feishu:{...t.feishu,baseDomain:c.target.value}}),className:"font-mono",placeholder:"https://open.feishu.cn",autoComplete:"off"})]})]})}function SM({channel:e}){const t=e==="telegram"?d.telegram:d.feishu,n=bM[e];return a.jsxs("div",{className:"space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800",children:[a.jsxs(Co,{title:d.messaging.faqSetupTitle,children:[a.jsx("ol",{className:"list-decimal space-y-1 pl-4",children:t.setupSteps.map(s=>a.jsx("li",{children:s},s))}),a.jsx("p",{className:"mt-1.5",children:a.jsx(cx,{href:n.tutorial,label:d.messaging.tutorial})})]}),a.jsx(Co,{title:d.messaging.faqWhatTitle,children:a.jsx("p",{children:t.intro})}),a.jsx(Co,{title:d.messaging.faqTroubleTitle,children:a.jsxs("ul",{className:"list-disc space-y-1 pl-4",children:[a.jsx("li",{children:d.messaging.troubleNoChat}),a.jsx("li",{children:d.messaging.troubleConnError})]})})]})}function TF({sessionId:e,active:t}){const n=kM(e,{poll:t});return a.jsx("div",{className:"h-full overflow-y-auto p-3",children:n.form===null?a.jsxs("div",{className:"space-y-2",children:[a.jsx(on,{className:"h-5 w-40"}),a.jsx(on,{className:"h-24 w-full"})]}):a.jsxs("div",{className:"space-y-3",children:[a.jsx(wM,{b:n}),a.jsx("div",{className:"flex items-center justify-end gap-2",children:a.jsx(ge,{variant:"primary",size:"sm",disabled:n.busy,onClick:()=>{n.save()},children:n.busy?d.common.saving:d.common.save})}),a.jsx(SM,{channel:n.form.channel})]})})}const MF={dark:!0,surface:"bg-gray-950 text-gray-100",border:"border-gray-800",iconButton:"text-gray-400 hover:bg-gray-800 hover:text-gray-200",grip:"text-gray-600",tabActive:"bg-gray-800 text-gray-100",tabIdle:"text-gray-400 hover:bg-gray-800 hover:text-gray-200",tabKill:"bg-gray-800 hover:bg-gray-700",muted:"text-gray-400",success:"text-emerald-400",attention:"text-amber-400",danger:"text-red-400",outlineButton:"border-gray-700 text-gray-300 hover:bg-gray-800"},EF={dark:!1,surface:"bg-white text-gray-900",border:"border-gray-200",iconButton:"text-gray-500 hover:bg-gray-100 hover:text-gray-800",grip:"text-gray-400",tabActive:"bg-gray-100 text-gray-900",tabIdle:"text-gray-500 hover:bg-gray-100 hover:text-gray-800",tabKill:"bg-gray-100 hover:bg-gray-200",muted:"text-gray-500",success:"text-emerald-600",attention:"text-amber-600",danger:"text-red-600",outlineButton:"border-gray-300 text-gray-600 hover:bg-gray-100"};function jM(){return as().terminalDark?MF:EF}const xu=new Map,wf=new Map,ux=new Set;function CM(){for(const e of[...ux])e()}function AF(e){return ux.add(e),()=>ux.delete(e)}const NM={status:"connecting",info:null};function _F(e){return(e!==null?wf.get(e):void 0)??NM}function TM(e){let t=xu.get(e);return t||(t=document.createElement("div"),t.className="flex h-full w-full min-h-0 flex-col",xu.set(e,t)),t}function L2(e,t){const n=wf.get(e)??{...NM};wf.set(e,{...n,...t}),CM()}function RF(e){return async()=>{const t=await vf(`/api/terminals/${encodeURIComponent(e)}`);if(!t)throw new Error("Terminal no longer exists.");return t}}function IF(){const e=[];for(const t of["right","bottom"]){if(!Ba(t))continue;const n=CB(t);if(n===null||!n.startsWith("terminal:"))continue;const s=n.slice(9);e.includes(s)||e.push(s)}return e}let Im=[];function LF(){const e=IF();return(e.length!==Im.length||e.some((t,n)=>t!==Im[n]))&&(Im=e),Im}function OF(){const e=y.useSyncExternalStore(Zf,LF);return y.useEffect(()=>{for(const t of[...xu.keys()])e.includes(t)||(xu.get(t)?.remove(),xu.delete(t),wf.delete(t));CM()},[e]),a.jsx(a.Fragment,{children:e.map(t=>ss.createPortal(a.jsx(YT,{ensure:RF(t),onStatus:n=>{L2(t,{status:n}),n==="exited"&&Xs()},onInfo:n=>{L2(t,{info:n}),Xs()},onTitle:n=>XB(t,n),className:"min-h-0 flex-1 overflow-hidden"},t),TM(t),t))})}const ep=320,Ky="penguin.panelWidth";function Wy(e){return Math.max(ep,Math.min(720,Math.round(e*.5)))}function MM(e){return Math.min(Wy(e),Math.max(ep,Math.round(e*.4)))}function DF(){try{const e=Number(localStorage.getItem(Ky));return Number.isFinite(e)&&e>0?e:null}catch{return null}}function $F(){const e=DF();return e===null?MM(window.innerWidth):Math.min(Wy(window.innerWidth),Math.max(ep,Math.round(e)))}const Pu=zl(()=>({width:null}));function Yy(){const{width:e}=Pu.getState();if(e!==null)return e;const t=$F();return Pu.setState({width:t}),t}function EM(e){e!==Pu.getState().width&&Pu.setState({width:e})}function UF(){return Yy()}function PF(){return Bl(Pu,()=>Yy())}function zF(e){EM(Math.min(Wy(window.innerWidth),Math.max(ep,Math.round(e))))}function BF(){try{localStorage.setItem(Ky,String(Math.round(Yy())))}catch{}}function HF(){EM(MM(window.innerWidth));try{localStorage.removeItem(Ky)}catch{}}const FF=.45;function AM(){return document.querySelector("[data-dock-host]")?.getBoundingClientRect()??null}function O2(e,t){const n=document.elementFromPoint(e,t)?.closest?.("[data-dock-pos]");if(n?.dataset.dockPos)return n.dataset.dockPos;const s=AM();if(!s||e<s.left||e>s.right||t<s.top||t>s.bottom)return null;const o=[["right",(s.right-e)/s.width],["bottom",(s.bottom-t)/s.height]];o.sort((u,f)=>u[1]-f[1]);const c=o[0];return c[1]<=FF?c[0]:null}function qF(e,t){const n=document.querySelector(`[data-testid='dock'][data-position='${t}']`)?.getBoundingClientRect()??null;if(t==="bottom"){const u=Math.min(n?.height??Math.max(UT,Math.min(Oy*e.height,VT()*e.height)),e.height);return{left:e.left,top:e.bottom-u,width:e.width,height:u}}const s=document.querySelector("[data-dock-row]")?.getBoundingClientRect()??e,o=Math.max(e.top,s.top),c=Math.min(n?.width??UF(),e.width);return{left:e.right-c,top:o,width:c,height:s.bottom-o}}function D2(e){const t=e.candidate===e.position;return a.jsx("div",{"data-dock-pos":e.position,"data-testid":"dock-layout-target",className:`${e.shape} rounded-[3px] border transition-colors duration-100 ${t?"border-sky-400 bg-sky-500/60":"border-gray-400/70 bg-gray-500/10 dark:border-white/30 dark:bg-white/10"}`})}function $2({candidate:e}){const t=AM();return t?ss.createPortal(a.jsxs(a.Fragment,{children:[e&&a.jsx("div",{"data-testid":"dock-layout-preview","data-pos":e,"aria-hidden":!0,className:"pointer-events-none fixed z-[65] rounded-sm border border-sky-400/70 bg-sky-500/20",style:qF(t,e)}),a.jsxs("div",{"data-testid":"dock-layout-widget",className:"fixed z-[70] flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2.5 shadow-lg dark:border-white/20 dark:bg-gray-900/90",style:{left:t.right-108,top:t.bottom-96},children:[a.jsx(D2,{position:"bottom",candidate:e,shape:"h-4 w-9"}),a.jsx(D2,{position:"right",candidate:e,shape:"h-9 w-4.5"})]})]}),document.body):null}const VF="M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";function GF({size:e=Ye.iconButton}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a.jsx("circle",{cx:"5",cy:"12",r:"2.5"}),a.jsx("circle",{cx:"19",cy:"5.5",r:"2.5"}),a.jsx("circle",{cx:"19",cy:"18.5",r:"2.5"}),a.jsx("path",{d:"M7.4 11 16.7 6.6M7.4 13l9.3 4.4"})]})}function wl(e){switch(e){case"agents":return d.chat.openAgents;case"workspace":return d.chat.workspacePanel;case"memory":return d.chat.memoryViewTitle;case"trace":return d.nav.traces;case"messaging":return d.messaging.panelTitle}}function dx(e,t=Ye.iconButton){switch(e){case"agents":return a.jsx(GF,{size:t});case"workspace":return a.jsx(Oe,{d:El,size:t});case"memory":return a.jsx(Oe,{d:VF,size:t});case"trace":return a.jsx(Oe,{d:vs.traces,size:t});case"messaging":return a.jsx(Oe,{d:XC,size:t})}}function Yg(e){const t=y.useRef(e);t.current=e;const n=y.useRef(null);return y.useMemo(()=>({onPointerDown:s=>{if(s.button!==0)return;const o=t.current.begin(s);o!==null&&(n.current={payload:o,x:s.clientX,y:s.clientY,started:!1},s.currentTarget.setPointerCapture(s.pointerId))},onPointerMove:s=>{const o=n.current;if(o){if(!o.started){const c=t.current.threshold??5;if(Math.hypot(s.clientX-o.x,s.clientY-o.y)<c)return;o.started=!0}t.current.onMove?.(s,o.payload)}},onPointerUp:s=>{const o=n.current;n.current=null,s.currentTarget.releasePointerCapture?.(s.pointerId),o&&t.current.onEnd?.(o.payload,o.started)},onPointerCancel:()=>{n.current=null,t.current.onCancel?.()}}),[])}const U2="M12 5v14M5 12h14",KF="M4 5h16v14H4zM4 14h16",WF="M4 5h16v14H4zM14 5v14",YF="M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5";function Lm(e){return a.jsx("button",{type:"button",title:e.label,"aria-label":e.label,"data-testid":e.testId,onClick:e.onClick,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:e.children})}function P2(e){return a.jsxs("div",{"data-testid":"dock-tab","data-tab-id":e.tabId,...e.terminalId!==void 0?{"data-terminal-id":e.terminalId}:{},"data-active":e.active,className:`flex h-6 max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${e.active?"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200":"text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"}`,children:[a.jsxs("button",{type:"button",title:e.title,onClick:e.onSelect,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs",children:[a.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:e.glyph}),a.jsx("span",{className:"min-w-0 truncate",children:e.label}),e.badge&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${Fl.attention}`})]}),a.jsx("button",{type:"button",title:e.closeLabel,"aria-label":`${e.closeLabel}: ${e.label}`,"data-testid":"dock-tab-close",onClick:e.onClose,className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200",children:a.jsx(Hl,{size:10})})]})}function XF({id:e,active:t}){const n=jM(),s=y.useSyncExternalStore(AF,()=>_F(t?e:null)),o=y.useRef(null);return y.useEffect(()=>{const c=o.current;if(!c||!t)return;const u=TM(e);return c.appendChild(u),()=>{u.parentElement===c&&c.removeChild(u)}},[e,t]),a.jsx("div",{ref:o,"data-testid":"dock-terminal-body","data-status":s.status,className:`flex min-h-0 flex-1 flex-col overflow-hidden px-2 py-1 ${n.surface}`})}function z2(e,t,n){return e?`${e.seq??n}: ${KB(e.title)||e.name}`:`${n}: ${t.slice(0,6)}`}function QF({choose:e,chooseTerminal:t,terminalSupported:n,horizontal:s}){const o="flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",c=u=>a.jsxs("button",{type:"button","data-testid":`dock-pick-${u}`,onClick:()=>e(u),className:o,children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:dx(u)}),a.jsx("span",{className:"min-w-0 truncate",children:wl(u)})]},u);return a.jsx("div",{"data-testid":"dock-picker",className:"flex min-h-0 flex-1 items-center justify-center overflow-y-auto p-4",children:a.jsxs("div",{className:s?"flex max-w-full flex-wrap items-center justify-center gap-1":"flex w-60 flex-col gap-0.5",children:[c("agents"),n&&a.jsxs("button",{type:"button","data-testid":"dock-pick-terminal",onClick:t,className:o,children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:a.jsx(Oe,{d:vs.terminal,size:Ye.iconButton})}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.terminal.title}),a.jsx("kbd",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:"Ctrl+`"})]}),c("workspace"),c("memory"),c("trace"),c("messaging")]})})}function B2({view:e,renderPanel:t,panelBadges:n,terminalSupported:s,open:o=!0,animateEntrance:c=!0}){y.useSyncExternalStore(Zf,$y);const u=y.useSyncExternalStore(ZT,QT),f=new Map(u.map(he=>[he.id,he])),{position:p,merged:h,tabs:x,activeKey:g}=e,v=p==="bottom",w=p==="right"?"bottom":"right",[S,C]=y.useState(!1),N=x.find(he=>kn(he)===g)??null,[T,_]=y.useState(null),R=y.useCallback((he,ne)=>{if(he.kind==="terminal"){_({id:he.terminalId,label:ne});return}J0(kn(he))},[]),D=y.useCallback(()=>{T&&(ZB(T.id),J0(`terminal:${T.id}`),_(null))},[T]),z=y.useCallback(()=>{if(N?.kind!=="terminal")return;const he=h?Lu(kn(N))??"bottom":p;eH(N.terminalId,he)},[N,h,p]),E=y.useRef(null);y.useEffect(()=>{g!==null&&E.current?.querySelector(`[data-tab-id="${CSS.escape(g)}"]`)?.scrollIntoView({block:"nearest",inline:"nearest"})},[g,x]),y.useEffect(()=>{const he=E.current;if(!he)return;const ne=oe=>{const J=Math.abs(oe.deltaX)>Math.abs(oe.deltaY)?oe.deltaX:oe.deltaY;J===0||he.scrollWidth<=he.clientWidth||(oe.preventDefault(),he.scrollLeft+=J)};return he.addEventListener("wheel",ne,{passive:!1}),()=>he.removeEventListener("wheel",ne)},[]);const[L,F]=y.useState({active:!1,candidate:null}),V=()=>F({active:!1,candidate:null}),P=Yg({begin:he=>h||he.target.closest("button, [data-testid='dock-tab']")?null:{},onMove:he=>F({active:!0,candidate:O2(he.clientX,he.clientY)}),onEnd:(he,ne)=>{const oe=L.candidate;V(),ne&&oe&&oe!==p&&o2(p,oe)},onCancel:V}),[B,Y]=y.useState({active:!1,candidate:null}),q=()=>Y({active:!1,candidate:null}),K=Yg({threshold:6,begin:he=>{if(h)return null;const ne=he.target;if(ne.closest("[data-testid='dock-tab-close']"))return null;const oe=ne.closest("[data-tab-id]")?.dataset.tabId;return oe?{id:oe}:null},onMove:(he,{id:ne})=>{const oe=he.currentTarget.getBoundingClientRect();if(he.clientY<oe.top-20||he.clientY>oe.bottom+20){Y({active:!0,candidate:O2(he.clientX,he.clientY)});return}Y({active:!1,candidate:null});const J=[...he.currentTarget.querySelectorAll("[data-tab-id]")],ht=J.map(He=>He.dataset.tabId),ve=J.filter(He=>He.dataset.tabId!==ne);let Xe=ve.length;for(let He=0;He<ve.length;He+=1){const Pe=ve[He].getBoundingClientRect();if(he.clientX<Pe.left+Pe.width/2){Xe=He;break}}const Ge=ve.map(He=>He.dataset.tabId);Ge.splice(Xe,0,ne),Ge.some((He,Pe)=>He!==ht[Pe])&&EB(p,Ge)},onEnd:({id:he},ne)=>{const{active:oe,candidate:J}=B;if(q(),!ne){qg(he);return}!oe||!J||J===Lu(he)||MB(he,J)},onCancel:q}),[H,$]=y.useState(!1),X=PF(),le=y.useRef(null),ie=Yg({threshold:0,begin:he=>(he.preventDefault(),$(!0),{}),onMove:he=>{const ne=le.current?.getBoundingClientRect();if(ne)if(v){const oe=document.querySelector("[data-dock-host]")?.getBoundingClientRect();if(!oe||oe.height===0)return;UB((ne.bottom-he.clientY)/oe.height)}else zF(ne.right-he.clientX)},onEnd:()=>{$(!1),v||BF()},onCancel:()=>$(!1)}),[I,A]=y.useState(()=>{const he=document.querySelector("[data-dock-host]");return he instanceof HTMLElement?he.getBoundingClientRect().height:0});y.useLayoutEffect(()=>{if(!v)return;const he=document.querySelector("[data-dock-host]");if(!(he instanceof HTMLElement))return;const ne=()=>A(he.getBoundingClientRect().height);ne();const oe=new ResizeObserver(ne);return oe.observe(he),()=>oe.disconnect()},[v]);const Q=Math.round(Math.min(Oy*I,Math.max(UT,VT()*I))),j=y.useCallback(()=>v?PB():HF(),[v]),U=he=>{C(!1),ho(he,h?void 0:p)},ee=new Set(By(u.map(he=>he.id))),re=u.filter(he=>ee.has(he.id)),ke=a.jsxs(Qn,{open:S,setOpen:C,portal:{direction:"down",align:"right"},menuClass:"w-56",button:a.jsx(Lm,{label:d.dock.addTab,testId:"dock-add",onClick:()=>C(!S),children:a.jsx(Oe,{d:U2,size:Ye.iconButton})}),children:[DT.map(he=>a.jsxs("button",{type:"button","data-testid":`dock-add-${he}`,onClick:()=>U(he),className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:dx(he)}),a.jsx("span",{className:"min-w-0 truncate",children:wl(he)})]},he)),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mx-2 my-1 border-t border-gray-100 dark:border-gray-800"}),a.jsxs("button",{type:"button","data-testid":"dock-add-terminal",onClick:()=>{C(!1),eM(h?void 0:p)},className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:a.jsx(Oe,{d:U2,size:Ye.iconButton})}),a.jsx("span",{className:"min-w-0 truncate",children:d.terminal.newShell})]}),re.map((he,ne)=>a.jsx("button",{type:"button","data-testid":"dock-add-shell","data-terminal-id":he.id,onClick:()=>{C(!1),nd(he.id,h?void 0:p)},className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:a.jsx("span",{className:"min-w-0 truncate",children:z2(he,he.id,ne+1)})},he.id))]})]}),[be,ye]=y.useState(!c);y.useEffect(()=>{if(be)return;let he=0;const ne=requestAnimationFrame(()=>{he=requestAnimationFrame(()=>ye(!0))});return()=>{cancelAnimationFrame(ne),cancelAnimationFrame(he)}},[]);const Se=L.active||B.active,Me=L.active?L.candidate:B.candidate,ze=new Map;x.forEach(he=>{he.kind==="terminal"&&ze.set(he.terminalId,ze.size+1)});const De=a.jsxs("header",{"data-testid":"dock-header",...P,className:`flex shrink-0 items-center gap-2 border-b border-gray-200 px-2 py-1.5 text-xs dark:border-gray-800 ${h?"":"cursor-grab select-none"}`,children:[a.jsx("div",{ref:E,"data-testid":"dock-tab-strip",...K,className:"no-scrollbar flex min-w-0 items-center gap-1 overflow-x-auto",children:x.map(he=>{const ne=kn(he);if(he.kind==="panel")return a.jsx(P2,{tabId:ne,label:wl(he.panel),title:wl(he.panel),glyph:dx(he.panel,Ye.inlineGlyph),active:ne===g,badge:n?.[he.panel]===!0,closeLabel:d.dock.closeTab,onSelect:()=>qg(ne),onClose:()=>R(he,wl(he.panel))},ne);const oe=f.get(he.terminalId),J=z2(oe,he.terminalId,ze.get(he.terminalId)??1);return a.jsx(P2,{tabId:ne,terminalId:he.terminalId,label:J,title:oe?`${oe.name} — ${oe.cwd}`:J,glyph:a.jsx(Oe,{d:vs.terminal,size:Ye.inlineGlyph}),active:ne===g,badge:!1,closeLabel:d.terminal.killShell,onSelect:()=>qg(ne),onClose:()=>R(he,J)},ne)})}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[N?.kind==="terminal"&&a.jsx(Lm,{label:d.terminal.detach,testId:"dock-detach",onClick:z,children:a.jsx(Oe,{d:YF,size:Ye.rowLead})}),ke,!h&&x.length>0&&a.jsx(Lm,{label:p==="right"?d.dock.moveToBottom:d.dock.moveToRight,testId:"dock-move",onClick:()=>o2(p,w),children:a.jsx(Oe,{d:p==="right"?KF:WF,size:Ye.rowLead})}),a.jsx(Lm,{label:d.dock.hideDock,testId:"dock-close",onClick:()=>_B(e),children:a.jsx(Hl,{size:12})})]})]}),ct=x.length===0?a.jsx(QF,{choose:he=>ho(he,h?void 0:p),chooseTerminal:()=>{tM(h?void 0:p)},terminalSupported:s,horizontal:v}):a.jsx("div",{className:"relative min-h-0 flex-1",children:x.map(he=>{const ne=kn(he),oe=ne===g;return a.jsx("div",{className:oe?"flex h-full min-h-0 flex-col":"hidden",children:he.kind==="panel"?t(he.panel,oe):a.jsx(XF,{id:he.terminalId,active:oe})},ne)})}),bt=a.jsx(ln,{open:T!==null,title:d.dock.killConfirmTitle,onClose:()=>_(null),onConfirm:D,confirmLabel:d.terminal.killShell,children:T!==null&&a.jsx("p",{children:d.dock.killConfirmBody(T.label)})});return v?a.jsxs("div",{ref:le,"data-testid":"dock","data-position":"bottom",style:{height:o&&be?Q:0},inert:!o,className:`relative flex w-full shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${o?"border-t border-gray-200 dark:border-gray-800":""} ${H?"":"transition-[height] duration-200"}`,children:[o&&a.jsx("div",{"data-testid":"dock-resizer",role:"separator","aria-orientation":"horizontal","aria-label":d.dock.resize,title:d.dock.resize,...ie,onDoubleClick:j,className:`absolute -top-[3px] left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${H?"bg-sky-500/60":"bg-transparent hover:bg-sky-500/40"}`}),a.jsxs("div",{style:{height:Q},className:"flex min-h-0 shrink-0 flex-col",children:[De,ct]}),Se&&a.jsx($2,{candidate:Me}),bt]}):a.jsxs(a.Fragment,{children:[o&&a.jsx("div",{"data-testid":"dock-resizer",role:"separator","aria-orientation":"vertical","aria-label":d.dock.resize,title:d.dock.resize,...ie,onDoubleClick:j,className:`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 ${H?"bg-sky-500/60":"bg-transparent hover:bg-sky-500/40"}`}),a.jsxs("div",{ref:le,"data-testid":"dock","data-position":"right",style:{width:o&&be?X:0},inert:!o,className:`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${o?"border-l border-gray-200 dark:border-gray-800":""} ${H?"":"transition-[width] duration-200"}`,children:[a.jsxs("div",{style:{width:X},className:"flex min-h-0 flex-1 flex-col",children:[De,ct]}),Se&&a.jsx($2,{candidate:Me}),bt]})]})}const ZF=200;function H2(e){const t=e!==null,n=wB(),s=y.useRef(null);t&&(s.current=e);const o=y.useRef({open:t,instant:n,animate:!0}),c=y.useRef(!1),[,u]=y.useState(0);if(t!==o.current.open){const f=n===o.current.instant;o.current={open:t,instant:n,animate:f},c.current=!t&&f&&s.current!==null}else n!==o.current.instant&&(o.current.instant=n);return y.useEffect(()=>{if(t||!c.current)return;const f=window.setTimeout(()=>{c.current=!1,u(p=>p+1)},ZF);return()=>window.clearTimeout(f)},[t]),t?{view:e,open:!0,animateEntrance:o.current.animate}:c.current&&s.current!==null?{view:s.current,open:!1,animateEntrance:!0}:{view:null,open:!1,animateEntrance:!0}}function JF(){return{sessionId:null,taskCount:0,autoOpenedAt:null}}function eq(e,t){const n=t.sessionId!==e.sessionId,s=!n&&t.taskCount<e.taskCount;return(n||t.taskCount!==e.taskCount)&&(e.sessionId=t.sessionId,e.taskCount=t.taskCount,e.autoOpenedAt=s?t.taskCount:null),t.liveSpawn&&e.autoOpenedAt!==e.taskCount?(e.autoOpenedAt=e.taskCount,"autoOpen"):null}const tq=300;function nq(e){const t=mn().user?.userId??null,n=t&&e?aM(t,e):null,s=y.useMemo(()=>n?$i(n):{},[n]),o=y.useRef(s.text??""),c=y.useRef(s.handoffAgentId??null),u=y.useRef(s.switchModelRef??null),f=y.useRef(s.skills??[]),p=y.useRef(null),h=y.useCallback(()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null)},[]),x=y.useCallback(()=>{if(h(),!n)return;const N=o.current,T=c.current,_=u.current,R=f.current;if(!N&&!T&&!_&&R.length===0){Du(n);return}const D={text:N};T&&(D.handoffAgentId=T),_&&(D.switchModelRef=_),R.length>0&&(D.skills=R),Qs(n,D)},[h,n]);y.useEffect(()=>(o.current=s.text??"",c.current=s.handoffAgentId??null,u.current=s.switchModelRef??null,f.current=s.skills??[],()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null,x())}),[s,x]);const g=y.useCallback(N=>{o.current=N,h(),p.current=window.setTimeout(()=>{p.current=null,x()},tq)},[h,x]),v=y.useCallback(N=>{c.current=N,x()},[x]),w=y.useCallback(N=>{u.current=N,x()},[x]),S=y.useCallback(N=>{f.current=N,x()},[x]),C=y.useCallback(()=>{h(),o.current="",f.current=[],c.current=null,u.current=null,n&&Du(n)},[h,n]);return{initial:s,onTextChange:g,onHandoffTargetChange:v,onPendingModelChange:w,onSkillsChange:S,discard:C}}function Xg(e){const t=e.lastIndexOf("-");if(t<=0)return null;const n=Number.parseInt(e.slice(t+1),10);return!Number.isInteger(n)||n<0?null:{epoch:e.slice(0,t),seq:n}}const Qg=200,rq=100,aq=1e6;function sq(e){const t=e.now??(()=>Date.now()),n=new Set,s=new Map;let o=bl(n),c=!1,u="buffering",f=[],p=null,h=null,x=0,g=!1,v=[],w=new Map,S=0,C=null,N=null;const T={hasMore:!1,loading:!1,error:null};let _=0;const R=()=>{v=[],w=new Map,S=0,C=null,N=null,T.hasMore=!1,T.loading=!1,T.error=null,_=0},D=q=>{R(),q!==void 0&&(C=q.before??null,N=q.before??null,T.hasMore=q.before!==void 0,_=q.earlierTurns)},z=()=>{s.size!==0&&(s.clear(),e.onPendingChange())},E=()=>{let q=!1;for(const[K,H]of[...s])(H.origin===void 0||H.origin.length===0)&&(s.delete(K),q=!0);q&&e.onPendingChange()},L=(q,K)=>{if(ay(q)&&q.payload.type==="approval_decision"&&s.delete(Rl(q.origin,q.payload.tool_call_id))&&e.onPendingChange(),K&&!Nu(q.payload)&&FL(K,q)){UN(o,q);return}Tu(o,q,t())},F=q=>{switch(q.type){case"approval_request":{const K=q.toolCall.payload.tool_call_id,H={toolCall:q.toolCall};if(q.origin&&(H.origin=q.origin),s.set(Rl(q.origin,K),H),!_L(o,q.origin,K)){const $={...q.toolCall};q.origin&&q.origin.length>0?$.origin=[...q.origin]:delete $.origin,Tu(o,$,t()),e.onModelChange()}e.onPendingChange();return}case"task_state":{p=q.state,e.onTaskState(q.state),e.onQueuedFollowUps?.(q.queued??0),e.onPendingSteering?.(q.pendingSteering??[]),e.onPendingFollowUps?.(q.pendingFollowUps??[]),e.onSubagents?.(q.subagents??[]),q.state==="idle"&&(EL(o),E(),e.onModelChange());return}case"resync_required":{V();return}case"credentials_updated":return;case"hello":return}},V=async()=>{x+=1,u="buffering",f=[],z(),await B(x,bl(n),{page:{kind:"tail",limit:Qg},splice:v.length>0})},P=(q,K)=>{const H=Xg(K.cursor);if(!H)return q;const $=h===null?null:Xg(h);if($!==null&&$.epoch!==H.epoch)return q;const X=[],le=[];for(const I of q){const A=I.id===null?null:Xg(I.id);A!==null&&A.epoch===H.epoch&&A.seq<=H.seq?(I.kind!=="omni"||!Nu(I.msg.payload))&&X.push(I):le.push(I)}const ie=K.fragments.map(I=>({kind:"omni",msg:I,id:null,seeded:!0}));return[...X,...ie,...le]},B=async(q,K,H={})=>{try{let $=await e.loadMessages(H.page);if(c||q!==x)return;if(H.splice===!0){const j=$.page?.before??null;if(!($.page!==void 0&&j!==null&&j===N))if($.page!==void 0&&j===null)D($.page);else{if($=await e.loadMessages(),c||q!==x)return;D(void 0)}}else H.page!==void 0?D($.page):D(void 0);const{messages:X,live:le,serverNowMs:ie}=$;K&&(o=K);const I=o;$.page!==void 0&&Nw(I.stats,$.page.prior),Mw(I,X,t(),ie??null);const A=HL(X,100),Q=le!==void 0?P(f,le):f;f=[];for(let j=0;j<Q.length;j+=1){const U=Q[j];if(U.kind==="omni"?L(U.msg,A):F(U.ev),c)return;if(q!==x){f.push(...Q.slice(j+1).filter(ee=>ee.kind!=="omni"||!ee.seeded));return}}u="live",p==="idle"&&j0(I),g=!1,e.onError(null),e.onLoading(!1),e.onModelChange()}catch($){if(c||q!==x)return;g=!0,e.onLoading(!1),e.onError($ instanceof Error?$.message:String($))}};return{get model(){return o},get prefixItems(){return v},get prefixSubagents(){return w},get outlineOffset(){return _},get older(){return T},get pendingApprovals(){return s},load:()=>(x+=1,B(x,void 0,{page:{kind:"tail",limit:Qg}})),retry:async()=>{c||!g||(e.onError(null),e.onLoading(!0),x+=1,await B(x,bl(n),{page:{kind:"tail",limit:Qg}}))},loadOlder:async()=>{if(c||u!=="live"||g||T.loading||!T.hasMore||C===null)return;const q=x;T.loading=!0,T.error=null,e.onModelChange();try{const K=await e.loadMessages({kind:"before",cursor:C,limit:rq});if(c||q!==x)return;if(K.page===void 0)throw new Error("windowed history not supported");S+=1;const H=bl(n);H.nextItemId=-S*aq,Nw(H.stats,K.page.prior),Mw(H,K.messages,t(),null),j0(H),v=[...H.items,...v];const $=new Map(H.subagents);for(const[X,le]of w)$.set(X,le);w=$,C=K.page.before??null,T.hasMore=K.page.before!==void 0,_=K.page.earlierTurns}catch(K){if(c||q!==x)return;T.error=K instanceof Error?K.message:String(K)}finally{!c&&q===x&&(T.loading=!1,e.onModelChange())}},handleOmni:(q,K=null)=>{if(!c){if(K!==null&&(h=K),u==="buffering"){f.push({kind:"omni",msg:q,id:K});return}L(q,null),e.onModelChange()}},handleServer:(q,K=null)=>{if(!c){if(K!==null&&(h=K),q.type==="session_title"){e.onSessionTitle?.(q.sessionId,q.title);return}if(q.type==="session_created"){e.onSessionCreated?.(q.sessionId);return}if(q.type==="goal_started"||q.type==="goal_round"||q.type==="goal_finished"){e.onGoalEvent?.(q);return}if(u==="buffering"){q.type==="task_state"&&(p=q.state,e.onTaskState(q.state),e.onQueuedFollowUps?.(q.queued??0),e.onPendingSteering?.(q.pendingSteering??[]),e.onPendingFollowUps?.(q.pendingFollowUps??[])),f.push({kind:"server",ev:q,id:K});return}F(q)}},markLocalDecision:q=>{AL(o,q)},resolveApproval:q=>{s.delete(q)&&e.onPendingChange()},dispose:()=>{c=!0}}}const iq=120,oq=new Map,lq=[],cq=new Map,uq={hasMore:!1,loading:!1,error:null};function dq(e,t,n,s){const[o,c]=y.useState(0),[u,f]=y.useState(!0),[p,h]=y.useState(t),[x,g]=y.useState(0),[v,w]=y.useState([]),[S,C]=y.useState([]),[N,T]=y.useState([]),[_,R]=y.useState(null),[D,z]=y.useState(0),[E,L]=y.useState(null),F=y.useCallback(A=>{L(Q=>A.type==="goal_started"?{objective:A.objective,status:"active",budget:A.budget,used:0,rounds:0}:A.type==="goal_round"?{objective:Q?.objective??"",status:"active",budget:A.budget,used:A.used,rounds:A.round}:{objective:Q?.objective??"",status:A.outcome,budget:Q?.budget??-1,used:A.used,rounds:A.rounds})},[]),V=y.useRef(n);V.current=n;const P=y.useRef(s);P.current=s;const B=y.useRef(null),Y=y.useRef(null);Y.current===null&&(Y.current=bl());const q=y.useRef(null),K=y.useRef(null),H=y.useRef(0),$=y.useCallback(()=>{if(q.current!==null||K.current!==null)return;const A=()=>{H.current=Date.now(),c(j=>j+1)},Q=H.current+iq-Date.now();if(Q>0){K.current=window.setTimeout(()=>{K.current=null,A()},Q);return}q.current=requestAnimationFrame(()=>{q.current=null,A()})},[]);y.useEffect(()=>{if(!e){B.current?.dispose(),B.current=null,h("idle"),g(0),w([]),C([]),T([]),f(!1),R(null),L(null),z(ee=>ee+1),c(ee=>ee+1);return}c(ee=>ee+1),f(!0),R(null),h(t),L(null),g(0),w([]),C([]),T([]),z(ee=>ee+1);let A=!1;const Q=()=>{nA(e).then(ee=>{A||!ee.goal||ee.goal.status!=="active"||L(re=>re??ee.goal)}).catch(()=>{})},j=sq({loadMessages:ee=>sC(e,ee),onTaskState:h,onQueuedFollowUps:g,onPendingSteering:w,onPendingFollowUps:C,onSubagents:T,onLoading:f,onError:R,onModelChange:$,onPendingChange:()=>z(ee=>ee+1),onSessionTitle:(ee,re)=>V.current?.(ee,re),onSessionCreated:()=>P.current?.(),onGoalEvent:F});B.current=j;const U=_R(e,{onOmniMessage:j.handleOmni,onServerEvent:j.handleServer,onOpen:Q,onError:ee=>{ee&&qm().catch(()=>{})}});return j.load(),()=>{A=!0,j.dispose(),U.close(),q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),K.current!==null&&(window.clearTimeout(K.current),K.current=null)}},[e]);const X=y.useCallback(A=>{B.current?.markLocalDecision(A)},[]),le=y.useCallback(A=>{B.current?.resolveApproval(A)},[]),ie=y.useCallback(()=>{B.current?.retry()},[]),I=y.useCallback(()=>{B.current?.loadOlder()},[]);return{model:B.current?.model??Y.current,prefixItems:B.current?.prefixItems??lq,prefixSubagents:B.current?.prefixSubagents??cq,outlineOffset:B.current?.outlineOffset??0,older:B.current?.older??uq,loadOlder:I,version:o,loading:u,taskState:p,queuedFollowUps:x,pendingSteering:v,pendingFollowUps:S,subagents:N,pendingApprovals:B.current?.pendingApprovals??oq,markLocalDecision:X,resolveApproval:le,error:_,retry:ie,goal:E}}const mq="M4 5h16v14H4zM4 14h16",fq="M4 5h16v14H4zM14 5v14",pq=e=>`relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${e?"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200":"text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"}`;function hq({agentsPending:e}){y.useSyncExternalStore(Zf,$y);const t=vl("agents")??"right",n=[{position:"bottom",label:d.dock.bottomDock,icon:mq},{position:"right",label:d.dock.rightDock,icon:fq}];return a.jsx("div",{className:"flex shrink-0 items-center gap-1","data-testid":"panels-toolbar",children:n.map(({position:s,label:o,icon:c})=>a.jsxs("button",{type:"button","aria-expanded":Ba(s),onClick:()=>AB(s),title:o,"aria-label":o,"data-testid":`dock-toggle-${s}`,className:pq(Ba(s)),children:[a.jsx(Oe,{d:c,size:Ye.iconButton}),e&&t===s&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${Fl.attention}`})]},s))})}const gq=15e3;function Zg({icon:e,value:t,label:n}){return a.jsxs("span",{title:n,className:`flex shrink-0 items-center ${Ro.tight} font-mono text-xs text-gray-500 dark:text-gray-400`,children:[a.jsx(Oe,{d:e}),t]})}function xq({sessionId:e}){return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.sessionIdLabel}),a.jsxs("div",{className:"flex items-start gap-1.5",children:[a.jsx("span",{className:"min-w-0 flex-1 break-all font-mono text-xs leading-5",children:e}),a.jsx(Wu,{text:e,label:d.chat.copySessionId,className:PN})]})]})}function yq({stats:e,taskOpen:t,taskStartLocalMs:n}){const[s,o]=y.useState(()=>Date.now());return y.useEffect(()=>{if(!t)return;o(Date.now());const c=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(c)},[t]),t?a.jsx(a.Fragment,{children:ZC(vL(e,t,n,s))}):a.jsx(a.Fragment,{children:Pn(e.sessionElapsedMs)})}function bq(e,t){const n=e.stats;return{tokensText:It(n.sessionTotal+n.subagentTotal),costText:t.costText,costUncosted:t.costUncosted,elapsedNode:a.jsx(yq,{stats:n,taskOpen:e.taskOpen,taskStartLocalMs:e.taskStartLocalMs})}}const ya="new",vq=e=>e!==null&&e.startsWith("draft-")?e:null,F2=100;function kq(){const e=yr(),t=$r(),n=MC(),{user:s}=mn(),{currency:o}=as(),{currentProject:c,currentAgent:u,setCurrentAgentId:f,reloadAgents:p,agents:h}=en(),x=c?.projectId??null,g=u?.agentId??null,{sessions:v,loading:w,reload:S,add:C,isDeleted:N,replace:T,setStatus:_,setTitle:R}=Ii(),D=y.useRef(dM()),z=y.useRef(null),[,E]=y.useState(0),[L,F]=y.useState(!1),[V,P]=y.useState(!1),[B,Y]=y.useState(!1),[q,K]=y.useState(null),[H,$]=y.useState([]),[X,le]=y.useState(null),[ie,I]=y.useState(null),[A,Q]=y.useState(null),j=n.sessionId??null;y.useSyncExternalStore(Zf,$y),y.useSyncExternalStore(ZT,d2);const[U,ee]=y.useState(null),[re,ke]=y.useState(null),[be,ye]=y.useState(null),[Se,Me]=y.useState(null);y.useEffect(()=>{ee(null),ke(null),ye(null),Me(null)},[j]);const ze=vl("workspace")!==null,De=vl("memory")!==null,ct=vl("agents")!==null;y.useEffect(()=>{ze||ee(null)},[ze]),y.useEffect(()=>{De||ke(null)},[De]),y.useEffect(()=>{ct||(ye(null),Me(null))},[ct]);const bt=vq(j),he=j===ya||bt!==null,ne=he?null:v.find(de=>de.sessionId===j)??null;y.useEffect(()=>{he||JT(ne?.workspace??null)},[he,ne?.workspace]);const oe=ne?{provider:ne.provider,modelId:ne.modelId}:null;Li(ne?ne.title??d.chat.defaultSessionTitle:d.nav.chat);const J=dq(ne?.sessionId??null,ne?.status??"idle",R,()=>{S()}),{initial:ht,onTextChange:ve,onHandoffTargetChange:Xe,onPendingModelChange:Ge,onSkillsChange:He,discard:Pe}=nq(ne?.sessionId??null),W=y.useMemo(()=>J.prefixItems.length>0?[...J.prefixItems,...J.model.items]:J.model.items,[J.version,j]),me=y.useMemo(()=>bz(W),[J.version,j]),Ue=y.useMemo(()=>iB(W),[J.version,j]),pe=y.useMemo(()=>J.prefixItems.length>0||J.prefixSubagents.size>0?{...J.model,items:[...W],subagents:new Map([...J.prefixSubagents,...J.model.subagents])}:J.model,[J.version,j]),$e=y.useMemo(()=>jL(W.flatMap(de=>de.kind==="task_stats"&&de.memoryChanges!==void 0?[de.memoryChanges]:[])),[J.version,j]),nt=y.useRef($e);SL(nt.current,$e)||(nt.current=$e);const gt=nt.current,Ke=DH(x,ne?.agentId??null,vl("memory")!==null||gt.length>0,gt),dt=y.useMemo(()=>UU(Ke.scopes,gt)??void 0,[Ke.scopes,gt]),pt=y.useRef(null),wt=fB(pt,J.version),st=ne?.sessionId??null,Bt=ne?.agentId??null,Sn=ne?.thinkingLevel??"";y.useEffect(()=>{st&&Bt&&f(Bt)},[st,Bt,f]);const Dn=y.useRef(JF()),Vt=aP(J.model.items),ar=J.taskState!=="idle"&&uP(J.model);y.useEffect(()=>{eq(Dn.current,{sessionId:st,taskCount:Vt,liveSpawn:ar})==="autoOpen"&&!TB("agents")&&ho("agents")},[st,Vt,ar]);const[zn,Xt]=y.useState([]);y.useEffect(()=>{if(Xt(Re=>Re.length>0?[]:Re),!x||!Bt)return;let de=!1;return Bu(x,Bt).then(Re=>{de||Xt(Re.skills)}).catch(()=>{}),()=>{de=!0}},[x,Bt]);const[Cn,lr]=y.useState("");y.useEffect(()=>{if(lr(""),!x||!Bt)return;let de=!1;return Ao(x,Bt).then(Re=>{de||lr(Re.config.model?.thinkingLevel??"")}).catch(()=>{}),()=>{de=!0}},[x,Bt]);const Mt=x&&j?jH(x,j):null,[Pr,Bn]=y.useState(null);y.useEffect(()=>{if(he||!x||!j||!Mt||w||v.some(Re=>Re.sessionId===j))return;if(N(j)){Bn(Mt);return}let de=!1;return d0(j).then(Re=>{if(de)return;const Qe=SH(Re.session,x);Qe?C(Qe):Bn(Mt)},()=>{de||Bn(Mt)}),()=>{de=!0}},[he,x,j,Mt,w,v,C,N]),y.useEffect(()=>{if(w||he||j&&v.some(Re=>Re.sessionId===j)||j&&Pr!==Mt)return;const de=PC(v);e(de?`/chat/${de.sessionId}`:`/chat/${ya}`,{replace:!0})},[w,he,j,Mt,Pr,v,e]),y.useEffect(()=>{st!==null&&_(st,J.taskState)},[J.taskState,st,_]);const Nr=y.useRef({id:st,state:"idle"}),[Tr,Te]=y.useState(0);y.useEffect(()=>{const de=Nr.current,Re=de.id===st;Nr.current={id:st,state:Re?J.taskState:"idle"},!(!Re||st===null)&&de.state!=="idle"&&J.taskState==="idle"&&(S(),p(),Te(Qe=>Qe+1))},[J.taskState,st,S,p]);const Ie=ne?.lastActiveAt??null;y.useEffect(()=>{st===null||Ie===null||J.taskState==="idle"&&Gx(x,st,Ie)},[x,st,Ie,J.taskState]);const ut=y.useRef(new Map);y.useEffect(()=>{z.current=null,Q(null),ut.current=new Map,$([]),I(null)},[j]);const St=y.useCallback(async de=>{const Re=ne?.sessionId??null,Qe=ut.current,mt=Re===null?[]:de.filter(Pt=>!Qe.has(Pt));if(Re!==null&&mt.length>0)for(let Pt=0;Pt<mt.length;Pt+=F2){const Wt=mt.slice(Pt,Pt+F2),Ka=jA(Re,Wt).then(_r=>new Set(_r.existing)).catch(()=>null);for(const _r of Wt){const Rr=Ka.then(Ir=>Ir?.has(_r)??!1);Qe.set(_r,Rr),Rr.then(Ir=>{Qe.get(_r)===Rr&&(Ir?Qe.set(_r,!0):Qe.delete(_r))})}}const Et=new Set;return await Promise.all(de.map(async Pt=>{const Wt=Qe.get(Pt);(Wt===!0||Wt instanceof Promise&&await Wt)&&Et.add(Pt)})),Et},[ne?.sessionId]);y.useEffect(()=>{if(!x||!ne||z.current===ne.sessionId&&J.taskState!=="idle"&&!V)return;let de=!1;return iC(x,{groupBy:"session",agentId:ne.agentId}).then(Re=>{if(de)return;z.current=ne.sessionId;const Qe=Re.groups.find(mt=>mt.key===ne.sessionId);CH(D.current,ne.sessionId,Qe??null),I(Qe?{cacheRead:Qe.cacheRead,cacheWrite:Qe.cacheWrite,output:Qe.output}:null),E(mt=>mt+1)}).catch(()=>{}),()=>{de=!0}},[x,ne,J.taskState,V]);const gn=y.useRef(st);y.useEffect(()=>{gn.current=st},[st]);const Nn=H.filter(de=>de.running).length,Hn=J.taskState!=="idle"||Nn>0||V&&H.length>0;y.useEffect(()=>{if(!st)return;let de=!1;const Re=()=>{q1(st).then(mt=>{de||$(mt.processes)}).catch(()=>{})};if(Re(),!Hn)return()=>{de=!0};const Qe=window.setInterval(Re,gq);return()=>{de=!0,window.clearInterval(Qe)}},[st,J.taskState,Hn]);const Dt=y.useCallback(async(de,Re,Qe)=>{if(!ne||X!==null)return;const mt=ne.sessionId;le(de);try{await Re(mt,de)}catch(Et){Et instanceof xr&&Qe.includes(Et.status)||Be(Ae(Et))}finally{le(null),q1(mt).then(Et=>{gn.current===mt&&$(Et.processes)}).catch(()=>{})}},[ne,X]),Rn=y.useCallback(de=>Dt(de,iA,[404]),[Dt]),zr=y.useCallback(de=>Dt(de,oA,[404,409]),[Dt]);y.useEffect(()=>{if(!x)return;let de=!1;return K(null),(async()=>{try{const Re=await Ml(x);if(de)return;K(Re);const{prefs:Qe}=await Sx();if(de||Qe.credentialGuideSeen)return;const mt=Re.models.find(Pt=>zt(Pt,Re.defaultModel));(!Re.defaultModel||!mt||!Ol(mt))&&F(!0),Nf({credentialGuideSeen:!0}).catch(()=>{})}catch{}})(),()=>{de=!0}},[x]),y.useEffect(()=>{if(!x)return;let de=!1;const Re=Qe=>{const mt=cM(Qe,x);!mt||mt.defaultModel===void 0||(K(null),Ml(x).then(Et=>{de||K(Et)}).catch(()=>{}))};return window.addEventListener($u,Re),()=>{de=!0,window.removeEventListener($u,Re)}},[x]);const cr=y.useCallback(async(de,Re)=>{Re!==de&&(await S(),HT(Re),e(`/chat/${Re}`,{replace:!0}))},[S,e]),Js=y.useCallback(async(de,Re)=>{if(!ne)return!1;try{const Qe=await su(ne.sessionId,{input:de,...Re?{goal:Re}:{},...Sn?{thinkingLevel:Sn}:{}});return Pe(),await cr(ne.sessionId,Qe.sessionId),!0}catch(Qe){return Be(Ae(Qe,{modelId:ne.modelId})),!1}},[ne,Sn,Pe,cr]),Mr=y.useCallback(async(de,Re)=>{if(!x||!ne)return!1;const Qe=await d0(ne.sessionId).then(Pt=>Pt.session.tracePath).catch(()=>{}),mt={type:"text",text:JU({sessionId:ne.sessionId,...ne.title!==void 0?{sessionTitle:ne.title}:{},...Qe!==void 0?{tracePath:Qe}:{},workspace:ne.workspace,prevProvider:ne.provider,prevModelId:ne.modelId})};let Et=null;try{const Pt=await u0(x,ne.agentId,{provider:de.provider,modelId:de.modelId,workspace:ne.workspace,approvalMode:ne.approvalMode});Et=Pt.session.sessionId;const Wt=await su(Et,{input:[mt,...Re]});return C(Pt.session),Pe(),e(`/chat/${Wt.sessionId}`),!0}catch(Pt){return Et&&nf(Et).catch(()=>{}),Be(Ae(Pt,{modelId:de.modelId})),!1}},[x,ne,C,Pe,e]),ta=y.useCallback(async(de,Re)=>{if(!x||!u||!ne)return!1;const Qe={type:"text",text:ZU({agentId:u.agentId,...u.name!==void 0?{agentName:u.name}:{},sessionId:ne.sessionId,workspace:ne.workspace,...ne.title!==void 0?{sessionTitle:ne.title}:{}})};let mt=null;try{const Et=await u0(x,de.agentId,{approvalMode:ne.approvalMode});mt=Et.session.sessionId;const Pt=await su(mt,{input:[Qe,...Re]});return C(Et.session),Pe(),e(`/chat/${Pt.sessionId}`),!0}catch(Et){return mt&&nf(mt).catch(()=>{}),Be(Ae(Et,q?.defaultModel?{modelId:q.defaultModel.modelId}:{})),!1}},[x,u,ne,C,Pe,e,q]),Br=y.useCallback(async()=>{ne&&await aA(ne.sessionId).catch(()=>{})},[ne]),is=y.useCallback(async de=>{if(!ne)return!1;try{const Re=await su(ne.sessionId,{input:de,queueIfBusy:!0,...Sn?{thinkingLevel:Sn}:{}});return Pe(),await cr(ne.sessionId,Re.sessionId),!0}catch(Re){return Be(Ae(Re,{modelId:ne.modelId})),!1}},[ne,Sn,Pe,cr]),Hr=y.useCallback(async(de,Re=[],Qe=[])=>{if(!ne)return"failed";try{return await lA(ne.sessionId,{text:de,...Re.length>0?{images:Re}:{},...Qe.length>0?{files:Qe}:{}}),Pe(),"queued"}catch(mt){return mt instanceof xr&&mt.status===409?"not_running":(Be(Ae(mt,{modelId:ne.modelId})),"failed")}},[ne,Pe]),fn=y.useCallback(de=>{ne&&tf(ne.sessionId,{thinkingLevel:de}).then(Re=>T(Re.session)).catch(Re=>{Be(Ae(Re))})},[ne,T]),Fr=y.useCallback(async de=>{if(!ne)return null;try{return await dA(ne.sessionId,de)}catch(Re){return Be(Ae(Re)),null}},[ne]),qr=y.useCallback(async de=>{if(!ne)return null;try{const Re=await mA(ne.sessionId,de);return Re.thinkingLevel&&fn(Re.thinkingLevel),Re}catch(Re){return Be(Ae(Re)),null}},[ne,fn]),pn=y.useCallback(async(de,Re,Qe)=>{if(!ne)return;J.markLocalDecision(de);const mt=Rl(Qe,de);try{await rA(ne.sessionId,de,{decision:Re}),J.resolveApproval(mt)}catch(Et){Et instanceof xr&&Et.status===404&&J.resolveApproval(mt)}},[ne,J]),na=y.useCallback(de=>{!ne||B||(Y(!0),tf(ne.sessionId,{approvalMode:de}).then(Re=>T(Re.session)).catch(Re=>{Be(Ae(Re))}).finally(()=>Y(!1)))},[ne,B,T]),Jn=y.useCallback(async()=>{if(!ne)return!1;try{const de=await fA(ne.sessionId);return await cr(ne.sessionId,de.sessionId),!0}catch(de){return Be(Ae(de,{modelId:ne.modelId})),!1}},[ne,cr]),Er=y.useCallback(async()=>{await Jn()},[Jn]),ur=y.useCallback(de=>{pz(J.model.items,Hg(Sn,Cn),de)?Q({phase:"ask",level:de}):fn(de)},[J.model,Sn,Cn,fn]),os=y.useCallback(()=>{if(A===null||J.taskState!=="idle")return;const de={phase:"compacting",level:A.level,baseline:jT(J.model.items)};Q(de),wr(d.chat.thinkingSwitchCompacting),Jn().then(Re=>{Re||Q(Qe=>Qe===de?{phase:"settle",level:de.level}:Qe)})},[A,J.taskState,J.model,Jn]);y.useEffect(()=>{if(A===null)return;const de=gz(A,J.model.items);de.act!=="wait"&&(Q(null),fn(de.level),de.notice==="compacted"?yt(d.chat.thinkingSwitchApplied(W0(d.chat.thinkingLevelNames,de.level)??de.level)):de.notice==="compaction-failed"&&Be(d.chat.thinkingSwitchCompactFailed))},[J.version,J.model,A,fn]);const ls=y.useCallback(()=>{s&&x&&Yl(s.userId,x),e(`/chat/${ya}`)},[s,x,e]),ra=y.useCallback(async de=>{if(ne)try{let Re=de.position;if(Re===void 0){const mt=await sC(ne.sessionId),Et=bl();for(const Wt of mt.messages)Tu(Et,Wt);j0(Et);const Pt=[...Et.items].reverse().find(Wt=>Wt.kind==="task_stats"&&Wt.assistantText===de.assistantText&&Wt.atMs===de.atMs&&Wt.forkPosition!==void 0);Re=Pt?.kind==="task_stats"?Pt.forkPosition:void 0}if(Re===void 0){Be(d.chat.forkSessionFailed);return}const Qe=await WE(ne.sessionId,{position:Re});C(Qe.session),e(`/chat/${Qe.session.sessionId}`)}catch(Re){Be(Ae(Re,{modelId:ne.modelId}))}},[ne,C,e]),cs=q?.models.find(de=>zt(de,oe))?.pricing,ka={pendingApprovals:J.pendingApprovals,onApprove:pn,origin:[],taskRunning:J.taskState!=="idle",taskCost:de=>Cw(de.tokensByBucket,cs),onRetryNow:()=>{ne&&sA(ne.sessionId).catch(()=>{})},onGiveUp:()=>{Br()},onOpenFile:de=>{ho("workspace"),ee({path:de})},onOpenSubagent:(de,Re)=>{ho("agents"),Me({anchorSessionId:Re[0]??de}),ye({sessionId:de,origin:[...Re,de]})},onOpenMemory:()=>{ho("memory"),ke({target:null})},onLocateMemoryChange:de=>{ho("memory"),ke({target:{scope:de.scope,...de.scopeKey!==void 0?{scopeKey:de.scopeKey}:{},file:de.file}})},...dt!==void 0?{deletedMemoryKeys:dt}:{},workspace:ne?.workspace??null,statFiles:St,onFork:ra},Ar=[...J.pendingApprovals.keys()].some(de=>!de.startsWith(" ")),er=NB(),Tn=H2(er.find(de=>de.position==="right")??null),Vr=H2(er.find(de=>de.position==="bottom")??null),wa=d2(),Mn=(de,Re)=>{if(!ne)return a.jsx(Fa,{title:wl(de),description:d.dock.draftEmpty});switch(de){case"agents":return a.jsx(UH,{session:ne,model:pe,version:J.version,taskRunning:J.taskState!=="idle",ctx:ka,focusRequest:be,taskScope:Se,subagents:J.subagents,models:q?.models??[],approvalMode:ne.approvalMode,onChangeApprovalMode:na,modeSaving:B,parentThinkingLevel:Hg(Sn,Cn)},ne.sessionId);case"workspace":return a.jsx(OH,{session:ne,openRequest:U,active:Re,reloadSignal:Tr});case"memory":return a.jsx(HU,{session:ne,changes:gt,scopes:Ke.scopes,listingError:Ke.error,request:re,active:Re,onOpenSettings:()=>e(`/agents/${ne.agentId}?tab=memory`)},ne.sessionId);case"trace":return a.jsx(pF,{session:ne,active:Re},ne.sessionId);case"messaging":return a.jsx(TF,{sessionId:ne.sessionId,active:Re},ne.sessionId)}};if(!x||!g)return a.jsx("div",{className:"p-6",children:a.jsx(on,{className:"h-6 w-64"})});const Gr=J.model.taskOpen?Cw({cacheRead:J.model.stats.taskCacheRead,cacheWrite:J.model.stats.taskCacheWrite,output:J.model.stats.taskOutput},cs):null,En=bq(J.model,NH(D.current,{sessionId:ne?.sessionId??null,taskCount:rP(J.model.items),taskOpen:J.model.taskOpen,loading:J.loading,liveUsd:Gr,currency:o})),us=ie?ie.cacheRead+ie.cacheWrite:0,hn=ie&&us>0?`${Math.round(100*ie.cacheRead/us)}%`:null,Sa=h.find(de=>de.agentId===ne?.agentId),Ts=Sa&&Sa.name!==void 0?_n(Sa):null,Ga=q?.models.find(de=>zt(de,oe)),Ct=Ga?.contextWindow,ds=Ga?.vision!==!1,ja=ne!==null&&!J.loading&&!J.error&&J.model.items.length===0,br=ne&&a.jsx(Iy,{status:J.taskState,onSend:Js,onSteer:Hr,steeringDeliveredCount:J.model.items.filter(de=>de.kind==="user_steering").length,pendingSteering:J.pendingSteering,onRecallSteering:Fr,onQueueFollowUp:is,queuedFollowUps:J.queuedFollowUps,pendingFollowUps:J.pendingFollowUps,onRecallFollowUp:qr,onStop:Br,onCompact:Er,modelRef:oe,...q!==null?{models:q.models}:{},...q?.defaultModel!==void 0?{defaultModel:q.defaultModel}:{},onSwitchModel:Mr,turnThinkingLevel:Hg(Sn,Cn),onChangeTurnThinkingLevel:ur,...Ct!==void 0?{contextWindow:Ct}:{},contextNow:J.model.stats.contextNow,contextStale:J.model.stats.contextStale,sessionId:ne.sessionId,vision:ds,approvalMode:ne.approvalMode,onChangeApprovalMode:na,modeSaving:B,autoFocus:!0,agents:h,currentAgentId:ne.agentId,skills:zn,...ht.skills&&ht.skills.length>0?{initialSkills:ht.skills}:{},onSkillsChange:He,onHandoff:ta,initialText:ht.text??"",onTextChange:ve,history:me,...ht.handoffAgentId?{initialHandoffTargetId:ht.handoffAgentId}:{},onHandoffTargetChange:Xe,...ht.switchModelRef?{initialPendingModelRef:ht.switchModelRef}:{},onPendingModelChange:Ge}),Ca=ne===null?null:rN(J.taskState,ne.hasTrace,!1);return a.jsxs("div",{"data-dock-host":!0,className:"flex h-full flex-col bg-white dark:bg-gray-950",children:[ne&&a.jsxs("div",{className:"flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[a.jsx("h1",{className:"flex min-w-0 text-[15px] font-semibold",children:a.jsx(Of,{text:ne.title??d.chat.defaultSessionTitle})}),Ca==="running"&&a.jsxs("span",{title:S0(Ca),className:"flex shrink-0 items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400",children:[a.jsx(vN,{activity:Ca}),a.jsx("span",{className:"hidden sm:inline",children:S0(Ca)})]})]}),a.jsx(hq,{agentsPending:Ar}),!wt.shown&&a.jsx(hB,{entries:Ue,turnOffset:J.outlineOffset,scrollRef:pt,running:J.taskState!=="idle"}),a.jsx(Qn,{open:V,setOpen:P,menuClass:"right-0 top-full mt-1 w-96 max-w-[calc(100vw-1.5rem)] origin-top-right",button:a.jsxs("button",{type:"button",title:d.chat.infoPanel,"aria-label":d.chat.infoPanel,"aria-expanded":V,onClick:()=>P(!V),className:`flex h-7 shrink-0 items-center rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${V?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsxs("span",{className:"hidden items-center gap-3 px-2 sm:flex",children:[a.jsx(Zg,{icon:Xn.tokens,value:En.tokensText,label:`${d.chat.statTokens}(Token)`}),En.costText!=null&&a.jsx(Zg,{icon:Xn.cost,value:`${En.costText}${En.costUncosted?" *":""}`,label:`${d.common.cost}(${o})${En.costUncosted?` · ${d.usage.uncostedNote}`:""}`}),a.jsx(Zg,{icon:Xn.elapsed,value:En.elapsedNode,label:d.chat.statElapsed}),Nn>0&&a.jsxs("span",{title:d.chat.runningServices(Nn),className:`flex shrink-0 items-center ${Ro.tight} font-mono text-xs ${sn.busy}`,children:[a.jsx(Oe,{d:Xn.services}),Nn]})]}),a.jsx("span",{className:"flex h-7 w-7 items-center justify-center text-gray-500 sm:hidden dark:text-gray-400",children:a.jsx(Oe,{d:RI,size:Ye.navRow})})]}),children:a.jsxs("div",{className:"space-y-3 px-3.5 py-2.5 text-sm",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.agent}),a.jsxs("p",{className:"truncate text-xs",children:[a.jsx("span",{className:"font-mono",children:ne.agentId}),Ts!==null&&a.jsx("span",{className:"ml-1.5 text-gray-400 dark:text-gray-500",children:Ts})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.model}),a.jsxs("p",{className:"truncate text-xs",children:[a.jsx("span",{className:"font-mono",children:ne.modelId}),a.jsx("span",{className:"ml-1.5 text-gray-400 dark:text-gray-500",children:Ws(ne.provider)?.label??ne.provider})]})]}),a.jsx(xq,{sessionId:ne.sessionId}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.workspace}),a.jsx("p",{className:"break-all font-mono text-xs leading-5",children:ne.workspace})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.common.created}),a.jsx("p",{className:"font-mono text-xs",children:Jr(ne.createdAt)})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.sessionStats}),a.jsxs("ul",{className:"list-inside list-disc space-y-0.5 font-mono text-xs",children:[a.jsxs("li",{children:[d.chat.statTotalTokens," ",En.tokensText,hn!==null&&`${d.chat.statParenOpen}${d.chat.statCacheHit(hn)}${d.chat.statParenClose}`]}),En.costText!=null&&a.jsxs("li",{children:[d.common.cost," ",En.costText,En.costUncosted?" *":""]}),a.jsxs("li",{children:[d.chat.statElapsed," ",En.elapsedNode]})]})]}),H.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.processList}),a.jsx("ul",{className:"mt-1 space-y-1.5",children:H.map(de=>a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${de.running?`animate-pulse ${Fl.busy}`:"bg-gray-300 dark:bg-gray-600"}`}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate font-mono text-xs",title:de.cmd,children:de.cmd}),a.jsxs("span",{className:"block truncate text-[11px] text-gray-400 dark:text-gray-500",children:[Jr(de.startedAt),de.pid!==null&&` · pid ${de.pid}`,de.running&&de.serviceUrl!==void 0&&a.jsxs(a.Fragment,{children:[" · ",a.jsx("a",{href:de.serviceUrl,target:"_blank",rel:"noopener noreferrer",title:de.serviceUrl,className:"text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-700 hover:decoration-gray-500 dark:text-gray-400 dark:decoration-gray-600 dark:hover:text-gray-200",children:de.serviceUrl.replace(/^https?:\/\//i,"")})]})]})]}),de.running?a.jsx("button",{type:"button",disabled:X!==null,onClick:()=>{Rn(de.processId)},className:"shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400",children:X===de.processId?d.common.loading:d.chat.processStop}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400 dark:text-gray-500",children:d.chat.processExited}),a.jsx("button",{type:"button",title:d.chat.processRemoveHint,disabled:X!==null,onClick:()=>{zr(de.processId)},className:"shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400",children:X===de.processId?d.common.loading:d.chat.processRemove})]})]},de.processId))})]})]})})]}),a.jsxs("div",{"data-dock-row":!0,className:"flex min-h-0 flex-1",children:[a.jsx(Mz,{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:he?a.jsx(vH,{projectId:x,models:q,...bt!==null?{draftId:bt}:{}},`draft:${x}:${bt??t.key}`):a.jsx("div",{className:"anim-fade flex min-h-0 flex-1 flex-col",children:ne?J.error?a.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6",children:[a.jsxs("p",{className:"text-sm text-red-600 dark:text-red-400",children:[d.chat.historyLoadFailed,":",J.error]}),a.jsx(ge,{onClick:J.retry,children:d.common.retry})]}):J.loading?a.jsxs("div",{className:"space-y-3 p-6",children:[a.jsx(on,{className:"h-5 w-1/3"}),a.jsx(on,{className:"h-5 w-2/3"}),a.jsx(on,{className:"h-5 w-1/2"})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"min-h-0 flex-1",children:ja?a.jsx("div",{className:"flex h-full items-center justify-center px-4",children:a.jsx("p",{className:"text-lg font-medium text-gray-400 dark:text-gray-500",children:d.chat.emptyGreeting})}):a.jsx(pT,{items:W,version:J.version,ctx:ka,scrollElRef:pt,older:{hasMore:J.older.hasMore,loading:J.older.loading,error:J.older.error,prependedCount:J.prefixItems.length,onLoad:J.loadOlder},outline:a.jsx(pB,{entries:Ue,turnOffset:J.outlineOffset,version:J.version,scrollRef:pt,running:J.taskState!=="idle",fit:wt})})}),a.jsx("div",{className:"shrink-0 border-t border-gray-200 bg-white px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3 dark:border-gray-800 dark:bg-gray-950",children:a.jsxs("div",{className:"mx-auto max-w-3xl",children:[J.goal&&a.jsx(NP,{goal:J.goal}),br]})})]}):w?a.jsx("div",{className:"space-y-3 p-6",children:a.jsx(on,{className:"h-5 w-1/2"})}):a.jsx(Fa,{title:d.chat.noSessions,action:a.jsx(ge,{onClick:ls,children:d.nav.newChat})})},ne?.sessionId??"empty")}),Tn.view&&a.jsx(B2,{view:Tn.view,open:Tn.open,animateEntrance:Tn.animateEntrance,renderPanel:Mn,panelBadges:{agents:Ar},terminalSupported:wa})]}),Vr.view&&a.jsx(B2,{view:Vr.view,open:Vr.open,animateEntrance:Vr.animateEntrance,renderPanel:Mn,panelBadges:{agents:Ar},terminalSupported:wa}),a.jsx(Yt,{open:L,title:d.project.noCredentialTitle,onClose:()=>F(!1),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>F(!1),children:d.project.later}),a.jsx(ge,{variant:"primary",onClick:()=>{F(!1),e("/models")},children:d.project.goToModels})]}),children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.project.noCredentialBody})}),a.jsxs(ln,{open:A?.phase==="ask",title:d.chat.thinkingSwitchTitle,tone:"primary",confirmLabel:d.chat.thinkingSwitchCompactFirst,confirmDisabled:J.taskState!=="idle",onConfirm:os,secondaryLabel:d.chat.thinkingSwitchConfirm,onSecondary:()=>{A!==null&&fn(A.level),Q(null)},onClose:()=>Q(null),children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.chat.thinkingSwitchBody(W0(d.chat.thinkingLevelNames,A?.level)??A?.level??"")}),J.taskState!=="idle"&&a.jsx("p",{className:"mt-2 text-sm text-gray-500 dark:text-gray-400",children:d.chat.thinkingSwitchBusyHint})]})]})}function wq({sessionId:e,onClose:t,onChanged:n}){const s=kM(e,{poll:!0,...n?{onChanged:n}:{},onLoadFailed:t});return a.jsx(Yt,{open:!0,title:d.messaging.dialogTitle,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,children:d.common.close}),a.jsx(ge,{variant:"primary",disabled:s.busy||s.form===null,onClick:()=>{s.save()},children:s.busy?d.common.saving:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(wM,{b:s}),s.form!==null&&a.jsx(SM,{channel:s.form.channel})]})})}const mx=/^[a-z][a-z0-9_]{1,63}$/,q2=/^[a-z][a-z0-9_]{1,31}$/,Sq=/^[a-z0-9_]+$/,jq=64;function Cq(e){const t=[];return y.Children.forEach(e,n=>{if(!y.isValidElement(n)||n.type!=="option")return;const s=n.props;t.push({value:s.value!==void 0?String(s.value):"",label:s.children??"",...s.disabled?{disabled:!0}:{}})}),t}const Nq=`flex w-full items-center gap-2 text-left ${Uf} disabled:cursor-not-allowed disabled:opacity-60`,Tq={base:"text-base",sm:"text-xs"};function Ss({label:e,hint:t,error:n,required:s,size:o="base",className:c,children:u,value:f,onChange:p,disabled:h,"aria-label":x}){const g=Cq(u),v=String(f??""),w=g.find(E=>E.value===v),S=y.useId(),[C,N]=y.useState(!1),{triggerRef:T,panelRef:_,position:R}=$f({open:C,onClose:()=>N(!1),estimatedHeight:g.length*36+8}),D=E=>{N(!1),p?.({target:{value:E}}),T.current?.focus()},z=a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:T,type:"button",disabled:h,"aria-haspopup":"listbox","aria-expanded":C,...x!==void 0?{"aria-label":x}:{},"aria-required":s||void 0,"aria-invalid":n?!0:void 0,"aria-describedby":n?S:void 0,onClick:()=>N(E=>!E),className:`${Nq} ${Pf[o]} ${n?zf:""} ${c??""}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:w?.label??g[0]?.label??""}),a.jsx(ns,{className:"text-gray-400"})]}),C&&R&&ss.createPortal(a.jsx("div",{ref:_,role:"listbox",className:"anim-pop fixed z-[60] max-h-60 overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",style:{left:R.left,width:R.triggerWidth,top:R.topPx,bottom:R.bottomPx},children:g.map((E,L)=>a.jsxs("button",{type:"button",role:"option","aria-selected":E.value===v,disabled:E.disabled,onClick:()=>D(E.value),className:`flex items-center ${ny} ${Tq[o]} disabled:opacity-50 ${E.value===v?"bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:E.label}),E.value===v&&a.jsx(qu,{className:"text-gray-500 dark:text-gray-400"})]},`${E.value}-${L}`))}),document.body)]});return a.jsx(Vu,{label:e,hint:t,error:n,errorId:S,required:s,children:z})}const Mq=["always-ask","read-only","allow-all","deny-all"];function Eq({open:e,onClose:t,onCreated:n}){const{user:s}=mn(),o=s&&!s.isAdmin?`${s.userId}-`:"",[c,u]=y.useState(""),[f,p]=y.useState(""),[h,x]=y.useState(void 0),[g,v]=y.useState(!1);y.useEffect(()=>{e&&(u(""),p(""),x(void 0))},[e]);const w=async()=>{const S=o+c.trim();if(!c.trim()){x(d.common.requiredField);return}if(!(o?Sq.test(c.trim())&&S.length<=jq:mx.test(S))){x(o?d.project.idPrefixHint:d.project.idHint);return}v(!0),x(void 0);try{const N=await bE({projectId:S,...f.trim()?{name:f.trim()}:{}});n(N.project.projectId)}catch(N){x(Ae(N))}finally{v(!1)}};return a.jsx(Yt,{open:e,title:d.project.createTitle,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:g,onClick:()=>{w()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[o?a.jsxs("div",{children:[a.jsx(Yn,{required:!0,children:d.project.id}),a.jsxs("div",{className:"flex items-stretch",children:[a.jsx("span",{className:"flex shrink-0 items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-100 px-2 font-mono text-xs text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400",children:o}),a.jsx(at,{size:"sm",className:"rounded-l-none",value:c,invalid:!!h,onChange:S=>{u(S.target.value),x(void 0)},autoFocus:!0})]}),h?a.jsx(ga,{children:h}):a.jsx(wo,{children:d.project.idPrefixHint})]}):a.jsx(at,{label:d.project.id,required:!0,size:"sm",value:c,error:h,onChange:S=>{u(S.target.value),x(void 0)},hint:d.project.idHint,autoFocus:!0}),a.jsx(at,{label:d.project.displayName,hint:d.project.displayNameHint,size:"sm",value:f,onChange:S=>p(S.target.value)})]})})}const Aq={general:If,members:Bx,defaults:"M4 21v-7m0-4V3m8 18v-9m0-4V3m8 18v-5m0-4V3M1 14h6m2-6h6m2 8h6",security:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"};function _q({d:e}){return a.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"shrink-0",children:a.jsx("path",{d:e})})}function xl({title:e,description:t,children:n}){return a.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm",children:e}),t!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-400",children:t})]}),n!==void 0&&a.jsx("div",{className:"flex shrink-0 items-center gap-2",children:n})]})}function Rq({open:e,onClose:t}){const{desktopMode:n}=mn(),{currentProject:s}=en(),[o,c]=y.useState("general");y.useEffect(()=>{e&&c("general")},[e]);const u=s?.projectId,f=s?.role==="owner";if(!s||!u)return null;const p=[{key:"general",label:d.project.settingsTabGeneral},...n?[]:[{key:"members",label:d.project.settingsTabMembers}],{key:"defaults",label:d.project.settingsTabDefaults},{key:"security",label:d.project.settingsTabSecurity,info:d.project.commandPolicyInfo}],h=p.find(x=>x.key===o)??p[0];return a.jsx(Yt,{open:e,title:d.project.settingsTitle,onClose:t,widthClass:"sm:max-w-3xl",children:a.jsxs("div",{className:"flex flex-col gap-3 sm:min-h-[26rem] sm:flex-row sm:gap-0",children:[a.jsx("nav",{"aria-label":d.project.settingsTitle,className:"flex shrink-0 gap-1 overflow-x-auto sm:w-44 sm:flex-col sm:overflow-x-visible sm:border-r sm:border-gray-100 sm:pr-3 dark:sm:border-gray-800",children:p.map(x=>a.jsxs("button",{type:"button","aria-current":h.key===x.key?"page":void 0,onClick:()=>c(x.key),className:`flex shrink-0 items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm transition-colors duration-150 ${h.key===x.key?"bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/60"}`,children:[a.jsx(_q,{d:Aq[x.key]}),a.jsx("span",{className:"truncate",children:x.label})]},x.key))}),a.jsxs("section",{className:"min-w-0 flex-1 sm:pl-5",children:[a.jsxs("h3",{className:"flex items-center gap-1.5 text-base font-semibold",children:[h.label,h.info!==void 0&&a.jsx(ba,{label:h.label,children:h.info})]}),a.jsxs("div",{className:"mt-2",children:[h.key==="general"&&a.jsx(Iq,{projectId:u,isOwner:f,onClose:t}),h.key==="members"&&a.jsx(Lq,{projectId:u,isOwner:f}),h.key==="defaults"&&a.jsx(Oq,{projectId:u,isOwner:f}),h.key==="security"&&a.jsx($q,{projectId:u,isOwner:f})]})]})]})})}function Iq({projectId:e,isOwner:t,onClose:n}){const{currentProject:s,setCurrentProjectId:o,projects:c,reloadProjects:u}=en(),f=s?wu(s):"",[p,h]=y.useState(f),[x,g]=y.useState(!1),[v,w]=y.useState(void 0),[S,C]=y.useState(!1),N=async()=>{const _=p.trim();if(!(!_||_===f||x)){g(!0),w(void 0);try{await vE(e,{name:_}),await u()}catch(R){w(Ae(R))}finally{g(!1)}}},T=async()=>{try{await kE(e),n();const _=c.find(R=>R.projectId!==e);await u(),_&&o(_.projectId)}catch(_){Be(Ae(_))}};return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(xl,{title:d.project.displayName,children:t?a.jsxs("div",{className:"flex flex-col items-end gap-1",children:[a.jsxs("div",{className:"flex items-stretch gap-2",children:[a.jsx(at,{size:"sm",className:"w-44",value:p,invalid:!!v,maxLength:100,onChange:_=>{h(_.target.value),v&&w(void 0)},onKeyDown:_=>{_.key==="Enter"&&N()}}),a.jsx(ge,{size:"sm",disabled:x||!p.trim()||p.trim()===f,onClick:()=>{N()},children:d.common.save})]}),v!==void 0&&a.jsx(ga,{children:v})]}):a.jsx("span",{className:"text-sm",children:f})}),a.jsx(xl,{title:d.project.projectIdLabel,children:a.jsx("span",{className:"font-mono text-xs text-gray-400",children:e})}),t&&(e==="default_project"?a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteDefaultForbidden}):c.length<=1?a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteLastForbidden}):a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteProjectDesc,children:a.jsx(ge,{size:"sm",variant:"danger",onClick:()=>C(!0),children:d.common.delete})})),a.jsx(ln,{open:S,title:d.project.deleteProject,onClose:()=>C(!1),onConfirm:()=>{T()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.project.deleteConfirm})})]})}function Lq({projectId:e,isOwner:t}){const{user:n}=mn(),[s,o]=y.useState(null),[c,u]=y.useState(""),[f,p]=y.useState(null);y.useEffect(()=>{let g=!1;return o(null),p(null),mg(e).then(v=>{g||o(v.members)}).catch(v=>{g||p(Ae(v))}),()=>{g=!0}},[e]);const h=async()=>{if(c.trim())try{await wE(e,{userId:c.trim()}),u("");const g=await mg(e);o(g.members)}catch(g){Be(Ae(g))}},x=async g=>{try{await SE(e,g);const v=await mg(e);o(v.members)}catch(v){Be(Ae(v))}};return f?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:f}):s===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):a.jsx("div",{className:"overflow-x-auto rounded-md border border-gray-200 dark:border-gray-800",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-100 bg-gray-50 text-left text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400",children:[a.jsx("th",{className:"whitespace-nowrap px-2.5 py-1.5 font-medium",children:d.common.username}),a.jsx("th",{className:"whitespace-nowrap px-2.5 py-1.5 font-medium",children:d.common.role}),a.jsx("th",{className:"w-20 whitespace-nowrap px-2.5 py-1.5 text-right font-medium",children:d.common.actions})]})}),a.jsxs("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[s.map(g=>a.jsxs("tr",{children:[a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:g.userId}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:a.jsx(On,{tone:"gray",children:g.role})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1 text-right",children:t&&g.role!=="owner"&&g.userId!==n?.userId&&a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>{x(g.userId)},children:d.project.removeMember})})]},g.userId)),t&&a.jsxs("tr",{children:[a.jsx("td",{className:"px-2.5 py-1.5",children:a.jsx(at,{placeholder:d.common.username,size:"sm",value:c,onChange:g=>u(g.target.value),onKeyDown:g=>{g.key==="Enter"&&h()}})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:a.jsx(On,{tone:"gray",children:"member"})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1 text-right",children:a.jsx(ge,{size:"sm",disabled:!c.trim(),onClick:()=>{h()},children:d.project.addMember})})]})]})]})})}function Oq({projectId:e,isOwner:t}){const{user:n}=mn(),{agents:s}=en(),[o,c]=y.useState(null),[u,f]=y.useState(null),[p,h]=y.useState(null),[x,g]=y.useState(!1),[v,w]=y.useState(""),[S,C]=y.useState(""),[N,T]=y.useState(""),[_,R]=y.useState(""),[D,z]=y.useState(null);y.useEffect(()=>{let B=!1;return Qj(e).then(Y=>{B||(c(Y),w(Y.agentId??""),C(Y.workspace??""),T(Y.approvalMode??""),R(Y.thinkingLevel??""))}).catch(Y=>{B||h(Ae(Y))}),Ml(e).then(Y=>{B||(f(Y),z(Y.defaultModel??null))}).catch(Y=>{B||h(Ae(Y))}),()=>{B=!0}},[e]);const E=o!==null&&(v!==(o.agentId??"")||S.trim()!==(o.workspace??"")||N!==(o.approvalMode??"")||_!==(o.thinkingLevel??"")),L=u!==null&&D!==null&&!zt(u.defaultModel,D),F=async()=>{if(x||!E&&!L)return;g(!0);let B=null;try{if(E){const Y={...v?{agentId:v}:{},...S.trim()?{workspace:S.trim()}:{},...N?{approvalMode:N}:{},..._?{thinkingLevel:_}:{}},q=await jE(e,Y);c(q),n&&dH(n.userId,e),B={projectId:e,defaults:q}}if(L&&D){const Y=await ME(e,{provider:D.provider,modelId:D.modelId});f(q=>q&&{...q,defaultModel:Y.defaultModel}),n&&iM(n.userId,e),B={...B??{projectId:e},defaultModel:Y.defaultModel}}B&&yt(d.common.saved)}catch(Y){Be(Ae(Y))}finally{B&&xH(B),g(!1)}},V=o?.agentId?(()=>{const B=s.find(Y=>Y.agentId===o.agentId);return B?_n(B):o.agentId})():d.project.chatDefaultsNotSet,P=u?.models.find(B=>zt(B,u.defaultModel));return a.jsxs("div",{children:[a.jsxs("p",{className:"mb-2 flex items-center gap-1.5 text-xs font-medium text-gray-500",children:[d.project.chatDefaultsTitle,a.jsx(ba,{label:d.project.chatDefaultsTitle,children:d.project.chatDefaultsHint})]}),p?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:p}):o===null||u===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):t?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[a.jsxs(Ss,{label:d.project.chatDefaultsAgent,size:"sm",value:v,onChange:B=>w(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsNotSet}),s.map(B=>a.jsx("option",{value:B.agentId,children:_n(B)},B.agentId))]}),a.jsxs(Ss,{label:d.chat.approvalMode,size:"sm",value:N,onChange:B=>T(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsApprovalNotSet}),Mq.map(B=>a.jsx("option",{value:B,children:d.chat.approvalModeNames[B]??B},B))]}),a.jsxs(Ss,{label:d.chat.thinkingLevel,size:"sm",value:_,onChange:B=>R(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsThinkingNotSet}),ST.map(B=>a.jsx("option",{value:B,children:d.chat.thinkingLevelNames[B]??B},B))]}),a.jsxs("div",{children:[a.jsxs("span",{className:"mb-1 flex items-center gap-1",children:[a.jsx(Yn,{block:!1,children:d.chat.model}),a.jsx(ba,{label:d.chat.model,children:d.project.chatDefaultsModelHint})]}),u.models.length>0?a.jsx(a.Fragment,{children:a.jsx(Ay,{models:u.models,value:D,defaultModel:u.defaultModel,onChange:z,disabled:x,variant:"form"})}):a.jsx("p",{className:"text-xs text-gray-400",children:d.models.empty})]}),a.jsxs("div",{className:"sm:col-span-2",children:[a.jsx(Yn,{children:d.chat.workspace}),a.jsx(sd,{projectId:e,workspace:S,onChange:C,variant:"form"}),a.jsx(wo,{children:d.chat.workspaceHintShort})]})]}),a.jsx("div",{className:"mt-3 flex justify-end",children:a.jsx(ge,{size:"sm",disabled:x||!E&&!L,onClick:()=>{F()},children:d.common.save})})]}):a.jsx("div",{className:"space-y-1 text-sm",children:[[d.project.chatDefaultsAgent,V],[d.chat.workspace,o.workspace??d.chat.workspaceAuto],[d.chat.approvalMode,o.approvalMode?d.chat.approvalModeNames[o.approvalMode]??o.approvalMode:d.project.chatDefaultsApprovalNotSet],[d.chat.thinkingLevel,o.thinkingLevel?d.chat.thinkingLevelNames[o.thinkingLevel]??o.thinkingLevel:d.project.chatDefaultsThinkingNotSet],[d.chat.model,P?P.displayName??P.modelId:d.project.chatDefaultsNotSet]].map(([B,Y])=>a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"w-24 shrink-0 text-xs text-gray-500",children:B}),a.jsx("span",{className:"min-w-0 flex-1 break-all",children:Y})]},B))})]})}function Dq(e,t){return e.name===t.name&&e.pattern===t.pattern&&(e.description??"")===(t.description??"")&&e.enabled===t.enabled}function V2({initial:e,onApply:t,onCancel:n}){const[s,o]=y.useState(e?.name??""),[c,u]=y.useState(e?.pattern??""),[f,p]=y.useState(e?.description??""),[h,x]=y.useState(void 0),g=()=>{const v=s.trim(),w=c.trim();if(!v||!w)return;try{new RegExp(w)}catch{x(d.project.commandPolicyInvalidPattern);return}const S=f.trim();t({name:v,pattern:w,...S!==""?{description:S}:{},enabled:e?.enabled??!0})};return a.jsxs("div",{className:"space-y-2 py-3",children:[a.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[a.jsx("div",{className:"sm:w-40",children:a.jsx(at,{size:"sm",label:d.project.commandPolicyRuleName,required:!0,value:s,maxLength:64,autoFocus:!0,onChange:v=>o(v.target.value)})}),a.jsx("div",{className:"min-w-0 flex-1",children:a.jsx(at,{size:"sm",className:"font-mono",label:d.project.commandPolicyRulePattern,required:!0,value:c,maxLength:512,...h!==void 0?{error:h}:{},onChange:v=>{u(v.target.value),h&&x(void 0)},onKeyDown:v=>{v.key==="Enter"&&g()}})})]}),a.jsx(at,{size:"sm",label:d.project.commandPolicyRuleDesc,value:f,maxLength:300,onChange:v=>p(v.target.value)}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(ge,{size:"sm",variant:"ghost",onClick:n,children:d.common.cancel}),a.jsx(ge,{size:"sm",disabled:!s.trim()||!c.trim(),onClick:g,children:d.project.commandPolicyApplyRule})]})]})}function $q({projectId:e,isOwner:t}){const[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(!1),[p,h]=y.useState(!0),[x,g]=y.useState([]),[v,w]=y.useState(null);y.useEffect(()=>{let N=!1;return s(null),c(null),w(null),CE(e).then(T=>{N||(s(T),h(T.enabled),g(T.rules))}).catch(T=>{N||c(Ae(T))}),()=>{N=!0}},[e]);const S=n!==null&&(p!==n.enabled||x.length!==n.rules.length||x.some((N,T)=>!Dq(N,n.rules[T]))),C=async()=>{if(!(u||!S)){f(!0);try{const N=await NE(e,{enabled:p,rules:x});s(N),h(N.enabled),g(N.rules),yt(d.common.saved)}catch(N){Be(Ae(N))}finally{f(!1)}}};return a.jsx("div",{children:o!==null?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:o}):n===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:a.jsx(xl,{title:d.project.commandPolicyEnable,description:d.project.commandPolicyEnableDesc,children:t?a.jsx(js,{checked:p,onChange:h,disabled:u}):a.jsx("span",{className:"text-xs text-gray-400",children:p?d.project.commandPolicyOn:d.project.commandPolicyOff})})}),a.jsxs("div",{className:p?"":"opacity-50",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-gray-100 py-1.5 dark:border-gray-800/60",children:[a.jsxs("p",{className:"text-xs font-medium text-gray-500",children:[d.project.commandPolicyRules," ·"," ",a.jsx("span",{className:"font-semibold",children:x.length})]}),t&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>g(n.defaultRules.map(N=>({...N}))),children:d.project.commandPolicyRestore}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>w("new"),children:d.project.commandPolicyAddRule})]})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[v==="new"&&a.jsx(V2,{initial:null,onApply:N=>{g([N,...x]),w(null)},onCancel:()=>w(null)}),x.map((N,T)=>v===T?a.jsx(V2,{initial:N,onApply:_=>{g(x.map((R,D)=>D===T?_:R)),w(null)},onCancel:()=>w(null)},`edit-${T}`):a.jsxs("div",{className:`flex items-center gap-3 py-2.5 ${N.enabled?"":"opacity-60"}`,children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm font-medium",children:N.name}),N.description!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-400",children:N.description}),a.jsx("p",{className:"mt-0.5 truncate font-mono text-[11px] text-gray-400",title:N.pattern,children:N.pattern})]}),t?a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx(js,{checked:N.enabled,disabled:u||!p,onChange:_=>g(x.map((R,D)=>D===T?{...R,enabled:_}:R))}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>w(T),children:d.project.commandPolicyEditRule}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>g(x.filter((_,R)=>R!==T)),children:d.common.delete})]}):a.jsx("span",{className:"shrink-0 text-xs text-gray-400",children:N.enabled?d.project.commandPolicyOn:d.project.commandPolicyOff})]},`${N.name}-${T}`)),x.length===0&&v!=="new"&&a.jsx("p",{className:"py-3 text-xs text-gray-400",children:d.project.commandPolicyEmpty})]})]}),t&&a.jsx("div",{className:"mt-2 flex justify-end border-t border-gray-100 pt-3 dark:border-gray-800/60",children:a.jsx(ge,{size:"sm",disabled:u||!S||v!==null,onClick:()=>{C()},children:d.common.save})})]})})}function Uq({status:e,checkPending:t,menuItemClass:n,onInstallRequest:s}){const o=FC(e,t),c=o.action==="none",u=o.labelKind==="checking"?d.update.checking:o.labelKind==="downloading"?d.update.clientDownloading(o.version,o.percent):o.labelKind==="install"?d.update.clientRestartToInstall(o.version):d.update.clientCheckNow,f=o.labelKind==="unsupported"?o.unsupportedReason==="linux-not-appimage"?d.update.clientUnsupportedNonAppImage:d.update.clientUnsupportedDev:null,p=a.jsxs("button",{type:"button",disabled:c,onClick:()=>{o.action==="install"?s():o.action==="check"&&dI()},className:`${n} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.busy&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"}),!o.busy&&o.labelKind==="install"&&a.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]"}),a.jsx("span",{className:"min-w-0 truncate",children:u})]}),o.appVersion!==null&&a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:`v${o.appVersion}`})]});return f!==null?a.jsx("span",{className:"block",title:f,children:p}):p}function Pq({version:e,newVersion:t,checking:n,menuItemClass:s,onCheck:o,onOpenDialog:c}){const u=t!==null,f=n?d.update.checking:u?d.update.newVersion(t):d.update.checkNow;return a.jsxs("button",{type:"button",disabled:n,onClick:u?c:o,className:`${s} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[n&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"}),!n&&u&&a.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]"}),a.jsx("span",{className:"min-w-0 truncate",children:f})]}),e!==null&&a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:`v${e}`})]})}function zq({open:e,onClose:t,latestVersion:n,releaseUrl:s=null,canUpdate:o,onRunFinished:c}){const[u,f]=y.useState("confirm"),[p,h]=y.useState(null);y.useEffect(()=>{e&&(f("confirm"),h(null))},[e]);const x=()=>{u==="done"&&c?.(),t()},g=async()=>{f("running");try{h(await $A())}catch(w){h({status:"failed",output:Ae(w),needsRestart:!1})}f("done")},v=p===null?null:p.status==="updated"?{text:d.update.updated,className:sn.success}:p.status==="unsupported"?{text:d.update.unsupported,className:sn.attention}:{text:d.update.failed,className:sn.danger};return a.jsx(Yt,{open:e,title:o?d.update.updateNow:n!==null?d.update.newVersion(n):d.update.releaseNotes,onClose:u==="running"?()=>{}:x,footer:u==="done"||!o?a.jsx(ge,{onClick:x,children:d.common.close}):a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:x,disabled:u==="running",children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:u==="running",onClick:()=>{g()},children:u==="running"?d.update.updating:d.update.updateNow})]}),children:u==="done"&&p!==null&&v!==null?a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:`text-sm font-medium ${v.className}`,children:v.text}),p.status==="updated"&&a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:d.update.restartHint}),p.output!==""&&a.jsx("pre",{className:"max-h-56 overflow-auto rounded-md bg-gray-100 p-3 text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:bg-gray-800 dark:text-gray-300",children:oT(p.output)})]}):a.jsxs("div",{className:"space-y-2",children:[n!==null&&a.jsx("p",{className:"text-sm font-medium",children:d.update.newVersion(n)}),s!==null&&a.jsx("p",{children:a.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-brand-600 underline-offset-2 hover:underline dark:text-brand-300",children:d.update.releaseNotes})}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:o?d.update.confirmBody:d.update.adminOnly}),u==="running"&&a.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:d.update.updating})]})})}function Bq(e){return!(e.desktopMode&&e.sessionVia==="desktop")}const Hq=[{key:"general",group:"personal",visible:()=>!0},{key:"appearance",group:"personal",visible:()=>!0},{key:"account",group:"personal",visible:e=>Bq(e)},{key:"proxy",group:"server",visible:e=>e.isAdmin},{key:"uploads",group:"server",visible:e=>e.isAdmin},{key:"users",group:"server",visible:e=>e.isAdmin&&!e.desktopMode}];function Fq(e){return Hq.filter(t=>t.visible(e)).map(({key:t,group:n})=>({key:t,group:n}))}function qq(e){const t=[];for(const n of e)t.includes(n.group)||t.push(n.group);return t}function Vq(e,t){return t.some(n=>n.key===e)?e:t[0]?.key??null}const Gq=e=>`flex w-full items-center gap-2 whitespace-nowrap rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${e?"bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`;function Kq({open:e,onClose:t,title:n,groups:s,active:o,onSelect:c,children:u}){const f=s.length>1,p=s.flatMap(x=>x.items).find(x=>x.key===o),h=p?.label??n;return a.jsx(Yt,{open:e,onClose:t,title:n,headerless:!0,bare:!0,widthClass:"sm:max-w-3xl",children:a.jsxs("div",{className:"flex h-[min(40rem,85vh)] flex-col sm:flex-row",children:[a.jsx("nav",{"aria-label":n,className:"flex shrink-0 gap-1 overflow-x-auto border-b border-gray-100 p-2 sm:w-44 sm:flex-col sm:overflow-x-visible sm:overflow-y-auto sm:border-b-0 sm:border-r sm:p-3 dark:border-gray-800",children:s.map(x=>a.jsxs("div",{className:"contents sm:mt-3 sm:block sm:first:mt-0",children:[f&&x.label!==void 0&&a.jsx("p",{className:"hidden px-2.5 pb-1 text-[11px] font-medium uppercase tracking-wide text-gray-400 sm:block dark:text-gray-500",children:x.label}),x.items.map(g=>a.jsxs("button",{type:"button",className:Gq(g.key===o),"aria-current":g.key===o?"page":void 0,onClick:()=>c(g.key),children:[g.icon!==void 0&&a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:g.icon}),a.jsx("span",{className:"min-w-0 truncate",children:g.label})]},g.key))]},x.key))}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 px-4 pt-4 sm:px-6 sm:pt-5",children:[a.jsxs("h2",{className:`flex min-w-0 items-center ${Ro.row} text-lg font-semibold`,children:[h,p?.info!==void 0&&a.jsx(ba,{label:h,children:p.info})]}),a.jsx(Rf,{onClose:t})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3 sm:px-6 sm:pb-6",children:u})]})]})})}function _i({label:e,hint:t,info:n,children:s}){return a.jsxs("div",{className:"flex items-center justify-between gap-4 py-3.5 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("p",{className:`flex items-center ${Ro.row} text-sm font-medium`,children:[e,n!==void 0&&a.jsx(ba,{label:e,children:n})]}),t!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:t})]}),a.jsx("div",{className:"shrink-0",children:s})]})}function Wq({value:e,onChange:t}){return a.jsx("div",{className:"flex items-center gap-1.5",children:cE.map(n=>a.jsx("button",{type:"button",title:d.settings.accentNames[n.value],"aria-label":d.settings.accentNames[n.value],"aria-pressed":e===n.value,onClick:()=>t(n.value),className:`h-5 w-5 rounded-full border transition-transform duration-150 hover:scale-110 ${e===n.value?"border-gray-500 ring-2 ring-gray-400/50 dark:border-gray-300":"border-transparent"}`,style:{backgroundColor:n.color}},n.value))})}const Yq=14*1024*1024;function Xq(){const{projects:e,currentProject:t}=en(),{reload:n}=Ii(),[s,o]=y.useState(""),[c,u]=y.useState(""),[f,p]=y.useState([]),[h,x]=y.useState(!1),g=s!==""?s:t?.projectId??e[0]?.projectId??"",v=f.some(N=>N.agentId===c)?c:(f.find(N=>N.agentId==="default_agent")??f[0])?.agentId??"";y.useEffect(()=>{if(g==="")return;let N=!1;return aC(g).then(T=>{N||p(T.agents)}).catch(()=>{N||p([])}),()=>{N=!0}},[g]);const w=h||v==="",S=async N=>{if(!(g===""||v==="")){x(!0);try{await bA(g,v,{dataBase64:N});const T=e.find(R=>R.projectId===g),_=`${T?wu(T):g} · ${f.find(R=>R.agentId===v)?.name??v}`;g===t?.projectId&&await n(),yt(d.settings.importTraceDone(_))}catch(T){Be(Ae(T))}finally{x(!1)}}},C=N=>{const T=N.target.files?.[0];if(N.target.value="",!T||v==="")return;if(T.size>Yq){Be(d.settings.importTraceTooLarge);return}const _=new FileReader;_.onload=()=>{const R=_.result;S(R.slice(R.indexOf(",")+1))},_.onerror=()=>Be(d.common.unknownError),_.readAsDataURL(T)};return a.jsx(_i,{label:d.settings.importTrace,info:d.settings.importTraceInfo,children:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsx("div",{className:"w-32",children:a.jsx(Ss,{size:"sm",value:g,disabled:h,onChange:N=>{o(N.target.value),u("")},"aria-label":d.settings.importTraceProject,children:e.map(N=>a.jsx("option",{value:N.projectId,children:wu(N)},N.projectId))})}),a.jsx("div",{className:"w-32",children:a.jsx(Ss,{size:"sm",value:v,disabled:w,onChange:N=>u(N.target.value),"aria-label":d.settings.importTraceAgent,children:f.map(N=>a.jsx("option",{value:N.agentId,children:_n(N)},N.agentId))})}),a.jsxs("label",{className:`inline-flex shrink-0 items-center justify-center gap-1 rounded-md border border-gray-300 px-3 py-1 text-sm font-medium transition-colors duration-150 dark:border-gray-700 ${w?"pointer-events-none opacity-60":"cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:[a.jsx(Xl,{accept:".jsonl",disabled:w,onChange:C}),a.jsx(YC,{size:14}),h?d.settings.importTraceRunning:d.settings.importTracePick]})]})})}function Qq(){const{lang:e,setLang:t}=Dr(),{currency:n,setCurrency:s}=as(),o=[{value:"en",label:d.settings.langEn},{value:"zh",label:d.settings.langZh},{value:"system",label:d.settings.followSystem}],c=[{value:"USD",label:d.models.currencyUsd},{value:"CNY",label:d.models.currencyCny}];return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.settings.language,info:d.settings.languageInfo,children:a.jsx(ws,{options:o,value:e,onChange:t})}),a.jsx(_i,{label:d.models.currency,info:d.settings.currencyInfo,children:a.jsx(ws,{options:c,value:n,onChange:s,cols:2})}),a.jsx(Xq,{})]})}function Zq(){const{mode:e,setMode:t,fontScale:n,setFontScale:s,accent:o,setAccent:c,terminalMode:u,setTerminalMode:f}=as(),p=[{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark},{value:"system",label:d.settings.followSystem}],h=[{value:"app",label:d.settings.followAppTheme},{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark}],x=[{value:"sm",label:d.settings.fontSmall},{value:"md",label:d.settings.fontMedium},{value:"lg",label:d.settings.fontLarge}];return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.settings.theme,info:d.settings.themeInfo,children:a.jsx(ws,{options:p,value:e,onChange:t})}),a.jsx(_i,{label:d.settings.terminalTheme,info:d.settings.terminalThemeInfo,children:a.jsx(ws,{options:h,value:u,onChange:f})}),a.jsx(_i,{label:d.settings.fontSize,info:d.settings.fontSizeInfo,children:a.jsx(ws,{options:x,value:n,onChange:s})}),a.jsx(_i,{label:d.settings.accent,info:d.settings.accentInfo,children:a.jsx(Wq,{value:o,onChange:c})})]})}function _M({open:e,onClose:t}){const{refresh:n,sessionVia:s}=mn(),o=s==="desktop",[c,u]=y.useState(""),[f,p]=y.useState(""),[h,x]=y.useState(""),[g,v]=y.useState({}),[w,S]=y.useState(!1),C=()=>v(T=>T.old||T.new||T.confirm?{}:T);y.useEffect(()=>{e&&(u(""),p(""),x(""),v({}))},[e]);const N=async()=>{const T={};if(!o&&!c&&(T.old=d.common.requiredField),f||(T.new=d.common.requiredField),h||(T.confirm=d.common.requiredField),!T.confirm&&f!==h&&(T.confirm=d.account.passwordMismatch),T.old||T.new||T.confirm){v(T);return}S(!0),v({});try{await fE(o?{newPassword:f}:{oldPassword:c,newPassword:f}),await n(),t()}catch(_){_ instanceof xr&&_.code==="invalid_password"?v({new:Ae(_)}):v({old:Ae(_)})}finally{S(!1)}};return a.jsx(Yt,{open:e,title:d.account.changePassword,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:w,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:w,onClick:()=>{N()},children:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[!o&&a.jsx(ts,{label:d.account.oldPassword,required:!0,size:"sm",value:c,onChange:T=>{u(T.target.value),C()},error:g.old,autoComplete:"current-password",info:d.account.oldPasswordHint,infoLabel:d.account.oldPassword,autoFocus:!0}),a.jsx(ts,{label:d.account.newPassword,required:!0,size:"sm",value:f,onChange:T=>{p(T.target.value),C()},error:g.new,autoComplete:"new-password",hint:d.auth.passwordHint,autoFocus:o}),a.jsx(ts,{label:d.account.confirmPassword,required:!0,size:"sm",value:h,onChange:T=>{x(T.target.value),C()},error:g.confirm,autoComplete:"new-password"})]})})}function Jq(){const[e,t]=y.useState(!1);return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.account.changePassword,info:d.settings.changePasswordInfo,children:a.jsx(ge,{variant:"secondary",onClick:()=>t(!0),children:d.account.changePassword})}),a.jsx(_M,{open:e,onClose:()=>t(!1)})]})}function RM({actions:e,children:t}){return a.jsxs("section",{children:[a.jsx("div",{className:"space-y-4",children:t}),e!==void 0&&a.jsx("div",{className:"mt-5 flex justify-end gap-2 border-t border-gray-100 pt-4 dark:border-gray-800/60",children:e})]})}function eV(){const[e,t]=y.useState(null),[n,s]=y.useState(!0),[o,c]=y.useState(!0),[u,f]=y.useState(""),[p,h]=y.useState(null),[x,g]=y.useState(!1),v=C=>{t(C),s(C.proxyForApp),c(C.proxyForAgent),f(C.proxyUrl??"")};y.useEffect(()=>{let C=!1;return Yj().then(N=>{C||v(N.settings)}).catch(N=>{C||Be(Ae(N))}),()=>{C=!0}},[]);const w=async()=>{if(e===null||x)return;if(n===e.proxyForApp&&o===e.proxyForAgent&&u.trim()===(e.proxyUrl??"")){wr(d.common.noChangesToSave);return}g(!0),h(null);try{const N=await Xj({proxyForApp:n,proxyForAgent:o,proxyUrl:u});v(N.settings),yt(d.common.saved)}catch(N){N instanceof xr&&N.code==="invalid_proxy_url"?h(Ae(N)):Be(Ae(N))}finally{g(!1)}},S=e!==null;return a.jsxs(RM,{actions:a.jsx(ge,{variant:"primary",disabled:!S||x,onClick:()=>{w()},children:d.common.save}),children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-sm font-medium",children:d.settings.proxyForApp}),a.jsx(js,{checked:n,onChange:s,disabled:!S})]}),a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-sm font-medium",children:d.settings.proxyForAgent}),a.jsx(js,{checked:o,onChange:c,disabled:!S})]}),a.jsx(at,{label:d.settings.proxyAddress,size:"sm",value:u,placeholder:d.settings.proxyAddressPlaceholder,disabled:!S,...p!==null?{error:p}:{},onChange:C=>{f(C.target.value),p!==null&&h(null)}})]})}function tV(){const{uploadLimits:e,refresh:t}=mn(),[n,s]=y.useState(null),[o,c]=y.useState(""),[u,f]=y.useState(""),[p,h]=y.useState(null),[x,g]=y.useState(!1),v=C=>{s(C),c(String(C.attachmentMaxMb)),f(String(C.attachmentTotalMb))};y.useEffect(()=>{let C=!1;return Yj().then(N=>{C||v(N.settings)}).catch(N=>{C||Be(Ae(N))}),()=>{C=!0}},[]);const w=async()=>{if(n===null||x)return;const C=Number(o.trim()),N=Number(u.trim()),T=o.trim()===""||!Number.isInteger(C),_=u.trim()===""||!Number.isInteger(N);if(T||_){h({text:d.errors.byCode.invalid_attachment_limit,max:T,total:_});return}if(C===n.attachmentMaxMb&&N===n.attachmentTotalMb){wr(d.common.noChangesToSave);return}g(!0),h(null);try{const R=await Xj({attachmentMaxMb:C,attachmentTotalMb:N});v(R.settings),await t().catch(()=>{}),yt(d.common.saved)}catch(R){R instanceof xr&&R.code==="invalid_attachment_limit"?h({text:Ae(R),max:!0,total:!0}):Be(Ae(R))}finally{g(!1)}},S=n!==null;return a.jsxs(RM,{actions:a.jsx(ge,{variant:"primary",disabled:!S||x,onClick:()=>{w()},children:d.common.save}),children:[a.jsx(at,{label:d.settings.attachmentMaxMb,required:!0,size:"sm",type:"number",inputMode:"numeric",min:e.attachmentLimitMinMb,max:e.attachmentLimitMaxMb,hint:d.settings.attachmentMaxMbHint(e.attachmentLimitMinMb,e.attachmentLimitMaxMb),value:o,disabled:!S,...p?.max===!0?{error:p.text}:{},onChange:C=>{c(C.target.value),p!==null&&h(null)}}),a.jsx(at,{label:d.settings.attachmentTotalMb,required:!0,size:"sm",type:"number",inputMode:"numeric",min:e.attachmentLimitMinMb,max:e.attachmentLimitMaxMb,hint:d.settings.attachmentTotalMbHint(e.attachmentLimitMinMb,e.attachmentLimitMaxMb),value:u,disabled:!S,...p?.total===!0?p.max?{invalid:!0}:{error:p.text}:{},onChange:C=>{f(C.target.value),p!==null&&h(null)}})]})}function nV(){const{user:e,desktopMode:t}=mn(),[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(!1),[p,h]=y.useState(null),[x,g]=y.useState(null),v=y.useCallback(async()=>{try{s((await pE()).users),c(null)}catch(w){c(Ae(w))}},[]);return y.useEffect(()=>{e?.isAdmin&&!t&&v()},[e?.isAdmin,t,v]),e&&(!e.isAdmin||t)?null:a.jsxs("div",{children:[a.jsx("div",{className:"mb-4 flex justify-end",children:a.jsx(ge,{variant:"primary",onClick:()=>f(!0),children:d.admin.createUser})}),n===null?a.jsx("p",{className:"text-sm text-gray-400",children:d.common.loading}):a.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-800",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-100 bg-gray-50 text-left text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400",children:[a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.username}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.role}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.created}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 text-right font-medium",children:d.common.actions})]})}),a.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:n.map(w=>a.jsxs("tr",{children:[a.jsxs("td",{className:"whitespace-nowrap px-3 py-2 font-medium",children:[w.userId,w.passwordIsInitial&&a.jsx("span",{className:"ml-2 align-middle",children:a.jsx(On,{tone:"gray",children:d.admin.initialPasswordFlag})})]}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2",children:a.jsx(On,{tone:"gray",children:w.isAdmin?d.admin.roleAdmin:d.admin.roleUser})}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400",children:Jr(w.createdAt)}),a.jsxs("td",{className:"whitespace-nowrap px-3 py-1.5 text-right",children:[a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>h(w),children:d.admin.resetPassword}),!w.isAdmin&&a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>g(w),children:d.common.delete})]})]},w.userId))})]})}),o&&a.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:o}),a.jsx(rV,{open:u,onClose:()=>f(!1),onDone:()=>{f(!1),v()}}),a.jsx(aV,{user:p,onClose:()=>h(null)}),a.jsx(sV,{user:x,onClose:()=>g(null),onDone:()=>{g(null),v()}})]})}function rV({open:e,onClose:t,onDone:n}){const[s,o]=y.useState(""),[c,u]=y.useState(""),[f,p]=y.useState({}),[h,x]=y.useState(!1),g=()=>p(w=>w.userId||w.password?{}:w);y.useEffect(()=>{e&&(o(""),u(""),p({}))},[e]);const v=async()=>{const w=s.trim(),S={};if(w?q2.test(w)||(S.userId=d.auth.usernameHint):S.userId=d.common.requiredField,c||(S.password=d.common.requiredField),S.userId||S.password){p(S);return}x(!0),p({});try{await hE({userId:w,password:c}),n()}catch(C){C instanceof xr&&C.code==="invalid_password"?p({password:Ae(C)}):p({userId:Ae(C)})}finally{x(!1)}};return a.jsx(Yt,{open:e,title:d.admin.createUser,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:h,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:h,onClick:()=>{v()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{label:d.common.username,required:!0,size:"sm",value:s,onChange:w=>{o(w.target.value),g()},error:f.userId,hint:d.auth.usernameHint,autoFocus:!0}),a.jsx(ts,{label:d.admin.initialPassword,required:!0,size:"sm",value:c,onChange:w=>{u(w.target.value),g()},error:f.password,autoComplete:"new-password",hint:d.auth.passwordHint}),q2.test(s.trim())&&a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.admin.defaultProjectNote(`${s.trim()}-default_project`)})]})})}function aV({user:e,onClose:t}){const[n,s]=y.useState(""),[o,c]=y.useState(void 0),[u,f]=y.useState(!1);y.useEffect(()=>{e&&(s(""),c(void 0))},[e]);const p=async()=>{if(e){if(!n){c(d.common.requiredField);return}f(!0),c(void 0);try{await gE(e.userId,{password:n}),t()}catch(h){c(Ae(h))}finally{f(!1)}}};return a.jsx(Yt,{open:e!==null,title:e?d.admin.resetPasswordTitle(e.userId):"",onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:u,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:u,onClick:()=>{p()},children:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(ts,{label:d.admin.initialPassword,required:!0,size:"sm",value:n,onChange:h=>{s(h.target.value),c(void 0)},error:o,autoComplete:"new-password",hint:d.auth.passwordHint,autoFocus:!0}),a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.admin.resetPasswordNote})]})})}function sV({user:e,onClose:t,onDone:n}){const[s,o]=y.useState(!1),[c,u]=y.useState(null),[f,p]=y.useState(!1);y.useEffect(()=>{e&&(o(!1),u(null))},[e]);const h=async()=>{if(e){p(!0),u(null);try{await xE(e.userId),n()}catch(x){u(Ae(x))}finally{p(!1)}}};return a.jsx(Yt,{open:e!==null,title:e?d.admin.deleteUserTitle(e.userId):"",onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:f,children:d.common.cancel}),s?a.jsx(ge,{variant:"danger",disabled:f,onClick:()=>{h()},children:d.common.confirm}):a.jsx(ge,{variant:"danger",onClick:()=>o(!0),children:d.common.delete})]}),children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:e?d.admin.deleteUserConfirm(e.userId):""}),c&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:c})]})})}const iV={general:If,appearance:"M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4l1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4m11.4-11.4l1.4-1.4",account:"M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z",proxy:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",uploads:"M12 15V4m0 0L7 9m5-5l5 5M4 20h16",users:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"};function oV({open:e,onClose:t}){const{user:n,desktopMode:s,sessionVia:o,uploadLimits:c}=mn(),u=Fq({isAdmin:n?.isAdmin===!0,desktopMode:s,sessionVia:o}),[f,p]=y.useState(null);y.useEffect(()=>{e&&p(null)},[e]);const h=Vq(f,u);if(h===null)return null;const x={general:d.settings.generalTitle,appearance:d.settings.appearanceTitle,account:d.settings.accountTitle,proxy:d.settings.proxyTitle,uploads:d.settings.uploadLimitsTitle,users:d.admin.users},g={personal:d.settings.groupPersonal,server:d.settings.groupServer},v={proxy:d.settings.proxyInfo,uploads:d.settings.uploadLimitsInfo(c.attachmentMaxCount,c.imageMaxMb)},w=qq(u).map(S=>({key:S,label:g[S],items:u.filter(C=>C.group===S).map(C=>({key:C.key,label:x[C.key],icon:a.jsx(vn,{d:iV[C.key],size:16}),...v[C.key]!==void 0?{info:v[C.key]}:{}}))}));return a.jsxs(Kq,{open:e,onClose:t,title:d.settings.systemSettings,groups:w,active:h,onSelect:p,children:[h==="general"&&a.jsx(Qq,{}),h==="appearance"&&a.jsx(Zq,{}),h==="account"&&a.jsx(Jq,{}),h==="proxy"&&a.jsx(eV,{}),h==="uploads"&&a.jsx(tV,{}),h==="users"&&a.jsx(nV,{})]})}const Jm="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";function lV({size:e=16}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[a.jsx("circle",{cx:"5",cy:"12",r:"2"}),a.jsx("circle",{cx:"12",cy:"12",r:"2"}),a.jsx("circle",{cx:"19",cy:"12",r:"2"})]})}const G2="M21 21l-4.35-4.35M17 11a6 6 0 1 1-12 0 6 6 0 0 1 12 0z",cV="M21 5h-7M10 5H3M21 12h-9M8 12H3M21 19h-5M12 19H3M14 2v6M8 9v6M16 16v6",uV="M18 6L6 18M6 6l12 12",dV="application/x-penguin-session-id",IM="application/x-penguin-group-key",K2=e=>e.dataTransfer.types.includes(IM),W2="(hover: hover) and (pointer: fine)";function Y2({base:e,size:t=15}){return a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a.jsx("g",{transform:"translate(-1 -1) scale(0.82)",children:a.jsx("path",{d:e})}),a.jsx("path",{d:"M18.5 15.5v6M15.5 18.5h6",strokeWidth:"2"})]})}const Zc="block w-full px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800",Jc=e=>`flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${e?"bg-gray-200/70 text-gray-700 dark:bg-gray-800 dark:text-gray-200":"text-gray-400 hover:bg-gray-200/50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"}`,X2="px-2.5 pb-0.5 pt-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500",mV=e=>`penguin.sidebarCollapsedGroups.${e}`,fV=e=>`penguin.sidebarPinnedGroups.${e}`;function Om(e){if(!e)return new Set;try{const t=JSON.parse(localStorage.getItem(e)??"[]");return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function Q2(e,t){if(e)try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}const Dm=(e,t)=>`${t}\0${e}`,Jg="\0drafts";function pV({activity:e}){return e===null?a.jsx("span",{"aria-hidden":"true",className:"block h-3 w-3 shrink-0"}):a.jsx(vN,{activity:e})}function Z2({onNavigate:e,onCollapse:t}){const n=yr(),{user:s,logout:o,desktopMode:c,sessionVia:u}=mn(),{locale:f}=Dr(),{projects:p,currentProject:h,setCurrentProjectId:x,reloadProjects:g,agents:v,currentAgent:w,setCurrentAgentId:S}=en(),{sessions:C,byAgent:N,countsByAgent:T,workspaceCountsByAgent:_,isLoadedFor:R,hasMoreFor:D,loadMoreFor:z,loading:E,remove:L,replace:F}=Ii(),P=Mx("/chat/:sessionId")?.params.sessionId??null,[B,Y]=y.useState(!1),[q,K]=y.useState(!1),[H,$]=y.useState(!1),[X,le]=y.useState(!1),[ie,I]=y.useState(!1),A=HC({desktopMode:c,sessionVia:u}),Q=VC(A,q),[j,U]=y.useState(!1),{version:ee,update:re}=Px(q),ke=zx(),be=GC(re),[ye,Se]=y.useState(!1),[Me,ze]=y.useState(!1),De=h?.projectId??null,ct=VI(De),bt=De===null?null:mV(De),he=De===null?null:fV(De),[ne,oe]=y.useState(YI),[J,ht]=y.useState(bg),[ve,Xe]=y.useState(()=>Om(bt)),[Ge,He]=y.useState(()=>Om(he)),[Pe,W]=y.useState(()=>dw(De)),[me,Ue]=y.useState(s6),[pe,$e]=y.useState(()=>vg(De,bg())),[nt,gt]=y.useState(()=>kg(De,bg())),[Ke,dt]=y.useState(()=>fw(De)),[pt,wt]=y.useState(null),[st,Bt]=y.useState(""),[Sn,Dn]=y.useState(null),[Vt,ar]=y.useState(!1),[zn,Xt]=y.useState(""),[Cn,lr]=y.useState(!1),[Mt,Pr]=y.useState(()=>window.matchMedia(W2).matches);y.useEffect(()=>{const G=window.matchMedia(W2),Ce=Ze=>Pr(Ze.matches);return G.addEventListener("change",Ce),()=>G.removeEventListener("change",Ce)},[]);const[Bn,Nr]=y.useState(null),[Tr,Te]=y.useState(null),[Ie,ut]=y.useState(null),[St,gn]=y.useState(null);y.useEffect(()=>{Xe(Om(bt)),He(Om(he)),W(dw(De)),$e(vg(De,J)),gt(kg(De,J)),dt(fw(De)),Mr(0),cr(new Map)},[bt,he,De]);const[Nn,Hn]=y.useState(new Set),[Dt,Rn]=y.useState(new Set),[zr,cr]=y.useState(new Map),[Js,Mr]=y.useState(0),[ta,Br]=y.useState(null),[is,Hr]=y.useState(!1),[fn,Fr]=y.useState(null),qr=pH(s?.userId??null,De),[pn,na]=y.useState(null),[Jn,Er]=y.useState(""),[ur,os]=y.useState(!1),[ls,ra]=y.useState(null),[cs,ka]=y.useState(null),Ar=G=>{NI(G),ht(G),$e(vg(De,G)),gt(kg(De,G)),Mr(0),cr(new Map)},er=()=>{const G=!ne;XI(G),oe(G)},Tn=y.useMemo(()=>a6(PR(C),Ke),[C,Ke]),Vr=y.useMemo(()=>UR(_),[_]),wa=y.useMemo(()=>gw(v,G=>G.agentId,{pinned:Ge,order:J==="agent"?nt:[]}),[v,Ge,nt,J]),Mn=y.useMemo(()=>gw(Tn,G=>G.key,{pinned:Ge,order:J==="workspace"?nt:[]}),[Tn,Ge,nt,J]),Gr=y.useMemo(()=>wa.map(G=>G.agentId),[wa]),En=y.useMemo(()=>Mn.map(G=>G.key),[Mn]),us=G=>J==="agent"?G.agentId:J==="time"?zc:vo(G.workspace),hn=G=>{if(Ct)return;const Ce=new Set(ve);Ce.has(G)?Ce.delete(G):Ce.add(G),Xe(Ce),Q2(bt,Ce)},Sa=G=>{const Ce=new Set(Ge);Ce.has(G)?Ce.delete(G):Ce.add(G),He(Ce),Q2(he,Ce)},Ts=G=>{const Ce=QI(Pe,G);W(Ce),mw(De,Ce)},Ga=G=>{i6(G),Ue(G)},Ct=zn.trim()!=="",ds=J==="agent"?wa.length:J==="workspace"?Mn.length:0,ja=DC(ds),br=$C(Js,ds),Ca=G=>Ct?G:aw(G,br),de=()=>!Ct&&ja>1?a.jsx(EI,{page:br,pageCount:ja,onChange:Mr}):null,Re=me==="manual"&&Mt?"manual":"recent",Qe=G=>Ct?G.filter(Ce=>$R(Ce,zn)):G,mt=J==="time"?gg(Qe(C)):null,Et=mt===null?[]:qR(mt.active,Date.now()),Pt=VR(T),Wt=G=>[...T].filter(([,Ce])=>Ce[G]>0).map(([Ce])=>Ce),Ka=Wt("active").filter(G=>D(G,"active")),_r=G=>({active:G,subagent:[],schedule:[],archived:[]}),Rr=()=>{ar(!1),Xt("")},Ir=(G,Ce,Ze)=>{if(!Bn)return;const it=Yx(G,Bn.id,Ce,Ze);if(it===G)return;const tt=l6(pe,it);$e(tt),pw(De,J,tt)},Ui=(G,Ce,Ze)=>{if(Ie===null)return;const it=m6(nt,G,Ie,Ce,Ze);it!==nt&&(gt(it),d6(De,J,it))},ae=(G,Ce)=>{if(!Mt||Ct||!Xx(J))return{header:{},dropEdge:null};const Ze=Ie,it=Ze!==null&&Ze!==G&&Ge.has(Ze)===Ge.has(G),tt=Je=>{const ft=Je.currentTarget.getBoundingClientRect();return Je.clientY-ft.top>ft.height/2};return{header:{draggable:!0,onDragStart:Je=>{Je.dataTransfer.setData(IM,G),Je.dataTransfer.effectAllowed="move",ut(G)},onDragEnd:()=>{ut(null),gn(null)},onDragOver:Je=>{if(!it||!K2(Je))return;Je.preventDefault(),Je.dataTransfer.dropEffect="move";const ft=tt(Je);gn(An=>An?.key===G&&An.after===ft?An:{key:G,after:ft})},onDragLeave:Je=>{const ft=Je.relatedTarget;ft instanceof Node&&Je.currentTarget.contains(ft)||gn(An=>An?.key===G?null:An)},onDrop:Je=>{!it||Ze===null||!K2(Je)||(Je.preventDefault(),Ui(Ce,G,tt(Je)),ut(null),gn(null))}},dropEdge:it&&St?.key===G?St.after?"below":"above":null}},_e=Ct?qr.filter(G=>sx(G).toLowerCase().includes(zn.trim().toLowerCase())):qr,et=_e.length>0||(J==="agent"?wa.some(G=>Qe(N.get(G.agentId)??[]).length>0):J==="time"?mt!==null&&Object.values(mt).some(G=>G.length>0):Mn.some(G=>Qe(G.sessions).length>0)),qe=(G,Ce)=>`${Ce}\0${G}`,vt=G=>J==="workspace"?G:void 0,xn=(G,Ce,Ze)=>{const it=qe(G,Ce);Rn(tt=>new Set(tt).add(it)),z(Ze,Ce,vt(G)).finally(()=>{Rn(tt=>{const Je=new Set(tt);return Je.delete(it),Je})})},tr=(G,Ce,Ze)=>{if(Ct)return;const it=Dm(G,Ce),tt=!Nn.has(it);if(Hn(Je=>{const ft=new Set(Je);return tt?ft.add(it):ft.delete(it),ft}),tt){const Je=vt(G),ft=Ze.filter(An=>!R(An,Ce,Je));ft.length>0&&z(ft,Ce,Je)}},Pi=y.useRef(null);y.useEffect(()=>{if(!P)return;const G=C.find(ft=>ft.sessionId===P);if(!G)return;const Ce=ha(G);if(Ce==="active"||Ce==="archived")return;const Ze=`${J}\0${P}`;if(Pi.current===Ze)return;Pi.current=Ze;const it=J==="agent"?G.agentId:J==="time"?zc:vo(G.workspace),tt=Dm(it,Ce);Hn(ft=>ft.has(tt)?ft:new Set(ft).add(tt));const Je=J==="workspace"?it:void 0;R(G.agentId,Ce,Je)||z([G.agentId],Ce,Je)},[P,C,J,R,z]),y.useEffect(()=>{if(!(J!=="workspace"||Ct))for(const G of aw(Mn,br)){const Ce=Vr.get(G.key),Ze=Ce?.totals.active??0;if(G.sessions.filter(ft=>ha(ft)==="active").length>=Math.min(bs,Ze))continue;const Je=[...new Set([...Ce?.agents.active??[],...G.sessions.map(ft=>ft.agentId)])].filter(ft=>!R(ft,"active",G.key));Je.length>0&&z(Je,"active",G.key)}},[J,Ct,Mn,br,Vr,R,z]);const ei=async()=>{if(!Me){ze(!0);try{const G=fI(await iw());G.kind==="disabled"?wr(d.update.checkDisabled):G.kind==="failed"?Be(d.update.checkFailed):G.kind==="found"?yt(d.update.foundNew(G.latestVersion)):yt(d.update.upToDate)}catch(G){Be(Ae(G))}finally{ze(!1)}}},id=async G=>{!G.archived&&G.sessionId===P&&Hn(Ce=>new Set(Ce).add(Dm(us(G),"archived")));try{const Ce=await tf(G.sessionId,{archived:!G.archived});F(Ce.session)}catch{}},zi=async()=>{if(!pn)return;const G=Jn.trim();if(G){os(!0),ra(null);try{const Ce=await tf(pn.sessionId,{title:G});F(Ce.session),na(null)}catch(Ce){ra(Ae(Ce))}finally{os(!1)}}},Lo=async()=>{if(!ta)return;Hr(!0);const G=ta;try{await nf(G.sessionId),L(G.sessionId),s&&Du(aM(s.userId,G.sessionId));const Ce=ZI(Pe,G.sessionId);Ce!==Pe&&(W(Ce),mw(De,Ce)),GI(De,G.sessionId);const Ze=c6(pe,G.sessionId);if(Ze!==pe&&($e(Ze),pw(De,J,Ze)),Br(null),P===G.sessionId){const it=(N.get(G.agentId)??[]).filter(tt=>{const Je=ha(tt);return tt.sessionId!==G.sessionId&&(Je==="active"||Je==="schedule")});n(it[0]?`/chat/${it[0].sessionId}`:"/chat")}}catch(Ce){Be(Ae(Ce))}finally{Hr(!1)}},Oo=G=>{n(G),e?.()},nr=(G,Ce)=>{s&&De&&Yl(s.userId,De),G&&S(G);const Ze={...G?{agentId:G}:{},...Ce!==void 0?{workspace:Ce}:{}};n(`/chat/${ya}`,Object.keys(Ze).length>0?{state:Ze}:void 0),e?.()},Ms=()=>{fn&&(s&&De&&lM(s.userId,De,fn.id),P===fn.id&&n(`/chat/${ya}`),Fr(null))},Bi=(v.find(G=>G.agentId==="default_agent")??v[0])?.agentId,Hi=w?.agentId??Bi,Do=CI(J),ms=Do==="agent"?d.agent.create:Do==="chat"?d.chat.newSessionMenu:d.chat.newWorkspaceEntity,Fi=G=>{G!==Ke&&(dt(G),e6(De,G))},qi=G=>{const Ce=t6(Ke,G);if(Ce===Ke)return;Fi(Ce);const Ze=vo(G),it=Mn.findIndex(tt=>tt.key===Ze);Mr(OR(it>=0?it:Mn.length))},$o=y.useMemo(()=>new Set(Ke.map(G=>G.path)),[Ke]),od=G=>{Bt(Ke.find(Ce=>Ce.path===G)?.alias??""),wt({path:G})},ld=()=>{pt&&(Fi(n6(Ke,pt.path,st)),wt(null))},sp=()=>{Sn&&(Fi(r6(Ke,Sn.path)),Dn(null))},ip=G=>{Gx(De,G.sessionId,G.lastActiveAt),S(G.agentId),Oo(`/chat/${G.sessionId}`)},Ql=y.useMemo(()=>new Map(v.map(G=>[G.agentId,_n(G)])),[v]),cd=(G,Ce,Ze,it=!1)=>a.jsx("ul",{className:"space-y-0.5",children:G.map(tt=>{const Je=Ze!==void 0&&Bn?.scope===Ze.scope?Bn:null,ft=Je!==null&&Je.id!==tt.sessionId&&Pe.has(Je.id)===Pe.has(tt.sessionId),An=Ze===void 0?{}:{draggable:!0,onDragStart:Ht=>{Ht.dataTransfer.setData(dV,tt.sessionId),Ht.dataTransfer.effectAllowed="move",Nr({scope:Ze.scope,id:tt.sessionId})},onDragEnd:()=>{Nr(null),Te(null)},onDragOver:Ht=>{if(!Je||!ft)return;Ht.preventDefault();const dr=Ht.currentTarget.getBoundingClientRect(),ti=Ht.clientY-dr.top>dr.height/2;Te(Na=>Na?.id===tt.sessionId&&Na.after===ti?Na:{id:tt.sessionId,after:ti})},onDragLeave:()=>Te(Ht=>Ht?.id===tt.sessionId?null:Ht),onDrop:Ht=>{if(!Je||!ft)return;Ht.preventDefault();const dr=Ht.currentTarget.getBoundingClientRect(),ti=Ht.clientY-dr.top>dr.height/2,Na=Ze.fullRows.filter(Vi=>Pe.has(Vi.sessionId)===Pe.has(Je.id)).map(Vi=>Vi.sessionId);Ir(Na,tt.sessionId,ti),Nr(null),Te(null)},dropEdge:ft&&Tr?.id===tt.sessionId?Tr.after?"below":"above":null};return a.jsx(gV,{s:tt,active:tt.sessionId===P,activity:KI(tt,ct,P),pinned:Pe.has(tt.sessionId),canPin:it,lastActive:UI(tt.lastActiveAt,f),...Ce?{agentHint:Ql.get(tt.agentId)??tt.agentId}:{},...An,onOpen:ip,onTogglePin:Ht=>Ts(Ht.sessionId),onRename:Ht=>{ra(null),Er(Ht.title??""),na(Ht)},onMessaging:Ht=>ka(Ht),onDelete:Ht=>Br(Ht),onToggleArchive:Ht=>{id(Ht)}},tt.sessionId)})}),ud=(G,Ce,Ze,it,tt,Je)=>{const ft=Ze[Ce];if(Ct&&ft.length===0)return null;const An=Ct?ft.length:Math.max(Je?.[Ce]??0,ft.length);if(An===0)return null;const Ht=!Ct&&ft.length<An&&tt.some(dr=>D(dr,Ce,vt(G)));return a.jsx(AI,{label:d.chat.folderGroups[Ce](An),open:Ct||Nn.has(Dm(G,Ce)),onToggle:()=>tr(G,Ce,tt),more:Ht,moreLabel:d.chat.expandRestSessions(Math.max(An-ft.length,0)),pending:Dt.has(qe(G,Ce)),onMore:()=>xn(G,Ce,tt),children:cd(ft,it)},Ce)},op=(G,Ce,Ze)=>{const it=(zr.get(G)??bs)+bs;cr(tt=>{const Je=new Map(tt);return Je.set(G,it),Je}),Ce.length>0&&Ze<it&&xn(G,"active",Ce)},lp=G=>{cr(Ce=>{if(!Ce.has(G))return Ce;const Ze=new Map(Ce);return Ze.delete(G),Ze})},Zl=(G,Ce,Ze,it,tt)=>{const Je=zr.get(G)??bs,ft=o6(Ce.active,Ta=>Ta.sessionId,{pinned:Pe,sortMode:Re,order:pe,recencyOf:Ta=>Ta.lastActiveAt}),An=Ct?ft:ft.slice(0,Je),Ht=Re==="manual"&&!Ct?{scope:G,fullRows:ft}:void 0,dr=tt("active"),ti=dr.length>0&&!dr.some(Ta=>D(Ta,"active",vt(G))),Na=Ct?0:DR({shown:An.length,loaded:Ce.active.length,total:it?.active??0,fullyLoaded:ti}),Vi=!Ct&&Je>bs&&Ce.active.length>bs,dd=rf.map(Ta=>ud(G,Ta,Ce,Ze,tt(Ta),it)),up=Ce.active.length===0&&dd.every(Ta=>Ta===null),dp=Dt.has(qe(G,"active"));return a.jsxs(a.Fragment,{children:[up?a.jsx("p",{className:"px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}):cd(An,Ze,Ht,!0),Na>0&&a.jsx(Km,{label:d.chat.expandRestSessions(Na),ariaLabel:d.chat.expandRestSessions(Na),pending:dp,onClick:()=>op(G,dr,Ce.active.length),className:"mt-0.5"}),Vi&&a.jsx(Km,{label:d.chat.showLess,ariaLabel:d.chat.showLess,onClick:()=>lp(G),...Na>0?{}:{className:"mt-0.5"}}),dd]})},Jl=mt===null?[]:rf.map(G=>ud(zc,G,mt,!0,Wt(G),Pt)),cp=WI.map(G=>({to:`/${G}`,label:d.nav[G],icon:vs[G]}));return a.jsxs("div",{className:"flex h-full w-full flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-1 px-2 pt-2",children:[t&&a.jsx("button",{type:"button",title:d.nav.collapseSidebar,"aria-label":d.nav.collapseSidebar,onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M15 6l-6 6 6 6M4 4v16",size:18})}),a.jsxs(Qn,{open:B,setOpen:Y,className:"min-w-0 flex-1",menuClass:"left-0 right-0 top-full mt-1 origin-top",button:a.jsxs("button",{type:"button",onClick:()=>Y(!B),className:"flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800",children:[a.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:h?wu(h):d.common.loading}),a.jsx("span",{className:"text-gray-400",children:a.jsx(ns,{})})]}),children:[p.map(G=>a.jsxs("button",{type:"button",onClick:()=>{x(G.projectId),Y(!1)},className:`flex w-full items-center justify-between gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${G.projectId===h?.projectId?"font-semibold":""}`,children:[a.jsx("span",{className:"truncate",children:wu(G)}),a.jsx(On,{tone:"gray",children:G.role})]},G.projectId)),a.jsxs("div",{className:"mt-1.5 border-t border-gray-100 pt-1.5 dark:border-gray-800",children:[a.jsxs("button",{type:"button",className:Zc,onClick:()=>{Y(!1),$(!0)},children:["+ ",d.project.create]}),h&&a.jsx("button",{type:"button",className:Zc,onClick:()=>{Y(!1),le(!0)},children:d.project.settings})]})]})]}),a.jsx("div",{className:"shrink-0 px-2 pb-2 pt-2",children:a.jsxs("button",{type:"button",onClick:()=>nr(Bi),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${P===ya?"bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`,children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a.jsx(vn,{d:Jm})}),d.chat.newSessionMenu]})}),a.jsxs("div",{className:"relative min-h-0 flex-1 overflow-y-auto px-2 pb-2",children:[a.jsxs("nav",{className:"space-y-0.5",children:[a.jsx("div",{className:`grid transition-[grid-template-rows] duration-200 ease-out ${ne?"grid-rows-[0fr]":"grid-rows-[1fr]"}`,children:a.jsx("div",{className:"overflow-hidden",inert:ne,children:a.jsx("div",{className:`space-y-0.5 transition-opacity duration-200 ${ne?"opacity-0":"opacity-100"}`,children:cp.map(G=>{const Ce=G.to==="/agents"?ke.kernelNote:null;return a.jsxs(Lx,{to:G.to,onClick:()=>e?.(),...Ce!==null?{title:Ce,"aria-label":`${G.label} · ${Ce}`}:{},className:({isActive:Ze})=>`relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${Ze?"bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`,children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a.jsx(vn,{d:G.icon})}),G.label,Ce!==null&&a.jsx(Mo,{size:"inline",position:"right-2.5 top-1/2 -translate-y-1/2"})]},G.to)})})})}),a.jsx("button",{type:"button",onClick:er,"aria-expanded":!ne,"aria-label":ne?d.nav.expandGroup:d.nav.collapseGroup,title:ne?d.nav.expandGroup:d.nav.collapseGroup,className:"flex h-4 w-full items-center justify-center rounded-md bg-gray-200/70 text-gray-400 transition-colors duration-150 hover:bg-gray-300/60 hover:text-gray-700 dark:bg-gray-800/70 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300",children:a.jsx(ns,{size:12,className:`transition-transform duration-200 ${ne?"":"rotate-180"}`})})]}),a.jsxs("div",{className:`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${Vt?"grid-cols-[0fr_1fr]":"grid-cols-[1fr_1fr]"}`,children:[a.jsx("span",{className:`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${Vt?"opacity-0":"opacity-100"}`,children:d.chat.sessionList}),a.jsxs("div",{className:"flex min-w-0 items-center justify-end gap-0.5",children:[Vt?a.jsxs("div",{className:"flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md border border-gray-300 bg-white px-1.5 transition-colors duration-150 focus-within:border-gray-400 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-500",children:[a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:G2,size:12})}),a.jsx("input",{autoFocus:!0,value:zn,placeholder:d.chat.searchSessionsPlaceholder,"aria-label":d.chat.searchSessions,...Gu,onChange:G=>Xt(G.target.value),onKeyDown:G=>{G.key==="Escape"&&(G.stopPropagation(),Rr())},className:"min-w-0 flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"}),a.jsx("button",{type:"button",title:d.chat.searchClear,"aria-label":d.chat.searchClear,onClick:Rr,className:"flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300",children:a.jsx(vn,{d:uV,size:11})})]}):a.jsx("button",{type:"button",title:d.chat.searchSessions,"aria-label":d.chat.searchSessions,onClick:()=>ar(!0),className:Jc(!1),children:a.jsx(vn,{d:G2,size:14})}),a.jsxs(Qn,{open:Cn,setOpen:lr,portal:{direction:"down",align:"right"},menuClass:"w-40",button:a.jsx("button",{type:"button",title:d.chat.listSettings,"aria-label":d.chat.listSettings,"aria-haspopup":"menu","aria-expanded":Cn,onClick:()=>lr(!Cn),className:Jc(Cn),children:a.jsx(vn,{d:cV,size:14})}),children:[a.jsx("p",{className:X2,children:d.chat.groupModeSection}),a.jsx(eu,{icon:xm.workspace,label:d.chat.groupByWorkspace,checked:J==="workspace",onSelect:()=>{Ar("workspace"),lr(!1)}}),a.jsx(eu,{icon:xm.agent,label:d.chat.groupByAgent,checked:J==="agent",onSelect:()=>{Ar("agent"),lr(!1)}}),a.jsx(eu,{icon:xm.time,label:d.chat.groupByTime,checked:J==="time",onSelect:()=>{Ar("time"),lr(!1)}}),a.jsx("div",{className:"my-1 border-t border-gray-100 dark:border-gray-800"}),a.jsx("p",{className:X2,children:d.chat.sortModeSection}),Mt&&a.jsx(eu,{icon:lw.manual,label:d.chat.sortManual,checked:me==="manual",onSelect:()=>{Ga("manual"),lr(!1)}}),a.jsx(eu,{icon:lw.recent,label:d.chat.sortRecent,checked:me==="recent",onSelect:()=>{Ga("recent"),lr(!1)}})]}),Do==="agent"?a.jsx("button",{type:"button",title:ms,"aria-label":ms,onClick:()=>{n("/agents",{state:{create:!0}}),e?.()},className:Jc(!1),children:a.jsx(Y2,{base:vs.agents})}):Do==="chat"?a.jsx("button",{type:"button",title:ms,"aria-label":ms,onClick:()=>nr(),className:Jc(!1),children:a.jsx(vn,{d:Jm,size:Ye.iconButton})}):a.jsx(sd,{projectId:De??"",workspace:"",onChange:qi,trigger:(G,Ce)=>a.jsx("button",{type:"button",title:ms,"aria-label":ms,"aria-expanded":G,onClick:Ce,className:Jc(G),children:a.jsx(Y2,{base:El})})},De??"no-project")]})]}),_e.length>0&&a.jsxs("div",{className:"pt-2.5",children:[a.jsx(ym,{open:Ct||!ve.has(Jg),onToggle:()=>hn(Jg),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:Jm,size:Ye.groupHeaderGlyph})}),label:d.chat.draftGroup,uppercase:!0,count:_e.length}),(Ct||!ve.has(Jg))&&a.jsx("ul",{className:"space-y-0.5",children:_e.map(G=>a.jsx(hV,{entry:G,active:G.id===P,onOpen:()=>Oo(`/chat/${G.id}`),onDelete:()=>Fr(G)},G.id))})]}),J==="agent"?E&&v.length===0?a.jsx(Sr,{rows:5}):Ca(wa).map(G=>{const Ce=Qe(N.get(G.agentId)??[]);if(Ct&&Ce.length===0)return null;const Ze=gg(Ce),it=!Ct&&ve.has(G.agentId),tt=Ge.has(G.agentId),Je=ae(G.agentId,Gr);return a.jsxs(J2,{dropEdge:Je.dropEdge,children:[a.jsx(ym,{...Je.header,open:!it,onToggle:()=>hn(G.agentId),icon:a.jsx(Ha,{id:G.agentId,name:_n(G),size:18,className:"shrink-0 rounded"}),label:_n(G),uppercase:!0,actions:a.jsxs(a.Fragment,{children:[a.jsx(ej,{pinned:tt,onToggle:()=>Sa(G.agentId)}),a.jsx("button",{type:"button",title:d.chat.newSessionMenu,"aria-label":d.chat.newSessionMenu,onClick:()=>nr(G.agentId),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M12 5v14M5 12h14",size:Ye.groupHeaderAction})}),a.jsx("button",{type:"button",title:d.agent.settings,onClick:()=>Oo(`/agents/${G.agentId}`),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:If,size:Ye.groupHeaderAction})})]})}),it?null:Zl(G.agentId,Ze,!1,T.get(G.agentId),()=>[G.agentId])]},G.agentId)}):null,J==="agent"?de():null,J!=="workspace"?null:E&&C.length===0?a.jsx(Sr,{rows:5}):Mn.length===0&&!Ct?a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}):Ca(Mn).map(G=>{const Ce=Qe(G.sessions);if(Ct&&Ce.length===0)return null;const Ze=gg(Ce),it=!Ct&&ve.has(G.key),tt=Ge.has(G.key),Je=ae(G.key,En),ft=Vr.get(G.key),An=[...new Set(G.sessions.map(dr=>dr.agentId))],Ht=dr=>[...new Set([...ft?.agents[dr]??[],...An])];return a.jsxs(J2,{dropEdge:Je.dropEdge,children:[a.jsx(ym,{...Je.header,open:!it,onToggle:()=>hn(G.key),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:it?El:kI,size:Ye.groupHeaderGlyph})}),label:G.temp?d.chat.tempWorkspaces:G.label,count:Ct?Ze.active.length:Math.max(ft?.totals.active??0,Ze.active.length),...G.fullPath!==null?{title:G.fullPath}:{},actions:a.jsxs(a.Fragment,{children:[a.jsx(ej,{pinned:tt,onToggle:()=>Sa(G.key)}),a.jsx("button",{type:"button",title:d.chat.newSessionInWorkspace,"aria-label":d.chat.newSessionInWorkspace,onClick:()=>nr(Hi,G.fullPath??""),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M12 5v14M5 12h14",size:Ye.groupHeaderAction})}),$o.has(G.key)&&a.jsx(xV,{onRename:()=>od(G.key),onDelete:()=>Dn({path:G.key,label:G.label})})]})}),it?null:Zl(G.key,Ze,!0,ft?.totals,Ht)]},G.key)}),J==="workspace"?de():null,J!=="time"||mt===null?null:E&&C.length===0?a.jsx(Sr,{rows:5}):a.jsxs(a.Fragment,{children:[Et.map(G=>{const Ce=!Ct&&ve.has(G.key);return a.jsxs("div",{className:"pt-2.5",children:[a.jsx(ym,{open:!Ce,onToggle:()=>hn(G.key),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:xm.time,size:Ye.groupHeaderGlyph})}),label:d.chat.timeGroups[G.bucket],uppercase:!0,count:G.sessions.length}),Ce?null:Zl(G.key,_r(G.sessions),!0,void 0,()=>[])]},G.key)}),Et.length===0&&!Ct&&Jl.every(G=>G===null)&&a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}),!Ct&&mt.active.length<Pt.active&&Ka.length>0&&a.jsx(Km,{label:d.chat.loadMoreSessions,ariaLabel:d.chat.loadMoreSessions,pending:Dt.has(qe(zc,"active")),onClick:()=>xn(zc,"active",Ka),className:"mt-1"}),a.jsx("div",{className:"pt-2.5",children:Jl})]}),Ct&&!et&&a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.searchNoMatches})]}),a.jsx("div",{className:"shrink-0 border-t border-gray-200 p-2 dark:border-gray-800",children:a.jsx(Qn,{open:q,setOpen:K,menuClass:"bottom-full left-0 right-0 mb-1 origin-bottom",button:a.jsxs("button",{type:"button",onClick:()=>K(!q),...ke.softwareNote!==null?{title:ke.softwareNote,"aria-label":`${s?.userId??""} · ${ke.softwareNote}`}:{},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800",children:[a.jsxs("span",{className:"relative flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900",children:[(s?.userId??"?").slice(0,1).toUpperCase(),ke.software!==null&&a.jsx(Mo,{})]}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:s?.userId}),s?.isAdmin&&a.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.auth.admin})]}),children:a.jsxs("div",{className:"py-1",children:[a.jsx("button",{type:"button",className:Zc,onClick:()=>{K(!1),I(!0)},children:d.settings.systemSettings}),!c&&a.jsx(Pq,{version:ee?.version??null,newVersion:be,checking:Me,menuItemClass:Zc,onCheck:()=>{ei()},onOpenDialog:()=>{K(!1),Se(!0)}}),A&&a.jsx(Uq,{status:Q.status,checkPending:Q.checkPending,menuItemClass:Zc,onInstallRequest:()=>{K(!1),U(!0)}}),!c&&a.jsx("button",{type:"button",className:"block w-full px-3.5 py-2 text-left text-sm text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40",onClick:()=>{K(!1),o().then(()=>n("/login"))},children:d.auth.logout})]})})}),a.jsx(oV,{open:ie,onClose:()=>I(!1)}),a.jsx(zq,{open:ye,onClose:()=>Se(!1),latestVersion:be,releaseUrl:re?.releaseUrl??null,canUpdate:s?.isAdmin===!0,onRunFinished:()=>{iw().catch(()=>{})}}),a.jsx(ln,{open:j,title:d.update.clientInstallConfirmTitle,onClose:()=>U(!1),onConfirm:()=>{U(!1),mI()},confirmLabel:d.update.clientInstallConfirmAction,tone:"primary",children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.update.clientInstallConfirmBody})}),a.jsx(Eq,{open:H,onClose:()=>$(!1),onCreated:G=>{$(!1),g().then(()=>x(G))}}),h&&a.jsx(Rq,{open:X,onClose:()=>le(!1)}),a.jsx(Yt,{open:pn!==null,title:d.chat.renameSession,onClose:()=>ur?void 0:na(null),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>na(null),disabled:ur,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:ur||!Jn.trim(),onClick:()=>{zi()},children:d.common.save})]}),children:a.jsx(at,{label:d.chat.renameSessionLabel,value:Jn,error:ls??void 0,autoFocus:!0,maxLength:120,onChange:G=>{Er(G.target.value),ls&&ra(null)},onKeyDown:G=>{G.key==="Enter"&&Jn.trim()&&!ur&&zi()}})}),cs&&a.jsx(wq,{sessionId:cs.sessionId,onClose:()=>ka(null),onChanged:(G,Ce)=>{const Ze=C.find(tt=>tt.sessionId===G);if(!Ze)return;const it={...Ze};Ce!==null?it.messagingChannel=Ce:delete it.messagingChannel,F(it)}}),a.jsx(Yt,{open:pt!==null,title:d.chat.renameWorkspace,onClose:()=>wt(null),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>wt(null),children:d.common.cancel}),a.jsx(ge,{variant:"primary",onClick:ld,children:d.common.save})]}),children:a.jsx(at,{label:d.chat.renameWorkspaceLabel,hint:d.chat.renameWorkspaceHint,value:st,placeholder:pt?$x(pt.path):"",autoFocus:!0,maxLength:80,onChange:G=>Bt(G.target.value),onKeyDown:G=>{G.key==="Enter"&&!G.nativeEvent.isComposing&&ld()}})}),a.jsx(ln,{open:ta!==null,title:d.chat.deleteSession,confirmLabel:d.common.delete,busy:is,onClose:()=>is?void 0:Br(null),onConfirm:()=>{Lo()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:ta?d.chat.deleteSessionConfirm(ta.title??d.chat.defaultSessionTitle):""})}),a.jsx(ln,{open:Sn!==null,title:d.chat.deleteWorkspace,confirmLabel:d.common.delete,onClose:()=>Dn(null),onConfirm:sp,children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:Sn?d.chat.deleteWorkspaceConfirm(Sn.label):""})}),a.jsx(ln,{open:fn!==null,title:d.chat.deleteDraft,confirmLabel:d.common.delete,onClose:()=>Fr(null),onConfirm:Ms,children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:fn?d.chat.deleteDraftConfirm(sx(fn)||d.chat.draftUntitled):""})})]})}function hV({entry:e,active:t,onOpen:n,onDelete:s}){const o=sx(e)||d.chat.draftUntitled;return a.jsx("li",{children:a.jsxs("div",{"data-title-reveal":!0,className:`group flex items-center rounded-md pr-1 transition-colors duration-150 ${t?"bg-gray-200/70 dark:bg-gray-800":"hover:bg-gray-200/50 dark:hover:bg-gray-800/70"}`,children:[a.jsx("button",{type:"button",onClick:n,className:"flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left",children:a.jsx(Of,{scrollReveal:!0,text:o,className:`min-w-0 flex-1 text-sm ${t?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"}`})}),a.jsx("div",{className:"flex shrink-0 items-center",children:a.jsx("button",{type:"button",title:d.chat.deleteDraft,"aria-label":d.chat.deleteDraft,onClick:s,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 hover:bg-gray-300/60 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:hover:bg-gray-700 dark:hover:text-red-400",children:a.jsx(vn,{d:"M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6",size:14})})})]})})}function J2({dropEdge:e,children:t}){return a.jsxs("div",{className:"relative pt-2.5",children:[e!==null&&a.jsx("div",{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${e==="above"?"top-1":"-bottom-1"}`}),t]})}function ej({pinned:e,onToggle:t}){return a.jsx("button",{type:"button",title:e?d.nav.unpinGroup:d.nav.pinGroup,"aria-label":d.nav.pinGroup,"aria-pressed":e,onClick:t,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-all duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${e?"text-gray-500 dark:text-gray-400":"text-gray-400 opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100 dark:text-gray-500"}`,children:a.jsx(vn,{d:Qx,size:Ye.groupHeaderAction})})}function gV({s:e,active:t,activity:n,pinned:s,canPin:o=!1,lastActive:c,agentHint:u,draggable:f=!1,dropEdge:p=null,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w,onOpen:S,onTogglePin:C,onRename:N,onMessaging:T,onDelete:_,onToggleArchive:R}){const D=w6(),z=F=>{D.close(),{pin:C,rename:N,messaging:T,archive:R,delete:_}[F](e)},E=F=>{D.returnFocus()?.focus(),z(F)},L={archived:e.archived,pinned:s};return a.jsxs("li",{className:"relative",...f?{draggable:!0,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}:{},children:[p!==null&&a.jsx("div",{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${p==="above"?"-top-px":"-bottom-px"}`}),a.jsxs("div",{"data-title-reveal":!0,ref:D.rowRef,...D.rowProps,className:`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${f?"cursor-grab ":""}${t?"bg-gray-200/70 dark:bg-gray-800":"hover:bg-gray-200/50 dark:hover:bg-gray-800/70"}`,children:[a.jsxs("button",{type:"button","data-testid":"session-row","data-session-id":e.sessionId,onClick:()=>{D.consumeLongPressClick()||S(e)},className:"flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left",children:[u!==void 0&&a.jsxs("span",{title:u,className:"flex shrink-0 items-center",children:[a.jsx(Ha,{id:e.agentId,name:u,size:14,className:"rounded"}),a.jsx("span",{className:"sr-only",children:u})]}),a.jsx(Of,{scrollReveal:!0,text:e.title??d.chat.defaultSessionTitle,className:`min-w-0 flex-1 text-sm ${t?"font-medium text-gray-900 dark:text-gray-100":e.archived?"text-gray-400 dark:text-gray-500":"text-gray-700 dark:text-gray-300"}`}),s&&o&&a.jsxs("span",{title:d.chat.pinnedSession,className:"shrink-0 text-gray-400 dark:text-gray-500",children:[a.jsx(vn,{d:Qx,size:12}),a.jsx("span",{className:"sr-only",children:d.chat.pinnedSession})]}),e.messagingChannel!==void 0&&a.jsxs("span",{title:d.messaging.enabledIndicator[e.messagingChannel],className:"shrink-0 text-gray-400 dark:text-gray-500",children:[a.jsx(vn,{d:II,size:12}),a.jsx("span",{className:"sr-only",children:d.messaging.enabledIndicator[e.messagingChannel]})]}),a.jsx(pV,{activity:n}),e.pendingApprovalCount>0&&a.jsx("span",{title:d.chat.pendingApprovals(e.pendingApprovalCount),children:a.jsx(On,{tone:"amber",children:e.pendingApprovalCount})})]}),a.jsxs("div",{className:"relative flex h-6 min-w-12 shrink-0 items-center justify-end",children:[a.jsx("div",{className:"peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center",children:a.jsx(E6,{actions:N6,state:L,onRun:z,onMore:D.openAt})}),c!==""&&a.jsx("span",{"aria-hidden":!0,className:"pointer-events-none px-1 text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0 dark:text-gray-500",children:c})]}),a.jsx(Qn,{open:D.open,setOpen:D.setOpen,portal:{direction:"down",align:"left"},anchorRect:D.anchor,returnFocus:D.returnFocus,className:"contents",menuClass:"w-36",button:null,children:a.jsx(M6,{actions:T6(o),state:L,onRun:E})})]})]})}function xV({onRename:e,onDelete:t}){const[n,s]=y.useState(!1),o=c=>()=>{s(!1),c()};return a.jsxs(Qn,{open:n,setOpen:s,portal:{direction:"down",align:"right"},menuClass:"w-32",className:"shrink-0",button:a.jsx("button",{type:"button",title:d.chat.workspaceMenu,"aria-label":d.chat.workspaceMenu,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>s(!n),className:"flex h-7 w-7 shrink-0 items-center justify-center text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100",children:a.jsx(lV,{size:16})}),children:[a.jsxs("button",{type:"button",className:ey,onClick:o(e),children:[ty(Zx),d.chat.renameWorkspace]}),a.jsxs("button",{type:"button",className:gN,onClick:o(t),children:[a.jsx("span",{className:"shrink-0",children:a.jsx(vn,{d:Jx,size:13})}),d.chat.deleteWorkspace]})]})}function eu({icon:e,label:t,checked:n,onSelect:s}){return a.jsxs("button",{type:"button","aria-pressed":n,onClick:s,className:`${ey} justify-between`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[ty(e),a.jsx("span",{className:"truncate",children:t})]}),n&&a.jsx(qu,{className:"shrink-0 text-gray-500 dark:text-gray-400"})]})}const yV="M8 10h8M8 14h5M21 12a9 9 0 1 1-4.2-7.6L21 4v5h-5",e0=e=>`relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${e?"bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-500 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"}`;function bV({onExpand:e}){const{user:t}=mn(),n=yr(),{agents:s,currentProject:o,setCurrentAgentId:c}=en(),{sessions:u,loading:f}=Ii(),p=zx(),h=Mx("/chat/:sessionId")?.params.sessionId??null,x=h!==null&&h!==ya,g=y.useMemo(()=>PC(u),[u]),v=()=>{g&&(c(g.agentId),n(`/chat/${g.sessionId}`))},w=()=>{t&&o&&Yl(t.userId,o.projectId);const C=(s.find(N=>N.agentId==="default_agent")??s[0])?.agentId;C&&c(C),n(`/chat/${ya}`,C?{state:{agentId:C}}:void 0)},S=[{to:"/agents",label:d.nav.agents,icon:vs.agents},{to:"/skills",label:d.nav.skills,icon:vs.skills},{to:"/models",label:d.nav.models,icon:vs.models},{to:"/usage",label:d.nav.usage,icon:vs.usage},{to:"/benchmark",label:d.nav.benchmark,icon:vs.benchmark}];return a.jsxs("div",{className:"flex h-full flex-col items-center gap-1 py-2.5",children:[a.jsx("button",{type:"button",title:d.nav.expandSidebar,"aria-label":d.nav.expandSidebar,onClick:e,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:"M9 6l6 6-6 6M20 4v16",size:18})}),a.jsxs("nav",{className:"no-scrollbar mt-1 flex min-h-0 flex-1 flex-col items-center gap-1 overflow-y-auto",children:[a.jsx("button",{type:"button",title:d.nav.lastConversation,"aria-label":d.nav.lastConversation,disabled:!g&&!f,onClick:v,className:g||f?e0(x):"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-md text-gray-300 dark:text-gray-700",children:a.jsx(Oe,{d:yV,size:18})}),a.jsx("button",{type:"button",title:d.chat.newSessionMenu,"aria-label":d.chat.newSessionMenu,onClick:w,className:e0(h===ya),children:a.jsx(Oe,{d:Jm,size:18})}),S.map(C=>{const N=C.to==="/agents"?p.kernelNote:null;return a.jsxs(Lx,{to:C.to,title:N!==null?`${C.label} · ${N}`:C.label,"aria-label":N!==null?`${C.label} · ${N}`:C.label,className:({isActive:T})=>e0(T),children:[a.jsx(Oe,{d:C.icon,size:18}),N!==null&&a.jsx(Mo,{})]},C.to)})]}),a.jsxs("button",{type:"button",title:[t?.userId??"",d.nav.expandSidebar].concat(p.softwareNote!==null?[p.softwareNote]:[]).join(" · "),"aria-label":p.softwareNote!==null?`${t?.userId??""} · ${p.softwareNote}`:t?.userId??d.auth.admin,onClick:e,className:"relative mt-auto flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900",children:[(t?.userId??"?").slice(0,1).toUpperCase(),p.software!==null&&a.jsx(Mo,{})]})]})}function vV(){const{user:e,desktopMode:t}=mn(),n=Mx("/chat/:sessionId")?.params.sessionId??null;y.useLayoutEffect(()=>{SB(n)},[n]),vI();const s=zx(!0),[o,c]=y.useState(!1),[u,f]=y.useState(!1),[p,h]=y.useState(null),x=!!e?.passwordIsInitial&&!t;y.useEffect(()=>{if(!x)return;let C=!1;return Sx().then(N=>{C||h(N.prefs.initialPasswordBannerDismissed===!0)}).catch(()=>{C||h(!1)}),()=>{C=!0}},[x]);const g=()=>{h(!0),Nf({initialPasswordBannerDismissed:!0}).catch(()=>{})},[v,w]=y.useState(()=>localStorage.getItem("penguin.sidebarCollapsed")==="1"),S=()=>w(C=>{const N=!C;return localStorage.setItem("penguin.sidebarCollapsed",N?"1":"0"),N});return a.jsxs("div",{className:"flex h-full",children:[a.jsx("aside",{className:`hidden shrink-0 border-r border-gray-200 bg-gray-50 md:block dark:border-gray-800 dark:bg-gray-900 ${v?"w-12":"w-64 lg:w-72"}`,children:v?a.jsx(bV,{onExpand:S}):a.jsx(Z2,{onCollapse:S})}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[a.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-2 md:hidden dark:border-gray-800 dark:bg-gray-950",children:[a.jsxs("button",{type:"button","aria-label":s.note!==null?`${d.chat.sessionList} · ${s.note}`:d.chat.sessionList,...s.note!==null?{title:s.note}:{},onClick:()=>c(!0),className:"relative flex h-9 w-9 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":!0,children:a.jsx("path",{d:"M4 6h16M4 12h16M4 18h16"})}),s.any&&a.jsx(Mo,{})]}),a.jsx("span",{className:"text-sm font-semibold",children:d.appName})]}),x&&p===!1&&a.jsxs("div",{className:`relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs ${Df.attention}`,children:[a.jsx("span",{children:d.account.initialPasswordBanner}),a.jsx("button",{type:"button",className:"shrink-0 font-medium underline underline-offset-2 hover:text-amber-950 dark:hover:text-amber-100",onClick:()=>f(!0),children:d.account.changeNow}),a.jsx("button",{type:"button","aria-label":d.common.close,title:d.common.close,onClick:g,className:"absolute inset-y-0.5 right-1.5 flex items-center rounded-md px-1 text-amber-500 transition-colors duration-150 hover:text-amber-950 dark:text-amber-400/70 dark:hover:text-amber-100",children:a.jsx(Hl,{size:12})})]}),a.jsx("main",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:a.jsx(V_,{})}),a.jsx(OF,{})]}),a.jsx(_M,{open:u,onClose:()=>f(!1)}),a.jsx(QC,{open:o,side:"left",title:d.appName,onClose:()=>c(!1),children:a.jsx("div",{className:"h-full bg-gray-50 dark:bg-gray-900",children:a.jsx(Z2,{onNavigate:()=>c(!1)})})})]})}const Xy=1440,Qy=900,fx=3,kV=3,tj=Xy/fx,nj=Qy/kV,$m=28,Um=14;function wV(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function SV(e,t){return e.x1-Um<=t.x2&&e.x2+Um>=t.x1&&e.y1-Um<=t.y2&&e.y2+Um>=t.y1}function jV(e,t,n,s){return{x1:Math.min(e,n),y1:Math.min(t,s),x2:Math.max(e,n),y2:Math.max(t,s)}}const CV=[{cell:0,edge:"left"},{cell:1,edge:"top"},{cell:2,edge:"right"},{cell:3,edge:"left"},{cell:5,edge:"right"},{cell:6,edge:"bottom"},{cell:7,edge:"bottom"},{cell:8,edge:"right"}];function NV(){const e=wV(12696599),t=[];for(const{cell:n,edge:s}of CV){const o=n%fx*tj+$m,c=Math.floor(n/fx)*nj+$m,u=o+tj-2*$m,f=c+nj-2*$m,p=[],h=(R,D,z,E)=>{const L=z[0]>0?u-R:z[0]<0?R-o:z[1]>0?f-D:D-c;for(let F=Math.min(60+e()*150,L);F>=40;F/=2){const V=Math.round(R+z[0]*F),P=Math.round(D+z[1]*F),B=jV(R,D,V,P);if(p.every((Y,q)=>E.has(q)||!SV(B,Y)))return p.push(B),[V,P]}return null},x=(R,D,z)=>(z-R)*(.35+e()*.3)>R-D?1:-1,g=(R,D,z,E,L,F,V)=>{let[P,B]=[R,D],Y=z;const q=[`M${Math.round(P)},${Math.round(B)}`],K=[];for(let H=0;H<E;H+=1){const $=H===0?V:new Set([p.length-1]),X=h(P,B,Y,$);if(!X)break;[P,B]=X,q.push(`L${P},${B}`),K.push([P,B]),Y=Y[0]!==0?[0,x(B,c,f)]:[x(P,o,u),0]}return K.length>=2&&t.push({d:q.join(" "),end:K[K.length-1],dur:L,delay:F}),K},v=.15+e()*.7,w=s==="left"?0:s==="right"?Xy:Math.round(o+(u-o)*v),S=s==="top"?0:s==="bottom"?Qy:Math.round(c+(f-c)*v),C=s==="left"?[1,0]:s==="right"?[-1,0]:s==="top"?[0,1]:[0,-1],N=12+e()*8,T=e()*3.2,_=g(w,S,C,3+Math.floor(e()*3),N,T,new Set);if(n%2===0&&_.length>=3){const[R,D]=_[1],[z,E]=_[2],L=[-Math.sign(z-R),-Math.sign(E-D)];g(R,D,L,2,N,T+1.4,new Set([1,2]))}}return t}const TV=NV();function MV(){return a.jsx("svg",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 h-full w-full text-slate-500/25 dark:text-cyan-300/15",viewBox:`0 0 ${Xy} ${Qy}`,preserveAspectRatio:"xMidYMid slice",fill:"none",children:TV.map((e,t)=>a.jsxs("g",{style:{"--trace-dur":`${e.dur.toFixed(1)}s`},children:[a.jsx("path",{d:e.d,pathLength:1,stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",className:"login-trace",style:{animationDelay:`${e.delay.toFixed(1)}s`}}),a.jsx("circle",{cx:e.end[0],cy:e.end[1],r:"3",fill:"currentColor",className:"login-via",style:{animationDelay:`${e.delay.toFixed(1)}s`}})]},t))})}function EV(){Li(d.auth.login);const{login:e}=mn(),{mode:t,setMode:n}=as(),{lang:s,setLang:o}=Dr(),c=yr(),[u,f]=y.useState(""),[p,h]=y.useState(""),[x,g]=y.useState({}),[v,w]=y.useState(!1),S=()=>g(_=>_.userId||_.password||_.form?{}:_),C=async()=>{const _={};if(u.trim()||(_.userId=d.common.requiredField),p||(_.password=d.common.requiredField),_.userId||_.password){g(_);return}w(!0),g({});try{await e(u.trim(),p),c("/chat",{replace:!0})}catch(R){g({form:Ae(R)})}finally{w(!1)}},N=[{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark},{value:"system",label:d.settings.followSystem}],T=[{value:"en",label:d.settings.langEn},{value:"zh",label:d.settings.langZh},{value:"system",label:d.settings.followSystem}];return a.jsxs("div",{className:"relative flex min-h-full items-center justify-center overflow-hidden p-4",children:[a.jsx(MV,{}),a.jsxs("div",{className:"absolute right-4 top-4 flex flex-col items-end gap-1.5 sm:flex-row sm:items-center sm:gap-2",children:[a.jsx("div",{"aria-label":d.settings.language,children:a.jsx(ws,{options:T,value:s,onChange:o})}),a.jsx("div",{"aria-label":d.settings.theme,children:a.jsx(ws,{options:N,value:t,onChange:n})})]}),a.jsxs("div",{className:"anim-rise relative w-full max-w-sm",children:[a.jsx(OT,{className:"mx-auto mb-3 h-16 w-16 rounded-2xl"}),a.jsx("h1",{className:"mb-6 text-center text-3xl font-semibold tracking-tight",children:d.appName}),a.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("form",{className:"space-y-4",onSubmit:_=>{_.preventDefault(),C()},children:[a.jsx(at,{label:d.common.username,required:!0,value:u,onChange:_=>{f(_.target.value),S()},error:x.userId,autoComplete:"username",autoFocus:!0}),a.jsx(ts,{label:d.auth.password,required:!0,value:p,onChange:_=>{h(_.target.value),S()},error:x.password,autoComplete:"current-password"}),x.form&&a.jsx("p",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900 dark:bg-red-950/50 dark:text-red-300",children:x.form}),a.jsx(ge,{type:"submit",variant:"primary",className:"w-full justify-center py-2.5 text-sm font-semibold",disabled:v,children:d.auth.login})]}),a.jsx("p",{className:"mt-4 text-center text-xs text-gray-400 dark:text-gray-500",children:d.auth.defaultAdminNote}),a.jsx("p",{className:"mt-1.5 text-center text-xs text-gray-400 dark:text-gray-500",children:d.auth.forgotAdminNote})]})]})]})}const tu=100,Ni=30,Da=2;function AV({data:e,label:t,className:n=""}){const s=Math.max(1,...e),o=e.length>1?(tu-2*Da)/(e.length-1):0,c=e.map((h,x)=>[Da+x*o,Ni-Da-h/s*(Ni-2*Da)]),u=`${Da},${Ni-Da} ${tu-Da},${Ni-Da}`,f=c.length>1?c.map(([h,x])=>`${h},${x}`).join(" "):u,p=c.length>1?`${f} ${tu-Da},${Ni-Da} ${Da},${Ni-Da}`:null;return a.jsxs("svg",{width:tu,height:Ni,viewBox:`0 0 ${tu} ${Ni}`,role:"img","aria-label":t,className:`text-emerald-600 dark:text-emerald-500 ${n}`,children:[a.jsx("title",{children:t}),p!==null&&a.jsx("polygon",{points:p,fill:"currentColor",fillOpacity:"0.12"}),a.jsx("polyline",{points:f,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}const px="inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-gray-300 bg-white px-2.5 py-1 text-xs font-medium text-gray-800 transition-colors duration-150 hover:bg-gray-50 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800",LM=".tar.gz,.tgz,.gz,application/gzip,application/x-gzip";function OM(e){return new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{const o=s.result;t(o.slice(o.indexOf(",")+1))},s.onerror=()=>n(s.error??new Error("File read failed.")),s.readAsDataURL(e)})}function _V(e){return e.replace(/\.(tar\.gz|tgz|gz)$/i,"").replace(/-v\d+$/,"")}const RV=new Set(["default_agent"]),Gs={newChat:"M12 5v14M5 12h14",trash:"M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6",sessions:"M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",vaultKeys:"M15.5 7.5l3 3L22 7l-3-3M21 2l-9.6 9.6M13 15.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z",schedules:"M12 21a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm0-10v3l2 1.5M5 3L2.5 5.5M19 3l2.5 2.5",skills:"M12 6.5C10.5 5 8 4.5 4 5v12c4-.5 6.5 0 8 1.5 1.5-1.5 4-2 8-1.5V5c-4-.5-6.5 0-8 1.5zm0 0V18",usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",memory:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18ZM12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18ZM15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"},nu="inline-flex shrink-0 cursor-pointer items-center gap-1 tabular-nums transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200";function IV(){const e=yr();Li(d.nav.agents);const{locale:t}=Dr(),{user:n}=mn(),{currentProject:s,agents:o,agentsLoading:c,reloadAgents:u,setCurrentAgentId:f}=en(),[p,h]=y.useState(!1),[x,g]=y.useState(""),[v,w]=y.useState(""),[S,C]=y.useState(""),[N,T]=y.useState(void 0),[_,R]=y.useState(!1),[D,z]=y.useState(null),[E,L]=y.useState(null),F=y.useRef(!1),[V,P]=y.useState([]),[B,Y]=y.useState(!1),[q,K]=y.useState(""),[H,$]=y.useState(null),[X,le]=y.useState(null),[ie,I]=y.useState([]),[A,Q]=y.useState(!1),[j,U]=y.useState(null),ee=()=>{g(""),w(""),C(""),T(void 0),P([]),Y(!1),K(""),$(null),le(null),I([]),Q(!1),U(null),h(!0)},re=oe=>{const J=oe.target.files?.[0];if(oe.target.value="",!!J&&(U(J),P([]),K(""),I([]),!x.trim())){const ht=_V(J.name);mx.test(ht)&&g(ht)}};y.useEffect(()=>{!p||D!==null||F.current||(F.current=!0,L(null),oC().then(oe=>z(oe.groups.flatMap(J=>J.skills))).catch(oe=>{F.current=!1,L(Ae(oe))}))},[p,D]);const ke=$r(),be=ke.state?.create===!0;y.useEffect(()=>{be&&(ee(),e(ke.pathname,{replace:!0}))},[be]);const[ye,Se]=y.useState(null),[Me,ze]=y.useState(null),De=s?.projectId;y.useEffect(()=>{if(!p||!q||!De){$(null),le(null);return}let oe=!1;return $(null),le(null),KE(De,q).then(J=>{oe||$(J.skills)}).catch(J=>{oe||($(null),le(Ae(J)))}),()=>{oe=!0}},[p,De,q]),y.useEffect(()=>{if(H===null){I(J=>J.length===0?J:[]);return}const oe=new Set(H.map(J=>J.name));I(J=>{const ht=J.filter(ve=>oe.has(ve));return ht.length===J.length?J:ht})},[H]);const ct=async()=>{if(!De)return;const oe=x.trim();if(!oe){T(d.common.requiredField);return}if(!mx.test(oe)){T(d.agent.idHint);return}R(!0),T(void 0);try{const J={agentId:oe};v.trim()&&(J.name=v.trim()),S.trim()&&(J.description=S.trim()),j!==null?J.dataBase64=await OM(j):(V.length>0&&(J.skills=V),q&&ie.length>0&&(J.skillsDirectory=q,J.directorySkills=ie));const ht=await FE(De,J);h(!1),await u(),f(ht.agent.agentId),e(`/agents/${ht.agent.agentId}`)}catch(J){T(Ae(J))}finally{R(!1)}},bt=oe=>{n&&De&&Yl(n.userId,De),f(oe),e(`/chat/${ya}`,{state:{agentId:oe}})},he=(oe,J)=>{f(oe),e(`/agents/${oe}?tab=${J}`)},ne=async()=>{if(!(!De||!ye)){R(!0),ze(null);try{await kA(De,ye.agentId),Se(null),await u()}catch(oe){ze(Ae(oe))}finally{R(!1)}}};return a.jsxs("div",{className:"h-full overflow-y-auto p-4 md:p-6",children:[a.jsxs("div",{className:"mx-auto max-w-5xl",children:[a.jsxs("div",{className:"mb-4 flex items-center justify-between gap-2",children:[a.jsx("h1",{className:"text-xl font-semibold",children:d.agent.listTitle}),a.jsx(ge,{variant:"primary",onClick:ee,children:d.agent.create})]}),c?a.jsx("div",{className:"space-y-3",children:Array.from({length:4},(oe,J)=>a.jsxs(SN,{className:"flex flex-wrap items-center gap-x-6 gap-y-2 px-5 py-4",children:[a.jsxs("div",{className:"min-w-[14rem] flex-1",children:[a.jsx(on,{className:"h-[18px] w-40"}),a.jsx(on,{className:"mt-1.5 h-4 w-2/3"}),a.jsx(on,{className:"mt-1.5 h-4 w-48"})]}),a.jsx(on,{className:"hidden h-9 w-40 md:block"}),a.jsx(on,{className:"h-8 w-52"})]},J))}):o.length===0?a.jsx(Fa,{title:d.common.none}):a.jsx("div",{className:"space-y-3",children:o.map(oe=>{const J=RV.has(oe.agentId);return a.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 rounded-md border border-gray-200 bg-white px-5 py-4 dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"min-w-[14rem] flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ha,{id:oe.agentId,name:_n(oe),size:18,className:"shrink-0 rounded"}),a.jsx("span",{className:"min-w-0 truncate text-base font-bold",children:_n(oe)}),a.jsx("span",{className:"hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500",children:oe.agentId}),a.jsxs(On,{tone:"gray",children:["v",oe.version]}),oe.kernelOutdated&&a.jsx(OI,{onClick:()=>he(oe.agentId,"overview"),children:d.agent.kernelUpdateNeeded})]}),a.jsx("p",{className:"mt-1.5 min-h-4 truncate text-xs text-gray-500 dark:text-gray-400",children:oe.description??""}),a.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-500 dark:text-gray-400",children:[a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 tabular-nums",title:d.agent.sessionCount(oe.sessionCount),children:[a.jsx(Oe,{d:Gs.sessions,size:Ye.inlineGlyph}),oe.sessionCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.toolCount(oe.toolCount),"aria-label":d.agent.toolCount(oe.toolCount),onClick:()=>he(oe.agentId,"tools"),children:[a.jsx(Oe,{d:Xn.toolCalls,size:Ye.inlineGlyph}),oe.toolCount]}),a.jsxs("button",{type:"button",className:nu,title:d.skills.skillCount(oe.skillCount),"aria-label":d.skills.skillCount(oe.skillCount),onClick:()=>he(oe.agentId,"skills"),children:[a.jsx(Oe,{d:Gs.skills,size:Ye.inlineGlyph}),oe.skillCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.memoryCount(oe.memoryCount),"aria-label":d.agent.memoryCount(oe.memoryCount),onClick:()=>he(oe.agentId,"memory"),children:[a.jsx(Oe,{d:Gs.memory,size:Ye.inlineGlyph}),oe.memoryCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.vaultKeyCount(oe.vaultKeyCount),"aria-label":d.agent.vaultKeyCount(oe.vaultKeyCount),onClick:()=>he(oe.agentId,"vault"),children:[a.jsx(Oe,{d:Gs.vaultKeys,size:Ye.inlineGlyph}),oe.vaultKeyCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.scheduleCount(oe.scheduleCount),"aria-label":d.agent.scheduleCount(oe.scheduleCount),onClick:()=>he(oe.agentId,"schedules"),children:[a.jsx(Oe,{d:Gs.schedules,size:Ye.inlineGlyph}),oe.scheduleCount]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:`${d.agent.updatedAt} ${oe.updatedAt?Jr(oe.updatedAt):"—"}`,children:[a.jsx(Oe,{d:Xn.elapsed,size:Ye.inlineGlyph}),oe.updatedAt?$I(oe.updatedAt,t):"—"]})]})]}),a.jsx(AV,{data:oe.sessionActivity,label:d.agent.activity(oe.sessionActivity.length||30),className:"hidden shrink-0 md:block"}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsxs(ge,{size:"sm",variant:"primary",onClick:()=>bt(oe.agentId),children:[a.jsx(Oe,{d:Gs.newChat}),d.chat.newSessionMenu]}),a.jsxs(ge,{size:"sm",onClick:()=>{f(oe.agentId),e(`/agents/${oe.agentId}`)},children:[a.jsx(Oe,{d:If}),d.common.settings]}),a.jsx(ge,{size:"icon",title:d.nav.usage,"aria-label":d.nav.usage,onClick:()=>e(`/usage?agentId=${encodeURIComponent(oe.agentId)}`),children:a.jsx(Oe,{d:Gs.usage,size:15,className:"text-gray-600 dark:text-gray-300"})}),J?a.jsx("span",{role:"img",title:d.agent.builtinUndeletable,"aria-label":d.agent.builtinUndeletable,className:"inline-flex cursor-not-allowed items-center justify-center rounded-md border border-transparent p-1.5 text-gray-300 dark:text-gray-600",children:a.jsx(Oe,{d:Gs.trash,size:15})}):a.jsx(ge,{size:"icon",variant:"danger",title:d.agent.deleteAgent,"aria-label":d.agent.deleteAgent,onClick:()=>Se({agentId:oe.agentId,name:_n(oe)}),children:a.jsx(Oe,{d:Gs.trash,size:15})})]})]},oe.agentId)})})]}),a.jsx(Yt,{open:p,title:d.agent.createTitle,onClose:()=>h(!1),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>h(!1),children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:_,onClick:()=>{ct()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{label:d.agent.id,required:!0,size:"sm",value:x,onChange:oe=>{g(oe.target.value),T(void 0)},error:N,hint:d.agent.idHint,autoFocus:!0}),a.jsx(at,{label:d.common.name,size:"sm",value:v,onChange:oe=>w(oe.target.value),hint:d.agent.nameHint}),a.jsx(ir,{label:d.agent.description,size:"sm",rows:3,value:S,onChange:oe=>C(oe.target.value)}),a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createSnapshot}),j===null?a.jsxs("label",{className:`${px} ${_?"pointer-events-none opacity-60":""}`,children:[a.jsx(Xl,{accept:LM,disabled:_,onChange:re}),d.agent.createSnapshotPick]}):a.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx("span",{className:"min-w-0 truncate rounded-md border border-gray-300 bg-gray-50 px-2.5 py-1 font-mono text-xs dark:border-gray-700 dark:bg-gray-900",children:j.name}),a.jsx("button",{type:"button",title:d.agent.createSnapshotClear,"aria-label":d.agent.createSnapshotClear,disabled:_,onClick:()=>U(null),className:"shrink-0 rounded-md p-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300",children:a.jsx(Hl,{size:12})})]}),a.jsx(wo,{children:j===null?d.agent.createSnapshotHint:d.agent.createSnapshotSkillsOff})]}),j===null&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createSkills}),a.jsx(Ru,{open:B,setOpen:Y,label:V.length===0?d.agent.createSkillsPlaceholder:d.agent.createSkillsPicked(V.length),muted:V.length===0,title:d.agent.createSkills,ariaLabel:d.agent.createSkills,disabled:_,menuClass:"w-[26rem]",children:a.jsx(q0,{skills:D??[],selected:V,onToggle:oe=>P(J=>V0(J,oe)),onSelectAll:oe=>P(J=>LS(J,oe)),onSelectNone:oe=>P(J=>OS(J,oe)),emptyHint:D===null?d.common.loading:d.agent.createSkillsEmpty})}),E?a.jsx(ga,{children:E}):a.jsx(wo,{children:d.agent.createSkillsHint})]}),a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createDirSkills}),a.jsx(sd,{projectId:De??"",workspace:q,onChange:K,variant:"form",fieldLabel:d.agent.createDirSkills,emptyLabel:d.agent.createDirSkillsPick,menuHint:d.agent.createDirSkillsHint,clearLabel:d.agent.createDirSkillsClear}),q&&H!==null&&H.length>0&&a.jsx("div",{className:"mt-2",children:a.jsx(Ru,{open:A,setOpen:Q,label:ie.length===0?d.agent.createSkillsPlaceholder:d.agent.createSkillsPicked(ie.length),muted:ie.length===0,title:d.agent.createDirSkills,ariaLabel:d.agent.createDirSkills,disabled:_,menuClass:"w-[26rem]",children:a.jsx(q0,{skills:H,selected:ie,onToggle:oe=>I(J=>V0(J,oe)),onSelectAll:oe=>I(J=>LS(J,oe)),onSelectNone:oe=>I(J=>OS(J,oe)),emptyHint:d.agent.createDirSkillsEmpty})})}),X?a.jsx(ga,{children:X}):a.jsx(wo,{children:q?H===null?d.common.loading:H.length===0?d.agent.createDirSkillsEmpty:d.agent.createDirSkillsFound(H.length):d.agent.createDirSkillsHint})]})]})]})}),a.jsxs(ln,{open:ye!==null,title:d.agent.deleteAgent,busy:_,onClose:()=>{Se(null),ze(null)},onConfirm:()=>{ne()},children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:ye?d.agent.deleteConfirm(ye.name):""}),Me&&a.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:Me})]})]})}function LV({items:e,active:t,onChange:n}){return a.jsx("div",{role:"tablist",className:"flex max-w-full gap-1 overflow-x-auto overflow-y-hidden border-b border-gray-200 dark:border-gray-800",children:e.map(s=>{const o=s.badge??null;return a.jsxs("button",{type:"button",role:"tab","aria-selected":s.key===t,...o!==null?{title:o,"aria-label":`${s.label} · ${o}`}:{},onClick:()=>n(s.key),className:`relative -mb-px whitespace-nowrap border-b-2 px-3 py-2 text-sm transition-colors duration-150 ${s.key===t?"border-gray-900 font-semibold text-gray-900 dark:border-gray-100 dark:text-gray-100":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-800 dark:text-gray-400 dark:hover:border-gray-700 dark:hover:text-gray-200"}`,children:[s.label,o!==null&&a.jsx(Mo,{size:"inline",position:"right-1 top-1"})]},s.key)})})}const OV=288,DV={base:"text-base",sm:"text-xs"},$V={base:"text-xs",sm:"text-[11px]"};function Sf({options:e,value:t,onChange:n,placeholder:s,mono:o,label:c,error:u,required:f,fullWidth:p,size:h="base","aria-label":x}){const[g,v]=y.useState(!1),{triggerRef:w,panelRef:S,position:C}=$f({open:g,onClose:()=>v(!1),estimatedHeight:e.length*48+16,panelWidth:OV}),N=t!=null?e.find(R=>R.value===t):void 0,T=y.useId(),_=a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:w,type:"button","aria-label":x,"aria-haspopup":"listbox","aria-expanded":g,"aria-required":f||void 0,"aria-invalid":u?!0:void 0,"aria-describedby":u?T:void 0,onClick:()=>v(R=>!R),className:`flex items-center gap-2 ${Uf} ${Pf[h]} ${u?zf:""}`+(p?" w-full justify-between":""),children:[a.jsx("span",{className:`min-w-0 truncate ${o?"font-mono":""}`,children:N?.triggerLabel??s??"—"}),a.jsx(ns,{className:"text-gray-400"})]}),g&&C&&ss.createPortal(a.jsx("div",{ref:S,role:"listbox",style:{position:"fixed",top:C.topPx,bottom:C.bottomPx,left:C.left,minWidth:C.triggerWidth},className:"anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:e.map(R=>a.jsxs("button",{type:"button",role:"option","aria-selected":R.value===t,onClick:()=>{n(R.value),v(!1)},className:`block ${ny} hover:bg-gray-100 dark:hover:bg-gray-800 ${R.value===t?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsxs("span",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:`${DV[h]} ${R.value===t?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"}`,children:R.label}),R.value===t&&a.jsx(qu,{className:"text-gray-500 dark:text-gray-400"})]}),a.jsx("span",{className:`mt-0.5 block ${$V[h]} text-gray-500 dark:text-gray-400`,children:R.description})]},R.value))}),document.body)]});return a.jsx(Vu,{label:c,error:u,errorId:T,required:f,children:_})}const UV=/^(www\.)?(github|gitlab|gitee|bitbucket)\.(com|org)$/i;function PV(e){const t=e.trim();if(/^git@[\w.-]+:/.test(t)||/\.git$/i.test(t))return"repoUrl";if(/^https?:\/\//i.test(t)){try{if(UV.test(new URL(t).hostname))return"repoUrl"}catch{}return"webUrl"}return/^(\/|~\/|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/.test(t)?"localPath":/^[A-Za-z@][\w@./-]*\s+\S/.test(t)?"command":"reference"}function t0(e){return`${d.skills.importPromptLead[PV(e)](e)}
|
|
180
|
+
`).trim();if(!E)return!1;try{return await R(E),!0}catch(L){return D(L),!1}},onSteer:async z=>{try{return await R(z),"queued"}catch(E){return D(E),"failed"}},steeringDeliveredCount:c,onStop:async()=>{await uA(e,t).catch(()=>{})},modelRef:T,models:u,turnThinkingLevel:C||x,onChangeTurnThinkingLevel:N,..._!==void 0?{contextWindow:_}:{},contextNow:o,vision:!1,approvalMode:f,onChangeApprovalMode:p,modeSaving:h,agents:[],skills:w})})}const Tl={cacheRead:"#7dd3fc",cacheWrite:"#0ea5e9",output:"#0369a1"};function BH({cacheRead:e,cacheWrite:t,output:n,max:s,size:o=44}){const c=e+t+n,u=Math.max(2,Math.round(o*.16)),f=o/2,p=(o-u)/2,h=2*Math.PI*p,x=Math.max(s,c,1),g=s>0?c/s:0,v=g>.95?sn.danger:g>.8?sn.attention:"text-gray-300 dark:text-gray-700",w=[{key:"cacheRead",value:e,color:Tl.cacheRead,label:d.usage.colCacheRead},{key:"cacheWrite",value:t,color:Tl.cacheWrite,label:d.usage.colCacheWrite},{key:"output",value:n,color:Tl.output,label:d.usage.colOutput}],S=`${d.chat.contextUsage} ${It(c)}/${It(s)}`+w.map(N=>` · ${N.label} ${It(N.value)}`).join("");let C=0;return a.jsxs("svg",{width:o,height:o,viewBox:`0 0 ${o} ${o}`,className:`block shrink-0 ${v}`,role:"img","aria-label":S,children:[a.jsx("title",{children:S}),a.jsx("circle",{cx:f,cy:f,r:p,fill:"none",stroke:"currentColor",strokeOpacity:.35,strokeWidth:u}),w.map(N=>{if(N.value<=0)return null;const T=N.value/x*h,_=-(C/x)*h;return C+=N.value,a.jsx("circle",{cx:f,cy:f,r:p,fill:"none",stroke:N.color,strokeWidth:u,strokeDasharray:`${T} ${h}`,strokeDashoffset:_,transform:`rotate(-90 ${f} ${f})`},N.key)})]})}function HH(e,t){const n=Math.min(e.callMs,e.approvalMs??e.callMs),s=Math.max(n,e.approvalMs??n,e.outputMs??t);return{startMs:n,endMs:s}}function FH(e){const t=new Map,n=[...e].sort((o,c)=>o.startMs-c.startMs||o.endMs-c.endMs);for(const o of n){let c=t.get(o.name);c||(c=[],t.set(o.name,c));const u=c.find(f=>o.startMs>=f.lastEnd);u?(u.spans.push(o),u.lastEnd=Math.max(u.lastEnd,o.endMs)):c.push({spans:[o],lastEnd:o.endMs})}const s=[];for(const[o,c]of t)for(const u of c)s.push({name:o,spans:u.spans});return s}const fa={thinking:"bg-violet-500 dark:bg-violet-400",text:"bg-sky-500 dark:bg-sky-400",toolgen:"bg-amber-500 dark:bg-amber-400",approvalWait:"bg-rose-400 dark:bg-rose-300",exec:"bg-emerald-500 dark:bg-emerald-400",other:"bg-gray-400 dark:bg-gray-500"},kf="sticky left-0 z-10 flex h-4 w-[5.5rem] shrink-0 items-center justify-end bg-white pr-2 dark:bg-gray-950",ix="truncate font-mono text-[11px]",M2=.25,ox=24,qH=1/ox,qs=(e,t,n)=>Math.min(n,Math.max(t,e));function VH(e){return e==="thinking"?fa.thinking:e==="text"?fa.text:fa.toolgen}function GH(e){return e==="thinking"?d.traces.kindThinking:e==="text"?d.traces.kindModelReply:d.traces.kindToolGen}function KH(e){return e==="thinking"?"thinking":e==="text"?"text":"toolgen"}function co(e){if(e===void 0)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function WH(e,t,n){const s=new Map,o=u=>{let f=s.get(u);return f||(f={segs:[],spans:[],others:[]},s.set(u,f)),f};for(const u of e){const f=co(u.startTs),p=co(u.endTs);f===null||p===null||o(u.taskIndex).segs.push({kind:u.kind,...u.name!==void 0?{name:u.name}:{},ts:u.endTs,startMs:f,endMs:p})}for(const u of t){const f=co(u.callTs);f!==null&&o(u.taskIndex).spans.push({name:u.name||u.toolCallId,toolCallId:u.toolCallId,callTs:u.callTs,...u.approvalTs!==void 0?{approvalTsRaw:u.approvalTs}:{},...u.outputTs!==void 0?{outputTsRaw:u.outputTs}:{},callMs:f,approvalMs:co(u.approvalTs),outputMs:co(u.outputTs),failed:u.stopReason!==void 0&&u.stopReason!=="completed",...u.stopReason!==void 0?{status:u.stopReason}:{},...u.decision!==void 0?{decision:u.decision}:{}})}for(const u of n){const f=co(u.startTs),p=co(u.endTs);f===null||p===null||o(u.taskIndex).others.push({key:u.key,name:u.name,ts:u.endTs,startMs:f,endMs:p,failed:u.failed===!0})}const c=[];for(const[u,{segs:f,spans:p,others:h}]of[...s.entries()].sort((x,g)=>x[0]-g[0])){if(f.length===0&&p.length===0&&h.length===0)continue;const x=[...f.map(N=>N.startMs),...p.map(N=>N.callMs),...h.map(N=>N.startMs)],g=[...f.map(N=>N.endMs),...p.map(N=>N.outputMs??N.approvalMs??N.callMs),...h.map(N=>N.endMs)],v=Math.min(...x),w=Math.max(...g,...x),S=Math.max(1,w-v);p.sort((N,T)=>N.callMs-T.callMs),h.sort((N,T)=>N.startMs-T.startMs);const C=FH(p.map(N=>({...N,...HH(N,v+S)})));c.push({taskIndex:u,segs:f,others:h,t0:v,total:S,toolRows:C})}return c}function lx({children:e}){return a.jsx("div",{className:"relative h-4 min-w-0 flex-1 overflow-hidden bg-gray-100 dark:bg-gray-800/60",children:e})}function YH({label:e,children:t}){return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-400 dark:text-gray-500`,title:e,children:a.jsx("span",{className:ix,children:e})}),a.jsx(lx,{children:t})]})}function XH({total:e}){const t=[0,.25,.5,.75,1];return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:kf}),a.jsx("div",{className:"relative h-4 min-w-0 flex-1",children:t.map((n,s)=>a.jsx("span",{className:`absolute top-0 font-mono text-[11px] text-gray-400 dark:text-gray-500 ${s===0?"":s===t.length-1?"-translate-x-full":"-translate-x-1/2"}`,style:{left:`${n*100}%`},children:Pn(n*e)},s))})]})}function QH({segments:e,toolSpans:t,otherSpans:n=[],highlight:s,onHighlight:o,onJump:c,hideTaskLabel:u=!1}){const f=y.useMemo(()=>WH(e,t,n),[e,t,n]),{firstBarKeyByTs:p,barKeys:h}=y.useMemo(()=>{const j=new Map,U=new Set,ee=(re,ke)=>{U.add(ke),j.has(re)||j.set(re,ke)};for(const re of f){re.segs.forEach((ke,be)=>ee(ke.ts,`s-${re.taskIndex}-${be}`));for(const ke of re.toolRows)for(const be of ke.spans)be.approvalMs!==null&&be.approvalMs>be.callMs&&ee(be.approvalTsRaw??be.callTs,`w-${be.toolCallId}`),be.approvalMs===null&&be.outputMs===null?ee(be.callTs,`p-${be.toolCallId}`):ee(be.outputTsRaw??be.callTs,`e-${be.toolCallId}`);for(const ke of re.others)ee(ke.ts,`o-${ke.key}`)}return{firstBarKeyByTs:j,barKeys:U}},[f]),[x,g]=y.useState(null),[v,w]=y.useState(1),[S,C]=y.useState({left:0,width:1}),N=y.useRef(null),T=y.useRef(null),_=y.useRef(S);_.current=S;const R=y.useRef(v);R.current=v;const D=y.useRef(null),z=y.useRef(null),E=y.useCallback(()=>{const j=N.current;if(!j)return;const U=j.scrollWidth||1;C({left:j.scrollLeft/U,width:Math.min(1,j.clientWidth/U)})},[]);if(y.useLayoutEffect(()=>{const j=N.current;if(j){if(D.current){const U=j.scrollWidth-j.clientWidth;j.scrollLeft=qs(D.current(j),0,Math.max(0,U)),D.current=null}E()}},[v,f,E]),y.useLayoutEffect(()=>{const j=N.current;if(!j||typeof ResizeObserver>"u")return;const U=new ResizeObserver(()=>E());return U.observe(j),()=>U.disconnect()},[E]),y.useLayoutEffect(()=>()=>z.current?.(),[]),f.length===0)return a.jsx("p",{className:"text-xs text-gray-400",children:d.common.none});const L=s?.ts,F=s?.key,V=(j,U)=>o?.(U?{ts:U,key:j}:null),P=()=>o?.(null),B=F??(L!==void 0?p.get(L):void 0),Y=B!==void 0&&h.has(B)?B:void 0,q=Y!==void 0,K=j=>Y===j,H=(j,U)=>x!==null&&!U||q&&!j?"opacity-15":"",$=(j,U,ee,re)=>{const ke=qs((j-ee)/re*100,0,100),be=qs((U-j)/re*100,0,100-ke);return ke>=100?{left:"100%",width:"0%",marginLeft:"-2px"}:{left:`${ke}%`,width:`${be}%`}},X=[{key:"thinking",className:fa.thinking,label:d.traces.kindThinking},{key:"text",className:fa.text,label:d.traces.kindModelReply},{key:"toolgen",className:fa.toolgen,label:d.traces.kindToolGen},{key:"approvalWait",className:fa.approvalWait,label:d.traces.legendApprovalWait},{key:"exec",className:fa.exec,label:d.traces.legendToolExec},{key:"other",className:fa.other,label:d.traces.legendOther}],le=(j,U)=>{const ee=qs(U,qH,1),re=qs(1/ee,M2,ox),ke=qs(j,0,1-ee);D.current=be=>ke*be.scrollWidth,w(re)},ie=j=>{j.preventDefault();const U=T.current,ee=N.current;if(!U||!ee)return;const re=U.getBoundingClientRect().width||1,ke=j.clientX,be=ee.scrollLeft,ye=Math.max(0,ee.scrollWidth-ee.clientWidth),Se=ze=>{const De=(ze.clientX-ke)/re;ee.scrollLeft=qs(be+De*ee.scrollWidth,0,ye),E()},Me=()=>{window.removeEventListener("pointermove",Se),window.removeEventListener("pointerup",Me),window.removeEventListener("pointercancel",Me),z.current=null};window.addEventListener("pointermove",Se),window.addEventListener("pointerup",Me),window.addEventListener("pointercancel",Me),z.current=Me},I=j=>U=>{U.preventDefault(),U.stopPropagation();const ee=T.current;if(!ee)return;const re=ee.getBoundingClientRect(),ke=ye=>{const Se=qs((ye.clientX-re.left)/(re.width||1),0,1),Me=_.current;if(j==="right")le(Me.left,Se-Me.left);else{const ze=Me.left+Me.width;le(Se,ze-Se)}},be=()=>{window.removeEventListener("pointermove",ke),window.removeEventListener("pointerup",be),window.removeEventListener("pointercancel",be),z.current=null};window.addEventListener("pointermove",ke),window.addEventListener("pointerup",be),window.addEventListener("pointercancel",be),z.current=be},A=()=>{D.current=()=>0,w(1)},Q=j=>{const U=N.current,ee=qs(R.current*j,M2,ox);if(ee!==R.current){if(U){const re=U.clientWidth/2,ke=(U.scrollLeft+re)/(U.scrollWidth||1);D.current=be=>ke*be.scrollWidth-re}w(ee)}};return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{ref:N,className:"no-scrollbar overflow-x-auto overflow-y-hidden",children:a.jsx("div",{className:"space-y-4",style:{width:`${v*100}%`},children:f.map(j=>a.jsxs("div",{className:"space-y-1",children:[!u&&a.jsxs("div",{className:"flex items-center gap-2 pl-[5.5rem]",children:[a.jsx("span",{className:"rounded bg-gray-100 px-1.5 py-0.5 text-[11px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400",children:d.traces.task(j.taskIndex+1)}),a.jsx("span",{className:"font-mono text-[11px] text-gray-400",children:Pn(j.total)})]}),a.jsx(YH,{label:d.traces.laneLLM,children:j.segs.map((U,ee)=>{const re=KH(U.kind),ke=x===null||x===re,be=`s-${j.taskIndex}-${ee}`,ye=K(be);return a.jsx("span",{onMouseEnter:()=>V(be,U.ts),onMouseLeave:P,onClick:()=>c?.(U.ts),title:`${GH(U.kind)}${U.name?` ${U.name}`:""} · ${Pn(U.endMs-U.startMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${VH(U.kind)} ${H(ye,ke)}`,style:$(U.startMs,U.endMs,j.t0,j.total)},ee)})}),j.toolRows.map((U,ee)=>a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-500 dark:text-gray-400`,title:U.name,children:a.jsx("span",{className:ix,children:U.name})}),a.jsx(lx,{children:U.spans.map(re=>{const ke=re.approvalMs??re.callMs,be=re.outputMs===null,ye=re.outputMs??j.t0+j.total,Se=re.approvalTsRaw??re.callTs,Me=re.outputTsRaw??re.callTs;return a.jsxs(y.Fragment,{children:[re.approvalMs!==null&&re.approvalMs>re.callMs&&a.jsx("span",{onMouseEnter:()=>V(`w-${re.toolCallId}`,Se),onMouseLeave:P,onClick:()=>c?.(Se),title:`${re.name} · ${d.traces.legendApprovalWait}${re.decision?` (${re.decision})`:""} · ${Pn(re.approvalMs-re.callMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.approvalWait} ${H(K(`w-${re.toolCallId}`),x===null||x==="approvalWait")}`,style:$(re.callMs,re.approvalMs,j.t0,j.total)}),re.approvalMs===null&&be?(()=>{const ze=H(K(`p-${re.toolCallId}`),x===null||x==="approvalWait");return a.jsx("span",{onMouseEnter:()=>V(`p-${re.toolCallId}`,re.callTs),onMouseLeave:P,onClick:()=>c?.(re.callTs),title:`${re.name} · ${d.traces.legendApprovalWait} · ${d.traces.inProgress}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.approvalWait} ${ze||"animate-pulse"}`,style:$(re.callMs,ye,j.t0,j.total)})})():(()=>{const ze=H(K(`e-${re.toolCallId}`),x===null||x==="exec"),De=be&&!ze;return a.jsx("span",{onMouseEnter:()=>V(`e-${re.toolCallId}`,Me),onMouseLeave:P,onClick:()=>c?.(Me),title:`${re.name} · ${d.traces.legendToolExec} · ${be?d.traces.inProgress:Pn(ye-ke)}${re.failed?` · ${re.status}`:""}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.exec} ${re.failed?"ring-1 ring-red-500":""} ${De?"animate-pulse opacity-70":ze}`,style:$(ke,ye,j.t0,j.total)})})()]},re.toolCallId)})})]},`${ee}-${U.name}`)),j.others.map(U=>{const ee=H(K(`o-${U.key}`),x===null||x==="other");return a.jsxs("div",{className:"flex items-center",children:[a.jsx("span",{className:`${kf} text-gray-500 dark:text-gray-400`,title:U.name,children:a.jsx("span",{className:ix,children:U.name})}),a.jsx(lx,{children:a.jsx("span",{onMouseEnter:()=>V(`o-${U.key}`,U.ts),onMouseLeave:P,onClick:()=>c?.(U.ts),title:`${U.name} · ${d.traces.legendOther} · ${Pn(U.endMs-U.startMs)}`,className:`absolute inset-y-0 min-w-[2px] cursor-pointer ${fa.other} ${U.failed?"ring-1 ring-red-500":""} ${ee}`,style:$(U.startMs,U.endMs,j.t0,j.total)})})]},U.key)}),a.jsx(XH,{total:j.total})]},j.taskIndex))})}),a.jsx("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-gray-100 pt-2.5 dark:border-gray-800",children:X.map(j=>a.jsxs("button",{type:"button",onMouseEnter:()=>g(j.key),onMouseLeave:()=>g(null),className:`flex items-center gap-1 px-1 font-mono text-[11px] text-gray-500 transition-opacity duration-150 dark:text-gray-400 ${x!==null&&x!==j.key?"opacity-30":""}`,children:[a.jsx("span",{className:`inline-block h-2 w-3 rounded-sm ${j.className}`}),j.label]},j.key))}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400",children:d.traces.zoom}),a.jsx("button",{type:"button","aria-label":d.traces.zoomOut,title:d.traces.zoomOut,onClick:()=>Q(1/1.4),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800",children:a.jsx("span",{className:"text-[11px] leading-none",children:"−"})}),a.jsx("div",{ref:T,onDoubleClick:A,title:d.traces.zoomReset,className:"relative h-3 min-w-0 flex-1 rounded bg-gray-100 dark:bg-gray-800",children:a.jsxs("div",{role:"scrollbar","aria-label":d.traces.zoom,onPointerDown:ie,className:"absolute inset-y-0 flex cursor-grab items-center justify-between rounded bg-gray-400/70 active:cursor-grabbing dark:bg-gray-500/70",style:{left:`${S.left*100}%`,width:`${Math.max(S.width*100,3)}%`},children:[a.jsx("span",{onPointerDown:I("left"),className:"h-full w-1.5 shrink-0 cursor-ew-resize rounded-l bg-gray-500/80 dark:bg-gray-400/80"}),a.jsx("span",{onPointerDown:I("right"),className:"h-full w-1.5 shrink-0 cursor-ew-resize rounded-r bg-gray-500/80 dark:bg-gray-400/80"})]})}),a.jsx("button",{type:"button","aria-label":d.traces.zoomIn,title:d.traces.zoomIn,onClick:()=>Q(1.4),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800",children:a.jsx("span",{className:"text-[11px] leading-none",children:"+"})}),a.jsxs("span",{className:"w-9 shrink-0 text-right font-mono text-[11px] tabular-nums text-gray-400",children:[v.toFixed(2),"×"]})]}),o&&a.jsx("p",{className:"text-[11px] text-gray-400 dark:text-gray-600",children:d.traces.linkHint})]})}function ZH(e){return e==="session_meta"?"brand":e==="model_msg"?"gray":"amber"}const JH={text:"M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",thinking:"M9 18h6M10 21h4M12 3a6 6 0 0 0-3 11v2h6v-2a6 6 0 0 0-3-11z",image_url:"M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",inline_data:"M3 5h18v14H3zM3 15l5-5 4 4 3-3 6 6",tool_call:"M14.7 6.3a4 4 0 0 0-5 5L4 17v3h3l5.7-5.7a4 4 0 0 0 5-5l-2.5 2.5-2-2 2.5-2.5z",tool_call_output:"M4 6l4 4-4 4M12 18h8",token_usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",request_begin:"M5 12h14M13 6l6 6-6 6",request_end:"M19 12H5M11 6l-6 6 6 6",approval_decision:"M9 12l2 2 4-4M12 3l7 3v6c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z",compaction_begin:"M8 3H4v4M16 3h4v4M8 21H4v-4M16 21h4v-4M9 12h6",compaction_end:"M8 3H4v4M16 3h4v4M8 21H4v-4M16 21h4v-4M9 12h6",abort:"M6 6h12v12H6z",subagent:"M12 3v6m0 0l-5 4v8m5-12l5 4v8M4 21h16",mcp_connect_begin:"M9 7V3m6 4V3M7 7h10v4a5 5 0 0 1-10 0zM12 16v5",mcp_connect_end:"M9 7V3m6 4V3M7 7h10v4a5 5 0 0 1-10 0zM12 16v5",tool_list_ready:"M14.7 6.3a4 4 0 0 0-5 5L4 17v3h3l5.7-5.7a4 4 0 0 0 5-5l-2.5 2.5-2-2 2.5-2.5z"},eF="M12 8v5m0 3h.01M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z";function tF({type:e}){return a.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",className:"shrink-0 text-gray-400 dark:text-gray-500","aria-hidden":!0,children:a.jsx("path",{d:JH[e]??eF})})}function nF(e){const t=e.payload;switch(t.type){case void 0:return"";case"text":return`${String(t.role)}: ${String(t.text??"").slice(0,120)}`;case"thinking":return String(t.thinking??"").slice(0,120);case"image_url":return"[image]";case"inline_data":return`[image] ${String(t.mime_type??"")}`;case"tool_call":return`${String(t.name)} ${String(t.arguments??"").slice(0,100)}`;case"tool_call_output":{const n=String(t.output??"").slice(0,120);return Array.isArray(t.images)&&t.images.length>0?`[image] ${n}`:n}case"token_usage":{const n=t.request,s=t.session;return`request.total=${n?.total??0} session.total=${s?.total??0}`}case"request_end":return`status=${String(t.status)}`;case"approval_decision":return`${String(t.decision)} · ${String(t.tool_call_id)}`;case"compaction_begin":case"compaction_end":return`${String(t.mode)} (${String(t.reason)})${t.status?` · ${String(t.status)}`:""}`;case"mcp_connect_begin":return Array.isArray(t.servers)?t.servers.map(String).join(", "):"";case"mcp_connect_end":{const s=(Array.isArray(t.results)?t.results:[]).map(o=>`${String(o.server)}:${String(o.status)}(${String(o.duration_ms)}ms)`);return[String(t.status??""),s.join(" ")].filter(Boolean).join(" · ")}case"tool_list_ready":return Array.isArray(t.tools)?d.traces.toolDefs(t.tools.length):"";case"abort":{const n=t.error_code!=null?String(t.error_code):"",s=t.error_message!=null?String(t.error_message):"",o=t.reason!=null?String(t.reason):"";return[n||o,s].filter(Boolean).join(" · ")}case"goal_finished":return`${String(t.outcome)} · rounds=${String(t.rounds)} · tokens=${String(t.tokens_used)}`;case"subagent":return String(t.session_id??"");default:return e.type==="session_meta"?`${String(t.session_id??"")} · ${String(t.model_id??"")}`:""}}function rF(e){const t=e.payload;return t.stop_reason??t.status}const lu="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded bg-gray-100 px-2.5 py-2 text-xs dark:bg-gray-800/70";function aF({p:e}){const t=e.request??{},n=e.session??{},s=(o,c)=>a.jsxs("tr",{children:[a.jsx("td",{className:"pr-3 text-gray-400",children:o}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.cache_read??0)}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.cache_write??0)}),a.jsx("td",{className:"pr-3 text-right font-mono",children:It(c.output??0)}),a.jsx("td",{className:"text-right font-mono",children:It(c.total??0)})]});return a.jsxs("table",{className:"text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-gray-400",children:[a.jsx("th",{}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"cacheRead"}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"cacheWrite"}),a.jsx("th",{className:"pr-3 text-right font-normal",children:"output"}),a.jsx("th",{className:"text-right font-normal",children:"total"})]})}),a.jsxs("tbody",{children:[s("request",t),s("session",n)]})]})}const pM="cursor-pointer text-xs font-medium text-gray-500 marker:text-gray-400 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200";function sF({p:e}){const t=[["session_id",String(e.session_id??"")],["source",String(e.source??"")],["model_id",String(e.model_id??"")],["context_window",String(e.model_context_window??"")],...typeof e.thinking_level=="string"&&e.thinking_level?[["thinking_level",e.thinking_level]]:[],["agent_state",String(e.agent_state??"")],["workspace",String(e.workspace??"")]],n=String(e.system_prompt??"");return a.jsxs("div",{className:"space-y-2.5",children:[a.jsx("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-xs",children:t.map(([s,o])=>a.jsxs(y.Fragment,{children:[a.jsx("dt",{className:"text-gray-400",children:s}),a.jsx("dd",{className:"min-w-0 break-all font-mono text-gray-700 dark:text-gray-300",children:o||"—"})]},s))}),n.trim()&&a.jsxs("details",{children:[a.jsx("summary",{className:pM,children:d.traces.systemPrompt}),a.jsx("div",{className:"md-body mt-1.5 max-h-96 overflow-auto rounded bg-gray-100 px-2.5 py-2 text-sm leading-relaxed text-gray-700 dark:bg-gray-800/70 dark:text-gray-300",children:a.jsx(Zu,{remarkPlugins:Ju,children:n})})]})]})}function iF({schema:e}){const t=e.properties!==null&&typeof e.properties=="object"?e.properties:null;if(!t||Object.keys(t).length===0)return a.jsx("pre",{className:`${lu} mt-1`,children:JSON.stringify(e,null,2)});const n=new Set(Array.isArray(e.required)?e.required.map(String):[]),s=o=>{if(Array.isArray(o.enum))return o.enum.map(String).join(" | ");const c=typeof o.type=="string"?o.type:"object";if(c==="array"){const u=o.items;return`${u!==null&&typeof u=="object"?s(u):"unknown"}[]`}return c};return a.jsx("table",{className:"mt-1 w-full text-xs",children:a.jsx("tbody",{children:Object.entries(t).map(([o,c])=>a.jsxs("tr",{className:"align-top",children:[a.jsxs("td",{className:"whitespace-nowrap pr-3 font-mono text-gray-700 dark:text-gray-300",children:[o,n.has(o)&&a.jsx(kN,{label:d.traces.requiredParam})]}),a.jsx("td",{className:"whitespace-nowrap pr-3 font-mono text-gray-400 dark:text-gray-500",children:s(c)}),a.jsx("td",{className:"text-gray-500 dark:text-gray-400",children:typeof c.description=="string"?c.description:""})]},o))})})}function oF({p:e}){const t=Array.isArray(e.tools)?e.tools:[];return t.length===0?a.jsx("p",{className:"text-xs text-gray-400",children:"—"}):a.jsx("ul",{className:"divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800",children:t.map((n,s)=>a.jsxs("li",{className:"px-2.5 py-1.5 text-xs",children:[a.jsx("span",{className:"font-mono font-semibold text-gray-700 dark:text-gray-300",children:n.name??"—"}),n.description&&a.jsx("p",{className:"mt-0.5 text-gray-500 dark:text-gray-400",children:n.description}),n.parameters!==null&&typeof n.parameters=="object"&&a.jsxs("details",{className:"mt-1",children:[a.jsx("summary",{className:pM,children:d.traces.toolParams}),a.jsx(iF,{schema:n.parameters})]})]},s))})}function lF({msg:e}){const t=e.payload;if(e.type==="session_meta")return a.jsx(sF,{p:t});if(t.type==="tool_list_ready")return a.jsx(oF,{p:t});switch(t.type){case"text":case"thinking":{const n=String(t.text??t.thinking??"");return n.trim()?a.jsx("div",{className:"md-body text-sm leading-relaxed text-gray-700 dark:text-gray-300",children:a.jsx(Zu,{remarkPlugins:Ju,children:n})}):a.jsx("p",{className:"text-xs text-gray-400",children:"—"})}case"image_url":return a.jsx(Ys,{src:String(t.image_url??""),alt:"trace",className:"max-h-48 max-w-full rounded-md"});case"inline_data":return a.jsx(Ys,{src:`data:${String(t.mime_type??"")};base64,${String(t.data??"")}`,alt:"trace",className:"max-h-48 max-w-full rounded-md"});case"tool_call":return a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("p",{className:"font-mono text-xs font-semibold text-gray-700 dark:text-gray-300",children:String(t.name??"")}),a.jsx("pre",{className:lu,children:String(t.arguments??"")})]});case"tool_call_output":{const n=Array.isArray(t.images)?t.images:[];return n.length===0?a.jsx("pre",{className:lu,children:String(t.output??"")}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("pre",{className:lu,children:String(t.output??"")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:n.map((s,o)=>a.jsx(Ys,{src:s,alt:"trace",className:"max-h-48 max-w-full rounded-md"},o))})]})}case"token_usage":return a.jsx(aF,{p:t});default:return a.jsx("pre",{className:lu,children:JSON.stringify(t,null,2)})}}function cF({msg:e,rowKey:t,matched:n,onHighlight:s}){const[o,c]=y.useState(!1),u=e.payload.type??e.type,f=rF(e);return a.jsxs("li",{"data-trace-row":t,children:[a.jsxs("button",{type:"button",onClick:()=>c(p=>!p),onMouseEnter:()=>s?.({ts:e.timestamp,rowKey:t}),onMouseLeave:()=>s?.(null),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left transition-colors duration-150 ${n?"bg-amber-50 dark:bg-amber-950/40":"hover:bg-gray-50 dark:hover:bg-gray-800/50"}`,children:[a.jsx("span",{className:"shrink-0 font-mono text-[11px] text-gray-400",children:PI(e.timestamp)}),a.jsx(tF,{type:u}),a.jsx(On,{tone:ZH(e.type),children:u}),e.origin&&e.origin.length>0&&a.jsx(On,{tone:"brand",children:"origin"}),a.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-gray-500 dark:text-gray-400",children:nF(e)})]}),o&&a.jsxs("div",{className:"border-t border-gray-100 bg-gray-50/60 px-3 py-2 dark:border-gray-800 dark:bg-gray-900/40",children:[a.jsx(lF,{msg:e}),f&&a.jsx("div",{className:"mt-1.5 flex justify-end",children:a.jsx(On,{tone:P6(f),children:f})})]})]})}function uF(e){return e?.compaction!==!0?null:d.chat.compactionTitle(e.compactionMode??"summarize")}const E2=()=>({cacheRead:0,cacheWrite:0,output:0}),dF=2500,A2=(e,t)=>`${e}-${t}`;function Vs({label:e,value:t}){return a.jsxs("div",{className:"flex items-baseline justify-between gap-3 py-0.5",children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400",children:e}),a.jsx("span",{className:"truncate font-mono text-sm font-semibold tabular-nums",children:t})]})}const hM=e=>e.cacheRead+e.cacheWrite,gM=e=>JC(e.cacheRead,e.cacheWrite),xM="flex shrink-0 items-center font-mono text-[11px] tabular-nums text-gray-500 dark:text-gray-400";function Qc({icon:e,value:t,label:n}){return a.jsxs("span",{title:n,"aria-label":n,className:`${xM} gap-1`,children:[a.jsx(Oe,{d:e,className:"text-gray-400"}),t]})}function mF({buckets:e}){const t=hM(e),n=`${d.traces.cacheHit} ${It(e.cacheRead)} · ${d.traces.hitRate} ${Lf(gM(e))}`;return a.jsxs("span",{"aria-label":`${d.traces.taskInput} ${It(t)} · ${n}`,className:xM,children:[a.jsxs("span",{title:d.traces.taskInput,className:"flex items-center gap-1",children:[a.jsx(Oe,{d:Xn.input,className:"text-gray-400"}),It(t)]}),a.jsxs("span",{title:n,className:"ml-1 flex items-center gap-0.5 text-gray-400",children:[a.jsx("span",{children:"("}),a.jsx(Oe,{d:Xn.cacheHit}),a.jsx("span",{children:It(e.cacheRead)}),a.jsx("span",{children:")"})]})]})}function fF({projectId:e,agentId:t,sessionId:n,index:s,highlight:o,onHighlight:c}){const{currency:u}=as(),[f,p]=y.useState(null),[h,x]=y.useState([]),[g,v]=y.useState(0),[w,S]=y.useState(0),[C,N]=y.useState(null),[T,_]=y.useState(null),[R,D]=y.useState(new Set),[z,E]=y.useState(null),L=y.useRef(null),F=y.useRef(null);y.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]),y.useEffect(()=>{p(null),x([]),_(null),D(new Set),E(null);let A=!1;return Promise.all([xA(e,t,n,s),gA(e,t,n,s,0,1e3),Ml(e).catch(()=>null)]).then(([Q,j,U])=>{A||(p(Q),x(j.events),v(j.offset),S(j.total),N(U))}).catch(Q=>{A||_(Ae(Q))}),()=>{A=!0}},[e,t,n,s]);const V=y.useMemo(()=>{const A=h.find(j=>j.type==="session_meta"),Q=A?A.payload:void 0;if(!(!Q?.model_id||!Q.provider))return C?.models.find(j=>j.modelId===Q.model_id&&j.provider===Q.provider)?.pricing},[h,C]),P=A=>V?(A.cacheRead*V.cacheRead+A.cacheWrite*V.cacheWrite+A.output*V.output)/1e6:null,B=y.useMemo(()=>{const A=h.find(Q=>Q.type==="session_meta");return TT(A?A.payload.model_context_window:void 0)},[h]),{tasks:Y,global:q,statsByTask:K,globalLlmMs:H}=y.useMemo(()=>{const A={buckets:E2(),toolCalls:0},Q=new Map;if(!f)return{tasks:[],global:A,statsByTask:Q,globalLlmMs:0};const j=new Map;for(const Se of f.tasks){const Me=Date.parse(Se.startTs),ze=Date.parse(Se.endTs);Number.isFinite(Me)&&Number.isFinite(ze)&&j.set(Se.taskIndex,{min:Me,max:ze})}const U=new Map,ee=Se=>{let Me=U.get(Se);if(!Me){const ze=j.get(Se);Me={taskIndex:Se,segments:[],spans:[],otherSpans:[],messages:[],toolCalls:0,durationMs:ze?Math.max(0,ze.max-ze.min):0},U.set(Se,Me)}return Me};for(const Se of f.tasks)ee(Se.taskIndex);for(const Se of f.modelSegments)ee(Se.taskIndex).segments.push(Se);for(const Se of f.toolSpans){const Me=ee(Se.taskIndex);Me.spans.push(Se),Me.toolCalls+=1}for(const Se of f.otherSpans??[])ee(Se.taskIndex).otherSpans.push(Se);const re=Se=>{for(const Me of f.tasks)if(Se>=Me.messageFrom&&Se<=Me.messageTo)return Me.taskIndex;return null};for(let Se=0;Se<h.length;Se++){const Me=h[Se];if(Me.origin&&Me.origin.length>0)continue;const ze=re(g+Se);ze!==null&&ee(ze).messages.push(Me)}A.toolCalls=f.toolSpans.length;const ke=new Map(f.tasks.map(Se=>[Se.taskIndex,Se]));for(const Se of f.tasks)A.buckets.cacheRead+=Se.tokens.cacheRead,A.buckets.cacheWrite+=Se.tokens.cacheWrite,A.buckets.output+=Se.tokens.output;const be=f.tasks.reduce((Se,Me)=>Se+Me.llmMs,0);return{tasks:[...U.values()].sort((Se,Me)=>Se.taskIndex-Me.taskIndex),global:A,statsByTask:ke,globalLlmMs:be}},[f,h,g]);if(T)return a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:T});if(!f)return a.jsx(on,{className:"h-40"});const $=f.elapsedMs,X=A=>D(Q=>{const j=new Set(Q);return j.has(A)?j.delete(A):j.add(A),j}),le=A=>{for(const Q of Y){const j=Q.messages.findIndex(U=>U.timestamp===A);if(j>=0)return A2(Q.taskIndex,j)}return null},ie=o?.rowKey??(o?.ts!==void 0?le(o.ts):null),I=A=>{const Q=le(A);Q!==null&&(E(Q),requestAnimationFrame(()=>{L.current?.querySelector(`[data-trace-row="${Q}"]`)?.scrollIntoView({block:"center",behavior:"smooth"})}),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>E(null),dF))};return a.jsxs("div",{ref:L,className:"space-y-4",children:[a.jsxs("div",{className:"rounded-md border border-gray-200 p-3 dark:border-gray-800",children:[a.jsx("p",{className:"mb-2 text-xs font-semibold text-gray-500",children:d.traces.globalSummary}),a.jsxs("div",{className:"grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-3",children:[a.jsxs("div",{children:[a.jsx(Vs,{label:d.traces.tasksLabel,value:String(f.tasks.length)}),a.jsx(Vs,{label:d.traces.toolCalls,value:String(q.toolCalls)}),a.jsx(Vs,{label:d.traces.compactions,value:String(f.compactionCount)})]}),a.jsxs("div",{children:[a.jsx(Vs,{label:d.chat.statInput,value:It(hM(q.buckets))}),a.jsx(Vs,{label:d.traces.cacheHit,value:`${It(q.buckets.cacheRead)} · ${Lf(gM(q.buckets))}`}),a.jsx(Vs,{label:d.chat.statOutput,value:It(q.buckets.output)})]}),a.jsxs("div",{children:[a.jsx(Vs,{label:d.common.cost,value:rs(P(q.buckets),u)}),a.jsx(Vs,{label:d.chat.statElapsed,value:Pn(Math.max(0,$))}),a.jsx(Vs,{label:d.chat.statTps,value:sf(v0(q.buckets.output,H))})]})]})]}),Y.map(A=>{const Q=!R.has(A.taskIndex),j=K.get(A.taskIndex),U=j?.context,ee=j?.tokens??E2(),re=uF(j);return a.jsxs("div",{className:"overflow-hidden rounded-md border border-gray-200 dark:border-gray-800",children:[a.jsxs("button",{type:"button",onClick:()=>X(A.taskIndex),"aria-expanded":Q,className:"flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800/60",children:[a.jsx(Zn,{open:Q,size:13,className:"text-gray-400"}),a.jsx("span",{className:"shrink-0 text-sm font-semibold",children:d.traces.task(A.taskIndex+1)}),re!==null&&a.jsx("span",{className:"shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400",children:re}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-x-3 gap-y-1",children:[a.jsx(Qc,{icon:Xn.toolCalls,value:String(A.toolCalls),label:d.traces.toolCalls}),a.jsx(mF,{buckets:ee}),a.jsx(Qc,{icon:Xn.output,value:It(ee.output),label:d.traces.taskOutput}),a.jsx(Qc,{icon:Xn.cost,value:rs(P(ee),u),label:`${d.common.cost}(${u})`}),a.jsx(Qc,{icon:Xn.elapsed,value:Pn(A.durationMs),label:d.chat.statElapsed}),a.jsx(Qc,{icon:Xn.tps,value:sf(v0(ee.output,j?.llmMs??0)),label:d.chat.statTps})]}),U&&a.jsx(BH,{cacheRead:U.cacheRead,cacheWrite:U.cacheWrite,output:U.output,max:B,size:22})]}),Q&&a.jsxs("div",{className:"space-y-3 p-3",children:[(A.segments.length>0||A.spans.length>0||A.otherSpans.length>0)&&a.jsxs("div",{className:"rounded-md border border-gray-100 p-2 dark:border-gray-800/60",children:[a.jsx("p",{className:"mb-1.5 text-[11px] font-medium text-gray-500",children:d.traces.timeline}),a.jsx(QH,{segments:A.segments,toolSpans:A.spans,otherSpans:A.otherSpans,highlight:o,onHighlight:c,onJump:I,hideTaskLabel:!0})]}),a.jsxs("div",{children:[a.jsxs("p",{className:"mb-1.5 text-[11px] font-medium text-gray-500",children:[d.traces.messages,"(",A.messages.length,")"]}),A.messages.length===0?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.none}):a.jsx("ul",{className:"divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800",children:A.messages.map((ke,be)=>{const ye=A2(A.taskIndex,be);return a.jsx(cF,{msg:ke,rowKey:ye,matched:ye===ie||ye===z,onHighlight:Se=>c(Se)},be)})})]})]})]},A.taskIndex)}),h.length<w&&a.jsx("p",{className:"text-xs text-gray-400",children:d.traces.truncatedNote(h.length,w)})]})}const Wg=6;function pF({session:e,active:t}){const[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(null),[p,h]=y.useState(!1),[x,g]=y.useState(null),[v,w]=y.useState(0),S=y.useRef(t);if(y.useEffect(()=>{t&&!S.current&&w(T=>T+1),S.current=t},[t]),y.useEffect(()=>{if(!t)return;let T=!1;return hA(e.sessionId).then(_=>{T||(s([..._.files].sort((R,D)=>D.index-R.index)),c(null))}).catch(_=>{T||(s([]),c(Ae(_)))}),()=>{T=!0}},[t,v,e.sessionId]),n===null)return a.jsxs("div",{className:"space-y-3 p-4",children:[a.jsx(on,{className:"h-5 w-2/3"}),a.jsx(on,{className:"h-5 w-1/2"})]});if(o!==null)return a.jsx(Fa,{title:d.tracePanel.loadFailed,description:o});if(n.length===0)return a.jsx(Fa,{title:d.tracePanel.empty,description:d.tracePanel.emptyHint});const C=n.find(T=>T.index===u)??n[0],N=p?n:n.slice(0,Wg);return a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[a.jsx("span",{className:"mr-1 text-xs text-gray-400",children:d.traces.filesTitle}),N.map(T=>a.jsxs("button",{type:"button",onClick:()=>f(T.index),title:`${T.date} · ${ju(T.sizeBytes)}`,className:`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${T.index===C.index?"border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100":"border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"}`,children:["#",String(T.index).padStart(3,"0")]},T.index)),!p&&n.length>Wg&&a.jsxs("button",{type:"button",title:d.chat.loadMore,"aria-label":d.chat.loadMore,onClick:()=>h(!0),className:"rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60",children:["+",n.length-Wg]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("p",{className:"min-w-0 flex-1 truncate font-mono text-xs text-gray-400",children:[C.date," · ",ju(C.sizeBytes)]}),a.jsxs("a",{href:yA(e.projectId,e.agentId,e.sessionId,C.index),download:!0,className:"inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60",children:[a.jsx(Hx,{size:Ye.rowLead}),d.traces.exportFile]})]}),a.jsx(fF,{projectId:e.projectId,agentId:e.agentId,sessionId:e.sessionId,index:C.index,highlight:x,onHighlight:g})]})})}function Co({children:e,label:t,title:n,className:s=""}){const[o,c]=y.useState(!1),u=y.useId();return a.jsxs("div",{className:s,children:[a.jsxs("button",{type:"button","aria-expanded":o,"aria-controls":u,...n===void 0&&t!==void 0?{"aria-label":d.common.moreInfoAbout(t)}:{},onClick:()=>c(f=>!f),className:`flex items-center ${Ro.tight} rounded text-xs text-gray-500 transition-colors duration-150 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200`,children:[a.jsx(Zn,{open:o,size:Ye.chevronDense}),n??d.common.moreInfo]}),a.jsx("div",{id:u,hidden:!o,className:"mt-1.5 pl-4.5 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:e})]})}const hF="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z",gF="M3 3l18 18M10.6 5.1A11 11 0 0 1 12 5c6.4 0 10 7 10 7a17.6 17.6 0 0 1-3.2 3.9M6.6 6.6C4 8.3 2 12 2 12s3.6 7 10 7a10 10 0 0 0 4.8-1.2M9.9 9.9a3 3 0 0 0 4.2 4.2";function ts({label:e,hint:t,info:n,infoLabel:s,error:o,invalid:c,required:u,size:f="base",className:p,id:h,...x}){const[g,v]=y.useState(!1),w=g?d.auth.hidePassword:d.auth.showPassword,S=y.useId(),C=y.useId(),N=h??C;return a.jsx(Vu,{label:e,hint:t,error:o,errorId:S,required:u,info:n,infoLabel:s,controlId:N,children:a.jsxs("div",{className:"relative",children:[a.jsx(at,{...x,id:n!==void 0?N:h,required:u,size:f,type:g?"text":"password",invalid:!!o||!!c,"aria-describedby":o?S:void 0,className:`${f==="sm"?"pr-8":"pr-10"} ${p??""}`}),a.jsx("button",{type:"button","aria-label":w,title:w,tabIndex:-1,onClick:()=>v(T=>!T),className:`absolute inset-y-0 right-0 flex items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300 ${f==="sm"?"w-8":"w-10"}`,children:a.jsx("svg",{width:f==="sm"?14:16,height:f==="sm"?14:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a.jsx("path",{d:g?gF:hF})})})]})})}function ws({options:e,value:t,onChange:n,cols:s=3}){return a.jsx("div",{className:`grid ${s===2?"grid-cols-2":"grid-cols-3"} gap-0.5 rounded-md bg-gray-100 p-0.5 dark:bg-gray-800`,children:e.map(o=>a.jsx("button",{type:"button",onClick:()=>n(o.value),className:`rounded px-1 py-1 text-xs transition-colors duration-150 ${t===o.value?"bg-white font-medium text-gray-900 shadow-sm dark:bg-gray-600 dark:text-gray-100":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"}`,children:o.label},o.value))})}function js({checked:e,onChange:t,disabled:n,className:s,...o}){return a.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:n,onClick:()=>t(!e),className:"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full inset-ring inset-ring-black/10 dark:inset-ring-white/10 transition-colors duration-200 ease-out focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent-bg)]/40 disabled:cursor-not-allowed disabled:opacity-60 "+(e?"bg-[var(--accent-bg)]":"bg-gray-200 dark:bg-gray-700")+` ${s??""}`,...o,children:a.jsx("span",{"aria-hidden":!0,className:`inline-block size-4 rounded-full border border-black/10 bg-white transition-transform duration-200 ease-out ${e?"translate-x-[18px]":"translate-x-0.5"}`})})}const yM="https://open.feishu.cn",xF=/^\d+:[A-Za-z0-9_-]{5,}$/;function yF(e="feishu"){return{channel:e,feishu:{appId:"",appSecret:"",baseDomain:yM,clearSecret:!1},telegram:{botToken:"",clearToken:!1}}}function _2(e){const t=e.find(s=>s.enabled)?.channel,n=yF(t??e[0]?.channel??"feishu");for(const s of e)s.channel==="feishu"&&(n.feishu={appId:s.appId,appSecret:"",baseDomain:s.baseDomain,clearSecret:!1});return n}function bF(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function vF(e,t){const n={};if(e.channel==="telegram"){const f=e.telegram.botToken.trim(),p=f===""&&e.telegram.clearToken&&t;return f===""&&!t?n.botToken="required":f!==""&&!xF.test(f)&&(n.botToken="token_invalid"),Object.keys(n).length>0?{ok:!1,errors:n}:{ok:!0,channel:"telegram",body:{...f!==""?{botToken:f}:{},...p?{clearBotToken:!0}:{}}}}const s=e.feishu.appId.trim();s===""&&(n.appId="required");const o=e.feishu.appSecret.trim(),c=o===""&&e.feishu.clearSecret&&t;o===""&&!t&&(n.appSecret="required");const u=e.feishu.baseDomain.trim()||yM;return bF(u)||(n.baseDomain="url_invalid"),Object.keys(n).length>0?{ok:!1,errors:n}:{ok:!0,channel:"feishu",body:{appId:s,...o!==""?{appSecret:o}:{},...c?{clearAppSecret:!0}:{},baseDomain:u}}}function kF(e){if(e.channel==="telegram"){const o=e.telegram.botToken.trim();return{channel:"telegram",body:{...o!==""?{botToken:o}:{}}}}const t=e.feishu.appId.trim(),n=e.feishu.appSecret.trim(),s=e.feishu.baseDomain.trim();return{channel:"feishu",body:{...t!==""?{appId:t}:{},...n!==""?{appSecret:n}:{},...s!==""?{baseDomain:s}:{}}}}function wF(e,t){return e.channel==="telegram"?e.telegram.botToken.trim()!==""||e.telegram.clearToken:e.feishu.appId!==t.feishu.appId||e.feishu.baseDomain!==t.feishu.baseDomain||e.feishu.appSecret.trim()!==""||e.feishu.clearSecret}function SF(e,t){return e.channel==="telegram"?e.telegram.botToken.trim()!==""||t:e.feishu.appId.trim()!==""&&e.feishu.appSecret.trim()!==""||t}const jF=3e3,bM={feishu:{tutorial:"https://open.feishu.cn/document/develop-an-echo-bot/introduction",console:"https://open.feishu.cn/app"},telegram:{tutorial:"https://core.telegram.org/bots/tutorial",console:"https://core.telegram.org/bots/api"}},CF={disconnected:"muted",connecting:"busy",connected:"success",error:"danger"};function Rm(e){if(e!==void 0)return e==="required"?d.common.requiredField:e==="token_invalid"?d.telegram.invalidToken:d.feishu.invalidDomain}const Uu={secretConfigured:!1,secretMasked:null,enabled:!1,status:{state:"disconnected"},lastChatKnown:!1};function vM(e,t){if(e===null)return{...Uu,status:t};const n=e.channel==="telegram"?e.botTokenMasked:e.appSecretMasked;return{secretConfigured:n!==void 0,secretMasked:n??null,enabled:e.enabled,status:t,lastChatKnown:e.lastChatKnown}}function NF(e){const t={feishu:Uu,telegram:Uu};for(const n of e.bindings)t[n.binding.channel]=vM(n.binding,n.status);return t}function kM(e,t){const{poll:n,onChanged:s,onLoadFailed:o}=t,[c,u]=y.useState(null),[f,p]=y.useState(null),[h,x]=y.useState({feishu:Uu,telegram:Uu}),[g,v]=y.useState({}),[w,S]=y.useState(!1),[C,N]=y.useState(!1),[T,_]=y.useState(!1),[R,D]=y.useState(!1),z=y.useRef(null);y.useEffect(()=>{let I=!1,A=z.current===e;const Q=async U=>{try{const ee=await YE(e);if(I)return;if(x(NF(ee)),U){const re=_2(ee.bindings.map(ke=>ke.binding));u(re),p(re),A=!0}}catch(ee){if(I)return;U&&(A=!0,Be(Ae(ee)),o?.())}};z.current!==e&&(z.current=e,u(null),p(null),Q(!0));const j=n?setInterval(()=>{Q(!1)},jF):null;return()=>{I=!0,j!==null&&clearInterval(j),!A&&z.current===e&&(z.current=null)}},[e,n]);const E=I=>{u(A=>A&&{...A,...I}),v({})},L=I=>{E({channel:I})},F=c?.channel??"feishu",V=h[F],P=h.feishu.enabled?"feishu":h.telegram.enabled?"telegram":null,B=P!==null&&P!==F,Y=c!==null&&f!==null&&wF(c,f),q=(I,A,Q)=>{if(x(j=>({...j,[I]:vM(A,Q)})),A!==null){const j=_2([A]),U=I==="feishu"?{feishu:j.feishu}:{telegram:j.telegram};u(ee=>ee&&{...ee,...U}),p(ee=>ee&&{...ee,...U})}},K=async()=>{if(c){_(!0);try{const I=kF(c);if(I.channel==="telegram"){const A=await eA(e,I.body);if(A.ok){const Q=A.latencyMs??0;yt(A.botUsername!==void 0?d.messaging.testOkAs(A.botUsername,Q):d.messaging.testOk(Q))}else Be(d.messaging.testFail(A.error??d.common.unknownError))}else{const A=await JE(e,I.body);A.ok?yt(d.messaging.testOk(A.latencyMs??0)):Be(d.messaging.testFail(A.error??d.common.unknownError))}}catch(I){Be(d.messaging.testFail(Ae(I)))}finally{_(!1)}}},H=async()=>{D(!0);try{await tA(e,F),yt(d.messaging.testMessageSent)}catch(I){Be(Ae(I))}finally{D(!1)}},$=async()=>{if(!c)return;const I=vF(c,h[c.channel].secretConfigured);if(!I.ok){v(I.errors);return}S(!0);try{const A=I.channel==="telegram"?await QE(e,I.body):await XE(e,I.body);q(I.channel,A.binding,A.status),yt(d.common.saved)}catch(A){Be(Ae(A))}finally{S(!1)}},X=async I=>{N(!0);try{const A=await ZE(e,F,I);q(F,A.binding,A.status),s?.(e,I&&A.binding?.enabled===!0?F:null)}catch(A){Be(Ae(A))}finally{N(!1)}},le=!V.enabled&&(B||!V.secretConfigured||Y),ie=!V.enabled&&P!==null&&B?d.messaging.otherEnabledHint(d.messaging.channelName[P]):!V.enabled&&!V.secretConfigured?d.messaging.credentialMissingHint:!V.enabled&&Y?d.messaging.saveBeforeEnable:null;return{form:c,patchForm:E,selectChannel:L,channels:h,fieldErrors:g,dirty:Y,busy:w,toggling:C,testing:T,sendingTest:R,testable:c!==null&&SF(c,V.secretConfigured),toggleBlocked:le||C||w,toggleHint:ie,save:$,toggleEnabled:X,testConnection:K,sendTestMessage:H}}function cx({href:e,label:t}){return a.jsxs("a",{href:e,target:"_blank",rel:"noreferrer noopener",className:"shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300",children:[t," ↗"]})}function R2({label:e,required:t,link:n,children:s}){return a.jsxs("div",{className:"block",children:[a.jsxs("span",{className:"mb-1 flex items-baseline justify-between gap-2",children:[a.jsx(Yn,{block:!1,...t?{required:!0}:{},children:e}),n]}),s]})}function I2({masked:e,clearLabel:t,checked:n,enabled:s,onChange:o}){return a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400",children:[a.jsx("span",{className:"font-mono",children:e}),a.jsxs("label",{className:`flex items-center gap-1.5 ${s?"cursor-not-allowed opacity-60":""}`,children:[a.jsx("input",{type:"checkbox",checked:n,disabled:s,onChange:c=>o(c.target.checked)}),t]}),s&&a.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:d.messaging.disableBeforeClearHint})]})}function wM({b:e}){const{form:t}=e;if(!t)return null;const n=t.channel,s=e.channels[n],o=bM[n];return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{role:"group","aria-label":d.messaging.channelLabel,children:a.jsx(ws,{cols:2,options:[{value:"feishu",label:d.messaging.channelName.feishu},{value:"telegram",label:d.messaging.channelName.telegram}],value:n,onChange:c=>e.selectChannel(c)})}),a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[a.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300",children:[a.jsx(js,{checked:s.enabled,disabled:e.toggleBlocked,onChange:c=>{e.toggleEnabled(c)}}),d.messaging.enabled]}),a.jsx("span",{className:"ml-2 text-gray-500 dark:text-gray-400",children:d.messaging.statusLabel}),a.jsx("span",{className:`font-medium ${sn[CF[s.status.state]]}`,children:d.messaging.status[s.status.state]})]}),s.status.state==="error"&&s.status.lastError!==void 0&&a.jsx("p",{title:s.status.lastError,className:"line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400",children:s.status.lastError})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(ge,{size:"sm",disabled:e.testing||e.busy||!e.testable,onClick:()=>{e.testConnection()},children:e.testing?d.messaging.testing:d.messaging.test}),a.jsx(ge,{size:"sm",disabled:e.sendingTest||e.busy||s.status.state!=="connected"||!s.lastChatKnown,...s.lastChatKnown?{}:{title:n==="telegram"?d.telegram.testMessageNoChat:d.feishu.testMessageNoChat},onClick:()=>{e.sendTestMessage()},children:e.sendingTest?d.messaging.sendingTestMessage:d.messaging.sendTestMessage})]}),e.toggleHint!==null&&a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:e.toggleHint}),n==="telegram"?a.jsxs(a.Fragment,{children:[a.jsx(R2,{label:d.telegram.botToken,required:!s.secretConfigured,link:a.jsx(cx,{href:o.console,label:d.messaging.console}),children:a.jsx(ts,{size:"sm","aria-label":d.telegram.botToken,...s.secretConfigured?{placeholder:d.telegram.botTokenKeepHint}:{},error:Rm(e.fieldErrors.botToken),value:t.telegram.botToken,onChange:c=>e.patchForm({telegram:{botToken:c.target.value,clearToken:!1}}),autoComplete:"off"})}),s.secretMasked!==null&&t.telegram.botToken===""&&a.jsx(I2,{masked:s.secretMasked,clearLabel:d.telegram.clearToken,checked:t.telegram.clearToken,enabled:s.enabled,onChange:c=>e.patchForm({telegram:{...t.telegram,clearToken:c}})})]}):a.jsxs(a.Fragment,{children:[a.jsx(R2,{label:d.feishu.appId,required:!0,link:a.jsx(cx,{href:o.console,label:d.messaging.console}),children:a.jsx(at,{size:"sm","aria-label":d.feishu.appId,error:Rm(e.fieldErrors.appId),value:t.feishu.appId,onChange:c=>e.patchForm({feishu:{...t.feishu,appId:c.target.value}}),className:"font-mono",placeholder:"cli_xxxxxxxxxxxxxxxx",autoComplete:"off"})}),a.jsx(ts,{size:"sm",label:d.feishu.appSecret,...s.secretConfigured?{placeholder:d.feishu.appSecretKeepHint}:{required:!0},error:Rm(e.fieldErrors.appSecret),value:t.feishu.appSecret,onChange:c=>e.patchForm({feishu:{...t.feishu,appSecret:c.target.value,clearSecret:!1}}),autoComplete:"off"}),s.secretMasked!==null&&t.feishu.appSecret===""&&a.jsx(I2,{masked:s.secretMasked,clearLabel:d.feishu.clearSecret,checked:t.feishu.clearSecret,enabled:s.enabled,onChange:c=>e.patchForm({feishu:{...t.feishu,clearSecret:c}})}),a.jsx(at,{size:"sm",label:d.feishu.baseDomain,hint:d.feishu.baseDomainHint,error:Rm(e.fieldErrors.baseDomain),value:t.feishu.baseDomain,onChange:c=>e.patchForm({feishu:{...t.feishu,baseDomain:c.target.value}}),className:"font-mono",placeholder:"https://open.feishu.cn",autoComplete:"off"})]})]})}function SM({channel:e}){const t=e==="telegram"?d.telegram:d.feishu,n=bM[e];return a.jsxs("div",{className:"space-y-2 border-t border-gray-200 pt-3 dark:border-gray-800",children:[a.jsxs(Co,{title:d.messaging.faqSetupTitle,children:[a.jsx("ol",{className:"list-decimal space-y-1 pl-4",children:t.setupSteps.map(s=>a.jsx("li",{children:s},s))}),a.jsx("p",{className:"mt-1.5",children:a.jsx(cx,{href:n.tutorial,label:d.messaging.tutorial})})]}),a.jsx(Co,{title:d.messaging.faqWhatTitle,children:a.jsx("p",{children:t.intro})}),a.jsx(Co,{title:d.messaging.faqTroubleTitle,children:a.jsxs("ul",{className:"list-disc space-y-1 pl-4",children:[a.jsx("li",{children:d.messaging.troubleNoChat}),a.jsx("li",{children:d.messaging.troubleConnError}),e==="telegram"&&a.jsx("li",{children:d.messaging.troubleOnePoller})]})})]})}function TF({sessionId:e,active:t}){const n=kM(e,{poll:t});return a.jsx("div",{className:"h-full overflow-y-auto p-3",children:n.form===null?a.jsxs("div",{className:"space-y-2",children:[a.jsx(on,{className:"h-5 w-40"}),a.jsx(on,{className:"h-24 w-full"})]}):a.jsxs("div",{className:"space-y-3",children:[a.jsx(wM,{b:n}),a.jsx("div",{className:"flex items-center justify-end gap-2",children:a.jsx(ge,{variant:"primary",size:"sm",disabled:n.busy,onClick:()=>{n.save()},children:n.busy?d.common.saving:d.common.save})}),a.jsx(SM,{channel:n.form.channel})]})})}const MF={dark:!0,surface:"bg-gray-950 text-gray-100",border:"border-gray-800",iconButton:"text-gray-400 hover:bg-gray-800 hover:text-gray-200",grip:"text-gray-600",tabActive:"bg-gray-800 text-gray-100",tabIdle:"text-gray-400 hover:bg-gray-800 hover:text-gray-200",tabKill:"bg-gray-800 hover:bg-gray-700",muted:"text-gray-400",success:"text-emerald-400",attention:"text-amber-400",danger:"text-red-400",outlineButton:"border-gray-700 text-gray-300 hover:bg-gray-800"},EF={dark:!1,surface:"bg-white text-gray-900",border:"border-gray-200",iconButton:"text-gray-500 hover:bg-gray-100 hover:text-gray-800",grip:"text-gray-400",tabActive:"bg-gray-100 text-gray-900",tabIdle:"text-gray-500 hover:bg-gray-100 hover:text-gray-800",tabKill:"bg-gray-100 hover:bg-gray-200",muted:"text-gray-500",success:"text-emerald-600",attention:"text-amber-600",danger:"text-red-600",outlineButton:"border-gray-300 text-gray-600 hover:bg-gray-100"};function jM(){return as().terminalDark?MF:EF}const xu=new Map,wf=new Map,ux=new Set;function CM(){for(const e of[...ux])e()}function AF(e){return ux.add(e),()=>ux.delete(e)}const NM={status:"connecting",info:null};function _F(e){return(e!==null?wf.get(e):void 0)??NM}function TM(e){let t=xu.get(e);return t||(t=document.createElement("div"),t.className="flex h-full w-full min-h-0 flex-col",xu.set(e,t)),t}function L2(e,t){const n=wf.get(e)??{...NM};wf.set(e,{...n,...t}),CM()}function RF(e){return async()=>{const t=await vf(`/api/terminals/${encodeURIComponent(e)}`);if(!t)throw new Error("Terminal no longer exists.");return t}}function IF(){const e=[];for(const t of["right","bottom"]){if(!Ba(t))continue;const n=CB(t);if(n===null||!n.startsWith("terminal:"))continue;const s=n.slice(9);e.includes(s)||e.push(s)}return e}let Im=[];function LF(){const e=IF();return(e.length!==Im.length||e.some((t,n)=>t!==Im[n]))&&(Im=e),Im}function OF(){const e=y.useSyncExternalStore(Zf,LF);return y.useEffect(()=>{for(const t of[...xu.keys()])e.includes(t)||(xu.get(t)?.remove(),xu.delete(t),wf.delete(t));CM()},[e]),a.jsx(a.Fragment,{children:e.map(t=>ss.createPortal(a.jsx(YT,{ensure:RF(t),onStatus:n=>{L2(t,{status:n}),n==="exited"&&Xs()},onInfo:n=>{L2(t,{info:n}),Xs()},onTitle:n=>XB(t,n),className:"min-h-0 flex-1 overflow-hidden"},t),TM(t),t))})}const ep=320,Ky="penguin.panelWidth";function Wy(e){return Math.max(ep,Math.min(720,Math.round(e*.5)))}function MM(e){return Math.min(Wy(e),Math.max(ep,Math.round(e*.4)))}function DF(){try{const e=Number(localStorage.getItem(Ky));return Number.isFinite(e)&&e>0?e:null}catch{return null}}function $F(){const e=DF();return e===null?MM(window.innerWidth):Math.min(Wy(window.innerWidth),Math.max(ep,Math.round(e)))}const Pu=zl(()=>({width:null}));function Yy(){const{width:e}=Pu.getState();if(e!==null)return e;const t=$F();return Pu.setState({width:t}),t}function EM(e){e!==Pu.getState().width&&Pu.setState({width:e})}function UF(){return Yy()}function PF(){return Bl(Pu,()=>Yy())}function zF(e){EM(Math.min(Wy(window.innerWidth),Math.max(ep,Math.round(e))))}function BF(){try{localStorage.setItem(Ky,String(Math.round(Yy())))}catch{}}function HF(){EM(MM(window.innerWidth));try{localStorage.removeItem(Ky)}catch{}}const FF=.45;function AM(){return document.querySelector("[data-dock-host]")?.getBoundingClientRect()??null}function O2(e,t){const n=document.elementFromPoint(e,t)?.closest?.("[data-dock-pos]");if(n?.dataset.dockPos)return n.dataset.dockPos;const s=AM();if(!s||e<s.left||e>s.right||t<s.top||t>s.bottom)return null;const o=[["right",(s.right-e)/s.width],["bottom",(s.bottom-t)/s.height]];o.sort((u,f)=>u[1]-f[1]);const c=o[0];return c[1]<=FF?c[0]:null}function qF(e,t){const n=document.querySelector(`[data-testid='dock'][data-position='${t}']`)?.getBoundingClientRect()??null;if(t==="bottom"){const u=Math.min(n?.height??Math.max(UT,Math.min(Oy*e.height,VT()*e.height)),e.height);return{left:e.left,top:e.bottom-u,width:e.width,height:u}}const s=document.querySelector("[data-dock-row]")?.getBoundingClientRect()??e,o=Math.max(e.top,s.top),c=Math.min(n?.width??UF(),e.width);return{left:e.right-c,top:o,width:c,height:s.bottom-o}}function D2(e){const t=e.candidate===e.position;return a.jsx("div",{"data-dock-pos":e.position,"data-testid":"dock-layout-target",className:`${e.shape} rounded-[3px] border transition-colors duration-100 ${t?"border-sky-400 bg-sky-500/60":"border-gray-400/70 bg-gray-500/10 dark:border-white/30 dark:bg-white/10"}`})}function $2({candidate:e}){const t=AM();return t?ss.createPortal(a.jsxs(a.Fragment,{children:[e&&a.jsx("div",{"data-testid":"dock-layout-preview","data-pos":e,"aria-hidden":!0,className:"pointer-events-none fixed z-[65] rounded-sm border border-sky-400/70 bg-sky-500/20",style:qF(t,e)}),a.jsxs("div",{"data-testid":"dock-layout-widget",className:"fixed z-[70] flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white/95 p-2.5 shadow-lg dark:border-white/20 dark:bg-gray-900/90",style:{left:t.right-108,top:t.bottom-96},children:[a.jsx(D2,{position:"bottom",candidate:e,shape:"h-4 w-9"}),a.jsx(D2,{position:"right",candidate:e,shape:"h-9 w-4.5"})]})]}),document.body):null}const VF="M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z";function GF({size:e=Ye.iconButton}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a.jsx("circle",{cx:"5",cy:"12",r:"2.5"}),a.jsx("circle",{cx:"19",cy:"5.5",r:"2.5"}),a.jsx("circle",{cx:"19",cy:"18.5",r:"2.5"}),a.jsx("path",{d:"M7.4 11 16.7 6.6M7.4 13l9.3 4.4"})]})}function wl(e){switch(e){case"agents":return d.chat.openAgents;case"workspace":return d.chat.workspacePanel;case"memory":return d.chat.memoryViewTitle;case"trace":return d.nav.traces;case"messaging":return d.messaging.panelTitle}}function dx(e,t=Ye.iconButton){switch(e){case"agents":return a.jsx(GF,{size:t});case"workspace":return a.jsx(Oe,{d:El,size:t});case"memory":return a.jsx(Oe,{d:VF,size:t});case"trace":return a.jsx(Oe,{d:vs.traces,size:t});case"messaging":return a.jsx(Oe,{d:XC,size:t})}}function Yg(e){const t=y.useRef(e);t.current=e;const n=y.useRef(null);return y.useMemo(()=>({onPointerDown:s=>{if(s.button!==0)return;const o=t.current.begin(s);o!==null&&(n.current={payload:o,x:s.clientX,y:s.clientY,started:!1},s.currentTarget.setPointerCapture(s.pointerId))},onPointerMove:s=>{const o=n.current;if(o){if(!o.started){const c=t.current.threshold??5;if(Math.hypot(s.clientX-o.x,s.clientY-o.y)<c)return;o.started=!0}t.current.onMove?.(s,o.payload)}},onPointerUp:s=>{const o=n.current;n.current=null,s.currentTarget.releasePointerCapture?.(s.pointerId),o&&t.current.onEnd?.(o.payload,o.started)},onPointerCancel:()=>{n.current=null,t.current.onCancel?.()}}),[])}const U2="M12 5v14M5 12h14",KF="M4 5h16v14H4zM4 14h16",WF="M4 5h16v14H4zM14 5v14",YF="M14 4h6v6M20 4l-8 8M10 6H5a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5";function Lm(e){return a.jsx("button",{type:"button",title:e.label,"aria-label":e.label,"data-testid":e.testId,onClick:e.onClick,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:e.children})}function P2(e){return a.jsxs("div",{"data-testid":"dock-tab","data-tab-id":e.tabId,...e.terminalId!==void 0?{"data-terminal-id":e.terminalId}:{},"data-active":e.active,className:`flex h-6 max-w-44 items-center rounded-md pr-0.5 transition-colors duration-150 ${e.active?"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200":"text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-300"}`,children:[a.jsxs("button",{type:"button",title:e.title,onClick:e.onSelect,className:"flex h-full min-w-0 flex-1 items-center gap-1.5 pl-2 pr-1 text-left text-xs",children:[a.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:e.glyph}),a.jsx("span",{className:"min-w-0 truncate",children:e.label}),e.badge&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${Fl.attention}`})]}),a.jsx("button",{type:"button",title:e.closeLabel,"aria-label":`${e.closeLabel}: ${e.label}`,"data-testid":"dock-tab-close",onClick:e.onClose,className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-200 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200",children:a.jsx(Hl,{size:10})})]})}function XF({id:e,active:t}){const n=jM(),s=y.useSyncExternalStore(AF,()=>_F(t?e:null)),o=y.useRef(null);return y.useEffect(()=>{const c=o.current;if(!c||!t)return;const u=TM(e);return c.appendChild(u),()=>{u.parentElement===c&&c.removeChild(u)}},[e,t]),a.jsx("div",{ref:o,"data-testid":"dock-terminal-body","data-status":s.status,className:`flex min-h-0 flex-1 flex-col overflow-hidden px-2 py-1 ${n.surface}`})}function z2(e,t,n){return e?`${e.seq??n}: ${KB(e.title)||e.name}`:`${n}: ${t.slice(0,6)}`}function QF({choose:e,chooseTerminal:t,terminalSupported:n,horizontal:s}){const o="flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",c=u=>a.jsxs("button",{type:"button","data-testid":`dock-pick-${u}`,onClick:()=>e(u),className:o,children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:dx(u)}),a.jsx("span",{className:"min-w-0 truncate",children:wl(u)})]},u);return a.jsx("div",{"data-testid":"dock-picker",className:"flex min-h-0 flex-1 items-center justify-center overflow-y-auto p-4",children:a.jsxs("div",{className:s?"flex max-w-full flex-wrap items-center justify-center gap-1":"flex w-60 flex-col gap-0.5",children:[c("agents"),n&&a.jsxs("button",{type:"button","data-testid":"dock-pick-terminal",onClick:t,className:o,children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:a.jsx(Oe,{d:vs.terminal,size:Ye.iconButton})}),a.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.terminal.title}),a.jsx("kbd",{className:"shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500",children:"Ctrl+`"})]}),c("workspace"),c("memory"),c("trace"),c("messaging")]})})}function B2({view:e,renderPanel:t,panelBadges:n,terminalSupported:s,open:o=!0,animateEntrance:c=!0}){y.useSyncExternalStore(Zf,$y);const u=y.useSyncExternalStore(ZT,QT),f=new Map(u.map(he=>[he.id,he])),{position:p,merged:h,tabs:x,activeKey:g}=e,v=p==="bottom",w=p==="right"?"bottom":"right",[S,C]=y.useState(!1),N=x.find(he=>kn(he)===g)??null,[T,_]=y.useState(null),R=y.useCallback((he,ne)=>{if(he.kind==="terminal"){_({id:he.terminalId,label:ne});return}J0(kn(he))},[]),D=y.useCallback(()=>{T&&(ZB(T.id),J0(`terminal:${T.id}`),_(null))},[T]),z=y.useCallback(()=>{if(N?.kind!=="terminal")return;const he=h?Lu(kn(N))??"bottom":p;eH(N.terminalId,he)},[N,h,p]),E=y.useRef(null);y.useEffect(()=>{g!==null&&E.current?.querySelector(`[data-tab-id="${CSS.escape(g)}"]`)?.scrollIntoView({block:"nearest",inline:"nearest"})},[g,x]),y.useEffect(()=>{const he=E.current;if(!he)return;const ne=oe=>{const J=Math.abs(oe.deltaX)>Math.abs(oe.deltaY)?oe.deltaX:oe.deltaY;J===0||he.scrollWidth<=he.clientWidth||(oe.preventDefault(),he.scrollLeft+=J)};return he.addEventListener("wheel",ne,{passive:!1}),()=>he.removeEventListener("wheel",ne)},[]);const[L,F]=y.useState({active:!1,candidate:null}),V=()=>F({active:!1,candidate:null}),P=Yg({begin:he=>h||he.target.closest("button, [data-testid='dock-tab']")?null:{},onMove:he=>F({active:!0,candidate:O2(he.clientX,he.clientY)}),onEnd:(he,ne)=>{const oe=L.candidate;V(),ne&&oe&&oe!==p&&o2(p,oe)},onCancel:V}),[B,Y]=y.useState({active:!1,candidate:null}),q=()=>Y({active:!1,candidate:null}),K=Yg({threshold:6,begin:he=>{if(h)return null;const ne=he.target;if(ne.closest("[data-testid='dock-tab-close']"))return null;const oe=ne.closest("[data-tab-id]")?.dataset.tabId;return oe?{id:oe}:null},onMove:(he,{id:ne})=>{const oe=he.currentTarget.getBoundingClientRect();if(he.clientY<oe.top-20||he.clientY>oe.bottom+20){Y({active:!0,candidate:O2(he.clientX,he.clientY)});return}Y({active:!1,candidate:null});const J=[...he.currentTarget.querySelectorAll("[data-tab-id]")],ht=J.map(He=>He.dataset.tabId),ve=J.filter(He=>He.dataset.tabId!==ne);let Xe=ve.length;for(let He=0;He<ve.length;He+=1){const Pe=ve[He].getBoundingClientRect();if(he.clientX<Pe.left+Pe.width/2){Xe=He;break}}const Ge=ve.map(He=>He.dataset.tabId);Ge.splice(Xe,0,ne),Ge.some((He,Pe)=>He!==ht[Pe])&&EB(p,Ge)},onEnd:({id:he},ne)=>{const{active:oe,candidate:J}=B;if(q(),!ne){qg(he);return}!oe||!J||J===Lu(he)||MB(he,J)},onCancel:q}),[H,$]=y.useState(!1),X=PF(),le=y.useRef(null),ie=Yg({threshold:0,begin:he=>(he.preventDefault(),$(!0),{}),onMove:he=>{const ne=le.current?.getBoundingClientRect();if(ne)if(v){const oe=document.querySelector("[data-dock-host]")?.getBoundingClientRect();if(!oe||oe.height===0)return;UB((ne.bottom-he.clientY)/oe.height)}else zF(ne.right-he.clientX)},onEnd:()=>{$(!1),v||BF()},onCancel:()=>$(!1)}),[I,A]=y.useState(()=>{const he=document.querySelector("[data-dock-host]");return he instanceof HTMLElement?he.getBoundingClientRect().height:0});y.useLayoutEffect(()=>{if(!v)return;const he=document.querySelector("[data-dock-host]");if(!(he instanceof HTMLElement))return;const ne=()=>A(he.getBoundingClientRect().height);ne();const oe=new ResizeObserver(ne);return oe.observe(he),()=>oe.disconnect()},[v]);const Q=Math.round(Math.min(Oy*I,Math.max(UT,VT()*I))),j=y.useCallback(()=>v?PB():HF(),[v]),U=he=>{C(!1),ho(he,h?void 0:p)},ee=new Set(By(u.map(he=>he.id))),re=u.filter(he=>ee.has(he.id)),ke=a.jsxs(Qn,{open:S,setOpen:C,portal:{direction:"down",align:"right"},menuClass:"w-56",button:a.jsx(Lm,{label:d.dock.addTab,testId:"dock-add",onClick:()=>C(!S),children:a.jsx(Oe,{d:U2,size:Ye.iconButton})}),children:[DT.map(he=>a.jsxs("button",{type:"button","data-testid":`dock-add-${he}`,onClick:()=>U(he),className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:dx(he)}),a.jsx("span",{className:"min-w-0 truncate",children:wl(he)})]},he)),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mx-2 my-1 border-t border-gray-100 dark:border-gray-800"}),a.jsxs("button",{type:"button","data-testid":"dock-add-terminal",onClick:()=>{C(!1),eM(h?void 0:p)},className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:[a.jsx("span",{className:"shrink-0 text-gray-500 dark:text-gray-400",children:a.jsx(Oe,{d:U2,size:Ye.iconButton})}),a.jsx("span",{className:"min-w-0 truncate",children:d.terminal.newShell})]}),re.map((he,ne)=>a.jsx("button",{type:"button","data-testid":"dock-add-shell","data-terminal-id":he.id,onClick:()=>{C(!1),nd(he.id,h?void 0:p)},className:"mx-1 flex w-[calc(100%-0.5rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",children:a.jsx("span",{className:"min-w-0 truncate",children:z2(he,he.id,ne+1)})},he.id))]})]}),[be,ye]=y.useState(!c);y.useEffect(()=>{if(be)return;let he=0;const ne=requestAnimationFrame(()=>{he=requestAnimationFrame(()=>ye(!0))});return()=>{cancelAnimationFrame(ne),cancelAnimationFrame(he)}},[]);const Se=L.active||B.active,Me=L.active?L.candidate:B.candidate,ze=new Map;x.forEach(he=>{he.kind==="terminal"&&ze.set(he.terminalId,ze.size+1)});const De=a.jsxs("header",{"data-testid":"dock-header",...P,className:`flex shrink-0 items-center gap-2 border-b border-gray-200 px-2 py-1.5 text-xs dark:border-gray-800 ${h?"":"cursor-grab select-none"}`,children:[a.jsx("div",{ref:E,"data-testid":"dock-tab-strip",...K,className:"no-scrollbar flex min-w-0 items-center gap-1 overflow-x-auto",children:x.map(he=>{const ne=kn(he);if(he.kind==="panel")return a.jsx(P2,{tabId:ne,label:wl(he.panel),title:wl(he.panel),glyph:dx(he.panel,Ye.inlineGlyph),active:ne===g,badge:n?.[he.panel]===!0,closeLabel:d.dock.closeTab,onSelect:()=>qg(ne),onClose:()=>R(he,wl(he.panel))},ne);const oe=f.get(he.terminalId),J=z2(oe,he.terminalId,ze.get(he.terminalId)??1);return a.jsx(P2,{tabId:ne,terminalId:he.terminalId,label:J,title:oe?`${oe.name} — ${oe.cwd}`:J,glyph:a.jsx(Oe,{d:vs.terminal,size:Ye.inlineGlyph}),active:ne===g,badge:!1,closeLabel:d.terminal.killShell,onSelect:()=>qg(ne),onClose:()=>R(he,J)},ne)})}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[N?.kind==="terminal"&&a.jsx(Lm,{label:d.terminal.detach,testId:"dock-detach",onClick:z,children:a.jsx(Oe,{d:YF,size:Ye.rowLead})}),ke,!h&&x.length>0&&a.jsx(Lm,{label:p==="right"?d.dock.moveToBottom:d.dock.moveToRight,testId:"dock-move",onClick:()=>o2(p,w),children:a.jsx(Oe,{d:p==="right"?KF:WF,size:Ye.rowLead})}),a.jsx(Lm,{label:d.dock.hideDock,testId:"dock-close",onClick:()=>_B(e),children:a.jsx(Hl,{size:12})})]})]}),ct=x.length===0?a.jsx(QF,{choose:he=>ho(he,h?void 0:p),chooseTerminal:()=>{tM(h?void 0:p)},terminalSupported:s,horizontal:v}):a.jsx("div",{className:"relative min-h-0 flex-1",children:x.map(he=>{const ne=kn(he),oe=ne===g;return a.jsx("div",{className:oe?"flex h-full min-h-0 flex-col":"hidden",children:he.kind==="panel"?t(he.panel,oe):a.jsx(XF,{id:he.terminalId,active:oe})},ne)})}),bt=a.jsx(ln,{open:T!==null,title:d.dock.killConfirmTitle,onClose:()=>_(null),onConfirm:D,confirmLabel:d.terminal.killShell,children:T!==null&&a.jsx("p",{children:d.dock.killConfirmBody(T.label)})});return v?a.jsxs("div",{ref:le,"data-testid":"dock","data-position":"bottom",style:{height:o&&be?Q:0},inert:!o,className:`relative flex w-full shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${o?"border-t border-gray-200 dark:border-gray-800":""} ${H?"":"transition-[height] duration-200"}`,children:[o&&a.jsx("div",{"data-testid":"dock-resizer",role:"separator","aria-orientation":"horizontal","aria-label":d.dock.resize,title:d.dock.resize,...ie,onDoubleClick:j,className:`absolute -top-[3px] left-0 right-0 z-20 h-1.5 cursor-ns-resize transition-colors duration-150 ${H?"bg-sky-500/60":"bg-transparent hover:bg-sky-500/40"}`}),a.jsxs("div",{style:{height:Q},className:"flex min-h-0 shrink-0 flex-col",children:[De,ct]}),Se&&a.jsx($2,{candidate:Me}),bt]}):a.jsxs(a.Fragment,{children:[o&&a.jsx("div",{"data-testid":"dock-resizer",role:"separator","aria-orientation":"vertical","aria-label":d.dock.resize,title:d.dock.resize,...ie,onDoubleClick:j,className:`w-1.5 shrink-0 cursor-col-resize transition-colors duration-150 ${H?"bg-sky-500/60":"bg-transparent hover:bg-sky-500/40"}`}),a.jsxs("div",{ref:le,"data-testid":"dock","data-position":"right",style:{width:o&&be?X:0},inert:!o,className:`relative flex min-h-0 shrink-0 flex-col overflow-hidden bg-white dark:bg-gray-950 ${o?"border-l border-gray-200 dark:border-gray-800":""} ${H?"":"transition-[width] duration-200"}`,children:[a.jsxs("div",{style:{width:X},className:"flex min-h-0 flex-1 flex-col",children:[De,ct]}),Se&&a.jsx($2,{candidate:Me}),bt]})]})}const ZF=200;function H2(e){const t=e!==null,n=wB(),s=y.useRef(null);t&&(s.current=e);const o=y.useRef({open:t,instant:n,animate:!0}),c=y.useRef(!1),[,u]=y.useState(0);if(t!==o.current.open){const f=n===o.current.instant;o.current={open:t,instant:n,animate:f},c.current=!t&&f&&s.current!==null}else n!==o.current.instant&&(o.current.instant=n);return y.useEffect(()=>{if(t||!c.current)return;const f=window.setTimeout(()=>{c.current=!1,u(p=>p+1)},ZF);return()=>window.clearTimeout(f)},[t]),t?{view:e,open:!0,animateEntrance:o.current.animate}:c.current&&s.current!==null?{view:s.current,open:!1,animateEntrance:!0}:{view:null,open:!1,animateEntrance:!0}}function JF(){return{sessionId:null,taskCount:0,autoOpenedAt:null}}function eq(e,t){const n=t.sessionId!==e.sessionId,s=!n&&t.taskCount<e.taskCount;return(n||t.taskCount!==e.taskCount)&&(e.sessionId=t.sessionId,e.taskCount=t.taskCount,e.autoOpenedAt=s?t.taskCount:null),t.liveSpawn&&e.autoOpenedAt!==e.taskCount?(e.autoOpenedAt=e.taskCount,"autoOpen"):null}const tq=300;function nq(e){const t=mn().user?.userId??null,n=t&&e?aM(t,e):null,s=y.useMemo(()=>n?$i(n):{},[n]),o=y.useRef(s.text??""),c=y.useRef(s.handoffAgentId??null),u=y.useRef(s.switchModelRef??null),f=y.useRef(s.skills??[]),p=y.useRef(null),h=y.useCallback(()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null)},[]),x=y.useCallback(()=>{if(h(),!n)return;const N=o.current,T=c.current,_=u.current,R=f.current;if(!N&&!T&&!_&&R.length===0){Du(n);return}const D={text:N};T&&(D.handoffAgentId=T),_&&(D.switchModelRef=_),R.length>0&&(D.skills=R),Qs(n,D)},[h,n]);y.useEffect(()=>(o.current=s.text??"",c.current=s.handoffAgentId??null,u.current=s.switchModelRef??null,f.current=s.skills??[],()=>{p.current!==null&&(window.clearTimeout(p.current),p.current=null,x())}),[s,x]);const g=y.useCallback(N=>{o.current=N,h(),p.current=window.setTimeout(()=>{p.current=null,x()},tq)},[h,x]),v=y.useCallback(N=>{c.current=N,x()},[x]),w=y.useCallback(N=>{u.current=N,x()},[x]),S=y.useCallback(N=>{f.current=N,x()},[x]),C=y.useCallback(()=>{h(),o.current="",f.current=[],c.current=null,u.current=null,n&&Du(n)},[h,n]);return{initial:s,onTextChange:g,onHandoffTargetChange:v,onPendingModelChange:w,onSkillsChange:S,discard:C}}function Xg(e){const t=e.lastIndexOf("-");if(t<=0)return null;const n=Number.parseInt(e.slice(t+1),10);return!Number.isInteger(n)||n<0?null:{epoch:e.slice(0,t),seq:n}}const Qg=200,rq=100,aq=1e6;function sq(e){const t=e.now??(()=>Date.now()),n=new Set,s=new Map;let o=bl(n),c=!1,u="buffering",f=[],p=null,h=null,x=0,g=!1,v=[],w=new Map,S=0,C=null,N=null;const T={hasMore:!1,loading:!1,error:null};let _=0;const R=()=>{v=[],w=new Map,S=0,C=null,N=null,T.hasMore=!1,T.loading=!1,T.error=null,_=0},D=q=>{R(),q!==void 0&&(C=q.before??null,N=q.before??null,T.hasMore=q.before!==void 0,_=q.earlierTurns)},z=()=>{s.size!==0&&(s.clear(),e.onPendingChange())},E=()=>{let q=!1;for(const[K,H]of[...s])(H.origin===void 0||H.origin.length===0)&&(s.delete(K),q=!0);q&&e.onPendingChange()},L=(q,K)=>{if(ay(q)&&q.payload.type==="approval_decision"&&s.delete(Rl(q.origin,q.payload.tool_call_id))&&e.onPendingChange(),K&&!Nu(q.payload)&&FL(K,q)){UN(o,q);return}Tu(o,q,t())},F=q=>{switch(q.type){case"approval_request":{const K=q.toolCall.payload.tool_call_id,H={toolCall:q.toolCall};if(q.origin&&(H.origin=q.origin),s.set(Rl(q.origin,K),H),!_L(o,q.origin,K)){const $={...q.toolCall};q.origin&&q.origin.length>0?$.origin=[...q.origin]:delete $.origin,Tu(o,$,t()),e.onModelChange()}e.onPendingChange();return}case"task_state":{p=q.state,e.onTaskState(q.state),e.onQueuedFollowUps?.(q.queued??0),e.onPendingSteering?.(q.pendingSteering??[]),e.onPendingFollowUps?.(q.pendingFollowUps??[]),e.onSubagents?.(q.subagents??[]),q.state==="idle"&&(EL(o),E(),e.onModelChange());return}case"resync_required":{V();return}case"credentials_updated":return;case"hello":return}},V=async()=>{x+=1,u="buffering",f=[],z(),await B(x,bl(n),{page:{kind:"tail",limit:Qg},splice:v.length>0})},P=(q,K)=>{const H=Xg(K.cursor);if(!H)return q;const $=h===null?null:Xg(h);if($!==null&&$.epoch!==H.epoch)return q;const X=[],le=[];for(const I of q){const A=I.id===null?null:Xg(I.id);A!==null&&A.epoch===H.epoch&&A.seq<=H.seq?(I.kind!=="omni"||!Nu(I.msg.payload))&&X.push(I):le.push(I)}const ie=K.fragments.map(I=>({kind:"omni",msg:I,id:null,seeded:!0}));return[...X,...ie,...le]},B=async(q,K,H={})=>{try{let $=await e.loadMessages(H.page);if(c||q!==x)return;if(H.splice===!0){const j=$.page?.before??null;if(!($.page!==void 0&&j!==null&&j===N))if($.page!==void 0&&j===null)D($.page);else{if($=await e.loadMessages(),c||q!==x)return;D(void 0)}}else H.page!==void 0?D($.page):D(void 0);const{messages:X,live:le,serverNowMs:ie}=$;K&&(o=K);const I=o;$.page!==void 0&&Nw(I.stats,$.page.prior),Mw(I,X,t(),ie??null);const A=HL(X,100),Q=le!==void 0?P(f,le):f;f=[];for(let j=0;j<Q.length;j+=1){const U=Q[j];if(U.kind==="omni"?L(U.msg,A):F(U.ev),c)return;if(q!==x){f.push(...Q.slice(j+1).filter(ee=>ee.kind!=="omni"||!ee.seeded));return}}u="live",p==="idle"&&j0(I),g=!1,e.onError(null),e.onLoading(!1),e.onModelChange()}catch($){if(c||q!==x)return;g=!0,e.onLoading(!1),e.onError($ instanceof Error?$.message:String($))}};return{get model(){return o},get prefixItems(){return v},get prefixSubagents(){return w},get outlineOffset(){return _},get older(){return T},get pendingApprovals(){return s},load:()=>(x+=1,B(x,void 0,{page:{kind:"tail",limit:Qg}})),retry:async()=>{c||!g||(e.onError(null),e.onLoading(!0),x+=1,await B(x,bl(n),{page:{kind:"tail",limit:Qg}}))},loadOlder:async()=>{if(c||u!=="live"||g||T.loading||!T.hasMore||C===null)return;const q=x;T.loading=!0,T.error=null,e.onModelChange();try{const K=await e.loadMessages({kind:"before",cursor:C,limit:rq});if(c||q!==x)return;if(K.page===void 0)throw new Error("windowed history not supported");S+=1;const H=bl(n);H.nextItemId=-S*aq,Nw(H.stats,K.page.prior),Mw(H,K.messages,t(),null),j0(H),v=[...H.items,...v];const $=new Map(H.subagents);for(const[X,le]of w)$.set(X,le);w=$,C=K.page.before??null,T.hasMore=K.page.before!==void 0,_=K.page.earlierTurns}catch(K){if(c||q!==x)return;T.error=K instanceof Error?K.message:String(K)}finally{!c&&q===x&&(T.loading=!1,e.onModelChange())}},handleOmni:(q,K=null)=>{if(!c){if(K!==null&&(h=K),u==="buffering"){f.push({kind:"omni",msg:q,id:K});return}L(q,null),e.onModelChange()}},handleServer:(q,K=null)=>{if(!c){if(K!==null&&(h=K),q.type==="session_title"){e.onSessionTitle?.(q.sessionId,q.title);return}if(q.type==="session_created"){e.onSessionCreated?.(q.sessionId);return}if(q.type==="goal_started"||q.type==="goal_round"||q.type==="goal_finished"){e.onGoalEvent?.(q);return}if(u==="buffering"){q.type==="task_state"&&(p=q.state,e.onTaskState(q.state),e.onQueuedFollowUps?.(q.queued??0),e.onPendingSteering?.(q.pendingSteering??[]),e.onPendingFollowUps?.(q.pendingFollowUps??[])),f.push({kind:"server",ev:q,id:K});return}F(q)}},markLocalDecision:q=>{AL(o,q)},resolveApproval:q=>{s.delete(q)&&e.onPendingChange()},dispose:()=>{c=!0}}}const iq=120,oq=new Map,lq=[],cq=new Map,uq={hasMore:!1,loading:!1,error:null};function dq(e,t,n,s){const[o,c]=y.useState(0),[u,f]=y.useState(!0),[p,h]=y.useState(t),[x,g]=y.useState(0),[v,w]=y.useState([]),[S,C]=y.useState([]),[N,T]=y.useState([]),[_,R]=y.useState(null),[D,z]=y.useState(0),[E,L]=y.useState(null),F=y.useCallback(A=>{L(Q=>A.type==="goal_started"?{objective:A.objective,status:"active",budget:A.budget,used:0,rounds:0}:A.type==="goal_round"?{objective:Q?.objective??"",status:"active",budget:A.budget,used:A.used,rounds:A.round}:{objective:Q?.objective??"",status:A.outcome,budget:Q?.budget??-1,used:A.used,rounds:A.rounds})},[]),V=y.useRef(n);V.current=n;const P=y.useRef(s);P.current=s;const B=y.useRef(null),Y=y.useRef(null);Y.current===null&&(Y.current=bl());const q=y.useRef(null),K=y.useRef(null),H=y.useRef(0),$=y.useCallback(()=>{if(q.current!==null||K.current!==null)return;const A=()=>{H.current=Date.now(),c(j=>j+1)},Q=H.current+iq-Date.now();if(Q>0){K.current=window.setTimeout(()=>{K.current=null,A()},Q);return}q.current=requestAnimationFrame(()=>{q.current=null,A()})},[]);y.useEffect(()=>{if(!e){B.current?.dispose(),B.current=null,h("idle"),g(0),w([]),C([]),T([]),f(!1),R(null),L(null),z(ee=>ee+1),c(ee=>ee+1);return}c(ee=>ee+1),f(!0),R(null),h(t),L(null),g(0),w([]),C([]),T([]),z(ee=>ee+1);let A=!1;const Q=()=>{nA(e).then(ee=>{A||!ee.goal||ee.goal.status!=="active"||L(re=>re??ee.goal)}).catch(()=>{})},j=sq({loadMessages:ee=>sC(e,ee),onTaskState:h,onQueuedFollowUps:g,onPendingSteering:w,onPendingFollowUps:C,onSubagents:T,onLoading:f,onError:R,onModelChange:$,onPendingChange:()=>z(ee=>ee+1),onSessionTitle:(ee,re)=>V.current?.(ee,re),onSessionCreated:()=>P.current?.(),onGoalEvent:F});B.current=j;const U=_R(e,{onOmniMessage:j.handleOmni,onServerEvent:j.handleServer,onOpen:Q,onError:ee=>{ee&&qm().catch(()=>{})}});return j.load(),()=>{A=!0,j.dispose(),U.close(),q.current!==null&&(cancelAnimationFrame(q.current),q.current=null),K.current!==null&&(window.clearTimeout(K.current),K.current=null)}},[e]);const X=y.useCallback(A=>{B.current?.markLocalDecision(A)},[]),le=y.useCallback(A=>{B.current?.resolveApproval(A)},[]),ie=y.useCallback(()=>{B.current?.retry()},[]),I=y.useCallback(()=>{B.current?.loadOlder()},[]);return{model:B.current?.model??Y.current,prefixItems:B.current?.prefixItems??lq,prefixSubagents:B.current?.prefixSubagents??cq,outlineOffset:B.current?.outlineOffset??0,older:B.current?.older??uq,loadOlder:I,version:o,loading:u,taskState:p,queuedFollowUps:x,pendingSteering:v,pendingFollowUps:S,subagents:N,pendingApprovals:B.current?.pendingApprovals??oq,markLocalDecision:X,resolveApproval:le,error:_,retry:ie,goal:E}}const mq="M4 5h16v14H4zM4 14h16",fq="M4 5h16v14H4zM14 5v14",pq=e=>`relative flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors duration-150 ${e?"bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200":"text-gray-500 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"}`;function hq({agentsPending:e}){y.useSyncExternalStore(Zf,$y);const t=vl("agents")??"right",n=[{position:"bottom",label:d.dock.bottomDock,icon:mq},{position:"right",label:d.dock.rightDock,icon:fq}];return a.jsx("div",{className:"flex shrink-0 items-center gap-1","data-testid":"panels-toolbar",children:n.map(({position:s,label:o,icon:c})=>a.jsxs("button",{type:"button","aria-expanded":Ba(s),onClick:()=>AB(s),title:o,"aria-label":o,"data-testid":`dock-toggle-${s}`,className:pq(Ba(s)),children:[a.jsx(Oe,{d:c,size:Ye.iconButton}),e&&t===s&&a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 rounded-full ${Fl.attention}`})]},s))})}const gq=15e3;function Zg({icon:e,value:t,label:n}){return a.jsxs("span",{title:n,className:`flex shrink-0 items-center ${Ro.tight} font-mono text-xs text-gray-500 dark:text-gray-400`,children:[a.jsx(Oe,{d:e}),t]})}function xq({sessionId:e}){return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.sessionIdLabel}),a.jsxs("div",{className:"flex items-start gap-1.5",children:[a.jsx("span",{className:"min-w-0 flex-1 break-all font-mono text-xs leading-5",children:e}),a.jsx(Wu,{text:e,label:d.chat.copySessionId,className:PN})]})]})}function yq({stats:e,taskOpen:t,taskStartLocalMs:n}){const[s,o]=y.useState(()=>Date.now());return y.useEffect(()=>{if(!t)return;o(Date.now());const c=setInterval(()=>o(Date.now()),1e3);return()=>clearInterval(c)},[t]),t?a.jsx(a.Fragment,{children:ZC(vL(e,t,n,s))}):a.jsx(a.Fragment,{children:Pn(e.sessionElapsedMs)})}function bq(e,t){const n=e.stats;return{tokensText:It(n.sessionTotal+n.subagentTotal),costText:t.costText,costUncosted:t.costUncosted,elapsedNode:a.jsx(yq,{stats:n,taskOpen:e.taskOpen,taskStartLocalMs:e.taskStartLocalMs})}}const ya="new",vq=e=>e!==null&&e.startsWith("draft-")?e:null,F2=100;function kq(){const e=yr(),t=$r(),n=MC(),{user:s}=mn(),{currency:o}=as(),{currentProject:c,currentAgent:u,setCurrentAgentId:f,reloadAgents:p,agents:h}=en(),x=c?.projectId??null,g=u?.agentId??null,{sessions:v,loading:w,reload:S,add:C,isDeleted:N,replace:T,setStatus:_,setTitle:R}=Ii(),D=y.useRef(dM()),z=y.useRef(null),[,E]=y.useState(0),[L,F]=y.useState(!1),[V,P]=y.useState(!1),[B,Y]=y.useState(!1),[q,K]=y.useState(null),[H,$]=y.useState([]),[X,le]=y.useState(null),[ie,I]=y.useState(null),[A,Q]=y.useState(null),j=n.sessionId??null;y.useSyncExternalStore(Zf,$y),y.useSyncExternalStore(ZT,d2);const[U,ee]=y.useState(null),[re,ke]=y.useState(null),[be,ye]=y.useState(null),[Se,Me]=y.useState(null);y.useEffect(()=>{ee(null),ke(null),ye(null),Me(null)},[j]);const ze=vl("workspace")!==null,De=vl("memory")!==null,ct=vl("agents")!==null;y.useEffect(()=>{ze||ee(null)},[ze]),y.useEffect(()=>{De||ke(null)},[De]),y.useEffect(()=>{ct||(ye(null),Me(null))},[ct]);const bt=vq(j),he=j===ya||bt!==null,ne=he?null:v.find(de=>de.sessionId===j)??null;y.useEffect(()=>{he||JT(ne?.workspace??null)},[he,ne?.workspace]);const oe=ne?{provider:ne.provider,modelId:ne.modelId}:null;Li(ne?ne.title??d.chat.defaultSessionTitle:d.nav.chat);const J=dq(ne?.sessionId??null,ne?.status??"idle",R,()=>{S()}),{initial:ht,onTextChange:ve,onHandoffTargetChange:Xe,onPendingModelChange:Ge,onSkillsChange:He,discard:Pe}=nq(ne?.sessionId??null),W=y.useMemo(()=>J.prefixItems.length>0?[...J.prefixItems,...J.model.items]:J.model.items,[J.version,j]),me=y.useMemo(()=>bz(W),[J.version,j]),Ue=y.useMemo(()=>iB(W),[J.version,j]),pe=y.useMemo(()=>J.prefixItems.length>0||J.prefixSubagents.size>0?{...J.model,items:[...W],subagents:new Map([...J.prefixSubagents,...J.model.subagents])}:J.model,[J.version,j]),$e=y.useMemo(()=>jL(W.flatMap(de=>de.kind==="task_stats"&&de.memoryChanges!==void 0?[de.memoryChanges]:[])),[J.version,j]),nt=y.useRef($e);SL(nt.current,$e)||(nt.current=$e);const gt=nt.current,Ke=DH(x,ne?.agentId??null,vl("memory")!==null||gt.length>0,gt),dt=y.useMemo(()=>UU(Ke.scopes,gt)??void 0,[Ke.scopes,gt]),pt=y.useRef(null),wt=fB(pt,J.version),st=ne?.sessionId??null,Bt=ne?.agentId??null,Sn=ne?.thinkingLevel??"";y.useEffect(()=>{st&&Bt&&f(Bt)},[st,Bt,f]);const Dn=y.useRef(JF()),Vt=aP(J.model.items),ar=J.taskState!=="idle"&&uP(J.model);y.useEffect(()=>{eq(Dn.current,{sessionId:st,taskCount:Vt,liveSpawn:ar})==="autoOpen"&&!TB("agents")&&ho("agents")},[st,Vt,ar]);const[zn,Xt]=y.useState([]);y.useEffect(()=>{if(Xt(Re=>Re.length>0?[]:Re),!x||!Bt)return;let de=!1;return Bu(x,Bt).then(Re=>{de||Xt(Re.skills)}).catch(()=>{}),()=>{de=!0}},[x,Bt]);const[Cn,lr]=y.useState("");y.useEffect(()=>{if(lr(""),!x||!Bt)return;let de=!1;return Ao(x,Bt).then(Re=>{de||lr(Re.config.model?.thinkingLevel??"")}).catch(()=>{}),()=>{de=!0}},[x,Bt]);const Mt=x&&j?jH(x,j):null,[Pr,Bn]=y.useState(null);y.useEffect(()=>{if(he||!x||!j||!Mt||w||v.some(Re=>Re.sessionId===j))return;if(N(j)){Bn(Mt);return}let de=!1;return d0(j).then(Re=>{if(de)return;const Qe=SH(Re.session,x);Qe?C(Qe):Bn(Mt)},()=>{de||Bn(Mt)}),()=>{de=!0}},[he,x,j,Mt,w,v,C,N]),y.useEffect(()=>{if(w||he||j&&v.some(Re=>Re.sessionId===j)||j&&Pr!==Mt)return;const de=PC(v);e(de?`/chat/${de.sessionId}`:`/chat/${ya}`,{replace:!0})},[w,he,j,Mt,Pr,v,e]),y.useEffect(()=>{st!==null&&_(st,J.taskState)},[J.taskState,st,_]);const Nr=y.useRef({id:st,state:"idle"}),[Tr,Te]=y.useState(0);y.useEffect(()=>{const de=Nr.current,Re=de.id===st;Nr.current={id:st,state:Re?J.taskState:"idle"},!(!Re||st===null)&&de.state!=="idle"&&J.taskState==="idle"&&(S(),p(),Te(Qe=>Qe+1))},[J.taskState,st,S,p]);const Ie=ne?.lastActiveAt??null;y.useEffect(()=>{st===null||Ie===null||J.taskState==="idle"&&Gx(x,st,Ie)},[x,st,Ie,J.taskState]);const ut=y.useRef(new Map);y.useEffect(()=>{z.current=null,Q(null),ut.current=new Map,$([]),I(null)},[j]);const St=y.useCallback(async de=>{const Re=ne?.sessionId??null,Qe=ut.current,mt=Re===null?[]:de.filter(Pt=>!Qe.has(Pt));if(Re!==null&&mt.length>0)for(let Pt=0;Pt<mt.length;Pt+=F2){const Wt=mt.slice(Pt,Pt+F2),Ka=jA(Re,Wt).then(_r=>new Set(_r.existing)).catch(()=>null);for(const _r of Wt){const Rr=Ka.then(Ir=>Ir?.has(_r)??!1);Qe.set(_r,Rr),Rr.then(Ir=>{Qe.get(_r)===Rr&&(Ir?Qe.set(_r,!0):Qe.delete(_r))})}}const Et=new Set;return await Promise.all(de.map(async Pt=>{const Wt=Qe.get(Pt);(Wt===!0||Wt instanceof Promise&&await Wt)&&Et.add(Pt)})),Et},[ne?.sessionId]);y.useEffect(()=>{if(!x||!ne||z.current===ne.sessionId&&J.taskState!=="idle"&&!V)return;let de=!1;return iC(x,{groupBy:"session",agentId:ne.agentId}).then(Re=>{if(de)return;z.current=ne.sessionId;const Qe=Re.groups.find(mt=>mt.key===ne.sessionId);CH(D.current,ne.sessionId,Qe??null),I(Qe?{cacheRead:Qe.cacheRead,cacheWrite:Qe.cacheWrite,output:Qe.output}:null),E(mt=>mt+1)}).catch(()=>{}),()=>{de=!0}},[x,ne,J.taskState,V]);const gn=y.useRef(st);y.useEffect(()=>{gn.current=st},[st]);const Nn=H.filter(de=>de.running).length,Hn=J.taskState!=="idle"||Nn>0||V&&H.length>0;y.useEffect(()=>{if(!st)return;let de=!1;const Re=()=>{q1(st).then(mt=>{de||$(mt.processes)}).catch(()=>{})};if(Re(),!Hn)return()=>{de=!0};const Qe=window.setInterval(Re,gq);return()=>{de=!0,window.clearInterval(Qe)}},[st,J.taskState,Hn]);const Dt=y.useCallback(async(de,Re,Qe)=>{if(!ne||X!==null)return;const mt=ne.sessionId;le(de);try{await Re(mt,de)}catch(Et){Et instanceof xr&&Qe.includes(Et.status)||Be(Ae(Et))}finally{le(null),q1(mt).then(Et=>{gn.current===mt&&$(Et.processes)}).catch(()=>{})}},[ne,X]),Rn=y.useCallback(de=>Dt(de,iA,[404]),[Dt]),zr=y.useCallback(de=>Dt(de,oA,[404,409]),[Dt]);y.useEffect(()=>{if(!x)return;let de=!1;return K(null),(async()=>{try{const Re=await Ml(x);if(de)return;K(Re);const{prefs:Qe}=await Sx();if(de||Qe.credentialGuideSeen)return;const mt=Re.models.find(Pt=>zt(Pt,Re.defaultModel));(!Re.defaultModel||!mt||!Ol(mt))&&F(!0),Nf({credentialGuideSeen:!0}).catch(()=>{})}catch{}})(),()=>{de=!0}},[x]),y.useEffect(()=>{if(!x)return;let de=!1;const Re=Qe=>{const mt=cM(Qe,x);!mt||mt.defaultModel===void 0||(K(null),Ml(x).then(Et=>{de||K(Et)}).catch(()=>{}))};return window.addEventListener($u,Re),()=>{de=!0,window.removeEventListener($u,Re)}},[x]);const cr=y.useCallback(async(de,Re)=>{Re!==de&&(await S(),HT(Re),e(`/chat/${Re}`,{replace:!0}))},[S,e]),Js=y.useCallback(async(de,Re)=>{if(!ne)return!1;try{const Qe=await su(ne.sessionId,{input:de,...Re?{goal:Re}:{},...Sn?{thinkingLevel:Sn}:{}});return Pe(),await cr(ne.sessionId,Qe.sessionId),!0}catch(Qe){return Be(Ae(Qe,{modelId:ne.modelId})),!1}},[ne,Sn,Pe,cr]),Mr=y.useCallback(async(de,Re)=>{if(!x||!ne)return!1;const Qe=await d0(ne.sessionId).then(Pt=>Pt.session.tracePath).catch(()=>{}),mt={type:"text",text:JU({sessionId:ne.sessionId,...ne.title!==void 0?{sessionTitle:ne.title}:{},...Qe!==void 0?{tracePath:Qe}:{},workspace:ne.workspace,prevProvider:ne.provider,prevModelId:ne.modelId})};let Et=null;try{const Pt=await u0(x,ne.agentId,{provider:de.provider,modelId:de.modelId,workspace:ne.workspace,approvalMode:ne.approvalMode});Et=Pt.session.sessionId;const Wt=await su(Et,{input:[mt,...Re]});return C(Pt.session),Pe(),e(`/chat/${Wt.sessionId}`),!0}catch(Pt){return Et&&nf(Et).catch(()=>{}),Be(Ae(Pt,{modelId:de.modelId})),!1}},[x,ne,C,Pe,e]),ta=y.useCallback(async(de,Re)=>{if(!x||!u||!ne)return!1;const Qe={type:"text",text:ZU({agentId:u.agentId,...u.name!==void 0?{agentName:u.name}:{},sessionId:ne.sessionId,workspace:ne.workspace,...ne.title!==void 0?{sessionTitle:ne.title}:{}})};let mt=null;try{const Et=await u0(x,de.agentId,{approvalMode:ne.approvalMode});mt=Et.session.sessionId;const Pt=await su(mt,{input:[Qe,...Re]});return C(Et.session),Pe(),e(`/chat/${Pt.sessionId}`),!0}catch(Et){return mt&&nf(mt).catch(()=>{}),Be(Ae(Et,q?.defaultModel?{modelId:q.defaultModel.modelId}:{})),!1}},[x,u,ne,C,Pe,e,q]),Br=y.useCallback(async()=>{ne&&await aA(ne.sessionId).catch(()=>{})},[ne]),is=y.useCallback(async de=>{if(!ne)return!1;try{const Re=await su(ne.sessionId,{input:de,queueIfBusy:!0,...Sn?{thinkingLevel:Sn}:{}});return Pe(),await cr(ne.sessionId,Re.sessionId),!0}catch(Re){return Be(Ae(Re,{modelId:ne.modelId})),!1}},[ne,Sn,Pe,cr]),Hr=y.useCallback(async(de,Re=[],Qe=[])=>{if(!ne)return"failed";try{return await lA(ne.sessionId,{text:de,...Re.length>0?{images:Re}:{},...Qe.length>0?{files:Qe}:{}}),Pe(),"queued"}catch(mt){return mt instanceof xr&&mt.status===409?"not_running":(Be(Ae(mt,{modelId:ne.modelId})),"failed")}},[ne,Pe]),fn=y.useCallback(de=>{ne&&tf(ne.sessionId,{thinkingLevel:de}).then(Re=>T(Re.session)).catch(Re=>{Be(Ae(Re))})},[ne,T]),Fr=y.useCallback(async de=>{if(!ne)return null;try{return await dA(ne.sessionId,de)}catch(Re){return Be(Ae(Re)),null}},[ne]),qr=y.useCallback(async de=>{if(!ne)return null;try{const Re=await mA(ne.sessionId,de);return Re.thinkingLevel&&fn(Re.thinkingLevel),Re}catch(Re){return Be(Ae(Re)),null}},[ne,fn]),pn=y.useCallback(async(de,Re,Qe)=>{if(!ne)return;J.markLocalDecision(de);const mt=Rl(Qe,de);try{await rA(ne.sessionId,de,{decision:Re}),J.resolveApproval(mt)}catch(Et){Et instanceof xr&&Et.status===404&&J.resolveApproval(mt)}},[ne,J]),na=y.useCallback(de=>{!ne||B||(Y(!0),tf(ne.sessionId,{approvalMode:de}).then(Re=>T(Re.session)).catch(Re=>{Be(Ae(Re))}).finally(()=>Y(!1)))},[ne,B,T]),Jn=y.useCallback(async()=>{if(!ne)return!1;try{const de=await fA(ne.sessionId);return await cr(ne.sessionId,de.sessionId),!0}catch(de){return Be(Ae(de,{modelId:ne.modelId})),!1}},[ne,cr]),Er=y.useCallback(async()=>{await Jn()},[Jn]),ur=y.useCallback(de=>{pz(J.model.items,Hg(Sn,Cn),de)?Q({phase:"ask",level:de}):fn(de)},[J.model,Sn,Cn,fn]),os=y.useCallback(()=>{if(A===null||J.taskState!=="idle")return;const de={phase:"compacting",level:A.level,baseline:jT(J.model.items)};Q(de),wr(d.chat.thinkingSwitchCompacting),Jn().then(Re=>{Re||Q(Qe=>Qe===de?{phase:"settle",level:de.level}:Qe)})},[A,J.taskState,J.model,Jn]);y.useEffect(()=>{if(A===null)return;const de=gz(A,J.model.items);de.act!=="wait"&&(Q(null),fn(de.level),de.notice==="compacted"?yt(d.chat.thinkingSwitchApplied(W0(d.chat.thinkingLevelNames,de.level)??de.level)):de.notice==="compaction-failed"&&Be(d.chat.thinkingSwitchCompactFailed))},[J.version,J.model,A,fn]);const ls=y.useCallback(()=>{s&&x&&Yl(s.userId,x),e(`/chat/${ya}`)},[s,x,e]),ra=y.useCallback(async de=>{if(ne)try{let Re=de.position;if(Re===void 0){const mt=await sC(ne.sessionId),Et=bl();for(const Wt of mt.messages)Tu(Et,Wt);j0(Et);const Pt=[...Et.items].reverse().find(Wt=>Wt.kind==="task_stats"&&Wt.assistantText===de.assistantText&&Wt.atMs===de.atMs&&Wt.forkPosition!==void 0);Re=Pt?.kind==="task_stats"?Pt.forkPosition:void 0}if(Re===void 0){Be(d.chat.forkSessionFailed);return}const Qe=await WE(ne.sessionId,{position:Re});C(Qe.session),e(`/chat/${Qe.session.sessionId}`)}catch(Re){Be(Ae(Re,{modelId:ne.modelId}))}},[ne,C,e]),cs=q?.models.find(de=>zt(de,oe))?.pricing,ka={pendingApprovals:J.pendingApprovals,onApprove:pn,origin:[],taskRunning:J.taskState!=="idle",taskCost:de=>Cw(de.tokensByBucket,cs),onRetryNow:()=>{ne&&sA(ne.sessionId).catch(()=>{})},onGiveUp:()=>{Br()},onOpenFile:de=>{ho("workspace"),ee({path:de})},onOpenSubagent:(de,Re)=>{ho("agents"),Me({anchorSessionId:Re[0]??de}),ye({sessionId:de,origin:[...Re,de]})},onOpenMemory:()=>{ho("memory"),ke({target:null})},onLocateMemoryChange:de=>{ho("memory"),ke({target:{scope:de.scope,...de.scopeKey!==void 0?{scopeKey:de.scopeKey}:{},file:de.file}})},...dt!==void 0?{deletedMemoryKeys:dt}:{},workspace:ne?.workspace??null,statFiles:St,onFork:ra},Ar=[...J.pendingApprovals.keys()].some(de=>!de.startsWith(" ")),er=NB(),Tn=H2(er.find(de=>de.position==="right")??null),Vr=H2(er.find(de=>de.position==="bottom")??null),wa=d2(),Mn=(de,Re)=>{if(!ne)return a.jsx(Fa,{title:wl(de),description:d.dock.draftEmpty});switch(de){case"agents":return a.jsx(UH,{session:ne,model:pe,version:J.version,taskRunning:J.taskState!=="idle",ctx:ka,focusRequest:be,taskScope:Se,subagents:J.subagents,models:q?.models??[],approvalMode:ne.approvalMode,onChangeApprovalMode:na,modeSaving:B,parentThinkingLevel:Hg(Sn,Cn)},ne.sessionId);case"workspace":return a.jsx(OH,{session:ne,openRequest:U,active:Re,reloadSignal:Tr});case"memory":return a.jsx(HU,{session:ne,changes:gt,scopes:Ke.scopes,listingError:Ke.error,request:re,active:Re,onOpenSettings:()=>e(`/agents/${ne.agentId}?tab=memory`)},ne.sessionId);case"trace":return a.jsx(pF,{session:ne,active:Re},ne.sessionId);case"messaging":return a.jsx(TF,{sessionId:ne.sessionId,active:Re},ne.sessionId)}};if(!x||!g)return a.jsx("div",{className:"p-6",children:a.jsx(on,{className:"h-6 w-64"})});const Gr=J.model.taskOpen?Cw({cacheRead:J.model.stats.taskCacheRead,cacheWrite:J.model.stats.taskCacheWrite,output:J.model.stats.taskOutput},cs):null,En=bq(J.model,NH(D.current,{sessionId:ne?.sessionId??null,taskCount:rP(J.model.items),taskOpen:J.model.taskOpen,loading:J.loading,liveUsd:Gr,currency:o})),us=ie?ie.cacheRead+ie.cacheWrite:0,hn=ie&&us>0?`${Math.round(100*ie.cacheRead/us)}%`:null,Sa=h.find(de=>de.agentId===ne?.agentId),Ts=Sa&&Sa.name!==void 0?_n(Sa):null,Ga=q?.models.find(de=>zt(de,oe)),Ct=Ga?.contextWindow,ds=Ga?.vision!==!1,ja=ne!==null&&!J.loading&&!J.error&&J.model.items.length===0,br=ne&&a.jsx(Iy,{status:J.taskState,onSend:Js,onSteer:Hr,steeringDeliveredCount:J.model.items.filter(de=>de.kind==="user_steering").length,pendingSteering:J.pendingSteering,onRecallSteering:Fr,onQueueFollowUp:is,queuedFollowUps:J.queuedFollowUps,pendingFollowUps:J.pendingFollowUps,onRecallFollowUp:qr,onStop:Br,onCompact:Er,modelRef:oe,...q!==null?{models:q.models}:{},...q?.defaultModel!==void 0?{defaultModel:q.defaultModel}:{},onSwitchModel:Mr,turnThinkingLevel:Hg(Sn,Cn),onChangeTurnThinkingLevel:ur,...Ct!==void 0?{contextWindow:Ct}:{},contextNow:J.model.stats.contextNow,contextStale:J.model.stats.contextStale,sessionId:ne.sessionId,vision:ds,approvalMode:ne.approvalMode,onChangeApprovalMode:na,modeSaving:B,autoFocus:!0,agents:h,currentAgentId:ne.agentId,skills:zn,...ht.skills&&ht.skills.length>0?{initialSkills:ht.skills}:{},onSkillsChange:He,onHandoff:ta,initialText:ht.text??"",onTextChange:ve,history:me,...ht.handoffAgentId?{initialHandoffTargetId:ht.handoffAgentId}:{},onHandoffTargetChange:Xe,...ht.switchModelRef?{initialPendingModelRef:ht.switchModelRef}:{},onPendingModelChange:Ge}),Ca=ne===null?null:rN(J.taskState,ne.hasTrace,!1);return a.jsxs("div",{"data-dock-host":!0,className:"flex h-full flex-col bg-white dark:bg-gray-950",children:[ne&&a.jsxs("div",{className:"flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800",children:[a.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[a.jsx("h1",{className:"flex min-w-0 text-[15px] font-semibold",children:a.jsx(Of,{text:ne.title??d.chat.defaultSessionTitle})}),Ca==="running"&&a.jsxs("span",{title:S0(Ca),className:"flex shrink-0 items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400",children:[a.jsx(vN,{activity:Ca}),a.jsx("span",{className:"hidden sm:inline",children:S0(Ca)})]})]}),a.jsx(hq,{agentsPending:Ar}),!wt.shown&&a.jsx(hB,{entries:Ue,turnOffset:J.outlineOffset,scrollRef:pt,running:J.taskState!=="idle"}),a.jsx(Qn,{open:V,setOpen:P,menuClass:"right-0 top-full mt-1 w-96 max-w-[calc(100vw-1.5rem)] origin-top-right",button:a.jsxs("button",{type:"button",title:d.chat.infoPanel,"aria-label":d.chat.infoPanel,"aria-expanded":V,onClick:()=>P(!V),className:`flex h-7 shrink-0 items-center rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${V?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsxs("span",{className:"hidden items-center gap-3 px-2 sm:flex",children:[a.jsx(Zg,{icon:Xn.tokens,value:En.tokensText,label:`${d.chat.statTokens}(Token)`}),En.costText!=null&&a.jsx(Zg,{icon:Xn.cost,value:`${En.costText}${En.costUncosted?" *":""}`,label:`${d.common.cost}(${o})${En.costUncosted?` · ${d.usage.uncostedNote}`:""}`}),a.jsx(Zg,{icon:Xn.elapsed,value:En.elapsedNode,label:d.chat.statElapsed}),Nn>0&&a.jsxs("span",{title:d.chat.runningServices(Nn),className:`flex shrink-0 items-center ${Ro.tight} font-mono text-xs ${sn.busy}`,children:[a.jsx(Oe,{d:Xn.services}),Nn]})]}),a.jsx("span",{className:"flex h-7 w-7 items-center justify-center text-gray-500 sm:hidden dark:text-gray-400",children:a.jsx(Oe,{d:RI,size:Ye.navRow})})]}),children:a.jsxs("div",{className:"space-y-3 px-3.5 py-2.5 text-sm",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.agent}),a.jsxs("p",{className:"truncate text-xs",children:[a.jsx("span",{className:"font-mono",children:ne.agentId}),Ts!==null&&a.jsx("span",{className:"ml-1.5 text-gray-400 dark:text-gray-500",children:Ts})]})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.model}),a.jsxs("p",{className:"truncate text-xs",children:[a.jsx("span",{className:"font-mono",children:ne.modelId}),a.jsx("span",{className:"ml-1.5 text-gray-400 dark:text-gray-500",children:Ws(ne.provider)?.label??ne.provider})]})]}),a.jsx(xq,{sessionId:ne.sessionId}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.workspace}),a.jsx("p",{className:"break-all font-mono text-xs leading-5",children:ne.workspace})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.common.created}),a.jsx("p",{className:"font-mono text-xs",children:Jr(ne.createdAt)})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.sessionStats}),a.jsxs("ul",{className:"list-inside list-disc space-y-0.5 font-mono text-xs",children:[a.jsxs("li",{children:[d.chat.statTotalTokens," ",En.tokensText,hn!==null&&`${d.chat.statParenOpen}${d.chat.statCacheHit(hn)}${d.chat.statParenClose}`]}),En.costText!=null&&a.jsxs("li",{children:[d.common.cost," ",En.costText,En.costUncosted?" *":""]}),a.jsxs("li",{children:[d.chat.statElapsed," ",En.elapsedNode]})]})]}),H.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:d.chat.processList}),a.jsx("ul",{className:"mt-1 space-y-1.5",children:H.map(de=>a.jsxs("li",{className:"flex items-center gap-2",children:[a.jsx("span",{"aria-hidden":!0,className:`h-1.5 w-1.5 shrink-0 rounded-full ${de.running?`animate-pulse ${Fl.busy}`:"bg-gray-300 dark:bg-gray-600"}`}),a.jsxs("span",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate font-mono text-xs",title:de.cmd,children:de.cmd}),a.jsxs("span",{className:"block truncate text-[11px] text-gray-400 dark:text-gray-500",children:[Jr(de.startedAt),de.pid!==null&&` · pid ${de.pid}`,de.running&&de.serviceUrl!==void 0&&a.jsxs(a.Fragment,{children:[" · ",a.jsx("a",{href:de.serviceUrl,target:"_blank",rel:"noopener noreferrer",title:de.serviceUrl,className:"text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-700 hover:decoration-gray-500 dark:text-gray-400 dark:decoration-gray-600 dark:hover:text-gray-200",children:de.serviceUrl.replace(/^https?:\/\//i,"")})]})]})]}),de.running?a.jsx("button",{type:"button",disabled:X!==null,onClick:()=>{Rn(de.processId)},className:"shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400",children:X===de.processId?d.common.loading:d.chat.processStop}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"shrink-0 text-[11px] text-gray-400 dark:text-gray-500",children:d.chat.processExited}),a.jsx("button",{type:"button",title:d.chat.processRemoveHint,disabled:X!==null,onClick:()=>{zr(de.processId)},className:"shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400",children:X===de.processId?d.common.loading:d.chat.processRemove})]})]},de.processId))})]})]})})]}),a.jsxs("div",{"data-dock-row":!0,className:"flex min-h-0 flex-1",children:[a.jsx(Mz,{className:"relative flex min-h-0 min-w-0 flex-1 flex-col",children:he?a.jsx(vH,{projectId:x,models:q,...bt!==null?{draftId:bt}:{}},`draft:${x}:${bt??t.key}`):a.jsx("div",{className:"anim-fade flex min-h-0 flex-1 flex-col",children:ne?J.error?a.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6",children:[a.jsxs("p",{className:"text-sm text-red-600 dark:text-red-400",children:[d.chat.historyLoadFailed,":",J.error]}),a.jsx(ge,{onClick:J.retry,children:d.common.retry})]}):J.loading?a.jsxs("div",{className:"space-y-3 p-6",children:[a.jsx(on,{className:"h-5 w-1/3"}),a.jsx(on,{className:"h-5 w-2/3"}),a.jsx(on,{className:"h-5 w-1/2"})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"min-h-0 flex-1",children:ja?a.jsx("div",{className:"flex h-full items-center justify-center px-4",children:a.jsx("p",{className:"text-lg font-medium text-gray-400 dark:text-gray-500",children:d.chat.emptyGreeting})}):a.jsx(pT,{items:W,version:J.version,ctx:ka,scrollElRef:pt,older:{hasMore:J.older.hasMore,loading:J.older.loading,error:J.older.error,prependedCount:J.prefixItems.length,onLoad:J.loadOlder},outline:a.jsx(pB,{entries:Ue,turnOffset:J.outlineOffset,version:J.version,scrollRef:pt,running:J.taskState!=="idle",fit:wt})})}),a.jsx("div",{className:"shrink-0 border-t border-gray-200 bg-white px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3 dark:border-gray-800 dark:bg-gray-950",children:a.jsxs("div",{className:"mx-auto max-w-3xl",children:[J.goal&&a.jsx(NP,{goal:J.goal}),br]})})]}):w?a.jsx("div",{className:"space-y-3 p-6",children:a.jsx(on,{className:"h-5 w-1/2"})}):a.jsx(Fa,{title:d.chat.noSessions,action:a.jsx(ge,{onClick:ls,children:d.nav.newChat})})},ne?.sessionId??"empty")}),Tn.view&&a.jsx(B2,{view:Tn.view,open:Tn.open,animateEntrance:Tn.animateEntrance,renderPanel:Mn,panelBadges:{agents:Ar},terminalSupported:wa})]}),Vr.view&&a.jsx(B2,{view:Vr.view,open:Vr.open,animateEntrance:Vr.animateEntrance,renderPanel:Mn,panelBadges:{agents:Ar},terminalSupported:wa}),a.jsx(Yt,{open:L,title:d.project.noCredentialTitle,onClose:()=>F(!1),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>F(!1),children:d.project.later}),a.jsx(ge,{variant:"primary",onClick:()=>{F(!1),e("/models")},children:d.project.goToModels})]}),children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.project.noCredentialBody})}),a.jsxs(ln,{open:A?.phase==="ask",title:d.chat.thinkingSwitchTitle,tone:"primary",confirmLabel:d.chat.thinkingSwitchCompactFirst,confirmDisabled:J.taskState!=="idle",onConfirm:os,secondaryLabel:d.chat.thinkingSwitchConfirm,onSecondary:()=>{A!==null&&fn(A.level),Q(null)},onClose:()=>Q(null),children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.chat.thinkingSwitchBody(W0(d.chat.thinkingLevelNames,A?.level)??A?.level??"")}),J.taskState!=="idle"&&a.jsx("p",{className:"mt-2 text-sm text-gray-500 dark:text-gray-400",children:d.chat.thinkingSwitchBusyHint})]})]})}function wq({sessionId:e,onClose:t,onChanged:n}){const s=kM(e,{poll:!0,...n?{onChanged:n}:{},onLoadFailed:t});return a.jsx(Yt,{open:!0,title:d.messaging.dialogTitle,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,children:d.common.close}),a.jsx(ge,{variant:"primary",disabled:s.busy||s.form===null,onClick:()=>{s.save()},children:s.busy?d.common.saving:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(wM,{b:s}),s.form!==null&&a.jsx(SM,{channel:s.form.channel})]})})}const mx=/^[a-z][a-z0-9_]{1,63}$/,q2=/^[a-z][a-z0-9_]{1,31}$/,Sq=/^[a-z0-9_]+$/,jq=64;function Cq(e){const t=[];return y.Children.forEach(e,n=>{if(!y.isValidElement(n)||n.type!=="option")return;const s=n.props;t.push({value:s.value!==void 0?String(s.value):"",label:s.children??"",...s.disabled?{disabled:!0}:{}})}),t}const Nq=`flex w-full items-center gap-2 text-left ${Uf} disabled:cursor-not-allowed disabled:opacity-60`,Tq={base:"text-base",sm:"text-xs"};function Ss({label:e,hint:t,error:n,required:s,size:o="base",className:c,children:u,value:f,onChange:p,disabled:h,"aria-label":x}){const g=Cq(u),v=String(f??""),w=g.find(E=>E.value===v),S=y.useId(),[C,N]=y.useState(!1),{triggerRef:T,panelRef:_,position:R}=$f({open:C,onClose:()=>N(!1),estimatedHeight:g.length*36+8}),D=E=>{N(!1),p?.({target:{value:E}}),T.current?.focus()},z=a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:T,type:"button",disabled:h,"aria-haspopup":"listbox","aria-expanded":C,...x!==void 0?{"aria-label":x}:{},"aria-required":s||void 0,"aria-invalid":n?!0:void 0,"aria-describedby":n?S:void 0,onClick:()=>N(E=>!E),className:`${Nq} ${Pf[o]} ${n?zf:""} ${c??""}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:w?.label??g[0]?.label??""}),a.jsx(ns,{className:"text-gray-400"})]}),C&&R&&ss.createPortal(a.jsx("div",{ref:_,role:"listbox",className:"anim-pop fixed z-[60] max-h-60 overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",style:{left:R.left,width:R.triggerWidth,top:R.topPx,bottom:R.bottomPx},children:g.map((E,L)=>a.jsxs("button",{type:"button",role:"option","aria-selected":E.value===v,disabled:E.disabled,onClick:()=>D(E.value),className:`flex items-center ${ny} ${Tq[o]} disabled:opacity-50 ${E.value===v?"bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"}`,children:[a.jsx("span",{className:"min-w-0 flex-1 truncate",children:E.label}),E.value===v&&a.jsx(qu,{className:"text-gray-500 dark:text-gray-400"})]},`${E.value}-${L}`))}),document.body)]});return a.jsx(Vu,{label:e,hint:t,error:n,errorId:S,required:s,children:z})}const Mq=["always-ask","read-only","allow-all","deny-all"];function Eq({open:e,onClose:t,onCreated:n}){const{user:s}=mn(),o=s&&!s.isAdmin?`${s.userId}-`:"",[c,u]=y.useState(""),[f,p]=y.useState(""),[h,x]=y.useState(void 0),[g,v]=y.useState(!1);y.useEffect(()=>{e&&(u(""),p(""),x(void 0))},[e]);const w=async()=>{const S=o+c.trim();if(!c.trim()){x(d.common.requiredField);return}if(!(o?Sq.test(c.trim())&&S.length<=jq:mx.test(S))){x(o?d.project.idPrefixHint:d.project.idHint);return}v(!0),x(void 0);try{const N=await bE({projectId:S,...f.trim()?{name:f.trim()}:{}});n(N.project.projectId)}catch(N){x(Ae(N))}finally{v(!1)}};return a.jsx(Yt,{open:e,title:d.project.createTitle,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:g,onClick:()=>{w()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[o?a.jsxs("div",{children:[a.jsx(Yn,{required:!0,children:d.project.id}),a.jsxs("div",{className:"flex items-stretch",children:[a.jsx("span",{className:"flex shrink-0 items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-100 px-2 font-mono text-xs text-gray-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400",children:o}),a.jsx(at,{size:"sm",className:"rounded-l-none",value:c,invalid:!!h,onChange:S=>{u(S.target.value),x(void 0)},autoFocus:!0})]}),h?a.jsx(ga,{children:h}):a.jsx(wo,{children:d.project.idPrefixHint})]}):a.jsx(at,{label:d.project.id,required:!0,size:"sm",value:c,error:h,onChange:S=>{u(S.target.value),x(void 0)},hint:d.project.idHint,autoFocus:!0}),a.jsx(at,{label:d.project.displayName,hint:d.project.displayNameHint,size:"sm",value:f,onChange:S=>p(S.target.value)})]})})}const Aq={general:If,members:Bx,defaults:"M4 21v-7m0-4V3m8 18v-9m0-4V3m8 18v-5m0-4V3M1 14h6m2-6h6m2 8h6",security:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"};function _q({d:e}){return a.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,className:"shrink-0",children:a.jsx("path",{d:e})})}function xl({title:e,description:t,children:n}){return a.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm",children:e}),t!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-400",children:t})]}),n!==void 0&&a.jsx("div",{className:"flex shrink-0 items-center gap-2",children:n})]})}function Rq({open:e,onClose:t}){const{desktopMode:n}=mn(),{currentProject:s}=en(),[o,c]=y.useState("general");y.useEffect(()=>{e&&c("general")},[e]);const u=s?.projectId,f=s?.role==="owner";if(!s||!u)return null;const p=[{key:"general",label:d.project.settingsTabGeneral},...n?[]:[{key:"members",label:d.project.settingsTabMembers}],{key:"defaults",label:d.project.settingsTabDefaults},{key:"security",label:d.project.settingsTabSecurity,info:d.project.commandPolicyInfo}],h=p.find(x=>x.key===o)??p[0];return a.jsx(Yt,{open:e,title:d.project.settingsTitle,onClose:t,widthClass:"sm:max-w-3xl",children:a.jsxs("div",{className:"flex flex-col gap-3 sm:min-h-[26rem] sm:flex-row sm:gap-0",children:[a.jsx("nav",{"aria-label":d.project.settingsTitle,className:"flex shrink-0 gap-1 overflow-x-auto sm:w-44 sm:flex-col sm:overflow-x-visible sm:border-r sm:border-gray-100 sm:pr-3 dark:sm:border-gray-800",children:p.map(x=>a.jsxs("button",{type:"button","aria-current":h.key===x.key?"page":void 0,onClick:()=>c(x.key),className:`flex shrink-0 items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm transition-colors duration-150 ${h.key===x.key?"bg-gray-100 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-800/60"}`,children:[a.jsx(_q,{d:Aq[x.key]}),a.jsx("span",{className:"truncate",children:x.label})]},x.key))}),a.jsxs("section",{className:"min-w-0 flex-1 sm:pl-5",children:[a.jsxs("h3",{className:"flex items-center gap-1.5 text-base font-semibold",children:[h.label,h.info!==void 0&&a.jsx(ba,{label:h.label,children:h.info})]}),a.jsxs("div",{className:"mt-2",children:[h.key==="general"&&a.jsx(Iq,{projectId:u,isOwner:f,onClose:t}),h.key==="members"&&a.jsx(Lq,{projectId:u,isOwner:f}),h.key==="defaults"&&a.jsx(Oq,{projectId:u,isOwner:f}),h.key==="security"&&a.jsx($q,{projectId:u,isOwner:f})]})]})]})})}function Iq({projectId:e,isOwner:t,onClose:n}){const{currentProject:s,setCurrentProjectId:o,projects:c,reloadProjects:u}=en(),f=s?wu(s):"",[p,h]=y.useState(f),[x,g]=y.useState(!1),[v,w]=y.useState(void 0),[S,C]=y.useState(!1),N=async()=>{const _=p.trim();if(!(!_||_===f||x)){g(!0),w(void 0);try{await vE(e,{name:_}),await u()}catch(R){w(Ae(R))}finally{g(!1)}}},T=async()=>{try{await kE(e),n();const _=c.find(R=>R.projectId!==e);await u(),_&&o(_.projectId)}catch(_){Be(Ae(_))}};return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(xl,{title:d.project.displayName,children:t?a.jsxs("div",{className:"flex flex-col items-end gap-1",children:[a.jsxs("div",{className:"flex items-stretch gap-2",children:[a.jsx(at,{size:"sm",className:"w-44",value:p,invalid:!!v,maxLength:100,onChange:_=>{h(_.target.value),v&&w(void 0)},onKeyDown:_=>{_.key==="Enter"&&N()}}),a.jsx(ge,{size:"sm",disabled:x||!p.trim()||p.trim()===f,onClick:()=>{N()},children:d.common.save})]}),v!==void 0&&a.jsx(ga,{children:v})]}):a.jsx("span",{className:"text-sm",children:f})}),a.jsx(xl,{title:d.project.projectIdLabel,children:a.jsx("span",{className:"font-mono text-xs text-gray-400",children:e})}),t&&(e==="default_project"?a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteDefaultForbidden}):c.length<=1?a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteLastForbidden}):a.jsx(xl,{title:d.project.deleteProject,description:d.project.deleteProjectDesc,children:a.jsx(ge,{size:"sm",variant:"danger",onClick:()=>C(!0),children:d.common.delete})})),a.jsx(ln,{open:S,title:d.project.deleteProject,onClose:()=>C(!1),onConfirm:()=>{T()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.project.deleteConfirm})})]})}function Lq({projectId:e,isOwner:t}){const{user:n}=mn(),[s,o]=y.useState(null),[c,u]=y.useState(""),[f,p]=y.useState(null);y.useEffect(()=>{let g=!1;return o(null),p(null),mg(e).then(v=>{g||o(v.members)}).catch(v=>{g||p(Ae(v))}),()=>{g=!0}},[e]);const h=async()=>{if(c.trim())try{await wE(e,{userId:c.trim()}),u("");const g=await mg(e);o(g.members)}catch(g){Be(Ae(g))}},x=async g=>{try{await SE(e,g);const v=await mg(e);o(v.members)}catch(v){Be(Ae(v))}};return f?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:f}):s===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):a.jsx("div",{className:"overflow-x-auto rounded-md border border-gray-200 dark:border-gray-800",children:a.jsxs("table",{className:"w-full text-xs",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-100 bg-gray-50 text-left text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400",children:[a.jsx("th",{className:"whitespace-nowrap px-2.5 py-1.5 font-medium",children:d.common.username}),a.jsx("th",{className:"whitespace-nowrap px-2.5 py-1.5 font-medium",children:d.common.role}),a.jsx("th",{className:"w-20 whitespace-nowrap px-2.5 py-1.5 text-right font-medium",children:d.common.actions})]})}),a.jsxs("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[s.map(g=>a.jsxs("tr",{children:[a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:g.userId}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:a.jsx(On,{tone:"gray",children:g.role})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1 text-right",children:t&&g.role!=="owner"&&g.userId!==n?.userId&&a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>{x(g.userId)},children:d.project.removeMember})})]},g.userId)),t&&a.jsxs("tr",{children:[a.jsx("td",{className:"px-2.5 py-1.5",children:a.jsx(at,{placeholder:d.common.username,size:"sm",value:c,onChange:g=>u(g.target.value),onKeyDown:g=>{g.key==="Enter"&&h()}})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1.5",children:a.jsx(On,{tone:"gray",children:"member"})}),a.jsx("td",{className:"whitespace-nowrap px-2.5 py-1 text-right",children:a.jsx(ge,{size:"sm",disabled:!c.trim(),onClick:()=>{h()},children:d.project.addMember})})]})]})]})})}function Oq({projectId:e,isOwner:t}){const{user:n}=mn(),{agents:s}=en(),[o,c]=y.useState(null),[u,f]=y.useState(null),[p,h]=y.useState(null),[x,g]=y.useState(!1),[v,w]=y.useState(""),[S,C]=y.useState(""),[N,T]=y.useState(""),[_,R]=y.useState(""),[D,z]=y.useState(null);y.useEffect(()=>{let B=!1;return Qj(e).then(Y=>{B||(c(Y),w(Y.agentId??""),C(Y.workspace??""),T(Y.approvalMode??""),R(Y.thinkingLevel??""))}).catch(Y=>{B||h(Ae(Y))}),Ml(e).then(Y=>{B||(f(Y),z(Y.defaultModel??null))}).catch(Y=>{B||h(Ae(Y))}),()=>{B=!0}},[e]);const E=o!==null&&(v!==(o.agentId??"")||S.trim()!==(o.workspace??"")||N!==(o.approvalMode??"")||_!==(o.thinkingLevel??"")),L=u!==null&&D!==null&&!zt(u.defaultModel,D),F=async()=>{if(x||!E&&!L)return;g(!0);let B=null;try{if(E){const Y={...v?{agentId:v}:{},...S.trim()?{workspace:S.trim()}:{},...N?{approvalMode:N}:{},..._?{thinkingLevel:_}:{}},q=await jE(e,Y);c(q),n&&dH(n.userId,e),B={projectId:e,defaults:q}}if(L&&D){const Y=await ME(e,{provider:D.provider,modelId:D.modelId});f(q=>q&&{...q,defaultModel:Y.defaultModel}),n&&iM(n.userId,e),B={...B??{projectId:e},defaultModel:Y.defaultModel}}B&&yt(d.common.saved)}catch(Y){Be(Ae(Y))}finally{B&&xH(B),g(!1)}},V=o?.agentId?(()=>{const B=s.find(Y=>Y.agentId===o.agentId);return B?_n(B):o.agentId})():d.project.chatDefaultsNotSet,P=u?.models.find(B=>zt(B,u.defaultModel));return a.jsxs("div",{children:[a.jsxs("p",{className:"mb-2 flex items-center gap-1.5 text-xs font-medium text-gray-500",children:[d.project.chatDefaultsTitle,a.jsx(ba,{label:d.project.chatDefaultsTitle,children:d.project.chatDefaultsHint})]}),p?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:p}):o===null||u===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):t?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[a.jsxs(Ss,{label:d.project.chatDefaultsAgent,size:"sm",value:v,onChange:B=>w(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsNotSet}),s.map(B=>a.jsx("option",{value:B.agentId,children:_n(B)},B.agentId))]}),a.jsxs(Ss,{label:d.chat.approvalMode,size:"sm",value:N,onChange:B=>T(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsApprovalNotSet}),Mq.map(B=>a.jsx("option",{value:B,children:d.chat.approvalModeNames[B]??B},B))]}),a.jsxs(Ss,{label:d.chat.thinkingLevel,size:"sm",value:_,onChange:B=>R(B.target.value),children:[a.jsx("option",{value:"",children:d.project.chatDefaultsThinkingNotSet}),ST.map(B=>a.jsx("option",{value:B,children:d.chat.thinkingLevelNames[B]??B},B))]}),a.jsxs("div",{children:[a.jsxs("span",{className:"mb-1 flex items-center gap-1",children:[a.jsx(Yn,{block:!1,children:d.chat.model}),a.jsx(ba,{label:d.chat.model,children:d.project.chatDefaultsModelHint})]}),u.models.length>0?a.jsx(a.Fragment,{children:a.jsx(Ay,{models:u.models,value:D,defaultModel:u.defaultModel,onChange:z,disabled:x,variant:"form"})}):a.jsx("p",{className:"text-xs text-gray-400",children:d.models.empty})]}),a.jsxs("div",{className:"sm:col-span-2",children:[a.jsx(Yn,{children:d.chat.workspace}),a.jsx(sd,{projectId:e,workspace:S,onChange:C,variant:"form"}),a.jsx(wo,{children:d.chat.workspaceHintShort})]})]}),a.jsx("div",{className:"mt-3 flex justify-end",children:a.jsx(ge,{size:"sm",disabled:x||!E&&!L,onClick:()=>{F()},children:d.common.save})})]}):a.jsx("div",{className:"space-y-1 text-sm",children:[[d.project.chatDefaultsAgent,V],[d.chat.workspace,o.workspace??d.chat.workspaceAuto],[d.chat.approvalMode,o.approvalMode?d.chat.approvalModeNames[o.approvalMode]??o.approvalMode:d.project.chatDefaultsApprovalNotSet],[d.chat.thinkingLevel,o.thinkingLevel?d.chat.thinkingLevelNames[o.thinkingLevel]??o.thinkingLevel:d.project.chatDefaultsThinkingNotSet],[d.chat.model,P?P.displayName??P.modelId:d.project.chatDefaultsNotSet]].map(([B,Y])=>a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"w-24 shrink-0 text-xs text-gray-500",children:B}),a.jsx("span",{className:"min-w-0 flex-1 break-all",children:Y})]},B))})]})}function Dq(e,t){return e.name===t.name&&e.pattern===t.pattern&&(e.description??"")===(t.description??"")&&e.enabled===t.enabled}function V2({initial:e,onApply:t,onCancel:n}){const[s,o]=y.useState(e?.name??""),[c,u]=y.useState(e?.pattern??""),[f,p]=y.useState(e?.description??""),[h,x]=y.useState(void 0),g=()=>{const v=s.trim(),w=c.trim();if(!v||!w)return;try{new RegExp(w)}catch{x(d.project.commandPolicyInvalidPattern);return}const S=f.trim();t({name:v,pattern:w,...S!==""?{description:S}:{},enabled:e?.enabled??!0})};return a.jsxs("div",{className:"space-y-2 py-3",children:[a.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[a.jsx("div",{className:"sm:w-40",children:a.jsx(at,{size:"sm",label:d.project.commandPolicyRuleName,required:!0,value:s,maxLength:64,autoFocus:!0,onChange:v=>o(v.target.value)})}),a.jsx("div",{className:"min-w-0 flex-1",children:a.jsx(at,{size:"sm",className:"font-mono",label:d.project.commandPolicyRulePattern,required:!0,value:c,maxLength:512,...h!==void 0?{error:h}:{},onChange:v=>{u(v.target.value),h&&x(void 0)},onKeyDown:v=>{v.key==="Enter"&&g()}})})]}),a.jsx(at,{size:"sm",label:d.project.commandPolicyRuleDesc,value:f,maxLength:300,onChange:v=>p(v.target.value)}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(ge,{size:"sm",variant:"ghost",onClick:n,children:d.common.cancel}),a.jsx(ge,{size:"sm",disabled:!s.trim()||!c.trim(),onClick:g,children:d.project.commandPolicyApplyRule})]})]})}function $q({projectId:e,isOwner:t}){const[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(!1),[p,h]=y.useState(!0),[x,g]=y.useState([]),[v,w]=y.useState(null);y.useEffect(()=>{let N=!1;return s(null),c(null),w(null),CE(e).then(T=>{N||(s(T),h(T.enabled),g(T.rules))}).catch(T=>{N||c(Ae(T))}),()=>{N=!0}},[e]);const S=n!==null&&(p!==n.enabled||x.length!==n.rules.length||x.some((N,T)=>!Dq(N,n.rules[T]))),C=async()=>{if(!(u||!S)){f(!0);try{const N=await NE(e,{enabled:p,rules:x});s(N),h(N.enabled),g(N.rules),yt(d.common.saved)}catch(N){Be(Ae(N))}finally{f(!1)}}};return a.jsx("div",{children:o!==null?a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:o}):n===null?a.jsx("p",{className:"text-xs text-gray-400",children:d.common.loading}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:a.jsx(xl,{title:d.project.commandPolicyEnable,description:d.project.commandPolicyEnableDesc,children:t?a.jsx(js,{checked:p,onChange:h,disabled:u}):a.jsx("span",{className:"text-xs text-gray-400",children:p?d.project.commandPolicyOn:d.project.commandPolicyOff})})}),a.jsxs("div",{className:p?"":"opacity-50",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-gray-100 py-1.5 dark:border-gray-800/60",children:[a.jsxs("p",{className:"text-xs font-medium text-gray-500",children:[d.project.commandPolicyRules," ·"," ",a.jsx("span",{className:"font-semibold",children:x.length})]}),t&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>g(n.defaultRules.map(N=>({...N}))),children:d.project.commandPolicyRestore}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>w("new"),children:d.project.commandPolicyAddRule})]})]}),a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[v==="new"&&a.jsx(V2,{initial:null,onApply:N=>{g([N,...x]),w(null)},onCancel:()=>w(null)}),x.map((N,T)=>v===T?a.jsx(V2,{initial:N,onApply:_=>{g(x.map((R,D)=>D===T?_:R)),w(null)},onCancel:()=>w(null)},`edit-${T}`):a.jsxs("div",{className:`flex items-center gap-3 py-2.5 ${N.enabled?"":"opacity-60"}`,children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm font-medium",children:N.name}),N.description!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-400",children:N.description}),a.jsx("p",{className:"mt-0.5 truncate font-mono text-[11px] text-gray-400",title:N.pattern,children:N.pattern})]}),t?a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx(js,{checked:N.enabled,disabled:u||!p,onChange:_=>g(x.map((R,D)=>D===T?{...R,enabled:_}:R))}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>w(T),children:d.project.commandPolicyEditRule}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:u||!p||v!==null,onClick:()=>g(x.filter((_,R)=>R!==T)),children:d.common.delete})]}):a.jsx("span",{className:"shrink-0 text-xs text-gray-400",children:N.enabled?d.project.commandPolicyOn:d.project.commandPolicyOff})]},`${N.name}-${T}`)),x.length===0&&v!=="new"&&a.jsx("p",{className:"py-3 text-xs text-gray-400",children:d.project.commandPolicyEmpty})]})]}),t&&a.jsx("div",{className:"mt-2 flex justify-end border-t border-gray-100 pt-3 dark:border-gray-800/60",children:a.jsx(ge,{size:"sm",disabled:u||!S||v!==null,onClick:()=>{C()},children:d.common.save})})]})})}function Uq({status:e,checkPending:t,menuItemClass:n,onInstallRequest:s}){const o=FC(e,t),c=o.action==="none",u=o.labelKind==="checking"?d.update.checking:o.labelKind==="downloading"?d.update.clientDownloading(o.version,o.percent):o.labelKind==="install"?d.update.clientRestartToInstall(o.version):d.update.clientCheckNow,f=o.labelKind==="unsupported"?o.unsupportedReason==="linux-not-appimage"?d.update.clientUnsupportedNonAppImage:d.update.clientUnsupportedDev:null,p=a.jsxs("button",{type:"button",disabled:c,onClick:()=>{o.action==="install"?s():o.action==="check"&&dI()},className:`${n} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.busy&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"}),!o.busy&&o.labelKind==="install"&&a.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]"}),a.jsx("span",{className:"min-w-0 truncate",children:u})]}),o.appVersion!==null&&a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:`v${o.appVersion}`})]});return f!==null?a.jsx("span",{className:"block",title:f,children:p}):p}function Pq({version:e,newVersion:t,checking:n,menuItemClass:s,onCheck:o,onOpenDialog:c}){const u=t!==null,f=n?d.update.checking:u?d.update.newVersion(t):d.update.checkNow;return a.jsxs("button",{type:"button",disabled:n,onClick:u?c:o,className:`${s} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[n&&a.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"}),!n&&u&&a.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]"}),a.jsx("span",{className:"min-w-0 truncate",children:f})]}),e!==null&&a.jsx("span",{className:"shrink-0 text-xs text-gray-400 dark:text-gray-500",children:`v${e}`})]})}function zq({open:e,onClose:t,latestVersion:n,releaseUrl:s=null,canUpdate:o,onRunFinished:c}){const[u,f]=y.useState("confirm"),[p,h]=y.useState(null);y.useEffect(()=>{e&&(f("confirm"),h(null))},[e]);const x=()=>{u==="done"&&c?.(),t()},g=async()=>{f("running");try{h(await $A())}catch(w){h({status:"failed",output:Ae(w),needsRestart:!1})}f("done")},v=p===null?null:p.status==="updated"?{text:d.update.updated,className:sn.success}:p.status==="unsupported"?{text:d.update.unsupported,className:sn.attention}:{text:d.update.failed,className:sn.danger};return a.jsx(Yt,{open:e,title:o?d.update.updateNow:n!==null?d.update.newVersion(n):d.update.releaseNotes,onClose:u==="running"?()=>{}:x,footer:u==="done"||!o?a.jsx(ge,{onClick:x,children:d.common.close}):a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:x,disabled:u==="running",children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:u==="running",onClick:()=>{g()},children:u==="running"?d.update.updating:d.update.updateNow})]}),children:u==="done"&&p!==null&&v!==null?a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:`text-sm font-medium ${v.className}`,children:v.text}),p.status==="updated"&&a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:d.update.restartHint}),p.output!==""&&a.jsx("pre",{className:"max-h-56 overflow-auto rounded-md bg-gray-100 p-3 text-xs leading-relaxed whitespace-pre-wrap text-gray-700 dark:bg-gray-800 dark:text-gray-300",children:oT(p.output)})]}):a.jsxs("div",{className:"space-y-2",children:[n!==null&&a.jsx("p",{className:"text-sm font-medium",children:d.update.newVersion(n)}),s!==null&&a.jsx("p",{children:a.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-brand-600 underline-offset-2 hover:underline dark:text-brand-300",children:d.update.releaseNotes})}),a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:o?d.update.confirmBody:d.update.adminOnly}),u==="running"&&a.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:d.update.updating})]})})}function Bq(e){return!(e.desktopMode&&e.sessionVia==="desktop")}const Hq=[{key:"general",group:"personal",visible:()=>!0},{key:"appearance",group:"personal",visible:()=>!0},{key:"account",group:"personal",visible:e=>Bq(e)},{key:"proxy",group:"server",visible:e=>e.isAdmin},{key:"uploads",group:"server",visible:e=>e.isAdmin},{key:"users",group:"server",visible:e=>e.isAdmin&&!e.desktopMode}];function Fq(e){return Hq.filter(t=>t.visible(e)).map(({key:t,group:n})=>({key:t,group:n}))}function qq(e){const t=[];for(const n of e)t.includes(n.group)||t.push(n.group);return t}function Vq(e,t){return t.some(n=>n.key===e)?e:t[0]?.key??null}const Gq=e=>`flex w-full items-center gap-2 whitespace-nowrap rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${e?"bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`;function Kq({open:e,onClose:t,title:n,groups:s,active:o,onSelect:c,children:u}){const f=s.length>1,p=s.flatMap(x=>x.items).find(x=>x.key===o),h=p?.label??n;return a.jsx(Yt,{open:e,onClose:t,title:n,headerless:!0,bare:!0,widthClass:"sm:max-w-3xl",children:a.jsxs("div",{className:"flex h-[min(40rem,85vh)] flex-col sm:flex-row",children:[a.jsx("nav",{"aria-label":n,className:"flex shrink-0 gap-1 overflow-x-auto border-b border-gray-100 p-2 sm:w-44 sm:flex-col sm:overflow-x-visible sm:overflow-y-auto sm:border-b-0 sm:border-r sm:p-3 dark:border-gray-800",children:s.map(x=>a.jsxs("div",{className:"contents sm:mt-3 sm:block sm:first:mt-0",children:[f&&x.label!==void 0&&a.jsx("p",{className:"hidden px-2.5 pb-1 text-[11px] font-medium uppercase tracking-wide text-gray-400 sm:block dark:text-gray-500",children:x.label}),x.items.map(g=>a.jsxs("button",{type:"button",className:Gq(g.key===o),"aria-current":g.key===o?"page":void 0,onClick:()=>c(g.key),children:[g.icon!==void 0&&a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:g.icon}),a.jsx("span",{className:"min-w-0 truncate",children:g.label})]},g.key))]},x.key))}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 px-4 pt-4 sm:px-6 sm:pt-5",children:[a.jsxs("h2",{className:`flex min-w-0 items-center ${Ro.row} text-lg font-semibold`,children:[h,p?.info!==void 0&&a.jsx(ba,{label:h,children:p.info})]}),a.jsx(Rf,{onClose:t})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3 sm:px-6 sm:pb-6",children:u})]})]})})}function _i({label:e,hint:t,info:n,children:s}){return a.jsxs("div",{className:"flex items-center justify-between gap-4 py-3.5 first:pt-0 last:pb-0",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("p",{className:`flex items-center ${Ro.row} text-sm font-medium`,children:[e,n!==void 0&&a.jsx(ba,{label:e,children:n})]}),t!==void 0&&a.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:t})]}),a.jsx("div",{className:"shrink-0",children:s})]})}function Wq({value:e,onChange:t}){return a.jsx("div",{className:"flex items-center gap-1.5",children:cE.map(n=>a.jsx("button",{type:"button",title:d.settings.accentNames[n.value],"aria-label":d.settings.accentNames[n.value],"aria-pressed":e===n.value,onClick:()=>t(n.value),className:`h-5 w-5 rounded-full border transition-transform duration-150 hover:scale-110 ${e===n.value?"border-gray-500 ring-2 ring-gray-400/50 dark:border-gray-300":"border-transparent"}`,style:{backgroundColor:n.color}},n.value))})}const Yq=14*1024*1024;function Xq(){const{projects:e,currentProject:t}=en(),{reload:n}=Ii(),[s,o]=y.useState(""),[c,u]=y.useState(""),[f,p]=y.useState([]),[h,x]=y.useState(!1),g=s!==""?s:t?.projectId??e[0]?.projectId??"",v=f.some(N=>N.agentId===c)?c:(f.find(N=>N.agentId==="default_agent")??f[0])?.agentId??"";y.useEffect(()=>{if(g==="")return;let N=!1;return aC(g).then(T=>{N||p(T.agents)}).catch(()=>{N||p([])}),()=>{N=!0}},[g]);const w=h||v==="",S=async N=>{if(!(g===""||v==="")){x(!0);try{await bA(g,v,{dataBase64:N});const T=e.find(R=>R.projectId===g),_=`${T?wu(T):g} · ${f.find(R=>R.agentId===v)?.name??v}`;g===t?.projectId&&await n(),yt(d.settings.importTraceDone(_))}catch(T){Be(Ae(T))}finally{x(!1)}}},C=N=>{const T=N.target.files?.[0];if(N.target.value="",!T||v==="")return;if(T.size>Yq){Be(d.settings.importTraceTooLarge);return}const _=new FileReader;_.onload=()=>{const R=_.result;S(R.slice(R.indexOf(",")+1))},_.onerror=()=>Be(d.common.unknownError),_.readAsDataURL(T)};return a.jsx(_i,{label:d.settings.importTrace,info:d.settings.importTraceInfo,children:a.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[a.jsx("div",{className:"w-32",children:a.jsx(Ss,{size:"sm",value:g,disabled:h,onChange:N=>{o(N.target.value),u("")},"aria-label":d.settings.importTraceProject,children:e.map(N=>a.jsx("option",{value:N.projectId,children:wu(N)},N.projectId))})}),a.jsx("div",{className:"w-32",children:a.jsx(Ss,{size:"sm",value:v,disabled:w,onChange:N=>u(N.target.value),"aria-label":d.settings.importTraceAgent,children:f.map(N=>a.jsx("option",{value:N.agentId,children:_n(N)},N.agentId))})}),a.jsxs("label",{className:`inline-flex shrink-0 items-center justify-center gap-1 rounded-md border border-gray-300 px-3 py-1 text-sm font-medium transition-colors duration-150 dark:border-gray-700 ${w?"pointer-events-none opacity-60":"cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"}`,children:[a.jsx(Xl,{accept:".jsonl",disabled:w,onChange:C}),a.jsx(YC,{size:14}),h?d.settings.importTraceRunning:d.settings.importTracePick]})]})})}function Qq(){const{lang:e,setLang:t}=Dr(),{currency:n,setCurrency:s}=as(),o=[{value:"en",label:d.settings.langEn},{value:"zh",label:d.settings.langZh},{value:"system",label:d.settings.followSystem}],c=[{value:"USD",label:d.models.currencyUsd},{value:"CNY",label:d.models.currencyCny}];return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.settings.language,info:d.settings.languageInfo,children:a.jsx(ws,{options:o,value:e,onChange:t})}),a.jsx(_i,{label:d.models.currency,info:d.settings.currencyInfo,children:a.jsx(ws,{options:c,value:n,onChange:s,cols:2})}),a.jsx(Xq,{})]})}function Zq(){const{mode:e,setMode:t,fontScale:n,setFontScale:s,accent:o,setAccent:c,terminalMode:u,setTerminalMode:f}=as(),p=[{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark},{value:"system",label:d.settings.followSystem}],h=[{value:"app",label:d.settings.followAppTheme},{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark}],x=[{value:"sm",label:d.settings.fontSmall},{value:"md",label:d.settings.fontMedium},{value:"lg",label:d.settings.fontLarge}];return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.settings.theme,info:d.settings.themeInfo,children:a.jsx(ws,{options:p,value:e,onChange:t})}),a.jsx(_i,{label:d.settings.terminalTheme,info:d.settings.terminalThemeInfo,children:a.jsx(ws,{options:h,value:u,onChange:f})}),a.jsx(_i,{label:d.settings.fontSize,info:d.settings.fontSizeInfo,children:a.jsx(ws,{options:x,value:n,onChange:s})}),a.jsx(_i,{label:d.settings.accent,info:d.settings.accentInfo,children:a.jsx(Wq,{value:o,onChange:c})})]})}function _M({open:e,onClose:t}){const{refresh:n,sessionVia:s}=mn(),o=s==="desktop",[c,u]=y.useState(""),[f,p]=y.useState(""),[h,x]=y.useState(""),[g,v]=y.useState({}),[w,S]=y.useState(!1),C=()=>v(T=>T.old||T.new||T.confirm?{}:T);y.useEffect(()=>{e&&(u(""),p(""),x(""),v({}))},[e]);const N=async()=>{const T={};if(!o&&!c&&(T.old=d.common.requiredField),f||(T.new=d.common.requiredField),h||(T.confirm=d.common.requiredField),!T.confirm&&f!==h&&(T.confirm=d.account.passwordMismatch),T.old||T.new||T.confirm){v(T);return}S(!0),v({});try{await fE(o?{newPassword:f}:{oldPassword:c,newPassword:f}),await n(),t()}catch(_){_ instanceof xr&&_.code==="invalid_password"?v({new:Ae(_)}):v({old:Ae(_)})}finally{S(!1)}};return a.jsx(Yt,{open:e,title:d.account.changePassword,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:w,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:w,onClick:()=>{N()},children:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[!o&&a.jsx(ts,{label:d.account.oldPassword,required:!0,size:"sm",value:c,onChange:T=>{u(T.target.value),C()},error:g.old,autoComplete:"current-password",info:d.account.oldPasswordHint,infoLabel:d.account.oldPassword,autoFocus:!0}),a.jsx(ts,{label:d.account.newPassword,required:!0,size:"sm",value:f,onChange:T=>{p(T.target.value),C()},error:g.new,autoComplete:"new-password",hint:d.auth.passwordHint,autoFocus:o}),a.jsx(ts,{label:d.account.confirmPassword,required:!0,size:"sm",value:h,onChange:T=>{x(T.target.value),C()},error:g.confirm,autoComplete:"new-password"})]})})}function Jq(){const[e,t]=y.useState(!1);return a.jsxs("div",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:[a.jsx(_i,{label:d.account.changePassword,info:d.settings.changePasswordInfo,children:a.jsx(ge,{variant:"secondary",onClick:()=>t(!0),children:d.account.changePassword})}),a.jsx(_M,{open:e,onClose:()=>t(!1)})]})}function RM({actions:e,children:t}){return a.jsxs("section",{children:[a.jsx("div",{className:"space-y-4",children:t}),e!==void 0&&a.jsx("div",{className:"mt-5 flex justify-end gap-2 border-t border-gray-100 pt-4 dark:border-gray-800/60",children:e})]})}function eV(){const[e,t]=y.useState(null),[n,s]=y.useState(!0),[o,c]=y.useState(!0),[u,f]=y.useState(""),[p,h]=y.useState(null),[x,g]=y.useState(!1),v=C=>{t(C),s(C.proxyForApp),c(C.proxyForAgent),f(C.proxyUrl??"")};y.useEffect(()=>{let C=!1;return Yj().then(N=>{C||v(N.settings)}).catch(N=>{C||Be(Ae(N))}),()=>{C=!0}},[]);const w=async()=>{if(e===null||x)return;if(n===e.proxyForApp&&o===e.proxyForAgent&&u.trim()===(e.proxyUrl??"")){wr(d.common.noChangesToSave);return}g(!0),h(null);try{const N=await Xj({proxyForApp:n,proxyForAgent:o,proxyUrl:u});v(N.settings),yt(d.common.saved)}catch(N){N instanceof xr&&N.code==="invalid_proxy_url"?h(Ae(N)):Be(Ae(N))}finally{g(!1)}},S=e!==null;return a.jsxs(RM,{actions:a.jsx(ge,{variant:"primary",disabled:!S||x,onClick:()=>{w()},children:d.common.save}),children:[a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-sm font-medium",children:d.settings.proxyForApp}),a.jsx(js,{checked:n,onChange:s,disabled:!S})]}),a.jsxs("div",{className:"flex items-center justify-between gap-3",children:[a.jsx("span",{className:"text-sm font-medium",children:d.settings.proxyForAgent}),a.jsx(js,{checked:o,onChange:c,disabled:!S})]}),a.jsx(at,{label:d.settings.proxyAddress,size:"sm",value:u,placeholder:d.settings.proxyAddressPlaceholder,disabled:!S,...p!==null?{error:p}:{},onChange:C=>{f(C.target.value),p!==null&&h(null)}})]})}function tV(){const{uploadLimits:e,refresh:t}=mn(),[n,s]=y.useState(null),[o,c]=y.useState(""),[u,f]=y.useState(""),[p,h]=y.useState(null),[x,g]=y.useState(!1),v=C=>{s(C),c(String(C.attachmentMaxMb)),f(String(C.attachmentTotalMb))};y.useEffect(()=>{let C=!1;return Yj().then(N=>{C||v(N.settings)}).catch(N=>{C||Be(Ae(N))}),()=>{C=!0}},[]);const w=async()=>{if(n===null||x)return;const C=Number(o.trim()),N=Number(u.trim()),T=o.trim()===""||!Number.isInteger(C),_=u.trim()===""||!Number.isInteger(N);if(T||_){h({text:d.errors.byCode.invalid_attachment_limit,max:T,total:_});return}if(C===n.attachmentMaxMb&&N===n.attachmentTotalMb){wr(d.common.noChangesToSave);return}g(!0),h(null);try{const R=await Xj({attachmentMaxMb:C,attachmentTotalMb:N});v(R.settings),await t().catch(()=>{}),yt(d.common.saved)}catch(R){R instanceof xr&&R.code==="invalid_attachment_limit"?h({text:Ae(R),max:!0,total:!0}):Be(Ae(R))}finally{g(!1)}},S=n!==null;return a.jsxs(RM,{actions:a.jsx(ge,{variant:"primary",disabled:!S||x,onClick:()=>{w()},children:d.common.save}),children:[a.jsx(at,{label:d.settings.attachmentMaxMb,required:!0,size:"sm",type:"number",inputMode:"numeric",min:e.attachmentLimitMinMb,max:e.attachmentLimitMaxMb,hint:d.settings.attachmentMaxMbHint(e.attachmentLimitMinMb,e.attachmentLimitMaxMb),value:o,disabled:!S,...p?.max===!0?{error:p.text}:{},onChange:C=>{c(C.target.value),p!==null&&h(null)}}),a.jsx(at,{label:d.settings.attachmentTotalMb,required:!0,size:"sm",type:"number",inputMode:"numeric",min:e.attachmentLimitMinMb,max:e.attachmentLimitMaxMb,hint:d.settings.attachmentTotalMbHint(e.attachmentLimitMinMb,e.attachmentLimitMaxMb),value:u,disabled:!S,...p?.total===!0?p.max?{invalid:!0}:{error:p.text}:{},onChange:C=>{f(C.target.value),p!==null&&h(null)}})]})}function nV(){const{user:e,desktopMode:t}=mn(),[n,s]=y.useState(null),[o,c]=y.useState(null),[u,f]=y.useState(!1),[p,h]=y.useState(null),[x,g]=y.useState(null),v=y.useCallback(async()=>{try{s((await pE()).users),c(null)}catch(w){c(Ae(w))}},[]);return y.useEffect(()=>{e?.isAdmin&&!t&&v()},[e?.isAdmin,t,v]),e&&(!e.isAdmin||t)?null:a.jsxs("div",{children:[a.jsx("div",{className:"mb-4 flex justify-end",children:a.jsx(ge,{variant:"primary",onClick:()=>f(!0),children:d.admin.createUser})}),n===null?a.jsx("p",{className:"text-sm text-gray-400",children:d.common.loading}):a.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-800",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-100 bg-gray-50 text-left text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400",children:[a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.username}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.role}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 font-medium",children:d.common.created}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2 text-right font-medium",children:d.common.actions})]})}),a.jsx("tbody",{className:"divide-y divide-gray-100 dark:divide-gray-800/60",children:n.map(w=>a.jsxs("tr",{children:[a.jsxs("td",{className:"whitespace-nowrap px-3 py-2 font-medium",children:[w.userId,w.passwordIsInitial&&a.jsx("span",{className:"ml-2 align-middle",children:a.jsx(On,{tone:"gray",children:d.admin.initialPasswordFlag})})]}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2",children:a.jsx(On,{tone:"gray",children:w.isAdmin?d.admin.roleAdmin:d.admin.roleUser})}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400",children:Jr(w.createdAt)}),a.jsxs("td",{className:"whitespace-nowrap px-3 py-1.5 text-right",children:[a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>h(w),children:d.admin.resetPassword}),!w.isAdmin&&a.jsx(ge,{size:"sm",variant:"ghost",onClick:()=>g(w),children:d.common.delete})]})]},w.userId))})]})}),o&&a.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:o}),a.jsx(rV,{open:u,onClose:()=>f(!1),onDone:()=>{f(!1),v()}}),a.jsx(aV,{user:p,onClose:()=>h(null)}),a.jsx(sV,{user:x,onClose:()=>g(null),onDone:()=>{g(null),v()}})]})}function rV({open:e,onClose:t,onDone:n}){const[s,o]=y.useState(""),[c,u]=y.useState(""),[f,p]=y.useState({}),[h,x]=y.useState(!1),g=()=>p(w=>w.userId||w.password?{}:w);y.useEffect(()=>{e&&(o(""),u(""),p({}))},[e]);const v=async()=>{const w=s.trim(),S={};if(w?q2.test(w)||(S.userId=d.auth.usernameHint):S.userId=d.common.requiredField,c||(S.password=d.common.requiredField),S.userId||S.password){p(S);return}x(!0),p({});try{await hE({userId:w,password:c}),n()}catch(C){C instanceof xr&&C.code==="invalid_password"?p({password:Ae(C)}):p({userId:Ae(C)})}finally{x(!1)}};return a.jsx(Yt,{open:e,title:d.admin.createUser,onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:h,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:h,onClick:()=>{v()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{label:d.common.username,required:!0,size:"sm",value:s,onChange:w=>{o(w.target.value),g()},error:f.userId,hint:d.auth.usernameHint,autoFocus:!0}),a.jsx(ts,{label:d.admin.initialPassword,required:!0,size:"sm",value:c,onChange:w=>{u(w.target.value),g()},error:f.password,autoComplete:"new-password",hint:d.auth.passwordHint}),q2.test(s.trim())&&a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.admin.defaultProjectNote(`${s.trim()}-default_project`)})]})})}function aV({user:e,onClose:t}){const[n,s]=y.useState(""),[o,c]=y.useState(void 0),[u,f]=y.useState(!1);y.useEffect(()=>{e&&(s(""),c(void 0))},[e]);const p=async()=>{if(e){if(!n){c(d.common.requiredField);return}f(!0),c(void 0);try{await gE(e.userId,{password:n}),t()}catch(h){c(Ae(h))}finally{f(!1)}}};return a.jsx(Yt,{open:e!==null,title:e?d.admin.resetPasswordTitle(e.userId):"",onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:u,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:u,onClick:()=>{p()},children:d.common.save})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(ts,{label:d.admin.initialPassword,required:!0,size:"sm",value:n,onChange:h=>{s(h.target.value),c(void 0)},error:o,autoComplete:"new-password",hint:d.auth.passwordHint,autoFocus:!0}),a.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.admin.resetPasswordNote})]})})}function sV({user:e,onClose:t,onDone:n}){const[s,o]=y.useState(!1),[c,u]=y.useState(null),[f,p]=y.useState(!1);y.useEffect(()=>{e&&(o(!1),u(null))},[e]);const h=async()=>{if(e){p(!0),u(null);try{await xE(e.userId),n()}catch(x){u(Ae(x))}finally{p(!1)}}};return a.jsx(Yt,{open:e!==null,title:e?d.admin.deleteUserTitle(e.userId):"",onClose:t,footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:t,disabled:f,children:d.common.cancel}),s?a.jsx(ge,{variant:"danger",disabled:f,onClick:()=>{h()},children:d.common.confirm}):a.jsx(ge,{variant:"danger",onClick:()=>o(!0),children:d.common.delete})]}),children:a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:e?d.admin.deleteUserConfirm(e.userId):""}),c&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:c})]})})}const iV={general:If,appearance:"M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4l1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4m11.4-11.4l1.4-1.4",account:"M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z",proxy:"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",uploads:"M12 15V4m0 0L7 9m5-5l5 5M4 20h16",users:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"};function oV({open:e,onClose:t}){const{user:n,desktopMode:s,sessionVia:o,uploadLimits:c}=mn(),u=Fq({isAdmin:n?.isAdmin===!0,desktopMode:s,sessionVia:o}),[f,p]=y.useState(null);y.useEffect(()=>{e&&p(null)},[e]);const h=Vq(f,u);if(h===null)return null;const x={general:d.settings.generalTitle,appearance:d.settings.appearanceTitle,account:d.settings.accountTitle,proxy:d.settings.proxyTitle,uploads:d.settings.uploadLimitsTitle,users:d.admin.users},g={personal:d.settings.groupPersonal,server:d.settings.groupServer},v={proxy:d.settings.proxyInfo,uploads:d.settings.uploadLimitsInfo(c.attachmentMaxCount,c.imageMaxMb)},w=qq(u).map(S=>({key:S,label:g[S],items:u.filter(C=>C.group===S).map(C=>({key:C.key,label:x[C.key],icon:a.jsx(vn,{d:iV[C.key],size:16}),...v[C.key]!==void 0?{info:v[C.key]}:{}}))}));return a.jsxs(Kq,{open:e,onClose:t,title:d.settings.systemSettings,groups:w,active:h,onSelect:p,children:[h==="general"&&a.jsx(Qq,{}),h==="appearance"&&a.jsx(Zq,{}),h==="account"&&a.jsx(Jq,{}),h==="proxy"&&a.jsx(eV,{}),h==="uploads"&&a.jsx(tV,{}),h==="users"&&a.jsx(nV,{})]})}const Jm="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";function lV({size:e=16}){return a.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:[a.jsx("circle",{cx:"5",cy:"12",r:"2"}),a.jsx("circle",{cx:"12",cy:"12",r:"2"}),a.jsx("circle",{cx:"19",cy:"12",r:"2"})]})}const G2="M21 21l-4.35-4.35M17 11a6 6 0 1 1-12 0 6 6 0 0 1 12 0z",cV="M21 5h-7M10 5H3M21 12h-9M8 12H3M21 19h-5M12 19H3M14 2v6M8 9v6M16 16v6",uV="M18 6L6 18M6 6l12 12",dV="application/x-penguin-session-id",IM="application/x-penguin-group-key",K2=e=>e.dataTransfer.types.includes(IM),W2="(hover: hover) and (pointer: fine)";function Y2({base:e,size:t=15}){return a.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a.jsx("g",{transform:"translate(-1 -1) scale(0.82)",children:a.jsx("path",{d:e})}),a.jsx("path",{d:"M18.5 15.5v6M15.5 18.5h6",strokeWidth:"2"})]})}const Zc="block w-full px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800",Jc=e=>`flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${e?"bg-gray-200/70 text-gray-700 dark:bg-gray-800 dark:text-gray-200":"text-gray-400 hover:bg-gray-200/50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"}`,X2="px-2.5 pb-0.5 pt-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500",mV=e=>`penguin.sidebarCollapsedGroups.${e}`,fV=e=>`penguin.sidebarPinnedGroups.${e}`;function Om(e){if(!e)return new Set;try{const t=JSON.parse(localStorage.getItem(e)??"[]");return new Set(Array.isArray(t)?t.filter(n=>typeof n=="string"):[])}catch{return new Set}}function Q2(e,t){if(e)try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}const Dm=(e,t)=>`${t}\0${e}`,Jg="\0drafts";function pV({activity:e}){return e===null?a.jsx("span",{"aria-hidden":"true",className:"block h-3 w-3 shrink-0"}):a.jsx(vN,{activity:e})}function Z2({onNavigate:e,onCollapse:t}){const n=yr(),{user:s,logout:o,desktopMode:c,sessionVia:u}=mn(),{locale:f}=Dr(),{projects:p,currentProject:h,setCurrentProjectId:x,reloadProjects:g,agents:v,currentAgent:w,setCurrentAgentId:S}=en(),{sessions:C,byAgent:N,countsByAgent:T,workspaceCountsByAgent:_,isLoadedFor:R,hasMoreFor:D,loadMoreFor:z,loading:E,remove:L,replace:F}=Ii(),P=Mx("/chat/:sessionId")?.params.sessionId??null,[B,Y]=y.useState(!1),[q,K]=y.useState(!1),[H,$]=y.useState(!1),[X,le]=y.useState(!1),[ie,I]=y.useState(!1),A=HC({desktopMode:c,sessionVia:u}),Q=VC(A,q),[j,U]=y.useState(!1),{version:ee,update:re}=Px(q),ke=zx(),be=GC(re),[ye,Se]=y.useState(!1),[Me,ze]=y.useState(!1),De=h?.projectId??null,ct=VI(De),bt=De===null?null:mV(De),he=De===null?null:fV(De),[ne,oe]=y.useState(YI),[J,ht]=y.useState(bg),[ve,Xe]=y.useState(()=>Om(bt)),[Ge,He]=y.useState(()=>Om(he)),[Pe,W]=y.useState(()=>dw(De)),[me,Ue]=y.useState(s6),[pe,$e]=y.useState(()=>vg(De,bg())),[nt,gt]=y.useState(()=>kg(De,bg())),[Ke,dt]=y.useState(()=>fw(De)),[pt,wt]=y.useState(null),[st,Bt]=y.useState(""),[Sn,Dn]=y.useState(null),[Vt,ar]=y.useState(!1),[zn,Xt]=y.useState(""),[Cn,lr]=y.useState(!1),[Mt,Pr]=y.useState(()=>window.matchMedia(W2).matches);y.useEffect(()=>{const G=window.matchMedia(W2),Ce=Ze=>Pr(Ze.matches);return G.addEventListener("change",Ce),()=>G.removeEventListener("change",Ce)},[]);const[Bn,Nr]=y.useState(null),[Tr,Te]=y.useState(null),[Ie,ut]=y.useState(null),[St,gn]=y.useState(null);y.useEffect(()=>{Xe(Om(bt)),He(Om(he)),W(dw(De)),$e(vg(De,J)),gt(kg(De,J)),dt(fw(De)),Mr(0),cr(new Map)},[bt,he,De]);const[Nn,Hn]=y.useState(new Set),[Dt,Rn]=y.useState(new Set),[zr,cr]=y.useState(new Map),[Js,Mr]=y.useState(0),[ta,Br]=y.useState(null),[is,Hr]=y.useState(!1),[fn,Fr]=y.useState(null),qr=pH(s?.userId??null,De),[pn,na]=y.useState(null),[Jn,Er]=y.useState(""),[ur,os]=y.useState(!1),[ls,ra]=y.useState(null),[cs,ka]=y.useState(null),Ar=G=>{NI(G),ht(G),$e(vg(De,G)),gt(kg(De,G)),Mr(0),cr(new Map)},er=()=>{const G=!ne;XI(G),oe(G)},Tn=y.useMemo(()=>a6(PR(C),Ke),[C,Ke]),Vr=y.useMemo(()=>UR(_),[_]),wa=y.useMemo(()=>gw(v,G=>G.agentId,{pinned:Ge,order:J==="agent"?nt:[]}),[v,Ge,nt,J]),Mn=y.useMemo(()=>gw(Tn,G=>G.key,{pinned:Ge,order:J==="workspace"?nt:[]}),[Tn,Ge,nt,J]),Gr=y.useMemo(()=>wa.map(G=>G.agentId),[wa]),En=y.useMemo(()=>Mn.map(G=>G.key),[Mn]),us=G=>J==="agent"?G.agentId:J==="time"?zc:vo(G.workspace),hn=G=>{if(Ct)return;const Ce=new Set(ve);Ce.has(G)?Ce.delete(G):Ce.add(G),Xe(Ce),Q2(bt,Ce)},Sa=G=>{const Ce=new Set(Ge);Ce.has(G)?Ce.delete(G):Ce.add(G),He(Ce),Q2(he,Ce)},Ts=G=>{const Ce=QI(Pe,G);W(Ce),mw(De,Ce)},Ga=G=>{i6(G),Ue(G)},Ct=zn.trim()!=="",ds=J==="agent"?wa.length:J==="workspace"?Mn.length:0,ja=DC(ds),br=$C(Js,ds),Ca=G=>Ct?G:aw(G,br),de=()=>!Ct&&ja>1?a.jsx(EI,{page:br,pageCount:ja,onChange:Mr}):null,Re=me==="manual"&&Mt?"manual":"recent",Qe=G=>Ct?G.filter(Ce=>$R(Ce,zn)):G,mt=J==="time"?gg(Qe(C)):null,Et=mt===null?[]:qR(mt.active,Date.now()),Pt=VR(T),Wt=G=>[...T].filter(([,Ce])=>Ce[G]>0).map(([Ce])=>Ce),Ka=Wt("active").filter(G=>D(G,"active")),_r=G=>({active:G,subagent:[],schedule:[],archived:[]}),Rr=()=>{ar(!1),Xt("")},Ir=(G,Ce,Ze)=>{if(!Bn)return;const it=Yx(G,Bn.id,Ce,Ze);if(it===G)return;const tt=l6(pe,it);$e(tt),pw(De,J,tt)},Ui=(G,Ce,Ze)=>{if(Ie===null)return;const it=m6(nt,G,Ie,Ce,Ze);it!==nt&&(gt(it),d6(De,J,it))},ae=(G,Ce)=>{if(!Mt||Ct||!Xx(J))return{header:{},dropEdge:null};const Ze=Ie,it=Ze!==null&&Ze!==G&&Ge.has(Ze)===Ge.has(G),tt=Je=>{const ft=Je.currentTarget.getBoundingClientRect();return Je.clientY-ft.top>ft.height/2};return{header:{draggable:!0,onDragStart:Je=>{Je.dataTransfer.setData(IM,G),Je.dataTransfer.effectAllowed="move",ut(G)},onDragEnd:()=>{ut(null),gn(null)},onDragOver:Je=>{if(!it||!K2(Je))return;Je.preventDefault(),Je.dataTransfer.dropEffect="move";const ft=tt(Je);gn(An=>An?.key===G&&An.after===ft?An:{key:G,after:ft})},onDragLeave:Je=>{const ft=Je.relatedTarget;ft instanceof Node&&Je.currentTarget.contains(ft)||gn(An=>An?.key===G?null:An)},onDrop:Je=>{!it||Ze===null||!K2(Je)||(Je.preventDefault(),Ui(Ce,G,tt(Je)),ut(null),gn(null))}},dropEdge:it&&St?.key===G?St.after?"below":"above":null}},_e=Ct?qr.filter(G=>sx(G).toLowerCase().includes(zn.trim().toLowerCase())):qr,et=_e.length>0||(J==="agent"?wa.some(G=>Qe(N.get(G.agentId)??[]).length>0):J==="time"?mt!==null&&Object.values(mt).some(G=>G.length>0):Mn.some(G=>Qe(G.sessions).length>0)),qe=(G,Ce)=>`${Ce}\0${G}`,vt=G=>J==="workspace"?G:void 0,xn=(G,Ce,Ze)=>{const it=qe(G,Ce);Rn(tt=>new Set(tt).add(it)),z(Ze,Ce,vt(G)).finally(()=>{Rn(tt=>{const Je=new Set(tt);return Je.delete(it),Je})})},tr=(G,Ce,Ze)=>{if(Ct)return;const it=Dm(G,Ce),tt=!Nn.has(it);if(Hn(Je=>{const ft=new Set(Je);return tt?ft.add(it):ft.delete(it),ft}),tt){const Je=vt(G),ft=Ze.filter(An=>!R(An,Ce,Je));ft.length>0&&z(ft,Ce,Je)}},Pi=y.useRef(null);y.useEffect(()=>{if(!P)return;const G=C.find(ft=>ft.sessionId===P);if(!G)return;const Ce=ha(G);if(Ce==="active"||Ce==="archived")return;const Ze=`${J}\0${P}`;if(Pi.current===Ze)return;Pi.current=Ze;const it=J==="agent"?G.agentId:J==="time"?zc:vo(G.workspace),tt=Dm(it,Ce);Hn(ft=>ft.has(tt)?ft:new Set(ft).add(tt));const Je=J==="workspace"?it:void 0;R(G.agentId,Ce,Je)||z([G.agentId],Ce,Je)},[P,C,J,R,z]),y.useEffect(()=>{if(!(J!=="workspace"||Ct))for(const G of aw(Mn,br)){const Ce=Vr.get(G.key),Ze=Ce?.totals.active??0;if(G.sessions.filter(ft=>ha(ft)==="active").length>=Math.min(bs,Ze))continue;const Je=[...new Set([...Ce?.agents.active??[],...G.sessions.map(ft=>ft.agentId)])].filter(ft=>!R(ft,"active",G.key));Je.length>0&&z(Je,"active",G.key)}},[J,Ct,Mn,br,Vr,R,z]);const ei=async()=>{if(!Me){ze(!0);try{const G=fI(await iw());G.kind==="disabled"?wr(d.update.checkDisabled):G.kind==="failed"?Be(d.update.checkFailed):G.kind==="found"?yt(d.update.foundNew(G.latestVersion)):yt(d.update.upToDate)}catch(G){Be(Ae(G))}finally{ze(!1)}}},id=async G=>{!G.archived&&G.sessionId===P&&Hn(Ce=>new Set(Ce).add(Dm(us(G),"archived")));try{const Ce=await tf(G.sessionId,{archived:!G.archived});F(Ce.session)}catch{}},zi=async()=>{if(!pn)return;const G=Jn.trim();if(G){os(!0),ra(null);try{const Ce=await tf(pn.sessionId,{title:G});F(Ce.session),na(null)}catch(Ce){ra(Ae(Ce))}finally{os(!1)}}},Lo=async()=>{if(!ta)return;Hr(!0);const G=ta;try{await nf(G.sessionId),L(G.sessionId),s&&Du(aM(s.userId,G.sessionId));const Ce=ZI(Pe,G.sessionId);Ce!==Pe&&(W(Ce),mw(De,Ce)),GI(De,G.sessionId);const Ze=c6(pe,G.sessionId);if(Ze!==pe&&($e(Ze),pw(De,J,Ze)),Br(null),P===G.sessionId){const it=(N.get(G.agentId)??[]).filter(tt=>{const Je=ha(tt);return tt.sessionId!==G.sessionId&&(Je==="active"||Je==="schedule")});n(it[0]?`/chat/${it[0].sessionId}`:"/chat")}}catch(Ce){Be(Ae(Ce))}finally{Hr(!1)}},Oo=G=>{n(G),e?.()},nr=(G,Ce)=>{s&&De&&Yl(s.userId,De),G&&S(G);const Ze={...G?{agentId:G}:{},...Ce!==void 0?{workspace:Ce}:{}};n(`/chat/${ya}`,Object.keys(Ze).length>0?{state:Ze}:void 0),e?.()},Ms=()=>{fn&&(s&&De&&lM(s.userId,De,fn.id),P===fn.id&&n(`/chat/${ya}`),Fr(null))},Bi=(v.find(G=>G.agentId==="default_agent")??v[0])?.agentId,Hi=w?.agentId??Bi,Do=CI(J),ms=Do==="agent"?d.agent.create:Do==="chat"?d.chat.newSessionMenu:d.chat.newWorkspaceEntity,Fi=G=>{G!==Ke&&(dt(G),e6(De,G))},qi=G=>{const Ce=t6(Ke,G);if(Ce===Ke)return;Fi(Ce);const Ze=vo(G),it=Mn.findIndex(tt=>tt.key===Ze);Mr(OR(it>=0?it:Mn.length))},$o=y.useMemo(()=>new Set(Ke.map(G=>G.path)),[Ke]),od=G=>{Bt(Ke.find(Ce=>Ce.path===G)?.alias??""),wt({path:G})},ld=()=>{pt&&(Fi(n6(Ke,pt.path,st)),wt(null))},sp=()=>{Sn&&(Fi(r6(Ke,Sn.path)),Dn(null))},ip=G=>{Gx(De,G.sessionId,G.lastActiveAt),S(G.agentId),Oo(`/chat/${G.sessionId}`)},Ql=y.useMemo(()=>new Map(v.map(G=>[G.agentId,_n(G)])),[v]),cd=(G,Ce,Ze,it=!1)=>a.jsx("ul",{className:"space-y-0.5",children:G.map(tt=>{const Je=Ze!==void 0&&Bn?.scope===Ze.scope?Bn:null,ft=Je!==null&&Je.id!==tt.sessionId&&Pe.has(Je.id)===Pe.has(tt.sessionId),An=Ze===void 0?{}:{draggable:!0,onDragStart:Ht=>{Ht.dataTransfer.setData(dV,tt.sessionId),Ht.dataTransfer.effectAllowed="move",Nr({scope:Ze.scope,id:tt.sessionId})},onDragEnd:()=>{Nr(null),Te(null)},onDragOver:Ht=>{if(!Je||!ft)return;Ht.preventDefault();const dr=Ht.currentTarget.getBoundingClientRect(),ti=Ht.clientY-dr.top>dr.height/2;Te(Na=>Na?.id===tt.sessionId&&Na.after===ti?Na:{id:tt.sessionId,after:ti})},onDragLeave:()=>Te(Ht=>Ht?.id===tt.sessionId?null:Ht),onDrop:Ht=>{if(!Je||!ft)return;Ht.preventDefault();const dr=Ht.currentTarget.getBoundingClientRect(),ti=Ht.clientY-dr.top>dr.height/2,Na=Ze.fullRows.filter(Vi=>Pe.has(Vi.sessionId)===Pe.has(Je.id)).map(Vi=>Vi.sessionId);Ir(Na,tt.sessionId,ti),Nr(null),Te(null)},dropEdge:ft&&Tr?.id===tt.sessionId?Tr.after?"below":"above":null};return a.jsx(gV,{s:tt,active:tt.sessionId===P,activity:KI(tt,ct,P),pinned:Pe.has(tt.sessionId),canPin:it,lastActive:UI(tt.lastActiveAt,f),...Ce?{agentHint:Ql.get(tt.agentId)??tt.agentId}:{},...An,onOpen:ip,onTogglePin:Ht=>Ts(Ht.sessionId),onRename:Ht=>{ra(null),Er(Ht.title??""),na(Ht)},onMessaging:Ht=>ka(Ht),onDelete:Ht=>Br(Ht),onToggleArchive:Ht=>{id(Ht)}},tt.sessionId)})}),ud=(G,Ce,Ze,it,tt,Je)=>{const ft=Ze[Ce];if(Ct&&ft.length===0)return null;const An=Ct?ft.length:Math.max(Je?.[Ce]??0,ft.length);if(An===0)return null;const Ht=!Ct&&ft.length<An&&tt.some(dr=>D(dr,Ce,vt(G)));return a.jsx(AI,{label:d.chat.folderGroups[Ce](An),open:Ct||Nn.has(Dm(G,Ce)),onToggle:()=>tr(G,Ce,tt),more:Ht,moreLabel:d.chat.expandRestSessions(Math.max(An-ft.length,0)),pending:Dt.has(qe(G,Ce)),onMore:()=>xn(G,Ce,tt),children:cd(ft,it)},Ce)},op=(G,Ce,Ze)=>{const it=(zr.get(G)??bs)+bs;cr(tt=>{const Je=new Map(tt);return Je.set(G,it),Je}),Ce.length>0&&Ze<it&&xn(G,"active",Ce)},lp=G=>{cr(Ce=>{if(!Ce.has(G))return Ce;const Ze=new Map(Ce);return Ze.delete(G),Ze})},Zl=(G,Ce,Ze,it,tt)=>{const Je=zr.get(G)??bs,ft=o6(Ce.active,Ta=>Ta.sessionId,{pinned:Pe,sortMode:Re,order:pe,recencyOf:Ta=>Ta.lastActiveAt}),An=Ct?ft:ft.slice(0,Je),Ht=Re==="manual"&&!Ct?{scope:G,fullRows:ft}:void 0,dr=tt("active"),ti=dr.length>0&&!dr.some(Ta=>D(Ta,"active",vt(G))),Na=Ct?0:DR({shown:An.length,loaded:Ce.active.length,total:it?.active??0,fullyLoaded:ti}),Vi=!Ct&&Je>bs&&Ce.active.length>bs,dd=rf.map(Ta=>ud(G,Ta,Ce,Ze,tt(Ta),it)),up=Ce.active.length===0&&dd.every(Ta=>Ta===null),dp=Dt.has(qe(G,"active"));return a.jsxs(a.Fragment,{children:[up?a.jsx("p",{className:"px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}):cd(An,Ze,Ht,!0),Na>0&&a.jsx(Km,{label:d.chat.expandRestSessions(Na),ariaLabel:d.chat.expandRestSessions(Na),pending:dp,onClick:()=>op(G,dr,Ce.active.length),className:"mt-0.5"}),Vi&&a.jsx(Km,{label:d.chat.showLess,ariaLabel:d.chat.showLess,onClick:()=>lp(G),...Na>0?{}:{className:"mt-0.5"}}),dd]})},Jl=mt===null?[]:rf.map(G=>ud(zc,G,mt,!0,Wt(G),Pt)),cp=WI.map(G=>({to:`/${G}`,label:d.nav[G],icon:vs[G]}));return a.jsxs("div",{className:"flex h-full w-full flex-col",children:[a.jsxs("div",{className:"flex shrink-0 items-center gap-1 px-2 pt-2",children:[t&&a.jsx("button",{type:"button",title:d.nav.collapseSidebar,"aria-label":d.nav.collapseSidebar,onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M15 6l-6 6 6 6M4 4v16",size:18})}),a.jsxs(Qn,{open:B,setOpen:Y,className:"min-w-0 flex-1",menuClass:"left-0 right-0 top-full mt-1 origin-top",button:a.jsxs("button",{type:"button",onClick:()=>Y(!B),className:"flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-base font-semibold transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800",children:[a.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:h?wu(h):d.common.loading}),a.jsx("span",{className:"text-gray-400",children:a.jsx(ns,{})})]}),children:[p.map(G=>a.jsxs("button",{type:"button",onClick:()=>{x(G.projectId),Y(!1)},className:`flex w-full items-center justify-between gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${G.projectId===h?.projectId?"font-semibold":""}`,children:[a.jsx("span",{className:"truncate",children:wu(G)}),a.jsx(On,{tone:"gray",children:G.role})]},G.projectId)),a.jsxs("div",{className:"mt-1.5 border-t border-gray-100 pt-1.5 dark:border-gray-800",children:[a.jsxs("button",{type:"button",className:Zc,onClick:()=>{Y(!1),$(!0)},children:["+ ",d.project.create]}),h&&a.jsx("button",{type:"button",className:Zc,onClick:()=>{Y(!1),le(!0)},children:d.project.settings})]})]})]}),a.jsx("div",{className:"shrink-0 px-2 pb-2 pt-2",children:a.jsxs("button",{type:"button",onClick:()=>nr(Bi),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm font-medium transition-colors duration-150 ${P===ya?"bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`,children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a.jsx(vn,{d:Jm})}),d.chat.newSessionMenu]})}),a.jsxs("div",{className:"relative min-h-0 flex-1 overflow-y-auto px-2 pb-2",children:[a.jsxs("nav",{className:"space-y-0.5",children:[a.jsx("div",{className:`grid transition-[grid-template-rows] duration-200 ease-out ${ne?"grid-rows-[0fr]":"grid-rows-[1fr]"}`,children:a.jsx("div",{className:"overflow-hidden",inert:ne,children:a.jsx("div",{className:`space-y-0.5 transition-opacity duration-200 ${ne?"opacity-0":"opacity-100"}`,children:cp.map(G=>{const Ce=G.to==="/agents"?ke.kernelNote:null;return a.jsxs(Lx,{to:G.to,onClick:()=>e?.(),...Ce!==null?{title:Ce,"aria-label":`${G.label} · ${Ce}`}:{},className:({isActive:Ze})=>`relative flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${Ze?"bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-600 hover:bg-gray-200/50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"}`,children:[a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:a.jsx(vn,{d:G.icon})}),G.label,Ce!==null&&a.jsx(Mo,{size:"inline",position:"right-2.5 top-1/2 -translate-y-1/2"})]},G.to)})})})}),a.jsx("button",{type:"button",onClick:er,"aria-expanded":!ne,"aria-label":ne?d.nav.expandGroup:d.nav.collapseGroup,title:ne?d.nav.expandGroup:d.nav.collapseGroup,className:"flex h-4 w-full items-center justify-center rounded-md bg-gray-200/70 text-gray-400 transition-colors duration-150 hover:bg-gray-300/60 hover:text-gray-700 dark:bg-gray-800/70 dark:text-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-300",children:a.jsx(ns,{size:12,className:`transition-transform duration-200 ${ne?"":"rotate-180"}`})})]}),a.jsxs("div",{className:`mt-3 grid items-center px-1 pt-2 transition-[grid-template-columns] duration-200 ease-out ${Vt?"grid-cols-[0fr_1fr]":"grid-cols-[1fr_1fr]"}`,children:[a.jsx("span",{className:`min-w-0 overflow-hidden whitespace-nowrap px-1 text-[11px] font-semibold uppercase tracking-wide text-gray-400 transition-opacity duration-200 dark:text-gray-500 ${Vt?"opacity-0":"opacity-100"}`,children:d.chat.sessionList}),a.jsxs("div",{className:"flex min-w-0 items-center justify-end gap-0.5",children:[Vt?a.jsxs("div",{className:"flex h-6 min-w-0 flex-1 items-center gap-1 rounded-md border border-gray-300 bg-white px-1.5 transition-colors duration-150 focus-within:border-gray-400 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-500",children:[a.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:G2,size:12})}),a.jsx("input",{autoFocus:!0,value:zn,placeholder:d.chat.searchSessionsPlaceholder,"aria-label":d.chat.searchSessions,...Gu,onChange:G=>Xt(G.target.value),onKeyDown:G=>{G.key==="Escape"&&(G.stopPropagation(),Rr())},className:"min-w-0 flex-1 bg-transparent text-xs text-gray-700 placeholder:text-gray-400 focus:outline-none dark:text-gray-200 dark:placeholder:text-gray-500"}),a.jsx("button",{type:"button",title:d.chat.searchClear,"aria-label":d.chat.searchClear,onClick:Rr,className:"flex h-4 w-4 shrink-0 items-center justify-center text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-300",children:a.jsx(vn,{d:uV,size:11})})]}):a.jsx("button",{type:"button",title:d.chat.searchSessions,"aria-label":d.chat.searchSessions,onClick:()=>ar(!0),className:Jc(!1),children:a.jsx(vn,{d:G2,size:14})}),a.jsxs(Qn,{open:Cn,setOpen:lr,portal:{direction:"down",align:"right"},menuClass:"w-40",button:a.jsx("button",{type:"button",title:d.chat.listSettings,"aria-label":d.chat.listSettings,"aria-haspopup":"menu","aria-expanded":Cn,onClick:()=>lr(!Cn),className:Jc(Cn),children:a.jsx(vn,{d:cV,size:14})}),children:[a.jsx("p",{className:X2,children:d.chat.groupModeSection}),a.jsx(eu,{icon:xm.workspace,label:d.chat.groupByWorkspace,checked:J==="workspace",onSelect:()=>{Ar("workspace"),lr(!1)}}),a.jsx(eu,{icon:xm.agent,label:d.chat.groupByAgent,checked:J==="agent",onSelect:()=>{Ar("agent"),lr(!1)}}),a.jsx(eu,{icon:xm.time,label:d.chat.groupByTime,checked:J==="time",onSelect:()=>{Ar("time"),lr(!1)}}),a.jsx("div",{className:"my-1 border-t border-gray-100 dark:border-gray-800"}),a.jsx("p",{className:X2,children:d.chat.sortModeSection}),Mt&&a.jsx(eu,{icon:lw.manual,label:d.chat.sortManual,checked:me==="manual",onSelect:()=>{Ga("manual"),lr(!1)}}),a.jsx(eu,{icon:lw.recent,label:d.chat.sortRecent,checked:me==="recent",onSelect:()=>{Ga("recent"),lr(!1)}})]}),Do==="agent"?a.jsx("button",{type:"button",title:ms,"aria-label":ms,onClick:()=>{n("/agents",{state:{create:!0}}),e?.()},className:Jc(!1),children:a.jsx(Y2,{base:vs.agents})}):Do==="chat"?a.jsx("button",{type:"button",title:ms,"aria-label":ms,onClick:()=>nr(),className:Jc(!1),children:a.jsx(vn,{d:Jm,size:Ye.iconButton})}):a.jsx(sd,{projectId:De??"",workspace:"",onChange:qi,trigger:(G,Ce)=>a.jsx("button",{type:"button",title:ms,"aria-label":ms,"aria-expanded":G,onClick:Ce,className:Jc(G),children:a.jsx(Y2,{base:El})})},De??"no-project")]})]}),_e.length>0&&a.jsxs("div",{className:"pt-2.5",children:[a.jsx(ym,{open:Ct||!ve.has(Jg),onToggle:()=>hn(Jg),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:Jm,size:Ye.groupHeaderGlyph})}),label:d.chat.draftGroup,uppercase:!0,count:_e.length}),(Ct||!ve.has(Jg))&&a.jsx("ul",{className:"space-y-0.5",children:_e.map(G=>a.jsx(hV,{entry:G,active:G.id===P,onOpen:()=>Oo(`/chat/${G.id}`),onDelete:()=>Fr(G)},G.id))})]}),J==="agent"?E&&v.length===0?a.jsx(Sr,{rows:5}):Ca(wa).map(G=>{const Ce=Qe(N.get(G.agentId)??[]);if(Ct&&Ce.length===0)return null;const Ze=gg(Ce),it=!Ct&&ve.has(G.agentId),tt=Ge.has(G.agentId),Je=ae(G.agentId,Gr);return a.jsxs(J2,{dropEdge:Je.dropEdge,children:[a.jsx(ym,{...Je.header,open:!it,onToggle:()=>hn(G.agentId),icon:a.jsx(Ha,{id:G.agentId,name:_n(G),size:18,className:"shrink-0 rounded"}),label:_n(G),uppercase:!0,actions:a.jsxs(a.Fragment,{children:[a.jsx(ej,{pinned:tt,onToggle:()=>Sa(G.agentId)}),a.jsx("button",{type:"button",title:d.chat.newSessionMenu,"aria-label":d.chat.newSessionMenu,onClick:()=>nr(G.agentId),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M12 5v14M5 12h14",size:Ye.groupHeaderAction})}),a.jsx("button",{type:"button",title:d.agent.settings,onClick:()=>Oo(`/agents/${G.agentId}`),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:If,size:Ye.groupHeaderAction})})]})}),it?null:Zl(G.agentId,Ze,!1,T.get(G.agentId),()=>[G.agentId])]},G.agentId)}):null,J==="agent"?de():null,J!=="workspace"?null:E&&C.length===0?a.jsx(Sr,{rows:5}):Mn.length===0&&!Ct?a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}):Ca(Mn).map(G=>{const Ce=Qe(G.sessions);if(Ct&&Ce.length===0)return null;const Ze=gg(Ce),it=!Ct&&ve.has(G.key),tt=Ge.has(G.key),Je=ae(G.key,En),ft=Vr.get(G.key),An=[...new Set(G.sessions.map(dr=>dr.agentId))],Ht=dr=>[...new Set([...ft?.agents[dr]??[],...An])];return a.jsxs(J2,{dropEdge:Je.dropEdge,children:[a.jsx(ym,{...Je.header,open:!it,onToggle:()=>hn(G.key),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:it?El:kI,size:Ye.groupHeaderGlyph})}),label:G.temp?d.chat.tempWorkspaces:G.label,count:Ct?Ze.active.length:Math.max(ft?.totals.active??0,Ze.active.length),...G.fullPath!==null?{title:G.fullPath}:{},actions:a.jsxs(a.Fragment,{children:[a.jsx(ej,{pinned:tt,onToggle:()=>Sa(G.key)}),a.jsx("button",{type:"button",title:d.chat.newSessionInWorkspace,"aria-label":d.chat.newSessionInWorkspace,onClick:()=>nr(Hi,G.fullPath??""),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(vn,{d:"M12 5v14M5 12h14",size:Ye.groupHeaderAction})}),$o.has(G.key)&&a.jsx(xV,{onRename:()=>od(G.key),onDelete:()=>Dn({path:G.key,label:G.label})})]})}),it?null:Zl(G.key,Ze,!0,ft?.totals,Ht)]},G.key)}),J==="workspace"?de():null,J!=="time"||mt===null?null:E&&C.length===0?a.jsx(Sr,{rows:5}):a.jsxs(a.Fragment,{children:[Et.map(G=>{const Ce=!Ct&&ve.has(G.key);return a.jsxs("div",{className:"pt-2.5",children:[a.jsx(ym,{open:!Ce,onToggle:()=>hn(G.key),icon:a.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:a.jsx(vn,{d:xm.time,size:Ye.groupHeaderGlyph})}),label:d.chat.timeGroups[G.bucket],uppercase:!0,count:G.sessions.length}),Ce?null:Zl(G.key,_r(G.sessions),!0,void 0,()=>[])]},G.key)}),Et.length===0&&!Ct&&Jl.every(G=>G===null)&&a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.noSessions}),!Ct&&mt.active.length<Pt.active&&Ka.length>0&&a.jsx(Km,{label:d.chat.loadMoreSessions,ariaLabel:d.chat.loadMoreSessions,pending:Dt.has(qe(zc,"active")),onClick:()=>xn(zc,"active",Ka),className:"mt-1"}),a.jsx("div",{className:"pt-2.5",children:Jl})]}),Ct&&!et&&a.jsx("p",{className:"px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600",children:d.chat.searchNoMatches})]}),a.jsx("div",{className:"shrink-0 border-t border-gray-200 p-2 dark:border-gray-800",children:a.jsx(Qn,{open:q,setOpen:K,menuClass:"bottom-full left-0 right-0 mb-1 origin-bottom",button:a.jsxs("button",{type:"button",onClick:()=>K(!q),...ke.softwareNote!==null?{title:ke.softwareNote,"aria-label":`${s?.userId??""} · ${ke.softwareNote}`}:{},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800",children:[a.jsxs("span",{className:"relative flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900",children:[(s?.userId??"?").slice(0,1).toUpperCase(),ke.software!==null&&a.jsx(Mo,{})]}),a.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:s?.userId}),s?.isAdmin&&a.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:d.auth.admin})]}),children:a.jsxs("div",{className:"py-1",children:[a.jsx("button",{type:"button",className:Zc,onClick:()=>{K(!1),I(!0)},children:d.settings.systemSettings}),!c&&a.jsx(Pq,{version:ee?.version??null,newVersion:be,checking:Me,menuItemClass:Zc,onCheck:()=>{ei()},onOpenDialog:()=>{K(!1),Se(!0)}}),A&&a.jsx(Uq,{status:Q.status,checkPending:Q.checkPending,menuItemClass:Zc,onInstallRequest:()=>{K(!1),U(!0)}}),!c&&a.jsx("button",{type:"button",className:"block w-full px-3.5 py-2 text-left text-sm text-red-600 transition-colors duration-150 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-950/40",onClick:()=>{K(!1),o().then(()=>n("/login"))},children:d.auth.logout})]})})}),a.jsx(oV,{open:ie,onClose:()=>I(!1)}),a.jsx(zq,{open:ye,onClose:()=>Se(!1),latestVersion:be,releaseUrl:re?.releaseUrl??null,canUpdate:s?.isAdmin===!0,onRunFinished:()=>{iw().catch(()=>{})}}),a.jsx(ln,{open:j,title:d.update.clientInstallConfirmTitle,onClose:()=>U(!1),onConfirm:()=>{U(!1),mI()},confirmLabel:d.update.clientInstallConfirmAction,tone:"primary",children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:d.update.clientInstallConfirmBody})}),a.jsx(Eq,{open:H,onClose:()=>$(!1),onCreated:G=>{$(!1),g().then(()=>x(G))}}),h&&a.jsx(Rq,{open:X,onClose:()=>le(!1)}),a.jsx(Yt,{open:pn!==null,title:d.chat.renameSession,onClose:()=>ur?void 0:na(null),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>na(null),disabled:ur,children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:ur||!Jn.trim(),onClick:()=>{zi()},children:d.common.save})]}),children:a.jsx(at,{label:d.chat.renameSessionLabel,value:Jn,error:ls??void 0,autoFocus:!0,maxLength:120,onChange:G=>{Er(G.target.value),ls&&ra(null)},onKeyDown:G=>{G.key==="Enter"&&Jn.trim()&&!ur&&zi()}})}),cs&&a.jsx(wq,{sessionId:cs.sessionId,onClose:()=>ka(null),onChanged:(G,Ce)=>{const Ze=C.find(tt=>tt.sessionId===G);if(!Ze)return;const it={...Ze};Ce!==null?it.messagingChannel=Ce:delete it.messagingChannel,F(it)}}),a.jsx(Yt,{open:pt!==null,title:d.chat.renameWorkspace,onClose:()=>wt(null),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>wt(null),children:d.common.cancel}),a.jsx(ge,{variant:"primary",onClick:ld,children:d.common.save})]}),children:a.jsx(at,{label:d.chat.renameWorkspaceLabel,hint:d.chat.renameWorkspaceHint,value:st,placeholder:pt?$x(pt.path):"",autoFocus:!0,maxLength:80,onChange:G=>Bt(G.target.value),onKeyDown:G=>{G.key==="Enter"&&!G.nativeEvent.isComposing&&ld()}})}),a.jsx(ln,{open:ta!==null,title:d.chat.deleteSession,confirmLabel:d.common.delete,busy:is,onClose:()=>is?void 0:Br(null),onConfirm:()=>{Lo()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:ta?d.chat.deleteSessionConfirm(ta.title??d.chat.defaultSessionTitle):""})}),a.jsx(ln,{open:Sn!==null,title:d.chat.deleteWorkspace,confirmLabel:d.common.delete,onClose:()=>Dn(null),onConfirm:sp,children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:Sn?d.chat.deleteWorkspaceConfirm(Sn.label):""})}),a.jsx(ln,{open:fn!==null,title:d.chat.deleteDraft,confirmLabel:d.common.delete,onClose:()=>Fr(null),onConfirm:Ms,children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:fn?d.chat.deleteDraftConfirm(sx(fn)||d.chat.draftUntitled):""})})]})}function hV({entry:e,active:t,onOpen:n,onDelete:s}){const o=sx(e)||d.chat.draftUntitled;return a.jsx("li",{children:a.jsxs("div",{"data-title-reveal":!0,className:`group flex items-center rounded-md pr-1 transition-colors duration-150 ${t?"bg-gray-200/70 dark:bg-gray-800":"hover:bg-gray-200/50 dark:hover:bg-gray-800/70"}`,children:[a.jsx("button",{type:"button",onClick:n,className:"flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left",children:a.jsx(Of,{scrollReveal:!0,text:o,className:`min-w-0 flex-1 text-sm ${t?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"}`})}),a.jsx("div",{className:"flex shrink-0 items-center",children:a.jsx("button",{type:"button",title:d.chat.deleteDraft,"aria-label":d.chat.deleteDraft,onClick:s,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 hover:bg-gray-300/60 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:hover:bg-gray-700 dark:hover:text-red-400",children:a.jsx(vn,{d:"M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6",size:14})})})]})})}function J2({dropEdge:e,children:t}){return a.jsxs("div",{className:"relative pt-2.5",children:[e!==null&&a.jsx("div",{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${e==="above"?"top-1":"-bottom-1"}`}),t]})}function ej({pinned:e,onToggle:t}){return a.jsx("button",{type:"button",title:e?d.nav.unpinGroup:d.nav.pinGroup,"aria-label":d.nav.pinGroup,"aria-pressed":e,onClick:t,className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-all duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${e?"text-gray-500 dark:text-gray-400":"text-gray-400 opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100 dark:text-gray-500"}`,children:a.jsx(vn,{d:Qx,size:Ye.groupHeaderAction})})}function gV({s:e,active:t,activity:n,pinned:s,canPin:o=!1,lastActive:c,agentHint:u,draggable:f=!1,dropEdge:p=null,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w,onOpen:S,onTogglePin:C,onRename:N,onMessaging:T,onDelete:_,onToggleArchive:R}){const D=w6(),z=F=>{D.close(),{pin:C,rename:N,messaging:T,archive:R,delete:_}[F](e)},E=F=>{D.returnFocus()?.focus(),z(F)},L={archived:e.archived,pinned:s};return a.jsxs("li",{className:"relative",...f?{draggable:!0,onDragStart:h,onDragEnd:x,onDragOver:g,onDragLeave:v,onDrop:w}:{},children:[p!==null&&a.jsx("div",{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-[var(--accent-bg)] ${p==="above"?"-top-px":"-bottom-px"}`}),a.jsxs("div",{"data-title-reveal":!0,ref:D.rowRef,...D.rowProps,className:`group flex select-none items-center rounded-md pr-1 transition-colors duration-150 ${f?"cursor-grab ":""}${t?"bg-gray-200/70 dark:bg-gray-800":"hover:bg-gray-200/50 dark:hover:bg-gray-800/70"}`,children:[a.jsxs("button",{type:"button","data-testid":"session-row","data-session-id":e.sessionId,onClick:()=>{D.consumeLongPressClick()||S(e)},className:"flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left",children:[u!==void 0&&a.jsxs("span",{title:u,className:"flex shrink-0 items-center",children:[a.jsx(Ha,{id:e.agentId,name:u,size:14,className:"rounded"}),a.jsx("span",{className:"sr-only",children:u})]}),a.jsx(Of,{scrollReveal:!0,text:e.title??d.chat.defaultSessionTitle,className:`min-w-0 flex-1 text-sm ${t?"font-medium text-gray-900 dark:text-gray-100":e.archived?"text-gray-400 dark:text-gray-500":"text-gray-700 dark:text-gray-300"}`}),s&&o&&a.jsxs("span",{title:d.chat.pinnedSession,className:"shrink-0 text-gray-400 dark:text-gray-500",children:[a.jsx(vn,{d:Qx,size:12}),a.jsx("span",{className:"sr-only",children:d.chat.pinnedSession})]}),e.messagingChannel!==void 0&&a.jsxs("span",{title:d.messaging.enabledIndicator[e.messagingChannel],className:"shrink-0 text-gray-400 dark:text-gray-500",children:[a.jsx(vn,{d:II,size:12}),a.jsx("span",{className:"sr-only",children:d.messaging.enabledIndicator[e.messagingChannel]})]}),a.jsx(pV,{activity:n}),e.pendingApprovalCount>0&&a.jsx("span",{title:d.chat.pendingApprovals(e.pendingApprovalCount),children:a.jsx(On,{tone:"amber",children:e.pendingApprovalCount})})]}),a.jsxs("div",{className:"relative flex h-6 min-w-12 shrink-0 items-center justify-end",children:[a.jsx("div",{className:"peer absolute right-0 top-1/2 flex -translate-y-1/2 items-center",children:a.jsx(E6,{actions:N6,state:L,onRun:z,onMore:D.openAt})}),c!==""&&a.jsx("span",{"aria-hidden":!0,className:"pointer-events-none px-1 text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-0 peer-focus-within:opacity-0 dark:text-gray-500",children:c})]}),a.jsx(Qn,{open:D.open,setOpen:D.setOpen,portal:{direction:"down",align:"left"},anchorRect:D.anchor,returnFocus:D.returnFocus,className:"contents",menuClass:"w-36",button:null,children:a.jsx(M6,{actions:T6(o),state:L,onRun:E})})]})]})}function xV({onRename:e,onDelete:t}){const[n,s]=y.useState(!1),o=c=>()=>{s(!1),c()};return a.jsxs(Qn,{open:n,setOpen:s,portal:{direction:"down",align:"right"},menuClass:"w-32",className:"shrink-0",button:a.jsx("button",{type:"button",title:d.chat.workspaceMenu,"aria-label":d.chat.workspaceMenu,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>s(!n),className:"flex h-7 w-7 shrink-0 items-center justify-center text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100",children:a.jsx(lV,{size:16})}),children:[a.jsxs("button",{type:"button",className:ey,onClick:o(e),children:[ty(Zx),d.chat.renameWorkspace]}),a.jsxs("button",{type:"button",className:gN,onClick:o(t),children:[a.jsx("span",{className:"shrink-0",children:a.jsx(vn,{d:Jx,size:13})}),d.chat.deleteWorkspace]})]})}function eu({icon:e,label:t,checked:n,onSelect:s}){return a.jsxs("button",{type:"button","aria-pressed":n,onClick:s,className:`${ey} justify-between`,children:[a.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[ty(e),a.jsx("span",{className:"truncate",children:t})]}),n&&a.jsx(qu,{className:"shrink-0 text-gray-500 dark:text-gray-400"})]})}const yV="M8 10h8M8 14h5M21 12a9 9 0 1 1-4.2-7.6L21 4v5h-5",e0=e=>`relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 ${e?"bg-gray-200/70 text-gray-900 dark:bg-gray-800 dark:text-gray-100":"text-gray-500 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"}`;function bV({onExpand:e}){const{user:t}=mn(),n=yr(),{agents:s,currentProject:o,setCurrentAgentId:c}=en(),{sessions:u,loading:f}=Ii(),p=zx(),h=Mx("/chat/:sessionId")?.params.sessionId??null,x=h!==null&&h!==ya,g=y.useMemo(()=>PC(u),[u]),v=()=>{g&&(c(g.agentId),n(`/chat/${g.sessionId}`))},w=()=>{t&&o&&Yl(t.userId,o.projectId);const C=(s.find(N=>N.agentId==="default_agent")??s[0])?.agentId;C&&c(C),n(`/chat/${ya}`,C?{state:{agentId:C}}:void 0)},S=[{to:"/agents",label:d.nav.agents,icon:vs.agents},{to:"/skills",label:d.nav.skills,icon:vs.skills},{to:"/models",label:d.nav.models,icon:vs.models},{to:"/usage",label:d.nav.usage,icon:vs.usage},{to:"/benchmark",label:d.nav.benchmark,icon:vs.benchmark}];return a.jsxs("div",{className:"flex h-full flex-col items-center gap-1 py-2.5",children:[a.jsx("button",{type:"button",title:d.nav.expandSidebar,"aria-label":d.nav.expandSidebar,onClick:e,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-200/70 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:a.jsx(Oe,{d:"M9 6l6 6-6 6M20 4v16",size:18})}),a.jsxs("nav",{className:"no-scrollbar mt-1 flex min-h-0 flex-1 flex-col items-center gap-1 overflow-y-auto",children:[a.jsx("button",{type:"button",title:d.nav.lastConversation,"aria-label":d.nav.lastConversation,disabled:!g&&!f,onClick:v,className:g||f?e0(x):"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-md text-gray-300 dark:text-gray-700",children:a.jsx(Oe,{d:yV,size:18})}),a.jsx("button",{type:"button",title:d.chat.newSessionMenu,"aria-label":d.chat.newSessionMenu,onClick:w,className:e0(h===ya),children:a.jsx(Oe,{d:Jm,size:18})}),S.map(C=>{const N=C.to==="/agents"?p.kernelNote:null;return a.jsxs(Lx,{to:C.to,title:N!==null?`${C.label} · ${N}`:C.label,"aria-label":N!==null?`${C.label} · ${N}`:C.label,className:({isActive:T})=>e0(T),children:[a.jsx(Oe,{d:C.icon,size:18}),N!==null&&a.jsx(Mo,{})]},C.to)})]}),a.jsxs("button",{type:"button",title:[t?.userId??"",d.nav.expandSidebar].concat(p.softwareNote!==null?[p.softwareNote]:[]).join(" · "),"aria-label":p.softwareNote!==null?`${t?.userId??""} · ${p.softwareNote}`:t?.userId??d.auth.admin,onClick:e,className:"relative mt-auto flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900",children:[(t?.userId??"?").slice(0,1).toUpperCase(),p.software!==null&&a.jsx(Mo,{})]})]})}function vV(){const{user:e,desktopMode:t}=mn(),n=Mx("/chat/:sessionId")?.params.sessionId??null;y.useLayoutEffect(()=>{SB(n)},[n]),vI();const s=zx(!0),[o,c]=y.useState(!1),[u,f]=y.useState(!1),[p,h]=y.useState(null),x=!!e?.passwordIsInitial&&!t;y.useEffect(()=>{if(!x)return;let C=!1;return Sx().then(N=>{C||h(N.prefs.initialPasswordBannerDismissed===!0)}).catch(()=>{C||h(!1)}),()=>{C=!0}},[x]);const g=()=>{h(!0),Nf({initialPasswordBannerDismissed:!0}).catch(()=>{})},[v,w]=y.useState(()=>localStorage.getItem("penguin.sidebarCollapsed")==="1"),S=()=>w(C=>{const N=!C;return localStorage.setItem("penguin.sidebarCollapsed",N?"1":"0"),N});return a.jsxs("div",{className:"flex h-full",children:[a.jsx("aside",{className:`hidden shrink-0 border-r border-gray-200 bg-gray-50 md:block dark:border-gray-800 dark:bg-gray-900 ${v?"w-12":"w-64 lg:w-72"}`,children:v?a.jsx(bV,{onExpand:S}):a.jsx(Z2,{onCollapse:S})}),a.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[a.jsxs("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-2 md:hidden dark:border-gray-800 dark:bg-gray-950",children:[a.jsxs("button",{type:"button","aria-label":s.note!==null?`${d.chat.sessionList} · ${s.note}`:d.chat.sessionList,...s.note!==null?{title:s.note}:{},onClick:()=>c(!0),className:"relative flex h-9 w-9 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200",children:[a.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":!0,children:a.jsx("path",{d:"M4 6h16M4 12h16M4 18h16"})}),s.any&&a.jsx(Mo,{})]}),a.jsx("span",{className:"text-sm font-semibold",children:d.appName})]}),x&&p===!1&&a.jsxs("div",{className:`relative flex shrink-0 items-center justify-center gap-3 border-b px-8 py-1.5 text-xs ${Df.attention}`,children:[a.jsx("span",{children:d.account.initialPasswordBanner}),a.jsx("button",{type:"button",className:"shrink-0 font-medium underline underline-offset-2 hover:text-amber-950 dark:hover:text-amber-100",onClick:()=>f(!0),children:d.account.changeNow}),a.jsx("button",{type:"button","aria-label":d.common.close,title:d.common.close,onClick:g,className:"absolute inset-y-0.5 right-1.5 flex items-center rounded-md px-1 text-amber-500 transition-colors duration-150 hover:text-amber-950 dark:text-amber-400/70 dark:hover:text-amber-100",children:a.jsx(Hl,{size:12})})]}),a.jsx("main",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:a.jsx(V_,{})}),a.jsx(OF,{})]}),a.jsx(_M,{open:u,onClose:()=>f(!1)}),a.jsx(QC,{open:o,side:"left",title:d.appName,onClose:()=>c(!1),children:a.jsx("div",{className:"h-full bg-gray-50 dark:bg-gray-900",children:a.jsx(Z2,{onNavigate:()=>c(!1)})})})]})}const Xy=1440,Qy=900,fx=3,kV=3,tj=Xy/fx,nj=Qy/kV,$m=28,Um=14;function wV(e){return()=>{e|=0,e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function SV(e,t){return e.x1-Um<=t.x2&&e.x2+Um>=t.x1&&e.y1-Um<=t.y2&&e.y2+Um>=t.y1}function jV(e,t,n,s){return{x1:Math.min(e,n),y1:Math.min(t,s),x2:Math.max(e,n),y2:Math.max(t,s)}}const CV=[{cell:0,edge:"left"},{cell:1,edge:"top"},{cell:2,edge:"right"},{cell:3,edge:"left"},{cell:5,edge:"right"},{cell:6,edge:"bottom"},{cell:7,edge:"bottom"},{cell:8,edge:"right"}];function NV(){const e=wV(12696599),t=[];for(const{cell:n,edge:s}of CV){const o=n%fx*tj+$m,c=Math.floor(n/fx)*nj+$m,u=o+tj-2*$m,f=c+nj-2*$m,p=[],h=(R,D,z,E)=>{const L=z[0]>0?u-R:z[0]<0?R-o:z[1]>0?f-D:D-c;for(let F=Math.min(60+e()*150,L);F>=40;F/=2){const V=Math.round(R+z[0]*F),P=Math.round(D+z[1]*F),B=jV(R,D,V,P);if(p.every((Y,q)=>E.has(q)||!SV(B,Y)))return p.push(B),[V,P]}return null},x=(R,D,z)=>(z-R)*(.35+e()*.3)>R-D?1:-1,g=(R,D,z,E,L,F,V)=>{let[P,B]=[R,D],Y=z;const q=[`M${Math.round(P)},${Math.round(B)}`],K=[];for(let H=0;H<E;H+=1){const $=H===0?V:new Set([p.length-1]),X=h(P,B,Y,$);if(!X)break;[P,B]=X,q.push(`L${P},${B}`),K.push([P,B]),Y=Y[0]!==0?[0,x(B,c,f)]:[x(P,o,u),0]}return K.length>=2&&t.push({d:q.join(" "),end:K[K.length-1],dur:L,delay:F}),K},v=.15+e()*.7,w=s==="left"?0:s==="right"?Xy:Math.round(o+(u-o)*v),S=s==="top"?0:s==="bottom"?Qy:Math.round(c+(f-c)*v),C=s==="left"?[1,0]:s==="right"?[-1,0]:s==="top"?[0,1]:[0,-1],N=12+e()*8,T=e()*3.2,_=g(w,S,C,3+Math.floor(e()*3),N,T,new Set);if(n%2===0&&_.length>=3){const[R,D]=_[1],[z,E]=_[2],L=[-Math.sign(z-R),-Math.sign(E-D)];g(R,D,L,2,N,T+1.4,new Set([1,2]))}}return t}const TV=NV();function MV(){return a.jsx("svg",{"aria-hidden":!0,className:"pointer-events-none absolute inset-0 h-full w-full text-slate-500/25 dark:text-cyan-300/15",viewBox:`0 0 ${Xy} ${Qy}`,preserveAspectRatio:"xMidYMid slice",fill:"none",children:TV.map((e,t)=>a.jsxs("g",{style:{"--trace-dur":`${e.dur.toFixed(1)}s`},children:[a.jsx("path",{d:e.d,pathLength:1,stroke:"currentColor",strokeWidth:"1",strokeLinecap:"round",strokeLinejoin:"round",className:"login-trace",style:{animationDelay:`${e.delay.toFixed(1)}s`}}),a.jsx("circle",{cx:e.end[0],cy:e.end[1],r:"3",fill:"currentColor",className:"login-via",style:{animationDelay:`${e.delay.toFixed(1)}s`}})]},t))})}function EV(){Li(d.auth.login);const{login:e}=mn(),{mode:t,setMode:n}=as(),{lang:s,setLang:o}=Dr(),c=yr(),[u,f]=y.useState(""),[p,h]=y.useState(""),[x,g]=y.useState({}),[v,w]=y.useState(!1),S=()=>g(_=>_.userId||_.password||_.form?{}:_),C=async()=>{const _={};if(u.trim()||(_.userId=d.common.requiredField),p||(_.password=d.common.requiredField),_.userId||_.password){g(_);return}w(!0),g({});try{await e(u.trim(),p),c("/chat",{replace:!0})}catch(R){g({form:Ae(R)})}finally{w(!1)}},N=[{value:"light",label:d.settings.themeLight},{value:"dark",label:d.settings.themeDark},{value:"system",label:d.settings.followSystem}],T=[{value:"en",label:d.settings.langEn},{value:"zh",label:d.settings.langZh},{value:"system",label:d.settings.followSystem}];return a.jsxs("div",{className:"relative flex min-h-full items-center justify-center overflow-hidden p-4",children:[a.jsx(MV,{}),a.jsxs("div",{className:"absolute right-4 top-4 flex flex-col items-end gap-1.5 sm:flex-row sm:items-center sm:gap-2",children:[a.jsx("div",{"aria-label":d.settings.language,children:a.jsx(ws,{options:T,value:s,onChange:o})}),a.jsx("div",{"aria-label":d.settings.theme,children:a.jsx(ws,{options:N,value:t,onChange:n})})]}),a.jsxs("div",{className:"anim-rise relative w-full max-w-sm",children:[a.jsx(OT,{className:"mx-auto mb-3 h-16 w-16 rounded-2xl"}),a.jsx("h1",{className:"mb-6 text-center text-3xl font-semibold tracking-tight",children:d.appName}),a.jsxs("div",{className:"rounded-xl border border-gray-200 bg-white p-6 shadow-sm dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("form",{className:"space-y-4",onSubmit:_=>{_.preventDefault(),C()},children:[a.jsx(at,{label:d.common.username,required:!0,value:u,onChange:_=>{f(_.target.value),S()},error:x.userId,autoComplete:"username",autoFocus:!0}),a.jsx(ts,{label:d.auth.password,required:!0,value:p,onChange:_=>{h(_.target.value),S()},error:x.password,autoComplete:"current-password"}),x.form&&a.jsx("p",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700 dark:border-red-900 dark:bg-red-950/50 dark:text-red-300",children:x.form}),a.jsx(ge,{type:"submit",variant:"primary",className:"w-full justify-center py-2.5 text-sm font-semibold",disabled:v,children:d.auth.login})]}),a.jsx("p",{className:"mt-4 text-center text-xs text-gray-400 dark:text-gray-500",children:d.auth.defaultAdminNote}),a.jsx("p",{className:"mt-1.5 text-center text-xs text-gray-400 dark:text-gray-500",children:d.auth.forgotAdminNote})]})]})]})}const tu=100,Ni=30,Da=2;function AV({data:e,label:t,className:n=""}){const s=Math.max(1,...e),o=e.length>1?(tu-2*Da)/(e.length-1):0,c=e.map((h,x)=>[Da+x*o,Ni-Da-h/s*(Ni-2*Da)]),u=`${Da},${Ni-Da} ${tu-Da},${Ni-Da}`,f=c.length>1?c.map(([h,x])=>`${h},${x}`).join(" "):u,p=c.length>1?`${f} ${tu-Da},${Ni-Da} ${Da},${Ni-Da}`:null;return a.jsxs("svg",{width:tu,height:Ni,viewBox:`0 0 ${tu} ${Ni}`,role:"img","aria-label":t,className:`text-emerald-600 dark:text-emerald-500 ${n}`,children:[a.jsx("title",{children:t}),p!==null&&a.jsx("polygon",{points:p,fill:"currentColor",fillOpacity:"0.12"}),a.jsx("polyline",{points:f,fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]})}const px="inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-gray-300 bg-white px-2.5 py-1 text-xs font-medium text-gray-800 transition-colors duration-150 hover:bg-gray-50 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800",LM=".tar.gz,.tgz,.gz,application/gzip,application/x-gzip";function OM(e){return new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{const o=s.result;t(o.slice(o.indexOf(",")+1))},s.onerror=()=>n(s.error??new Error("File read failed.")),s.readAsDataURL(e)})}function _V(e){return e.replace(/\.(tar\.gz|tgz|gz)$/i,"").replace(/-v\d+$/,"")}const RV=new Set(["default_agent"]),Gs={newChat:"M12 5v14M5 12h14",trash:"M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6",sessions:"M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",vaultKeys:"M15.5 7.5l3 3L22 7l-3-3M21 2l-9.6 9.6M13 15.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z",schedules:"M12 21a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm0-10v3l2 1.5M5 3L2.5 5.5M19 3l2.5 2.5",skills:"M12 6.5C10.5 5 8 4.5 4 5v12c4-.5 6.5 0 8 1.5 1.5-1.5 4-2 8-1.5V5c-4-.5-6.5 0-8 1.5zm0 0V18",usage:"M4 20V10m6 10V4m6 16v-7m4 7H2",memory:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18ZM12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18ZM15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"},nu="inline-flex shrink-0 cursor-pointer items-center gap-1 tabular-nums transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200";function IV(){const e=yr();Li(d.nav.agents);const{locale:t}=Dr(),{user:n}=mn(),{currentProject:s,agents:o,agentsLoading:c,reloadAgents:u,setCurrentAgentId:f}=en(),[p,h]=y.useState(!1),[x,g]=y.useState(""),[v,w]=y.useState(""),[S,C]=y.useState(""),[N,T]=y.useState(void 0),[_,R]=y.useState(!1),[D,z]=y.useState(null),[E,L]=y.useState(null),F=y.useRef(!1),[V,P]=y.useState([]),[B,Y]=y.useState(!1),[q,K]=y.useState(""),[H,$]=y.useState(null),[X,le]=y.useState(null),[ie,I]=y.useState([]),[A,Q]=y.useState(!1),[j,U]=y.useState(null),ee=()=>{g(""),w(""),C(""),T(void 0),P([]),Y(!1),K(""),$(null),le(null),I([]),Q(!1),U(null),h(!0)},re=oe=>{const J=oe.target.files?.[0];if(oe.target.value="",!!J&&(U(J),P([]),K(""),I([]),!x.trim())){const ht=_V(J.name);mx.test(ht)&&g(ht)}};y.useEffect(()=>{!p||D!==null||F.current||(F.current=!0,L(null),oC().then(oe=>z(oe.groups.flatMap(J=>J.skills))).catch(oe=>{F.current=!1,L(Ae(oe))}))},[p,D]);const ke=$r(),be=ke.state?.create===!0;y.useEffect(()=>{be&&(ee(),e(ke.pathname,{replace:!0}))},[be]);const[ye,Se]=y.useState(null),[Me,ze]=y.useState(null),De=s?.projectId;y.useEffect(()=>{if(!p||!q||!De){$(null),le(null);return}let oe=!1;return $(null),le(null),KE(De,q).then(J=>{oe||$(J.skills)}).catch(J=>{oe||($(null),le(Ae(J)))}),()=>{oe=!0}},[p,De,q]),y.useEffect(()=>{if(H===null){I(J=>J.length===0?J:[]);return}const oe=new Set(H.map(J=>J.name));I(J=>{const ht=J.filter(ve=>oe.has(ve));return ht.length===J.length?J:ht})},[H]);const ct=async()=>{if(!De)return;const oe=x.trim();if(!oe){T(d.common.requiredField);return}if(!mx.test(oe)){T(d.agent.idHint);return}R(!0),T(void 0);try{const J={agentId:oe};v.trim()&&(J.name=v.trim()),S.trim()&&(J.description=S.trim()),j!==null?J.dataBase64=await OM(j):(V.length>0&&(J.skills=V),q&&ie.length>0&&(J.skillsDirectory=q,J.directorySkills=ie));const ht=await FE(De,J);h(!1),await u(),f(ht.agent.agentId),e(`/agents/${ht.agent.agentId}`)}catch(J){T(Ae(J))}finally{R(!1)}},bt=oe=>{n&&De&&Yl(n.userId,De),f(oe),e(`/chat/${ya}`,{state:{agentId:oe}})},he=(oe,J)=>{f(oe),e(`/agents/${oe}?tab=${J}`)},ne=async()=>{if(!(!De||!ye)){R(!0),ze(null);try{await kA(De,ye.agentId),Se(null),await u()}catch(oe){ze(Ae(oe))}finally{R(!1)}}};return a.jsxs("div",{className:"h-full overflow-y-auto p-4 md:p-6",children:[a.jsxs("div",{className:"mx-auto max-w-5xl",children:[a.jsxs("div",{className:"mb-4 flex items-center justify-between gap-2",children:[a.jsx("h1",{className:"text-xl font-semibold",children:d.agent.listTitle}),a.jsx(ge,{variant:"primary",onClick:ee,children:d.agent.create})]}),c?a.jsx("div",{className:"space-y-3",children:Array.from({length:4},(oe,J)=>a.jsxs(SN,{className:"flex flex-wrap items-center gap-x-6 gap-y-2 px-5 py-4",children:[a.jsxs("div",{className:"min-w-[14rem] flex-1",children:[a.jsx(on,{className:"h-[18px] w-40"}),a.jsx(on,{className:"mt-1.5 h-4 w-2/3"}),a.jsx(on,{className:"mt-1.5 h-4 w-48"})]}),a.jsx(on,{className:"hidden h-9 w-40 md:block"}),a.jsx(on,{className:"h-8 w-52"})]},J))}):o.length===0?a.jsx(Fa,{title:d.common.none}):a.jsx("div",{className:"space-y-3",children:o.map(oe=>{const J=RV.has(oe.agentId);return a.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 rounded-md border border-gray-200 bg-white px-5 py-4 dark:border-gray-800 dark:bg-gray-900",children:[a.jsxs("div",{className:"min-w-[14rem] flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ha,{id:oe.agentId,name:_n(oe),size:18,className:"shrink-0 rounded"}),a.jsx("span",{className:"min-w-0 truncate text-base font-bold",children:_n(oe)}),a.jsx("span",{className:"hidden shrink-0 font-mono text-xs text-gray-400 md:inline dark:text-gray-500",children:oe.agentId}),a.jsxs(On,{tone:"gray",children:["v",oe.version]}),oe.kernelOutdated&&a.jsx(OI,{onClick:()=>he(oe.agentId,"overview"),children:d.agent.kernelUpdateNeeded})]}),a.jsx("p",{className:"mt-1.5 min-h-4 truncate text-xs text-gray-500 dark:text-gray-400",children:oe.description??""}),a.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-500 dark:text-gray-400",children:[a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1 tabular-nums",title:d.agent.sessionCount(oe.sessionCount),children:[a.jsx(Oe,{d:Gs.sessions,size:Ye.inlineGlyph}),oe.sessionCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.toolCount(oe.toolCount),"aria-label":d.agent.toolCount(oe.toolCount),onClick:()=>he(oe.agentId,"tools"),children:[a.jsx(Oe,{d:Xn.toolCalls,size:Ye.inlineGlyph}),oe.toolCount]}),a.jsxs("button",{type:"button",className:nu,title:d.skills.skillCount(oe.skillCount),"aria-label":d.skills.skillCount(oe.skillCount),onClick:()=>he(oe.agentId,"skills"),children:[a.jsx(Oe,{d:Gs.skills,size:Ye.inlineGlyph}),oe.skillCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.memoryCount(oe.memoryCount),"aria-label":d.agent.memoryCount(oe.memoryCount),onClick:()=>he(oe.agentId,"memory"),children:[a.jsx(Oe,{d:Gs.memory,size:Ye.inlineGlyph}),oe.memoryCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.vaultKeyCount(oe.vaultKeyCount),"aria-label":d.agent.vaultKeyCount(oe.vaultKeyCount),onClick:()=>he(oe.agentId,"vault"),children:[a.jsx(Oe,{d:Gs.vaultKeys,size:Ye.inlineGlyph}),oe.vaultKeyCount]}),a.jsxs("button",{type:"button",className:nu,title:d.agent.scheduleCount(oe.scheduleCount),"aria-label":d.agent.scheduleCount(oe.scheduleCount),onClick:()=>he(oe.agentId,"schedules"),children:[a.jsx(Oe,{d:Gs.schedules,size:Ye.inlineGlyph}),oe.scheduleCount]}),a.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",title:`${d.agent.updatedAt} ${oe.updatedAt?Jr(oe.updatedAt):"—"}`,children:[a.jsx(Oe,{d:Xn.elapsed,size:Ye.inlineGlyph}),oe.updatedAt?$I(oe.updatedAt,t):"—"]})]})]}),a.jsx(AV,{data:oe.sessionActivity,label:d.agent.activity(oe.sessionActivity.length||30),className:"hidden shrink-0 md:block"}),a.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[a.jsxs(ge,{size:"sm",variant:"primary",onClick:()=>bt(oe.agentId),children:[a.jsx(Oe,{d:Gs.newChat}),d.chat.newSessionMenu]}),a.jsxs(ge,{size:"sm",onClick:()=>{f(oe.agentId),e(`/agents/${oe.agentId}`)},children:[a.jsx(Oe,{d:If}),d.common.settings]}),a.jsx(ge,{size:"icon",title:d.nav.usage,"aria-label":d.nav.usage,onClick:()=>e(`/usage?agentId=${encodeURIComponent(oe.agentId)}`),children:a.jsx(Oe,{d:Gs.usage,size:15,className:"text-gray-600 dark:text-gray-300"})}),J?a.jsx("span",{role:"img",title:d.agent.builtinUndeletable,"aria-label":d.agent.builtinUndeletable,className:"inline-flex cursor-not-allowed items-center justify-center rounded-md border border-transparent p-1.5 text-gray-300 dark:text-gray-600",children:a.jsx(Oe,{d:Gs.trash,size:15})}):a.jsx(ge,{size:"icon",variant:"danger",title:d.agent.deleteAgent,"aria-label":d.agent.deleteAgent,onClick:()=>Se({agentId:oe.agentId,name:_n(oe)}),children:a.jsx(Oe,{d:Gs.trash,size:15})})]})]},oe.agentId)})})]}),a.jsx(Yt,{open:p,title:d.agent.createTitle,onClose:()=>h(!1),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>h(!1),children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:_,onClick:()=>{ct()},children:d.common.create})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{label:d.agent.id,required:!0,size:"sm",value:x,onChange:oe=>{g(oe.target.value),T(void 0)},error:N,hint:d.agent.idHint,autoFocus:!0}),a.jsx(at,{label:d.common.name,size:"sm",value:v,onChange:oe=>w(oe.target.value),hint:d.agent.nameHint}),a.jsx(ir,{label:d.agent.description,size:"sm",rows:3,value:S,onChange:oe=>C(oe.target.value)}),a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createSnapshot}),j===null?a.jsxs("label",{className:`${px} ${_?"pointer-events-none opacity-60":""}`,children:[a.jsx(Xl,{accept:LM,disabled:_,onChange:re}),d.agent.createSnapshotPick]}):a.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[a.jsx("span",{className:"min-w-0 truncate rounded-md border border-gray-300 bg-gray-50 px-2.5 py-1 font-mono text-xs dark:border-gray-700 dark:bg-gray-900",children:j.name}),a.jsx("button",{type:"button",title:d.agent.createSnapshotClear,"aria-label":d.agent.createSnapshotClear,disabled:_,onClick:()=>U(null),className:"shrink-0 rounded-md p-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:hover:text-gray-300",children:a.jsx(Hl,{size:12})})]}),a.jsx(wo,{children:j===null?d.agent.createSnapshotHint:d.agent.createSnapshotSkillsOff})]}),j===null&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createSkills}),a.jsx(Ru,{open:B,setOpen:Y,label:V.length===0?d.agent.createSkillsPlaceholder:d.agent.createSkillsPicked(V.length),muted:V.length===0,title:d.agent.createSkills,ariaLabel:d.agent.createSkills,disabled:_,menuClass:"w-[26rem]",children:a.jsx(q0,{skills:D??[],selected:V,onToggle:oe=>P(J=>V0(J,oe)),onSelectAll:oe=>P(J=>LS(J,oe)),onSelectNone:oe=>P(J=>OS(J,oe)),emptyHint:D===null?d.common.loading:d.agent.createSkillsEmpty})}),E?a.jsx(ga,{children:E}):a.jsx(wo,{children:d.agent.createSkillsHint})]}),a.jsxs("div",{children:[a.jsx(Yn,{children:d.agent.createDirSkills}),a.jsx(sd,{projectId:De??"",workspace:q,onChange:K,variant:"form",fieldLabel:d.agent.createDirSkills,emptyLabel:d.agent.createDirSkillsPick,menuHint:d.agent.createDirSkillsHint,clearLabel:d.agent.createDirSkillsClear}),q&&H!==null&&H.length>0&&a.jsx("div",{className:"mt-2",children:a.jsx(Ru,{open:A,setOpen:Q,label:ie.length===0?d.agent.createSkillsPlaceholder:d.agent.createSkillsPicked(ie.length),muted:ie.length===0,title:d.agent.createDirSkills,ariaLabel:d.agent.createDirSkills,disabled:_,menuClass:"w-[26rem]",children:a.jsx(q0,{skills:H,selected:ie,onToggle:oe=>I(J=>V0(J,oe)),onSelectAll:oe=>I(J=>LS(J,oe)),onSelectNone:oe=>I(J=>OS(J,oe)),emptyHint:d.agent.createDirSkillsEmpty})})}),X?a.jsx(ga,{children:X}):a.jsx(wo,{children:q?H===null?d.common.loading:H.length===0?d.agent.createDirSkillsEmpty:d.agent.createDirSkillsFound(H.length):d.agent.createDirSkillsHint})]})]})]})}),a.jsxs(ln,{open:ye!==null,title:d.agent.deleteAgent,busy:_,onClose:()=>{Se(null),ze(null)},onConfirm:()=>{ne()},children:[a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:ye?d.agent.deleteConfirm(ye.name):""}),Me&&a.jsx("p",{className:"mt-2 text-xs text-red-600 dark:text-red-400",children:Me})]})]})}function LV({items:e,active:t,onChange:n}){return a.jsx("div",{role:"tablist",className:"flex max-w-full gap-1 overflow-x-auto overflow-y-hidden border-b border-gray-200 dark:border-gray-800",children:e.map(s=>{const o=s.badge??null;return a.jsxs("button",{type:"button",role:"tab","aria-selected":s.key===t,...o!==null?{title:o,"aria-label":`${s.label} · ${o}`}:{},onClick:()=>n(s.key),className:`relative -mb-px whitespace-nowrap border-b-2 px-3 py-2 text-sm transition-colors duration-150 ${s.key===t?"border-gray-900 font-semibold text-gray-900 dark:border-gray-100 dark:text-gray-100":"border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-800 dark:text-gray-400 dark:hover:border-gray-700 dark:hover:text-gray-200"}`,children:[s.label,o!==null&&a.jsx(Mo,{size:"inline",position:"right-1 top-1"})]},s.key)})})}const OV=288,DV={base:"text-base",sm:"text-xs"},$V={base:"text-xs",sm:"text-[11px]"};function Sf({options:e,value:t,onChange:n,placeholder:s,mono:o,label:c,error:u,required:f,fullWidth:p,size:h="base","aria-label":x}){const[g,v]=y.useState(!1),{triggerRef:w,panelRef:S,position:C}=$f({open:g,onClose:()=>v(!1),estimatedHeight:e.length*48+16,panelWidth:OV}),N=t!=null?e.find(R=>R.value===t):void 0,T=y.useId(),_=a.jsxs(a.Fragment,{children:[a.jsxs("button",{ref:w,type:"button","aria-label":x,"aria-haspopup":"listbox","aria-expanded":g,"aria-required":f||void 0,"aria-invalid":u?!0:void 0,"aria-describedby":u?T:void 0,onClick:()=>v(R=>!R),className:`flex items-center gap-2 ${Uf} ${Pf[h]} ${u?zf:""}`+(p?" w-full justify-between":""),children:[a.jsx("span",{className:`min-w-0 truncate ${o?"font-mono":""}`,children:N?.triggerLabel??s??"—"}),a.jsx(ns,{className:"text-gray-400"})]}),g&&C&&ss.createPortal(a.jsx("div",{ref:S,role:"listbox",style:{position:"fixed",top:C.topPx,bottom:C.bottomPx,left:C.left,minWidth:C.triggerWidth},className:"anim-pop z-[60] max-h-[70vh] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900",children:e.map(R=>a.jsxs("button",{type:"button",role:"option","aria-selected":R.value===t,onClick:()=>{n(R.value),v(!1)},className:`block ${ny} hover:bg-gray-100 dark:hover:bg-gray-800 ${R.value===t?"bg-gray-100 dark:bg-gray-800":""}`,children:[a.jsxs("span",{className:"flex items-center justify-between gap-2",children:[a.jsx("span",{className:`${DV[h]} ${R.value===t?"font-medium text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"}`,children:R.label}),R.value===t&&a.jsx(qu,{className:"text-gray-500 dark:text-gray-400"})]}),a.jsx("span",{className:`mt-0.5 block ${$V[h]} text-gray-500 dark:text-gray-400`,children:R.description})]},R.value))}),document.body)]});return a.jsx(Vu,{label:c,error:u,errorId:T,required:f,children:_})}const UV=/^(www\.)?(github|gitlab|gitee|bitbucket)\.(com|org)$/i;function PV(e){const t=e.trim();if(/^git@[\w.-]+:/.test(t)||/\.git$/i.test(t))return"repoUrl";if(/^https?:\/\//i.test(t)){try{if(UV.test(new URL(t).hostname))return"repoUrl"}catch{}return"webUrl"}return/^(\/|~\/|\.{1,2}\/|[A-Za-z]:[\\/]|\\\\)/.test(t)?"localPath":/^[A-Za-z@][\w@./-]*\s+\S/.test(t)?"command":"reference"}function t0(e){return`${d.skills.importPromptLead[PV(e)](e)}
|
|
181
181
|
${d.skills.importPromptTail}`}function zV(e,t,n,s){const o=e.current;if(o&&(o.focus(),document.execCommand?.("insertText",!1,s)))return;const c=o?o.selectionStart:t.length,u=o?o.selectionEnd:t.length;n(t.slice(0,c)+s+t.slice(u)),requestAnimationFrame(()=>{if(!o)return;o.focus();const f=c+s.length;o.setSelectionRange(f,f)})}function Zy({agentId:e,feature:t,strings:n,canEdit:s,onConfigChanged:o}){const{currentProject:c}=en(),u=c?.projectId??null,[f,p]=y.useState(null),[h,x]=y.useState(""),[g,v]=y.useState(!1),w=y.useRef(null),{requestSave:S,element:C}=ql(),N=y.useCallback(V=>{const P=V[t];p(P),x(P.prompt)},[t]),T=V=>t==="skills"?{config:{skills:V}}:t==="vault"?{config:{vault:V}}:{config:{schedules:V}},_=async V=>{if(u){v(!0);try{const P=await To(u,e,T({enabled:V}));N(P.config),yt(d.common.saved),o?.()}catch(P){Be(Ae(P))}finally{v(!1)}}},R=async()=>{if(!u)return;const V=t==="skills"?$E:t==="vault"?DE:UE;try{const P=await V(u,e);p(P),x(P.prompt),yt(d.common.saved),o?.()}catch(P){Be(Ae(P))}},D=()=>S(()=>{u&&To(u,e,T({prompt:h})).then(V=>{N(V.config),yt(d.common.saved),o?.()}).catch(V=>Be(Ae(V)))}),z=f!==null&&a.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("p",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:n.enable}),a.jsx(js,{checked:f.enabled,onChange:V=>{_(V)},disabled:g||!s})]}),E=f?.legacySectionPresent===!0,L=f!==null&&!f.templateHasPlaceholder&&a.jsxs("div",{className:`flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${Df.attention}`,children:[a.jsx("p",{className:"text-xs",children:E?n.legacyTemplate??n.templateMissing:n.templateMissing}),s&&a.jsx(ge,{size:"sm",className:"shrink-0",onClick:()=>{R()},children:E?n.migrate??n.insertPlaceholder:n.insertPlaceholder})]}),F=f!==null&&a.jsxs("section",{className:"space-y-2.5 rounded-lg border border-gray-200 p-3.5 dark:border-gray-800",children:[a.jsxs("h3",{className:"flex items-center gap-1.5 text-sm font-semibold text-gray-800 dark:text-gray-200",children:[n.promptSection,a.jsx(ba,{label:n.promptSection,children:n.promptSectionHint})]}),a.jsx(ir,{ref:w,label:n.promptLabel,mono:!0,size:"sm",rows:12,readOnly:!s,value:h,onChange:V=>x(V.target.value)}),a.jsxs("div",{className:"rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("p",{className:"mb-2 text-xs font-semibold text-gray-500",children:d.agent.placeholdersTitle}),a.jsx("ul",{className:"space-y-1",children:n.promptPlaceholders.map(([V,P])=>a.jsxs("li",{className:"flex items-center gap-3 text-xs",children:[a.jsx("button",{type:"button",disabled:!s,onClick:()=>zV(w,h,x,V),title:d.memory.insertToken,className:"shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 disabled:pointer-events-none dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700",children:V}),a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:P})]},V))})]}),s&&a.jsx("div",{className:"flex justify-end",children:a.jsx(ge,{size:"sm",variant:"primary",onClick:D,children:d.common.save})}),C]});return{applyConfig:N,toggleCard:z,alertStrip:L,promptSection:F}}const BV="inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-gray-300 bg-white px-2.5 py-1 text-xs font-medium text-gray-800 transition-colors duration-150 hover:bg-gray-50 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800",HV="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6";function FV({agentId:e,onConfigChanged:t}){const n=yr(),{locale:s}=Dr(),o=mn().user?.userId??null,{currentProject:c,agents:u,setCurrentAgentId:f,reloadAgents:p}=en(),h=c?.projectId??null,{applyConfig:x,toggleCard:g,alertStrip:v,promptSection:w}=Zy({agentId:e,feature:"skills",strings:d.skills.injection,canEdit:!0,onConfigChanged:t}),[S,C]=y.useState(null),[N,T]=y.useState(null),[_,R]=y.useState(!1),[D,z]=y.useState(null),[E,L]=y.useState(!1),[F,V]=y.useState(""),[P,B]=y.useState(!1),[Y,q]=y.useState(null),[K,H]=y.useState(null),$=y.useCallback(async()=>{if(!(!h||!e)){C(null),T(null);try{const[ye,Se]=await Promise.all([Bu(h,e),Ao(h,e)]);C(ye.skills),x(Se.config)}catch(ye){T(Ae(ye))}}},[h,e,x]);y.useEffect(()=>{$()},[$]);const X=u.find(ye=>ye.agentId===e),le=X?_n(X):e,ie=async ye=>{if(h)try{const Se=await fetch(EA(h,e,ye));if(!Se.ok){const ct=await Se.json().catch(()=>null);throw new xr(Se.status,ct?.error?.code??"unknown",ct?.error?.message??d.common.unknownError)}const Me=/filename\*=UTF-8''([^;]+)/i.exec(Se.headers.get("content-disposition")??"")?.[1],ze=URL.createObjectURL(await Se.blob()),De=document.createElement("a");De.href=ze,De.download=Me?decodeURIComponent(Me):`${ye}.zip`,document.body.appendChild(De),De.click(),De.remove(),URL.revokeObjectURL(ze)}catch(Se){Be(Ae(Se))}},I=async()=>{if(!(!h||D===null)){R(!0);try{await lC(h,e,D),yt(d.skills.uninstalledToast(D,le)),await $(),p()}catch(ye){Be(Ae(ye))}finally{R(!1),z(null)}}},A=()=>{V(""),q(null),H(null),L(!0)},Q=F.trim(),j=t0(Q||d.skills.importSourceToken),U=lf(),ee=()=>{if(o&&h&&Q){Yl(o,h);const ye=ks(o,h);Qs(ye,{...$i(ye),agentId:e,text:t0(Q),skills:[],handoffAgentId:void 0})}f(e),n(`/chat/${ya}`,{state:{agentId:e}})},re=async(ye,Se,Me)=>{if(h){B(!0),q(null);try{await MA(h,e,{dataBase64:ye,...Me?{overwrite:!0}:{}}),H(null),L(!1),yt(d.skills.importDoneToast),await $(),p()}catch(ze){if(ze instanceof xr&&ze.status===409&&ze.code==="skill_exists"){const De=/:\s*([A-Za-z0-9_-]+)$/.exec(ze.message)?.[1]??Se;H({dataBase64:ye,name:De})}else H(null),q(Ae(ze))}finally{B(!1)}}},ke=ye=>{const Se=ye.target.files?.[0];if(ye.target.value="",!Se)return;q(null);const Me=Se.name.replace(/\.zip$/i,""),ze=new FileReader;ze.onload=()=>{const De=ze.result;re(De.slice(De.indexOf(",")+1),Me,!1)},ze.onerror=()=>q(d.common.unknownError),ze.readAsDataURL(Se)},be=ye=>[`v${ye.version}`,ye.updated?Al(ye.updated,s):null].filter(Se=>Se!==null).join(" · ");return h?a.jsxs("div",{className:"space-y-4",children:[a.jsx(Co,{label:d.agent.tabSkills,children:d.skills.agentTabDesc}),g,v,a.jsx("div",{className:"flex justify-end",children:a.jsx(ge,{size:"sm",variant:"primary",disabled:S===null,onClick:A,children:d.skills.importSkill})}),S===null?a.jsx(Sr,{rows:4}):S.length===0?a.jsx(Ff,{children:d.skills.agentTabEmpty}):a.jsx("div",{className:"overflow-hidden rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:S.map(ye=>a.jsxs("div",{className:"flex items-center gap-3 border-b border-gray-100 px-3 py-2.5 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40",children:[a.jsx("span",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${hT(ye.name)}`,children:a.jsx(Yf,{icon:ye.icon,size:20})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("span",{className:"block truncate font-mono text-[13px] font-semibold",title:ye.name,children:ye.name}),a.jsx("p",{className:"mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400",title:ye.description,children:Wl(s,ye)})]}),a.jsx("span",{className:"hidden shrink-0 text-[11px] text-gray-400 sm:block dark:text-gray-500",title:be(ye),children:be(ye)}),a.jsx(ge,{size:"icon",title:d.skills.exportSkill,"aria-label":`${d.skills.exportSkill} ${ye.name}`,disabled:_,onClick:()=>{ie(ye.name)},children:a.jsx(Hx,{size:14,className:"text-gray-600 dark:text-gray-300"})}),a.jsx(ge,{size:"icon",variant:"danger",title:d.skills.uninstall,"aria-label":`${d.skills.uninstall} ${ye.name}`,disabled:_,onClick:()=>z(ye.name),children:a.jsx(Oe,{d:HV,size:14})})]},ye.name))}),w,a.jsx(Yt,{open:E,title:d.skills.importSkill,onClose:()=>L(!1),widthClass:"sm:max-w-lg",children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("section",{children:[a.jsx("p",{className:"text-sm font-medium",children:d.skills.importChatTitle}),a.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:d.skills.importChatWhy}),a.jsxs("div",{className:"mt-2.5 space-y-2.5",children:[a.jsx(at,{size:"sm",label:d.skills.importSourceLabel,hint:d.skills.importSourceHint,value:F,onChange:ye=>V(ye.target.value),placeholder:d.skills.importSourcePlaceholder,autoComplete:"off"}),a.jsx(ir,{label:d.skills.importPromptLabel,size:"sm",rows:5,readOnly:!0,value:j,className:"text-gray-600 dark:text-gray-300"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(ge,{size:"sm",disabled:Q==="",onClick:()=>U.flash(t0(Q)),children:[a.jsx(cf,{copied:U.copied,size:12}),d.skills.importCopyPrompt]}),a.jsx(uf,{copied:U.copied}),a.jsx(ge,{size:"sm",variant:"primary",onClick:ee,children:d.skills.importOpenChat})]})]})]}),a.jsxs("section",{className:"border-t border-gray-200 pt-4 dark:border-gray-800",children:[a.jsx("p",{className:"text-sm font-medium",children:d.skills.importUploadTitle}),a.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:d.skills.importUploadDesc}),a.jsxs("label",{className:`${BV} mt-2.5 ${P?"pointer-events-none opacity-60":""}`,children:[a.jsx(Xl,{accept:".zip",disabled:P,onChange:ke}),P?d.skills.importUploading:d.skills.importUploadAction]}),Y&&a.jsx("p",{className:"mt-1.5 text-xs text-red-600 dark:text-red-400",children:Y})]})]})}),a.jsx(ln,{open:K!==null,title:d.skills.importOverwriteTitle,confirmLabel:d.skills.importOverwriteAction,busy:P,onClose:()=>H(null),onConfirm:()=>{K!==null&&re(K.dataBase64,K.name,!0)},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:K!==null?d.skills.importOverwriteBody(K.name):""})}),a.jsx(ln,{open:D!==null,title:D!==null?d.skills.uninstallConfirmTitle(D):"",busy:_,onClose:()=>z(null),onConfirm:()=>{I()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:D!==null?d.skills.uninstallConfirmBody(D,le):""})}),N&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:N})]}):null}const hx={damping:1,response:.35},rj={damping:.8,response:.3};function qV(e,t,n,s,o){const c=2*Math.PI/s.response,u=c*c,f=2*s.damping*c;let p=e,h=t,x=Math.min(o,64);for(;x>0;){const g=Math.min(x,8)/1e3,v=-u*(p-n)-f*h;h+=v*g,p+=h*g,x-=8}return[p,h]}function aj(e,t,n){return Math.abs(e-n)<.5&&Math.abs(t)<5}function VV(e,t){let n=e,s=0,o=e,c=hx,u,f=0,p=0;const h=()=>{f&&cancelAnimationFrame(f),f=0,p=0,u=void 0},x=g=>{const v=p?g-p:16;if(p=g,[n,s]=qV(n,s,o,c,v),aj(n,s,o)){n=o,s=0,f=0,p=0,t(n);const w=u;u=void 0,w?.();return}t(n),f=requestAnimationFrame(x)};return{get value(){return n},get velocity(){return s},animateTo(g,v,w){if(o=g,c=v,w?.velocity!==void 0&&(s=w.velocity),u=w?.onSettle,aj(n,s,o)){n=o,s=0,t(n);const S=u;u=void 0,S?.();return}f||(f=requestAnimationFrame(x))},stop(){return h(),[n,s]},set(g){h(),n=g,s=0,t(n)},dispose:h}}function GV(e,t=.998){return e/1e3*t/(1-t)}function KV(e,t,n=.55){return e*t*n/(t+n*Math.abs(e))}function WV(e,t){let n=t[0];for(const s of t)Math.abs(s-e)<Math.abs(n-e)&&(n=s);return n}const YV=.92,XV=.6;function QV(){const[e,t]=y.useState(()=>window.matchMedia("(prefers-reduced-motion: reduce)").matches);return y.useEffect(()=>{const n=window.matchMedia("(prefers-reduced-motion: reduce)"),s=o=>t(o.matches);return n.addEventListener("change",s),()=>n.removeEventListener("change",s)},[]),e}function ZV({open:e,snap:t,onSnapChange:n,onClose:s,title:o,children:c}){const[u,f]=y.useState(e),p=y.useRef(null),h=y.useRef(null),x=y.useRef(null),g=y.useRef(0),v=y.useRef(!1),w=y.useRef(!1),S=y.useRef(null),C=y.useRef([]),N=y.useRef({pointerY:0,sheetY:0}),T=y.useRef(e);T.current=e;const _=y.useRef(null),R=QV(),D=y.useCallback(B=>{const Y=g.current||1;p.current&&(p.current.style.transform=`translate3d(0, ${B}px, 0)`),h.current&&(h.current.style.opacity=String(Math.min(1,Math.max(0,1-B/Y))))},[]),z=y.useCallback(B=>{const Y=g.current;return B==="full"?0:Y*(1-XV/YV)},[]);y.useEffect(()=>{e&&f(!0)},[e]),y.useLayoutEffect(()=>{if(!u)return;const B=p.current;B&&(g.current=B.offsetHeight,x.current||(x.current=VV(g.current,D),x.current.set(g.current)))},[u,D]),y.useEffect(()=>{if(!u)return;const B=x.current;if(B)if(e){if(w.current=!1,v.current)return;const Y=z(t);if(S.current!==null&&Math.abs(S.current-Y)<1)return;if(S.current=Y,R){B.set(Y);return}B.animateTo(Y,hx)}else{if(w.current=!0,S.current=g.current,R){f(!1);return}B.animateTo(g.current,hx,{onSettle:()=>f(!1)})}},[u,e,t,R,z]),y.useEffect(()=>{u||(x.current?.dispose(),x.current=null,S.current=null,v.current=!1,w.current=!1)},[u]),y.useEffect(()=>()=>x.current?.dispose(),[]),y.useEffect(()=>{if(!u)return;const B=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=B}},[u]),y.useEffect(()=>{if(!u||!e)return;const B=Y=>{Y.key==="Escape"&&s()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[u,e,s]),y.useEffect(()=>{if(u)return _.current=document.activeElement instanceof HTMLElement?document.activeElement:null,()=>_.current?.focus()},[u]),y.useEffect(()=>{if(!u)return;const B=()=>{const Y=p.current;if(!Y||(g.current=Y.offsetHeight,v.current||w.current))return;const q=z(t);S.current=q,x.current?.set(q)};return window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[u,t,z]);const E=B=>{if(w.current)return;const Y=x.current;if(!Y)return;B.currentTarget.setPointerCapture(B.pointerId);const[q]=Y.stop();v.current=!0,N.current={pointerY:B.clientY,sheetY:q},C.current=[{y:B.clientY,t:performance.now()}]},L=B=>{if(!v.current)return;const Y=x.current;if(!Y)return;const q=N.current.sheetY+(B.clientY-N.current.pointerY),K=g.current,H=q<0?-KV(-q,K):Math.min(q,K);Y.set(H);const $=performance.now(),X=C.current;for(X.push({y:B.clientY,t:$});X.length>2&&$-X[0].t>100;)X.shift()},F=B=>{v.current=!1;const Y=x.current;if(!Y)return;const q=g.current,K=z("half"),H=T.current?Y.value+GV(B):q,$=WV(H,[0,K,q]);if(S.current=$,$===q){if(w.current=!0,R){f(!1),s();return}Y.animateTo(q,rj,{velocity:B,onSettle:()=>{f(!1),s()}});return}Y.animateTo($,rj,{velocity:B});const X=$===0?"full":"half";X!==t&&n?.(X)},V=()=>{if(!v.current)return;const B=C.current,Y=B[B.length-1],q=B[0],K=Y&&q?Y.t-q.t:0;F(K>0?(Y.y-q.y)/K*1e3:0)},P=()=>{v.current&&F(0)};return u?a.jsxs("div",{className:"fixed inset-0 z-50",role:"dialog","aria-modal":"true","aria-label":o,children:[a.jsx("div",{ref:h,className:`absolute inset-0 bg-black/45 ${R?"anim-fade":""}`,style:{opacity:0},onPointerDown:()=>s()}),a.jsxs("div",{ref:p,className:`absolute inset-x-0 bottom-0 flex h-[92dvh] flex-col overflow-hidden rounded-t-2xl border-t border-gray-200 bg-white shadow-2xl dark:border-gray-800 dark:bg-gray-900 ${R?"anim-fade":""}`,style:{transform:"translate3d(0, 100%, 0)"},children:[a.jsxs("div",{className:"shrink-0 cursor-grab touch-none select-none active:cursor-grabbing",onPointerDown:E,onPointerMove:L,onPointerUp:V,onPointerCancel:P,onLostPointerCapture:P,children:[a.jsx("div",{className:"mx-auto mt-2 h-1 w-9 rounded-full bg-gray-300 dark:bg-gray-600"}),a.jsxs("div",{className:"flex items-center justify-between px-4 pb-2 pt-1.5",children:[a.jsx("span",{className:"text-base font-semibold",children:o??""}),a.jsx(Rf,{onClose:s,onPointerDown:B=>B.stopPropagation()})]})]}),a.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain pb-[env(safe-area-inset-bottom)]",children:c})]})]}):null}function JV(e,t=""){const n=`${d.memory.editPromptLead(e)}
|
|
182
182
|
${d.memory.editPromptTail}`,s=t.trim();return s.length>0?`${n}${s}`:n}function eG(e,t){return`${d.memory.addPromptLead[e]}
|
|
183
183
|
${t.trim()}`}const tG="penguin-memory-scope",nG=1;class yl extends Error{constructor(t){super(t),this.name="MemoryDocumentError"}}function rG(e){if(e===null||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.content=="string"}function aG(e){let t;try{t=JSON.parse(e)}catch{throw new yl(d.memory.importInvalidFile)}if(t===null||typeof t!="object"||Array.isArray(t))throw new yl(d.memory.importInvalidFile);const n=t;if(n.format!==tG||n.version!==nG)throw new yl(d.memory.importInvalidFile);if(!Array.isArray(n.files)||!n.files.every(rG))throw new yl(d.memory.importInvalidFile);if(n.files.length===0&&typeof n.index!="string")throw new yl(d.memory.importEmptyFile);return n}function sG(e,t,n){const s=new Set(t.names),o=new Set(e.files.map(g=>g.name)),c=e.files.filter(g=>s.has(g.name)).map(g=>g.name),u=e.files.filter(g=>!s.has(g.name)).map(g=>g.name),f=n==="skip"?[]:c,p=n==="skip"?c:[],h=n==="replace"?[...s].filter(g=>!o.has(g)):[],x=n==="replace"&&t.hasIndex&&e.index!==null;return{added:u,overwritten:f,skipped:p,removed:h,replacesIndex:x,destroys:f.length>0||h.length>0||x}}function iG(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return null;const n=s=>String(s).padStart(2,"0");return`${t.getFullYear()}${n(t.getMonth()+1)}${n(t.getDate())}-${n(t.getHours())}${n(t.getMinutes())}`}function oG(e,t,n){const s=iG(n);return s===null?`${e}-${t}-memory.json`:`${e}-${t}-memory-${s}.json`}const sj="(min-width: 1024px)",lG="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7-10-7-10-7zM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z",cG="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z",uG="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m3 0l-1 13a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2L6 7m4 4v6m4-6v6",dG="M12 5v14M5 12h14",mG="inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-transparent px-2.5 py-1 text-xs font-medium text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 focus-within:ring-2 focus-within:ring-gray-400/30 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100",fG=(e,t,n)=>`penguin.memoryCollapsed.${e}.${t}.${n}`;function ij(e){if(!e)return new Set;try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?new Set(t.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function oj(e,t){if(e)try{localStorage.setItem(e,JSON.stringify([...t]))}catch{}}function pG({agentId:e,onConfigChanged:t}){const n=yr(),{locale:s}=Dr(),o=mn().user?.userId??null,{currentProject:c,setCurrentAgentId:u,reloadAgents:f}=en(),p=c?.projectId??null,h=c?.role==="owner",[x,g]=y.useState(!0),[v,w]=y.useState(!0),[S,C]=y.useState(""),[N,T]=y.useState(null),[_,R]=y.useState(null),[D,z]=y.useState(!1),E=o&&p?fG(o,p,e):null,[L,F]=y.useState(()=>ij(E)),[V,P]=y.useState(""),[B,Y]=y.useState(""),q=y.useRef(null),K=y.useRef(null),[H,$]=y.useState("main"),{requestSave:X,element:le}=ql(),[ie,I]=y.useState(!1),[A,Q]=y.useState(null),[j,U]=y.useState(null),[ee,re]=y.useState(""),[ke,be]=y.useState(null),[ye,Se]=y.useState(""),[Me,ze]=y.useState(null),[De,ct]=y.useState("skip"),[bt,he]=y.useState(null),[ne,oe]=y.useState(!1),[J,ht]=y.useState(null),[ve,Xe]=y.useState(()=>window.matchMedia(sj).matches),[Ge,He]=y.useState("half");y.useEffect(()=>{const Te=window.matchMedia(sj),Ie=ut=>Xe(ut.matches);return Te.addEventListener("change",Ie),()=>Te.removeEventListener("change",Ie)},[]),y.useEffect(()=>{F(ij(E))},[E]);const Pe=Te=>{const Ie=new Set(L);Ie.delete(Te)||Ie.add(Te),oj(E,Ie),F(Ie)},W=y.useCallback(async()=>{if(!(!p||!e)){T(null),R(null);try{const[Te,Ie]=await Promise.all([eC(p,e),Ao(p,e)]);P(Ie.config.memory.prompt),Y(Ie.config.memory.workspacePrompt),g(Te.enabled),w(Te.templateHasMemory),C(Te.memoryDir);const ut=new Set(Te.scopes.map(St=>St.scopeKey));F(St=>{const gn=new Set([...St].filter(Nn=>ut.has(Nn)));return gn.size===St.size?St:(oj(E,gn),gn)}),T(await Promise.all(Te.scopes.map(async St=>{try{return{scope:St,files:(await tC(p,e,St.scopeKey)).files}}catch{return{scope:St,files:[]}}})))}catch(Te){R(Ae(Te))}}},[p,e,E]);y.useEffect(()=>{W()},[W]);const me=async Te=>{if(p){z(!0);try{const Ie=await To(p,e,{config:{memory:{enabled:Te}}});g(Ie.config.memory.enabled),yt(d.common.saved),t?.()}catch(Ie){Be(Ae(Ie))}finally{z(!1)}}},Ue=async()=>{if(p)try{const Te=await PE(p,e);w(Te.templateHasMemory),yt(d.memory.insertPlaceholderDone),t?.()}catch(Te){Be(Ae(Te))}},pe=(Te,Ie,ut,St)=>{const gn=Te.current;if(gn&&(gn.focus(),document.execCommand?.("insertText",!1,St)))return;const Nn=gn?gn.selectionStart:Ie.length,Hn=gn?gn.selectionEnd:Ie.length;ut(Ie.slice(0,Nn)+St+Ie.slice(Hn)),requestAnimationFrame(()=>{if(!gn)return;gn.focus();const Dt=Nn+St.length;gn.setSelectionRange(Dt,Dt)})},$e=()=>X(()=>{p&&To(p,e,{config:{memory:{prompt:V,workspacePrompt:B}}}).then(Te=>{P(Te.config.memory.prompt),Y(Te.config.memory.workspacePrompt),yt(d.common.saved),t?.()}).catch(Te=>Be(Ae(Te)))}),nt=async(Te,Ie)=>{if(p)try{const ut=await nC(p,e,Te.scopeKey,Ie.name);He("half"),Q({scope:Te,file:ut.file,content:ut.content}),I(!0)}catch(ut){Be(Ae(ut))}},gt=(Te,Ie)=>`${S}/${Te.scopeKey}/${Ie.name}`,Ke=(Te,Ie)=>{I(!1),re(""),U({scope:Te,file:Ie})},dt=j?JV(j.file.title,ee):"",pt=lf(),wt=(Te,Ie)=>{if(!o||!p)return;const ut=ks(o,p);Qs(ut,{...$i(ut),agentId:e,text:Te,...Ie!==void 0?{workspace:Ie}:{},skills:[],handoffAgentId:void 0}),u(e),n(`/chat/${ya}`,{state:{agentId:e,...Ie!==void 0?{workspace:Ie}:{}}})},st=()=>{j&&wt(dt,j.scope.workspacePath)},Bt=Te=>{Se(""),be(Te)},Sn=ke?eG(ke.kind,ye):"",Dn=lf(),Vt=()=>{ke&&wt(Sn,ke.workspacePath)},ar=async Te=>{if(p)try{const Ie=await BE(p,e,Te.scopeKey),ut=URL.createObjectURL(new Blob([JSON.stringify(Ie,null,2)],{type:"application/json"})),St=document.createElement("a");St.href=ut,St.download=oG(e,Te.scopeKey,Ie.exportedAt),document.body.appendChild(St),St.click(),St.remove(),URL.revokeObjectURL(ut)}catch(Ie){Be(Ae(Ie))}},zn=async(Te,Ie)=>{const ut=Ie.target.files?.[0];if(Ie.target.value="",!!ut)try{const St=aG(await ut.text());ct("skip"),ze({scope:Te,fileName:ut.name,doc:St})}catch(St){Be(St instanceof yl?St.message:d.memory.importInvalidFile)}},Xt=async Te=>{if(!(!p||!Me)){oe(!0);try{const Ie=await HE(p,e,Me.scope.scopeKey,{mode:De,confirm:Te,payload:Me.doc}),ut=Ie.added.length+Ie.overwritten.length+Ie.removed.length;yt(ut===0?d.memory.importNothingNew:d.memory.importDone(Ie.added.length,Ie.overwritten.length,Ie.removed.length)),he(null),ze(null),await W(),f()}catch(Ie){Be(Ae(Ie))}finally{oe(!1)}}},Cn=()=>{if(!Me)return;const Te=N?.find(ut=>ut.scope.scopeKey===Me.scope.scopeKey),Ie=sG(Me.doc,{names:Te?.files.map(ut=>ut.name)??[],hasIndex:Me.scope.hasIndex},De);Ie.destroys?he(Ie):Xt(!1)},lr=async()=>{if(!p||!J)return;const Te=J;ht(null);try{await zE(p,e,Te.scope.scopeKey,Te.file.name),yt(d.memory.deleteDone),A&&A.file.name===Te.file.name&&I(!1),await W(),f()}catch(Ie){Be(Ae(Ie))}};if(_)return a.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:_});const Mt=Te=>Te.kind==="user"?d.memory.userScope:Te.workspacePath?.split(/[\\/]/).filter(Boolean).at(-1)??Te.scopeKey,Pr=(Te,Ie)=>a.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[a.jsx(ge,{size:"icon",title:d.memory.view,"aria-label":`${d.memory.view} ${Ie.title}`,onClick:()=>{nt(Te,Ie)},children:a.jsx(Oe,{d:lG,size:14,className:"text-gray-600 dark:text-gray-300"})}),a.jsx(ge,{size:"icon",title:d.memory.edit,"aria-label":`${d.memory.edit} ${Ie.title}`,onClick:()=>Ke(Te,Ie),children:a.jsx(Oe,{d:cG,size:14,className:"text-gray-600 dark:text-gray-300"})}),a.jsx(ge,{size:"icon",variant:"danger",title:d.memory.delete,"aria-label":`${d.memory.delete} ${Ie.title}`,onClick:()=>ht({scope:Te,file:Ie}),children:a.jsx(Oe,{d:uG,size:14})})]}),Bn=(Te,Ie)=>a.jsxs("li",{className:"flex items-center gap-3 px-3.5 py-2.5",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200",children:Ie.title}),Ie.description&&a.jsx("p",{className:"truncate text-xs text-gray-500 dark:text-gray-400",children:Ie.description})]}),a.jsx("span",{className:"shrink-0 text-xs tabular-nums text-gray-400 dark:text-gray-500",children:Ie.updatedAt??Al(Ie.modifiedAt,s)}),Pr(Te,Ie)]},Ie.name),Nr=A&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:A.file.updatedAt??Al(A.file.modifiedAt,s)}),A.file.description&&a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:A.file.description}),a.jsx("div",{className:"md-body border-t border-gray-100 pt-3 text-sm dark:border-gray-800",children:a.jsx(ed,{text:Y5(A.content)})})]}),Tr=A&&a.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx(ge,{size:"sm",onClick:()=>Ke(A.scope,A.file),children:d.memory.edit}),a.jsx(ge,{size:"sm",variant:"danger",onClick:()=>ht(A),children:d.memory.delete})]});return a.jsxs("div",{className:"space-y-5",children:[a.jsx(Co,{label:d.agent.tabMemory,children:d.memory.desc}),a.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-800",children:[a.jsx("p",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:d.memory.enable}),a.jsx(js,{checked:x,onChange:Te=>{me(Te)},disabled:D})]}),!v&&a.jsxs("div",{className:`flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${Df.attention}`,children:[a.jsx("p",{className:"text-xs",children:d.memory.templateMissing}),a.jsx(ge,{size:"sm",onClick:()=>{Ue()},children:d.memory.insertPlaceholder})]}),N===null?a.jsx(Sr,{rows:4}):a.jsx("div",{className:x?"space-y-5":"space-y-5 opacity-60",children:N.map(({scope:Te,files:Ie})=>{const ut=!L.has(Te.scopeKey);return a.jsxs("section",{className:"overflow-hidden rounded-lg border border-gray-200 dark:border-gray-800",children:[a.jsxs("div",{className:"@container flex items-center gap-2 bg-gray-50 pr-2 transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-800/60",children:[a.jsxs("button",{type:"button","aria-expanded":ut,onClick:()=>Pe(Te.scopeKey),className:"flex min-w-0 flex-1 items-center gap-2.5 px-3.5 py-2.5 text-left",children:[a.jsx("span",{className:"min-w-0 truncate text-sm font-semibold text-gray-800 dark:text-gray-200",children:Mt(Te)}),Te.kind==="workspace"&&Te.workspacePath!==void 0&&a.jsx("span",{className:"min-w-0 truncate font-mono text-[11px] text-gray-400 dark:text-gray-500",children:Te.workspacePath}),a.jsx("span",{className:"min-w-0 flex-1"}),a.jsx("span",{className:"shrink-0 whitespace-nowrap text-xs text-gray-400 dark:text-gray-500",children:d.memory.itemCount(Ie.length)})]}),a.jsx("span",{className:"shrink-0",children:a.jsxs(ge,{size:"sm",variant:"ghost",title:d.memory.exportScopeHint,"aria-label":d.memory.exportScopeLabel(Mt(Te)),onClick:()=>{ar(Te)},children:[a.jsx(Hx,{size:13}),a.jsx("span",{className:"hidden @md:inline",children:d.memory.exportScope})]})}),h&&a.jsxs("label",{className:`${mG} shrink-0`,title:d.memory.importScopeHint,"aria-label":d.memory.importScopeLabel(Mt(Te)),children:[a.jsx(Xl,{accept:".json,application/json",onChange:St=>{zn(Te,St)}}),a.jsx(YC,{size:13}),a.jsx("span",{className:"hidden @md:inline",children:d.memory.importScope})]}),a.jsx("span",{className:"shrink-0",children:a.jsxs(ge,{size:"sm",variant:"ghost",title:d.memory.add,"aria-label":d.memory.addScopeLabel(Mt(Te)),onClick:()=>Bt(Te),children:[a.jsx(Oe,{d:dG,size:13}),a.jsx("span",{className:"hidden @md:inline",children:d.memory.add})]})}),a.jsx("button",{type:"button","aria-expanded":ut,"aria-label":Mt(Te),onClick:()=>Pe(Te.scopeKey),className:"shrink-0 p-1.5",children:a.jsx(Zn,{open:ut,className:"text-gray-400"})})]}),a.jsx("div",{className:`grid transition-[grid-template-rows] duration-200 ease-out ${ut?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:a.jsx("div",{className:"overflow-hidden",inert:!ut,children:Ie.length===0?a.jsx("p",{className:"px-4 py-4 text-center text-xs text-gray-400 dark:text-gray-500",children:Te.kind==="user"?d.memory.emptyUserScope:d.memory.emptyScope}):a.jsx("ul",{className:"divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800 dark:border-gray-800",children:Ie.map(St=>Bn(Te,St))})})})]},Te.scopeKey)})}),a.jsxs("section",{className:"space-y-2.5 rounded-lg border border-gray-200 p-3.5 dark:border-gray-800",children:[a.jsxs("h3",{className:"flex items-center gap-1.5 text-sm font-semibold text-gray-800 dark:text-gray-200",children:[d.memory.promptSection,a.jsx(ba,{label:d.memory.promptSection,children:d.memory.promptSectionHint})]}),a.jsx(ir,{ref:q,label:d.memory.promptLabel,mono:!0,size:"sm",rows:12,value:V,onFocus:()=>$("main"),onChange:Te=>P(Te.target.value)}),a.jsx(ir,{ref:K,label:d.memory.workspacePromptLabel,mono:!0,size:"sm",rows:6,value:B,onFocus:()=>$("workspace"),onChange:Te=>Y(Te.target.value)}),a.jsxs("div",{className:"rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("p",{className:"mb-2 text-xs font-semibold text-gray-500",children:d.agent.placeholdersTitle}),a.jsx("ul",{className:"space-y-1",children:d.memory.promptPlaceholders.map(([Te,Ie])=>a.jsxs("li",{className:"flex items-center gap-3 text-xs",children:[a.jsx("button",{type:"button",onClick:()=>H==="main"?pe(q,V,P,Te):pe(K,B,Y,Te),title:d.memory.insertToken,className:"shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700",children:Te}),a.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:Ie})]},Te))})]}),a.jsx("div",{className:"flex justify-end",children:a.jsx(ge,{size:"sm",variant:"primary",onClick:$e,children:d.common.save})})]}),le,ve?a.jsx(QC,{open:ie,side:"right",title:A?.file.title??"",onClose:()=>I(!1),widthClass:"max-w-lg",children:A&&a.jsxs("div",{className:"flex h-full flex-col",children:[a.jsx("div",{className:"flex-1 space-y-3 overflow-y-auto px-4 py-3",children:Nr}),Tr]})}):a.jsx(ZV,{open:ie,snap:Ge,onSnapChange:He,title:A?.file.title??"",onClose:()=>I(!1),children:A&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"space-y-3 px-4 py-3",children:Nr}),Tr]})}),a.jsx(Yt,{open:j!==null,title:d.memory.editTitle,onClose:()=>U(null),widthClass:"sm:max-w-lg",children:j&&a.jsxs("div",{className:"space-y-2.5",children:[a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.memory.editWhy}),a.jsx("p",{className:"break-all font-mono text-[11px] text-gray-400 dark:text-gray-500",children:gt(j.scope,j.file)}),a.jsx(ir,{label:d.memory.editRequirementLabel,size:"sm",rows:2,value:ee,onChange:Te=>re(Te.target.value),placeholder:d.memory.editRequirementPlaceholder}),a.jsx(ir,{label:d.memory.editPromptLabel,size:"sm",rows:6,readOnly:!0,value:dt,className:"text-gray-600 dark:text-gray-300"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(ge,{size:"sm",onClick:()=>pt.flash(dt),children:[a.jsx(cf,{copied:pt.copied,size:12}),d.memory.editCopyPrompt]}),a.jsx(uf,{copied:pt.copied}),a.jsx(ge,{size:"sm",variant:"primary",onClick:st,children:d.memory.editOpenChat})]})]})}),a.jsx(Yt,{open:ke!==null,title:d.memory.addTitle,onClose:()=>be(null),widthClass:"sm:max-w-lg",children:ke&&a.jsxs("div",{className:"space-y-2.5",children:[a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.memory.addWhy}),a.jsx("p",{className:"break-all font-mono text-[11px] text-gray-400 dark:text-gray-500",children:`${S}/${ke.scopeKey}`}),a.jsx(ir,{label:d.memory.addContentLabel,required:!0,size:"sm",rows:4,value:ye,onChange:Te=>Se(Te.target.value),placeholder:d.memory.addContentPlaceholder}),a.jsx(ir,{label:d.memory.editPromptLabel,size:"sm",rows:6,readOnly:!0,value:Sn,className:"text-gray-600 dark:text-gray-300"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(ge,{size:"sm",disabled:ye.trim()==="",onClick:()=>Dn.flash(Sn),children:[a.jsx(cf,{copied:Dn.copied,size:12}),d.memory.editCopyPrompt]}),a.jsx(uf,{copied:Dn.copied}),a.jsx(ge,{size:"sm",variant:"primary",disabled:ye.trim()==="",onClick:Vt,children:d.memory.editOpenChat})]})]})}),a.jsx(Yt,{open:Me!==null,title:d.memory.importTitle,onClose:()=>ze(null),widthClass:"sm:max-w-lg",children:Me&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.memory.importWhy}),a.jsx("p",{className:"break-all font-mono text-[11px] text-gray-500 dark:text-gray-400",children:d.memory.importFile(Me.fileName,Me.doc.files.length)}),a.jsxs("fieldset",{className:"space-y-2",children:[a.jsx("legend",{className:"mb-1 text-xs font-medium text-gray-500 dark:text-gray-400",children:d.memory.importModeLabel}),[["skip",d.memory.importModeSkip,d.memory.importModeSkipHint],["overwrite",d.memory.importModeOverwrite,d.memory.importModeOverwriteHint],["replace",d.memory.importModeReplace,d.memory.importModeReplaceHint]].map(([Te,Ie,ut])=>a.jsxs("label",{className:"flex cursor-pointer items-start gap-2 text-sm",children:[a.jsx("input",{type:"radio",name:"memory-import-mode",className:"mt-1 shrink-0",checked:De===Te,onChange:()=>ct(Te)}),a.jsxs("span",{className:"min-w-0",children:[a.jsx("span",{className:"text-gray-800 dark:text-gray-200",children:Ie}),a.jsx("span",{className:"block text-xs text-gray-500 dark:text-gray-400",children:ut})]})]},Te))]}),a.jsx("div",{className:"flex justify-end",children:a.jsx(ge,{size:"sm",variant:"primary",disabled:ne,onClick:Cn,children:d.memory.importAction})})]})}),a.jsx(ln,{open:bt!==null,tone:"danger",title:d.memory.importConfirmTitle,confirmLabel:d.memory.importAction,busy:ne,onClose:()=>he(null),onConfirm:()=>{Xt(!0)},children:a.jsxs("div",{className:"space-y-1.5 text-sm text-gray-700 dark:text-gray-300",children:[bt&&bt.overwritten.length>0&&a.jsx("p",{className:"break-words",children:d.memory.importWillOverwrite(bt.overwritten)}),bt&&bt.removed.length>0&&a.jsx("p",{className:"break-words",children:d.memory.importWillRemove(bt.removed)}),bt?.replacesIndex&&a.jsx("p",{children:d.memory.importWillReplaceIndex}),a.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:d.memory.importIrreversible})]})}),a.jsx(ln,{open:J!==null,tone:"danger",title:d.memory.deleteTitle,confirmLabel:d.memory.delete,onClose:()=>ht(null),onConfirm:()=>{lr()},children:a.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:J?d.memory.deleteConfirm(J.file.title):""})})]})}function hG(e){return{prompt:d.agent.tabPrompt,runtime:d.agent.tabRuntime,tools:d.agent.tabTools,skills:d.agent.tabSkills,memory:d.agent.tabMemory,vault:d.agent.tabVault,schedules:d.agent.tabSchedules}[e]??e}const gG=/^[A-Za-z_][A-Za-z0-9_]*$/;function xG({agentId:e,onConfigChanged:t}){const{currentProject:n,reloadAgents:s}=en(),o=n?.projectId??null,c=n?.role==="owner",{applyConfig:u,toggleCard:f,alertStrip:p,promptSection:h}=Zy({agentId:e,feature:"vault",strings:d.vault.injection,canEdit:c,onConfigChanged:t}),[x,g]=y.useState(null),[v,w]=y.useState(null),[S,C]=y.useState(!1),[N,T]=y.useState(!1),[_,R]=y.useState(""),[D,z]=y.useState(""),[E,L]=y.useState({}),F=()=>L(ie=>ie.key||ie.value?{}:ie),[V,P]=y.useState(null),[B,Y]=y.useState(null),q=y.useCallback(async()=>{if(!(!o||!e)){g(null),w(null);try{const[ie,I]=await Promise.all([LE(o,e),Ao(o,e)]);g(ie.entries),u(I.config)}catch(ie){w(Ae(ie))}}},[o,e,u]);y.useEffect(()=>{q()},[q]);const K=async ie=>{if(!o||!e)return d.common.unknownError;C(!0);try{const I=await OE(o,e,ie);return g(I.entries),yt(d.common.saved),s(),null}catch(I){return Ae(I)}finally{C(!1)}},H=ie=>(x??[]).filter(I=>I.key!==ie).map(I=>({key:I.key})),$=()=>{R(""),z(""),L({}),T(!0)},X=async()=>{const ie=_.trim(),I={};if(ie?gG.test(ie)||(I.key=d.vault.keyInvalid):I.key=d.common.requiredField,D||(I.value=d.vault.valueRequired),I.key||I.value){L(I);return}if(L({}),B!==ie&&(x??[]).some(Q=>Q.key===ie)){Y(ie);return}Y(null);const A=await K({entries:[...H(ie),{key:ie,value:D}]});if(A!==null){L({key:A});return}T(!1)},le=async()=>{if(V===null)return;const ie=await K({entries:H(V)});ie!==null&&Be(ie),P(null)};return o?a.jsxs("div",{className:"space-y-4",children:[a.jsxs(Co,{label:d.agent.tabVault,children:[d.vault.desc,!c&&a.jsx("span",{className:"mt-1.5 block",children:d.vault.readOnlyHint})]}),f,p,x===null?a.jsx(Sr,{rows:4}):x.length===0?a.jsx(Ff,{children:d.vault.empty}):a.jsx("div",{className:"overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:a.jsxs("table",{className:"w-full min-w-[420px] text-left text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("th",{className:"px-3 py-2.5",children:d.vault.key}),a.jsx("th",{className:"px-3 py-2.5",children:d.vault.valueMasked}),a.jsx("th",{className:"px-3 py-2.5"})]})}),a.jsx("tbody",{children:x.map(ie=>a.jsxs("tr",{className:"border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40",children:[a.jsx("td",{className:"px-3 py-2 font-mono text-xs",children:ie.key}),a.jsx("td",{className:"px-3 py-2 font-mono text-xs text-gray-500 dark:text-gray-400",children:ie.valueMasked}),a.jsx("td",{className:"px-3 py-2 text-right",children:c&&a.jsx(ge,{size:"sm",variant:"ghost",disabled:S,onClick:()=>P(ie.key),children:d.vault.remove})})]},ie.key))})]})}),c&&x!==null&&a.jsx(ge,{size:"sm",variant:"primary",disabled:S,onClick:$,children:d.vault.add}),h,a.jsx(Yt,{open:N,title:d.vault.addTitle,onClose:()=>T(!1),footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>T(!1),children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:S,onClick:()=>{X()},children:d.vault.add})]}),children:a.jsxs("div",{className:"space-y-3",children:[a.jsx(at,{size:"sm",label:d.vault.key,required:!0,hint:d.vault.keyHint,error:E.key,value:_,onChange:ie=>{R(ie.target.value),F()},className:"font-mono",placeholder:"OPENAI_API_KEY",autoComplete:"off"}),a.jsx(ts,{size:"sm",label:d.vault.value,required:!0,error:E.value,value:D,onChange:ie=>{z(ie.target.value),F()},className:"font-mono",autoComplete:"off",onKeyDown:ie=>{ie.key==="Enter"&&!S&&X()}})]})}),a.jsx(ln,{open:B!==null,title:d.vault.overwriteTitle,tone:"primary",confirmLabel:d.common.save,busy:S,onClose:()=>Y(null),onConfirm:()=>{X()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:B!==null?d.vault.overwriteConfirm(B):""})}),a.jsx(ln,{open:V!==null,title:d.vault.deleteTitle,busy:S,onClose:()=>P(null),onConfirm:()=>{le()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:V!==null?d.vault.deleteConfirm(V):""})}),v&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:v})]}):null}const yG={active:"green",disabled:"gray",expired:"amber",done:"brand",missed:"amber",invalid:"red"};function lj(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=s=>s<10?`0${s}`:`${s}`;return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}const cj=e=>e.modelId&&e.provider?{provider:e.provider,modelId:e.modelId}:null,bG={editing:null,name:"",prompt:"",enabled:!0,startAt:"",endAt:"",period:"",target:"new",sessionId:"",workspace:"",model:null};function vG(e,t){const n=t.trim().toLowerCase();return n?e.filter(s=>s.sessionId.toLowerCase().includes(n)||(s.title??"").toLowerCase().includes(n)):e}function kG({projectId:e,agentId:t,value:n,onChange:s}){const[o,c]=y.useState(!1),[u,f]=y.useState(""),[p,h]=y.useState(null);y.useEffect(()=>{if(!o||p!==null)return;let v=!1;return c0(e,t).then(w=>{v||h(w.sessions)}).catch(()=>{v||h([])}),()=>{v=!0}},[o,p,e,t]);const x=p?.find(v=>v.sessionId===n)??null,g=x?x.title??d.chat.defaultSessionTitle:n||d.schedule.chooseSession;return a.jsx(Ru,{open:o,setOpen:c,label:g,muted:!n,title:n?`${d.schedule.sessionId}:${n}`:d.schedule.chooseSession,ariaLabel:d.schedule.chooseSession,ariaHaspopup:"listbox",menuClass:"w-80 origin-top-left",children:p===null?a.jsx("p",{className:"px-3 py-2 text-xs text-gray-400",children:d.common.loading}):p.length===0?a.jsx("p",{className:"px-3 py-2 text-xs text-gray-400",children:d.schedule.sessionEmpty}):a.jsx(Ey,{items:vG(p,u),itemKey:v=>v.sessionId,isCurrent:v=>v.sessionId===n,query:u,onQueryChange:f,searchPlaceholder:d.schedule.sessionSearch,emptyText:d.schedule.sessionNoMatch,onPick:v=>{s(v.sessionId),c(!1)},renderRow:v=>a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"min-w-0 flex-1 truncate text-gray-800 dark:text-gray-200",children:v.title??d.chat.defaultSessionTitle}),a.jsx("span",{className:"shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500",children:v.sessionId.slice(-6)})]})})})}function wG({agentId:e,onConfigChanged:t}){const{currentProject:n,reloadAgents:s}=en(),o=n?.projectId??null,c=n?.role==="owner",{applyConfig:u,toggleCard:f,alertStrip:p,promptSection:h}=Zy({agentId:e,feature:"schedules",strings:d.schedule.injection,canEdit:c,onConfigChanged:t}),[x,g]=y.useState(null),[v,w]=y.useState(null),[S,C]=y.useState(!1),[N,T]=y.useState(null),[_,R]=y.useState(null),[D,z]=y.useState({}),[E,L]=y.useState(null),[F,V]=y.useState(null),[P,B]=y.useState([]),[Y,q]=y.useState(null),K=y.useCallback(async()=>{if(!(!o||!e)){g(null),w(null);try{const[j,U]=await Promise.all([CA(o,e),Ao(o,e)]);g(j),u(U.config)}catch(j){w(Ae(j))}}},[o,e,u]);y.useEffect(()=>{K()},[K]),y.useEffect(()=>{!o||!c||Ml(o).then(j=>{B(j.models),q(j.defaultModel??null)}).catch(()=>{B([]),q(null)})},[o,c]);const H=j=>{z(U=>U.name||U.prompt||U.startAt||U.sessionId?{}:U),L(U=>U&&null),T(U=>U===null?U:{...U,...j})},$=j=>{z({}),L(null),T(j),R(j)},X=async()=>{if(!o||N===null)return;L(null);const j=N.editing??N.name.trim(),U={};if(j||(U.name=d.common.requiredField),N.prompt.trim()||(U.prompt=d.common.requiredField),N.startAt||(U.startAt=d.common.requiredField),N.target==="session"&&!N.sessionId.trim()&&(U.sessionId=d.common.requiredField),U.name||U.prompt||U.startAt||U.sessionId){z(U);return}if(z({}),N.editing!==null&&JSON.stringify(N)===JSON.stringify(_)){wr(d.common.noChangesToSave);return}const ee={prompt:N.prompt,enabled:N.enabled,startAt:new Date(N.startAt).toISOString(),...N.period.trim()?{period:N.period.trim()}:{},...N.endAt?{endAt:new Date(N.endAt).toISOString()}:{},...N.target==="session"&&N.sessionId.trim()?{sessionId:N.sessionId.trim()}:{},...N.target==="new"&&N.workspace.trim()?{workspace:N.workspace.trim()}:{},...N.target==="new"&&N.model&&!zt(Y,N.model)?{modelId:N.model.modelId,provider:N.model.provider}:{}};C(!0);try{N.editing!==null?await G1(o,e,N.editing,ee):await NA(o,e,{name:j,...ee}),T(null),yt(d.common.saved),await K(),s()}catch(re){L(Ae(re))}finally{C(!1)}},le=async j=>{if(!o)return;C(!0);const U=cj(j);try{await G1(o,e,j.name,{prompt:j.prompt,enabled:!j.enabled,startAt:j.startAt,...j.period!==void 0?{period:j.period}:{},...j.endAt!==void 0?{endAt:j.endAt}:{},...j.sessionId!==void 0?{sessionId:j.sessionId}:{},...j.workspace!==void 0?{workspace:j.workspace}:{},...U?{modelId:U.modelId,provider:U.provider}:{}}),yt(d.common.saved),await K()}catch(ee){Be(Ae(ee))}finally{C(!1)}},ie=j=>{$({editing:j.name,name:j.name,prompt:j.prompt,enabled:j.enabled,startAt:lj(j.startAt),endAt:lj(j.endAt),period:j.period??"",target:j.sessionId?"session":"new",sessionId:j.sessionId??"",workspace:j.workspace??"",model:cj(j)??Y})},I=async()=>{if(!(!o||F===null)){C(!0);try{await TA(o,e,F),N?.editing===F&&T(null),await K(),s()}catch(j){Be(Ae(j))}finally{C(!1),V(null)}}};if(!o)return null;const A=x?.schedules??[],Q=x?.invalidFiles??[];return a.jsxs("div",{className:"space-y-4",children:[a.jsxs(Co,{label:d.agent.tabSchedules,children:[d.schedule.desc,!c&&a.jsx("span",{className:"mt-1.5 block",children:d.schedule.readOnlyHint})]}),f,p,x===null?a.jsx(Sr,{rows:4}):A.length===0?a.jsx(Ff,{children:d.schedule.empty}):a.jsx("div",{className:"overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900",children:a.jsxs("table",{className:"w-full min-w-[720px] text-left text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"border-b border-gray-200 bg-gray-50/80 text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900",children:[a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.common.name}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.schedule.colStatus}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.schedule.colPeriod}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.schedule.colTarget}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.schedule.colFireTimes}),a.jsx("th",{className:"whitespace-nowrap px-3 py-2.5",children:d.schedule.colQueued}),c&&a.jsx("th",{className:"px-3 py-2.5"})]})}),a.jsx("tbody",{children:A.map(j=>a.jsxs("tr",{className:"border-b border-gray-100 transition-colors duration-150 last:border-b-0 hover:bg-gray-50 dark:border-gray-800/60 dark:hover:bg-gray-800/40",children:[a.jsx("td",{className:"max-w-40 truncate px-3 py-2 font-mono text-xs",title:j.name,children:j.name}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2",children:a.jsx("span",{title:j.invalidReason,children:a.jsx(On,{tone:yG[j.status],children:d.schedule.statusNames[j.status]??j.status})})}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-xs text-gray-500 dark:text-gray-400",children:j.period!==void 0?a.jsx("span",{className:"font-mono",children:j.period}):d.schedule.once}),a.jsx("td",{className:"max-w-36 truncate px-3 py-2 text-xs text-gray-500 dark:text-gray-400",title:j.sessionId,children:j.sessionId!==void 0?a.jsx("span",{className:"font-mono",children:j.sessionId}):d.schedule.newSession}),a.jsxs("td",{className:"whitespace-nowrap px-3 py-2 text-xs",children:[a.jsx("span",{className:"block text-gray-600 dark:text-gray-300",children:j.nextFireAt?Jr(j.nextFireAt):"—"}),a.jsx("span",{className:"block text-gray-400 dark:text-gray-500",children:j.lastFiredAt?Jr(j.lastFiredAt):"—"})]}),a.jsx("td",{className:"whitespace-nowrap px-3 py-2",children:j.queued&&a.jsx(On,{tone:"brand",children:d.schedule.queued})}),c&&a.jsxs("td",{className:"whitespace-nowrap px-3 py-2 text-right",children:[a.jsx(ge,{size:"sm",variant:"ghost",disabled:S,onClick:()=>{le(j)},children:j.enabled?d.schedule.disable:d.schedule.enable}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:S,onClick:()=>ie(j),children:d.common.edit}),a.jsx(ge,{size:"sm",variant:"ghost",disabled:S,onClick:()=>V(j.name),children:d.common.delete})]})]},j.name))})]})}),Q.length>0&&a.jsxs("div",{className:"text-xs text-red-600 dark:text-red-400",children:[a.jsx("p",{className:"font-medium",children:d.schedule.invalidFiles}),a.jsx("ul",{className:"mt-0.5 space-y-0.5 font-mono",children:Q.map(j=>a.jsxs("li",{children:[j.name,": ",j.error]},j.name))})]}),c&&x!==null&&a.jsx(ge,{size:"sm",variant:"primary",disabled:S,onClick:()=>$({...bG,model:Y}),children:d.schedule.addTitle}),h,a.jsx(Yt,{open:N!==null,title:N?.editing!=null?d.schedule.editTitle(N.editing):d.schedule.addTitle,onClose:()=>T(null),widthClass:"sm:max-w-lg",footer:a.jsxs(a.Fragment,{children:[a.jsx(ge,{onClick:()=>T(null),children:d.common.cancel}),a.jsx(ge,{variant:"primary",disabled:S,onClick:()=>{X()},children:N?.editing!=null?d.common.save:d.common.create})]}),children:N!==null&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:[a.jsx(at,{size:"sm",label:d.common.name,required:!0,hint:d.schedule.nameHint,error:D.name,value:N.name,disabled:N.editing!==null,onChange:j=>H({name:j.target.value}),className:"font-mono",placeholder:"daily_report",autoComplete:"off"}),a.jsx(at,{size:"sm",label:d.schedule.period,value:N.period,onChange:j=>H({period:j.target.value}),className:"font-mono",placeholder:d.schedule.periodPlaceholder,autoComplete:"off"}),a.jsx(at,{size:"sm",label:d.schedule.startAt,required:!0,type:"datetime-local",error:D.startAt,value:N.startAt,onChange:j=>H({startAt:j.target.value}),className:"font-mono"}),a.jsx(at,{size:"sm",label:d.schedule.endAt,type:"datetime-local",value:N.endAt,onChange:j=>H({endAt:j.target.value}),className:"font-mono"}),a.jsxs(Ss,{size:"sm",label:d.schedule.target,value:N.target,onChange:j=>H({target:j.target.value}),children:[a.jsx("option",{value:"new",children:d.schedule.targetNew}),a.jsx("option",{value:"session",children:d.schedule.targetSession})]}),N.target==="session"?a.jsxs("div",{children:[a.jsx(Yn,{required:!0,children:d.schedule.sessionId}),o&&a.jsx(kG,{projectId:o,agentId:e,value:N.sessionId,onChange:j=>H({sessionId:j})}),D.sessionId&&a.jsx(ga,{children:D.sessionId})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx(Yn,{children:d.schedule.model}),P.length>0?a.jsx(Ay,{models:P,value:N.model,...Y?{defaultModel:Y}:{},onChange:j=>H({model:j}),disabled:S,variant:"form"}):a.jsx("p",{className:"text-xs text-gray-400",children:d.schedule.modelDefault})]}),a.jsxs("div",{children:[a.jsx(Yn,{children:d.schedule.workspace}),a.jsx(sd,{projectId:o??"",workspace:N.workspace,onChange:j=>H({workspace:j}),variant:"form"}),a.jsx(wo,{children:d.chat.workspaceHintShort})]})]})]}),a.jsx(ir,{label:d.schedule.prompt,required:!0,size:"sm",rows:4,error:D.prompt,value:N.prompt,onChange:j=>H({prompt:j.target.value})}),a.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300",children:[a.jsx("input",{type:"checkbox",checked:N.enabled,onChange:j=>H({enabled:j.target.checked})}),d.schedule.enabled]}),E&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:E})]})}),a.jsx(ln,{open:F!==null,title:d.schedule.deleteTitle,busy:S,onClose:()=>V(null),onConfirm:()=>{I()},children:a.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-300",children:F!==null?d.schedule.deleteConfirm(F):""})}),v&&a.jsx("p",{className:"text-xs text-red-600 dark:text-red-400",children:v})]})}const Jy="auto",SG=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,No={connectTimeoutMs:1e4,timeoutMs:12e4,maxOutputLength:16e3},jG=new Set(["transport","command","args","env","cwd","url","headers","connectTimeoutMs","timeoutMs","maxOutputLength","permission"]);function CG(){return{name:"",transport:"http",command:"",argsText:"",envText:"",cwd:"",url:"",headersText:"",connectTimeoutMs:String(No.connectTimeoutMs),timeoutMs:String(No.timeoutMs),maxOutputLength:String(No.maxOutputLength),permission:Jy,extras:{}}}function uj(e,t){return e===null||typeof e!="object"?"":Object.entries(e).map(([n,s])=>`${n}${t}${String(s)}`).join(`
|