@deepseek-ai/dsh-client-ui-chat 0.2.3-alpha.3 → 0.2.3-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.i18n.yaml +6 -6
  2. package/README.md +4 -4
  3. package/README.zh.md +4 -4
  4. package/lib/client.js +6 -6
  5. package/lib/client.js.map +1 -1
  6. package/lib/types/client/apply.d.ts.map +1 -1
  7. package/lib/types/client/apply.js.map +1 -1
  8. package/lib/types/client/chat/AssistantMarkdown.d.ts.map +1 -1
  9. package/lib/types/client/chat/AssistantMarkdown.js.map +1 -1
  10. package/lib/types/client/chat/AssistantNodeView.d.ts +2 -2
  11. package/lib/types/client/chat/AssistantNodeView.d.ts.map +1 -1
  12. package/lib/types/client/chat/ChatNodeSeat.d.ts.map +1 -1
  13. package/lib/types/client/chat/ChatNodeSeat.js.map +1 -1
  14. package/lib/types/client/chat/ChatView.d.ts.map +1 -1
  15. package/lib/types/client/chat/ChatView.js.map +1 -1
  16. package/lib/types/client/chat/ContextBody.d.ts.map +1 -1
  17. package/lib/types/client/chat/ContextBody.js.map +1 -1
  18. package/lib/types/client/chat/ContextInjectionRow.d.ts.map +1 -1
  19. package/lib/types/client/chat/ContextInjectionRow.js.map +1 -1
  20. package/lib/types/client/chat/MessageItem.d.ts +3 -1
  21. package/lib/types/client/chat/MessageItem.d.ts.map +1 -1
  22. package/lib/types/client/chat/MessageItem.js.map +1 -1
  23. package/lib/types/client/chat/SystemPromptRow.d.ts.map +1 -1
  24. package/lib/types/client/chat/SystemPromptRow.js.map +1 -1
  25. package/lib/types/client/chat/TurnTailNodeView.d.ts.map +1 -1
  26. package/lib/types/client/chat/TurnTailNodeView.js.map +1 -1
  27. package/lib/types/client/chat/UserContent.js.map +1 -1
  28. package/lib/types/client/chat/register-node-renderers.d.ts +1 -5
  29. package/lib/types/client/chat/register-node-renderers.d.ts.map +1 -1
  30. package/lib/types/client/chat/register-node-renderers.js.map +1 -1
  31. package/lib/types/client/chat/text-interaction.d.ts.map +1 -1
  32. package/lib/types/client/chat/text-interaction.js.map +1 -1
  33. package/lib/types/client/chat/text-selection.d.ts +1 -0
  34. package/lib/types/client/chat/text-selection.d.ts.map +1 -1
  35. package/lib/types/client/chat/text-selection.js.map +1 -1
  36. package/lib/types/client/contract/slots.d.ts +18 -7
  37. package/lib/types/client/contract/slots.d.ts.map +1 -1
  38. package/lib/types/client/conversation-nodes/command.js.map +1 -1
  39. package/lib/types/client/conversation-nodes/fallback.js.map +1 -1
  40. package/lib/types/client/conversation-nodes/message.js.map +1 -1
  41. package/lib/types/client/conversation-nodes/tool.js.map +1 -1
  42. package/lib/types/client/index.d.ts +1 -1
  43. package/lib/types/client/index.d.ts.map +1 -1
  44. package/lib/types/client/presentation-policy.d.ts +2 -0
  45. package/lib/types/client/presentation-policy.d.ts.map +1 -1
  46. package/lib/types/client/presentation-policy.js.map +1 -1
  47. package/lib/types/client/settings/LinkOpeningRow.d.ts +0 -1
  48. package/lib/types/client/settings/LinkOpeningRow.d.ts.map +1 -1
  49. package/lib/types/client/settings/LinkOpeningRow.js.map +1 -1
  50. package/lib/types/client/settings/PerformanceUsageRow.d.ts.map +1 -1
  51. package/lib/types/client/settings/PerformanceUsageRow.js.map +1 -1
  52. package/lib/types/client/settings/PreferenceRow.js.map +1 -1
  53. package/lib/types/client/settings/TranscriptViewRow.d.ts.map +1 -1
  54. package/lib/types/client/settings/TranscriptViewRow.js.map +1 -1
  55. package/package.json +44 -44
  56. package/src/client/apply.ts +2 -1
  57. package/src/client/chat/AssistantMarkdown.tsx +3 -2
  58. package/src/client/chat/AssistantNodeView.tsx +2 -2
  59. package/src/client/chat/ChatGroupSeat.module.css +4 -2
  60. package/src/client/chat/ChatNodeSeat.tsx +4 -2
  61. package/src/client/chat/ChatView.module.css +37 -5
  62. package/src/client/chat/ChatView.tsx +13 -6
  63. package/src/client/chat/ContextBody.tsx +5 -2
  64. package/src/client/chat/ContextInjectionRow.tsx +3 -2
  65. package/src/client/chat/MessageItem.tsx +39 -28
  66. package/src/client/chat/SystemPromptRow.tsx +3 -2
  67. package/src/client/chat/TurnNavigator.module.css +9 -0
  68. package/src/client/chat/TurnTailNodeView.tsx +3 -2
  69. package/src/client/chat/UserContent.tsx +2 -2
  70. package/src/client/chat/register-node-renderers.ts +5 -8
  71. package/src/client/chat/text-interaction.ts +1 -2
  72. package/src/client/chat/text-selection.ts +20 -4
  73. package/src/client/contract/slots.ts +15 -8
  74. package/src/client/conversation-nodes/README.i18n.yaml +4 -4
  75. package/src/client/conversation-nodes/README.md +2 -1
  76. package/src/client/conversation-nodes/README.zh.md +2 -1
  77. package/src/client/conversation-nodes/command.ts +1 -1
  78. package/src/client/conversation-nodes/fallback.ts +1 -1
  79. package/src/client/conversation-nodes/message.ts +1 -1
  80. package/src/client/conversation-nodes/tool.ts +1 -1
  81. package/src/client/index.ts +2 -2
  82. package/src/client/presentation-policy.ts +6 -0
  83. package/src/client/settings/LinkOpeningRow.tsx +3 -1
  84. package/src/client/settings/PerformanceUsageRow.tsx +4 -1
  85. package/src/client/settings/PreferenceRow.tsx +4 -4
  86. package/src/client/settings/TranscriptViewRow.tsx +10 -3
package/lib/client.js CHANGED
@@ -1,5 +1,5 @@
1
1
 
2
- window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-client-ui-chat`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _deepseek_ai_dsh_client_store=require("@deepseek-ai/dsh-client-store");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");let _deepseek_ai_dsh_client_ui_primitives_client=require("@deepseek-ai/dsh-client-ui-primitives/client");let _tanstack_react_virtual=require("@tanstack/react-virtual");let react_dom=require("react-dom");function projectedString(values,key){if(values===void 0)return void 0;const value=Reflect.get(values,key);return typeof value===`string`?value:void 0}function selectSessionDirectory(state,sessionId){return projectedString(state.projectionsBySession[sessionId]?.values,`workingDirectory`)??projectedString(state.byId[sessionId]?.projectionValues,`workingDirectory`)??state.byId[sessionId]?.cwd}function sessionDirectory(sessions,sessionId){const live=sessions.binding(sessionId)?.session.projections.faceOf(`workingDirectory`).getSnapshot();return(typeof live===`string`?live:void 0)??selectSessionDirectory(sessions.list.getSnapshot(),sessionId)}const FILE_ADDRESS_PREFIX=`dsh-resource://file/`;function encodeSegment(segment){return encodeURIComponent(segment).replace(/%3A/gi,`:`)}function encodePath(path){return path.split(`/`).map(encodeSegment).join(`/`)}function sessionFileAddress(sessionId,path){const normalized=path.replace(/\\/g,`/`).replace(/^(?:\.\/)+/,``);return`${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`}function isWindowsStylePath(value){return/^[A-Za-z]:[/\\]/.test(value)||value.startsWith(`\\\\`)}function isAbsoluteWorkspacePath(path){return path.startsWith(`/`)||isWindowsStylePath(path)}function resolveWorkspacePath(cwd,path){if(isAbsoluteWorkspacePath(path))return path;if(cwd===void 0||cwd===``)return path;const separator=isWindowsStylePath(cwd)&&cwd.includes(`\\`)?`\\`:`/`;return`${cwd.replace(/[/\\]+$/,``)}${separator}${path.replace(/^(?:\.?[/\\])+/,``)}`}function fileAddressFor(sessionId,cwd,path){return sessionFileAddress(sessionId,resolveWorkspacePath(cwd,path))}function fileMediaUrl(base,path){if(!/^https?:/u.test(base)&&!base.startsWith(`dsh-app://app/`)||!isAbsoluteWorkspacePath(path)||/^[/\\]{2}/u.test(path)||/[\u0000-\u001f\u007f]/u.test(path))return void 0;return new URL(`api/file?path=${encodeURIComponent(path)}`,base).href}const EMPTY_LIST$1=[];const EMPTY_TIMELINE={turnOrder:EMPTY_LIST$1,turns:new Map};const EMPTY_NODE_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};const EMPTY_BOTTOM_SOURCE={getSnapshot:()=>false,subscribe:()=>()=>{}};const EMPTY_NODE_PROCESS_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};const EMPTY_TURN_NODE_SOURCE={getSnapshot:()=>EMPTY_LIST$1,subscribe:()=>()=>{}};const EMPTY_CHAT_SNAPSHOT={order:EMPTY_LIST$1,nodes:{get:()=>void 0,source:()=>EMPTY_NODE_SOURCE,bottomSource:()=>EMPTY_BOTTOM_SOURCE,turnDataSource:()=>EMPTY_TURN_NODE_SOURCE,processSource:()=>EMPTY_NODE_PROCESS_SOURCE,values:()=>EMPTY_LIST$1},locations:{getTurn:()=>EMPTY_LIST$1,getStep:()=>EMPTY_LIST$1},navigation:{items:()=>EMPTY_LIST$1},timeline:EMPTY_TIMELINE,legacy:{nodes:EMPTY_LIST$1,turnTimings:new Map,turnEnds:new Map,partial:null,runningCalls:EMPTY_LIST$1}};function commandOf(call){if(call===void 0)return void 0;try{const args=JSON.parse(call.argsRaw);const command=call.name===`terminal_send`?args.text:args.command;return typeof command===`string`&&command.length>0?command:void 0}catch{return}}function ApprovalCommand({callId,useChat}){return useChat(snapshot=>{for(const node of snapshot.nodes.values()){const root=node.kind===`tool-call`?node.data.root:void 0;if(root!==void 0&&root.callId===callId&&!(`kind`in root)&&root.phase===`start`)return commandOf(root)}})??null}function sessionFilePath(ctx,sessionId){return path=>resolveWorkspacePath(sessionDirectory(ctx.sessions,sessionId),path)}const DEPTH={exchange:0,input:1,turn:2,process:3};function isAtOrOutside(node,position){return node.groupTree!==void 0&&DEPTH[node.groupTree]<=DEPTH[position]}function markdownLabels(t){return{code:{copyLabel:t(`copy`),copiedLabel:t(`copied`),toolbarLabels:{codeLabel:t(`codeBlock.title`),wrapLabel:t(`codeBlock.wrap`),unwrapLabel:t(`codeBlock.unwrap`)}},footnotes:t(`markdown.footnotes`)}}var TurnNavigator_module_css_default={"dsh-turn-mark-busy":`eGxaPq_dsh-turn-mark-busy`,"dsh-turn-preview-enter":`eGxaPq_dsh-turn-preview-enter`,"fadeBottom":`eGxaPq_fadeBottom`,"fadeTop":`eGxaPq_fadeTop`,"frame":`eGxaPq_frame`,"mark":`eGxaPq_mark`,"markActive":`eGxaPq_markActive`,"markBusy":`eGxaPq_markBusy`,"markPreview":`eGxaPq_markPreview`,"markUnloaded":`eGxaPq_markUnloaded`,"marks":`eGxaPq_marks`,"preview":`eGxaPq_preview`,"previewPrompt":`eGxaPq_previewPrompt`,"previewResponse":`eGxaPq_previewResponse`,"scroller":`eGxaPq_scroller`,"slot":`eGxaPq_slot`};const TURN_SPACING_PX=10;const RAIL_INSET_PX=6;const FADE_PX=24;function preferredScrollBehavior(){return typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches?`auto`:`smooth`}const TurnMark=(0,react.memo)(function TurnMark({item,index,active,busy,previewId,registerElement,onNavigate,onPreview,onFocusChange,t}){const classes=[TurnNavigator_module_css_default.mark];if(item.anchor.kind===`unloaded`)classes.push(TurnNavigator_module_css_default.markUnloaded);if(active)classes.push(TurnNavigator_module_css_default.markActive);else if(previewId!==void 0)classes.push(TurnNavigator_module_css_default.markPreview);if(busy)classes.push(TurnNavigator_module_css_default.markBusy);return(0,react_jsx_runtime.jsx)(`button`,{ref:registerElement,"data-index":index,type:`button`,className:classes.join(` `),"aria-label":t(item.anchor.kind===`loaded`?`chat.turnNavigation.jump`:`chat.turnNavigation.jumpLoad`,{turn:item.turn}),"aria-current":active?`true`:void 0,"aria-busy":busy?`true`:void 0,"aria-describedby":previewId,onPointerMove:()=>{onPreview(item.turn)},onClick:()=>{onNavigate(item)},onFocus:()=>{onFocusChange(item.turn)},onBlur:()=>{onFocusChange(null)}})});function TurnNavigatorRail({items,activeTurn,busyTurn,onNavigate,t},ref){const[previewTurn,setPreviewTurn]=(0,react.useState)(null);const[focusedTurn,setFocusedTurn]=(0,react.useState)(null);const scrollerRef=(0,react.useRef)(null);const initialization=(0,react.useRef)({placed:false,index:0,follow:null,publishOffset:null});const pointerInsideRef=(0,react.useRef)(false);const previewId=(0,react.useId)();const turnIndexes=(0,react.useMemo)(()=>{const indexes=new Map;items.forEach((item,index)=>{indexes.set(item.turn,index)});return indexes},[items]);const activeIndex=activeTurn===null?void 0:turnIndexes.get(activeTurn);(0,react.useLayoutEffect)(()=>{initialization.current.index=activeIndex??0},[activeIndex]);const focusedIndex=focusedTurn===null?void 0:turnIndexes.get(focusedTurn);const previewIndex=previewTurn===null?void 0:turnIndexes.get(previewTurn);const onFocusChange=(0,react.useCallback)(turn=>{setFocusedTurn(turn);setPreviewTurn(turn)},[]);const virtualizer=(0,_tanstack_react_virtual.useVirtualizer)({count:items.length,enabled:items.length>=2,directDomUpdates:true,directDomUpdatesMode:`transform`,useScrollendEvent:true,getScrollElement:(0,react.useCallback)(()=>scrollerRef.current,[]),getItemKey:(0,react.useCallback)(index=>items[index]?.turn??index,[items]),estimateSize:()=>TURN_SPACING_PX,measureElement:()=>TURN_SPACING_PX,initialRect:{width:0,height:0},initialOffset:0,scrollToFn:(offset,options,instance)=>{if(initialization.current.placed)(0,_tanstack_react_virtual.elementScroll)(offset,options,instance)},observeElementOffset:(instance,notify)=>{initialization.current.publishOffset=notify;const dispose=(0,_tanstack_react_virtual.observeElementOffset)(instance,notify);return()=>{dispose?.();initialization.current.placed=false;initialization.current.follow=null;initialization.current.publishOffset=null}},observeElementRect:(instance,notify)=>{const element=instance.scrollElement;const Observer=instance.targetWindow?.ResizeObserver;if(element===null||Observer===void 0)return;const observer=new Observer(([entry])=>{if(entry===void 0)return;const box=entry.borderBoxSize[0];const rect={width:Math.round(box?.inlineSize??entry.contentRect.width),height:Math.round(box?.blockSize??entry.contentRect.height)};const initial=initialization.current;if(!initial.placed&&rect.height>0){const max=Math.max(0,instance.getTotalSize()-rect.height);const center=initial.index*TURN_SPACING_PX+RAIL_INSET_PX;const target=Math.max(0,Math.min(max,center-rect.height/2));initial.placed=true;initial.follow={index:initial.index,count:instance.options.count,height:rect.height};element.scrollTop=target;initial.publishOffset?.(target,false)}notify(rect)});observer.observe(element,{box:`border-box`});return()=>{observer.disconnect()}},paddingStart:RAIL_INSET_PX-TURN_SPACING_PX/2,paddingEnd:RAIL_INSET_PX-TURN_SPACING_PX/2,scrollPaddingStart:FADE_PX,scrollPaddingEnd:FADE_PX,overscan:3,rangeExtractor:(0,react.useCallback)(range=>{const indexes=(0,_tanstack_react_virtual.defaultRangeExtractor)(range);if(focusedIndex!==void 0){const last=Math.min(range.count-1,focusedIndex+1);for(let index=Math.max(0,focusedIndex-1);index<=last;index++)if(!indexes.includes(index))indexes.push(index);indexes.sort((left,right)=>left-right)}return indexes},[focusedIndex])});const scrollTop=virtualizer.scrollOffset??0;const viewHeight=virtualizer.scrollRect?.height??0;const virtualItems=virtualizer.getVirtualItems();const scrollToIndex=(0,react.useCallback)((index,reveal,behavior=preferredScrollBehavior())=>{const item=virtualizer.measurementsCache[index];const height=virtualizer.scrollRect?.height??0;if(item===void 0||height<=0)return;const current=virtualizer.scrollOffset??0;const center=item.start+item.size/2;if(reveal===`if-needed`){const{scrollPaddingStart,scrollPaddingEnd}=virtualizer.options;if(center>=current+scrollPaddingStart&&center<=current+height-scrollPaddingEnd)return}const target=center-height/2;const max=Math.max(0,virtualizer.getTotalSize()-height);const delta=Math.max(0,Math.min(max,target))-current;if(delta!==0)virtualizer.scrollBy(delta,{behavior})},[virtualizer]);(0,react.useImperativeHandle)(ref,()=>({activateTurn(turn){const index=turnIndexes.get(turn);const item=index===void 0?void 0:items[index];if(item!==void 0)onNavigate(item)},scrollToTurn(turn){const index=turnIndexes.get(turn);if(index!==void 0)scrollToIndex(index,`always`)}}),[items,turnIndexes,onNavigate,scrollToIndex]);(0,react.useEffect)(()=>{if(viewHeight<=0){initialization.current.follow=null;return}if(activeIndex===void 0||pointerInsideRef.current)return;const previous=initialization.current.follow;if(previous?.index===activeIndex&&previous.count===items.length&&previous.height===viewHeight)return;initialization.current.follow={index:activeIndex,count:items.length,height:viewHeight};scrollToIndex(activeIndex,`if-needed`,previous?.count===items.length&&previous.height===viewHeight?preferredScrollBehavior():`instant`)},[activeIndex,items.length,viewHeight,scrollToIndex]);if(items.length<2)return null;const preview=previewIndex===void 0?void 0:items[previewIndex];const previewPosition=virtualItems.find(item=>item.index===previewIndex);const fadeClasses=[TurnNavigator_module_css_default.scroller];if(scrollTop>1)fadeClasses.push(TurnNavigator_module_css_default.fadeTop);if(scrollTop<virtualizer.getTotalSize()-viewHeight-1)fadeClasses.push(TurnNavigator_module_css_default.fadeBottom);return(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.slot,children:(0,react_jsx_runtime.jsxs)(`nav`,{className:TurnNavigator_module_css_default.frame,"aria-label":t(`chat.turnNavigation.label`),onPointerEnter:()=>{pointerInsideRef.current=true},onPointerLeave:()=>{pointerInsideRef.current=false;setPreviewTurn(null)},children:[(0,react_jsx_runtime.jsx)(`div`,{ref:scrollerRef,className:fadeClasses.join(` `),children:(0,react_jsx_runtime.jsx)(`div`,{ref:virtualizer.containerRef,className:TurnNavigator_module_css_default.marks,children:virtualItems.map(({index,key})=>{const item=items[index];if(item===void 0)return null;return(0,react_jsx_runtime.jsx)(TurnMark,{item,index,active:item.turn===activeTurn,busy:item.turn===busyTurn,previewId:item.turn===previewTurn?previewId:void 0,registerElement:virtualizer.measureElement,onNavigate,onPreview:setPreviewTurn,onFocusChange,t},key)})})}),preview!==void 0&&previewPosition!==void 0&&(0,react_jsx_runtime.jsxs)(`div`,{id:previewId,role:`tooltip`,className:TurnNavigator_module_css_default.preview,style:{"--turn-preview-center":`${String(previewPosition.start+previewPosition.size/2-scrollTop)}px`},children:[(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.previewPrompt,children:preview.prompt||t(`chat.turnNavigation.turn`,{turn:preview.turn})}),preview.response!==``&&(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.previewResponse,children:preview.response})]})]})})}const TurnNavigator=(0,react.memo)((0,react.forwardRef)(TurnNavigatorRail));var ChatView_module_css_default={"asideSlot":`EvIC1a_asideSlot`,"callRow":`EvIC1a_callRow`,"column":`EvIC1a_column`,"flowItem":`EvIC1a_flowItem`,"frame":`EvIC1a_frame`,"hint":`EvIC1a_hint`,"historyHidden":`EvIC1a_historyHidden`,"modalAction":`EvIC1a_modalAction`,"older":`EvIC1a_older`,"openError":`EvIC1a_openError`,"root":`EvIC1a_root`,"running":`EvIC1a_running`,"running-enters-slot":`EvIC1a_running-enters-slot`,"runningContent":`EvIC1a_runningContent`,"runningDivider":`EvIC1a_runningDivider`,"runningIcon":`EvIC1a_runningIcon`,"runningText":`EvIC1a_runningText`,"runningWhaleAnimated":`EvIC1a_runningWhaleAnimated`,"runningWhaleStill":`EvIC1a_runningWhaleStill`,"scroll":`EvIC1a_scroll`,"textInteraction":`EvIC1a_textInteraction`,"toBottom":`EvIC1a_toBottom`,"toBottomSlot":`EvIC1a_toBottomSlot`,"turnSpacer":`EvIC1a_turnSpacer`};const ChatAside=(0,react.memo)(function ChatAside({renderSlot}){return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.asideSlot,"data-chat-aside":``,children:renderSlot(`conversation.chat.aside`,{})})});function brandString(value){return value}function brandNumber(value){return value}function SessionSeq(value){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);return brandNumber(value)}const EMPTY_ITEMS$1=[];function outlineEntry(value){if(typeof value!==`object`||value===null)return void 0;const entry=value;if(typeof entry.turn!==`number`||!Number.isSafeInteger(entry.turn)||entry.turn<0)return void 0;if(typeof entry.seq!==`number`||!Number.isSafeInteger(entry.seq)||entry.seq<0||Object.is(entry.seq,-0))return void 0;return{turn:entry.turn,seq:SessionSeq(entry.seq),prompt:typeof entry.prompt===`string`?entry.prompt:``,response:typeof entry.response===`string`?entry.response:``}}function outlineEntries(outline){return Array.isArray(outline)?outline:EMPTY_ITEMS$1}function mergeTurnRailItems(loaded,outline){const byTurn=new Map;for(const raw of outlineEntries(outline)){const entry=outlineEntry(raw);if(entry===void 0)continue;byTurn.set(entry.turn,{turn:entry.turn,prompt:entry.prompt,response:entry.response,anchor:{kind:`unloaded`,seq:entry.seq}})}for(const item of loaded){const preview=byTurn.get(item.turn);byTurn.set(item.turn,{turn:item.turn,prompt:item.prompt!==``?item.prompt:preview?.prompt??``,response:item.response!==``?item.response:preview?.response??``,anchor:{kind:`loaded`,key:item.anchorKey}})}if(byTurn.size===0)return EMPTY_ITEMS$1;return[...byTurn.values()].sort((left,right)=>left.turn-right.turn)}const PROJECTED_BLOCK_TAGS=new Set([`ADDRESS`,`ARTICLE`,`ASIDE`,`BLOCKQUOTE`,`DD`,`DIV`,`DL`,`DT`,`FIGCAPTION`,`FIGURE`,`FOOTER`,`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`HEADER`,`LI`,`MAIN`,`NAV`,`OL`,`P`,`PRE`,`SECTION`,`TABLE`,`TBODY`,`TFOOT`,`THEAD`,`TR`,`UL`]);const PROJECTED_CELL_TAGS=new Set([`TD`,`TH`]);function excluded(element){if(element.matches(`.katex-mathml, [data-text-interaction-exclude], [hidden], .sr-only`))return true;if(element.matches(`[aria-hidden="true"]`)&&!element.matches(`.katex-html`))return true;return element.tagName===`BUTTON`&&element.parentElement?.tagName!==`CODE`}function projectedBoundary(node){const tag=node.tagName;if(PROJECTED_CELL_TAGS.has(tag))return` `;return PROJECTED_BLOCK_TAGS.has(tag)?`
2
+ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-client-ui-chat`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _deepseek_ai_dsh_client_store=require("@deepseek-ai/dsh-client-store");let react_jsx_runtime=require("react/jsx-runtime");let react=require("react");let _deepseek_ai_dsh_client_ui_primitives_client=require("@deepseek-ai/dsh-client-ui-primitives/client");let _tanstack_react_virtual=require("@tanstack/react-virtual");let react_dom=require("react-dom");function projectedString(values,key){if(values===void 0)return void 0;const value=Reflect.get(values,key);return typeof value===`string`?value:void 0}function selectSessionDirectory(state,sessionId){return projectedString(state.projectionsBySession[sessionId]?.values,`workingDirectory`)??projectedString(state.byId[sessionId]?.projectionValues,`workingDirectory`)??state.byId[sessionId]?.cwd}function sessionDirectory(sessions,sessionId){const live=sessions.binding(sessionId)?.session.projections.faceOf(`workingDirectory`).getSnapshot();return(typeof live===`string`?live:void 0)??selectSessionDirectory(sessions.list.getSnapshot(),sessionId)}const FILE_ADDRESS_PREFIX=`dsh-resource://file/`;function encodeSegment(segment){return encodeURIComponent(segment).replace(/%3A/gi,`:`)}function encodePath(path){return path.split(`/`).map(encodeSegment).join(`/`)}function sessionFileAddress(sessionId,path){const normalized=path.replace(/\\/g,`/`).replace(/^(?:\.\/)+/,``);return`${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`}function isWindowsStylePath(value){return/^[A-Za-z]:[/\\]/.test(value)||value.startsWith(`\\\\`)}function isAbsoluteWorkspacePath(path){return path.startsWith(`/`)||isWindowsStylePath(path)}function resolveWorkspacePath(cwd,path){if(isAbsoluteWorkspacePath(path))return path;if(cwd===void 0||cwd===``)return path;const separator=isWindowsStylePath(cwd)&&cwd.includes(`\\`)?`\\`:`/`;return`${cwd.replace(/[/\\]+$/,``)}${separator}${path.replace(/^(?:\.?[/\\])+/,``)}`}function fileAddressFor(sessionId,cwd,path){return sessionFileAddress(sessionId,resolveWorkspacePath(cwd,path))}function fileMediaUrl(base,path){if(!/^https?:/u.test(base)&&!base.startsWith(`dsh-app://app/`)||!isAbsoluteWorkspacePath(path)||/^[/\\]{2}/u.test(path)||/[\u0000-\u001f\u007f]/u.test(path))return void 0;return new URL(`api/file?path=${encodeURIComponent(path)}`,base).href}const EMPTY_LIST$1=[];const EMPTY_TIMELINE={turnOrder:EMPTY_LIST$1,turns:new Map};const EMPTY_NODE_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};const EMPTY_BOTTOM_SOURCE={getSnapshot:()=>false,subscribe:()=>()=>{}};const EMPTY_NODE_PROCESS_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};const EMPTY_TURN_NODE_SOURCE={getSnapshot:()=>EMPTY_LIST$1,subscribe:()=>()=>{}};const EMPTY_CHAT_SNAPSHOT={order:EMPTY_LIST$1,nodes:{get:()=>void 0,source:()=>EMPTY_NODE_SOURCE,bottomSource:()=>EMPTY_BOTTOM_SOURCE,turnDataSource:()=>EMPTY_TURN_NODE_SOURCE,processSource:()=>EMPTY_NODE_PROCESS_SOURCE,values:()=>EMPTY_LIST$1},locations:{getTurn:()=>EMPTY_LIST$1,getStep:()=>EMPTY_LIST$1},navigation:{items:()=>EMPTY_LIST$1},timeline:EMPTY_TIMELINE,legacy:{nodes:EMPTY_LIST$1,turnTimings:new Map,turnEnds:new Map,partial:null,runningCalls:EMPTY_LIST$1}};function commandOf(call){if(call===void 0)return void 0;try{const args=JSON.parse(call.argsRaw);const command=call.name===`terminal_send`?args.text:args.command;return typeof command===`string`&&command.length>0?command:void 0}catch{return}}function ApprovalCommand({callId,useChat}){return useChat(snapshot=>{for(const node of snapshot.nodes.values()){const root=node.kind===`tool-call`?node.data.root:void 0;if(root!==void 0&&root.callId===callId&&!(`kind`in root)&&root.phase===`start`)return commandOf(root)}})??null}function sessionFilePath(ctx,sessionId){return path=>resolveWorkspacePath(sessionDirectory(ctx.sessions,sessionId),path)}const DEPTH={exchange:0,input:1,turn:2,process:3};function isAtOrOutside(node,position){return node.groupTree!==void 0&&DEPTH[node.groupTree]<=DEPTH[position]}function markdownLabels(t){return{code:{copyLabel:t(`copy`),copiedLabel:t(`copied`),toolbarLabels:{codeLabel:t(`codeBlock.title`),wrapLabel:t(`codeBlock.wrap`),unwrapLabel:t(`codeBlock.unwrap`)}},footnotes:t(`markdown.footnotes`)}}var TurnNavigator_module_css_default={"dsh-turn-mark-busy":`eGxaPq_dsh-turn-mark-busy`,"dsh-turn-preview-enter":`eGxaPq_dsh-turn-preview-enter`,"fadeBottom":`eGxaPq_fadeBottom`,"fadeTop":`eGxaPq_fadeTop`,"frame":`eGxaPq_frame`,"mark":`eGxaPq_mark`,"markActive":`eGxaPq_markActive`,"markBusy":`eGxaPq_markBusy`,"markPreview":`eGxaPq_markPreview`,"markUnloaded":`eGxaPq_markUnloaded`,"marks":`eGxaPq_marks`,"preview":`eGxaPq_preview`,"previewPrompt":`eGxaPq_previewPrompt`,"previewResponse":`eGxaPq_previewResponse`,"scroller":`eGxaPq_scroller`,"slot":`eGxaPq_slot`};const TURN_SPACING_PX=10;const RAIL_INSET_PX=6;const FADE_PX=24;function preferredScrollBehavior(){return typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches?`auto`:`smooth`}const TurnMark=(0,react.memo)(function TurnMark({item,index,active,busy,previewId,registerElement,onNavigate,onPreview,onFocusChange,t}){const classes=[TurnNavigator_module_css_default.mark];if(item.anchor.kind===`unloaded`)classes.push(TurnNavigator_module_css_default.markUnloaded);if(active)classes.push(TurnNavigator_module_css_default.markActive);else if(previewId!==void 0)classes.push(TurnNavigator_module_css_default.markPreview);if(busy)classes.push(TurnNavigator_module_css_default.markBusy);return(0,react_jsx_runtime.jsx)(`button`,{ref:registerElement,"data-index":index,type:`button`,className:classes.join(` `),"aria-label":t(item.anchor.kind===`loaded`?`chat.turnNavigation.jump`:`chat.turnNavigation.jumpLoad`,{turn:item.turn}),"aria-current":active?`true`:void 0,"aria-busy":busy?`true`:void 0,"aria-describedby":previewId,onPointerMove:()=>{onPreview(item.turn)},onClick:()=>{onNavigate(item)},onFocus:()=>{onFocusChange(item.turn)},onBlur:()=>{onFocusChange(null)}})});function TurnNavigatorRail({items,activeTurn,busyTurn,onNavigate,t},ref){const[previewTurn,setPreviewTurn]=(0,react.useState)(null);const[focusedTurn,setFocusedTurn]=(0,react.useState)(null);const scrollerRef=(0,react.useRef)(null);const initialization=(0,react.useRef)({placed:false,index:0,follow:null,publishOffset:null});const pointerInsideRef=(0,react.useRef)(false);const previewId=(0,react.useId)();const turnIndexes=(0,react.useMemo)(()=>{const indexes=new Map;items.forEach((item,index)=>{indexes.set(item.turn,index)});return indexes},[items]);const activeIndex=activeTurn===null?void 0:turnIndexes.get(activeTurn);(0,react.useLayoutEffect)(()=>{initialization.current.index=activeIndex??0},[activeIndex]);const focusedIndex=focusedTurn===null?void 0:turnIndexes.get(focusedTurn);const previewIndex=previewTurn===null?void 0:turnIndexes.get(previewTurn);const onFocusChange=(0,react.useCallback)(turn=>{setFocusedTurn(turn);setPreviewTurn(turn)},[]);const virtualizer=(0,_tanstack_react_virtual.useVirtualizer)({count:items.length,enabled:items.length>=2,directDomUpdates:true,directDomUpdatesMode:`transform`,useScrollendEvent:true,getScrollElement:(0,react.useCallback)(()=>scrollerRef.current,[]),getItemKey:(0,react.useCallback)(index=>items[index]?.turn??index,[items]),estimateSize:()=>TURN_SPACING_PX,measureElement:()=>TURN_SPACING_PX,initialRect:{width:0,height:0},initialOffset:0,scrollToFn:(offset,options,instance)=>{if(initialization.current.placed)(0,_tanstack_react_virtual.elementScroll)(offset,options,instance)},observeElementOffset:(instance,notify)=>{initialization.current.publishOffset=notify;const dispose=(0,_tanstack_react_virtual.observeElementOffset)(instance,notify);return()=>{dispose?.();initialization.current.placed=false;initialization.current.follow=null;initialization.current.publishOffset=null}},observeElementRect:(instance,notify)=>{const element=instance.scrollElement;const Observer=instance.targetWindow?.ResizeObserver;if(element===null||Observer===void 0)return;const observer=new Observer(([entry])=>{if(entry===void 0)return;const box=entry.borderBoxSize[0];const rect={width:Math.round(box?.inlineSize??entry.contentRect.width),height:Math.round(box?.blockSize??entry.contentRect.height)};const initial=initialization.current;if(!initial.placed&&rect.height>0){const max=Math.max(0,instance.getTotalSize()-rect.height);const center=initial.index*TURN_SPACING_PX+RAIL_INSET_PX;const target=Math.max(0,Math.min(max,center-rect.height/2));initial.placed=true;initial.follow={index:initial.index,count:instance.options.count,height:rect.height};element.scrollTop=target;initial.publishOffset?.(target,false)}notify(rect)});observer.observe(element,{box:`border-box`});return()=>{observer.disconnect()}},paddingStart:RAIL_INSET_PX-TURN_SPACING_PX/2,paddingEnd:RAIL_INSET_PX-TURN_SPACING_PX/2,scrollPaddingStart:FADE_PX,scrollPaddingEnd:FADE_PX,overscan:3,rangeExtractor:(0,react.useCallback)(range=>{const indexes=(0,_tanstack_react_virtual.defaultRangeExtractor)(range);if(focusedIndex!==void 0){const last=Math.min(range.count-1,focusedIndex+1);for(let index=Math.max(0,focusedIndex-1);index<=last;index++)if(!indexes.includes(index))indexes.push(index);indexes.sort((left,right)=>left-right)}return indexes},[focusedIndex])});const scrollTop=virtualizer.scrollOffset??0;const viewHeight=virtualizer.scrollRect?.height??0;const virtualItems=virtualizer.getVirtualItems();const scrollToIndex=(0,react.useCallback)((index,reveal,behavior=preferredScrollBehavior())=>{const item=virtualizer.measurementsCache[index];const height=virtualizer.scrollRect?.height??0;if(item===void 0||height<=0)return;const current=virtualizer.scrollOffset??0;const center=item.start+item.size/2;if(reveal===`if-needed`){const{scrollPaddingStart,scrollPaddingEnd}=virtualizer.options;if(center>=current+scrollPaddingStart&&center<=current+height-scrollPaddingEnd)return}const target=center-height/2;const max=Math.max(0,virtualizer.getTotalSize()-height);const delta=Math.max(0,Math.min(max,target))-current;if(delta!==0)virtualizer.scrollBy(delta,{behavior})},[virtualizer]);(0,react.useImperativeHandle)(ref,()=>({activateTurn(turn){const index=turnIndexes.get(turn);const item=index===void 0?void 0:items[index];if(item!==void 0)onNavigate(item)},scrollToTurn(turn){const index=turnIndexes.get(turn);if(index!==void 0)scrollToIndex(index,`always`)}}),[items,turnIndexes,onNavigate,scrollToIndex]);(0,react.useEffect)(()=>{if(viewHeight<=0){initialization.current.follow=null;return}if(activeIndex===void 0||pointerInsideRef.current)return;const previous=initialization.current.follow;if(previous?.index===activeIndex&&previous.count===items.length&&previous.height===viewHeight)return;initialization.current.follow={index:activeIndex,count:items.length,height:viewHeight};scrollToIndex(activeIndex,`if-needed`,previous?.count===items.length&&previous.height===viewHeight?preferredScrollBehavior():`instant`)},[activeIndex,items.length,viewHeight,scrollToIndex]);if(items.length<2)return null;const preview=previewIndex===void 0?void 0:items[previewIndex];const previewPosition=virtualItems.find(item=>item.index===previewIndex);const fadeClasses=[TurnNavigator_module_css_default.scroller];if(scrollTop>1)fadeClasses.push(TurnNavigator_module_css_default.fadeTop);if(scrollTop<virtualizer.getTotalSize()-viewHeight-1)fadeClasses.push(TurnNavigator_module_css_default.fadeBottom);return(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.slot,children:(0,react_jsx_runtime.jsxs)(`nav`,{className:TurnNavigator_module_css_default.frame,"aria-label":t(`chat.turnNavigation.label`),onPointerEnter:()=>{pointerInsideRef.current=true},onPointerLeave:()=>{pointerInsideRef.current=false;setPreviewTurn(null)},children:[(0,react_jsx_runtime.jsx)(`div`,{ref:scrollerRef,className:fadeClasses.join(` `),children:(0,react_jsx_runtime.jsx)(`div`,{ref:virtualizer.containerRef,className:TurnNavigator_module_css_default.marks,children:virtualItems.map(({index,key})=>{const item=items[index];if(item===void 0)return null;return(0,react_jsx_runtime.jsx)(TurnMark,{item,index,active:item.turn===activeTurn,busy:item.turn===busyTurn,previewId:item.turn===previewTurn?previewId:void 0,registerElement:virtualizer.measureElement,onNavigate,onPreview:setPreviewTurn,onFocusChange,t},key)})})}),preview!==void 0&&previewPosition!==void 0&&(0,react_jsx_runtime.jsxs)(`div`,{id:previewId,role:`tooltip`,className:TurnNavigator_module_css_default.preview,style:{"--turn-preview-center":`${String(previewPosition.start+previewPosition.size/2-scrollTop)}px`},children:[(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.previewPrompt,children:preview.prompt||t(`chat.turnNavigation.turn`,{turn:preview.turn})}),preview.response!==``&&(0,react_jsx_runtime.jsx)(`div`,{className:TurnNavigator_module_css_default.previewResponse,children:preview.response})]})]})})}const TurnNavigator=(0,react.memo)((0,react.forwardRef)(TurnNavigatorRail));var ChatView_module_css_default={"asideSlot":`EvIC1a_asideSlot`,"callRow":`EvIC1a_callRow`,"column":`EvIC1a_column`,"flowItem":`EvIC1a_flowItem`,"frame":`EvIC1a_frame`,"hint":`EvIC1a_hint`,"historyHidden":`EvIC1a_historyHidden`,"modalAction":`EvIC1a_modalAction`,"older":`EvIC1a_older`,"openError":`EvIC1a_openError`,"root":`EvIC1a_root`,"running":`EvIC1a_running`,"running-enters-slot":`EvIC1a_running-enters-slot`,"runningContent":`EvIC1a_runningContent`,"runningDivider":`EvIC1a_runningDivider`,"runningIcon":`EvIC1a_runningIcon`,"runningText":`EvIC1a_runningText`,"runningWhaleAnimated":`EvIC1a_runningWhaleAnimated`,"runningWhaleStill":`EvIC1a_runningWhaleStill`,"scroll":`EvIC1a_scroll`,"textInteraction":`EvIC1a_textInteraction`,"toBottom":`EvIC1a_toBottom`,"toBottomSlot":`EvIC1a_toBottomSlot`,"turnSpacer":`EvIC1a_turnSpacer`};const ChatAside=(0,react.memo)(function ChatAside({renderSlot}){return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.asideSlot,"data-chat-aside":``,children:renderSlot(`conversation.chat.aside`,{})})});function brandString(value){return value}function brandNumber(value){return value}const SURFACE_EVENT_TYPES=new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function isSurfaceEvent(event){if(!SURFACE_EVENT_TYPES.has(event.type))return false;return event.surfaceOp!==void 0}function isAppendSurfaceEvent(event){return isSurfaceEvent(event)&&event.surfaceOp===`append`}function isReplacementSurfaceEvent(event){return isSurfaceEvent(event)&&event.surfaceOp!==`append`}function SessionSeq(value){if(!Number.isSafeInteger(value)||value<0||Object.is(value,-0))throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`);return brandNumber(value)}const EMPTY_ITEMS$1=[];function outlineEntry(value){if(typeof value!==`object`||value===null)return void 0;const entry=value;if(typeof entry.turn!==`number`||!Number.isSafeInteger(entry.turn)||entry.turn<0)return void 0;if(typeof entry.seq!==`number`||!Number.isSafeInteger(entry.seq)||entry.seq<0||Object.is(entry.seq,-0))return void 0;return{turn:entry.turn,seq:SessionSeq(entry.seq),prompt:typeof entry.prompt===`string`?entry.prompt:``,response:typeof entry.response===`string`?entry.response:``}}function outlineEntries(outline){return Array.isArray(outline)?outline:EMPTY_ITEMS$1}function mergeTurnRailItems(loaded,outline){const byTurn=new Map;for(const raw of outlineEntries(outline)){const entry=outlineEntry(raw);if(entry===void 0)continue;byTurn.set(entry.turn,{turn:entry.turn,prompt:entry.prompt,response:entry.response,anchor:{kind:`unloaded`,seq:entry.seq}})}for(const item of loaded){const preview=byTurn.get(item.turn);byTurn.set(item.turn,{turn:item.turn,prompt:item.prompt!==``?item.prompt:preview?.prompt??``,response:item.response!==``?item.response:preview?.response??``,anchor:{kind:`loaded`,key:item.anchorKey}})}if(byTurn.size===0)return EMPTY_ITEMS$1;return[...byTurn.values()].sort((left,right)=>left.turn-right.turn)}const PROJECTED_BLOCK_TAGS=new Set([`ADDRESS`,`ARTICLE`,`ASIDE`,`BLOCKQUOTE`,`DD`,`DIV`,`DL`,`DT`,`FIGCAPTION`,`FIGURE`,`FOOTER`,`H1`,`H2`,`H3`,`H4`,`H5`,`H6`,`HEADER`,`LI`,`MAIN`,`NAV`,`OL`,`P`,`PRE`,`SECTION`,`TABLE`,`TBODY`,`TFOOT`,`THEAD`,`TR`,`UL`]);const PROJECTED_CELL_TAGS=new Set([`TD`,`TH`]);function excluded(element){if(element.matches(`.katex-mathml, [data-text-interaction-exclude], [hidden], .sr-only`))return true;if(element.matches(`[aria-hidden="true"]`)&&!element.matches(`.katex-html`))return true;return element.tagName===`BUTTON`&&element.parentElement?.tagName!==`CODE`}function projectedBoundary(node){const tag=node.tagName;if(PROJECTED_CELL_TAGS.has(tag))return` `;return PROJECTED_BLOCK_TAGS.has(tag)?`
3
3
  `:``}function projectedSeparator(previous,current){const left=projectedBoundary(previous);const right=projectedBoundary(current);if(left===`
4
4
  `||right===`
5
5
  `)return`
@@ -8,14 +8,14 @@ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-client-ui-chat`,factory:requi
8
8
  `,spans:[],boundaries:[]};let text=``;let previous=null;const spans=[];const boundaries=[];const offsets=new Array(node.childNodes.length+1).fill(0);for(const[index,child]of[...node.childNodes].entries()){const fragment=projectedFragment(child);if(fragment.text!==``&&previous!==null){const separator=projectedSeparator(previous,child);if(separator===`
9
9
  `?!text.endsWith(`
10
10
  `)&&!fragment.text.startsWith(`
11
- `):separator===` `&&!/[\t\n]$/u.test(text)&&!/^[\t\n]/u.test(fragment.text))text+=separator}offsets[index]=text.length;const base=text.length;text+=fragment.text;for(const span of fragment.spans)spans.push({node:span.node,start:base+span.start,offsets:span.offsets});for(const[owner,childOffsets]of fragment.boundaries)boundaries.push([owner,childOffsets.map(offset=>base+offset)]);if(fragment.text!==``)previous=child;offsets[index+1]=text.length}boundaries.push([node,offsets]);return{text,spans,boundaries}}function projectedOffset(projection,container,offset){if(container.nodeType===Node.TEXT_NODE){const span=projection.spans.find(candidate=>candidate.node===container);const projected=span?.offsets[offset];return span===void 0||projected===void 0?null:span.start+projected}return(projection.boundaries.find(([owner])=>owner===container)?.[1])?.[offset]??null}function readTextSelection(root,selection){if(selection===null||selection.rangeCount!==1||selection.isCollapsed)return null;const range=selection.getRangeAt(0);const sourceOf=node=>node.closest?.(`[data-text-interaction-source]`)??node.parentElement?.closest(`[data-text-interaction-source]`)??null;const source=sourceOf(range.startContainer);if(source===null||source!==sourceOf(range.endContainer)||!root.contains(source)||source.closest(`[hidden], [inert], [data-text-interaction-exclude]`)!==null)return null;return{source,range}}function selectedText(selection){const{source,range}=selection;const projection=projectedFragment(source);const start=projectedOffset(projection,range.startContainer,range.startOffset);const end=projectedOffset(projection,range.endContainer,range.endOffset);if(start===null||end===null)return null;const text=projection.text.slice(start,end).trim();return text===``?null:text}function rectBounds(rect){return{left:rect.left,top:rect.top,right:rect.left+rect.width,bottom:rect.top+rect.height}}function intersects(a,b){return a.right>b.left&&a.left<b.right&&a.bottom>b.top&&a.top<b.bottom}function sameRange(a,b){return a===b||a!==null&&b!==null&&a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset}function available(root,target){if(!root.isConnected||!root.contains(target.source)||!target.source.hasAttribute(`data-text-interaction-source`))return false;const view=root.ownerDocument.defaultView;if(view===null)return false;for(let node=target.source;node!==null;node=node.parentElement){const style=view.getComputedStyle(node);if(node.hidden||node.inert||node.hasAttribute(`data-text-interaction-exclude`)||style.display===`none`||style.visibility===`hidden`)return false}return target.selection===null||target.source.contains(target.selection.range.startContainer)&&target.source.contains(target.selection.range.endContainer)&&selectedText(target.selection)===target.text}function composerSeat(root){return root.closest(`[data-conversation-scroll]`)?.querySelector(`[data-composer-seat]`)??null}function visibleBounds(root,source,view){const rootRect=rectBounds(root.getBoundingClientRect());const bounds={left:Math.max(0,rootRect.left),right:Math.min(view.innerWidth,rootRect.right),top:0,bottom:view.innerHeight};for(let node=source;node!==null;node=node.parentElement){const style=view.getComputedStyle(node);const rect=rectBounds(node.getBoundingClientRect());if(/(auto|scroll|hidden|clip)/u.test(style.overflowX)){bounds.left=Math.max(bounds.left,rect.left);bounds.right=Math.min(bounds.right,rect.right)}if(/(auto|scroll|hidden|clip)/u.test(style.overflowY)){bounds.top=Math.max(bounds.top,rect.top);bounds.bottom=Math.min(bounds.bottom,rect.bottom)}}const composer=composerSeat(root)?.getBoundingClientRect();if(composer!==void 0&&composer.height>0&&composer.right>bounds.left&&composer.left<bounds.right)bounds.bottom=Math.min(bounds.bottom,composer.top);return bounds}function useTextInteraction(rootRef,surfaceRef,dispatchInteraction,registeredIds){const target=(0,react.useRef)(null);const[active,setActive]=(0,react.useState)(null);const dismiss=(0,react.useCallback)(()=>{target.current=null;if(surfaceRef.current!==null)surfaceRef.current.style.visibility=`hidden`;setActive(null)},[surfaceRef]);(0,react.useEffect)(dismiss,[registeredIds,dispatchInteraction,dismiss]);const readText=(0,react.useCallback)(()=>{const root=rootRef.current;const current=target.current;if(root===null||current===null||!available(root,current))return null;return current.selection===null?null:selectedText(current.selection)},[rootRef]);const clearSelection=(0,react.useCallback)(()=>{rootRef.current?.ownerDocument.getSelection()?.removeAllRanges()},[rootRef]);const place=(0,react.useCallback)(()=>{const root=rootRef.current;const surface=surfaceRef.current;const current=target.current;if(root===null||surface===null||current===null)return;if(!available(root,current)){dismiss();return}const view=root.ownerDocument.defaultView;if(view===null)return;const visible=visibleBounds(root,current.source,view);const selectionRects=current.selection===null?[]:[...current.selection.range.getClientRects()];const fallback=current.selection?.range.getBoundingClientRect()??current.source.getBoundingClientRect();const rects=selectionRects.length===0?[fallback]:selectionRects;const sourceRect=current.source.getBoundingClientRect();const pointX=current.point===null?0:sourceRect.left+current.point.x-current.source.scrollLeft;const pointY=current.point===null?0:sourceRect.top+current.point.y-current.source.scrollTop;const anchor=current.point===null?rects.map(rectBounds).find(rect=>intersects(rect,visible)):{left:pointX,right:pointX+1,top:pointY,bottom:pointY+1};if(anchor===void 0||!intersects(anchor,visible)||visible.right<=visible.left||visible.bottom<=visible.top){surface.style.visibility=`hidden`;return}const gap=8;surface.style.maxWidth=`${visible.right-visible.left}px`;surface.style.maxHeight=`${visible.bottom-visible.top}px`;const size=surface.getBoundingClientRect();const x=current.point===null?(Math.max(anchor.left,visible.left)+Math.min(anchor.right,visible.right)-size.width)/2:anchor.left;const above=anchor.top-gap-size.height;const below=anchor.bottom+gap;const preferredY=current.point===null&&above>=visible.top?above:below;const left=Math.max(visible.left,Math.min(x,visible.right-size.width));const top=Math.max(visible.top,Math.min(preferredY,visible.bottom-size.height));const rootRect=root.getBoundingClientRect();const scaleX=root.offsetWidth===0?1:rootRect.width/root.offsetWidth;const scaleY=root.offsetHeight===0?1:rootRect.height/root.offsetHeight;surface.style.left=`${(left-rootRect.left)/scaleX-root.clientLeft+root.scrollLeft}px`;surface.style.top=`${(top-rootRect.top)/scaleY-root.clientTop+root.scrollTop}px`;surface.style.visibility=`visible`},[dismiss,rootRef,surfaceRef]);(0,react.useLayoutEffect)(place,[active,place]);(0,react.useEffect)(()=>{const root=rootRef.current;const surface=surfaceRef.current;if(root===null||surface===null)return;const document=root.ownerDocument;const view=document.defaultView;if(view===null)return;let pointerSelecting=false;let keyboardSelecting=false;let selectionChangedDuringGesture=false;let previousRange=null;let frame;const schedulePlacement=()=>{if(target.current===null||frame!==void 0)return;frame=view.requestAnimationFrame(()=>{frame=void 0;place()})};const dispatch=(trigger,next,event)=>{if(!available(root,next))return;const id=dispatchInteraction({trigger,hasSelection:next.selection!==null,readText:()=>next.text,preventDefault:()=>{event.preventDefault()}});if(id===null)return;target.current=next;setActive({id,trigger})};const updateSelection=event=>{if(pointerSelecting||keyboardSelecting){selectionChangedDuringGesture=true;return}if(target.current!==null&&target.current.point!==null)return;if(target.current!==null&&surface.contains(document.activeElement))return;const selection=readTextSelection(root,document.getSelection());const range=selection?.range??null;if(!selectionChangedDuringGesture&&sameRange(previousRange,range))return;selectionChangedDuringGesture=false;previousRange=range?.cloneRange()??null;dismiss();if(selection===null)return;const text=selectedText(selection);if(text===null)return;dispatch(`selection`,{source:selection.source,selection:{...selection,range:selection.range.cloneRange()},text,point:null},event)};const insideSurface=event=>event.composedPath().includes(surface);const pointerDown=event=>{if(insideSurface(event))return;const selection=document.getSelection();previousRange=selection?.rangeCount===1?selection.getRangeAt(0).cloneRange():null;dismiss();selectionChangedDuringGesture=false;pointerSelecting=event.button===0&&root.contains(event.target)};const pointerUp=event=>{if(!pointerSelecting)return;pointerSelecting=false;updateSelection(event)};const cancel=()=>{pointerSelecting=false;keyboardSelecting=false;dismiss()};const keyDown=event=>{if(event.key===`Escape`){cancel();return}if(insideSurface(event)||!root.contains(event.target))return;if(event.key===`Shift`||event.shiftKey){keyboardSelecting=true;dismiss()}};const keyUp=event=>{if(!keyboardSelecting||event.key!==`Shift`&&event.shiftKey)return;keyboardSelecting=false;updateSelection(event)};const contextMenu=event=>{if(insideSurface(event))return;const element=event.target;const source=element.closest?.(`[data-text-interaction-source]`);if(source===void 0||source===null||!root.contains(source)||element.closest?.(`[data-text-interaction-exclude], button, input, textarea, [contenteditable="true"]`))return;pointerSelecting=false;dismiss();const selected=readTextSelection(root,document.getSelection());const keyboard=event.clientX===0&&event.clientY===0;const selection=selected?.source===source&&(keyboard||[...selected.range.getClientRects()].some(rect=>event.clientX>=rect.left&&event.clientX<=rect.right&&event.clientY>=rect.top&&event.clientY<=rect.bottom))?selected:null;const bounds=source.getBoundingClientRect();dispatch(`contextmenu`,{source,selection:selection===null?null:{...selection,range:selection.range.cloneRange()},text:selection===null?null:selectedText(selection),point:{x:(keyboard?0:event.clientX-bounds.left)+source.scrollLeft,y:(keyboard?0:event.clientY-bounds.top)+source.scrollTop}},event)};document.addEventListener(`selectionchange`,updateSelection);document.addEventListener(`pointerdown`,pointerDown,true);document.addEventListener(`pointerup`,pointerUp);document.addEventListener(`pointercancel`,cancel);document.addEventListener(`keydown`,keyDown);document.addEventListener(`keyup`,keyUp);document.addEventListener(`scroll`,schedulePlacement,true);root.addEventListener(`contextmenu`,contextMenu);view.addEventListener(`resize`,schedulePlacement);view.addEventListener(`blur`,cancel);return()=>{document.removeEventListener(`selectionchange`,updateSelection);document.removeEventListener(`pointerdown`,pointerDown,true);document.removeEventListener(`pointerup`,pointerUp);document.removeEventListener(`pointercancel`,cancel);document.removeEventListener(`keydown`,keyDown);document.removeEventListener(`keyup`,keyUp);document.removeEventListener(`scroll`,schedulePlacement,true);root.removeEventListener(`contextmenu`,contextMenu);view.removeEventListener(`resize`,schedulePlacement);view.removeEventListener(`blur`,cancel);if(frame!==void 0)view.cancelAnimationFrame(frame)}},[dismiss,place,rootRef,surfaceRef,dispatchInteraction]);(0,react.useEffect)(()=>{const root=rootRef.current;const surface=surfaceRef.current;if(active===null||root===null||surface===null)return;const view=root.ownerDocument.defaultView;if(view===null)return;let frame;const schedule=()=>{if(frame!==void 0)return;frame=view.requestAnimationFrame(()=>{frame=void 0;place()})};const resize=new ResizeObserver(schedule);resize.observe(root);resize.observe(surface);const composer=composerSeat(root);if(composer!==null)resize.observe(composer);const mutations=new MutationObserver(records=>{if(records.some(record=>!surface.contains(record.target)))schedule()});mutations.observe(root,{childList:true,subtree:true,characterData:true,attributes:true});return()=>{resize.disconnect();mutations.disconnect();if(frame!==void 0)view.cancelAnimationFrame(frame)}},[active,place,rootRef,surfaceRef]);return{active,dismiss,readText,clearSelection}}var ChatNavigation=class{viewport;reading;input;onBusyTurn;onHistoryIntent;jump=null;settleFrame=null;historyFrame=null;historyIntent=`none`;historyRequested=false;constructor(viewport,reading,input,onBusyTurn,onHistoryIntent=()=>{}){this.viewport=viewport;this.reading=reading;this.input=input;this.onBusyTurn=onBusyTurn;this.onHistoryIntent=onHistoryIntent}setInput(input){this.input=input;this.historyRequested=false;if(!input.isOpen||input.historyLoadStatus===`error`||!input.hasMore)this.setHistoryIntent(`none`)}reset(){this.cancel()}dispose(){this.clearTask();if(this.historyFrame!==null)cancelAnimationFrame(this.historyFrame);this.historyFrame=null}cancel(){this.setHistoryIntent(`none`);this.clearTask();this.onBusyTurn(null)}readerInteracted(){this.clearTask();this.onBusyTurn(null)}clearTask(){this.cancelFrame();this.jump=null;this.viewport.stopPreserving();this.viewport.cancelHistoryPrepend()}navigateToTurn=item=>{if(item.anchor.kind===`loaded`){this.cancel();const landing=this.viewport.scrollToTurn(item.turn);if(landing===null)return;this.reading.acceptNavigation(landing);if(this.input.loadingOlder)this.viewport.beginPreserving(landing.position);return}this.cancel();this.viewport.beginPreserving();this.reading.pauseFollowing();const jump={turn:item.turn,seq:item.anchor.seq,phase:`loading`,landing:`pending`,repageHead:null};this.jump=jump;this.onBusyTurn(jump.turn);this.request(jump)};loadEarlier=()=>{this.cancel();this.setHistoryIntent(`manual`);this.reading.pauseFollowing();if(this.input.historyLoadStatus===`error`){this.historyRequested=true;this.input.loadOlder()}else this.requestHistoryCheck()};setHistoryIntent(intent){if(intent===this.historyIntent)return;this.historyIntent=intent;this.onHistoryIntent(intent)}requestHistoryCheck(){if(!this.input.isOpen||this.input.historyLoadStatus===`error`)return;if(this.historyIntent===`none`&&(this.input.historyLoadStatus!==`idle`||!this.input.hasMore||this.reading.followingTail))return;if(this.historyFrame!==null||typeof requestAnimationFrame!==`function`)return;this.historyFrame=requestAnimationFrame(()=>{this.historyFrame=null;this.checkHistory()})}checkHistory(){const input=this.input;if(!input.isOpen||this.jump!==null||this.historyRequested||input.loadingOlder)return;if(input.historyLoadStatus===`error`)return;if(input.historyLoadStatus===`pendingConsumption`){if(this.historyIntent===`none`)return;if(this.reading.followingTail&&this.historyIntent===`auto`){this.setHistoryIntent(`none`);return}if(this.historyIntent===`manual`){this.viewport.beginManualPaging();this.reading.pauseFollowing();this.consumeHistory(`preserve`);return}const mode=this.viewport.historyConsumption();switch(mode){case`touch`:case`inner-scroll`:return;case`motion`:case`pointer`:case`unavailable`:this.setHistoryIntent(`none`);return;case`prepend`:if(!this.viewport.beginHistoryPrepend()&&input.firstSeq!==null){this.setHistoryIntent(`none`);return}break;case`preserve`:case`native`:break}if(mode===`preserve`){this.viewport.beginPreserving();if(!this.viewport.preserving)this.viewport.beginPaging();if(!this.viewport.preserving&&input.firstSeq!==null){this.setHistoryIntent(`none`);return}this.reading.pauseFollowing()}this.consumeHistory(mode);return}if(!input.hasMore||this.historyIntent!==`manual`&&(this.reading.followingTail||!this.viewport.confirmHistoryStart()))return;if(this.historyIntent===`none`)this.setHistoryIntent(`auto`);this.historyRequested=true;input.loadOlder()}consumeHistory(mode){this.historyRequested=true;if(this.input.consumeOlder())this.setHistoryIntent(`none`);else{this.historyRequested=false;if(mode===`preserve`)this.viewport.stopPreserving();if(mode===`prepend`)this.viewport.cancelHistoryPrepend()}}readerSampled(sample){if(sample.movedByReader&&this.jump?.landing===`landed`)this.jump.landing=`interrupted`;if(sample.followingTail||sample.movedByReader)this.viewport.stopPreserving()}contentCommitted(){if(!this.viewport.preserving||this.reading.pending)return false;if(this.landJump(false))return true;const landing=this.viewport.preserve();if(landing===null)return false;this.reading.preservePosition(landing);return true}reconcile(){const jump=this.jump;if(jump===null||this.reading.pending)return;if(jump.phase===`loading`){if(jump.landing===`pending`)this.landJump(false);return}if(this.input.loadingOlder)return;if(this.landJump(true))return;if((this.input.firstSeq===null||this.input.firstSeq>jump.seq)&&this.input.hasMore&&jump.repageHead!==this.input.firstSeq){jump.repageHead=this.input.firstSeq;this.viewport.beginPreserving();this.request(jump);return}const fallback=this.viewport.scrollToTurnAtOrAfter(jump.turn);this.cancel();if(fallback!==null)this.reading.acceptNavigation(fallback)}landJump(settle){const jump=this.jump;if(jump===null)return false;if(jump.landing===`interrupted`){if(settle){this.cancel();return true}return false}const landing=this.viewport.scrollToTurn(jump.turn);if(landing===null)return false;this.reading.acceptNavigation(landing);if(settle)this.cancel();else{this.viewport.beginPreserving(landing.position);jump.landing=`landed`}return true}request(jump){jump.phase=`loading`;const settled=()=>{if(this.jump!==jump)return;jump.phase=`settled`;this.cancelFrame();if(typeof requestAnimationFrame!==`function`)this.reconcile();else this.settleFrame=requestAnimationFrame(()=>{this.settleFrame=null;if(this.jump===jump)this.reconcile()})};this.input.loadThrough(jump.seq).then(settled,settled)}cancelFrame(){if(this.settleFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.settleFrame);this.settleFrame=null}};function useChatNavigation(viewport,reading,input){const[busyTurn,setBusyTurn]=(0,react.useState)(null);const[historyIntent,setHistoryIntent]=(0,react.useState)(`none`);const[navigation]=(0,react.useState)(()=>new ChatNavigation(viewport,reading,input,setBusyTurn,setHistoryIntent));(0,react.useLayoutEffect)(()=>{navigation.setInput(input)},[navigation,input]);(0,react.useLayoutEffect)(()=>()=>{navigation.dispose()},[navigation]);return{navigation,busyTurn,historyPending:historyIntent===`manual`,historyProcessing:historyIntent!==`none`}}function scrollMetrics(element){const height=element.clientHeight;return{top:element.scrollTop,height,floor:Math.max(0,element.scrollHeight-height)}}var ScrollFollow=class ScrollFollow{following;threshold;static owners=new WeakMap;target=null;sampledTop;constructor(following,threshold){this.following=following;this.threshold=threshold}static forElement(element){return this.owners.get(element)}bind(element){ScrollFollow.owners.set(element,this);return()=>{if(ScrollFollow.owners.get(element)===this)ScrollFollow.owners.delete(element)}}get active(){return this.following}get animating(){return this.target!==null}nearBottom(metrics){return Math.abs(metrics.floor-metrics.top)<=this.threshold}setFollowing(active){this.following=active;if(!active)this.target=null}reset(){this.setFollowing(false);this.sampledTop=void 0}sample(metrics,movedByReader=this.sampledTop===void 0||Math.abs(metrics.top-this.sampledTop)>.5){this.sampledTop=metrics.top;if(!this.animating&&movedByReader)this.following=this.nearBottom(metrics);return this.active}settle(metrics){const target=this.target;this.target=null;return this.sample(metrics,target===null?void 0:Math.abs(metrics.top-Math.min(target,metrics.floor))>this.threshold)}jump(element,metrics,top){const animated=this.animating;this.target=null;const target=Math.max(0,Math.min(metrics.floor,top));if(animated)element.scrollTo({top:target,behavior:`instant`});else if(target!==metrics.top)element.scrollTop=target;const landed={...metrics,top:element.scrollTop};this.sampledTop=landed.top;this.following=this.nearBottom(landed);return landed}toBottom(element,metrics,behavior){this.following=true;if(metrics.top===metrics.floor)return this.jump(element,metrics,metrics.floor);if(behavior===`instant`&&this.animating){if(this.target!==metrics.floor){this.target=metrics.floor;element.scrollTo({top:metrics.floor,behavior:`smooth`})}return metrics}if(behavior===`instant`||!this.animating&&this.nearBottom(metrics))return this.jump(element,metrics,metrics.floor);if(typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches)return this.jump(element,metrics,metrics.floor);if(this.target===null){this.target=metrics.floor;element.scrollTo({top:metrics.floor,behavior:`smooth`})}return metrics}interrupt(element,metrics){if(!this.animating)return;this.target=null;this.sampledTop=metrics.top;element.scrollTo({top:metrics.top,behavior:`instant`})}};function useScrollFollow(initial,threshold){const[follow]=(0,react.useState)(()=>new ScrollFollow(initial,threshold));return follow}const SCROLL_SAMPLE_INTERVAL_MS=500;var ChatReading=class{viewport;store;state;onChange;follow;sampleTimer=null;probeFrame=null;sampled=null;constructor(viewport,store,state,onChange,follow){this.viewport=viewport;this.store=store;this.state=state;this.onChange=onChange;this.follow=follow}get pending(){return this.sampleTimer!==null}get followingTail(){return this.state.followingTail}setStore(store){this.store=store}connect(sampled){this.sampled=sampled;return()=>{if(this.sampled===sampled)this.sampled=null}}dispose(){this.cancelPending();this.sampled=null}pauseFollowing(){this.cancelPending();this.publish({...this.state,followingTail:false})}followTail(behavior=`instant`){const landing=this.viewport.scrollToBottom(this.follow,behavior);if(landing===null)return;this.cancelPending();this.commit(landing,true,this.viewport.latestTurn)}followInputFold(input){this.cancelPending();return this.viewport.followInputFold(this.follow,input)}bindFolds(){return this.viewport.bindReader({follow:this.follow,landedAtTail:landing=>{this.cancelPending();this.commit(landing,true,this.viewport.latestTurn)},pending:()=>this.pending})}interruptFollow(){this.viewport.interruptFollow(this.follow)}restore(){const saved=this.store.read();if(saved===null){this.followTail();return}const landing=this.viewport.restore(saved);if(landing===null)return;this.cancelPending();const following=this.follow.nearBottom(landing.metrics);this.commit(landing,following,following?this.viewport.latestTurn:this.state.activeTurn,following);if(!this.state.followingTail&&landing.position===null){const position=this.viewport.capturePosition();if(position!==null)this.store.save(position)}this.refreshActiveTurn()}acceptNavigation(landing){this.cancelPending();const following=this.follow.nearBottom(landing.metrics);this.commit(landing,following,landing.turn??(following?this.viewport.latestTurn:this.state.activeTurn))}preservePosition(landing){this.cancelPending();this.commit(landing,this.state.followingTail,this.state.activeTurn)}onScroll=scroll=>{if(this.follow.animating)return;if(!scroll.movedByReader&&this.state.followingTail||scroll.movedByReader&&Math.abs(scroll.metrics.top-scroll.metrics.floor)<1){this.followTail();this.sampled?.({position:null,movedByReader:scroll.movedByReader,followingTail:true});return}this.sampleTimer??=window.setTimeout(this.flushSample,SCROLL_SAMPLE_INTERVAL_MS)};onScrollEnd=(outer=true)=>{if(this.follow.animating){if(!outer)return;const scroll=this.viewport.readScroll();if(scroll===null)return;if(this.follow.settle(scroll.metrics)){this.followTail();return}this.viewport.acknowledge(scroll.metrics);this.publish({...this.state,followingTail:false});this.refreshActiveTurn();return}this.flushSample()};onResize(){if(this.pending)return;if(this.state.followingTail)this.followTail();else this.refreshActiveTurn()}refreshActiveTurn(){if(this.pending)return;if(this.state.followingTail){this.publish({...this.state,initialized:true,activeTurn:this.viewport.latestTurn});return}if(this.probeFrame!==null)return;if(typeof requestAnimationFrame!==`function`)this.probe();else this.probeFrame=requestAnimationFrame(this.probe)}commit(landing,followingTail,activeTurn,initialized=true){if(followingTail)this.store.save(null);else if(landing.position!==null)this.store.save(landing.position);this.publish({initialized,followingTail,activeTurn})}publish(state){this.follow.setFollowing(state.followingTail);if(state.initialized===this.state.initialized&&state.followingTail===this.state.followingTail&&state.activeTurn===this.state.activeTurn)return;this.state=state;this.onChange(state)}cancelPending(){if(this.sampleTimer!==null)window.clearTimeout(this.sampleTimer);if(this.probeFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.probeFrame);this.sampleTimer=null;this.probeFrame=null}probe=()=>{this.probeFrame=null;if(this.pending)return;const scroll=this.viewport.readScroll();if(scroll===null)return;const activeTurn=this.follow.nearBottom(scroll.metrics)?this.viewport.latestTurn:this.viewport.readVisibleTurn(scroll.metrics);this.publish({...this.state,initialized:true,activeTurn})};flushSample=()=>{if(!this.pending)return;this.cancelPending();const scroll=this.viewport.readScroll();if(scroll===null)return;const followingTail=this.follow.sample(scroll.metrics,scroll.movedByReader);let position=null;if(!scroll.movedByReader&&followingTail)this.followTail();else{position=followingTail?null:this.viewport.capturePosition();this.viewport.acknowledge(scroll.metrics);if(followingTail||position!==null)this.store.save(position);const activeTurn=this.follow.nearBottom(scroll.metrics)?this.viewport.latestTurn:this.viewport.readVisibleTurn(scroll.metrics);this.publish({initialized:true,followingTail,activeTurn})}this.sampled?.({position,movedByReader:scroll.movedByReader,followingTail})}};function useChatReading(viewport,store,initialTurn){const[state,setState]=(0,react.useState)(()=>({initialized:false,followingTail:store.read()===null,activeTurn:initialTurn}));const follow=useScrollFollow(state.followingTail,25);const[reading]=(0,react.useState)(()=>new ChatReading(viewport,store,state,setState,follow));(0,react.useLayoutEffect)(()=>{reading.setStore(store)},[reading,store]);(0,react.useLayoutEffect)(()=>reading.bindFolds(),[reading]);(0,react.useLayoutEffect)(()=>()=>{reading.dispose()},[reading]);return{reading,state}}function useSearchableHidden(hidden,reveal,transition){const ref=(0,react.useRef)(null);(0,react.useLayoutEffect)(()=>{const element=ref.current;if(element===null)return;if(hidden&&element.contains(element.ownerDocument.activeElement)){reveal();return}const commit=()=>{if(hidden)element.setAttribute(`hidden`,`until-found`);else element.removeAttribute(`hidden`)};if(transition===void 0)commit();else transition(element,hidden,commit)},[hidden,reveal,transition]);(0,react.useEffect)(()=>{const element=ref.current;if(element===null)return;element.addEventListener(`beforematch`,reveal);return()=>{element.removeEventListener(`beforematch`,reveal)}},[reveal]);return ref}const FADE_OUT_MS=70;const CLOSE_DELAY_MS=50;const CLOSE_MS=110;const MOTION_SCOPE=`[data-chat-motion]`;const EASING=`cubic-bezier(0.4, 0, 0.2, 1)`;function motionEnabled(element){if(element.closest(MOTION_SCOPE)===null)return false;return typeof matchMedia!==`function`||!matchMedia(`(prefers-reduced-motion: reduce)`).matches}function hiddenOrCollapsing(element){return element.hasAttribute(`hidden`)||element.dataset.chatMotion===`collapse`}function revealedShare(box,progress){const start=box.height===0?0:box.fromHeight/box.height;return start+(1-start)*progress}function createFlowMotion(driver,foldingChanged,beforeInstantHide){const running=new Map;let folding=0;const foldIdleListeners=new Set;let batchScheduled=false;const boxes=new Map;let frameRequest=null;let batch=false;let cancelled=false;let clearEpoch=0;let batchCleanup=null;let cancelEmptyBatch=null;let settling=false;let anchoringDisabled=false;function cancelInput(){if(batch)cancelled=true}function resumeInput(){if(batch)cancelled=false}function batchMember(box){return box.element.parentElement?.closest(`[data-chat-motion="collapse"]`)===null}function runBatch(current){for(const box of[...boxes.values()]){if(!batchMember(box))continue;if(box.element.parentElement?.closest(`[hidden]`)!=null){box.finish();continue}const height=box.element.offsetHeight;const marginTop=Number.parseFloat(getComputedStyle(box.element).marginTop)||0;if(!box.closing){box.fromHeight=Math.min(height,box.height);box.fromMarginTop=Math.min(marginTop,box.marginTop);continue}box.height=height;box.marginTop=marginTop;if(height===0&&marginTop===0)box.finish()}const owned=[...boxes.values()];const members=owned.filter(batchMember).sort((left,right)=>left.element.compareDocumentPosition(right.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);if(!members.some(box=>box.closing))return false;batch=true;cancelled=false;const travelling=current.begin(members.map(box=>box.closing?box:{element:box.element,height:box.height-box.fromHeight,marginTop:box.marginTop-box.fromMarginTop,closing:false}));batchCleanup=()=>{current.finish(true)};for(const box of owned)box.take();for(const box of members){box.element.style.transition=`none`;box.element.style.height=`${box.closing?box.height:box.fromHeight}px`;box.element.style.marginTop=`${box.closing?box.marginTop:box.fromMarginTop}px`;box.element.style.opacity=box.closing?`1`:String(revealedShare(box,0))}const memberSet=new Set(members);const settledTravel=new Set;const freezeTravelling=()=>{for(const element of travelling){if(settledTravel.has(element))continue;settledTravel.add(element);element.style.translate=``;for(const box of owned){if(memberSet.has(box)||!element.contains(box.element))continue;box.element.style.transition=`none`;box.element.style.height=`${box.height}px`;box.element.style.marginTop=`${box.marginTop}px`;box.element.style.opacity=`1`}}};freezeTravelling();const reduced=typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;let started;let displacement=0;const settle=finishCancelled=>{batch=false;batchCleanup=null;cancelEmptyBatch=null;settling=true;try{for(const box of owned)if(boxes.get(box.element)===box)box.finish();current.finish(finishCancelled)}finally{settling=false}if(folding===0)notifyIdle();if([...boxes.values()].some(box=>box.held))flushBatch()};cancelEmptyBatch=()=>{if(members.some(box=>box.closing&&boxes.get(box.element)===box))return;if(frameRequest!==null)cancelAnimationFrame(frameRequest);frameRequest=null;settle(true)};const tick=now=>{frameRequest=null;started??=now;const elapsed=reduced?160:now-started;const linear=Math.min(1,Math.max(0,(elapsed-CLOSE_DELAY_MS)/CLOSE_MS));const progress=linear*linear*(3-2*linear);current.prepare(progress,cancelled);freezeTravelling();for(const box of members){if(boxes.get(box.element)!==box)continue;if(box.closing){box.element.style.height=`${box.height*(1-progress)}px`;box.element.style.marginTop=`${box.marginTop*(1-progress)}px`;box.element.style.opacity=travelling.has(box.element)?`1`:String(Math.max(0,1-elapsed/FADE_OUT_MS))}else{box.element.style.height=`${box.fromHeight+(box.height-box.fromHeight)*progress}px`;box.element.style.marginTop=`${box.fromMarginTop+(box.marginTop-box.fromMarginTop)*progress}px`;box.element.style.opacity=String(revealedShare(box,progress))}}displacement=current.frame(progress,cancelled);let removedBefore=0;for(const box of members){if(boxes.get(box.element)!==box)continue;if(box.closing){if(!travelling.has(box.element))box.element.style.translate=`0 ${displacement+removedBefore}px`;removedBefore+=(box.height+box.marginTop)*progress}else removedBefore-=(box.height-box.fromHeight+box.marginTop-box.fromMarginTop)*progress}if(linear<1){frameRequest=requestAnimationFrame(tick);return}settle(cancelled)};if(reduced)tick(0);else frameRequest=requestAnimationFrame(tick);return true}function foldActive(){return folding>0}function onFoldIdle(listener){if(folding===0)listener();else foldIdleListeners.add(listener);return()=>{foldIdleListeners.delete(listener)}}function flushBatch(){batchScheduled=false;if(batch)return;const current=[...boxes.values()].some(box=>box.closing)?driver():null;if(current!==null&&runBatch(current))return;const reduced=typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;for(const box of[...boxes.values()])if(reduced||box.held&&box.closing)box.finish();else if(box.held)box.release()}function scheduleBatch(){if(batchScheduled)return;batchScheduled=true;const epoch=clearEpoch;queueMicrotask(()=>{if(epoch===clearEpoch)flushBatch()})}function foldStarted(){folding+=1;if(folding!==1||anchoringDisabled)return;anchoringDisabled=true;foldingChanged(true)}function foldEnded(){folding=Math.max(0,folding-1);if(folding===0&&!settling)notifyIdle()}function notifyIdle(){if(anchoringDisabled){anchoringDisabled=false;foldingChanged(false)}const listeners=[...foldIdleListeners];foldIdleListeners.clear();for(const listener of listeners)listener()}function clearMotion(element,onEnd,timer){element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer);running.delete(element);boxes.delete(element);const{style}=element;style.height=``;style.marginTop=``;style.opacity=``;style.overflow=``;style.transition=``;style.translate=``;delete element.dataset.chatMotion}function cancelMotion(element){running.get(element)?.();cancelEmptyBatch?.()}function collapse(element,done){cancelMotion(element);const height=element.offsetHeight;const marginTop=Number.parseFloat(getComputedStyle(element).marginTop)||0;if(height===0&&marginTop===0){done();return}const{style}=element;const held=batch;element.dataset.chatMotion=`collapse`;foldStarted();scheduleBatch();style.transition=`none`;style.overflow=`hidden`;style.height=`${height}px`;style.marginTop=`${marginTop}px`;if(!held){element.offsetHeight;style.transition=`opacity ${FADE_OUT_MS}ms ${EASING}, height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`;style.opacity=`0`;style.height=`0px`;style.marginTop=`0px`}const finish=()=>{if(running.get(element)!==cancel)return;clearMotion(element,onEnd,timer);done();foldEnded()};const onEnd=event=>{if(event.target===element&&event.propertyName===`height`)finish()};const timer=held?void 0:setTimeout(finish,240);const cancel=()=>{clearMotion(element,onEnd,timer);foldEnded()};if(!held)element.addEventListener(`transitionend`,onEnd);running.set(element,cancel);boxes.set(element,{element,height,marginTop,fromHeight:height,fromMarginTop:marginTop,closing:true,held,finish,release:()=>{},take:()=>{element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer)}})}function reveal(element){cancelMotion(element);const height=element.offsetHeight;if(height===0)return;const marginTop=Number.parseFloat(getComputedStyle(element).marginTop)||0;scheduleBatch();const{style}=element;element.dataset.chatMotion=`reveal`;style.transition=`none`;style.overflow=`hidden`;style.opacity=`0`;style.height=`0px`;style.marginTop=`0px`;const finish=()=>{if(running.get(element)!==finish)return;clearMotion(element,onEnd,timer)};const onEnd=event=>{if(event.target===element&&event.propertyName===`height`)finish()};let timer;const startTransition=()=>{element.offsetHeight;style.transition=`height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, opacity ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`;style.height=`${height}px`;style.marginTop=`${marginTop}px`;style.opacity=`1`;timer=setTimeout(finish,240);element.addEventListener(`transitionend`,onEnd)};const held=batch;if(!held)startTransition();running.set(element,finish);const box={element,height,marginTop,fromHeight:0,fromMarginTop:0,closing:false,held,finish,release:()=>{box.held=false;startTransition()},take:()=>{element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer)}};boxes.set(element,box)}function clear(){clearEpoch++;batchScheduled=false;batch=false;cancelled=false;if(frameRequest!==null)cancelAnimationFrame(frameRequest);frameRequest=null;batchCleanup?.();batchCleanup=null;cancelEmptyBatch=null;foldIdleListeners.clear();for(const cancel of[...running.values()])cancel()}function hideNow(element,commit){beforeInstantHide?.(element);commit()}return{collapse,reveal,cancelMotion,foldActive,onFoldIdle,cancelInput,resumeInput,clear,hideNow,active:()=>running.size>0||batchScheduled||batch||settling,inputActive:()=>batch||batchScheduled&&[...boxes.values()].some(box=>box.closing&&batchMember(box))}}function useFlowTransition(motion,grow){const current=(0,react.useRef)(null);(0,react.useLayoutEffect)(()=>()=>{if(current.current!==null)motion?.cancelMotion(current.current);current.current=null},[motion]);const transition=(0,react.useCallback)((element,hidden,commit)=>{const mounted=current.current===element;const animate=mounted&&motionEnabled(element);current.current=element;if(hidden){if(hiddenOrCollapsing(element))return;if(mounted&&element.closest(MOTION_SCOPE)!==null&&motion!==void 0)motion.collapse(element,commit);else if(mounted&&motion?.hideNow!==void 0)motion.hideNow(element,commit);else commit();return}motion?.cancelMotion(element);const wasHidden=element.hasAttribute(`hidden`);commit();if(wasHidden&&animate&&grow)motion?.reveal(element)},[motion,grow]);return motion===void 0?void 0:transition}function useFlowHidden(hidden,reveal,motion){return useSearchableHidden(hidden,reveal,useFlowTransition(motion,false))}function useMotionHidden(ref,hidden,motion){const transition=useFlowTransition(motion,true);(0,react.useLayoutEffect)(()=>{const element=ref.current;if(element===null)return;transition?.(element,hidden,()=>{if(hidden)element.setAttribute(`hidden`,``);else element.removeAttribute(`hidden`)})},[ref,hidden,transition])}const READING_INTENTS=[`wheel`,`touchstart`,`pointerdown`,`keydown`,`beforematch`];const SCROLL_KEYS$1=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);var ChatViewport=class{elements=null;observer=null;events=null;turns=[];observation={top:0,landing:null};paging=null;historyPrepend=null;reader=null;historyEdge=null;historyHeight=0;historyScrolling=new Set;historyPointer=false;historyTouch=false;closing=null;closingFrame=null;settledContent=0;tailRequested=false;tailInput=false;retarget=null;motion=createFlowMotion(()=>this.foldDriver(),active=>{if(this.elements!==null)this.elements.scroller.style.overflowAnchor=active?`none`:``},element=>{this.measureClosing(element)});attach(list,column){this.detach();const scroller=list.closest(`[data-conversation-scroll]`)??list;const composer=scroller.querySelector(`[data-composer-seat]`);const spacer=list.querySelector(`[data-chat-turn-spacer]`);const elements={list,column,scroller,composer,spacer};this.elements=elements;if(spacer!==null)spacer.style.height=``;scroller.addEventListener(`scroll`,this.onHistoryScroll,{passive:true,capture:true});scroller.addEventListener(`pointerdown`,this.onHistoryPointerDown,{passive:true,capture:true});scroller.addEventListener(`touchstart`,this.onHistoryTouch,{passive:true,capture:true});for(const type of[`pointerup`,`pointercancel`,`touchend`,`touchcancel`,`transitionend`,`transitioncancel`])scroller.ownerDocument.addEventListener(type,this.onHistoryRelease,true);scroller.addEventListener(`scroll`,this.onScroll,{passive:true});scroller.addEventListener(`scrollend`,this.onScrollEnd,{passive:true,capture:true});for(const type of READING_INTENTS)scroller.addEventListener(type,this.onIntent,{passive:true,capture:true});if(typeof ResizeObserver!==`undefined`){this.observer=new ResizeObserver(entries=>{if(this.elements!==elements)return;if(entries.some(entry=>entry.target===elements.scroller))this.historyHeight=elements.scroller.clientHeight;this.settledContent=elements.scroller.scrollHeight-this.spacerHeight();this.keepAboveClosing();this.reclaimBelow();this.invalidate();this.pruneHistoryScrolling();this.events?.resize()});this.observer.observe(column);this.observer.observe(scroller);if(composer!==null)this.observer.observe(composer)}}detach(){this.historyPrepend=null;this.stopPreserving();this.motion.clear();if(this.elements!==null)this.elements.scroller.style.overflowAnchor=``;this.dropClosing();const scroller=this.elements?.scroller;scroller?.removeEventListener(`scroll`,this.onHistoryScroll,true);scroller?.removeEventListener(`pointerdown`,this.onHistoryPointerDown,true);scroller?.removeEventListener(`touchstart`,this.onHistoryTouch,true);for(const type of[`pointerup`,`pointercancel`,`touchend`,`touchcancel`,`transitionend`,`transitioncancel`])scroller?.ownerDocument.removeEventListener(type,this.onHistoryRelease,true);this.historyHeight=0;this.historyScrolling.clear();this.historyPointer=false;this.historyTouch=false;this.elements?.scroller.removeEventListener(`scroll`,this.onScroll);this.elements?.scroller.removeEventListener(`scrollend`,this.onScrollEnd,true);for(const type of READING_INTENTS)this.elements?.scroller.removeEventListener(type,this.onIntent,true);this.observer?.disconnect();this.observer=null;this.elements=null;this.events=null;this.tailRequested=false;this.tailInput=false;this.retarget=null;this.turns=[];this.observation={top:0,landing:null}}connect(events){this.events=events;return()=>{if(this.events===events)this.events=null}}updateTurns(turns){this.turns=turns}get latestTurn(){return this.turns.at(-1)?.turn??null}invalidate(){this.observation.landing=null}spacerHeight(){const spacer=this.elements?.spacer;return spacer==null?0:Number.parseFloat(spacer.style.height)||0}setSpacer(height){const spacer=this.elements?.spacer;if(spacer==null)return;const next=height<=0?``:`${Math.ceil(height)}px`;if(spacer.style.height!==next)spacer.style.height=next}bindReader(reader){this.reader=reader;return()=>{if(this.reader===reader)this.reader=null}}followInputFold(follow,input){if(this.elements===null||this.reader===null||!this.motion.inputActive())return false;this.interruptFollow(follow);this.tailRequested=true;this.tailInput||=input;this.retarget?.();return true}foldDriver(){const elements=this.elements;const reader=this.reader;if(elements===null||reader===null)return null;const{follow}=reader;let tail=false;let start=0;let base=0;let target=0;let removed=0;let growth=0;let initialHeight=0;let finalRoom=0;let previousColumnHeight=0;let previousProgress=0;let segmentProgress=0;let segmentTop=0;let written=0;const closing=[];const travelling=new Set;let reference=null;let referenceTop=0;let viewportTop=0;const screenTop=element=>element.getBoundingClientRect().top-viewportTop;const aim=()=>{const finalHeight=initialHeight-removed+growth;const height=elements.scroller.clientHeight;target=tail?Math.max(base,finalHeight-height,0):base;finalRoom=target===0?0:Math.max(0,target+height-finalHeight)};const restart=()=>{segmentTop=elements.scroller.scrollTop;segmentProgress=previousProgress};const automatic=cancelled=>!(cancelled&&tail);const position=(progress,cancelled)=>{if(!automatic(cancelled))return elements.scroller.scrollTop;const remaining=segmentProgress===1?1:(progress-segmentProgress)/(1-segmentProgress);return segmentTop+(target-segmentTop)*remaining};const room=(top,progress,cancelled)=>Math.max(automatic(cancelled)?finalRoom:0,top+elements.scroller.clientHeight-(initialHeight+(growth-removed)*progress));return{begin:boxes=>{tail=this.tailRequested||follow.active&&!reader.pending();const input=this.tailInput;this.tailRequested=false;this.tailInput=false;viewportTop=elements.scroller.getBoundingClientRect().top;start=elements.scroller.scrollTop;const originalRoom=this.spacerHeight();initialHeight=Math.max(elements.column.offsetHeight,elements.scroller.scrollHeight-originalRoom);if(tail&&!input){const pinned=originalRoom===0&&this.settledContent>elements.scroller.clientHeight&&follow.active&&!reader.pending()&&!follow.animating;const external=elements.scroller.scrollHeight-originalRoom-this.settledContent;if(external>.5&&pinned){elements.scroller.scrollTop=start+external;start=elements.scroller.scrollTop;this.observation={top:start,landing:null}}}let above=0;const below=[];for(const box of boxes){const amount=box.height+box.marginTop;const top=box.element.getBoundingClientRect().top-box.marginTop;if(box.closing){removed+=amount;above+=Math.max(0,Math.min(amount,viewportTop-top));if(top>=viewportTop)below.push(box.element);closing.push(box)}else{growth+=amount;if(top<viewportTop)above-=amount}}if(!tail)reference=this.readingReference();const referenceBefore=reference===null?0:screenTop(reference);elements.column.dataset.inputFold=``;if(reference!==null){referenceTop=screenTop(reference);above-=referenceTop-referenceBefore}base=Math.max(0,start-above);segmentTop=start;written=start;previousColumnHeight=elements.column.offsetHeight;aim();this.setSpacer(Math.max(originalRoom,finalRoom,removed));if(tail)follow.setFollowing(true);this.retarget=()=>{tail=true;follow.setFollowing(true);this.motion.resumeInput();aim();restart();if(target<=segmentTop)return;for(const box of closing){const shift=Number.parseFloat(box.element.style.translate.split(` `)[1]??``)||0;if(box.element.getBoundingClientRect().top-shift-box.marginTop>=viewportTop)travelling.add(box.element)}};if(tail&&target>start)for(const element of below)travelling.add(element);return travelling},prepare:(progress,cancelled)=>{if(this.elements!==elements)return;if(!tail){const drift=elements.scroller.scrollTop-written;if(Math.abs(drift)>.5){base=Math.max(0,base+drift);segmentTop+=drift;referenceTop-=drift;aim()}}const added=elements.column.offsetHeight-previousColumnHeight;if(added!==0){initialHeight+=added;aim();restart()}const top=position(progress,cancelled);this.setSpacer(Math.max(this.spacerHeight(),room(top,progress,cancelled)))},frame:(progress,cancelled)=>{if(this.elements!==elements)return 0;const top=position(progress,cancelled);elements.scroller.scrollTop=top;this.setSpacer(room(top,progress,cancelled));written=elements.scroller.scrollTop;if(reference!==null&&progress===1)referenceTop=screenTop(reference);if(automatic(cancelled))this.observation={top:written,landing:null};previousColumnHeight=elements.column.offsetHeight;previousProgress=progress;return written-start},finish:cancelled=>{this.retarget=null;this.tailRequested=false;this.tailInput=false;if(this.elements!==elements)return;elements.column.offsetHeight;delete elements.column.dataset.inputFold;if(!tail||cancelled){if(!tail&&reference?.isConnected===true&&reference.closest(`[hidden]`)===null){const shift=screenTop(reference)-referenceTop;if(Math.abs(shift)>.5){const top=elements.scroller.scrollTop+shift;const content=elements.scroller.scrollHeight-this.spacerHeight();this.setSpacer(Math.max(this.spacerHeight(),top+elements.scroller.clientHeight-content));elements.scroller.scrollTop=top}}const metrics=scrollMetrics(elements.scroller);const height=elements.scroller.scrollHeight-this.spacerHeight();this.setSpacer(metrics.top===0?0:Math.max(0,metrics.top+metrics.height-height));if(tail)this.invalidate();else this.observation={top:elements.scroller.scrollTop,landing:null};return}const content=elements.scroller.scrollHeight-this.spacerHeight();const clientHeight=elements.scroller.clientHeight;const top=Math.max(target,content-clientHeight,0);this.setSpacer(top===0?0:Math.max(0,top+clientHeight-content));elements.scroller.scrollTop=top;const metrics=scrollMetrics(elements.scroller);const landing={metrics,position:null,turn:this.latestTurn};this.observation={top:metrics.top,landing};reader.landedAtTail(landing)}}}readingReference(){const elements=this.elements;if(elements===null)return null;const viewport=elements.scroller.getBoundingClientRect();const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;if(rows[middle].getBoundingClientRect().bottom>viewport.top)high=middle;else low=middle+1}for(let index=low;index<rows.length;index++){const row=rows[index];if(row.hasAttribute(`hidden`))continue;const rect=row.getBoundingClientRect();if(rect.top>=viewport.bottom)return null;if(rect.height===0||rect.bottom<=viewport.top)continue;if(row.hasAttribute(`data-chat-motion`)||row.querySelector(`[data-chat-motion]`)!==null)continue;return row}return null}measureClosing(element){const elements=this.elements;const reader=this.reader;if(elements===null||reader===null||this.closing!==null||!element.isConnected)return;if(!reader.follow.active||reader.follow.animating||reader.pending())return;if(this.paging!==null||this.motion.foldActive()||this.motion.inputActive())return;const scroller=elements.scroller;const scrollHeight=scroller.scrollHeight;const height=scroller.clientHeight;const painted=scroller.scrollTop+height;const origin=scroller.getBoundingClientRect().top-scroller.scrollTop;const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;const end=row=>row!==element&&!row.contains(element)&&(element.compareDocumentPosition(row)&Node.DOCUMENT_POSITION_PRECEDING)!==0?painted:scrollHeight;const screen=(row,offset)=>offset-origin-(end(row)-height);let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;const row=rows[middle];if(screen(row,row.getBoundingClientRect().bottom)>0)high=middle;else low=middle+1}let first=-1;for(let index=low;index<rows.length&&first<0;index++){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.top)>=height)break;if(rect.height>0&&!row.hasAttribute(`hidden`))first=index}if(first<0)return;const anchors=[];const add=(row,rect)=>{if(rect.height>0&&!row.hasAttribute(`hidden`))anchors.push({element:row,fromEnd:end(row)-(rect.top-origin)})};add(rows[first],rows[first].getBoundingClientRect());for(let index=first+1;index<rows.length;index++){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.top)>=height)break;add(row,rect)}for(let index=first-1;index>=0;index--){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.bottom)<=-height)break;add(row,rect)}this.closing={rows:anchors,content:scrollHeight-this.spacerHeight()};if(typeof requestAnimationFrame===`function`)this.closingFrame=requestAnimationFrame(()=>{this.closingFrame=requestAnimationFrame(()=>{this.closingFrame=null;this.closing=null})})}dropClosing(){this.closing=null;if(this.closingFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.closingFrame);this.closingFrame=null}keepAboveClosing(){const closing=this.closing;const elements=this.elements;const reader=this.reader;if(closing===null)return;this.dropClosing();if(elements===null||reader===null||!reader.follow.active||reader.follow.animating||reader.pending())return;if(this.paging!==null||this.motion.foldActive()||this.motion.inputActive())return;const scroller=elements.scroller;const content=scroller.scrollHeight-this.spacerHeight();if(content>=closing.content-.5)return;const height=scroller.clientHeight;const origin=scroller.getBoundingClientRect().top-scroller.scrollTop;const cap=height/2;let top=content+cap-height;for(const row of closing.rows){if(!row.element.isConnected||row.element.closest(`[hidden]`)!==null)continue;const rect=row.element.getBoundingClientRect();if(rect.height===0)continue;top=rect.top-origin-(height-row.fromEnd);break}if(top+height-content>cap)top=content+cap-height;top=Math.max(0,top);this.setSpacer(top===0?0:Math.max(0,top+height-content));if(scroller.scrollTop!==top)scroller.scrollTop=top;const metrics=scrollMetrics(scroller);this.observation={top:metrics.top,landing:{metrics,position:null,turn:this.latestTurn}}}resetBelow(){this.dropClosing();this.setSpacer(0);this.invalidate()}reclaimBelow(){const elements=this.elements;if(elements===null||elements.spacer===null)return;const current=this.spacerHeight();if(current===0||this.motion.foldActive())return;const scroll=this.readScroll();if(scroll===null||scroll.movedByReader)return;const floorWithoutSpacer=scroll.metrics.floor-current;this.setSpacer(Math.min(current,Math.max(0,scroll.metrics.top-floorWithoutSpacer)))}interruptFollow(follow){if(!follow.animating)return;const metrics=this.metrics();if(metrics===null||this.elements===null)return;follow.interrupt(this.elements.scroller,metrics);this.observation={top:metrics.top,landing:null}}acknowledge(metrics){this.observation={top:metrics.top,landing:null};this.reclaimBelow()}readScroll(){const metrics=this.metrics();if(metrics===null)return null;return{metrics,movedByReader:Math.abs(metrics.top-Math.min(this.observation.top,metrics.floor))>.5}}metrics(){const scroller=this.elements?.scroller;if(scroller===void 0)return null;return scrollMetrics(scroller)}anchor(key,identity=`position`){if(this.elements===null)return null;let nodePart=null;for(const row of this.elements.list.querySelectorAll(`[data-chat-anchor-key]:not([hidden]):not([hidden] *)`)){if(row.dataset.chatAnchorKey===key||identity===`node`&&row.dataset.chatNodeKey===key)return row;if(nodePart===null&&row.dataset.chatNodeKey===key)nodePart=row}return nodePart}capturePosition(){const elements=this.elements;if(elements===null)return null;const{list,scroller,composer}=elements;const viewport=scroller.getBoundingClientRect();const bottom=composer?.getBoundingClientRect().top??viewport.bottom;let anchor=null;if(typeof document.elementsFromPoint===`function`&&bottom>viewport.top){const content=list.getBoundingClientRect();const left=Math.max(viewport.left,content.left);const right=Math.min(viewport.right,content.right);for(const element of document.elementsFromPoint(left+Math.max(0,right-left)/2,viewport.top+1)){const row=element.closest(`[data-chat-anchor-key]`);if(row!==null&&row.dataset.chatFlowKind!==`turn-process`&&list.contains(row)){anchor=row.dataset.chatGroupKey===void 0?row:row.querySelector(`[data-step-process-content] > [data-chat-anchor-key]:not(:empty):not([hidden]):not([hidden] *)`)??row;break}}}if(anchor===null){const rows=list.querySelectorAll(`[data-chat-flow-key]:not([data-chat-group-key]):not([data-chat-flow-kind="turn-process"]):not(:empty):not([hidden]):not([hidden] *)`);let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;if(rows.item(middle).getBoundingClientRect().bottom>viewport.top)high=middle;else low=middle+1}const row=rows[low];anchor=row!==void 0&&row.getBoundingClientRect().top<bottom?row:rows[0]??null}const key=anchor?.dataset.chatAnchorKey;return anchor===null||key===void 0?null:{anchorKey:key,anchorTop:anchor.getBoundingClientRect().top-viewport.top,scrollTop:scroller.scrollTop}}readVisibleTurn(metrics=this.metrics()){const knownTurn=this.observation.landing?.turn;if(knownTurn!=null&&metrics?.top===this.observation.top)return knownTurn;const elements=this.elements;const first=this.turns[0];if(elements===null||metrics===null||first===void 0)return null;const line=elements.scroller.getBoundingClientRect().top+Math.min(96,metrics.height*.2);const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;let low=0;let high=rows.length;let reading=first.turn;while(low<high){const middle=low+high>>>1;const row=rows[middle];if(row.getBoundingClientRect().top>line)high=middle;else{const value=row.getAttribute(`data-chat-turn`);const turn=value===null?NaN:Number(value);if(Number.isSafeInteger(turn))reading=turn;low=middle+1}}return reading}scrollToTurn(turn){const item=this.turns.find(candidate=>candidate.turn===turn);if(item===void 0)return null;const row=this.anchor(item.anchorKey,`node`);return row===null?null:this.align(row,24,turn)}scrollToTurnAtOrAfter(turn){if(this.elements===null)return null;for(const row of this.elements.list.querySelectorAll(`[data-chat-turn]:not([hidden]):not([hidden] *)`)){const candidate=Number(row.dataset.chatTurn);if(Number.isSafeInteger(candidate)&&candidate>=turn)return this.align(row,24,candidate)}return null}restore(position){const row=this.anchor(position.anchorKey);if(row!==null)return this.align(row,position.anchorTop,null);const metrics=this.metrics();return metrics===null?null:this.write(position.scrollTop,metrics,null)}beginManualPaging(){if(this.elements===null)return;if(this.elements.scroller.scrollTop<=.5)this.beginPaging();else{this.beginPreserving();if(!this.preserving)this.beginPaging()}}beginPaging(){this.stopPreserving();const row=this.pagingAnchor();if(row!==null)this.retain(row)}pagingAnchor(){return this.elements?.list.querySelector(`[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)`)??null}beginPreserving(position=this.capturePosition()){this.stopPreserving();if(position===null)return;const row=this.anchor(position.anchorKey);if(row===null)return;this.retain(row,position)}measurePaging(row,position,previousGroup){const elements=this.elements;const key=row.dataset.chatAnchorKey;if(elements===null||key===void 0)return null;const top=row.getBoundingClientRect().top;const body=row.closest(`[data-step-process-body]`);const content=body?.querySelector(`[data-step-process-content]`);return{row,group:body===null||content==null?null:{body,content,top:previousGroup?.top??top-body.getBoundingClientRect().top},position:position??{anchorKey:key,anchorTop:top-elements.scroller.getBoundingClientRect().top,scrollTop:elements.scroller.scrollTop}}}retain(row,position){const paging=this.measurePaging(row,position);if(paging===null)return null;this.retainPaging(paging);return paging}retainPaging(paging){this.stopPreserving();this.paging=paging;if(paging.group!==null)this.observer?.observe(paging.group.content)}stopPreserving(){const group=this.paging?.group;if(group!=null)this.observer?.unobserve(group.content);this.paging=null}get preserving(){return this.paging!==null}preserve(){const paging=this.resolvePaging(this.paging);if(paging===null){this.stopPreserving();return null}if(paging!==this.paging)this.retainPaging(paging);return this.applyPaging(paging)}resolvePaging(paging){const elements=this.elements;if(paging===null||elements===null)return null;if(!elements.list.contains(paging.row)){const replacement=this.anchor(paging.position.anchorKey);if(replacement===null)return null;paging=this.measurePaging(replacement,paging.position,paging.group);if(paging===null)return null}return paging.row.closest(`[hidden]`)!==null||paging.row.matches(`:empty`)?null:paging}applyPaging(paging){const elements=this.elements;if(elements===null)return null;const{row,group,position}=paging;if(group!==null&&group.body.contains(row)){const top=row.getBoundingClientRect().top-group.body.getBoundingClientRect().top;const metrics=scrollMetrics(group.body);const target=Math.max(0,Math.min(metrics.floor,metrics.top+top-group.top));if(metrics.top!==target){const follow=ScrollFollow.forElement(group.body);if(follow===void 0)group.body.scrollTop=target;else{follow.jump(group.body,metrics,target);follow.setFollowing(false)}}}const metrics=this.metrics();if(metrics===null)return null;const top=row.getBoundingClientRect().top-elements.scroller.getBoundingClientRect().top;const target=metrics.top+top-position.anchorTop;return this.write(target,metrics,null,{key:position.anchorKey,top})}scrollToBottom(follow,behavior=`instant`){const metrics=this.metrics();if(metrics===null||this.elements===null)return null;this.observation={top:metrics.top,landing:null};this.reclaimBelow();const landing={metrics:follow.toBottom(this.elements.scroller,scrollMetrics(this.elements.scroller),behavior),position:null,turn:this.latestTurn};this.observation={top:landing.metrics.top,landing};return landing}align(row,offset,turn){const metrics=this.metrics();if(metrics===null||this.elements===null)return null;const top=row.getBoundingClientRect().top-this.elements.scroller.getBoundingClientRect().top;return this.write(metrics.top+top-offset,metrics,turn,{key:row.dataset.chatAnchorKey,top})}write(target,metrics,turn,anchor){if(this.elements===null)return null;const top=Math.max(0,Math.min(metrics.floor,target));if(top!==metrics.top)this.elements.scroller.scrollTop=top;const actual=this.elements.scroller.scrollTop;const landing={metrics:{...metrics,top:actual},turn,position:anchor?.key===void 0?null:{anchorKey:anchor.key,anchorTop:anchor.top-(actual-metrics.top),scrollTop:actual}};this.observation={top:actual,landing};return landing}setHistoryEdge=element=>{this.historyEdge=element};pruneHistoryScrolling(){for(const target of this.historyScrolling)if(this.elements?.scroller.contains(target)!==true)this.historyScrolling.delete(target)}confirmHistoryStart(){const scroller=this.elements?.scroller;if(scroller===void 0||this.historyEdge===null||this.historyHeight<=0)return false;return scroller.getBoundingClientRect().top-this.historyEdge.getBoundingClientRect().bottom<=this.historyHeight*2}get historyInputHeld(){return this.historyTouch||this.historyPointer}historyConsumption(){const elements=this.elements;if(elements===null)return`unavailable`;if(this.historyTouch)return`touch`;if(this.historyScrolling.size>0&&(this.historyScrolling.size!==1||!this.historyScrolling.has(elements.scroller)))return`inner-scroll`;if(this.motion.active()||this.reader?.follow.animating)return`motion`;if(this.historyPointer)return`pointer`;if(this.historyScrolling.size===0)return elements.scroller.scrollTop<=.5?`prepend`:`preserve`;if(this.preserving||typeof CSS===`undefined`||!CSS.supports(`overflow-anchor`,`auto`))return`unavailable`;return elements.scroller.scrollTop<=.5?`prepend`:`native`}beginHistoryPrepend(){const row=this.pagingAnchor();this.historyPrepend=row===null?null:this.measurePaging(row);return this.historyPrepend!==null}cancelHistoryPrepend(){this.historyPrepend=null}finishHistoryPrepend(){const pending=this.historyPrepend;this.historyPrepend=null;const paging=this.resolvePaging(pending);return paging===null?null:this.applyPaging(paging)}onHistoryScroll=event=>{const target=event.target;if(target===this.elements?.scroller||target.hasAttribute(`data-step-process-body`))this.historyScrolling.add(target)};onHistoryPointerDown=()=>{this.historyPointer=true;this.events?.history?.()};onHistoryTouch=()=>{this.historyTouch=true;this.events?.history?.()};onHistoryRelease=event=>{if(event.type===`pointerup`||event.type===`pointercancel`)this.historyPointer=false;if(event.type===`touchend`||event.type===`touchcancel`)this.historyTouch=`touches`in event&&event.touches.length>0;this.events?.history?.()};onScroll=event=>{if(this.elements===null||event.target!==this.elements.scroller)return;if(this.observation.landing!==null&&this.elements.scroller.scrollTop===this.observation.top)return;this.invalidate();if(this.paging!==null){this.events?.resize();return}const scroll=this.readScroll();if(scroll!==null)this.events?.scroll(scroll)};onScrollEnd=event=>{if(event.target!==null)this.historyScrolling.delete(event.target);this.events?.history?.();if(event.target===this.elements?.scroller){this.events?.scrollEnd(true);this.reclaimBelow()}else if(event.target.hasAttribute(`data-step-process-body`))this.events?.scrollEnd(false)};onIntent=event=>{if(event.type===`keydown`||event.type===`pointerdown`){if(event.target.closest?.(`[data-composer-seat]`)!=null)return;if(event.type===`keydown`&&!SCROLL_KEYS$1.has(event.key))return}this.events?.intent?.();if(this.paging===null)return;this.stopPreserving();this.events?.interact()}};function useChatViewport(){const listRef=(0,react.useRef)(null);const columnRef=(0,react.useRef)(null);const[viewport]=(0,react.useState)(()=>new ChatViewport);(0,react.useLayoutEffect)(()=>{if(listRef.current===null||columnRef.current===null)return;viewport.attach(listRef.current,columnRef.current);return()=>{viewport.detach()}},[viewport]);return{viewport,listRef,columnRef}}function useChatScroll(input){const{isOpen,order,firstSeq,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,deferCompletedTurns,loadedTurns,chatScroll,hasMore,loadingOlder,historyLoadStatus,loadOlder,consumeOlder,loadThrough,transcriptView}=input;const{viewport,listRef,columnRef}=useChatViewport();const[historyInputHeld,setHistoryInputHeld]=(0,react.useState)(false);const{reading,state}=useChatReading(viewport,chatScroll,loadedTurns.at(-1)?.turn??null);const navigationInput=(0,react.useMemo)(()=>({firstSeq,loadingOlder,hasMore,historyLoadStatus,isOpen,loadOlder,consumeOlder,loadThrough}),[firstSeq,loadingOlder,hasMore,historyLoadStatus,isOpen,loadOlder,consumeOlder,loadThrough]);const{navigation,busyTurn,historyPending,historyProcessing}=useChatNavigation(viewport,reading,navigationInput);const content=(0,react.useRef)({input,applied:null,opened:false});const cancelPendingFollow=(0,react.useCallback)(()=>{viewport.motion.cancelInput()},[viewport]);const processContent=(0,react.useCallback)(()=>{const current=content.current.input;if(!current.isOpen&&!content.current.opened)return;const previous=content.current.applied;const steeringInput=current.steeringId!==null&&current.steeringId!==previous?.steeringId&&current.steeringId!==previous?.submissionId;const submissionInput=current.submissionId!==null&&current.submissionId!==previous?.submissionId&&current.submissionId!==previous?.steeringId;const ownInput=current.lastIsUser&&current.lastKey!==previous?.lastKey||steeringInput||submissionInput;if(reading.pending&&!ownInput)return;content.current.applied=current;if(current.isOpen&&!content.current.opened){content.current.opened=true;navigation.reset();reading.restore();return}if(ownInput){navigation.cancel();if(current.deferCompletedTurns&&reading.followInputFold(true))return;const steering=steeringInput||submissionInput&&current.submissionSteers;reading.followTail(current.deferCompletedTurns&&!steering?`smooth`:`instant`);return}if(navigation.contentCommitted()){navigation.reconcile();return}if((previous===null||current.isOpen!==previous.isOpen||current.firstSeq!==previous.firstSeq||current.lastKey!==previous.lastKey||current.order.length!==previous.order.length||current.running!==previous.running||current.steeringId!==previous.steeringId||current.submissionId!==previous.submissionId)&&reading.followingTail){navigation.cancel();if(current.deferCompletedTurns&&reading.followInputFold(false))return;reading.followTail()}else navigation.reconcile()},[reading,navigation]);(0,react.useLayoutEffect)(()=>{const disconnectViewport=viewport.connect({scroll:event=>{if(!content.current.opened)return;if(!event.movedByReader&&viewport.motion.foldActive())return;reading.onScroll(event)},scrollEnd:outer=>{reading.onScrollEnd(outer);navigation.requestHistoryCheck()},interact:()=>{navigation.readerInteracted()},history:()=>{setHistoryInputHeld(viewport.historyInputHeld);if(content.current.opened)navigation.requestHistoryCheck()},intent:()=>{cancelPendingFollow();reading.interruptFollow()},resize:()=>{if(!content.current.opened)return;navigation.requestHistoryCheck();if(navigation.contentCommitted()){navigation.reconcile();return}if(!content.current.input.deferCompletedTurns||!viewport.motion.foldActive())reading.onResize();navigation.reconcile()}});const disconnectReading=reading.connect(sample=>{navigation.readerSampled(sample);processContent();navigation.requestHistoryCheck()});return()=>{disconnectViewport();disconnectReading();content.current.opened=false;content.current.applied=null}},[viewport,reading,navigation,processContent,cancelPendingFollow]);(0,react.useLayoutEffect)(()=>{const previous=content.current.input;content.current.input={order,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,loadedTurns,chatScroll,deferCompletedTurns,transcriptView,...navigationInput};if(!deferCompletedTurns){cancelPendingFollow();reading.interruptFollow()}viewport.updateTurns(loadedTurns);const layoutChanged=previous.order!==order||previous.isOpen!==isOpen;const historyConsumed=previous.historyLoadStatus===`pendingConsumption`&&historyLoadStatus===`idle`;if(!isOpen||historyLoadStatus===`error`)viewport.cancelHistoryPrepend();else if(layoutChanged||historyConsumed){const landing=viewport.finishHistoryPrepend();if(landing!==null)reading.preservePosition(landing)}if(layoutChanged)viewport.invalidate();viewport.reclaimBelow();processContent();if(layoutChanged&&content.current.opened)reading.refreshActiveTurn();if(content.current.opened)navigation.requestHistoryCheck()},[viewport,reading,processContent,navigationInput,isOpen,order,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,loadedTurns,chatScroll,deferCompletedTurns,transcriptView,cancelPendingFollow]);const previousView=(0,react.useRef)(transcriptView);(0,react.useLayoutEffect)(()=>{if(previousView.current===transcriptView)return;previousView.current=transcriptView;cancelPendingFollow();reading.interruptFollow();return viewport.motion.onFoldIdle(()=>{viewport.resetBelow();if(content.current.opened)reading.onResize()})},[transcriptView,viewport,reading,cancelPendingFollow]);const returnToBottom=(0,react.useCallback)(()=>{cancelPendingFollow();navigation.cancel();reading.followTail()},[navigation,reading,cancelPendingFollow]);return{listRef,columnRef,...state,busyTurn,motion:viewport.motion,navigateToTurn:navigation.navigateToTurn,loadEarlier:navigation.loadEarlier,historyPending,historyProcessing,historyInputHeld,historyEdgeRef:viewport.setHistoryEdge,returnToBottom}}function openFailureMessage(error,fallback){const message=error instanceof Error?error.message:String(error);return message===``?fallback:message}function observedInputs(order,nodes){const observed=new Set;let lastInputTurn;for(const key of order){const node=nodes.get(key);if(node===void 0||!isAtOrOutside(node,`input`))continue;if(node.location.kind===`turn`||node.location.kind===`step`)lastInputTurn=node.location.turn.turn;const data=node.data;const source=typeof data===`object`&&data!==null&&`source`in data?data.source:void 0;if(typeof source===`object`&&source!==null&&`kind`in source&&source.kind===`user`&&`rpcId`in source&&typeof source.rpcId===`string`)observed.add(source.rpcId)}return{rpcIds:observed,lastInputTurn}}const MOTION_TAIL_MS=800;function ChatView({useSession,useChat,useConversation,useSessions,renderSlot,sessionId,openFile,openExternalLink,resolveFilePath,useContextMenu,loadOlder,consumeOlder,loadThrough,loadImage,inspectCall,inspectRequest,chatScroll,forkAt,usePresentation,useProjection,useInteractionIds,dispatchInteraction,t,fileDrag}){const{getTriggerProps}=useContextMenu();const getMarkdownTriggerProps=(0,react.useCallback)(target=>getTriggerProps(()=>{switch(target.kind){case`file`:return{kind:`file`,value:{sessionId,path:resolveFilePath(target.path),...target.line===void 0?{}:{line:target.line}}};case`url`:return{kind:`url`,value:{sessionId,url:target.url}};case`image`:return{kind:`image`,value:{sessionId,url:target.url,...target.name===void 0?{}:{name:target.name},...target.mediaType===void 0?{}:{mediaType:target.mediaType},...target.path===void 0?{}:{path:resolveFilePath(target.path)}}}}}),[getTriggerProps,resolveFilePath,sessionId]);const order=useChat(s=>s.order);const groupedEntries=useConversation(snapshot=>snapshot.views.grouped(`chat`)?.entries);const entries=(0,react.useMemo)(()=>groupedEntries??order.map(key=>({kind:`node`,key})),[groupedEntries,order]);const nodeStore=useChat(s=>s.nodes);const deferCompletedTurns=usePresentation(policy=>policy.collapseTiming===`next-input`);const transcriptView=usePresentation(policy=>policy.mode);const turnNavigationItems=useChat(s=>s.navigation.items());const turnOutline=useProjection(`turnOutline`);const railItems=(0,react.useMemo)(()=>mergeTurnRailItems(turnNavigationItems,turnOutline),[turnNavigationItems,turnOutline]);const inbox=useProjection(`inbox`);const cwd=useSessions(s=>s.byId[sessionId]?.cwd);const directory=useSessions(s=>selectSessionDirectory(s,sessionId));const fileImages=(0,react.useMemo)(()=>({fileDrag,resolve:path=>fileMediaUrl(document.baseURI,resolveWorkspacePath(directory,path)),resourceAddress:path=>sessionFileAddress(sessionId,resolveWorkspacePath(directory,path)),labels:{open:t(`image.open`),loading:t(`image.loading`),failed:t(`image.failed`),dialog:t(`image.dialog`),close:t(`image.close`)}}),[directory,t,fileDrag,sessionId]);const codeLabels=(0,react.useMemo)(()=>markdownLabels(t).code,[t]);const renderCode=(0,react.useCallback)(fence=>renderSlot(`conversation.chat.markdown.fence`,fence,{entryKey:fence.lang,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceCodeBlock,{lang:fence.lang,code:fence.code,streaming:fence.streaming,labels:codeLabels,diff:false})}),[renderSlot,codeLabels]);const running=useSession(s=>s.running);const[motionTail,setMotionTail]=(0,react.useState)(false);(0,react.useEffect)(()=>{if(!deferCompletedTurns){setMotionTail(false);return}if(running){setMotionTail(true);return}const timer=setTimeout(()=>{setMotionTail(false)},MOTION_TAIL_MS);return()=>{clearTimeout(timer)}},[running,deferCompletedTurns]);const openState=useSession(s=>s.openState);const openError=useSession(s=>s.openError);const hasMore=useSession(s=>s.hasMore);const loadingOlder=useSession(s=>s.loadingOlder);const historyLoadStatus=useSession(s=>s.historyLoadStatus);const historyWasPartial=useSession(s=>s.historyWasPartial);const[fileOpenError,setFileOpenError]=(0,react.useState)(null);const[fileOpenBusy,setFileOpenBusy]=(0,react.useState)(false);const fileOpenRequest=(0,react.useRef)(0);const requestOpenFile=(0,react.useCallback)((path,options)=>{const id=++fileOpenRequest.current;setFileOpenBusy(true);(options===void 0?openFile(path):openFile(path,options)).then(()=>{if(id!==fileOpenRequest.current)return;setFileOpenError(null);setFileOpenBusy(false)},error=>{if(id!==fileOpenRequest.current)return;setFileOpenError({path,message:openFailureMessage(error,t(`fileOpen.unknown`))});setFileOpenBusy(false)})},[openFile,t]);const closeFileOpenError=(0,react.useCallback)(()=>{fileOpenRequest.current+=1;setFileOpenError(null);setFileOpenBusy(false)},[]);const inboxSteering=(0,react.useMemo)(()=>inbox?.[`next-step`].filter(message=>message.source.kind===`user`)??[],[inbox]);const pendingSubmissions=useSession(s=>s.pendingSubmissions);const[visibleSubmissions,lastInputTurn]=(0,react.useMemo)(()=>{if(pendingSubmissions.length===0)return[pendingSubmissions,void 0];const observed=observedInputs(order,nodeStore);return[pendingSubmissions.filter(submission=>submission.placement!==`queued`&&!observed.rpcIds.has(submission.requestId)),observed.lastInputTurn]},[pendingSubmissions,order,nodeStore]);const pendingInputs=(0,react.useMemo)(()=>{const local=new Map(visibleSubmissions.map(submission=>[submission.requestId,submission]));const localIds=new Set(pendingSubmissions.filter(submission=>submission.placement!==`queued`).map(submission=>submission.requestId));return[...inboxSteering.flatMap(item=>{const source=item.source;if(source.kind!==`user`||!(`rpcId`in source))return[item];const submission=local.get(source.rpcId);if(submission===void 0)return localIds.has(source.rpcId)?[]:[item];local.delete(source.rpcId);return[submission]}),...local.values()]},[inboxSteering,pendingSubmissions,visibleSubmissions]);const deferCollapse=deferCompletedTurns&&!pendingInputs.some(item=>`requestId`in item&&item.placement===`transcript`);const firstKey=order[0];const firstSeq=firstKey===void 0?null:nodeStore.get(firstKey)?.anchorSeq??null;const lastKey=order.at(-1)??null;const latestSteering=pendingInputs.findLast(item=>`source`in item);const steeringId=latestSteering?.source.kind===`user`&&`rpcId`in latestSteering.source?latestSteering.source.rpcId:latestSteering?.id??null;const scroll=useChatScroll({isOpen:openState===`open`,order,firstSeq,lastKey,running,loadingOlder,historyLoadStatus,hasMore,chatScroll,loadOlder,consumeOlder,loadThrough,deferCompletedTurns,lastIsUser:lastKey!==null&&nodeStore.get(lastKey)?.kind===`user`,steeringId,submissionId:visibleSubmissions.at(-1)?.requestId??null,submissionSteers:visibleSubmissions.at(-1)?.placement===`steering`,loadedTurns:turnNavigationItems,transcriptView});const interactionSurfaceRef=(0,react.useRef)(null);const interactionIds=useInteractionIds(ids=>ids);const textInteraction=useTextInteraction(scroll.columnRef,interactionSurfaceRef,dispatchInteraction,interactionIds);const flowContext=(0,react.useMemo)(()=>({motion:scroll.motion}),[scroll.motion]);return(0,react_jsx_runtime.jsxs)(`div`,{className:ChatView_module_css_default.frame,children:[scroll.initialized&&(0,react_jsx_runtime.jsx)(TurnNavigator,{items:railItems,activeTurn:scroll.activeTurn,busyTurn:scroll.busyTurn,onNavigate:scroll.navigateToTurn,t}),(0,react_jsx_runtime.jsx)(ChatAside,{renderSlot}),(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.root,"data-chat-following-tail":scroll.followingTail?``:void 0,"data-conversation-overscroll":`none`,"data-conversation-scroll-anchor":scroll.followingTail?`none`:void 0,children:(0,react_jsx_runtime.jsxs)(`div`,{ref:scroll.listRef,className:ChatView_module_css_default.scroll,children:[(0,react_jsx_runtime.jsxs)(`div`,{ref:scroll.columnRef,className:ChatView_module_css_default.column,"data-chat-flow":``,"data-chat-motion":deferCompletedTurns&&scroll.initialized&&(running||motionTail||pendingInputs.length>0)?``:void 0,children:[openState===`loading`&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.hint,children:t(`chat.loadingHistory`)}),openState===`error`&&openError!==null&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.openError,children:t(`chat.loadError`,{message:openError.message,code:openError.code})}),(hasMore||historyWasPartial)&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.older,ref:scroll.historyEdgeRef,"data-chat-history":historyLoadStatus,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,disabled:!hasMore,onClick:scroll.loadEarlier,children:[[`more`,t(`chat.loadOlder`)],[`loading`,t(`chat.loadingOlder`)],[`processing`,t(`chat.processingOlder`)],[`error`,t(`chat.retryOlder`)],[`start`,t(`chat.historyStart`)]].map(([state,label])=>{const current=!hasMore?`start`:loadingOlder?`loading`:historyLoadStatus===`error`?`error`:scroll.historyInputHeld?`more`:scroll.historyProcessing?`processing`:`more`;return(0,react_jsx_runtime.jsx)(`span`,{"aria-hidden":state!==current,className:state===current?void 0:ChatView_module_css_default.historyHidden,children:label},state)})})}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownDelegateProvider,{getTriggerProps:getMarkdownTriggerProps,openFile:requestOpenFile,openExternalLink,fileImages,renderCode,children:renderSlot(`conversation.chat.flow`,{entries,pendingInputs,lastInputTurn,deferCollapse,cwd,openFile:requestOpenFile,inspectCall,inspectRequest,forkAt,loadImage},{hookContext:flowContext})}),(0,react_jsx_runtime.jsx)(`div`,{ref:interactionSurfaceRef,className:ChatView_module_css_default.textInteraction,"data-text-interaction-surface":``,"aria-hidden":textInteraction.active===null,children:textInteraction.active!==null&&renderSlot(`conversation.chat.text-interaction`,{trigger:textInteraction.active.trigger,readText:textInteraction.readText,dismiss:textInteraction.dismiss,clearSelection:textInteraction.clearSelection},{entryKey:textInteraction.active.id})})]}),(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.turnSpacer,"data-chat-turn-spacer":true,"aria-hidden":`true`})]})}),!scroll.followingTail&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.toBottomSlot,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:ChatView_module_css_default.toBottom,"aria-label":t(`chat.toBottom`),onClick:scroll.returnToBottom,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{size:16})})}),fileOpenError!==null&&(0,react_jsx_runtime.jsx)(FileOpenErrorDialog,{message:fileOpenError.message,busy:fileOpenBusy,onClose:closeFileOpenError,onRetry:()=>{requestOpenFile(fileOpenError.path)},t})]})}function FileOpenErrorDialog({message,busy,onClose,onRetry,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Modal,{open:true,onClose,closeLabel:t(`close`),title:t(`fileOpen.title`),description:message,footer:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Button,{variant:`outline`,className:ChatView_module_css_default.modalAction,onClick:onClose,children:t(`cancel`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Button,{variant:`primary`,className:ChatView_module_css_default.modalAction,disabled:busy,onClick:onRetry,children:t(`retry`)})]})})}const SIMPLE_ESCAPES={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
11
+ `):separator===` `&&!/[\t\n]$/u.test(text)&&!/^[\t\n]/u.test(fragment.text))text+=separator}offsets[index]=text.length;const base=text.length;text+=fragment.text;for(const span of fragment.spans)spans.push({node:span.node,start:base+span.start,offsets:span.offsets});for(const[owner,childOffsets]of fragment.boundaries)boundaries.push([owner,childOffsets.map(offset=>base+offset)]);if(fragment.text!==``)previous=child;offsets[index+1]=text.length}boundaries.push([node,offsets]);return{text,spans,boundaries}}function projectedOffset(projection,container,offset){if(container.nodeType===Node.TEXT_NODE){const span=projection.spans.find(candidate=>candidate.node===container);const projected=span?.offsets[offset];return span===void 0||projected===void 0?null:span.start+projected}return(projection.boundaries.find(([owner])=>owner===container)?.[1])?.[offset]??null}function endInSource(range,source){if(source.contains(range.endContainer))return range;const tail=range.cloneRange();tail.setStart(source,source.childNodes.length);if(tail.toString().trim()!==``)return null;const clamped=range.cloneRange();clamped.setEnd(source,source.childNodes.length);return clamped.collapsed?null:clamped}function readTextSelection(root,selection){if(selection===null||selection.rangeCount!==1||selection.isCollapsed)return null;const sourceOf=node=>node.closest?.(`[data-text-interaction-source]`)??node.parentElement?.closest(`[data-text-interaction-source]`)??null;const selected=selection.getRangeAt(0);const source=sourceOf(selected.startContainer);if(source===null||!root.contains(source)||source.closest(`[hidden], [inert], [data-text-interaction-exclude]`)!==null)return null;const range=endInSource(selected,source);return range===null||sourceOf(range.endContainer)!==source?null:{source,range}}function selectedText(selection){const{source,range}=selection;const projection=projectedFragment(source);const start=projectedOffset(projection,range.startContainer,range.startOffset);const end=projectedOffset(projection,range.endContainer,range.endOffset);if(start===null||end===null)return null;const text=projection.text.slice(start,end).trim();return text===``?null:text}function rectBounds(rect){return{left:rect.left,top:rect.top,right:rect.left+rect.width,bottom:rect.top+rect.height}}function intersects(a,b){return a.right>b.left&&a.left<b.right&&a.bottom>b.top&&a.top<b.bottom}function sameRange(a,b){return a===b||a!==null&&b!==null&&a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset}function available(root,target){if(!root.isConnected||!root.contains(target.source)||!target.source.hasAttribute(`data-text-interaction-source`))return false;const view=root.ownerDocument.defaultView;if(view===null)return false;for(let node=target.source;node!==null;node=node.parentElement){const style=view.getComputedStyle(node);if(node.hidden||node.inert||node.hasAttribute(`data-text-interaction-exclude`)||style.display===`none`||style.visibility===`hidden`)return false}return target.selection===null||target.source.contains(target.selection.range.startContainer)&&target.source.contains(target.selection.range.endContainer)&&selectedText(target.selection)===target.text}function composerSeat(root){return root.closest(`[data-conversation-scroll]`)?.querySelector(`[data-composer-seat]`)??null}function visibleBounds(root,source,view){const rootRect=rectBounds(root.getBoundingClientRect());const bounds={left:Math.max(0,rootRect.left),right:Math.min(view.innerWidth,rootRect.right),top:0,bottom:view.innerHeight};for(let node=source;node!==null;node=node.parentElement){const style=view.getComputedStyle(node);const rect=rectBounds(node.getBoundingClientRect());if(/(auto|scroll|hidden|clip)/u.test(style.overflowX)){bounds.left=Math.max(bounds.left,rect.left);bounds.right=Math.min(bounds.right,rect.right)}if(/(auto|scroll|hidden|clip)/u.test(style.overflowY)){bounds.top=Math.max(bounds.top,rect.top);bounds.bottom=Math.min(bounds.bottom,rect.bottom)}}const composer=composerSeat(root)?.getBoundingClientRect();if(composer!==void 0&&composer.height>0&&composer.right>bounds.left&&composer.left<bounds.right)bounds.bottom=Math.min(bounds.bottom,composer.top);return bounds}function useTextInteraction(rootRef,surfaceRef,dispatchInteraction,registeredIds){const target=(0,react.useRef)(null);const[active,setActive]=(0,react.useState)(null);const dismiss=(0,react.useCallback)(()=>{target.current=null;if(surfaceRef.current!==null)surfaceRef.current.style.visibility=`hidden`;setActive(null)},[surfaceRef]);(0,react.useEffect)(dismiss,[registeredIds,dispatchInteraction,dismiss]);const readText=(0,react.useCallback)(()=>{const root=rootRef.current;const current=target.current;if(root===null||current===null||!available(root,current))return null;return current.selection===null?null:selectedText(current.selection)},[rootRef]);const clearSelection=(0,react.useCallback)(()=>{rootRef.current?.ownerDocument.getSelection()?.removeAllRanges()},[rootRef]);const place=(0,react.useCallback)(()=>{const root=rootRef.current;const surface=surfaceRef.current;const current=target.current;if(root===null||surface===null||current===null)return;if(!available(root,current)){dismiss();return}const view=root.ownerDocument.defaultView;if(view===null)return;const visible=visibleBounds(root,current.source,view);const selectionRects=current.selection===null?[]:[...current.selection.range.getClientRects()];const fallback=current.selection?.range.getBoundingClientRect()??current.source.getBoundingClientRect();const rects=selectionRects.length===0?[fallback]:selectionRects;const sourceRect=current.source.getBoundingClientRect();const pointX=current.point===null?0:sourceRect.left+current.point.x-current.source.scrollLeft;const pointY=current.point===null?0:sourceRect.top+current.point.y-current.source.scrollTop;const anchor=current.point===null?rects.map(rectBounds).find(rect=>intersects(rect,visible)):{left:pointX,right:pointX+1,top:pointY,bottom:pointY+1};if(anchor===void 0||!intersects(anchor,visible)||visible.right<=visible.left||visible.bottom<=visible.top){surface.style.visibility=`hidden`;return}const gap=8;surface.style.maxWidth=`${visible.right-visible.left}px`;surface.style.maxHeight=`${visible.bottom-visible.top}px`;const size=surface.getBoundingClientRect();const x=current.point===null?(Math.max(anchor.left,visible.left)+Math.min(anchor.right,visible.right)-size.width)/2:anchor.left;const above=anchor.top-gap-size.height;const below=anchor.bottom+gap;const preferredY=current.point===null&&above>=visible.top?above:below;const left=Math.max(visible.left,Math.min(x,visible.right-size.width));const top=Math.max(visible.top,Math.min(preferredY,visible.bottom-size.height));const rootRect=root.getBoundingClientRect();const scaleX=root.offsetWidth===0?1:rootRect.width/root.offsetWidth;const scaleY=root.offsetHeight===0?1:rootRect.height/root.offsetHeight;surface.style.left=`${(left-rootRect.left)/scaleX-root.clientLeft+root.scrollLeft}px`;surface.style.top=`${(top-rootRect.top)/scaleY-root.clientTop+root.scrollTop}px`;surface.style.visibility=`visible`},[dismiss,rootRef,surfaceRef]);(0,react.useLayoutEffect)(place,[active,place]);(0,react.useEffect)(()=>{const root=rootRef.current;const surface=surfaceRef.current;if(root===null||surface===null)return;const document=root.ownerDocument;const view=document.defaultView;if(view===null)return;let pointerSelecting=false;let keyboardSelecting=false;let selectionChangedDuringGesture=false;let previousRange=null;let frame;const schedulePlacement=()=>{if(target.current===null||frame!==void 0)return;frame=view.requestAnimationFrame(()=>{frame=void 0;place()})};const dispatch=(trigger,next,event)=>{if(!available(root,next))return;const id=dispatchInteraction({trigger,hasSelection:next.selection!==null,readText:()=>next.text,preventDefault:()=>{event.preventDefault()}});if(id===null)return;target.current=next;setActive({id,trigger})};const updateSelection=event=>{if(pointerSelecting||keyboardSelecting){selectionChangedDuringGesture=true;return}if(target.current!==null&&target.current.point!==null)return;if(target.current!==null&&surface.contains(document.activeElement))return;const selection=readTextSelection(root,document.getSelection());const range=selection?.range??null;if(!selectionChangedDuringGesture&&sameRange(previousRange,range))return;selectionChangedDuringGesture=false;previousRange=range?.cloneRange()??null;dismiss();if(selection===null)return;const text=selectedText(selection);if(text===null)return;dispatch(`selection`,{source:selection.source,selection:{...selection,range:selection.range.cloneRange()},text,point:null},event)};const insideSurface=event=>event.composedPath().includes(surface);const pointerDown=event=>{if(insideSurface(event))return;previousRange=readTextSelection(root,document.getSelection())?.range.cloneRange()??null;dismiss();selectionChangedDuringGesture=false;pointerSelecting=event.button===0&&root.contains(event.target)};const pointerUp=event=>{if(!pointerSelecting)return;pointerSelecting=false;updateSelection(event)};const cancel=()=>{pointerSelecting=false;keyboardSelecting=false;dismiss()};const keyDown=event=>{if(event.key===`Escape`){cancel();return}if(insideSurface(event)||!root.contains(event.target))return;if(event.key===`Shift`||event.shiftKey){keyboardSelecting=true;dismiss()}};const keyUp=event=>{if(!keyboardSelecting||event.key!==`Shift`&&event.shiftKey)return;keyboardSelecting=false;updateSelection(event)};const contextMenu=event=>{if(insideSurface(event))return;const element=event.target;const source=element.closest?.(`[data-text-interaction-source]`);if(source===void 0||source===null||!root.contains(source)||element.closest?.(`[data-text-interaction-exclude], button, input, textarea, [contenteditable="true"]`))return;pointerSelecting=false;dismiss();const selected=readTextSelection(root,document.getSelection());const keyboard=event.clientX===0&&event.clientY===0;const selection=selected?.source===source&&(keyboard||[...selected.range.getClientRects()].some(rect=>event.clientX>=rect.left&&event.clientX<=rect.right&&event.clientY>=rect.top&&event.clientY<=rect.bottom))?selected:null;const bounds=source.getBoundingClientRect();dispatch(`contextmenu`,{source,selection:selection===null?null:{...selection,range:selection.range.cloneRange()},text:selection===null?null:selectedText(selection),point:{x:(keyboard?0:event.clientX-bounds.left)+source.scrollLeft,y:(keyboard?0:event.clientY-bounds.top)+source.scrollTop}},event)};document.addEventListener(`selectionchange`,updateSelection);document.addEventListener(`pointerdown`,pointerDown,true);document.addEventListener(`pointerup`,pointerUp);document.addEventListener(`pointercancel`,cancel);document.addEventListener(`keydown`,keyDown);document.addEventListener(`keyup`,keyUp);document.addEventListener(`scroll`,schedulePlacement,true);root.addEventListener(`contextmenu`,contextMenu);view.addEventListener(`resize`,schedulePlacement);view.addEventListener(`blur`,cancel);return()=>{document.removeEventListener(`selectionchange`,updateSelection);document.removeEventListener(`pointerdown`,pointerDown,true);document.removeEventListener(`pointerup`,pointerUp);document.removeEventListener(`pointercancel`,cancel);document.removeEventListener(`keydown`,keyDown);document.removeEventListener(`keyup`,keyUp);document.removeEventListener(`scroll`,schedulePlacement,true);root.removeEventListener(`contextmenu`,contextMenu);view.removeEventListener(`resize`,schedulePlacement);view.removeEventListener(`blur`,cancel);if(frame!==void 0)view.cancelAnimationFrame(frame)}},[dismiss,place,rootRef,surfaceRef,dispatchInteraction]);(0,react.useEffect)(()=>{const root=rootRef.current;const surface=surfaceRef.current;if(active===null||root===null||surface===null)return;const view=root.ownerDocument.defaultView;if(view===null)return;let frame;const schedule=()=>{if(frame!==void 0)return;frame=view.requestAnimationFrame(()=>{frame=void 0;place()})};const resize=new ResizeObserver(schedule);resize.observe(root);resize.observe(surface);const composer=composerSeat(root);if(composer!==null)resize.observe(composer);const mutations=new MutationObserver(records=>{if(records.some(record=>!surface.contains(record.target)))schedule()});mutations.observe(root,{childList:true,subtree:true,characterData:true,attributes:true});return()=>{resize.disconnect();mutations.disconnect();if(frame!==void 0)view.cancelAnimationFrame(frame)}},[active,place,rootRef,surfaceRef]);return{active,dismiss,readText,clearSelection}}var ChatNavigation=class{viewport;reading;input;onBusyTurn;onHistoryIntent;jump=null;settleFrame=null;historyFrame=null;historyIntent=`none`;historyRequested=false;constructor(viewport,reading,input,onBusyTurn,onHistoryIntent=()=>{}){this.viewport=viewport;this.reading=reading;this.input=input;this.onBusyTurn=onBusyTurn;this.onHistoryIntent=onHistoryIntent}setInput(input){this.input=input;this.historyRequested=false;if(!input.isOpen||input.historyLoadStatus===`error`||!input.hasMore)this.setHistoryIntent(`none`)}reset(){this.cancel()}dispose(){this.clearTask();if(this.historyFrame!==null)cancelAnimationFrame(this.historyFrame);this.historyFrame=null}cancel(){this.setHistoryIntent(`none`);this.clearTask();this.onBusyTurn(null)}readerInteracted(){this.clearTask();this.onBusyTurn(null)}clearTask(){this.cancelFrame();this.jump=null;this.viewport.stopPreserving();this.viewport.cancelHistoryPrepend()}navigateToTurn=item=>{if(item.anchor.kind===`loaded`){this.cancel();const landing=this.viewport.scrollToTurn(item.turn);if(landing===null)return;this.reading.acceptNavigation(landing);if(this.input.loadingOlder)this.viewport.beginPreserving(landing.position);return}this.cancel();this.viewport.beginPreserving();this.reading.pauseFollowing();const jump={turn:item.turn,seq:item.anchor.seq,phase:`loading`,landing:`pending`,repageHead:null};this.jump=jump;this.onBusyTurn(jump.turn);this.request(jump)};loadEarlier=()=>{this.cancel();this.setHistoryIntent(`manual`);this.reading.pauseFollowing();if(this.input.historyLoadStatus===`error`){this.historyRequested=true;this.input.loadOlder()}else this.requestHistoryCheck()};setHistoryIntent(intent){if(intent===this.historyIntent)return;this.historyIntent=intent;this.onHistoryIntent(intent)}requestHistoryCheck(){if(!this.input.isOpen||this.input.historyLoadStatus===`error`)return;if(this.historyIntent===`none`&&(this.input.historyLoadStatus!==`idle`||!this.input.hasMore||this.reading.followingTail))return;if(this.historyFrame!==null||typeof requestAnimationFrame!==`function`)return;this.historyFrame=requestAnimationFrame(()=>{this.historyFrame=null;this.checkHistory()})}checkHistory(){const input=this.input;if(!input.isOpen||this.jump!==null||this.historyRequested||input.loadingOlder)return;if(input.historyLoadStatus===`error`)return;if(input.historyLoadStatus===`pendingConsumption`){if(this.historyIntent===`none`)return;if(this.reading.followingTail&&this.historyIntent===`auto`){this.setHistoryIntent(`none`);return}if(this.historyIntent===`manual`){this.viewport.beginManualPaging();this.reading.pauseFollowing();this.consumeHistory(`preserve`);return}const mode=this.viewport.historyConsumption();switch(mode){case`touch`:case`inner-scroll`:return;case`motion`:case`pointer`:case`unavailable`:this.setHistoryIntent(`none`);return;case`prepend`:if(!this.viewport.beginHistoryPrepend()&&input.firstSeq!==null){this.setHistoryIntent(`none`);return}break;case`preserve`:case`native`:break}if(mode===`preserve`){this.viewport.beginPreserving();if(!this.viewport.preserving)this.viewport.beginPaging();if(!this.viewport.preserving&&input.firstSeq!==null){this.setHistoryIntent(`none`);return}this.reading.pauseFollowing()}this.consumeHistory(mode);return}if(!input.hasMore||this.historyIntent!==`manual`&&(this.reading.followingTail||!this.viewport.confirmHistoryStart()))return;if(this.historyIntent===`none`)this.setHistoryIntent(`auto`);this.historyRequested=true;input.loadOlder()}consumeHistory(mode){this.historyRequested=true;if(this.input.consumeOlder())this.setHistoryIntent(`none`);else{this.historyRequested=false;if(mode===`preserve`)this.viewport.stopPreserving();if(mode===`prepend`)this.viewport.cancelHistoryPrepend()}}readerSampled(sample){if(sample.movedByReader&&this.jump?.landing===`landed`)this.jump.landing=`interrupted`;if(sample.followingTail||sample.movedByReader)this.viewport.stopPreserving()}contentCommitted(){if(!this.viewport.preserving||this.reading.pending)return false;if(this.landJump(false))return true;const landing=this.viewport.preserve();if(landing===null)return false;this.reading.preservePosition(landing);return true}reconcile(){const jump=this.jump;if(jump===null||this.reading.pending)return;if(jump.phase===`loading`){if(jump.landing===`pending`)this.landJump(false);return}if(this.input.loadingOlder)return;if(this.landJump(true))return;if((this.input.firstSeq===null||this.input.firstSeq>jump.seq)&&this.input.hasMore&&jump.repageHead!==this.input.firstSeq){jump.repageHead=this.input.firstSeq;this.viewport.beginPreserving();this.request(jump);return}const fallback=this.viewport.scrollToTurnAtOrAfter(jump.turn);this.cancel();if(fallback!==null)this.reading.acceptNavigation(fallback)}landJump(settle){const jump=this.jump;if(jump===null)return false;if(jump.landing===`interrupted`){if(settle){this.cancel();return true}return false}const landing=this.viewport.scrollToTurn(jump.turn);if(landing===null)return false;this.reading.acceptNavigation(landing);if(settle)this.cancel();else{this.viewport.beginPreserving(landing.position);jump.landing=`landed`}return true}request(jump){jump.phase=`loading`;const settled=()=>{if(this.jump!==jump)return;jump.phase=`settled`;this.cancelFrame();if(typeof requestAnimationFrame!==`function`)this.reconcile();else this.settleFrame=requestAnimationFrame(()=>{this.settleFrame=null;if(this.jump===jump)this.reconcile()})};this.input.loadThrough(jump.seq).then(settled,settled)}cancelFrame(){if(this.settleFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.settleFrame);this.settleFrame=null}};function useChatNavigation(viewport,reading,input){const[busyTurn,setBusyTurn]=(0,react.useState)(null);const[historyIntent,setHistoryIntent]=(0,react.useState)(`none`);const[navigation]=(0,react.useState)(()=>new ChatNavigation(viewport,reading,input,setBusyTurn,setHistoryIntent));(0,react.useLayoutEffect)(()=>{navigation.setInput(input)},[navigation,input]);(0,react.useLayoutEffect)(()=>()=>{navigation.dispose()},[navigation]);return{navigation,busyTurn,historyPending:historyIntent===`manual`,historyProcessing:historyIntent!==`none`}}function scrollMetrics(element){const height=element.clientHeight;return{top:element.scrollTop,height,floor:Math.max(0,element.scrollHeight-height)}}var ScrollFollow=class ScrollFollow{following;threshold;static owners=new WeakMap;target=null;sampledTop;constructor(following,threshold){this.following=following;this.threshold=threshold}static forElement(element){return this.owners.get(element)}bind(element){ScrollFollow.owners.set(element,this);return()=>{if(ScrollFollow.owners.get(element)===this)ScrollFollow.owners.delete(element)}}get active(){return this.following}get animating(){return this.target!==null}nearBottom(metrics){return Math.abs(metrics.floor-metrics.top)<=this.threshold}setFollowing(active){this.following=active;if(!active)this.target=null}reset(){this.setFollowing(false);this.sampledTop=void 0}sample(metrics,movedByReader=this.sampledTop===void 0||Math.abs(metrics.top-this.sampledTop)>.5){this.sampledTop=metrics.top;if(!this.animating&&movedByReader)this.following=this.nearBottom(metrics);return this.active}settle(metrics){const target=this.target;this.target=null;return this.sample(metrics,target===null?void 0:Math.abs(metrics.top-Math.min(target,metrics.floor))>this.threshold)}jump(element,metrics,top){const animated=this.animating;this.target=null;const target=Math.max(0,Math.min(metrics.floor,top));if(animated)element.scrollTo({top:target,behavior:`instant`});else if(target!==metrics.top)element.scrollTop=target;const landed={...metrics,top:element.scrollTop};this.sampledTop=landed.top;this.following=this.nearBottom(landed);return landed}toBottom(element,metrics,behavior){this.following=true;if(metrics.top===metrics.floor)return this.jump(element,metrics,metrics.floor);if(behavior===`instant`&&this.animating){if(this.target!==metrics.floor){this.target=metrics.floor;element.scrollTo({top:metrics.floor,behavior:`smooth`})}return metrics}if(behavior===`instant`||!this.animating&&this.nearBottom(metrics))return this.jump(element,metrics,metrics.floor);if(typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches)return this.jump(element,metrics,metrics.floor);if(this.target===null){this.target=metrics.floor;element.scrollTo({top:metrics.floor,behavior:`smooth`})}return metrics}interrupt(element,metrics){if(!this.animating)return;this.target=null;this.sampledTop=metrics.top;element.scrollTo({top:metrics.top,behavior:`instant`})}};function useScrollFollow(initial,threshold){const[follow]=(0,react.useState)(()=>new ScrollFollow(initial,threshold));return follow}const SCROLL_SAMPLE_INTERVAL_MS=500;var ChatReading=class{viewport;store;state;onChange;follow;sampleTimer=null;probeFrame=null;sampled=null;constructor(viewport,store,state,onChange,follow){this.viewport=viewport;this.store=store;this.state=state;this.onChange=onChange;this.follow=follow}get pending(){return this.sampleTimer!==null}get followingTail(){return this.state.followingTail}setStore(store){this.store=store}connect(sampled){this.sampled=sampled;return()=>{if(this.sampled===sampled)this.sampled=null}}dispose(){this.cancelPending();this.sampled=null}pauseFollowing(){this.cancelPending();this.publish({...this.state,followingTail:false})}followTail(behavior=`instant`){const landing=this.viewport.scrollToBottom(this.follow,behavior);if(landing===null)return;this.cancelPending();this.commit(landing,true,this.viewport.latestTurn)}followInputFold(input){this.cancelPending();return this.viewport.followInputFold(this.follow,input)}bindFolds(){return this.viewport.bindReader({follow:this.follow,landedAtTail:landing=>{this.cancelPending();this.commit(landing,true,this.viewport.latestTurn)},pending:()=>this.pending})}interruptFollow(){this.viewport.interruptFollow(this.follow)}restore(){const saved=this.store.read();if(saved===null){this.followTail();return}const landing=this.viewport.restore(saved);if(landing===null)return;this.cancelPending();const following=this.follow.nearBottom(landing.metrics);this.commit(landing,following,following?this.viewport.latestTurn:this.state.activeTurn,following);if(!this.state.followingTail&&landing.position===null){const position=this.viewport.capturePosition();if(position!==null)this.store.save(position)}this.refreshActiveTurn()}acceptNavigation(landing){this.cancelPending();const following=this.follow.nearBottom(landing.metrics);this.commit(landing,following,landing.turn??(following?this.viewport.latestTurn:this.state.activeTurn))}preservePosition(landing){this.cancelPending();this.commit(landing,this.state.followingTail,this.state.activeTurn)}onScroll=scroll=>{if(this.follow.animating)return;if(!scroll.movedByReader&&this.state.followingTail||scroll.movedByReader&&Math.abs(scroll.metrics.top-scroll.metrics.floor)<1){this.followTail();this.sampled?.({position:null,movedByReader:scroll.movedByReader,followingTail:true});return}this.sampleTimer??=window.setTimeout(this.flushSample,SCROLL_SAMPLE_INTERVAL_MS)};onScrollEnd=(outer=true)=>{if(this.follow.animating){if(!outer)return;const scroll=this.viewport.readScroll();if(scroll===null)return;if(this.follow.settle(scroll.metrics)){this.followTail();return}this.viewport.acknowledge(scroll.metrics);this.publish({...this.state,followingTail:false});this.refreshActiveTurn();return}this.flushSample()};onResize(){if(this.pending)return;if(this.state.followingTail)this.followTail();else this.refreshActiveTurn()}refreshActiveTurn(){if(this.pending)return;if(this.state.followingTail){this.publish({...this.state,initialized:true,activeTurn:this.viewport.latestTurn});return}if(this.probeFrame!==null)return;if(typeof requestAnimationFrame!==`function`)this.probe();else this.probeFrame=requestAnimationFrame(this.probe)}commit(landing,followingTail,activeTurn,initialized=true){if(followingTail)this.store.save(null);else if(landing.position!==null)this.store.save(landing.position);this.publish({initialized,followingTail,activeTurn})}publish(state){this.follow.setFollowing(state.followingTail);if(state.initialized===this.state.initialized&&state.followingTail===this.state.followingTail&&state.activeTurn===this.state.activeTurn)return;this.state=state;this.onChange(state)}cancelPending(){if(this.sampleTimer!==null)window.clearTimeout(this.sampleTimer);if(this.probeFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.probeFrame);this.sampleTimer=null;this.probeFrame=null}probe=()=>{this.probeFrame=null;if(this.pending)return;const scroll=this.viewport.readScroll();if(scroll===null)return;const activeTurn=this.follow.nearBottom(scroll.metrics)?this.viewport.latestTurn:this.viewport.readVisibleTurn(scroll.metrics);this.publish({...this.state,initialized:true,activeTurn})};flushSample=()=>{if(!this.pending)return;this.cancelPending();const scroll=this.viewport.readScroll();if(scroll===null)return;const followingTail=this.follow.sample(scroll.metrics,scroll.movedByReader);let position=null;if(!scroll.movedByReader&&followingTail)this.followTail();else{position=followingTail?null:this.viewport.capturePosition();this.viewport.acknowledge(scroll.metrics);if(followingTail||position!==null)this.store.save(position);const activeTurn=this.follow.nearBottom(scroll.metrics)?this.viewport.latestTurn:this.viewport.readVisibleTurn(scroll.metrics);this.publish({initialized:true,followingTail,activeTurn})}this.sampled?.({position,movedByReader:scroll.movedByReader,followingTail})}};function useChatReading(viewport,store,initialTurn){const[state,setState]=(0,react.useState)(()=>({initialized:false,followingTail:store.read()===null,activeTurn:initialTurn}));const follow=useScrollFollow(state.followingTail,25);const[reading]=(0,react.useState)(()=>new ChatReading(viewport,store,state,setState,follow));(0,react.useLayoutEffect)(()=>{reading.setStore(store)},[reading,store]);(0,react.useLayoutEffect)(()=>reading.bindFolds(),[reading]);(0,react.useLayoutEffect)(()=>()=>{reading.dispose()},[reading]);return{reading,state}}function useSearchableHidden(hidden,reveal,transition){const ref=(0,react.useRef)(null);(0,react.useLayoutEffect)(()=>{const element=ref.current;if(element===null)return;if(hidden&&element.contains(element.ownerDocument.activeElement)){reveal();return}const commit=()=>{if(hidden)element.setAttribute(`hidden`,`until-found`);else element.removeAttribute(`hidden`)};if(transition===void 0)commit();else transition(element,hidden,commit)},[hidden,reveal,transition]);(0,react.useEffect)(()=>{const element=ref.current;if(element===null)return;element.addEventListener(`beforematch`,reveal);return()=>{element.removeEventListener(`beforematch`,reveal)}},[reveal]);return ref}const FADE_OUT_MS=70;const CLOSE_DELAY_MS=50;const CLOSE_MS=110;const MOTION_SCOPE=`[data-chat-motion]`;const EASING=`cubic-bezier(0.4, 0, 0.2, 1)`;function motionEnabled(element){if(element.closest(MOTION_SCOPE)===null)return false;return typeof matchMedia!==`function`||!matchMedia(`(prefers-reduced-motion: reduce)`).matches}function hiddenOrCollapsing(element){return element.hasAttribute(`hidden`)||element.dataset.chatMotion===`collapse`}function revealedShare(box,progress){const start=box.height===0?0:box.fromHeight/box.height;return start+(1-start)*progress}function createFlowMotion(driver,foldingChanged,beforeInstantHide){const running=new Map;let folding=0;const foldIdleListeners=new Set;let batchScheduled=false;const boxes=new Map;let frameRequest=null;let batch=false;let cancelled=false;let clearEpoch=0;let batchCleanup=null;let cancelEmptyBatch=null;let settling=false;let anchoringDisabled=false;function cancelInput(){if(batch)cancelled=true}function resumeInput(){if(batch)cancelled=false}function batchMember(box){return box.element.parentElement?.closest(`[data-chat-motion="collapse"]`)===null}function runBatch(current){for(const box of[...boxes.values()]){if(!batchMember(box))continue;if(box.element.parentElement?.closest(`[hidden]`)!=null){box.finish();continue}const height=box.element.offsetHeight;const marginTop=Number.parseFloat(getComputedStyle(box.element).marginTop)||0;if(!box.closing){box.fromHeight=Math.min(height,box.height);box.fromMarginTop=Math.min(marginTop,box.marginTop);continue}box.height=height;box.marginTop=marginTop;if(height===0&&marginTop===0)box.finish()}const owned=[...boxes.values()];const members=owned.filter(batchMember).sort((left,right)=>left.element.compareDocumentPosition(right.element)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1);if(!members.some(box=>box.closing))return false;batch=true;cancelled=false;const travelling=current.begin(members.map(box=>box.closing?box:{element:box.element,height:box.height-box.fromHeight,marginTop:box.marginTop-box.fromMarginTop,closing:false}));batchCleanup=()=>{current.finish(true)};for(const box of owned)box.take();for(const box of members){box.element.style.transition=`none`;box.element.style.height=`${box.closing?box.height:box.fromHeight}px`;box.element.style.marginTop=`${box.closing?box.marginTop:box.fromMarginTop}px`;box.element.style.opacity=box.closing?`1`:String(revealedShare(box,0))}const memberSet=new Set(members);const settledTravel=new Set;const freezeTravelling=()=>{for(const element of travelling){if(settledTravel.has(element))continue;settledTravel.add(element);element.style.translate=``;for(const box of owned){if(memberSet.has(box)||!element.contains(box.element))continue;box.element.style.transition=`none`;box.element.style.height=`${box.height}px`;box.element.style.marginTop=`${box.marginTop}px`;box.element.style.opacity=`1`}}};freezeTravelling();const reduced=typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;let started;let displacement=0;const settle=finishCancelled=>{batch=false;batchCleanup=null;cancelEmptyBatch=null;settling=true;try{for(const box of owned)if(boxes.get(box.element)===box)box.finish();current.finish(finishCancelled)}finally{settling=false}if(folding===0)notifyIdle();if([...boxes.values()].some(box=>box.held))flushBatch()};cancelEmptyBatch=()=>{if(members.some(box=>box.closing&&boxes.get(box.element)===box))return;if(frameRequest!==null)cancelAnimationFrame(frameRequest);frameRequest=null;settle(true)};const tick=now=>{frameRequest=null;started??=now;const elapsed=reduced?160:now-started;const linear=Math.min(1,Math.max(0,(elapsed-CLOSE_DELAY_MS)/CLOSE_MS));const progress=linear*linear*(3-2*linear);current.prepare(progress,cancelled);freezeTravelling();for(const box of members){if(boxes.get(box.element)!==box)continue;if(box.closing){box.element.style.height=`${box.height*(1-progress)}px`;box.element.style.marginTop=`${box.marginTop*(1-progress)}px`;box.element.style.opacity=travelling.has(box.element)?`1`:String(Math.max(0,1-elapsed/FADE_OUT_MS))}else{box.element.style.height=`${box.fromHeight+(box.height-box.fromHeight)*progress}px`;box.element.style.marginTop=`${box.fromMarginTop+(box.marginTop-box.fromMarginTop)*progress}px`;box.element.style.opacity=String(revealedShare(box,progress))}}displacement=current.frame(progress,cancelled);let removedBefore=0;for(const box of members){if(boxes.get(box.element)!==box)continue;if(box.closing){if(!travelling.has(box.element))box.element.style.translate=`0 ${displacement+removedBefore}px`;removedBefore+=(box.height+box.marginTop)*progress}else removedBefore-=(box.height-box.fromHeight+box.marginTop-box.fromMarginTop)*progress}if(linear<1){frameRequest=requestAnimationFrame(tick);return}settle(cancelled)};if(reduced)tick(0);else frameRequest=requestAnimationFrame(tick);return true}function foldActive(){return folding>0}function onFoldIdle(listener){if(folding===0)listener();else foldIdleListeners.add(listener);return()=>{foldIdleListeners.delete(listener)}}function flushBatch(){batchScheduled=false;if(batch)return;const current=[...boxes.values()].some(box=>box.closing)?driver():null;if(current!==null&&runBatch(current))return;const reduced=typeof matchMedia===`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;for(const box of[...boxes.values()])if(reduced||box.held&&box.closing)box.finish();else if(box.held)box.release()}function scheduleBatch(){if(batchScheduled)return;batchScheduled=true;const epoch=clearEpoch;queueMicrotask(()=>{if(epoch===clearEpoch)flushBatch()})}function foldStarted(){folding+=1;if(folding!==1||anchoringDisabled)return;anchoringDisabled=true;foldingChanged(true)}function foldEnded(){folding=Math.max(0,folding-1);if(folding===0&&!settling)notifyIdle()}function notifyIdle(){if(anchoringDisabled){anchoringDisabled=false;foldingChanged(false)}const listeners=[...foldIdleListeners];foldIdleListeners.clear();for(const listener of listeners)listener()}function clearMotion(element,onEnd,timer){element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer);running.delete(element);boxes.delete(element);const{style}=element;style.height=``;style.marginTop=``;style.opacity=``;style.overflow=``;style.transition=``;style.translate=``;delete element.dataset.chatMotion}function cancelMotion(element){running.get(element)?.();cancelEmptyBatch?.()}function collapse(element,done){cancelMotion(element);const height=element.offsetHeight;const marginTop=Number.parseFloat(getComputedStyle(element).marginTop)||0;if(height===0&&marginTop===0){done();return}const{style}=element;const held=batch;element.dataset.chatMotion=`collapse`;foldStarted();scheduleBatch();style.transition=`none`;style.overflow=`hidden`;style.height=`${height}px`;style.marginTop=`${marginTop}px`;if(!held){element.offsetHeight;style.transition=`opacity ${FADE_OUT_MS}ms ${EASING}, height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`;style.opacity=`0`;style.height=`0px`;style.marginTop=`0px`}const finish=()=>{if(running.get(element)!==cancel)return;clearMotion(element,onEnd,timer);done();foldEnded()};const onEnd=event=>{if(event.target===element&&event.propertyName===`height`)finish()};const timer=held?void 0:setTimeout(finish,240);const cancel=()=>{clearMotion(element,onEnd,timer);foldEnded()};if(!held)element.addEventListener(`transitionend`,onEnd);running.set(element,cancel);boxes.set(element,{element,height,marginTop,fromHeight:height,fromMarginTop:marginTop,closing:true,held,finish,release:()=>{},take:()=>{element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer)}})}function reveal(element){cancelMotion(element);const height=element.offsetHeight;if(height===0)return;const marginTop=Number.parseFloat(getComputedStyle(element).marginTop)||0;scheduleBatch();const{style}=element;element.dataset.chatMotion=`reveal`;style.transition=`none`;style.overflow=`hidden`;style.opacity=`0`;style.height=`0px`;style.marginTop=`0px`;const finish=()=>{if(running.get(element)!==finish)return;clearMotion(element,onEnd,timer)};const onEnd=event=>{if(event.target===element&&event.propertyName===`height`)finish()};let timer;const startTransition=()=>{element.offsetHeight;style.transition=`height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, opacity ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`;style.height=`${height}px`;style.marginTop=`${marginTop}px`;style.opacity=`1`;timer=setTimeout(finish,240);element.addEventListener(`transitionend`,onEnd)};const held=batch;if(!held)startTransition();running.set(element,finish);const box={element,height,marginTop,fromHeight:0,fromMarginTop:0,closing:false,held,finish,release:()=>{box.held=false;startTransition()},take:()=>{element.removeEventListener(`transitionend`,onEnd);clearTimeout(timer)}};boxes.set(element,box)}function clear(){clearEpoch++;batchScheduled=false;batch=false;cancelled=false;if(frameRequest!==null)cancelAnimationFrame(frameRequest);frameRequest=null;batchCleanup?.();batchCleanup=null;cancelEmptyBatch=null;foldIdleListeners.clear();for(const cancel of[...running.values()])cancel()}function hideNow(element,commit){beforeInstantHide?.(element);commit()}return{collapse,reveal,cancelMotion,foldActive,onFoldIdle,cancelInput,resumeInput,clear,hideNow,active:()=>running.size>0||batchScheduled||batch||settling,inputActive:()=>batch||batchScheduled&&[...boxes.values()].some(box=>box.closing&&batchMember(box))}}function useFlowTransition(motion,grow){const current=(0,react.useRef)(null);(0,react.useLayoutEffect)(()=>()=>{if(current.current!==null)motion?.cancelMotion(current.current);current.current=null},[motion]);const transition=(0,react.useCallback)((element,hidden,commit)=>{const mounted=current.current===element;const animate=mounted&&motionEnabled(element);current.current=element;if(hidden){if(hiddenOrCollapsing(element))return;if(mounted&&element.closest(MOTION_SCOPE)!==null&&motion!==void 0)motion.collapse(element,commit);else if(mounted&&motion?.hideNow!==void 0)motion.hideNow(element,commit);else commit();return}motion?.cancelMotion(element);const wasHidden=element.hasAttribute(`hidden`);commit();if(wasHidden&&animate&&grow)motion?.reveal(element)},[motion,grow]);return motion===void 0?void 0:transition}function useFlowHidden(hidden,reveal,motion){return useSearchableHidden(hidden,reveal,useFlowTransition(motion,false))}function useMotionHidden(ref,hidden,motion){const transition=useFlowTransition(motion,true);(0,react.useLayoutEffect)(()=>{const element=ref.current;if(element===null)return;transition?.(element,hidden,()=>{if(hidden)element.setAttribute(`hidden`,``);else element.removeAttribute(`hidden`)})},[ref,hidden,transition])}const READING_INTENTS=[`wheel`,`touchstart`,`pointerdown`,`keydown`,`beforematch`];const SCROLL_KEYS$1=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);var ChatViewport=class{elements=null;observer=null;events=null;turns=[];observation={top:0,landing:null};paging=null;historyPrepend=null;reader=null;historyEdge=null;historyHeight=0;historyScrolling=new Set;historyPointer=false;historyTouch=false;closing=null;closingFrame=null;settledContent=0;tailRequested=false;tailInput=false;retarget=null;motion=createFlowMotion(()=>this.foldDriver(),active=>{if(this.elements!==null)this.elements.scroller.style.overflowAnchor=active?`none`:``},element=>{this.measureClosing(element)});attach(list,column){this.detach();const scroller=list.closest(`[data-conversation-scroll]`)??list;const composer=scroller.querySelector(`[data-composer-seat]`);const spacer=list.querySelector(`[data-chat-turn-spacer]`);const elements={list,column,scroller,composer,spacer};this.elements=elements;if(spacer!==null)spacer.style.height=``;scroller.addEventListener(`scroll`,this.onHistoryScroll,{passive:true,capture:true});scroller.addEventListener(`pointerdown`,this.onHistoryPointerDown,{passive:true,capture:true});scroller.addEventListener(`touchstart`,this.onHistoryTouch,{passive:true,capture:true});for(const type of[`pointerup`,`pointercancel`,`touchend`,`touchcancel`,`transitionend`,`transitioncancel`])scroller.ownerDocument.addEventListener(type,this.onHistoryRelease,true);scroller.addEventListener(`scroll`,this.onScroll,{passive:true});scroller.addEventListener(`scrollend`,this.onScrollEnd,{passive:true,capture:true});for(const type of READING_INTENTS)scroller.addEventListener(type,this.onIntent,{passive:true,capture:true});if(typeof ResizeObserver!==`undefined`){this.observer=new ResizeObserver(entries=>{if(this.elements!==elements)return;if(entries.some(entry=>entry.target===elements.scroller))this.historyHeight=elements.scroller.clientHeight;this.settledContent=elements.scroller.scrollHeight-this.spacerHeight();this.keepAboveClosing();this.reclaimBelow();this.invalidate();this.pruneHistoryScrolling();this.events?.resize()});this.observer.observe(column);this.observer.observe(scroller);if(composer!==null)this.observer.observe(composer)}}detach(){this.historyPrepend=null;this.stopPreserving();this.motion.clear();if(this.elements!==null)this.elements.scroller.style.overflowAnchor=``;this.dropClosing();const scroller=this.elements?.scroller;scroller?.removeEventListener(`scroll`,this.onHistoryScroll,true);scroller?.removeEventListener(`pointerdown`,this.onHistoryPointerDown,true);scroller?.removeEventListener(`touchstart`,this.onHistoryTouch,true);for(const type of[`pointerup`,`pointercancel`,`touchend`,`touchcancel`,`transitionend`,`transitioncancel`])scroller?.ownerDocument.removeEventListener(type,this.onHistoryRelease,true);this.historyHeight=0;this.historyScrolling.clear();this.historyPointer=false;this.historyTouch=false;this.elements?.scroller.removeEventListener(`scroll`,this.onScroll);this.elements?.scroller.removeEventListener(`scrollend`,this.onScrollEnd,true);for(const type of READING_INTENTS)this.elements?.scroller.removeEventListener(type,this.onIntent,true);this.observer?.disconnect();this.observer=null;this.elements=null;this.events=null;this.tailRequested=false;this.tailInput=false;this.retarget=null;this.turns=[];this.observation={top:0,landing:null}}connect(events){this.events=events;return()=>{if(this.events===events)this.events=null}}updateTurns(turns){this.turns=turns}get latestTurn(){return this.turns.at(-1)?.turn??null}invalidate(){this.observation.landing=null}spacerHeight(){const spacer=this.elements?.spacer;return spacer==null?0:Number.parseFloat(spacer.style.height)||0}setSpacer(height){const spacer=this.elements?.spacer;if(spacer==null)return;const next=height<=0?``:`${Math.ceil(height)}px`;if(spacer.style.height!==next)spacer.style.height=next}bindReader(reader){this.reader=reader;return()=>{if(this.reader===reader)this.reader=null}}followInputFold(follow,input){if(this.elements===null||this.reader===null||!this.motion.inputActive())return false;this.interruptFollow(follow);this.tailRequested=true;this.tailInput||=input;this.retarget?.();return true}foldDriver(){const elements=this.elements;const reader=this.reader;if(elements===null||reader===null)return null;const{follow}=reader;let tail=false;let start=0;let base=0;let target=0;let removed=0;let growth=0;let initialHeight=0;let finalRoom=0;let previousColumnHeight=0;let previousProgress=0;let segmentProgress=0;let segmentTop=0;let written=0;const closing=[];const travelling=new Set;let reference=null;let referenceTop=0;let viewportTop=0;const screenTop=element=>element.getBoundingClientRect().top-viewportTop;const aim=()=>{const finalHeight=initialHeight-removed+growth;const height=elements.scroller.clientHeight;target=tail?Math.max(base,finalHeight-height,0):base;finalRoom=target===0?0:Math.max(0,target+height-finalHeight)};const restart=()=>{segmentTop=elements.scroller.scrollTop;segmentProgress=previousProgress};const automatic=cancelled=>!(cancelled&&tail);const position=(progress,cancelled)=>{if(!automatic(cancelled))return elements.scroller.scrollTop;const remaining=segmentProgress===1?1:(progress-segmentProgress)/(1-segmentProgress);return segmentTop+(target-segmentTop)*remaining};const room=(top,progress,cancelled)=>Math.max(automatic(cancelled)?finalRoom:0,top+elements.scroller.clientHeight-(initialHeight+(growth-removed)*progress));return{begin:boxes=>{tail=this.tailRequested||follow.active&&!reader.pending();const input=this.tailInput;this.tailRequested=false;this.tailInput=false;viewportTop=elements.scroller.getBoundingClientRect().top;start=elements.scroller.scrollTop;const originalRoom=this.spacerHeight();initialHeight=Math.max(elements.column.offsetHeight,elements.scroller.scrollHeight-originalRoom);if(tail&&!input){const pinned=originalRoom===0&&this.settledContent>elements.scroller.clientHeight&&follow.active&&!reader.pending()&&!follow.animating;const external=elements.scroller.scrollHeight-originalRoom-this.settledContent;if(external>.5&&pinned){elements.scroller.scrollTop=start+external;start=elements.scroller.scrollTop;this.observation={top:start,landing:null}}}let above=0;const below=[];for(const box of boxes){const amount=box.height+box.marginTop;const top=box.element.getBoundingClientRect().top-box.marginTop;if(box.closing){removed+=amount;above+=Math.max(0,Math.min(amount,viewportTop-top));if(top>=viewportTop)below.push(box.element);closing.push(box)}else{growth+=amount;if(top<viewportTop)above-=amount}}if(!tail)reference=this.readingReference();const referenceBefore=reference===null?0:screenTop(reference);elements.column.dataset.inputFold=``;if(reference!==null){referenceTop=screenTop(reference);above-=referenceTop-referenceBefore}base=Math.max(0,start-above);segmentTop=start;written=start;previousColumnHeight=elements.column.offsetHeight;aim();this.setSpacer(Math.max(originalRoom,finalRoom,removed));if(tail)follow.setFollowing(true);this.retarget=()=>{tail=true;follow.setFollowing(true);this.motion.resumeInput();aim();restart();if(target<=segmentTop)return;for(const box of closing){const shift=Number.parseFloat(box.element.style.translate.split(` `)[1]??``)||0;if(box.element.getBoundingClientRect().top-shift-box.marginTop>=viewportTop)travelling.add(box.element)}};if(tail&&target>start)for(const element of below)travelling.add(element);return travelling},prepare:(progress,cancelled)=>{if(this.elements!==elements)return;if(!tail){const drift=elements.scroller.scrollTop-written;if(Math.abs(drift)>.5){base=Math.max(0,base+drift);segmentTop+=drift;referenceTop-=drift;aim()}}const added=elements.column.offsetHeight-previousColumnHeight;if(added!==0){initialHeight+=added;aim();restart()}const top=position(progress,cancelled);this.setSpacer(Math.max(this.spacerHeight(),room(top,progress,cancelled)))},frame:(progress,cancelled)=>{if(this.elements!==elements)return 0;const top=position(progress,cancelled);elements.scroller.scrollTop=top;this.setSpacer(room(top,progress,cancelled));written=elements.scroller.scrollTop;if(reference!==null&&progress===1)referenceTop=screenTop(reference);if(automatic(cancelled))this.observation={top:written,landing:null};previousColumnHeight=elements.column.offsetHeight;previousProgress=progress;return written-start},finish:cancelled=>{this.retarget=null;this.tailRequested=false;this.tailInput=false;if(this.elements!==elements)return;elements.column.offsetHeight;delete elements.column.dataset.inputFold;if(!tail||cancelled){if(!tail&&reference?.isConnected===true&&reference.closest(`[hidden]`)===null){const shift=screenTop(reference)-referenceTop;if(Math.abs(shift)>.5){const top=elements.scroller.scrollTop+shift;const content=elements.scroller.scrollHeight-this.spacerHeight();this.setSpacer(Math.max(this.spacerHeight(),top+elements.scroller.clientHeight-content));elements.scroller.scrollTop=top}}const metrics=scrollMetrics(elements.scroller);const height=elements.scroller.scrollHeight-this.spacerHeight();this.setSpacer(metrics.top===0?0:Math.max(0,metrics.top+metrics.height-height));if(tail)this.invalidate();else this.observation={top:elements.scroller.scrollTop,landing:null};return}const content=elements.scroller.scrollHeight-this.spacerHeight();const clientHeight=elements.scroller.clientHeight;const top=Math.max(target,content-clientHeight,0);this.setSpacer(top===0?0:Math.max(0,top+clientHeight-content));elements.scroller.scrollTop=top;const metrics=scrollMetrics(elements.scroller);const landing={metrics,position:null,turn:this.latestTurn};this.observation={top:metrics.top,landing};reader.landedAtTail(landing)}}}readingReference(){const elements=this.elements;if(elements===null)return null;const viewport=elements.scroller.getBoundingClientRect();const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;if(rows[middle].getBoundingClientRect().bottom>viewport.top)high=middle;else low=middle+1}for(let index=low;index<rows.length;index++){const row=rows[index];if(row.hasAttribute(`hidden`))continue;const rect=row.getBoundingClientRect();if(rect.top>=viewport.bottom)return null;if(rect.height===0||rect.bottom<=viewport.top)continue;if(row.hasAttribute(`data-chat-motion`)||row.querySelector(`[data-chat-motion]`)!==null)continue;return row}return null}measureClosing(element){const elements=this.elements;const reader=this.reader;if(elements===null||reader===null||this.closing!==null||!element.isConnected)return;if(!reader.follow.active||reader.follow.animating||reader.pending())return;if(this.paging!==null||this.motion.foldActive()||this.motion.inputActive())return;const scroller=elements.scroller;const scrollHeight=scroller.scrollHeight;const height=scroller.clientHeight;const painted=scroller.scrollTop+height;const origin=scroller.getBoundingClientRect().top-scroller.scrollTop;const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;const end=row=>row!==element&&!row.contains(element)&&(element.compareDocumentPosition(row)&Node.DOCUMENT_POSITION_PRECEDING)!==0?painted:scrollHeight;const screen=(row,offset)=>offset-origin-(end(row)-height);let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;const row=rows[middle];if(screen(row,row.getBoundingClientRect().bottom)>0)high=middle;else low=middle+1}let first=-1;for(let index=low;index<rows.length&&first<0;index++){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.top)>=height)break;if(rect.height>0&&!row.hasAttribute(`hidden`))first=index}if(first<0)return;const anchors=[];const add=(row,rect)=>{if(rect.height>0&&!row.hasAttribute(`hidden`))anchors.push({element:row,fromEnd:end(row)-(rect.top-origin)})};add(rows[first],rows[first].getBoundingClientRect());for(let index=first+1;index<rows.length;index++){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.top)>=height)break;add(row,rect)}for(let index=first-1;index>=0;index--){const row=rows[index];const rect=row.getBoundingClientRect();if(screen(row,rect.bottom)<=-height)break;add(row,rect)}this.closing={rows:anchors,content:scrollHeight-this.spacerHeight()};if(typeof requestAnimationFrame===`function`)this.closingFrame=requestAnimationFrame(()=>{this.closingFrame=requestAnimationFrame(()=>{this.closingFrame=null;this.closing=null})})}dropClosing(){this.closing=null;if(this.closingFrame!==null&&typeof cancelAnimationFrame===`function`)cancelAnimationFrame(this.closingFrame);this.closingFrame=null}keepAboveClosing(){const closing=this.closing;const elements=this.elements;const reader=this.reader;if(closing===null)return;this.dropClosing();if(elements===null||reader===null||!reader.follow.active||reader.follow.animating||reader.pending())return;if(this.paging!==null||this.motion.foldActive()||this.motion.inputActive())return;const scroller=elements.scroller;const content=scroller.scrollHeight-this.spacerHeight();if(content>=closing.content-.5)return;const height=scroller.clientHeight;const origin=scroller.getBoundingClientRect().top-scroller.scrollTop;const cap=height/2;let top=content+cap-height;for(const row of closing.rows){if(!row.element.isConnected||row.element.closest(`[hidden]`)!==null)continue;const rect=row.element.getBoundingClientRect();if(rect.height===0)continue;top=rect.top-origin-(height-row.fromEnd);break}if(top+height-content>cap)top=content+cap-height;top=Math.max(0,top);this.setSpacer(top===0?0:Math.max(0,top+height-content));if(scroller.scrollTop!==top)scroller.scrollTop=top;const metrics=scrollMetrics(scroller);this.observation={top:metrics.top,landing:{metrics,position:null,turn:this.latestTurn}}}resetBelow(){this.dropClosing();this.setSpacer(0);this.invalidate()}reclaimBelow(){const elements=this.elements;if(elements===null||elements.spacer===null)return;const current=this.spacerHeight();if(current===0||this.motion.foldActive())return;const scroll=this.readScroll();if(scroll===null||scroll.movedByReader)return;const floorWithoutSpacer=scroll.metrics.floor-current;this.setSpacer(Math.min(current,Math.max(0,scroll.metrics.top-floorWithoutSpacer)))}interruptFollow(follow){if(!follow.animating)return;const metrics=this.metrics();if(metrics===null||this.elements===null)return;follow.interrupt(this.elements.scroller,metrics);this.observation={top:metrics.top,landing:null}}acknowledge(metrics){this.observation={top:metrics.top,landing:null};this.reclaimBelow()}readScroll(){const metrics=this.metrics();if(metrics===null)return null;return{metrics,movedByReader:Math.abs(metrics.top-Math.min(this.observation.top,metrics.floor))>.5}}metrics(){const scroller=this.elements?.scroller;if(scroller===void 0)return null;return scrollMetrics(scroller)}anchor(key,identity=`position`){if(this.elements===null)return null;let nodePart=null;for(const row of this.elements.list.querySelectorAll(`[data-chat-anchor-key]:not([hidden]):not([hidden] *)`)){if(row.dataset.chatAnchorKey===key||identity===`node`&&row.dataset.chatNodeKey===key)return row;if(nodePart===null&&row.dataset.chatNodeKey===key)nodePart=row}return nodePart}capturePosition(){const elements=this.elements;if(elements===null)return null;const{list,scroller,composer}=elements;const viewport=scroller.getBoundingClientRect();const bottom=composer?.getBoundingClientRect().top??viewport.bottom;let anchor=null;if(typeof document.elementsFromPoint===`function`&&bottom>viewport.top){const content=list.getBoundingClientRect();const left=Math.max(viewport.left,content.left);const right=Math.min(viewport.right,content.right);for(const element of document.elementsFromPoint(left+Math.max(0,right-left)/2,viewport.top+1)){const row=element.closest(`[data-chat-anchor-key]`);if(row!==null&&row.dataset.chatFlowKind!==`turn-process`&&list.contains(row)){anchor=row.dataset.chatGroupKey===void 0?row:row.querySelector(`[data-step-process-content] > [data-chat-anchor-key]:not(:empty):not([hidden]):not([hidden] *)`)??row;break}}}if(anchor===null){const rows=list.querySelectorAll(`[data-chat-flow-key]:not([data-chat-group-key]):not([data-chat-flow-kind="turn-process"]):not(:empty):not([hidden]):not([hidden] *)`);let low=0;let high=rows.length;while(low<high){const middle=low+high>>>1;if(rows.item(middle).getBoundingClientRect().bottom>viewport.top)high=middle;else low=middle+1}const row=rows[low];anchor=row!==void 0&&row.getBoundingClientRect().top<bottom?row:rows[0]??null}const key=anchor?.dataset.chatAnchorKey;return anchor===null||key===void 0?null:{anchorKey:key,anchorTop:anchor.getBoundingClientRect().top-viewport.top,scrollTop:scroller.scrollTop}}readVisibleTurn(metrics=this.metrics()){const knownTurn=this.observation.landing?.turn;if(knownTurn!=null&&metrics?.top===this.observation.top)return knownTurn;const elements=this.elements;const first=this.turns[0];if(elements===null||metrics===null||first===void 0)return null;const line=elements.scroller.getBoundingClientRect().top+Math.min(96,metrics.height*.2);const rows=(elements.column.querySelector(`:scope > [data-slot="conversation.chat.flow"]`)??elements.column).children;let low=0;let high=rows.length;let reading=first.turn;while(low<high){const middle=low+high>>>1;const row=rows[middle];if(row.getBoundingClientRect().top>line)high=middle;else{const value=row.getAttribute(`data-chat-turn`);const turn=value===null?NaN:Number(value);if(Number.isSafeInteger(turn))reading=turn;low=middle+1}}return reading}scrollToTurn(turn){const item=this.turns.find(candidate=>candidate.turn===turn);if(item===void 0)return null;const row=this.anchor(item.anchorKey,`node`);return row===null?null:this.align(row,24,turn)}scrollToTurnAtOrAfter(turn){if(this.elements===null)return null;for(const row of this.elements.list.querySelectorAll(`[data-chat-turn]:not([hidden]):not([hidden] *)`)){const candidate=Number(row.dataset.chatTurn);if(Number.isSafeInteger(candidate)&&candidate>=turn)return this.align(row,24,candidate)}return null}restore(position){const row=this.anchor(position.anchorKey);if(row!==null)return this.align(row,position.anchorTop,null);const metrics=this.metrics();return metrics===null?null:this.write(position.scrollTop,metrics,null)}beginManualPaging(){if(this.elements===null)return;if(this.elements.scroller.scrollTop<=.5)this.beginPaging();else{this.beginPreserving();if(!this.preserving)this.beginPaging()}}beginPaging(){this.stopPreserving();const row=this.pagingAnchor();if(row!==null)this.retain(row)}pagingAnchor(){return this.elements?.list.querySelector(`[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)`)??null}beginPreserving(position=this.capturePosition()){this.stopPreserving();if(position===null)return;const row=this.anchor(position.anchorKey);if(row===null)return;this.retain(row,position)}measurePaging(row,position,previousGroup){const elements=this.elements;const key=row.dataset.chatAnchorKey;if(elements===null||key===void 0)return null;const top=row.getBoundingClientRect().top;const body=row.closest(`[data-step-process-body]`);const content=body?.querySelector(`[data-step-process-content]`);return{row,group:body===null||content==null?null:{body,content,top:previousGroup?.top??top-body.getBoundingClientRect().top},position:position??{anchorKey:key,anchorTop:top-elements.scroller.getBoundingClientRect().top,scrollTop:elements.scroller.scrollTop}}}retain(row,position){const paging=this.measurePaging(row,position);if(paging===null)return null;this.retainPaging(paging);return paging}retainPaging(paging){this.stopPreserving();this.paging=paging;if(paging.group!==null)this.observer?.observe(paging.group.content)}stopPreserving(){const group=this.paging?.group;if(group!=null)this.observer?.unobserve(group.content);this.paging=null}get preserving(){return this.paging!==null}preserve(){const paging=this.resolvePaging(this.paging);if(paging===null){this.stopPreserving();return null}if(paging!==this.paging)this.retainPaging(paging);return this.applyPaging(paging)}resolvePaging(paging){const elements=this.elements;if(paging===null||elements===null)return null;if(!elements.list.contains(paging.row)){const replacement=this.anchor(paging.position.anchorKey);if(replacement===null)return null;paging=this.measurePaging(replacement,paging.position,paging.group);if(paging===null)return null}return paging.row.closest(`[hidden]`)!==null||paging.row.matches(`:empty`)?null:paging}applyPaging(paging){const elements=this.elements;if(elements===null)return null;const{row,group,position}=paging;if(group!==null&&group.body.contains(row)){const top=row.getBoundingClientRect().top-group.body.getBoundingClientRect().top;const metrics=scrollMetrics(group.body);const target=Math.max(0,Math.min(metrics.floor,metrics.top+top-group.top));if(metrics.top!==target){const follow=ScrollFollow.forElement(group.body);if(follow===void 0)group.body.scrollTop=target;else{follow.jump(group.body,metrics,target);follow.setFollowing(false)}}}const metrics=this.metrics();if(metrics===null)return null;const top=row.getBoundingClientRect().top-elements.scroller.getBoundingClientRect().top;const target=metrics.top+top-position.anchorTop;return this.write(target,metrics,null,{key:position.anchorKey,top})}scrollToBottom(follow,behavior=`instant`){const metrics=this.metrics();if(metrics===null||this.elements===null)return null;this.observation={top:metrics.top,landing:null};this.reclaimBelow();const landing={metrics:follow.toBottom(this.elements.scroller,scrollMetrics(this.elements.scroller),behavior),position:null,turn:this.latestTurn};this.observation={top:landing.metrics.top,landing};return landing}align(row,offset,turn){const metrics=this.metrics();if(metrics===null||this.elements===null)return null;const top=row.getBoundingClientRect().top-this.elements.scroller.getBoundingClientRect().top;return this.write(metrics.top+top-offset,metrics,turn,{key:row.dataset.chatAnchorKey,top})}write(target,metrics,turn,anchor){if(this.elements===null)return null;const top=Math.max(0,Math.min(metrics.floor,target));if(top!==metrics.top)this.elements.scroller.scrollTop=top;const actual=this.elements.scroller.scrollTop;const landing={metrics:{...metrics,top:actual},turn,position:anchor?.key===void 0?null:{anchorKey:anchor.key,anchorTop:anchor.top-(actual-metrics.top),scrollTop:actual}};this.observation={top:actual,landing};return landing}setHistoryEdge=element=>{this.historyEdge=element};pruneHistoryScrolling(){for(const target of this.historyScrolling)if(this.elements?.scroller.contains(target)!==true)this.historyScrolling.delete(target)}confirmHistoryStart(){const scroller=this.elements?.scroller;if(scroller===void 0||this.historyEdge===null||this.historyHeight<=0)return false;return scroller.getBoundingClientRect().top-this.historyEdge.getBoundingClientRect().bottom<=this.historyHeight*2}get historyInputHeld(){return this.historyTouch||this.historyPointer}historyConsumption(){const elements=this.elements;if(elements===null)return`unavailable`;if(this.historyTouch)return`touch`;if(this.historyScrolling.size>0&&(this.historyScrolling.size!==1||!this.historyScrolling.has(elements.scroller)))return`inner-scroll`;if(this.motion.active()||this.reader?.follow.animating)return`motion`;if(this.historyPointer)return`pointer`;if(this.historyScrolling.size===0)return elements.scroller.scrollTop<=.5?`prepend`:`preserve`;if(this.preserving||typeof CSS===`undefined`||!CSS.supports(`overflow-anchor`,`auto`))return`unavailable`;return elements.scroller.scrollTop<=.5?`prepend`:`native`}beginHistoryPrepend(){const row=this.pagingAnchor();this.historyPrepend=row===null?null:this.measurePaging(row);return this.historyPrepend!==null}cancelHistoryPrepend(){this.historyPrepend=null}finishHistoryPrepend(){const pending=this.historyPrepend;this.historyPrepend=null;const paging=this.resolvePaging(pending);return paging===null?null:this.applyPaging(paging)}onHistoryScroll=event=>{const target=event.target;if(target===this.elements?.scroller||target.hasAttribute(`data-step-process-body`))this.historyScrolling.add(target)};onHistoryPointerDown=()=>{this.historyPointer=true;this.events?.history?.()};onHistoryTouch=()=>{this.historyTouch=true;this.events?.history?.()};onHistoryRelease=event=>{if(event.type===`pointerup`||event.type===`pointercancel`)this.historyPointer=false;if(event.type===`touchend`||event.type===`touchcancel`)this.historyTouch=`touches`in event&&event.touches.length>0;this.events?.history?.()};onScroll=event=>{if(this.elements===null||event.target!==this.elements.scroller)return;if(this.observation.landing!==null&&this.elements.scroller.scrollTop===this.observation.top)return;this.invalidate();if(this.paging!==null){this.events?.resize();return}const scroll=this.readScroll();if(scroll!==null)this.events?.scroll(scroll)};onScrollEnd=event=>{if(event.target!==null)this.historyScrolling.delete(event.target);this.events?.history?.();if(event.target===this.elements?.scroller){this.events?.scrollEnd(true);this.reclaimBelow()}else if(event.target.hasAttribute(`data-step-process-body`))this.events?.scrollEnd(false)};onIntent=event=>{if(event.type===`keydown`||event.type===`pointerdown`){if(event.target.closest?.(`[data-composer-seat]`)!=null)return;if(event.type===`keydown`&&!SCROLL_KEYS$1.has(event.key))return}this.events?.intent?.();if(this.paging===null)return;this.stopPreserving();this.events?.interact()}};function useChatViewport(){const listRef=(0,react.useRef)(null);const columnRef=(0,react.useRef)(null);const[viewport]=(0,react.useState)(()=>new ChatViewport);(0,react.useLayoutEffect)(()=>{if(listRef.current===null||columnRef.current===null)return;viewport.attach(listRef.current,columnRef.current);return()=>{viewport.detach()}},[viewport]);return{viewport,listRef,columnRef}}function useChatScroll(input){const{isOpen,order,firstSeq,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,deferCompletedTurns,loadedTurns,chatScroll,hasMore,loadingOlder,historyLoadStatus,loadOlder,consumeOlder,loadThrough,transcriptView}=input;const{viewport,listRef,columnRef}=useChatViewport();const[historyInputHeld,setHistoryInputHeld]=(0,react.useState)(false);const{reading,state}=useChatReading(viewport,chatScroll,loadedTurns.at(-1)?.turn??null);const navigationInput=(0,react.useMemo)(()=>({firstSeq,loadingOlder,hasMore,historyLoadStatus,isOpen,loadOlder,consumeOlder,loadThrough}),[firstSeq,loadingOlder,hasMore,historyLoadStatus,isOpen,loadOlder,consumeOlder,loadThrough]);const{navigation,busyTurn,historyPending,historyProcessing}=useChatNavigation(viewport,reading,navigationInput);const content=(0,react.useRef)({input,applied:null,opened:false});const cancelPendingFollow=(0,react.useCallback)(()=>{viewport.motion.cancelInput()},[viewport]);const processContent=(0,react.useCallback)(()=>{const current=content.current.input;if(!current.isOpen&&!content.current.opened)return;const previous=content.current.applied;const steeringInput=current.steeringId!==null&&current.steeringId!==previous?.steeringId&&current.steeringId!==previous?.submissionId;const submissionInput=current.submissionId!==null&&current.submissionId!==previous?.submissionId&&current.submissionId!==previous?.steeringId;const ownInput=current.lastIsUser&&current.lastKey!==previous?.lastKey||steeringInput||submissionInput;if(reading.pending&&!ownInput)return;content.current.applied=current;if(current.isOpen&&!content.current.opened){content.current.opened=true;navigation.reset();reading.restore();return}if(ownInput){navigation.cancel();if(current.deferCompletedTurns&&reading.followInputFold(true))return;const steering=steeringInput||submissionInput&&current.submissionSteers;reading.followTail(current.deferCompletedTurns&&!steering?`smooth`:`instant`);return}if(navigation.contentCommitted()){navigation.reconcile();return}if((previous===null||current.isOpen!==previous.isOpen||current.firstSeq!==previous.firstSeq||current.lastKey!==previous.lastKey||current.order.length!==previous.order.length||current.running!==previous.running||current.steeringId!==previous.steeringId||current.submissionId!==previous.submissionId)&&reading.followingTail){navigation.cancel();if(current.deferCompletedTurns&&reading.followInputFold(false))return;reading.followTail()}else navigation.reconcile()},[reading,navigation]);(0,react.useLayoutEffect)(()=>{const disconnectViewport=viewport.connect({scroll:event=>{if(!content.current.opened)return;if(!event.movedByReader&&viewport.motion.foldActive())return;reading.onScroll(event)},scrollEnd:outer=>{reading.onScrollEnd(outer);navigation.requestHistoryCheck()},interact:()=>{navigation.readerInteracted()},history:()=>{setHistoryInputHeld(viewport.historyInputHeld);if(content.current.opened)navigation.requestHistoryCheck()},intent:()=>{cancelPendingFollow();reading.interruptFollow()},resize:()=>{if(!content.current.opened)return;navigation.requestHistoryCheck();if(navigation.contentCommitted()){navigation.reconcile();return}if(!content.current.input.deferCompletedTurns||!viewport.motion.foldActive())reading.onResize();navigation.reconcile()}});const disconnectReading=reading.connect(sample=>{navigation.readerSampled(sample);processContent();navigation.requestHistoryCheck()});return()=>{disconnectViewport();disconnectReading();content.current.opened=false;content.current.applied=null}},[viewport,reading,navigation,processContent,cancelPendingFollow]);(0,react.useLayoutEffect)(()=>{const previous=content.current.input;content.current.input={order,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,loadedTurns,chatScroll,deferCompletedTurns,transcriptView,...navigationInput};if(!deferCompletedTurns){cancelPendingFollow();reading.interruptFollow()}viewport.updateTurns(loadedTurns);const layoutChanged=previous.order!==order||previous.isOpen!==isOpen;const historyConsumed=previous.historyLoadStatus===`pendingConsumption`&&historyLoadStatus===`idle`;if(!isOpen||historyLoadStatus===`error`)viewport.cancelHistoryPrepend();else if(layoutChanged||historyConsumed){const landing=viewport.finishHistoryPrepend();if(landing!==null)reading.preservePosition(landing)}if(layoutChanged)viewport.invalidate();viewport.reclaimBelow();processContent();if(layoutChanged&&content.current.opened)reading.refreshActiveTurn();if(content.current.opened)navigation.requestHistoryCheck()},[viewport,reading,processContent,navigationInput,isOpen,order,lastKey,lastIsUser,steeringId,submissionId,submissionSteers,running,loadedTurns,chatScroll,deferCompletedTurns,transcriptView,cancelPendingFollow]);const previousView=(0,react.useRef)(transcriptView);(0,react.useLayoutEffect)(()=>{if(previousView.current===transcriptView)return;previousView.current=transcriptView;cancelPendingFollow();reading.interruptFollow();return viewport.motion.onFoldIdle(()=>{viewport.resetBelow();if(content.current.opened)reading.onResize()})},[transcriptView,viewport,reading,cancelPendingFollow]);const returnToBottom=(0,react.useCallback)(()=>{cancelPendingFollow();navigation.cancel();reading.followTail()},[navigation,reading,cancelPendingFollow]);return{listRef,columnRef,...state,busyTurn,motion:viewport.motion,navigateToTurn:navigation.navigateToTurn,loadEarlier:navigation.loadEarlier,historyPending,historyProcessing,historyInputHeld,historyEdgeRef:viewport.setHistoryEdge,returnToBottom}}function openFailureMessage(error,fallback){const message=error instanceof Error?error.message:String(error);return message===``?fallback:message}function observedInputs(order,nodes){const observed=new Set;let lastInputTurn;for(const key of order){const node=nodes.get(key);if(node===void 0||!isAtOrOutside(node,`input`))continue;if(node.location.kind===`turn`||node.location.kind===`step`)lastInputTurn=node.location.turn.turn;const data=node.data;const source=typeof data===`object`&&data!==null&&`source`in data?data.source:void 0;if(typeof source===`object`&&source!==null&&`kind`in source&&source.kind===`user`&&`rpcId`in source&&typeof source.rpcId===`string`)observed.add(source.rpcId)}return{rpcIds:observed,lastInputTurn}}const MOTION_TAIL_MS=800;function ChatView({useSession,useChat,useConversation,useSessions,renderSlot,sessionId,openFile,openExternalLink,resolveFilePath,useContextMenu,loadOlder,consumeOlder,loadThrough,loadImage,inspectCall,inspectRequest,chatScroll,forkAt,usePresentation,useProjection,useInteractionIds,dispatchInteraction,t,fileDrag}){const{getTriggerProps}=useContextMenu();const getMarkdownTriggerProps=(0,react.useCallback)(target=>getTriggerProps(()=>{switch(target.kind){case`file`:return{kind:`file`,value:{sessionId,path:resolveFilePath(target.path),...target.line===void 0?{}:{line:target.line}}};case`url`:return{kind:`url`,value:{sessionId,url:target.url}};case`image`:return{kind:`image`,value:{sessionId,url:target.url,...target.name===void 0?{}:{name:target.name},...target.mediaType===void 0?{}:{mediaType:target.mediaType},...target.path===void 0?{}:{path:resolveFilePath(target.path)}}}}}),[getTriggerProps,resolveFilePath,sessionId]);const order=useChat(s=>s.order);const groupedEntries=useConversation(snapshot=>snapshot.views.grouped(`chat`)?.entries);const entries=(0,react.useMemo)(()=>groupedEntries??order.map(key=>({kind:`node`,key})),[groupedEntries,order]);const nodeStore=useChat(s=>s.nodes);const inheritedFolded=useConversation(snapshot=>snapshot.inheritedHistoryFolded===true);const hasMore=useSession(s=>s.hasMore)&&!inheritedFolded;const deferCompletedTurns=usePresentation(policy=>policy.collapseTiming===`next-input`);const transcriptView=usePresentation(policy=>policy.mode);const turnNavigationItems=useChat(s=>s.navigation.items());const turnOutline=useProjection(`turnOutline`);const railItems=(0,react.useMemo)(()=>mergeTurnRailItems(turnNavigationItems,inheritedFolded?void 0:turnOutline),[turnNavigationItems,turnOutline,inheritedFolded]);const inbox=useProjection(`inbox`);const cwd=useSessions(s=>s.byId[sessionId]?.cwd);const directory=useSessions(s=>selectSessionDirectory(s,sessionId));const fileImages=(0,react.useMemo)(()=>({fileDrag,resolve:path=>fileMediaUrl(document.baseURI,resolveWorkspacePath(directory,path)),resourceAddress:path=>sessionFileAddress(sessionId,resolveWorkspacePath(directory,path)),labels:{open:t(`image.open`),loading:t(`image.loading`),failed:t(`image.failed`),dialog:t(`image.dialog`),close:t(`image.close`)}}),[directory,t,fileDrag,sessionId]);const codeLabels=(0,react.useMemo)(()=>markdownLabels(t).code,[t]);const renderCode=(0,react.useCallback)(fence=>renderSlot(`conversation.chat.markdown.fence`,fence,{entryKey:fence.lang,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceCodeBlock,{lang:fence.lang,code:fence.code,streaming:fence.streaming,labels:codeLabels,diff:false})}),[renderSlot,codeLabels]);const running=useSession(s=>s.running);const[motionTail,setMotionTail]=(0,react.useState)(false);(0,react.useEffect)(()=>{if(!deferCompletedTurns){setMotionTail(false);return}if(running){setMotionTail(true);return}const timer=setTimeout(()=>{setMotionTail(false)},MOTION_TAIL_MS);return()=>{clearTimeout(timer)}},[running,deferCompletedTurns]);const openState=useSession(s=>s.openState);const openError=useSession(s=>s.openError);const loadingOlder=useSession(s=>s.loadingOlder);const historyLoadStatus=useSession(s=>s.historyLoadStatus);const historyWasPartial=useSession(s=>s.historyWasPartial);const[fileOpenError,setFileOpenError]=(0,react.useState)(null);const[fileOpenBusy,setFileOpenBusy]=(0,react.useState)(false);const fileOpenRequest=(0,react.useRef)(0);const requestOpenFile=(0,react.useCallback)((path,options)=>{const id=++fileOpenRequest.current;setFileOpenBusy(true);(options===void 0?openFile(path):openFile(path,options)).then(()=>{if(id!==fileOpenRequest.current)return;setFileOpenError(null);setFileOpenBusy(false)},error=>{if(id!==fileOpenRequest.current)return;setFileOpenError({path,message:openFailureMessage(error,t(`fileOpen.unknown`))});setFileOpenBusy(false)})},[openFile,t]);const closeFileOpenError=(0,react.useCallback)(()=>{fileOpenRequest.current+=1;setFileOpenError(null);setFileOpenBusy(false)},[]);const retryFileOpen=(0,react.useCallback)(()=>{if(fileOpenError!==null)requestOpenFile(fileOpenError.path)},[fileOpenError,requestOpenFile]);const inboxSteering=(0,react.useMemo)(()=>inbox?.[`next-step`].filter(message=>message.source.kind===`user`)??[],[inbox]);const pendingSubmissions=useSession(s=>s.pendingSubmissions);const[visibleSubmissions,lastInputTurn]=(0,react.useMemo)(()=>{if(pendingSubmissions.length===0)return[pendingSubmissions,void 0];const observed=observedInputs(order,nodeStore);return[pendingSubmissions.filter(submission=>submission.placement!==`queued`&&!observed.rpcIds.has(submission.requestId)),observed.lastInputTurn]},[pendingSubmissions,order,nodeStore]);const pendingInputs=(0,react.useMemo)(()=>{const local=new Map(visibleSubmissions.map(submission=>[submission.requestId,submission]));const localIds=new Set(pendingSubmissions.filter(submission=>submission.placement!==`queued`).map(submission=>submission.requestId));return[...inboxSteering.flatMap(item=>{const source=item.source;if(source.kind!==`user`||!(`rpcId`in source))return[item];const submission=local.get(source.rpcId);if(submission===void 0)return localIds.has(source.rpcId)?[]:[item];local.delete(source.rpcId);return[submission]}),...local.values()]},[inboxSteering,pendingSubmissions,visibleSubmissions]);const deferCollapse=deferCompletedTurns&&!pendingInputs.some(item=>`requestId`in item&&item.placement===`transcript`);const firstKey=order[0];const firstSeq=firstKey===void 0?null:nodeStore.get(firstKey)?.anchorSeq??null;const lastKey=order.at(-1)??null;const latestSteering=pendingInputs.findLast(item=>`source`in item);const steeringId=latestSteering?.source.kind===`user`&&`rpcId`in latestSteering.source?latestSteering.source.rpcId:latestSteering?.id??null;const scroll=useChatScroll({isOpen:openState===`open`,order,firstSeq,lastKey,running,loadingOlder,historyLoadStatus,hasMore,chatScroll,loadOlder,consumeOlder,loadThrough,deferCompletedTurns,lastIsUser:lastKey!==null&&nodeStore.get(lastKey)?.kind===`user`,steeringId,submissionId:visibleSubmissions.at(-1)?.requestId??null,submissionSteers:visibleSubmissions.at(-1)?.placement===`steering`,loadedTurns:turnNavigationItems,transcriptView});const interactionSurfaceRef=(0,react.useRef)(null);const interactionIds=useInteractionIds(ids=>ids);const textInteraction=useTextInteraction(scroll.columnRef,interactionSurfaceRef,dispatchInteraction,interactionIds);const flowContext=(0,react.useMemo)(()=>({motion:scroll.motion}),[scroll.motion]);return(0,react_jsx_runtime.jsxs)(`div`,{className:ChatView_module_css_default.frame,children:[scroll.initialized&&(0,react_jsx_runtime.jsx)(TurnNavigator,{items:railItems,activeTurn:scroll.activeTurn,busyTurn:scroll.busyTurn,onNavigate:scroll.navigateToTurn,t}),(0,react_jsx_runtime.jsx)(ChatAside,{renderSlot}),(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.root,"data-chat-following-tail":scroll.followingTail?``:void 0,"data-conversation-overscroll":`none`,"data-conversation-scroll-anchor":scroll.followingTail?`none`:void 0,children:(0,react_jsx_runtime.jsxs)(`div`,{ref:scroll.listRef,className:ChatView_module_css_default.scroll,children:[(0,react_jsx_runtime.jsxs)(`div`,{ref:scroll.columnRef,className:ChatView_module_css_default.column,"data-chat-flow":``,"data-chat-motion":deferCompletedTurns&&scroll.initialized&&(running||motionTail||pendingInputs.length>0)?``:void 0,children:[openState===`loading`&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.hint,children:t(`chat.loadingHistory`)}),openState===`error`&&openError!==null&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.openError,children:t(`chat.loadError`,{message:openError.message,code:openError.code})}),!inheritedFolded&&(hasMore||historyWasPartial)&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.older,ref:scroll.historyEdgeRef,"data-chat-history":historyLoadStatus,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,disabled:!hasMore,onClick:scroll.loadEarlier,children:[[`more`,t(`chat.loadOlder`)],[`loading`,t(`chat.loadingOlder`)],[`processing`,t(`chat.processingOlder`)],[`error`,t(`chat.retryOlder`)],[`start`,t(`chat.historyStart`)]].map(([state,label])=>{const current=!hasMore?`start`:loadingOlder?`loading`:historyLoadStatus===`error`?`error`:scroll.historyInputHeld?`more`:scroll.historyProcessing?`processing`:`more`;return(0,react_jsx_runtime.jsx)(`span`,{"aria-hidden":state!==current,className:state===current?void 0:ChatView_module_css_default.historyHidden,children:label},state)})})}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownDelegateProvider,{getTriggerProps:getMarkdownTriggerProps,openFile:requestOpenFile,openExternalLink,fileImages,renderCode,children:renderSlot(`conversation.chat.flow`,{entries,pendingInputs,lastInputTurn,deferCollapse,cwd,openFile:requestOpenFile,inspectCall,inspectRequest,forkAt,loadImage},{hookContext:flowContext})}),(0,react_jsx_runtime.jsx)(`div`,{ref:interactionSurfaceRef,className:ChatView_module_css_default.textInteraction,"data-text-interaction-surface":``,"aria-hidden":textInteraction.active===null,children:textInteraction.active!==null&&renderSlot(`conversation.chat.text-interaction`,{trigger:textInteraction.active.trigger,readText:textInteraction.readText,dismiss:textInteraction.dismiss,clearSelection:textInteraction.clearSelection},{entryKey:textInteraction.active.id})})]}),(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.turnSpacer,"data-chat-turn-spacer":true,"aria-hidden":`true`})]})}),!scroll.followingTail&&(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.toBottomSlot,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:ChatView_module_css_default.toBottom,"aria-label":t(`chat.toBottom`),onClick:scroll.returnToBottom,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{size:16})})}),fileOpenError!==null&&(0,react_jsx_runtime.jsx)(FileOpenErrorDialog,{message:fileOpenError.message,busy:fileOpenBusy,onClose:closeFileOpenError,onRetry:retryFileOpen,t})]})}function FileOpenErrorDialog({message,busy,onClose,onRetry,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Modal,{open:true,onClose,closeLabel:t(`close`),title:t(`fileOpen.title`),description:message,footer:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Button,{variant:`outline`,className:ChatView_module_css_default.modalAction,onClick:onClose,children:t(`cancel`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Button,{variant:`primary`,className:ChatView_module_css_default.modalAction,disabled:busy,onClick:onRetry,children:t(`retry`)})]})})}const SIMPLE_ESCAPES={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
12
12
  `,r:`\r`,t:` `};const CONTENT_ESCAPE=/[\\\u0000-\u001f]/u;function isWhitespace(c){return c===` `||c===`
13
- `||c===`\r`||c===` `}function isHex(c){return c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`}var PartialArguments=class PartialArguments{static EMPTY=PartialArguments.fromObject({});static fromText(text){const view=new PartialArguments;view.append(text);view.sealed=true;return view}static fromObject(value){const view=new PartialArguments;view.object=typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{};view.sealed=true;return view}chunks=[];object;sealed=false;#ends=[];#size=0;#consumed=0;#mode=`root`;#escape=false;#keyStart=0;#keyEscaped=false;#key=``;#current=null;#nestedEnds=[];#nestedInString=false;#invalidAt;#invalidValue=false;#entries=new Map;#order=[];#reads=new Map;get isSealed(){return this.sealed}get invalid(){this.scan();return this.#mode===`invalid`||this.#invalidValue}append(fragment){if(this.sealed)throw new Error(`PartialArguments: cannot append to a sealed view`);if(fragment.length===0)return;this.chunks.push(fragment);this.#size+=fragment.length;this.#ends.push(this.#size)}settle(text){if(this.object!==void 0||text.length!==this.#size)return PartialArguments.fromText(text);let offset=0;for(const chunk of this.chunks){if(!text.startsWith(chunk,offset))return PartialArguments.fromText(text);offset+=chunk.length}this.chunks=text.length===0?[]:[text];this.#ends=text.length===0?[]:[text.length];this.sealed=true;return this}refresh(){if(this.#reads.size===0)return false;this.scan();let changed=false;let completions=false;for(const read of this.#reads.values()){if(read.completion){completions=true;continue}changed=this.refreshRead(read)||changed}if(completions){for(const read of this.#reads.values())if(read.completion)changed=this.refreshRead(read)||changed}if(this.sealed)this.#reads.clear();return changed}refreshRead(read){const now=read.answer();if(Object.is(now,read.last))return false;read.last=now;return true}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),keys=>keys.length)}has(key){return this.remember(`has`,key,()=>this.hasNow(key))}complete(key){return this.remember(`complete`,key,()=>this.completeNow(key))}stringLength(key,options){const step=Math.max(1,Math.floor(options?.step??1));const offset=options?.offset??0;return this.remember(`length:${step}:${offset}`,key,()=>this.lengthNow(key),length=>length===void 0?void 0:Math.ceil((length+offset)/step))}stringExceeds(key,maxLength){const limit=Math.max(0,Math.floor(maxLength));return this.remember(`exceeds:${limit}`,key,()=>(this.lengthNow(key,limit+1)??0)>limit)}text(key){return this.remember(`text`,key,()=>this.textNow(key))}textPrefix(key,maxLength){const limit=Math.max(1,Math.floor(maxLength));return this.remember(`prefix:${limit}`,key,()=>this.textPrefixNow(key,limit))}value(key){return this.remember(`value`,key,()=>this.valueNow(key))}remember(kind,key,read,comparison){this.scan();const result=read();if(!this.sealed){const id=`${kind}/${key}`;if(!this.#reads.has(id))this.#reads.set(id,{completion:kind===`complete`,answer:comparison===void 0?read:()=>comparison(read()),last:comparison===void 0?result:comparison(result)})}return result}closedNow(){return this.sealed||this.#mode===`closed`||this.#mode===`invalid`}keysNow(){return this.object===void 0?this.#order:Object.keys(this.object)}hasNow(key){return this.object===void 0?this.#entries.has(key):Object.hasOwn(this.object,key)}completeNow(key){if(this.object!==void 0)return Object.hasOwn(this.object,key);const entry=this.#entries.get(key);return entry!==void 0&&entry.end>=0&&(entry.kind===`string`?entry.invalidAt===void 0:!entry.invalid)}lengthNow(key,limit=Number.POSITIVE_INFINITY){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.length:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text!==void 0&&entry.text.at===entry.end)return entry.text.length;const read=entry.length??={at:entry.start,length:0,text:``};this.readString(entry,read,limit,false);return read.length}textNow(key){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text===void 0&&entry.end>=0&&entry.needsDecoding&&entry.invalidAt===void 0){let text;try{text=JSON.parse(`"${this.slice(entry.start,entry.end)}"`)}catch(_error){}if(text!==void 0)entry.text={at:entry.end,length:text.length,text}}const read=entry.text??={at:entry.start,length:0,text:``};this.readString(entry,read,Number.POSITIVE_INFINITY,true);return read.text}textPrefixNow(key,maxLength){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.slice(0,maxLength):void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;const prefixes=entry.prefixes??=new Map;let read=prefixes.get(maxLength);if(read===void 0){read={at:entry.start,length:0,text:``};prefixes.set(maxLength,read)}this.readString(entry,read,maxLength,true);return read.text}valueNow(key){if(this.object!==void 0){if(!Object.hasOwn(this.object,key))return void 0;const field=this.object[key];return typeof field===`string`?void 0:field}const entry=this.#entries.get(key);if(entry?.kind!==`value`||entry.end<0||entry.invalid)return void 0;if(entry.parsed===void 0)try{entry.parsed=JSON.parse(this.slice(entry.start,entry.end))}catch(_error){entry.invalid=true;this.#invalidValue=true}return entry.parsed}chunkAt(at){let low=0;let high=this.#ends.length;while(low<high){const mid=low+high>>>1;if(this.#ends[mid]<=at)low=mid+1;else high=mid}return low}slice(start,end){if(start>=end)return``;const first=this.chunkAt(start);const last=this.chunkAt(end-1);const base=first===0?0:this.#ends[first-1];if(first===last)return this.chunks[first].slice(start-base,end-base);const parts=[this.chunks[first].slice(start-base)];for(let i=first+1;i<last;i++)parts.push(this.chunks[i]);parts.push(this.chunks[last].slice(0,end-this.#ends[last-1]));return parts.join(``)}readString(entry,read,limit,materialize){const end=Math.min(entry.end<0?this.#consumed:entry.end,entry.invalidAt??Number.POSITIVE_INFINITY,this.#invalidAt??Number.POSITIVE_INFINITY);if(!entry.needsDecoding){const length=Math.min(end-read.at,limit-read.length);if(length<=0)return;if(materialize)read.text+=this.slice(read.at,read.at+length);read.at+=length;read.length+=length;return}let chunkIndex=this.chunkAt(read.at);while(read.at<end&&read.length<limit){const base=chunkIndex===0?0:this.#ends[chunkIndex-1];const chunk=this.chunks[chunkIndex];const remaining=chunk.slice(read.at-base,Math.min(chunk.length,end-base));const boundary=remaining.search(CONTENT_ESCAPE);const length=Math.min(boundary<0?remaining.length:boundary,limit-read.length);if(length>0){if(materialize)read.text+=remaining.slice(0,length);read.at+=length;read.length+=length;if(read.at===base+chunk.length)chunkIndex++;continue}const type=remaining.length>1?remaining[1]:read.at+1<end?this.chunks[chunkIndex+1][0]:void 0;let decoded;let width=2;if(remaining[0]===`\\`&&type===void 0&&entry.end<0)return;if(remaining[0]===`\\`&&type===`u`){const hex=this.slice(read.at+2,Math.min(end,read.at+6));let valid=true;for(let i=0;i<hex.length;i++)if(!isHex(hex[i]))valid=false;if(valid){if(hex.length<4&&entry.end<0)return;if(hex.length===4)decoded=String.fromCharCode(Number.parseInt(hex,16))}width=6}else if(remaining[0]===`\\`&&type!==void 0)decoded=SIMPLE_ESCAPES[type];if(decoded===void 0){entry.invalidAt=read.at;this.#invalidValue=true;return}if(materialize)read.text+=decoded;read.length++;read.at+=width;while(chunkIndex<this.chunks.length&&read.at>=this.#ends[chunkIndex])chunkIndex++}}scan(){if(this.object!==void 0||this.#consumed===this.#size)return;for(let i=this.chunkAt(this.#consumed);i<this.chunks.length&&this.#invalidAt===void 0;i++){const pending=this.chunks[i];const base=i===0?0:this.#ends[i-1];for(let index=this.#consumed-base;index<pending.length&&this.#mode!==`invalid`;index++){if(this.#mode===`string`||this.#mode===`nested`&&this.#nestedInString){const end=this.stringBoundary(pending,index);this.#consumed+=end-index;index=end;if(index===pending.length)break}this.step(pending[index],this.#consumed);this.#consumed++}}}stringBoundary(fragment,start){let at=start;while(true){const quote=fragment.indexOf(`"`,at);const end=quote<0?fragment.length:quote;if(this.#mode===`string`){const entry=this.#current;if(!entry.needsDecoding&&CONTENT_ESCAPE.test(fragment.slice(at,end)))entry.needsDecoding=true}let slashStart=end;while(slashStart>at&&fragment[slashStart-1]===`\\`)slashStart--;const escaped=(end-slashStart)%2===1!==(slashStart===at&&this.#escape);this.#escape=quote<0&&escaped;if(quote<0||!escaped)return end;at=quote+1}}step(c,at){switch(this.#mode){case`root`:if(isWhitespace(c))return;if(c===`{`){this.#mode=`key-or-end`;return}this.fail();return;case`key-or-end`:if(isWhitespace(c))return;if(c===`}`){this.#mode=`closed`;return}if(c===`"`){this.beginKey(at);return}this.fail();return;case`key-only`:if(isWhitespace(c))return;if(c===`"`){this.beginKey(at);return}this.fail();return;case`key`:this.stepKey(c,at);return;case`colon`:if(isWhitespace(c))return;if(c===`:`){this.#mode=`value`;return}this.fail();return;case`value`:this.beginValue(c,at);return;case`string`:{const entry=this.#current;entry.end=at;this.#current=null;this.#mode=`comma-or-end`;return}case`scalar`:this.stepScalar(c,at);return;case`nested`:this.stepNested(c,at);return;case`comma-or-end`:if(isWhitespace(c))return;if(c===`,`){this.#mode=`key-only`;return}if(c===`}`){this.#mode=`closed`;return}this.fail();return;case`closed`:if(isWhitespace(c))return;this.fail();return;case`invalid`:return;default:assertNever(this.#mode)}}fail(){this.#invalidAt=this.#consumed;this.#mode=`invalid`;this.#current=null}beginKey(at){this.#mode=`key`;this.#keyStart=at+1;this.#keyEscaped=false;this.#escape=false}stepKey(c,at){if(c<` `){this.fail();return}if(this.#escape){this.#escape=false;return}if(c===`\\`){this.#escape=true;this.#keyEscaped=true;return}if(c!==`"`)return;const raw=this.slice(this.#keyStart,at);if(this.#keyEscaped)try{this.#key=JSON.parse(`"${raw}"`)}catch(_error){this.fail();return}else this.#key=raw;this.#mode=`colon`}open(entry){if(!this.#entries.has(this.#key))this.#order.push(this.#key);this.#entries.set(this.#key,entry);this.#current=entry}beginValue(c,at){if(isWhitespace(c))return;if(c===`"`){this.open({kind:`string`,start:at+1,end:-1,needsDecoding:false,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0});this.#escape=false;this.#mode=`string`;return}if(c===`}`||c===`,`||c===`:`||c===`]`){this.fail();return}this.open({kind:`value`,start:at,end:-1,parsed:void 0,invalid:false});if(c===`{`||c===`[`){this.#mode=`nested`;this.#nestedEnds=[c===`{`?`}`:`]`];this.#nestedInString=false;this.#escape=false;return}this.#mode=`scalar`}stepScalar(c,at){if(c!==`,`&&c!==`}`&&!isWhitespace(c))return;this.closeValue(at);this.#mode=c===`,`?`key-only`:c===`}`?`closed`:`comma-or-end`}stepNested(c,at){if(this.#nestedInString){this.#nestedInString=false;return}if(c===`"`){this.#nestedInString=true;return}if(c===`{`||c===`[`){this.#nestedEnds.push(c===`{`?`}`:`]`);return}if(c===`}`||c===`]`){if(this.#nestedEnds.pop()!==c){this.fail();return}if(this.#nestedEnds.length===0){this.closeValue(at+1);this.#mode=`comma-or-end`}}}closeValue(end){const entry=this.#current;entry.end=end;this.#current=null}};function assertNever(value,context){const rendered=JSON.stringify(value)??String(value);throw new Error(`unreachable variant${context?` in ${context}`:``}: ${rendered}`)}function hasAssistantReplyContent(blocks){return blocks.some(block=>{if(block.kind===`reasoning`||block.kind===`tool-call`)return false;if(block.kind===`text`)return block.text.trim()!==``;return true})}function sameTurnProcessSpec(left,right){return left.turn===right.turn&&left.controlAnchorSeq===right.controlAnchorSeq&&left.processStartSeq===right.processStartSeq&&left.answerAnchorSeq===right.answerAnchorSeq&&left.answerStep===right.answerStep&&left.inlineReasoning===right.inlineReasoning&&left.messageCount===right.messageCount&&left.toolCallCount===right.toolCallCount&&left.subagentCount===right.subagentCount}function isSubagentDelegationTool(name){return name===`subagent`||name.startsWith(`subagent_`)}function turnProcessAlwaysOpen(node){const location=node?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return false;const reason=location.turn.end?.data.reason.kind;return location.turn.status===`open`||reason===`aborted`||reason===`interrupted`||reason===`error`}function storedTurnProcessEntry(state,turn){return state.turnProcesses.find(entry=>entry.turn===turn)}function turnProcessOpen(state,spec,defaultOpen){const stored=storedTurnProcessEntry(state,spec.turn);if(stored===void 0||stored.answerStep!==(spec.answerStep??0))return defaultOpen;return stored.collapsed!==true}function createChatStore(){return(0,_deepseek_ai_dsh_client_store.defineStore)({init:()=>({turnProcesses:[]}),actions:{setTurnProcessOpen:(draft,turn,answerStep,open)=>{const index=draft.turnProcesses.findIndex(entry=>entry.turn===turn);const next=open?{turn,answerStep}:{turn,answerStep,collapsed:true};if(index<0)draft.turnProcesses.push(next);else draft.turnProcesses[index]=next}}})}function stepRunsGrouped(grouping,turnOpen,deferCollapse){return grouping===`collapsed`||grouping===`history`&&!turnOpen&&!deferCollapse}function processTitle(summary,t){const labels=summary.counts.slice(0,3).map(({kind})=>t(`message.stepProcess.done.${kind}`));const first=labels[0];if(first===void 0)return t(`message.stepProcess.done.thinking`);const continuation=label=>label.charAt(0).toLowerCase()+label.slice(1);const second=labels[1];if(second===void 0)return first;if(labels.length===2){const prefix=t(`message.stepProcess.sharedPrefix`);return t(`message.stepProcess.joinTwo`,{first,second:continuation(prefix!==``&&first.startsWith(prefix)&&second.startsWith(prefix)?second.slice(prefix.length):second)})}const title=[first,...labels.slice(1).map(continuation)].join(t(`message.stepProcess.comma`));return summary.counts.length>3?t(`message.stepProcess.more`,{title}):title}function thinkingTitle(summary,t){const first=summary.counts[0];if(first===void 0||first.kind===`context`)return t(`message.stepProcess.thinking`);return t(`message.stepProcess.thinkingNext`,{title:processTitle(summary,t)})}function turnDataOf(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.data:void 0}function turnOf$1(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.turn:void 0}const ChatNodeSeat=(0,react.memo)(function ChatNodeSeat({nodeKey,groupPart,useChatNode,useChatNodeProcess,usePresentation,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,useStore,actions,renderSlot,t,useChatNodeBottom,deferCollapse,useGroupAction}){const bottom=useChatNodeBottom(nodeKey);const node=useChatNode(nodeKey);const routedNode=node;const turn=turnOf$1(routedNode);const processPresentation=useChatNodeProcess(nodeKey);const processSpec=processPresentation?.spec;const storedOpen=useStore(state=>processSpec!==void 0&&turnProcessOpen(state,processSpec,bottom===true&&deferCollapse));const liveProcess=processPresentation!==void 0&&!processPresentation.turnClosed;const interleavedInput=processPresentation?.hasInterleavedInput===true;const alwaysOpen=liveProcess||interleavedInput||turnProcessAlwaysOpen(routedNode);const processOpen=alwaysOpen||storedOpen;const setOpen=(0,react.useCallback)(open=>{if(processSpec!==void 0&&!alwaysOpen)actions.setTurnProcessOpen(processSpec.turn,processSpec.answerStep??0,open)},[actions,processSpec,alwaysOpen]);const foldCompleted=usePresentation(policy=>policy.foldCompletedTurns);const keepReplies=usePresentation(policy=>policy.foldedReplies===`all`);const processWindowReady=processSpec!==void 0&&processPresentation!==void 0&&foldCompleted&&processPresentation.turn===processSpec.turn&&(processPresentation.turnStarted||processPresentation.turnClosed);const replyRow=keepReplies&&routedNode?.kind===`assistant-step`&&groupPart!==`reasoning`&&hasAssistantReplyContent(routedNode.data.blocks);const processMember=routedNode!==void 0&&processWindowReady&&!replyRow&&!isAtOrOutside(routedNode,`turn`)&&routedNode.anchorSeq>=processSpec.processStartSeq&&(liveProcess||processSpec.answerAnchorSeq===null||routedNode.anchorSeq<processSpec.answerAnchorSeq||groupPart===`reasoning`&&routedNode.kind===`assistant-step`&&routedNode.data.step===processSpec.answerStep);const processAnswer=routedNode!==void 0&&processWindowReady&&!liveProcess&&groupPart!==`reasoning`&&routedNode.kind===`assistant-step`&&routedNode.data.step===processSpec.answerStep;const ownsDisclosure=routedNode?.kind===`turn-process`||processAnswer||replyRow;const foldable=processWindowReady&&(liveProcess||processMember||ownsDisclosure);const turnProcess=(0,react.useMemo)(()=>processSpec===void 0?void 0:{spec:processSpec,foldable,hasContent:!interleavedInput&&(processSpec.inlineReasoning||(keepReplies?processPresentation?.hasNonReplyProcess===true:processPresentation?.hasExternalProcess===true)),open:processOpen,setOpen},[foldable,interleavedInput,keepReplies,processOpen,processSpec,processPresentation?.hasExternalProcess,processPresentation?.hasNonReplyProcess,setOpen]);const processHidden=routedNode?.kind===`turn-process`&&foldCompleted&&!foldable||foldable&&processMember&&!processOpen;const wrapperRef=useGroupAction(processHidden,(0,react.useCallback)(()=>{if(processMember)setOpen(true)},[processMember,setOpen]));const[disclosureReset]=(0,react.useState)(()=>(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(0));const turnData=turnDataOf(routedNode);const hookContext=(0,react.useMemo)(()=>({turnData,disclosureReset,useGroupAction}),[turnData,disclosureReset,useGroupAction]);(0,react.useEffect)(()=>{if(processMember&&processHidden&&wrapperRef.current!==null&&hiddenOrCollapsing(wrapperRef.current))disclosureReset.set(disclosureReset.getSnapshot()+1)},[processMember,processHidden,wrapperRef,disclosureReset]);const turnOpen=routedNode?.location.kind===`turn`||routedNode?.location.kind===`step`?routedNode.location.turn.status===`open`:false;const stepRunsGroupedHere=usePresentation(policy=>stepRunsGrouped(policy.stepGrouping,turnOpen,bottom===true&&deferCollapse));const owner=(0,react.useMemo)(()=>node===void 0?null:{...groupPart===void 0?{}:{groupPart},cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,turnProcess,stepRunsGrouped:stepRunsGroupedHere},[node,groupPart,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,turnProcess,stepRunsGroupedHere]);if(routedNode===void 0||owner===null)return null;const routedOwner={...owner,node:routedNode};const flowKey=groupPart===void 0||groupPart===`response`?routedNode.key:JSON.stringify([routedNode.key,groupPart]);return(0,react_jsx_runtime.jsx)(`div`,{ref:wrapperRef,className:ChatView_module_css_default.flowItem,"data-chat-anchor-key":flowKey,"data-chat-flow-key":flowKey,"data-chat-paging-anchor":routedNode.kind!==`turn-process`||void 0,"data-chat-node-key":routedNode.key,"data-chat-group-part":groupPart,"data-chat-flow-kind":routedNode.kind,"data-chat-turn":turn,"data-turn-process-member":processMember||void 0,"data-turn-process-hidden":processHidden||void 0,children:renderSlot(`conversation.chat.node`,routedOwner,{entryKey:routedNode.kind,hookContext,fallback:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownSurface`,{type:routedNode.kind}),payload:routedNode.data,truncatedLabel:total=>t(`json.truncated`,{total})})})})});function chatRenderKey(entry){switch(entry.kind){case`node`:return JSON.stringify([`node`,entry.key,entry.groupPart??null]);case`group`:return JSON.stringify([`group`,entry.key]);default:return assertNever(entry)}}function useDisclosure(version=0){const[expandedVersion,setExpandedVersion]=(0,react.useState)(null);return{expanded:expandedVersion===version,setExpanded:(0,react.useCallback)(open=>{setExpandedVersion(open?version:null)},[version]),toggle:(0,react.useCallback)(()=>{setExpandedVersion(previous=>previous===version?null:version)},[version])}}function bindDisclosure(reset){const subscribe=listener=>reset.subscribe(listener);const getSnapshot=()=>reset.getSnapshot();return function useBoundDisclosure(){return useDisclosure((0,react.useSyncExternalStore)(subscribe,getSnapshot))}}const AT_REST={canScrollUp:false,canScrollDown:false};const SCROLL_KEYS=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function useProcessScroll(bodyRef,contentRef,open,grouped){const follow=useScrollFollow(false,1);const initialPosition=(0,react.useRef)(null);const[edges,setEdges]=(0,react.useState)(AT_REST);const initialize=(0,react.useCallback)(position=>{initialPosition.current=position},[]);const sync=(0,react.useCallback)(cause=>{const body=bodyRef.current;let next=AT_REST;if(body!==null&&body.closest(`[hidden], [data-group-expanded-mode]`)===null){let metrics=scrollMetrics(body);const initial=cause===`resize`?initialPosition.current:null;if(initial!==null){metrics=follow.jump(body,metrics,initial===`bottom`?metrics.floor:0);if(initial===`top`)follow.setFollowing(false);initialPosition.current=null}else{const wasAnimating=follow.animating;if(cause===`scrollend`)follow.settle(metrics);else follow.sample(metrics);if(follow.active&&(cause===`resize`||cause===`scrollend`&&wasAnimating))metrics=follow.toBottom(body,metrics,`smooth`)}next={canScrollUp:metrics.top>1,canScrollDown:metrics.top<metrics.floor-1}}else follow.reset();setEdges(previous=>previous.canScrollUp===next.canScrollUp&&previous.canScrollDown===next.canScrollDown?previous:next)},[bodyRef,follow]);const interrupt=(0,react.useCallback)(()=>{const body=bodyRef.current;if(body!==null&&follow.animating)follow.interrupt(body,scrollMetrics(body))},[bodyRef,follow]);const events=(0,react.useMemo)(()=>({onScroll:()=>{sync(`scroll`)},onWheel:interrupt,onTouchStart:interrupt,onPointerDown:interrupt,onKeyDown:event=>{if(!event.defaultPrevented&&SCROLL_KEYS.has(event.key))interrupt()}}),[interrupt,sync]);(0,react.useLayoutEffect)(()=>{interrupt();follow.reset();if(!grouped||!open)initialPosition.current=null},[follow,grouped,interrupt,open]);(0,react.useLayoutEffect)(()=>{const body=bodyRef.current;if(body===null||!open||typeof ResizeObserver===`undefined`)return;const unbind=follow.bind(body);const observer=new ResizeObserver(()=>{sync(`resize`)});const onScrollEnd=event=>{if(event.target===body)sync(`scrollend`)};body.addEventListener(`scrollend`,onScrollEnd);observer.observe(body);if(contentRef.current!==null)observer.observe(contentRef.current);return()=>{unbind();observer.disconnect();body.removeEventListener(`scrollend`,onScrollEnd)}},[bodyRef,contentRef,follow,open,sync]);return{edges,events,initialize}}var ChatGroupSeat_module_css_default={"activityIcon":`O_Ebla_activityIcon`,"body":`O_Ebla_body`,"chevron":`O_Ebla_chevron`,"content":`O_Ebla_content`,"expandedBody":`O_Ebla_expandedBody`,"fadeBottom":`O_Ebla_fadeBottom`,"fadeTop":`O_Ebla_fadeTop`,"label":`O_Ebla_label`,"leading":`O_Ebla_leading`,"root":`O_Ebla_root`,"title":`O_Ebla_title`};const PROCESS_TITLE_MINIMUM_MS=150;const PROCESS_ICONS={thinking:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconThinkOutlineRegular,{}),read:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),readImage:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),search:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconSearchOutlineRegular,{size:14}),edit:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconEditOutlineRegular,{size:14}),write:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconEditOutlineRegular,{size:14}),commands:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{}),code:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCodeOutlineRegular,{size:14}),webSearch:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconGlobeOutlineRegular,{}),webFetch:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),subagents:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconAgentPresetOutlineRegular,{size:14}),plan:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconPlanOutlineRegular,{}),questions:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconQuestionOutlineRegular,{}),tools:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconSparkleRegular,{size:14}),context:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,{size:14})};function sameLiveProcessTitle(left,right){return left.activity===right.activity&&left.detail===right.detail&&left.preparing===right.preparing&&left.thinking===right.thinking}function useStableLiveProcessTitle(desired,active){const[displayed,setDisplayed]=(0,react.useState)(desired);const displayedRef=(0,react.useRef)(displayed);const desiredRef=(0,react.useRef)(desired);const displayedAtRef=(0,react.useRef)(Date.now());(0,react.useEffect)(()=>{desiredRef.current=desired;if(!active||sameLiveProcessTitle(displayedRef.current,desired))return;const remaining=PROCESS_TITLE_MINIMUM_MS-(Date.now()-displayedAtRef.current);const commit=()=>{const next=desiredRef.current;displayedRef.current=next;displayedAtRef.current=Date.now();setDisplayed(next)};if(remaining<=0){commit();return}const timer=setTimeout(commit,remaining);return()=>{clearTimeout(timer)}},[active,desired.activity,desired.detail,desired.preparing,desired.thinking]);return active?displayed:desired}const GroupMembers=(0,react.memo)(function GroupMembers({members,...props}){return members.map(member=>(0,react.createElement)(ChatNodeSeat,{...props,key:chatRenderKey(member),nodeKey:member.key,...member.groupPart===void 0?{}:{groupPart:member.groupPart}}))});const ProcessGroupHeader=(0,react.memo)(function ProcessGroupHeader({groupKey,useChatGroup,usePresentation,t,open,bodyId,toggle}){const data=useChatGroup(groupKey,group=>group?.data);const detailed=usePresentation(policy=>data?.closed===false&&policy.liveProcessDetail);const live=useStableLiveProcessTitle({activity:data?.summary.running??`thinking`,detail:data?.summary.runningDetail??``,preparing:data?.summary.preparing===true,thinking:data===void 0||data.closed||data.summary.running!==void 0?``:thinkingTitle(data.summary,t)},data!==void 0&&!data.closed);if(data===void 0)return null;const label=data.closed?processTitle(data.summary,t):live.preparing?t(`message.stepProcess.prepare.${live.activity===`thinking`?`tools`:live.activity}`):live.activity===`thinking`?live.thinking:t(`message.stepProcess.${live.activity}`);const detail=detailed&&!data.closed?live.detail:``;const title=detail===``?label:`${label}${t(`message.turnProcess.separator`)}${detail}`;const activity=data.closed?data.summary.counts[0]?.kind??`thinking`:live.activity;return(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ChatGroupSeat_module_css_default.title,"aria-expanded":open,"aria-controls":bodyId,"data-process-activity":activity,onClick:event=>{event.currentTarget.focus();toggle()},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:ChatGroupSeat_module_css_default.leading,"aria-hidden":`true`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChatGroupSeat_module_css_default.activityIcon,"data-step-process-icon":true,children:PROCESS_ICONS[activity]}),(0,react_jsx_runtime.jsx)(`span`,{className:ChatGroupSeat_module_css_default.chevron,"data-step-process-chevron":true,children:open?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronUpOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{})})]}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{active:!data.closed,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{className:ChatGroupSeat_module_css_default.label,children:title})})]})});const ChatGroupSeat=(0,react.memo)(function ChatGroupSeat({groupKey,useChatGroup,useGroupHeaderAction,...props}){const members=useChatGroup(groupKey,group=>group?.members);const turn=useChatGroup(groupKey,group=>group?.data.turn);const closed=useChatGroup(groupKey,group=>group?.data.closed);const foldCompleted=props.usePresentation(policy=>policy.foldCompletedTurns);const{expanded:open,setExpanded:setOpen}=useDisclosure();const firstKey=members?.[0]?.key??``;const deferCollapse=props.useChatNodeBottom(firstKey)===true&&props.deferCollapse;const presentation=props.useChatNodeProcess(firstKey);const turnLocation=props.useChatNode(firstKey,node=>{const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0});const grouped=props.usePresentation(policy=>stepRunsGrouped(policy.stepGrouping,turnLocation?.status===`open`,deferCollapse));const reason=turnLocation?.end?.data.reason.kind;const alwaysOpen=presentation?.turnClosed===false||presentation?.hasInterleavedInput===true||reason===`aborted`||reason===`interrupted`||reason===`error`;const spec=presentation?.spec;const selectOpen=(0,react.useCallback)(state=>spec!==void 0&&turnProcessOpen(state,spec,deferCollapse),[spec,deferCollapse]);const storedOpen=props.useStore(selectOpen);const outerHidden=foldCompleted&&presentation?.turnClosed===true&&spec!==void 0&&!alwaysOpen&&!storedOpen;const revealOuter=(0,react.useCallback)(()=>{if(spec!==void 0&&!alwaysOpen)props.actions.setTurnProcessOpen(spec.turn,spec.answerStep??0,true)},[props.actions,spec,alwaysOpen]);const rootRef=props.useGroupAction(outerHidden,revealOuter);const headerRef=(0,react.useRef)(null);const deferCompletedTurns=props.usePresentation(policy=>policy.collapseTiming===`next-input`);useGroupHeaderAction(headerRef,!grouped||deferCompletedTurns&&outerHidden);(0,react.useEffect)(()=>{if(outerHidden&&rootRef.current!==null&&hiddenOrCollapsing(rootRef.current))setOpen(false)},[outerHidden,rootRef,setOpen]);const reveal=(0,react.useCallback)(()=>{setOpen(true)},[setOpen]);const bodyRef=props.useGroupAction(grouped&&!open,reveal);const contentRef=(0,react.useRef)(null);const bodyId=(0,react.useId)();const{edges,events,initialize}=useProcessScroll(bodyRef,contentRef,open,grouped);const toggle=(0,react.useCallback)(()=>{if(!open)initialize(closed===false?`bottom`:`top`);setOpen(!open)},[closed,initialize,open,setOpen]);const shownCap=!grouped?false:open?true:void 0;const[closingCap,setClosingCap]=(0,react.useState)(shownCap??true);if(shownCap!==void 0&&shownCap!==closingCap)setClosingCap(shownCap);if(members===void 0)return null;const capped=grouped&&(!deferCompletedTurns||(shownCap??closingCap));const classes=[ChatGroupSeat_module_css_default.body,!capped?ChatGroupSeat_module_css_default.expandedBody:``,capped&&edges.canScrollUp?ChatGroupSeat_module_css_default.fadeTop:``,capped&&edges.canScrollDown?ChatGroupSeat_module_css_default.fadeBottom:``];return(0,react_jsx_runtime.jsxs)(`div`,{ref:rootRef,className:ChatGroupSeat_module_css_default.root,"data-chat-group-key":groupKey,"data-chat-flow-key":groupKey,"data-chat-anchor-key":`group:${groupKey}`,"data-chat-turn":turn,"data-chat-paging-anchor":grouped&&!open||void 0,"data-step-process":true,"data-group-expanded-mode":!grouped||void 0,children:[(0,react_jsx_runtime.jsx)(`div`,{ref:headerRef,children:(0,react_jsx_runtime.jsx)(ProcessGroupHeader,{groupKey,useChatGroup,usePresentation:props.usePresentation,t:props.t,open,bodyId,toggle})}),(0,react_jsx_runtime.jsx)(`div`,{ref:bodyRef,id:bodyId,className:classes.join(` `),"data-step-process-body":true,"data-scroll-up":edges.canScrollUp||void 0,"data-scroll-down":edges.canScrollDown||void 0,...events,children:(0,react_jsx_runtime.jsx)(`div`,{ref:contentRef,className:ChatGroupSeat_module_css_default.content,"data-step-process-content":true,"data-chat-flow":``,children:(0,react_jsx_runtime.jsx)(GroupMembers,{...props,members})})})]})});var accessibility_module_css_default={"visuallyHidden":`TTCZqG_visuallyHidden`};var CommandStatusRow_module_css_default={"body":`kWGFkG_body`,"leading":`kWGFkG_leading`,"root":`kWGFkG_root`,"separator":`kWGFkG_separator`,"summary":`kWGFkG_summary`,"title":`kWGFkG_title`};const COMMAND_ICON=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{size:14});const CommandStatusRow=(0,react.memo)(function CommandStatusRow({title,state,summary,body,t}){const[expanded,setExpanded]=(0,react.useState)(false);const running=state===`running`;const open=expanded&&body!==null;const toggle=(0,react.useCallback)(()=>{setExpanded(value=>!value)},[]);const collapsedContent=(0,react.useMemo)(()=>(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:CommandStatusRow_module_css_default.separator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:CommandStatusRow_module_css_default.summary,"data-error":state===`error`||void 0,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{children:summary})})]}),[state,summary]);const content=(0,react.useMemo)(()=>open?(0,react_jsx_runtime.jsx)(`pre`,{className:CommandStatusRow_module_css_default.body,"data-error":state===`error`||void 0,children:body}):void 0,[body,open,state]);return(0,react_jsx_runtime.jsxs)(`div`,{className:CommandStatusRow_module_css_default.root,"data-variant":`others`,"data-state":state,children:[state===`running`&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.running`)}),state===`error`&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.failed`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{leadingClassName:CommandStatusRow_module_css_default.leading,titleClassName:CommandStatusRow_module_css_default.title,icon:COMMAND_ICON,title,running,open,expandable:body!==null,expandOnRowClick:true,keepContentWhenOpen:true,onToggle:toggle,collapsedContent,children:content})]})});var MessageItem_module_css_default={"attachmentRow":`Sixlwa_attachmentRow`,"compactionButton":`Sixlwa_compactionButton`,"compactionContextIcon":`Sixlwa_compactionContextIcon`,"compactionLeading":`Sixlwa_compactionLeading`,"compactionOpenIcon":`Sixlwa_compactionOpenIcon`,"compactionRow":`Sixlwa_compactionRow`,"compactionSep":`Sixlwa_compactionSep`,"compactionSummary":`Sixlwa_compactionSummary`,"compactionTitle":`Sixlwa_compactionTitle`,"contextRow":`Sixlwa_contextRow`,"fileCard":`Sixlwa_fileCard`,"fileContent":`Sixlwa_fileContent`,"fileIcon":`Sixlwa_fileIcon`,"fileMeta":`Sixlwa_fileMeta`,"fileName":`Sixlwa_fileName`,"inheritedHistoryCaption":`Sixlwa_inheritedHistoryCaption`,"inheritedHistoryIcon":`Sixlwa_inheritedHistoryIcon`,"inheritedHistoryLabel":`Sixlwa_inheritedHistoryLabel`,"inheritedHistoryLine":`Sixlwa_inheritedHistoryLine`,"inheritedHistoryRow":`Sixlwa_inheritedHistoryRow`,"maxTokensTitle":`Sixlwa_maxTokensTitle`,"referenceSummary":`Sixlwa_referenceSummary`,"retryBesideGroups":`Sixlwa_retryBesideGroups`,"retryDetailLabel":`Sixlwa_retryDetailLabel`,"retryDetails":`Sixlwa_retryDetails`,"retryLeading":`Sixlwa_retryLeading`,"retryProgress":`Sixlwa_retryProgress`,"retryRow":`Sixlwa_retryRow`,"retrySeparator":`Sixlwa_retrySeparator`,"retryTitle":`Sixlwa_retryTitle`,"turnErrorCode":`Sixlwa_turnErrorCode`,"turnErrorCopy":`Sixlwa_turnErrorCopy`,"turnErrorDot":`Sixlwa_turnErrorDot`,"turnErrorMessage":`Sixlwa_turnErrorMessage`,"turnErrorRow":`Sixlwa_turnErrorRow`,"turnErrorTitle":`Sixlwa_turnErrorTitle`,"userRow":`Sixlwa_userRow`,"userStack":`Sixlwa_userStack`};const CompactionItem=(0,react.memo)(function CompactionItem({node,openCompaction,title,fallbackSummary,t}){const summarySeq=node.summaryEventSeq;const available=openCompaction!==void 0&&summarySeq!==null;const pending=(0,react.useRef)(null);const[opening,setOpening]=(0,react.useState)(false);const[failure,setFailure]=(0,react.useState)(null);(0,react.useEffect)(()=>{pending.current=null;setOpening(false);setFailure(null);return()=>{pending.current?.abort()}},[node.seq,summarySeq,openCompaction]);const open=async()=>{if(!available||pending.current!==null)return;const controller=new AbortController;pending.current=controller;setOpening(true);setFailure(null);try{const result=await openCompaction(summarySeq,controller.signal);if(!controller.signal.aborted)setFailure(result)}catch(error){if(!controller.signal.aborted)setFailure(error instanceof Error?error.message:String(error))}finally{if(pending.current===controller)pending.current=null;if(!controller.signal.aborted)setOpening(false)}};const summary=node.shadowedItemCount!==null&&node.shadowedTokenCount!==null?t(`message.compaction.completed`,{items:node.shadowedItemCount,tokens:node.shadowedTokenCount}):fallbackSummary??t(`message.compaction.landed`);const action=t(`message.compaction.open`);return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.compactionRow,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:action,side:`top`,portal:true,delayMs:200,disabled:!available,children:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:MessageItem_module_css_default.compactionButton,disabled:!available||opening,"aria-busy":opening,"data-compaction-seq":node.seq,onClick:()=>{open()},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.compactionLeading,"aria-hidden":true,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionContextIcon,"data-compaction-icon":`context`,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{})}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionOpenIcon,"data-compaction-icon":`open`,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronRightOutlineRegular,{})})]}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionTitle,children:title??t(`message.compaction`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionSep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionSummary,children:summary}),available&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:action})]})}),failure!==null&&(0,react_jsx_runtime.jsx)(`p`,{role:`alert`,children:failure})]})});var ContextBody_module_css_default={"catalogNotice":`ZkiH0q_catalogNotice`,"entries":`ZkiH0q_entries`,"entry":`ZkiH0q_entry`,"entryDescription":`ZkiH0q_entryDescription`,"entryName":`ZkiH0q_entryName`,"field":`ZkiH0q_field`,"fieldKey":`ZkiH0q_fieldKey`,"fieldValue":`ZkiH0q_fieldValue`,"fields":`ZkiH0q_fields`,"file":`ZkiH0q_file`,"fileAction":`ZkiH0q_fileAction`,"filePath":`ZkiH0q_filePath`,"files":`ZkiH0q_files`,"recall":`ZkiH0q_recall`,"recallCounts":`ZkiH0q_recallCounts`,"recallLabel":`ZkiH0q_recallLabel`,"recalls":`ZkiH0q_recalls`,"relaySender":`ZkiH0q_relaySender`,"section":`ZkiH0q_section`,"sectionName":`ZkiH0q_sectionName`,"sectionNotice":`ZkiH0q_sectionNotice`,"sectionText":`ZkiH0q_sectionText`,"sections":`ZkiH0q_sections`,"text":`ZkiH0q_text`};const MAX_CHARS=2e4;const MAX_ENTRIES=200;function asRecord$1(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:null}function contentRuns(content){const runs=[];for(const block of content){if(block.type!==`text`){runs.push({block});continue}const last=runs[runs.length-1];if(last!==void 0&&`text`in last)last.text+=block.text;else runs.push({text:block.text})}return runs}function unknownBlocks(content){return contentRuns(content).flatMap(run=>`block`in run?[run.block]:[])}function boundedText(text,t){return text.length>MAX_CHARS?`${text.slice(0,MAX_CHARS)}\n${t(`json.truncated`,{total:text.length})}`:text}function fieldValue(value,t){return boundedText(typeof value===`string`?value:typeof value===`number`||typeof value===`boolean`?String(value):JSON.stringify(value),t)}function SourceFields({source,formRendered,t}){const record=asRecord$1(source);if(record===null)return null;const hidden=formRendered?[`kind`,`form`]:[`kind`];const rows=Object.entries(record).filter(([key])=>!hidden.includes(key));if(rows.length===0)return null;return(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.fields,"data-context-fields":true,children:rows.map(([key,value])=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.field,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.fieldKey,children:key}),(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.fieldValue,children:fieldValue(value,t)})]},key))})}function UnknownBlocks({blocks,t}){return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children:blocks.map((block,index)=>(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:block,truncatedLabel:total=>t(`json.truncated`,{total})},index))})}function ModelFacingContent({content,t}){return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children:contentRuns(content).map((run,index)=>`text`in run?run.text!==``&&(0,react_jsx_runtime.jsx)(`pre`,{className:ContextBody_module_css_default.text,"data-context-text":true,children:boundedText(run.text,t)},index):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:run.block,truncatedLabel:total=>t(`json.truncated`,{total})},index))})}function OpaqueBody({content,source,t}){return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t}),(0,react_jsx_runtime.jsx)(SourceFields,{source,formRendered:false,t})]})}function instructionChanges(source){const record=asRecord$1(source);const list=record===null?void 0:record[`changes`];if(!Array.isArray(list))return null;const changes=[];const seen=new Set;for(const entry of list){const change=asRecord$1(entry);if(change===null)return null;const path=change[`path`];if(typeof path!==`string`||path===``)return null;const action=change[`action`];if(action!==`set`&&action!==`replace`&&action!==`remove`)return null;const digest=change[`digest`];if(seen.has(path))continue;seen.add(path);changes.push({action,path,...typeof digest===`string`?{digest}:{}})}return changes.length===0?null:changes}function instructionAction(action,baseline){if(action===`remove`)return`message.context.instructions.removed`;if(baseline)return`message.context.instructions.loaded`;return action===`set`?`message.context.instructions.added`:`message.context.instructions.updated`}function InstructionsBody({content,source,t}){const changes=instructionChanges(source);if(changes===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});const baseline=asRecord$1(source)?.[`baseline`]===true;return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.files,"data-context-files":true,children:changes.map(change=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.file,title:change.digest,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.filePath,children:change.path}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.fileAction,children:t(instructionAction(change.action,baseline))})]},change.path))}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function catalogEntries(source){const record=asRecord$1(source);const list=record===null?void 0:record[`entries`];if(!Array.isArray(list))return null;const entries=[];for(const item of list){const entry=asRecord$1(item);if(entry===null)return null;const name=entry[`name`];const description=entry[`description`];if(typeof name!==`string`||name===``||typeof description!==`string`)return null;entries.push({name,description})}return entries}function CatalogBody({content,source,t}){const entries=catalogEntries(source);if(entries===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});const update=asRecord$1(source)?.[`update`]===true;const shown=entries.slice(0,MAX_ENTRIES);const rest=unknownBlocks(content);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[update&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-catalog-update":true,children:t(`message.context.catalog.replaced`)}),(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.entries,"data-context-entries":true,children:shown.map((entry,index)=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.entry,children:[(0,react_jsx_runtime.jsx)(`code`,{className:ContextBody_module_css_default.entryName,children:entry.name}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.entryDescription,children:entry.description})]},index))}),shown.length<entries.length&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-entries-truncated":true,children:t(`message.context.catalog.more`,{count:entries.length-shown.length})}),(0,react_jsx_runtime.jsx)(UnknownBlocks,{blocks:rest,t})]})}function snapshotSections(source){const record=asRecord$1(source);const list=record===null?void 0:record[`sections`];if(!Array.isArray(list))return null;const sections=[];for(const item of list){const section=asRecord$1(item);if(section===null)return null;const name=section[`name`];const text=section[`text`];if(typeof name!==`string`||name===``||typeof text!==`string`)return null;sections.push({name,text})}return sections.length===0?null:sections}function SnapshotBody({content,source,t}){const sections=snapshotSections(source);if(sections===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-snapshot-supersedes":true,children:t(`message.context.snapshot.supersedes`)}),(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.sections,"data-context-sections":true,children:sections.map((section,index)=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.section,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.sectionName,children:section.name}),(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionText,children:boundedText(section.text,t)})]},index))})]})}function SystemSectionsBody({message,t}){return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[message.reset&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-system-reset":true,children:t(`message.systemPromptReset`)}),message.notices.map((notice,index)=>(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-system-notice":true,children:boundedText(notice,t)},index)),(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.sections,"data-system-sections":true,children:message.changes.map(change=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.section,"data-system-section":change.change,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.sectionName,children:t(`message.systemSection.${change.change}`,{name:change.name})}),change.notices.map((notice,index)=>(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionNotice,"data-system-notice":true,children:boundedText(notice,t)},index)),change.text!==``&&(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionText,children:boundedText(change.text,t)})]},change.name))})]})}function NoticeBody({content,t}){return(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})}function RelayBody({content,source,t}){const sender=relaySender(source);if(sender===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.relaySender,"data-context-relay-sender":true,children:t(`message.context.relay.from`,{session:sender})}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function relaySender(source){const sender=asRecord$1(source)?.[`senderSessionId`];return typeof sender===`string`&&sender!==``?sender:null}function recalledSessions(source){const record=asRecord$1(source);const list=record===null?void 0:record[`references`];if(!Array.isArray(list))return null;const sessions=[];for(const item of list){const reference=asRecord$1(item);if(reference===null)return null;const label=reference[`label`];const retained=reference[`retainedMessages`];const omitted=reference[`omittedMessages`];const truncated=reference[`truncated`];if(typeof label!==`string`||label===``||typeof retained!==`number`||typeof omitted!==`number`||typeof truncated!==`boolean`)return null;sessions.push({label,retained,omitted,truncated})}return sessions.length===0?null:sessions}function RecallBody({content,source,t}){const sessions=recalledSessions(source);if(sessions===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.recalls,"data-context-recalls":true,children:sessions.map((session,index)=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.recall,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallLabel,children:session.label}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallCounts,children:t(`message.context.recall.counts`,{retained:session.retained,omitted:session.omitted})}),session.truncated&&(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallCounts,children:t(`message.context.recall.truncated`)})]},index))}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function noticeSummary(source){const summary=asRecord$1(source)?.[`summary`];return typeof summary===`string`&&summary!==``?summary:null}function contextBody(form,props){const opaque={rendered:null,summary:null,body:(0,react_jsx_runtime.jsx)(OpaqueBody,{...props})};switch(form){case`instructions`:return instructionChanges(props.source)===null?opaque:{rendered:`instructions`,summary:null,body:(0,react_jsx_runtime.jsx)(InstructionsBody,{...props})};case`catalog`:return catalogEntries(props.source)===null?opaque:{rendered:`catalog`,summary:null,body:(0,react_jsx_runtime.jsx)(CatalogBody,{...props})};case`snapshot`:return snapshotSections(props.source)===null?opaque:{rendered:`snapshot`,summary:null,body:(0,react_jsx_runtime.jsx)(SnapshotBody,{...props})};case`notice`:{const summary=noticeSummary(props.source);return summary===null?opaque:{rendered:`notice`,summary,body:(0,react_jsx_runtime.jsx)(NoticeBody,{...props})}}case`relay`:return relaySender(props.source)===null?opaque:{rendered:`relay`,summary:null,body:(0,react_jsx_runtime.jsx)(RelayBody,{...props})};case`recall`:return recalledSessions(props.source)===null?opaque:{rendered:`recall`,summary:null,body:(0,react_jsx_runtime.jsx)(RecallBody,{...props})};case null:return opaque;default:throw new Error(`unreachable context form: ${String(form)}`)}}var ContextInjectionRow_module_css_default={"body":`XrJvXW_body`,"chevron":`XrJvXW_chevron`,"root":`XrJvXW_root`,"sep":`XrJvXW_sep`,"source":`XrJvXW_source`,"summary":`XrJvXW_summary`,"toolChanges":`XrJvXW_toolChanges`};function ContextInjectionRow({content,source,producer,form,t}){const[open,setOpen]=(0,react.useState)(false);const{rendered,summary,body}=contextBody(form,{content,source,t});const toolBlocks=content.length>0&&content.every(block=>block.type===`tool-addition`||block.type===`tool-removal`)?content:void 0;const added=toolBlocks?.flatMap(block=>block.type===`tool-addition`?[block.toolName]:[])??[];const removed=toolBlocks?.flatMap(block=>block.type===`tool-removal`?[block.toolName]:[])??[];const single=toolBlocks?.length===1?toolBlocks[0]:void 0;const toolSummary=toolBlocks===void 0||single!==void 0?null:added.length>0&&removed.length>0?t(`message.toolsChanged`,{added:added.length,removed:removed.length}):added.length>0?t(`message.toolsAddedCount`,{count:added.length}):t(`message.toolsRemovedCount`,{count:removed.length});return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{className:ContextInjectionRow_module_css_default.root,icon:toolBlocks!==void 0?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}):producer.role===`recall`?(0,react_jsx_runtime.jsx)(`span`,{"data-context-recall-icon":true,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.ReferenceIconRegular,{kind:`session`})}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,{size:14}),chevronClassName:ContextInjectionRow_module_css_default.chevron,title:single!==void 0?t(single.type===`tool-addition`?`message.toolAdded`:`message.toolRemoved`,{name:single.toolName}):t(toolBlocks!==void 0?`message.toolsUpdated`:producer.role===`recall`?`message.contextRecall`:`message.contextInjection`),collapsedContent:toolSummary!==null?(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,children:toolSummary})]}):toolBlocks!==void 0||producer.label===null?void 0:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.source,"data-context-source":true,children:producer.label}),summary!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,"data-context-summary":true,children:summary})]})]}),keepContentWhenOpen:true,open:open&&single===void 0,expandable:single===void 0,expandOnRowClick:true,onToggle:()=>{setOpen(value=>!value)},children:(0,react_jsx_runtime.jsx)(`div`,{className:ContextInjectionRow_module_css_default.body,"data-context-injection-body":true,"data-context-form":rendered??void 0,children:toolBlocks===void 0?body:(0,react_jsx_runtime.jsxs)(`div`,{className:ContextInjectionRow_module_css_default.toolChanges,children:[added.length>0&&(0,react_jsx_runtime.jsx)(`div`,{children:t(`message.toolsAdded`,{names:added.join(`, `)})}),removed.length>0&&(0,react_jsx_runtime.jsx)(`div`,{children:t(`message.toolsRemoved`,{names:removed.join(`, `)})})]})})})}const LIVE_RUN_CLOCK_INTERVAL_MS=1e3;function pad2(n){return String(n).padStart(2,`0`)}function startOfLocalDay(ms){const d=new Date(ms);d.setHours(0,0,0,0);return d.getTime()}function msUntilNextLocalMidnight(ms){const next=new Date(ms);next.setHours(24,0,0,0);return Math.max(next.getTime()-ms,1)}function formatRunDuration(ms,t){const total=Math.max(0,Math.floor(ms/1e3));const hours=Math.floor(total/3600);const minutes=Math.floor(total/60)%60;const seconds=total%60;const parts=[];if(hours>0)parts.push({text:String(hours),numeric:true},{text:t(`duration.hourUnit`),numeric:false});if(total>=60)parts.push({text:String(minutes),numeric:true},{text:t(`duration.minuteUnit`),numeric:false});parts.push({text:String(seconds),numeric:true},{text:t(`duration.secondUnit`),numeric:false});return parts}function formatTokensPerSecond(tps){const clamped=Math.max(0,tps);return clamped>=10?String(Math.round(clamped)):String(Math.round(clamped*10)/10)}function formatMessageClock(time,t,now=Date.now()){const d=new Date(time);const n=new Date(now);const clock=`${pad2(d.getHours())}:${pad2(d.getMinutes())}`;if(d.getFullYear()===n.getFullYear()&&d.getMonth()===n.getMonth()&&d.getDate()===n.getDate())return clock;const params={y:d.getFullYear(),m:d.getMonth()+1,d:d.getDate()};return`${d.getFullYear()===n.getFullYear()?t(`clock.md`,params):t(`clock.ymd`,params)} ${clock}`}function useCalendarDay(){const[day,setDay]=(0,react.useState)(()=>startOfLocalDay(Date.now()));(0,react.useEffect)(()=>{let timer;const arm=()=>{const now=Date.now();setDay(startOfLocalDay(now));timer=setTimeout(arm,msUntilNextLocalMidnight(now))};timer=setTimeout(arm,msUntilNextLocalMidnight(Date.now()));return()=>{clearTimeout(timer)}},[]);return day}var MessageIconActions_module_css_default={"action":`xzv4MW_action`,"actions":`xzv4MW_actions`,"endInfo":`xzv4MW_endInfo`,"timeEnd":`xzv4MW_timeEnd`,"timeStart":`xzv4MW_timeStart`,"visuallyHidden":`xzv4MW_visuallyHidden`};function MessageIconActions({text,time,clock,onBranch,branchUnavailable=false,className,extraActions,usageAction,t}){const day=useCalendarDay();const reasonId=(0,react.useId)();const{copied,onCopy}=(0,_deepseek_ai_dsh_client_ui_primitives_client.useClipboardCopy)(text);const clockEl=time===void 0?null:(0,react_jsx_runtime.jsx)(`span`,{className:clock===`start`?MessageIconActions_module_css_default.timeStart:MessageIconActions_module_css_default.timeEnd,children:formatMessageClock(time,t,day)});return(0,react_jsx_runtime.jsxs)(`div`,{className:className===void 0?MessageIconActions_module_css_default.actions:`${MessageIconActions_module_css_default.actions} ${className}`,"data-clock":clock,children:[clock===`start`?clockEl:null,(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:copied?t(`copied`):t(`copy`),side:`bottom`,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:MessageIconActions_module_css_default.action,"aria-label":copied?t(`copied`):t(`copy`),onClick:onCopy,children:copied?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCheckOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCopyOutlineRegular,{})})}),extraActions,onBranch!==void 0&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:branchUnavailable?t(`message.branchUnavailable`):t(`message.branch`),side:`bottom`,openOnClick:branchUnavailable,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:MessageIconActions_module_css_default.action,"aria-label":t(`message.branch`),"aria-disabled":branchUnavailable||void 0,"aria-describedby":branchUnavailable?reasonId:void 0,"data-unavailable":branchUnavailable||void 0,onClick:branchUnavailable?void 0:onBranch,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,{})})}),onBranch!==void 0&&branchUnavailable&&(0,react_jsx_runtime.jsx)(`span`,{id:reasonId,className:MessageIconActions_module_css_default.visuallyHidden,children:t(`message.branchUnavailable`)}),clock===`end`?(0,react_jsx_runtime.jsxs)(`span`,{className:MessageIconActions_module_css_default.endInfo,children:[usageAction,clockEl]}):usageAction]})}const EMPTY_TEXT_FACTS={};function contentParts(content){const texts=[];const attachments=[];const rest=[];for(const block of content){const b=block;if(b.type===`text`&&typeof b.text===`string`)texts.push(b.text);else if(b.type===`image`&&b.attachment!==void 0)attachments.push({type:`image`,image:{attachment:b.attachment}});else if(b.type===`file`&&b.attachment!==void 0)attachments.push({type:`file`,file:b.attachment});else rest.push(block)}return{text:texts.join(``),attachments,rest}}function retrySeconds(milliseconds){return Math.max(1,Math.ceil(milliseconds/1e3))}function failureMessage(message,code,t){if(code===`ACCOUNT_SIGNED_OUT`)return t(`message.failure.accountSignedOut`);if(code===`INTERRUPTED`)return t(`message.failure.interrupted`);if(code===`ACCOUNT_SIGN_IN_REQUIRED`)return t(`message.failure.accountSignInRequired`);if(code===`QUOTA`||code===`ACCOUNT_QUOTA`)return t(`message.failure.quota`);return code===`AUTH`?t(`message.failure.auth`):message}function retryIcon(node,failed){if(node.failure.code===`EMPTY_RESPONSE`)return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWarningOutlineRegular,{});return failed?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWifiOffOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWifiOutlineRegular,{})}function ModelRetryItem({node,active,inFlight,failed,grouped,inspect,t}){const[open,setOpen]=(0,react.useState)(false);const toggle=(0,react.useCallback)(()=>{setOpen(value=>!value)},[]);const deadline=(0,react.useMemo)(()=>Date.now()+node.delayMs,[node.delayMs,node.seq]);const scheduledSeconds=retrySeconds(node.delayMs);const maximum=node.mode===`normal`?node.maxRetries:`∞`;const[countdown,setCountdown]=(0,react.useState)(()=>({deadline,seconds:retrySeconds(deadline-Date.now())}));const remainingSeconds=countdown.deadline===deadline?countdown.seconds:retrySeconds(deadline-Date.now());(0,react.useEffect)(()=>{if(!active)return;const updateCountdown=()=>{const next=retrySeconds(deadline-Date.now());setCountdown(current=>current.deadline===deadline&&current.seconds===next?current:{deadline,seconds:next});return next};if(updateCountdown()===1)return;const timer=window.setInterval(()=>{if(updateCountdown()===1)window.clearInterval(timer)},250);return()=>{window.clearInterval(timer)}},[active,deadline]);const retrying=active||inFlight;const label=retrying?t(`message.retry.active`):node.retryState===`cancelled`?t(`message.retry.cancelled`):node.retryState===`started`?t(`message.retry.started`):t(`message.retry.scheduled`);const seconds=active?remainingSeconds:scheduledSeconds;const status=t(`message.retry.status`,{label,retry:node.retry,maximum,seconds});const title=t(`message.retry.title`,{label,retry:node.retry,maximum});const remaining=t(`message.retry.countdown`,{seconds});return(0,react_jsx_runtime.jsxs)(`div`,{className:grouped?MessageItem_module_css_default.retryBesideGroups:void 0,"data-retry-row":true,"data-inspect-scope":true,"data-active":retrying||void 0,"data-failed":failed||void 0,children:[(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-atomic":`true`,children:status}),(0,react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{icon:retryIcon(node,failed),title,rowClassName:MessageItem_module_css_default.retryRow,leadingClassName:MessageItem_module_css_default.retryLeading,titleClassName:MessageItem_module_css_default.retryTitle,running:retrying,open,expandable:true,expandOnRowClick:true,keepContentWhenOpen:true,onToggle:toggle,collapsedContent:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retrySeparator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryProgress,children:remaining})]}),children:[(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.retryDetails,children:[(0,react_jsx_runtime.jsxs)(`div`,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryDetailLabel,children:t(`message.retry.delay`)}),t(`duration.milliseconds`,{milliseconds:Math.round(node.delayMs)})]}),(0,react_jsx_runtime.jsxs)(`div`,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryDetailLabel,children:t(`message.retry.failure`)}),failureMessage(node.failure.message,node.failure.code,t)]})]}),inspect!==void 0&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.InspectButton,{label:t(`message.retry.inspect`),onClick:inspect})]})]})}function TurnErrorItem({node,t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorRow,role:`status`,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.StateDot,{state:`error`,className:MessageItem_module_css_default.turnErrorDot}),(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorCopy,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorTitle,children:node.code===`ACCOUNT_SIGNED_OUT`||node.code===`INTERRUPTED`?t(`message.taskStopped`):t(`message.turnError`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorMessage,children:failureMessage(node.message,node.code,t)})]}),node.code!==void 0&&node.code!==`INTERRUPTED`&&(0,react_jsx_runtime.jsx)(`code`,{className:MessageItem_module_css_default.turnErrorCode,children:node.code})]})}function TurnMaxTokensItem({t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorRow,role:`status`,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.StateDot,{state:`warning`,className:MessageItem_module_css_default.turnErrorDot}),(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorCopy,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.maxTokensTitle,children:t(`message.maxTokens`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorMessage,children:t(`message.maxTokens.hint`)})]})]})}const UNDECORATED_ROW={kind:`user`,data:{source:null}};const NO_MESSAGE_SOURCE=()=>null;function UserStyleBubble({node,renderSlotChain,content,loadImage,renderFactorySlot,actions,pending=false,echo=false,batchStart=false,referenceLabels,skillNames,previewAttachments,facts:inputFacts=EMPTY_TEXT_FACTS,interactive=false}){const parts=(0,react.useMemo)(()=>contentParts(content),[content]);const prepared=(0,react.useMemo)(()=>({text:parts.text,attachments:previewAttachments??parts.attachments,extraBlocks:parts.rest,...referenceLabels===void 0?{}:{referenceLabels}}),[parts,previewAttachments,referenceLabels]);const facts=(0,react.useMemo)(()=>({...inputFacts,...referenceLabels===void 0?{}:{sessionLabels:referenceLabels},...skillNames===void 0?{}:{skillNames}}),[inputFacts,referenceLabels,skillNames]);return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.userRow,"data-pending-steering":pending||void 0,"data-submission-echo":echo||void 0,"data-chat-steering-batch":batchStart?`start`:void 0,children:[renderSlotChain(`conversation.chat.user.before`,{source:node.data.source,kind:node.kind},{fallback:null}),renderFactorySlot(`conversation.chat.user.content`,{content:prepared,loadImage,facts,interactive}),actions?.(prepared.text)]})}function PendingSteeringBubble({content,loadImage,renderFactorySlot,t}){return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node:UNDECORATED_ROW,renderSlotChain:NO_MESSAGE_SOURCE,content,renderFactorySlot,loadImage,pending:true,actions:text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,clock:`start`,className:MessageItem_module_css_default.actions,t})})}function PendingSubmissionBubble({submission,loadImage,renderFactorySlot,t}){return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node:UNDECORATED_ROW,renderSlotChain:NO_MESSAGE_SOURCE,content:(0,react.useMemo)(()=>submission.text===``?[]:[{type:`text`,text:submission.text}],[submission.text]),previewAttachments:(0,react.useMemo)(()=>submission.attachments.map(attachment=>attachment.type===`image`?{type:`image`,image:{preview:{url:attachment.value.previewUrl,...attachment.value.name===void 0?{}:{name:attachment.value.name},...attachment.value.width===void 0?{}:{width:attachment.value.width},...attachment.value.height===void 0?{}:{height:attachment.value.height}}}}:{type:`file`,file:attachment.value}),[submission.attachments]),renderFactorySlot,loadImage,pending:submission.placement===`steering`,echo:true,actions:text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,time:submission.time,clock:`start`,className:MessageItem_module_css_default.actions,t})})}const UserMessageNodeView=(0,react.memo)(function UserMessageNodeView({node,renderFactorySlot,loadImage,renderSlotChain,t}){const data=node.data;return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node,renderSlotChain,content:data.content,interactive:true,renderFactorySlot,loadImage,batchStart:node.kind===`steering`&&node.data.batchStart===true,...data.referenceLabels===void 0?{}:{referenceLabels:data.referenceLabels},...data.skillNames===void 0?{}:{skillNames:data.skillNames},actions:text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,time:data.time,clock:`start`,className:MessageItem_module_css_default.actions,t})})});const ContextMessageNodeView=(0,react.memo)(function ContextMessageNodeView({node,t}){const data=node.data;return(0,react_jsx_runtime.jsx)(ContextInjectionRow,{content:data.content,source:data.source,producer:data.producer,form:data.form,t})});const CompactionNodeView=(0,react.memo)(function CompactionNodeView({node,openCompaction,useCompactionPreview,t}){const available=useCompactionPreview(value=>value);const data=node.data;if(data.kind===`compaction-progress`){const title=t(`message.compaction.commandTitle`);if(data.status===`running`)return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title,state:`running`,summary:t(`message.compaction.running`),body:null,t});const error=data.status===`interrupted`?t(`message.taskStopped`):data.error;return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title,state:error===void 0?`ok`:`error`,summary:error??t(`command.done`),body:error?.includes(`
14
- `)?error:null,t})}return(0,react_jsx_runtime.jsx)(CompactionItem,{node:data,openCompaction:available?openCompaction:void 0,t})});const InheritedHistoryNodeView=(0,react.memo)(function InheritedHistoryNodeView({t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.inheritedHistoryRow,role:`separator`,"aria-label":t(`message.inheritedHistory`),children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLine,"aria-hidden":true}),(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.inheritedHistoryCaption,"aria-hidden":true,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,{className:MessageItem_module_css_default.inheritedHistoryIcon}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLabel,children:t(`message.inheritedHistory`)})]}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLine,"aria-hidden":true})]})});const RetryNodeView=(0,react.memo)(function RetryNodeView({node,inspectRequest,stepRunsGrouped,t}){const{current,failed,inFlight}=node.data;const inspect=(0,react.useMemo)(()=>inspectRequest===void 0?void 0:()=>{inspectRequest(current.turn,current.step)},[inspectRequest,current.turn,current.step]);return(0,react_jsx_runtime.jsx)(ModelRetryItem,{node:current,active:current.retryState===`scheduled`,inFlight,failed,grouped:stepRunsGrouped===true,inspect,t})});const TurnErrorNodeView=(0,react.memo)(function TurnErrorNodeView({node,t}){return(0,react_jsx_runtime.jsx)(TurnErrorItem,{node:node.data,t})});const TurnMaxTokensNodeView=(0,react.memo)(function TurnMaxTokensNodeView({t}){return(0,react_jsx_runtime.jsx)(TurnMaxTokensItem,{t})});const UnknownNodeView=(0,react.memo)(function UnknownNodeView({node,t}){const data=node.data;return(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.contextRow,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownSurface`,{type:data.type}),payload:data.data,truncatedLabel:total=>t(`json.truncated`,{total})})})});const REST_PATH=`M8.844 13.742C8.967 12.328 8.45 10.4 8.45 9.65C8.45 8.94 8.88 8.43 9.6 8.43C11.285 8.43 12.106 8.281 12.685 8.104C13.71 7.791 14.585 6.768 15.055 5.945C15.137 5.803 14.99 5.641 14.829 5.671C13.829 5.86 12.828 5.376 11.827 4.978C10.659 4.514 9.491 4.707 8.935 4.876C8.805 4.915 8.658 4.819 8.636 4.686C8.468 3.643 7.405 2.615 5.498 2.238C4.54 2.048 3.748 1.574 3.347 1.202C3.252 1.113 3.088 1.125 3.03 1.242C2.628 2.059 2.168 3.82 5.248 6.115C5.82 6.494 6.31 6.785 6.574 7.637C6.72 8.104 6.157 9.168 6.061 9.368C5.157 11.27 5.089 12.19 4.926 13.742`;function RunningWhaleTail(){return(0,react_jsx_runtime.jsxs)(`span`,{className:ChatView_module_css_default.runningIcon,"aria-hidden":`true`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChatView_module_css_default.runningWhaleAnimated}),(0,react_jsx_runtime.jsx)(`svg`,{className:ChatView_module_css_default.runningWhaleStill,width:`100%`,height:`100%`,viewBox:`0 0 16 16`,fill:`none`,children:(0,react_jsx_runtime.jsx)(`path`,{d:REST_PATH,stroke:`currentColor`,strokeWidth:1})})]})}const RunningStatus=(0,react.memo)(function RunningStatus({startTime,paused,holding=false,t}){const[now,setNow]=(0,react.useState)(Date.now);(0,react.useEffect)(()=>{if(startTime===void 0||paused||holding)return;setNow(Date.now());const timer=setInterval(()=>{setNow(Date.now())},LIVE_RUN_CLOCK_INTERVAL_MS);return()=>{clearInterval(timer)}},[startTime,paused,holding]);const label=startTime===void 0?t(`chat.deepDiving`):t(`chat.deepDivingFor`,{duration:formatRunDuration(Math.max(1e3,now-startTime),t).map(part=>part.text).join(``)});return(0,react_jsx_runtime.jsxs)(`div`,{className:ChatView_module_css_default.running,"data-chat-running":true,"data-holding":holding?``:void 0,"aria-hidden":holding||void 0,children:[holding?null:(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:t(`chat.deepDiving`)}),(0,react_jsx_runtime.jsx)(`span`,{className:ChatView_module_css_default.runningDivider,"aria-hidden":`true`}),(0,react_jsx_runtime.jsxs)(`span`,{className:ChatView_module_css_default.runningContent,children:[(0,react_jsx_runtime.jsx)(RunningWhaleTail,{}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{active:!holding,className:ChatView_module_css_default.runningText,children:label})]})]})});function isLocalSubmission(item){return`requestId`in item}function isTranscriptEcho(item){return isLocalSubmission(item)&&item.placement===`transcript`}const ChatFlow=(0,react.memo)(function ChatFlow({entries,pendingInputs,lastInputTurn,deferCollapse,useSession,useChat,useChatNode,useChatNodeBottom,useChatNodeProcess,useChatGroup,usePresentation,useConnectionState,useStore,actions,renderSlot,renderFactorySlot,t,useGroupAction,useGroupHeaderAction,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage}){const nodeStore=useChat(snapshot=>snapshot.nodes);const running=useSession(snapshot=>snapshot.running);const disconnected=useConnectionState(state=>state===`disconnected`||state===`connecting`);const latestTurnAnchor=useChat(snapshot=>snapshot.navigation.items().at(-1)?.anchorKey);const runningStartTime=useChatNode(latestTurnAnchor??``,node=>{const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.status===`open`?location.turn.start?.time:void 0:void 0});const latestTurnOpen=useChatNode(latestTurnAnchor??``,node=>{const location=node?.location;return(location?.kind===`turn`||location?.kind===`step`)&&location.turn.status===`open`});const holding=!running&&latestTurnOpen;const seatProps={nodeStore,useChatNode,useChatNodeBottom,useChatNodeProcess,usePresentation,useStore,actions,renderSlot,t,useGroupAction,deferCollapse,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage};const rows=entries.map(entry=>{switch(entry.kind){case`node`:return(0,react.createElement)(ChatNodeSeat,{...seatProps,key:chatRenderKey(entry),nodeKey:entry.key,...entry.groupPart===void 0?{}:{groupPart:entry.groupPart}});case`group`:return(0,react.createElement)(ChatGroupSeat,{...seatProps,key:chatRenderKey(entry),groupKey:entry.key,useChatGroup,useGroupHeaderAction});default:return assertNever(entry)}});const firstTranscript=pendingInputs.findIndex(isTranscriptEcho);const leadingRows=[];const openingRows=[];const pendingRows=[];for(const[index,item]of pendingInputs.entries()){const row=isLocalSubmission(item)?(0,react_jsx_runtime.jsx)(PendingSubmissionBubble,{submission:item,loadImage,renderFactorySlot,t},item.requestId):(0,react_jsx_runtime.jsx)(PendingSteeringBubble,{content:item.content,loadImage,renderFactorySlot,t},item.id);if(index<=firstTranscript)leadingRows.push(row);else if(isTranscriptEcho(item))openingRows.push(row);else pendingRows.push(row)}const tail=entries.at(-1);const node=tail?.kind===`node`?nodeStore.get(tail.key):void 0;if(node?.kind===`turn-process`&&node.location.kind===`turn`&&node.location.turn.status===`open`&&node.location.turn.turn!==lastInputTurn)rows.splice(rows.length-1,0,...leadingRows.splice(0));return[...rows,...leadingRows,...openingRows,...running||holding?[(0,react_jsx_runtime.jsx)(RunningStatus,{startTime:runningStartTime,paused:disconnected,holding,t},`running`)]:[],...pendingRows]});const NS=`chat`;const zh={"message.stepProcess.thinking":`正在分析请求`,"message.stepProcess.thinkingNext":`{title},正在思考下一步`,"message.stepProcess.read":`正在读取文件`,"message.stepProcess.readImage":`正在读取图片`,"message.stepProcess.write":`正在写入文件`,"message.stepProcess.search":`正在搜索代码`,"message.stepProcess.edit":`正在编辑文件`,"message.stepProcess.commands":`正在运行命令`,"message.stepProcess.code":`正在运行代码`,"message.stepProcess.webSearch":`正在搜索网页`,"message.stepProcess.webFetch":`正在访问网页`,"message.stepProcess.subagents":`正在协调子智能体`,"message.stepProcess.plan":`正在更新计划`,"message.stepProcess.questions":`等待你的操作`,"message.stepProcess.tools":`正在调用工具`,"message.stepProcess.prepare.read":`准备读取文件`,"message.stepProcess.prepare.readImage":`准备读取图片`,"message.stepProcess.prepare.write":`准备写入文件`,"message.stepProcess.prepare.search":`准备搜索代码`,"message.stepProcess.prepare.edit":`准备编辑文件`,"message.stepProcess.prepare.commands":`准备运行命令`,"message.stepProcess.prepare.code":`准备运行代码`,"message.stepProcess.prepare.webSearch":`准备搜索网页`,"message.stepProcess.prepare.webFetch":`准备访问网页`,"message.stepProcess.prepare.subagents":`准备协调子智能体`,"message.stepProcess.prepare.plan":`准备更新计划`,"message.stepProcess.prepare.questions":`准备提问`,"message.stepProcess.prepare.tools":`准备调用工具`,"message.stepProcess.done.thinking":`已完成分析`,"message.stepProcess.done.read":`已读取文件`,"message.stepProcess.done.readImage":`已读取图片`,"message.stepProcess.done.write":`已写入文件`,"message.stepProcess.done.search":`已搜索代码`,"message.stepProcess.done.edit":`修改了文件`,"message.stepProcess.done.commands":`执行了命令`,"message.stepProcess.done.code":`运行了代码`,"message.stepProcess.done.webSearch":`已搜索网页`,"message.stepProcess.done.webFetch":`已访问网页`,"message.stepProcess.done.subagents":`已协调子智能体`,"message.stepProcess.done.plan":`更新了计划`,"message.stepProcess.done.questions":`向用户提出了问题`,"message.stepProcess.done.tools":`已调用工具`,"message.stepProcess.done.context":`已注入上下文`,"message.stepProcess.joinTwo":`{first}并{second}`,"message.stepProcess.comma":`,`,"message.stepProcess.sharedPrefix":`已`,"message.stepProcess.more":`{title}等`,"message.trigger.request":`收到执行请求`,"message.trigger.goal":`继续执行目标`,"message.trigger.agent":`收到任务消息`,"message.trigger.team":`收到团队消息`,"message.trigger.subagent":`子任务状态更新`,"message.trigger.subagent.completed":`子智能体已完成任务`,"message.trigger.subagent.aborted":`子智能体任务已停止`,"message.trigger.subagent.error":`子智能体执行失败`,"message.trigger.subagent.maxTokens":`子智能体已达 token 上限`,"message.trigger.subagent.refusal":`子智能体拒绝执行`,"message.trigger.subagent.unknown":`子智能体异常结束`,"message.trigger.github":`收到 GitHub 事件`,"message.trigger.webhook":`收到外部事件`,"message.trigger.schedule":`自动化任务`,"message.trigger.job":`后台任务状态更新`,"message.trigger.plugin":`插件状态更新`,"message.trigger.explanation":`这条通知触发了本轮回复。`,"message.turnProcess.worked":`已完成`,"message.turnProcess.took":`已完成,用时 `,"message.turnProcess.failed":`处理失败`,"view.chat":`对话`,"image.open":`查看大图`,"image.loading":`加载图片…`,"image.failed":`图片无法预览`,"image.dialog":`图片预览`,"image.close":`关闭图片预览`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}秒`,"duration.compactMinutes":`{minutes}分{seconds}秒`,"duration.milliseconds":`{milliseconds}毫秒`,"stats.counts":`{turns} 轮 {steps} 步`,"stats.cacheHit":`缓存命中 {percent}%`,"stats.dialog.title":`会话统计`,"stats.dialog.usageTitle":`Token 用量`,"stats.dialog.llmTime":`模型用时`,"stats.dialog.toolTime":`工具调用用时`,"stats.dialog.ttft":`首 token 平均(TTFT)`,"stats.dialog.speed":`输出速度(TPS)`,"chat.loadingHistory":`载入历史…`,"chat.loadError":`历史加载失败:{message}({code})`,"chat.loadOlder":`加载更早`,"chat.loadingOlder":`正在加载`,"chat.processingOlder":`正在处理`,"chat.retryOlder":`重新加载`,"chat.historyStart":`已到会话开头`,"chat.toBottom":`回到底部`,"chat.deepDiving":`深度求索中`,"chat.deepDivingFor":`深度求索中,用时 {duration} ···`,"chat.turnNavigation.label":`轮次导航`,"chat.turnNavigation.jump":`跳转到第 {turn} 轮`,"chat.turnNavigation.jumpLoad":`加载并跳转到第 {turn} 轮`,"chat.turnNavigation.turn":`第 {turn} 轮`,"settings.performance.title":`性能与用量`,"settings.performance.description":`选择性能与用量信息展示的详细程度`,"settings.performance.compact":`简洁`,"settings.performance.detailed":`详细`,"settings.links.title":`网页链接默认打开方式`,"settings.links.description":`对话中网页链接的打开位置`,"settings.links.sidebar":`应用内侧边栏`,"settings.links.newTab":`默认浏览器`,"settings.transcript.title":`工作步骤展示`,"settings.transcript.description":`选择希望看到多少工具调用细节`,"settings.collapse.title":`工作步骤收起时机`,"settings.collapse.description":`选择何时自动收起工作步骤`,"settings.collapse.completion":`回答结束后`,"settings.collapse.nextInput":`下次有新消息时`,"settings.foldedReplies.title":`收起后显示的回复`,"settings.foldedReplies.description":`工作步骤收起后,保留哪些助手回复`,"settings.foldedReplies.all":`全部回复`,"settings.foldedReplies.final":`仅最终回答`,"settings.transcript.compact":`简洁`,"settings.transcript.standard":`标准`,"settings.transcript.detailed":`详细`,"settings.transcript.verbose":`完全展开`,"fileOpen.title":`无法打开文件`,"fileOpen.unknown":`无法打开此文件`,"message.extraBlock":`附加内容块`,"message.systemPrompt":`系统提示词`,"message.systemPromptUpdate":`系统提示词更新`,"message.systemSection.added":`新增 {name}`,"message.systemSection.updated":`更新 {name}`,"message.systemSection.cleared":`清空 {name}`,"message.systemSection.reordered":`调整顺序 {name}`,"message.systemSection.removed":`移除 {name}`,"message.systemSection.unchanged":`未变化 {name}`,"message.systemPromptReset":`取代此前的全部指令`,"message.systemPromptSections":`{count} 个章节`,"message.toolAdded":`已添加工具:{name}`,"message.toolRemoved":`已移除工具:{name}`,"message.toolsAdded":`新增:{names}`,"message.toolsAddedCount":`新增 {count} 个`,"message.toolsChanged":`新增 {added} 个,移除 {removed} 个`,"message.toolsRemoved":`移除:{names}`,"message.toolsRemovedCount":`移除 {count} 个`,"message.toolsUpdated":`工具已更新`,"message.contextInjection":`上下文注入`,"message.contextRecall":`跨会话召回`,"message.referenceSummary":`引用会话 · {labels}`,"message.referenceSeparator":`、`,"message.context.instructions.loaded":`已载入`,"message.context.instructions.added":`已新增`,"message.context.instructions.updated":`已更新`,"message.context.instructions.removed":`已移除`,"message.context.catalog.replaced":`替换目录`,"message.context.catalog.more":`…还有 {count} 条`,"message.context.snapshot.supersedes":`取代先前的快照`,"message.context.relay.from":`来自会话 {session}`,"message.context.recall.counts":`保留 {retained} 条 · 省略 {omitted} 条`,"message.context.recall.truncated":`已截断`,"message.compaction":`上下文已压缩`,"message.inheritedHistory":`以上为继承的历史消息`,"message.compaction.running":`正在压缩…`,"message.compaction.completed":`已压缩 {items} 条历史记录(约 {tokens} tokens)`,"message.compaction.open":`在侧栏查看压缩摘要`,"message.compaction.notFound":`摘要不可用:预览服务不可用,或摘要记录缺失、为空或无效。`,"message.compaction.readFailed":`无法读取摘要`,"message.compaction.landed":`较早的历史已压缩为摘要`,"message.compaction.commandTitle":`compact`,"message.think":`思考`,"message.unknownSurface":`未知 surface 事件:{type}`,"message.unknownBlock":`未知内容块`,"message.turnProcess.toolCalls.one":`{count} 次工具调用`,"message.turnProcess.toolCalls.other":`{count} 次工具调用`,"message.turnProcess.messages.one":`{count} 条消息`,"message.turnProcess.messages.other":`{count} 条消息`,"message.turnProcess.subagents.one":`{count} 个 subagent`,"message.turnProcess.subagents.other":`{count} 个 subagent`,"message.turnProcess.thoughtForAWhile":`已思考`,"message.turnProcess.separator":` · `,"message.stopped":`已停止`,"message.branch":`在新对话中分支`,"message.branchUnavailable":`仅可从已完成轮次的最后一条消息分支`,"message.retry.active":`正在重试模型请求`,"message.retry.cancelled":`模型请求重试已取消`,"message.retry.started":`已重试模型请求`,"message.continuation.requested":`已请求继续生成`,"message.retry.scheduled":`等待重试模型请求`,"message.retry.status":`{label}({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label}({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`重试延迟:`,"message.retry.failure":`失败原因:`,"message.retry.inspect":`查看`,"message.failure.auth":`API 密钥无效`,"message.taskStopped":`任务已停止`,"message.failure.accountSignedOut":`任务已因退出 DeepSeek 登录而停止。`,"message.failure.interrupted":`DSH 进程在本轮完成前退出(例如被强制结束、崩溃或关闭超时),重新启动后本轮已中止。未完成的工具调用结果未知。`,"message.failure.accountSignInRequired":`请先登录 DeepSeek,并确认请求地址支持账号认证。`,"message.failure.quota":`当前请求的额度已用尽`,"message.turnError":`本轮运行失败`,"message.maxTokens":`已达到输出 token 上限`,"message.maxTokens.hint":`回答被截断,已有输出保留在对话中。发送“继续”可让模型接着输出。`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`本轮用量`,"message.turnUsage.consumed":`用量 {total}`,"message.turnUsage.model":`提供方 / 模型`,"message.turnUsage.cacheHit":`缓存命中`,"message.turnUsage.input":`未缓存输入`,"message.turnUsage.cacheRead":`缓存读取`,"message.turnUsage.cacheWrite":`缓存写入`,"message.turnUsage.output":`输出`,"message.turnUsage.reasoning":`(其中推理 {tokens})`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`秒`,"duration.minuteUnit":`分`,"duration.hourUnit":`小时`,"command.running":`执行中…`,"command.failed":`指令失败`,"command.done":`已完成`,"command.title":`指令`,"row.running":`运行中`,"row.failed":`失败`,"json.truncated":`… 已截断,共 {total} 字符`,"clock.md":`{m}月{d}日`,"clock.ymd":`{y}年{m}月{d}日`};const en={"message.stepProcess.thinking":`Analyzing the request`,"message.stepProcess.thinkingNext":`{title}, thinking about the next step`,"message.stepProcess.read":`Reading files`,"message.stepProcess.readImage":`Reading images`,"message.stepProcess.write":`Writing files`,"message.stepProcess.search":`Searching code`,"message.stepProcess.edit":`Editing files`,"message.stepProcess.commands":`Running commands`,"message.stepProcess.code":`Running code`,"message.stepProcess.webSearch":`Searching the web`,"message.stepProcess.webFetch":`Visiting web pages`,"message.stepProcess.subagents":`Coordinating subagents`,"message.stepProcess.plan":`Updating the plan`,"message.stepProcess.questions":`Waiting for your action`,"message.stepProcess.tools":`Calling tools`,"message.stepProcess.prepare.read":`Preparing to read files`,"message.stepProcess.prepare.readImage":`Preparing to read images`,"message.stepProcess.prepare.write":`Preparing to write files`,"message.stepProcess.prepare.search":`Preparing to search code`,"message.stepProcess.prepare.edit":`Preparing to edit files`,"message.stepProcess.prepare.commands":`Preparing to run commands`,"message.stepProcess.prepare.code":`Preparing to run code`,"message.stepProcess.prepare.webSearch":`Preparing to search the web`,"message.stepProcess.prepare.webFetch":`Preparing to visit web pages`,"message.stepProcess.prepare.subagents":`Preparing to coordinate subagents`,"message.stepProcess.prepare.plan":`Preparing to update the plan`,"message.stepProcess.prepare.questions":`Preparing questions`,"message.stepProcess.prepare.tools":`Preparing tool calls`,"message.stepProcess.done.thinking":`Analysis completed`,"message.stepProcess.done.read":`Read files`,"message.stepProcess.done.readImage":`Read images`,"message.stepProcess.done.write":`Wrote files`,"message.stepProcess.done.search":`Searched code`,"message.stepProcess.done.edit":`Edited files`,"message.stepProcess.done.commands":`Ran commands`,"message.stepProcess.done.code":`Ran code`,"message.stepProcess.done.webSearch":`Searched the web`,"message.stepProcess.done.webFetch":`Visited web pages`,"message.stepProcess.done.subagents":`Coordinated subagents`,"message.stepProcess.done.plan":`Updated the plan`,"message.stepProcess.done.questions":`Asked questions`,"message.stepProcess.done.tools":`Called tools`,"message.stepProcess.done.context":`Injected context`,"message.stepProcess.joinTwo":`{first} and {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Execution requested`,"message.trigger.goal":`Continuing goal`,"message.trigger.agent":`Task message received`,"message.trigger.team":`Team message received`,"message.trigger.subagent":`Subtask status updated`,"message.trigger.subagent.completed":`Subagent run completed`,"message.trigger.subagent.aborted":`Subagent run stopped`,"message.trigger.subagent.error":`Subagent run failed`,"message.trigger.subagent.maxTokens":`Subagent reached the token limit`,"message.trigger.subagent.refusal":`Subagent declined the task`,"message.trigger.subagent.unknown":`Subagent run ended unexpectedly`,"message.trigger.github":`GitHub event received`,"message.trigger.webhook":`External event received`,"message.trigger.schedule":`Automation task`,"message.trigger.job":`Background task updated`,"message.trigger.plugin":`Plugin status updated`,"message.trigger.explanation":`This notification triggered this response.`,"message.turnProcess.worked":`Completed`,"message.turnProcess.took":`Completed in `,"message.turnProcess.failed":`Failed`,"view.chat":`Chat`,"image.open":`View full image`,"image.loading":`Loading image…`,"image.failed":`Image preview unavailable`,"image.dialog":`Image preview`,"image.close":`Close image preview`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turns {steps} steps`,"stats.cacheHit":`Cache hit {percent}%`,"stats.dialog.title":`Session statistics`,"stats.dialog.usageTitle":`Token usage`,"stats.dialog.llmTime":`LLM time`,"stats.dialog.toolTime":`Tool time`,"stats.dialog.ttft":`Avg time to first token (TTFT)`,"stats.dialog.speed":`Tokens per second (TPS)`,"chat.loadingHistory":`Loading history…`,"chat.loadError":`Failed to load history: {message} ({code})`,"chat.loadOlder":`Load earlier`,"chat.loadingOlder":`Loading earlier`,"chat.processingOlder":`Processing`,"chat.retryOlder":`Retry loading`,"chat.historyStart":`Start of conversation`,"chat.toBottom":`Back to bottom`,"chat.deepDiving":`Deep diving`,"chat.deepDivingFor":`Deep diving for {duration} ···`,"chat.turnNavigation.label":`Turn navigation`,"chat.turnNavigation.jump":`Jump to turn {turn}`,"chat.turnNavigation.jumpLoad":`Load and jump to turn {turn}`,"chat.turnNavigation.turn":`Turn {turn}`,"settings.performance.title":`Performance & usage`,"settings.performance.description":`Choose how much performance and usage information to show`,"settings.performance.compact":`Compact`,"settings.performance.detailed":`Detailed`,"settings.links.title":`Open chat links in`,"settings.links.description":`Choose where to open web links`,"settings.links.sidebar":`In-App Sidebar`,"settings.links.newTab":`Default Browser`,"settings.transcript.title":`Work details`,"settings.transcript.description":`Choose how much detail to show for tool calls`,"settings.collapse.title":`When to Collapse Work Details`,"settings.collapse.description":`Choose when to automatically collapse work details`,"settings.collapse.completion":`On completion`,"settings.collapse.nextInput":`On next message`,"settings.foldedReplies.title":`Replies After Collapse`,"settings.foldedReplies.description":`Choose which assistant replies stay visible when work details collapse`,"settings.foldedReplies.all":`All replies`,"settings.foldedReplies.final":`Final answer only`,"settings.transcript.compact":`Compact`,"settings.transcript.standard":`Standard`,"settings.transcript.detailed":`Detailed`,"settings.transcript.verbose":`Verbose`,"fileOpen.title":`Couldn’t open file`,"fileOpen.unknown":`Couldn’t open this file`,"message.extraBlock":`Extra content block`,"message.systemPrompt":`System prompt`,"message.systemPromptUpdate":`System prompt update`,"message.systemSection.added":`Added {name}`,"message.systemSection.updated":`Updated {name}`,"message.systemSection.cleared":`Cleared {name}`,"message.systemSection.reordered":`Reordered {name}`,"message.systemSection.removed":`Removed {name}`,"message.systemSection.unchanged":`Unchanged {name}`,"message.systemPromptReset":`Replaces all earlier instructions`,"message.systemPromptSections":`{count} sections`,"message.toolAdded":`Tool added: {name}`,"message.toolRemoved":`Tool removed: {name}`,"message.toolsAdded":`Added: {names}`,"message.toolsAddedCount":`{count} added`,"message.toolsChanged":`{added} added, {removed} removed`,"message.toolsRemoved":`Removed: {names}`,"message.toolsRemovedCount":`{count} removed`,"message.toolsUpdated":`Tools updated`,"message.contextInjection":`Context injection`,"message.contextRecall":`Session recall`,"message.referenceSummary":`Referenced session · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`loaded`,"message.context.instructions.added":`added`,"message.context.instructions.updated":`updated`,"message.context.instructions.removed":`removed`,"message.context.catalog.replaced":`Replacement catalog`,"message.context.catalog.more":`… {count} more`,"message.context.snapshot.supersedes":`Supersedes earlier snapshots`,"message.context.relay.from":`From session {session}`,"message.context.recall.counts":`{retained} kept · {omitted} omitted`,"message.context.recall.truncated":`truncated`,"message.compaction":`Context compacted`,"message.inheritedHistory":`Inherited history above`,"message.compaction.running":`Compacting context…`,"message.compaction.completed":`Compacted {items} history items (~{tokens} tokens)`,"message.compaction.open":`View compaction summary in the sidebar`,"message.compaction.notFound":`Summary unavailable: the preview service is unavailable, or the summary record is missing, empty or invalid.`,"message.compaction.readFailed":`Unable to read the summary`,"message.compaction.landed":`Earlier history condensed into a summary`,"message.compaction.commandTitle":`compact`,"message.think":`Think`,"message.unknownSurface":`Unknown surface event: {type}`,"message.unknownBlock":`Unknown content block`,"message.turnProcess.toolCalls.one":`{count} tool call`,"message.turnProcess.toolCalls.other":`{count} tool calls`,"message.turnProcess.messages.one":`{count} message`,"message.turnProcess.messages.other":`{count} messages`,"message.turnProcess.subagents.one":`{count} subagent`,"message.turnProcess.subagents.other":`{count} subagents`,"message.turnProcess.thoughtForAWhile":`Thought for a while`,"message.turnProcess.separator":` · `,"message.stopped":`Stopped`,"message.branch":`Branch into a new conversation`,"message.branchUnavailable":`Available only on the last message of a completed turn`,"message.retry.active":`Retrying model request`,"message.retry.cancelled":`Model request retry cancelled`,"message.retry.started":`Retried model request`,"message.continuation.requested":`Requested to continue generation`,"message.retry.scheduled":`Waiting to retry model request`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Retry delay: `,"message.retry.failure":`Failure reason: `,"message.retry.inspect":`Inspect`,"message.failure.auth":`API key is invalid`,"message.taskStopped":`Task stopped`,"message.failure.accountSignedOut":`Stopped because you signed out of DeepSeek.`,"message.failure.interrupted":`The DSH process exited before this turn finished (for example, it was killed, crashed, or timed out while shutting down), so the turn was closed when DSH restarted. Unfinished tool calls have unknown outcomes.`,"message.failure.accountSignInRequired":`Sign in to DeepSeek and ensure the request destination supports account authentication.`,"message.failure.quota":`Request quota exhausted.`,"message.turnError":`This turn failed`,"message.maxTokens":`Output token limit reached`,"message.maxTokens.hint":`The reply was cut off; earlier output is preserved in the conversation. Send "continue" to let the model resume.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Turn usage`,"message.turnUsage.consumed":`Usage {total}`,"message.turnUsage.model":`Provider / model`,"message.turnUsage.cacheHit":`Cache hit`,"message.turnUsage.input":`Uncached input`,"message.turnUsage.cacheRead":`Cached input`,"message.turnUsage.cacheWrite":`Cache write`,"message.turnUsage.output":`Output`,"message.turnUsage.reasoning":` ({tokens} reasoning)`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Running…`,"command.failed":`Command failed`,"command.done":`Completed`,"command.title":`Command`,"row.running":`Running`,"row.failed":`Failed`,"json.truncated":`… truncated, {total} characters total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const ja={"message.stepProcess.thinking":`リクエストを分析中`,"message.stepProcess.thinkingNext":`{title}、次のステップを検討中`,"message.stepProcess.read":`ファイルを読み取り中`,"message.stepProcess.readImage":`画像を読み取り中`,"message.stepProcess.write":`ファイルを書き込み中`,"message.stepProcess.search":`コードを検索中`,"message.stepProcess.edit":`ファイルを編集中`,"message.stepProcess.commands":`コマンドを実行中`,"message.stepProcess.code":`コードを実行中`,"message.stepProcess.webSearch":`ウェブを検索中`,"message.stepProcess.webFetch":`ウェブページを閲覧中`,"message.stepProcess.subagents":`サブエージェントを調整中`,"message.stepProcess.plan":`計画を更新中`,"message.stepProcess.questions":`操作を待機中`,"message.stepProcess.tools":`ツールを呼び出し中`,"message.stepProcess.prepare.read":`ファイル読み取りの準備中`,"message.stepProcess.prepare.readImage":`画像読み取りの準備中`,"message.stepProcess.prepare.write":`ファイル書き込みの準備中`,"message.stepProcess.prepare.search":`コード検索の準備中`,"message.stepProcess.prepare.edit":`ファイル編集の準備中`,"message.stepProcess.prepare.commands":`コマンド実行の準備中`,"message.stepProcess.prepare.code":`コード実行の準備中`,"message.stepProcess.prepare.webSearch":`ウェブ検索の準備中`,"message.stepProcess.prepare.webFetch":`ウェブページ閲覧の準備中`,"message.stepProcess.prepare.subagents":`サブエージェント調整の準備中`,"message.stepProcess.prepare.plan":`計画更新の準備中`,"message.stepProcess.prepare.questions":`質問の準備中`,"message.stepProcess.prepare.tools":`ツール呼び出しの準備中`,"message.stepProcess.done.thinking":`分析完了`,"message.stepProcess.done.read":`ファイルを読み取りました`,"message.stepProcess.done.readImage":`画像を読み取りました`,"message.stepProcess.done.write":`ファイルを書き込みました`,"message.stepProcess.done.search":`コードを検索しました`,"message.stepProcess.done.edit":`ファイルを編集しました`,"message.stepProcess.done.commands":`コマンドを実行しました`,"message.stepProcess.done.code":`コードを実行しました`,"message.stepProcess.done.webSearch":`ウェブを検索しました`,"message.stepProcess.done.webFetch":`ウェブページを閲覧しました`,"message.stepProcess.done.subagents":`サブエージェントを調整しました`,"message.stepProcess.done.plan":`計画を更新しました`,"message.stepProcess.done.questions":`質問しました`,"message.stepProcess.done.tools":`ツールを呼び出しました`,"message.stepProcess.done.context":`コンテキストを注入しました`,"message.stepProcess.joinTwo":`{first}と{second}`,"message.stepProcess.comma":`、`,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}など`,"message.trigger.request":`実行が要求されました`,"message.trigger.goal":`目標を継続中`,"message.trigger.agent":`タスクメッセージを受信しました`,"message.trigger.team":`チームメッセージを受信しました`,"message.trigger.subagent":`サブタスクの状態が更新されました`,"message.trigger.subagent.completed":`サブエージェントの実行が完了しました`,"message.trigger.subagent.aborted":`サブエージェントの実行が停止しました`,"message.trigger.subagent.error":`サブエージェントの実行が失敗しました`,"message.trigger.subagent.maxTokens":`サブエージェントがトークンの上限に達しました`,"message.trigger.subagent.refusal":`サブエージェントがタスクを拒否しました`,"message.trigger.subagent.unknown":`サブエージェントの実行が予期せず終了しました`,"message.trigger.github":`GitHubイベントを受信しました`,"message.trigger.webhook":`外部イベントを受信しました`,"message.trigger.schedule":`自動化タスク`,"message.trigger.job":`バックグラウンドタスクが更新されました`,"message.trigger.plugin":`プラグインの状態が更新されました`,"message.trigger.explanation":`この通知がこの応答のトリガーとなりました。`,"message.turnProcess.worked":`完了`,"message.turnProcess.took":`完了まで `,"message.turnProcess.failed":`失敗`,"view.chat":`チャット`,"image.open":`画像を全画面表示`,"image.loading":`画像を読み込み中…`,"image.failed":`画像プレビューを利用できません`,"image.dialog":`画像プレビュー`,"image.close":`画像プレビューを閉じる`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}秒`,"duration.compactMinutes":`{minutes}分{seconds}秒`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns}ターン {steps}ステップ`,"stats.cacheHit":`キャッシュヒット {percent}%`,"stats.dialog.title":`セッション統計`,"stats.dialog.usageTitle":`トークン使用量`,"stats.dialog.llmTime":`LLM時間`,"stats.dialog.toolTime":`ツール時間`,"stats.dialog.ttft":`平均初回トークン時間(TTFT)`,"stats.dialog.speed":`毎秒トークン数(TPS)`,"chat.loadingHistory":`履歴を読み込み中…`,"chat.loadError":`履歴の読み込みに失敗しました: {message}({code})`,"chat.loadOlder":`以前を読み込む`,"chat.loadingOlder":`読み込み中`,"chat.processingOlder":`処理中`,"chat.retryOlder":`再読み込み`,"chat.historyStart":`会話の先頭です`,"chat.toBottom":`最下部へ戻る`,"chat.deepDiving":`深掘り中`,"chat.deepDivingFor":`{duration} の間深く分析中 ···`,"chat.turnNavigation.label":`ターン移動`,"chat.turnNavigation.jump":`ターン {turn} へ移動`,"chat.turnNavigation.jumpLoad":`読み込んでターン {turn} へ移動`,"chat.turnNavigation.turn":`ターン {turn}`,"settings.performance.title":`パフォーマンスと使用状況`,"settings.performance.description":`パフォーマンスと使用状況の表示量を選択`,"settings.performance.compact":`コンパクト`,"settings.performance.detailed":`詳細`,"settings.links.title":`チャットリンクを開く場所`,"settings.links.description":`Web リンクを開く場所を選択`,"settings.links.sidebar":`アプリ内サイドバー`,"settings.links.newTab":`既定のブラウザー`,"settings.transcript.title":`作業の詳細`,"settings.transcript.description":`ツール呼び出しの表示詳細度を選択`,"settings.collapse.title":`作業詳細を折りたたむタイミング`,"settings.collapse.description":`作業詳細を自動で折りたたむタイミングを選択`,"settings.collapse.completion":`完了時`,"settings.collapse.nextInput":`次のメッセージ送信時`,"settings.foldedReplies.title":`折りたたみ後の返信`,"settings.foldedReplies.description":`作業詳細の折りたたみ時に表示するアシスタントの返信を選択`,"settings.foldedReplies.all":`すべての返信`,"settings.foldedReplies.final":`最終回答のみ`,"settings.transcript.compact":`コンパクト`,"settings.transcript.standard":`標準`,"settings.transcript.detailed":`詳細`,"settings.transcript.verbose":`冗長`,"fileOpen.title":`ファイルを開けませんでした`,"fileOpen.unknown":`このファイルを開けませんでした`,"message.extraBlock":`追加のコンテンツブロック`,"message.systemPrompt":`システムプロンプト`,"message.systemPromptUpdate":`システムプロンプトの更新`,"message.systemSection.added":`追加 {name}`,"message.systemSection.updated":`更新 {name}`,"message.systemSection.cleared":`クリア {name}`,"message.systemSection.reordered":`並べ替え {name}`,"message.systemSection.removed":`削除 {name}`,"message.systemSection.unchanged":`変更なし {name}`,"message.systemPromptReset":`以前の指示をすべて置き換えます`,"message.systemPromptSections":`{count} セクション`,"message.toolAdded":`ツールを追加: {name}`,"message.toolRemoved":`ツールを削除: {name}`,"message.toolsAdded":`追加: {names}`,"message.toolsAddedCount":`{count} 件追加`,"message.toolsChanged":`{added} 件追加、{removed} 件削除`,"message.toolsRemoved":`削除: {names}`,"message.toolsRemovedCount":`{count} 件削除`,"message.toolsUpdated":`ツールを更新しました`,"message.contextInjection":`コンテキスト注入`,"message.contextRecall":`セッションの呼び出し`,"message.referenceSummary":`参照セッション · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`読み込み済み`,"message.context.instructions.added":`追加済み`,"message.context.instructions.updated":`更新済み`,"message.context.instructions.removed":`削除済み`,"message.context.catalog.replaced":`置換カタログ`,"message.context.catalog.more":`… 他 {count} 件`,"message.context.snapshot.supersedes":`以前のスナップショットを置き換えます`,"message.context.relay.from":`セッション {session} から`,"message.context.recall.counts":`{retained} 件保持 · {omitted} 件除外`,"message.context.recall.truncated":`切り詰め済み`,"message.compaction":`コンテキストを圧縮しました`,"message.inheritedHistory":`ここまでは引き継いだ履歴です`,"message.compaction.running":`コンテキストを圧縮中…`,"message.compaction.completed":`履歴 {items} 件を圧縮しました(約 {tokens} トークン)`,"message.compaction.open":`圧縮の要約をサイドバーで表示`,"message.compaction.notFound":`要約を利用できません。プレビューサービスが利用できないか、要約が存在しない、空、または無効です。`,"message.compaction.readFailed":`要約を読み込めません`,"message.compaction.landed":`以前の履歴を要約に圧縮しました`,"message.compaction.commandTitle":`compact`,"message.think":`思考`,"message.unknownSurface":`不明なサーフェスイベント: {type}`,"message.unknownBlock":`不明なコンテンツブロック`,"message.turnProcess.toolCalls.one":`ツール呼び出し {count} 件`,"message.turnProcess.toolCalls.other":`ツール呼び出し {count} 件`,"message.turnProcess.messages.one":`メッセージ {count} 件`,"message.turnProcess.messages.other":`メッセージ {count} 件`,"message.turnProcess.subagents.one":`サブエージェント {count} 件`,"message.turnProcess.subagents.other":`サブエージェント {count} 件`,"message.turnProcess.thoughtForAWhile":`しばらく思考しました`,"message.turnProcess.separator":` · `,"message.stopped":`停止しました`,"message.branch":`新しい会話に分岐`,"message.branchUnavailable":`完了したターンの最後のメッセージでのみ利用できます`,"message.retry.active":`モデルリクエストを再試行中`,"message.retry.cancelled":`モデルリクエストの再試行をキャンセルしました`,"message.retry.started":`モデルリクエストを再試行しました`,"message.continuation.requested":`生成の続行をリクエストしました`,"message.retry.scheduled":`モデルリクエストの再試行待ちです`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}秒`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}秒`,"message.retry.delay":`再試行までの待機時間: `,"message.retry.failure":`失敗理由: `,"message.retry.inspect":`検査`,"message.failure.auth":`APIキーが無効です`,"message.taskStopped":`タスクを停止しました`,"message.failure.accountSignedOut":`DeepSeekからログアウトしたため停止しました。`,"message.failure.interrupted":`このターンが完了する前にDSHプロセスが終了したため(強制終了、クラッシュ、シャットダウン中のタイムアウトなど)、DSHの再起動時にターンは閉じられました。未完了のツール呼び出しの結果は不明です。`,"message.failure.accountSignInRequired":`DeepSeekにログインし、リクエスト先がアカウント認証に対応していることを確認してください。`,"message.failure.quota":`リクエストのクォータを使い切りました。`,"message.turnError":`このターンは失敗しました`,"message.maxTokens":`出力トークンの上限に達しました`,"message.maxTokens.hint":`応答が途中で打ち切られました。それまでの出力は会話に保持されています。「続けて」と送信するとモデルが再開します。`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`ターンの使用量`,"message.turnUsage.consumed":`使用量 {total}`,"message.turnUsage.model":`プロバイダー / モデル`,"message.turnUsage.cacheHit":`キャッシュヒット`,"message.turnUsage.input":`未キャッシュの入力`,"message.turnUsage.cacheRead":`キャッシュ済み入力`,"message.turnUsage.cacheWrite":`キャッシュ書き込み`,"message.turnUsage.output":`出力`,"message.turnUsage.reasoning":` (推論 {tokens})`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`秒`,"duration.minuteUnit":`分 `,"duration.hourUnit":`時間 `,"command.running":`実行中…`,"command.failed":`コマンドが失敗しました`,"command.done":`完了`,"command.title":`コマンド`,"row.running":`実行中`,"row.failed":`失敗`,"json.truncated":`… 省略表示、全{total}文字`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const es={"message.stepProcess.thinking":`Analizando la solicitud`,"message.stepProcess.thinkingNext":`{title}, pensando en el siguiente paso`,"message.stepProcess.read":`Leyendo archivos`,"message.stepProcess.readImage":`Leyendo imágenes`,"message.stepProcess.write":`Escribir archivos`,"message.stepProcess.search":`código de búsqueda`,"message.stepProcess.edit":`Editar archivos`,"message.stepProcess.commands":`Ejecutar comandos`,"message.stepProcess.code":`Código en ejecución`,"message.stepProcess.webSearch":`buscando en la web`,"message.stepProcess.webFetch":`Visitar páginas web`,"message.stepProcess.subagents":`Subagentes coordinadores`,"message.stepProcess.plan":`Actualizando el plan`,"message.stepProcess.questions":`Esperando tu acción`,"message.stepProcess.tools":`herramientas de llamada`,"message.stepProcess.prepare.read":`Preparándose para leer archivos`,"message.stepProcess.prepare.readImage":`Preparándose para leer imágenes`,"message.stepProcess.prepare.write":`Preparándose para escribir archivos`,"message.stepProcess.prepare.search":`Preparándose para buscar el código`,"message.stepProcess.prepare.edit":`Preparándose para editar archivos`,"message.stepProcess.prepare.commands":`Preparándose para ejecutar comandos`,"message.stepProcess.prepare.code":`Preparándose para ejecutar código`,"message.stepProcess.prepare.webSearch":`Preparándose para buscar en la web`,"message.stepProcess.prepare.webFetch":`Preparándose para visitar páginas web`,"message.stepProcess.prepare.subagents":`Preparándose para coordinar subagentes`,"message.stepProcess.prepare.plan":`Preparándose para actualizar el plan`,"message.stepProcess.prepare.questions":`Preparando preguntas`,"message.stepProcess.prepare.tools":`Preparando llamadas a herramientas`,"message.stepProcess.done.thinking":`Análisis completado`,"message.stepProcess.done.read":`leer archivos`,"message.stepProcess.done.readImage":`Leer imágenes`,"message.stepProcess.done.write":`Escribió archivos`,"message.stepProcess.done.search":`código buscado`,"message.stepProcess.done.edit":`Archivos editados`,"message.stepProcess.done.commands":`Comandos ejecutados`,"message.stepProcess.done.code":`código ejecutado`,"message.stepProcess.done.webSearch":`Busqué en la web`,"message.stepProcess.done.webFetch":`Paginas web visitadas`,"message.stepProcess.done.subagents":`Subagentes coordinados`,"message.stepProcess.done.plan":`Actualizado el plan`,"message.stepProcess.done.questions":`preguntas hechas`,"message.stepProcess.done.tools":`herramientas llamadas`,"message.stepProcess.done.context":`Contexto inyectado`,"message.stepProcess.joinTwo":`{first} y {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Ejecución solicitada`,"message.trigger.goal":`Objetivo continuo`,"message.trigger.agent":`Mensaje de tarea recibido`,"message.trigger.team":`Mensaje del equipo recibido`,"message.trigger.subagent":`Estado de subtarea actualizado`,"message.trigger.subagent.completed":`Ejecución del subagente completada`,"message.trigger.subagent.aborted":`Ejecución del subagente detenida`,"message.trigger.subagent.error":`La ejecución del subagente falló`,"message.trigger.subagent.maxTokens":`El subagente alcanzó el límite de tokens`,"message.trigger.subagent.refusal":`El subagente rechazó la tarea`,"message.trigger.subagent.unknown":`La ejecución del subagente terminó de forma inesperada`,"message.trigger.github":`Evento GitHub recibido`,"message.trigger.webhook":`Evento externo recibido`,"message.trigger.schedule":`Tarea de automatización`,"message.trigger.job":`Tarea en segundo plano actualizada`,"message.trigger.plugin":`Estado del complemento actualizado`,"message.trigger.explanation":`Esta notificación desencadenó esta respuesta.`,"message.turnProcess.worked":`Completado`,"message.turnProcess.took":`Completado en `,"message.turnProcess.failed":`Fallido`,"view.chat":`Chat`,"image.open":`Ver imagen completa`,"image.loading":`Cargando imagen…`,"image.failed":`Vista previa de la imagen no disponible`,"image.dialog":`Vista previa de la imagen`,"image.close":`Cerrar vista previa de la imagen`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turnos, {steps} pasos`,"stats.cacheHit":`Aciertos de caché: {percent}%`,"stats.dialog.title":`Estadísticas de sesión`,"stats.dialog.usageTitle":`Uso de tokens`,"stats.dialog.llmTime":`tiempo de maestría`,"stats.dialog.toolTime":`tiempo de herramienta`,"stats.dialog.ttft":`Tiempo promedio hasta el primer token (TTFT)`,"stats.dialog.speed":`Fichas por segundo (TPS)`,"chat.loadingHistory":`Cargando historial…`,"chat.loadError":`No se pudo cargar el historial: {message} ({code})`,"chat.loadOlder":`Cargar antes`,"chat.loadingOlder":`Cargando anteriores`,"chat.processingOlder":`Procesando`,"chat.retryOlder":`Reintentar carga`,"chat.historyStart":`Inicio de la conversación`,"chat.toBottom":`Volver al fondo`,"chat.deepDiving":`Razonamiento profundo`,"chat.deepDivingFor":`Razonando a fondo durante {duration} ···`,"chat.turnNavigation.label":`Navegación por turnos`,"chat.turnNavigation.jump":`Ir al turno {turn}`,"chat.turnNavigation.jumpLoad":`Cargar e ir al turno {turn}`,"chat.turnNavigation.turn":`Turno {turn}`,"settings.performance.title":`Rendimiento y uso`,"settings.performance.description":`Elija cuánta información de rendimiento y uso desea mostrar`,"settings.performance.compact":`Compacto`,"settings.performance.detailed":`Detallado`,"settings.links.title":`Abrir enlaces de chat en`,"settings.links.description":`Elija dónde abrir enlaces web`,"settings.links.sidebar":`Barra lateral en la aplicación`,"settings.links.newTab":`Navegador predeterminado`,"settings.transcript.title":`Detalles del trabajo`,"settings.transcript.description":`Elija cuántos detalles mostrar para las llamadas de herramientas`,"settings.collapse.title":`Cuándo contraer los detalles del trabajo`,"settings.collapse.description":`Elija cuándo contraer automáticamente los detalles del trabajo`,"settings.collapse.completion":`Al finalizar`,"settings.collapse.nextInput":`En el siguiente mensaje`,"settings.foldedReplies.title":`Respuestas después del plegado`,"settings.foldedReplies.description":`Elija qué respuestas del asistente permanecen visibles cuando los detalles del trabajo colapsan`,"settings.foldedReplies.all":`Todas las respuestas`,"settings.foldedReplies.final":`Solo respuesta final`,"settings.transcript.compact":`Compacto`,"settings.transcript.standard":`Estándar`,"settings.transcript.detailed":`Detallado`,"settings.transcript.verbose":`Detallado`,"fileOpen.title":`No se pudo abrir el archivo`,"fileOpen.unknown":`No se pudo abrir este archivo`,"message.extraBlock":`Bloque de contenido adicional`,"message.systemPrompt":`Aviso del sistema`,"message.systemPromptUpdate":`Actualización del mensaje del sistema`,"message.systemSection.added":`Añadido {name}`,"message.systemSection.updated":`Actualizado {name}`,"message.systemSection.cleared":`Vaciado {name}`,"message.systemSection.reordered":`Reordenado {name}`,"message.systemSection.removed":`Eliminado {name}`,"message.systemSection.unchanged":`Sin cambios {name}`,"message.systemPromptReset":`Reemplaza todas las instrucciones anteriores`,"message.systemPromptSections":`{count} secciones`,"message.toolAdded":`Herramienta agregada: {name}`,"message.toolRemoved":`Herramienta eliminada: {name}`,"message.toolsAdded":`Añadido: {names}`,"message.toolsAddedCount":`{count} añadido`,"message.toolsChanged":`{added} agregado, {removed} eliminado`,"message.toolsRemoved":`Eliminado: {names}`,"message.toolsRemovedCount":`{count} eliminado`,"message.toolsUpdated":`Herramientas actualizadas`,"message.contextInjection":`inyección de contexto`,"message.contextRecall":`Recuerdo de sesión`,"message.referenceSummary":`Sesión referenciada · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`cargado`,"message.context.instructions.added":`añadido`,"message.context.instructions.updated":`actualizado`,"message.context.instructions.removed":`eliminado`,"message.context.catalog.replaced":`Catálogo de repuestos`,"message.context.catalog.more":`… {count} más`,"message.context.snapshot.supersedes":`Reemplaza instantáneas anteriores`,"message.context.relay.from":`De la sesión {session}`,"message.context.recall.counts":`{retained} mantenido · {omitted} omitido`,"message.context.recall.truncated":`truncado`,"message.compaction":`Contexto compactado`,"message.inheritedHistory":`Historial heredado arriba`,"message.compaction.running":`Contexto de compactación…`,"message.compaction.completed":`Elementos del historial {items} compactados (~tokens {tokens})`,"message.compaction.open":`Ver el resumen de compactación en la barra lateral`,"message.compaction.notFound":`Resumen no disponible: el servicio no está disponible o el registro falta, está vacío o no es válido.`,"message.compaction.readFailed":`No se pudo leer el resumen`,"message.compaction.landed":`Historial anterior condensado en un resumen`,"message.compaction.commandTitle":`compacto`,"message.think":`pensar`,"message.unknownSurface":`Evento de superficie desconocido: {type}`,"message.unknownBlock":`Bloque de contenido desconocido`,"message.turnProcess.toolCalls.one":`Llamada a la herramienta {count}`,"message.turnProcess.toolCalls.other":`Llamadas a herramientas {count}`,"message.turnProcess.messages.one":`Mensaje {count}`,"message.turnProcess.messages.other":`Mensajes {count}`,"message.turnProcess.subagents.one":`Subagente {count}`,"message.turnProcess.subagents.other":`Subagentes {count}`,"message.turnProcess.thoughtForAWhile":`Razonó durante un tiempo`,"message.turnProcess.separator":` · `,"message.stopped":`Detenido`,"message.branch":`Pasar a una nueva conversación`,"message.branchUnavailable":`Disponible solo en el último mensaje de un turno completado`,"message.retry.active":`Reintentando solicitud de modelo`,"message.retry.cancelled":`Reintento de solicitud de modelo cancelado`,"message.retry.started":`Solicitud de modelo reintentada`,"message.continuation.requested":`Se ha solicitado continuar la generación`,"message.retry.scheduled":`Esperando para volver a intentar la solicitud de modelo`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Retraso de reintento: `,"message.retry.failure":`Razón del fracaso: `,"message.retry.inspect":`Inspeccionar`,"message.failure.auth":`La clave API no es válida`,"message.taskStopped":`Tarea detenida`,"message.failure.accountSignedOut":`Se detuvo porque cerró sesión en DeepSeek.`,"message.failure.interrupted":`El proceso DSH salió antes de que terminara este turno (por ejemplo, se detuvo, se estrelló o se agotó el tiempo de espera mientras se apagaba), por lo que el turno se cerró cuando se reinició DSH. Las llamadas a herramientas inacabadas tienen resultados desconocidos.`,"message.failure.accountSignInRequired":`Inicie sesión en DeepSeek y asegúrese de que el destino de la solicitud admita la autenticación de la cuenta.`,"message.failure.quota":`Solicitud de cupo agotado.`,"message.turnError":`Este turno falló`,"message.maxTokens":`Se alcanzó el límite del token de salida`,"message.maxTokens.hint":`La respuesta fue cortada; La salida anterior se conserva en la conversación. Envíe "continuar" para permitir que se reanude el modelo.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Uso del turno`,"message.turnUsage.consumed":`Uso {total}`,"message.turnUsage.model":`Proveedor / modelo`,"message.turnUsage.cacheHit":`Aciertos de caché`,"message.turnUsage.input":`Entrada sin caché`,"message.turnUsage.cacheRead":`Entrada en caché`,"message.turnUsage.cacheWrite":`escritura en caché`,"message.turnUsage.output":`Salida`,"message.turnUsage.reasoning":` (razonamiento {tokens})`,"message.turnUsage.count":`Tok {count}`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Corriendo…`,"command.failed":`El comando falló`,"command.done":`Completado`,"command.title":`Comando`,"row.running":`corriendo`,"row.failed":`Fallido`,"json.truncated":`… truncado, caracteres {total} en total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const fr={"message.stepProcess.thinking":`Analyser la demande`,"message.stepProcess.thinkingNext":`{title}, réflexion sur l'étape suivante`,"message.stepProcess.read":`Lecture de fichiers`,"message.stepProcess.readImage":`Lire des images`,"message.stepProcess.write":`Écriture de fichiers`,"message.stepProcess.search":`Recherche de code`,"message.stepProcess.edit":`Modification de fichiers`,"message.stepProcess.commands":`Exécuter des commandes`,"message.stepProcess.code":`Exécution du code`,"message.stepProcess.webSearch":`Recherche sur le Web`,"message.stepProcess.webFetch":`Visiter des pages Web`,"message.stepProcess.subagents":`Sous-agents de coordination`,"message.stepProcess.plan":`Mise à jour du plan`,"message.stepProcess.questions":`En attendant votre action`,"message.stepProcess.tools":`Outils d'appel`,"message.stepProcess.prepare.read":`Préparation à la lecture de fichiers`,"message.stepProcess.prepare.readImage":`Se préparer à lire des images`,"message.stepProcess.prepare.write":`Préparation à l'écriture de fichiers`,"message.stepProcess.prepare.search":`Préparation à la recherche de code`,"message.stepProcess.prepare.edit":`Préparation à la modification de fichiers`,"message.stepProcess.prepare.commands":`Préparation à l'exécution de commandes`,"message.stepProcess.prepare.code":`Préparation à l'exécution du code`,"message.stepProcess.prepare.webSearch":`Se préparer à effectuer une recherche sur le Web`,"message.stepProcess.prepare.webFetch":`Se préparer à visiter des pages Web`,"message.stepProcess.prepare.subagents":`Se préparer à coordonner les sous-agents`,"message.stepProcess.prepare.plan":`Préparation de la mise à jour du plan`,"message.stepProcess.prepare.questions":`Préparation des questions`,"message.stepProcess.prepare.tools":`Préparation des appels d'outils`,"message.stepProcess.done.thinking":`Analyse terminée`,"message.stepProcess.done.read":`Lire des fichiers`,"message.stepProcess.done.readImage":`Lire des images`,"message.stepProcess.done.write":`A écrit des fichiers`,"message.stepProcess.done.search":`Code recherché`,"message.stepProcess.done.edit":`Fichiers modifiés`,"message.stepProcess.done.commands":`Commandes exécutées`,"message.stepProcess.done.code":`Code exécuté`,"message.stepProcess.done.webSearch":`J'ai cherché sur le Web`,"message.stepProcess.done.webFetch":`Pages Web visitées`,"message.stepProcess.done.subagents":`Sous-agents coordonnés`,"message.stepProcess.done.plan":`Plan mis à jour`,"message.stepProcess.done.questions":`Questions posées`,"message.stepProcess.done.tools":`Outils appelés`,"message.stepProcess.done.context":`Contexte injecté`,"message.stepProcess.joinTwo":`{first} et {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Exécution demandée`,"message.trigger.goal":`Objectif continu`,"message.trigger.agent":`Message de tâche reçu`,"message.trigger.team":`Message d'équipe reçu`,"message.trigger.subagent":`Statut de la sous-tâche mis à jour`,"message.trigger.subagent.completed":`Exécution du sous-agent terminée`,"message.trigger.subagent.aborted":`Exécution du sous-agent arrêtée`,"message.trigger.subagent.error":`Échec de l’exécution du sous-agent`,"message.trigger.subagent.maxTokens":`Le sous-agent a atteint la limite de jetons`,"message.trigger.subagent.refusal":`Le sous-agent a refusé la tâche`,"message.trigger.subagent.unknown":`L’exécution du sous-agent s’est terminée de façon inattendue`,"message.trigger.github":`Événement GitHub reçu`,"message.trigger.webhook":`Événement externe reçu`,"message.trigger.schedule":`Tâche d'automatisation`,"message.trigger.job":`Tâche en arrière-plan mise à jour`,"message.trigger.plugin":`Statut du plugin mis à jour`,"message.trigger.explanation":`Cette notification a déclenché cette réponse.`,"message.turnProcess.worked":`Terminé`,"message.turnProcess.took":`Terminé en `,"message.turnProcess.failed":`Échec`,"view.chat":`Discussion`,"image.open":`Voir l'image complète`,"image.loading":`Chargement de l'image…`,"image.failed":`Aperçu de l'image indisponible`,"image.dialog":`Aperçu de l'image`,"image.close":`Fermer l'aperçu de l'image`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} tours, {steps} étapes`,"stats.cacheHit":`Taux de réussite du cache : {percent} %`,"stats.dialog.title":`Statistiques de session`,"stats.dialog.usageTitle":`Utilisation des jetons`,"stats.dialog.llmTime":`Temps LLM`,"stats.dialog.toolTime":`Temps d'outil`,"stats.dialog.ttft":`Temps moyen jusqu'au premier jeton (TTFT)`,"stats.dialog.speed":`Jetons par seconde (TPS)`,"chat.loadingHistory":`Chargement de l'historique…`,"chat.loadError":`Échec du chargement de l'historique\xA0: {message} ({code})`,"chat.loadOlder":`Charger plus tôt`,"chat.loadingOlder":`Chargement en cours`,"chat.processingOlder":`Traitement en cours`,"chat.retryOlder":`Réessayer`,"chat.historyStart":`Début de la conversation`,"chat.toBottom":`Retour en bas`,"chat.deepDiving":`Réflexion approfondie`,"chat.deepDivingFor":`Réflexion approfondie depuis {duration} ···`,"chat.turnNavigation.label":`Navigation entre les tours`,"chat.turnNavigation.jump":`Aller au tour {turn}`,"chat.turnNavigation.jumpLoad":`Charger et aller au tour {turn}`,"chat.turnNavigation.turn":`Tour {turn}`,"settings.performance.title":`Performances et utilisation`,"settings.performance.description":`Choisissez la quantité d'informations sur les performances et l'utilisation à afficher`,"settings.performance.compact":`Compacte`,"settings.performance.detailed":`Détaillé`,"settings.links.title":`Ouvrir les liens de discussion dans`,"settings.links.description":`Choisissez où ouvrir les liens Web`,"settings.links.sidebar":`Barre latérale dans l'application`,"settings.links.newTab":`Navigateur par défaut`,"settings.transcript.title":`Détails du travail`,"settings.transcript.description":`Choisissez le niveau de détails à afficher pour les appels d'outils`,"settings.collapse.title":`Quand réduire les détails du travail`,"settings.collapse.description":`Choisissez quand réduire automatiquement les détails du travail`,"settings.collapse.completion":`À la fin`,"settings.collapse.nextInput":`Au prochain message`,"settings.foldedReplies.title":`Réponses après le repli`,"settings.foldedReplies.description":`Choisissez quelles réponses de l'assistant restent visibles lorsque les détails du travail sont réduits`,"settings.foldedReplies.all":`Toutes les réponses`,"settings.foldedReplies.final":`Réponse finale seulement`,"settings.transcript.compact":`Compacte`,"settings.transcript.standard":`Norme`,"settings.transcript.detailed":`Détaillé`,"settings.transcript.verbose":`Verbeux`,"fileOpen.title":`Impossible d'ouvrir le fichier`,"fileOpen.unknown":`Impossible d'ouvrir ce fichier`,"message.extraBlock":`Bloc de contenu supplémentaire`,"message.systemPrompt":`Invite système`,"message.systemPromptUpdate":`Mise à jour de l'invite du système`,"message.systemSection.added":`Ajouté {name}`,"message.systemSection.updated":`Mis à jour {name}`,"message.systemSection.cleared":`Vidé {name}`,"message.systemSection.reordered":`Réordonné {name}`,"message.systemSection.removed":`Supprimé {name}`,"message.systemSection.unchanged":`Inchangé {name}`,"message.systemPromptReset":`Remplace toutes les instructions précédentes`,"message.systemPromptSections":`{count} sections`,"message.toolAdded":`Outil ajouté\xA0: {name}`,"message.toolRemoved":`Outil supprimé\xA0: {name}`,"message.toolsAdded":`Ajouté\xA0: {names}`,"message.toolsAddedCount":`{count} ajouté`,"message.toolsChanged":`{added} ajouté, {removed} supprimé`,"message.toolsRemoved":`Supprimé\xA0: {names}`,"message.toolsRemovedCount":`{count} supprimé`,"message.toolsUpdated":`Outils mis à jour`,"message.contextInjection":`Injection de contexte`,"message.contextRecall":`Rappel de session`,"message.referenceSummary":`Séance référencée · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`chargé`,"message.context.instructions.added":`ajouté`,"message.context.instructions.updated":`mis à jour`,"message.context.instructions.removed":`supprimé`,"message.context.catalog.replaced":`Catalogue de remplacement`,"message.context.catalog.more":`… {count} plus`,"message.context.snapshot.supersedes":`Remplace les instantanés précédents`,"message.context.relay.from":`De la séance {session}`,"message.context.recall.counts":`{retained} conservé · {omitted} omis`,"message.context.recall.truncated":`tronqué`,"message.compaction":`Contexte compacté`,"message.inheritedHistory":`Historique hérité ci-dessus`,"message.compaction.running":`Contexte de compactage…`,"message.compaction.completed":`Éléments d'historique {items} compactés (~jetons {tokens})`,"message.compaction.open":`Afficher le résumé de compactage dans le panneau latéral`,"message.compaction.notFound":`Résumé indisponible : le service est indisponible ou le résumé est absent, vide ou invalide.`,"message.compaction.readFailed":`Impossible de lire le résumé`,"message.compaction.landed":`Historique antérieur condensé en résumé`,"message.compaction.commandTitle":`compacte`,"message.think":`Pensez`,"message.unknownSurface":`Événement de surface inconnu\xA0: {type}`,"message.unknownBlock":`Bloc de contenu inconnu`,"message.turnProcess.toolCalls.one":`Appel d'outil {count}`,"message.turnProcess.toolCalls.other":`Appels d'outil {count}`,"message.turnProcess.messages.one":`Message {count}`,"message.turnProcess.messages.other":`Messages {count}`,"message.turnProcess.subagents.one":`Sous-agent {count}`,"message.turnProcess.subagents.other":`Sous-agents {count}`,"message.turnProcess.thoughtForAWhile":`Réflexion pendant un moment`,"message.turnProcess.separator":` · `,"message.stopped":`Arrêté`,"message.branch":`Lancez-vous dans une nouvelle conversation`,"message.branchUnavailable":`Disponible uniquement sur le dernier message d'un tour terminé`,"message.retry.active":`Nouvelle tentative de demande de modèle`,"message.retry.cancelled":`Nouvelle tentative de demande de modèle annulée`,"message.retry.started":`Demande de modèle réessayée`,"message.continuation.requested":`Suite de la génération demandée`,"message.retry.scheduled":`En attente de réessayer la demande de modèle`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds} s`,"message.retry.delay":`Délai de nouvelle tentative\xA0: `,"message.retry.failure":`Raison de l'échec\xA0: `,"message.retry.inspect":`Inspecter`,"message.failure.auth":`La clé API n'est pas valide`,"message.taskStopped":`Tâche arrêtée`,"message.failure.accountSignedOut":`Arrêté car vous vous êtes déconnecté de DeepSeek.`,"message.failure.interrupted":`Le processus DSH s'est terminé avant la fin de ce tour (par exemple, il a été arrêté, s'est écrasé ou a expiré lors de l'arrêt), de sorte que le tour a été fermé lorsque DSH a redémarré. Les appels d’outils inachevés ont des résultats inconnus.`,"message.failure.accountSignInRequired":`Connectez-vous à DeepSeek et assurez-vous que la destination de la demande prend en charge l'authentification du compte.`,"message.failure.quota":`Quota de demandes épuisé.`,"message.turnError":`Ce tour a échoué`,"message.maxTokens":`Limite de jetons de sortie atteinte`,"message.maxTokens.hint":`La réponse fut coupée ; la sortie antérieure est conservée dans la conversation. Envoyez «\xA0continuer\xA0» pour laisser le modèle reprendre.`,"message.tokensPerSecond":`{tps} jetons/s`,"message.turnUsage.title":`Consommation du tour`,"message.turnUsage.consumed":`Utilisation {total}`,"message.turnUsage.model":`Fournisseur / modèle`,"message.turnUsage.cacheHit":`Taux de réussite du cache`,"message.turnUsage.input":`Entrée non mise en cache`,"message.turnUsage.cacheRead":`Entrée en cache`,"message.turnUsage.cacheWrite":`Écriture en cache`,"message.turnUsage.output":`Sortie`,"message.turnUsage.reasoning":` (raisonnement {tokens})`,"message.turnUsage.count":`Jeton {count}`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Courir…`,"command.failed":`La commande a échoué`,"command.done":`Terminé`,"command.title":`Commande`,"row.running":`Courir`,"row.failed":`Échec`,"json.truncated":`… tronqué, nombre total de caractères {total}`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const de={"message.stepProcess.thinking":`Analyse der Anfrage`,"message.stepProcess.thinkingNext":`{title}, Überlegung zum nächsten Schritt`,"message.stepProcess.read":`Dateien lesen`,"message.stepProcess.readImage":`Bilder lesen`,"message.stepProcess.write":`Dateien schreiben`,"message.stepProcess.search":`Code wird gesucht`,"message.stepProcess.edit":`Bearbeiten von Dateien`,"message.stepProcess.commands":`Befehle ausführen`,"message.stepProcess.code":`Ausführen von Code`,"message.stepProcess.webSearch":`Suche im Internet`,"message.stepProcess.webFetch":`Besuch von Webseiten`,"message.stepProcess.subagents":`Koordinierende Unteragenten`,"message.stepProcess.plan":`Aktualisierung des Plans`,"message.stepProcess.questions":`Ich warte auf Ihre Aktion`,"message.stepProcess.tools":`Aufrufende Werkzeuge`,"message.stepProcess.prepare.read":`Vorbereitung zum Lesen von Dateien`,"message.stepProcess.prepare.readImage":`Vorbereitung zum Lesen von Bildern`,"message.stepProcess.prepare.write":`Vorbereitung zum Schreiben von Dateien`,"message.stepProcess.prepare.search":`Vorbereiten der Codesuche`,"message.stepProcess.prepare.edit":`Vorbereitung zum Bearbeiten von Dateien`,"message.stepProcess.prepare.commands":`Vorbereitung zum Ausführen von Befehlen`,"message.stepProcess.prepare.code":`Vorbereiten, Code auszuführen`,"message.stepProcess.prepare.webSearch":`Bereiten Sie sich auf die Suche im Internet vor`,"message.stepProcess.prepare.webFetch":`Vorbereitung auf den Besuch von Webseiten`,"message.stepProcess.prepare.subagents":`Vorbereitung zur Koordinierung von Subagenten`,"message.stepProcess.prepare.plan":`Vorbereitung zur Aktualisierung des Plans`,"message.stepProcess.prepare.questions":`Fragen vorbereiten`,"message.stepProcess.prepare.tools":`Toolaufrufe vorbereiten`,"message.stepProcess.done.thinking":`Analyse abgeschlossen`,"message.stepProcess.done.read":`Dateien lesen`,"message.stepProcess.done.readImage":`Bilder lesen`,"message.stepProcess.done.write":`Dateien geschrieben`,"message.stepProcess.done.search":`Gesuchter Code`,"message.stepProcess.done.edit":`Bearbeitete Dateien`,"message.stepProcess.done.commands":`Befehle ausgeführt`,"message.stepProcess.done.code":`Code ausgeführt`,"message.stepProcess.done.webSearch":`Habe das Internet durchsucht`,"message.stepProcess.done.webFetch":`Besuchte Webseiten`,"message.stepProcess.done.subagents":`Koordinierte Unteragenten`,"message.stepProcess.done.plan":`Plan aktualisiert`,"message.stepProcess.done.questions":`Gestellte Fragen`,"message.stepProcess.done.tools":`Werkzeuge genannt`,"message.stepProcess.done.context":`Kontext injiziert`,"message.stepProcess.joinTwo":`{first} und {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title} usw.`,"message.trigger.request":`Ausführung beantragt`,"message.trigger.goal":`Weiterführendes Ziel`,"message.trigger.agent":`Aufgabennachricht erhalten`,"message.trigger.team":`Teamnachricht erhalten`,"message.trigger.subagent":`Unteraufgabenstatus aktualisiert`,"message.trigger.subagent.completed":`Ausführung des Subagenten abgeschlossen`,"message.trigger.subagent.aborted":`Ausführung des Subagenten gestoppt`,"message.trigger.subagent.error":`Ausführung des Subagenten fehlgeschlagen`,"message.trigger.subagent.maxTokens":`Subagent hat das Token-Limit erreicht`,"message.trigger.subagent.refusal":`Subagent hat die Aufgabe abgelehnt`,"message.trigger.subagent.unknown":`Ausführung des Subagenten unerwartet beendet`,"message.trigger.github":`GitHub-Ereignis empfangen`,"message.trigger.webhook":`Externes Ereignis empfangen`,"message.trigger.schedule":`Automatisierungsaufgabe`,"message.trigger.job":`Hintergrundaufgabe aktualisiert`,"message.trigger.plugin":`Plugin-Status aktualisiert`,"message.trigger.explanation":`Diese Benachrichtigung hat diese Reaktion ausgelöst.`,"message.turnProcess.worked":`Abgeschlossen`,"message.turnProcess.took":`Fertiggestellt in `,"message.turnProcess.failed":`Fehlgeschlagen`,"view.chat":`Chat`,"image.open":`Vollständiges Bild anzeigen`,"image.loading":`Bild wird geladen…`,"image.failed":`Bildvorschau nicht verfügbar`,"image.dialog":`Bildvorschau`,"image.close":`Bildvorschau schließen`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} Runden, {steps} Schritte`,"stats.cacheHit":`Cache-Treffer: {percent}%`,"stats.dialog.title":`Sitzungsstatistiken`,"stats.dialog.usageTitle":`Token-Nutzung`,"stats.dialog.llmTime":`LLM-Zeit`,"stats.dialog.toolTime":`Werkzeugzeit`,"stats.dialog.ttft":`Durchschnittliche Zeit bis zum ersten Token (TTFT)`,"stats.dialog.speed":`Token pro Sekunde (TPS)`,"chat.loadingHistory":`Verlauf wird geladen…`,"chat.loadError":`Fehler beim Laden des Verlaufs: {message} ({code})`,"chat.loadOlder":`Früher laden`,"chat.loadingOlder":`Wird geladen`,"chat.processingOlder":`Wird verarbeitet`,"chat.retryOlder":`Erneut laden`,"chat.historyStart":`Anfang der Unterhaltung`,"chat.toBottom":`Zurück nach unten`,"chat.deepDiving":`Gründliches Nachdenken`,"chat.deepDivingFor":`Gründliches Nachdenken seit {duration} ···`,"chat.turnNavigation.label":`Rundennavigation`,"chat.turnNavigation.jump":`Zu Runde {turn} springen`,"chat.turnNavigation.jumpLoad":`Runde {turn} laden und öffnen`,"chat.turnNavigation.turn":`Runde {turn}`,"settings.performance.title":`Leistung und Nutzung`,"settings.performance.description":`Wählen Sie aus, wie viele Leistungs- und Nutzungsinformationen angezeigt werden sollen`,"settings.performance.compact":`Kompakt`,"settings.performance.detailed":`Ausführlich`,"settings.links.title":`Öffnen Sie Chat-Links in`,"settings.links.description":`Wählen Sie aus, wo Weblinks geöffnet werden sollen`,"settings.links.sidebar":`In-App-Seitenleiste`,"settings.links.newTab":`Standardbrowser`,"settings.transcript.title":`Arbeitsdetails`,"settings.transcript.description":`Wählen Sie aus, wie viele Details für Werkzeugaufrufe angezeigt werden sollen`,"settings.collapse.title":`Wann Arbeitsdetails minimiert werden sollten`,"settings.collapse.description":`Wählen Sie aus, wann Arbeitsdetails automatisch ausgeblendet werden sollen`,"settings.collapse.completion":`Nach Fertigstellung`,"settings.collapse.nextInput":`Bei der nächsten Nachricht`,"settings.foldedReplies.title":`Antworten nach dem Einklappen`,"settings.foldedReplies.description":`Wählen Sie aus, welche Assistentenantworten sichtbar bleiben, wenn die Arbeitsdetails ausgeblendet werden`,"settings.foldedReplies.all":`Alle Antworten`,"settings.foldedReplies.final":`Nur die endgültige Antwort`,"settings.transcript.compact":`Kompakt`,"settings.transcript.standard":`Standard`,"settings.transcript.detailed":`Ausführlich`,"settings.transcript.verbose":`Ausführlich`,"fileOpen.title":`Datei konnte nicht geöffnet werden`,"fileOpen.unknown":`Diese Datei konnte nicht geöffnet werden`,"message.extraBlock":`Zusätzlicher Inhaltsblock`,"message.systemPrompt":`Systemaufforderung`,"message.systemPromptUpdate":`Aktualisierung der Systemaufforderung`,"message.systemSection.added":`Hinzugefügt {name}`,"message.systemSection.updated":`Aktualisiert {name}`,"message.systemSection.cleared":`Geleert {name}`,"message.systemSection.reordered":`Neu angeordnet {name}`,"message.systemSection.removed":`Entfernt {name}`,"message.systemSection.unchanged":`Unverändert {name}`,"message.systemPromptReset":`Ersetzt alle früheren Anweisungen`,"message.systemPromptSections":`{count} Abschnitte`,"message.toolAdded":`Tool hinzugefügt: {name}`,"message.toolRemoved":`Entferntes Werkzeug: {name}`,"message.toolsAdded":`Hinzugefügt: {names}`,"message.toolsAddedCount":`{count} hinzugefügt`,"message.toolsChanged":`{added} hinzugefügt, {removed} entfernt`,"message.toolsRemoved":`Entfernt: {names}`,"message.toolsRemovedCount":`{count} entfernt`,"message.toolsUpdated":`Werkzeuge aktualisiert`,"message.contextInjection":`Kontextinjektion`,"message.contextRecall":`Sitzungsrückruf`,"message.referenceSummary":`Referenzierte Sitzung · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`geladen`,"message.context.instructions.added":`hinzugefügt`,"message.context.instructions.updated":`aktualisiert`,"message.context.instructions.removed":`entfernt`,"message.context.catalog.replaced":`Ersatzkatalog`,"message.context.catalog.more":`… {count} mehr`,"message.context.snapshot.supersedes":`Ersetzt frühere Schnappschüsse`,"message.context.relay.from":`Aus der Sitzung {session}`,"message.context.recall.counts":`{retained} beibehalten · {omitted} weggelassen`,"message.context.recall.truncated":`abgeschnitten`,"message.compaction":`Kontext verdichtet`,"message.inheritedHistory":`Übernommener Verlauf oben`,"message.compaction.running":`Kontext verdichten…`,"message.compaction.completed":`Komprimierte {items}-Verlaufselemente (~{tokens}-Tokens)`,"message.compaction.open":`Zusammenfassung der Komprimierung in der Seitenleiste anzeigen`,"message.compaction.notFound":`Zusammenfassung nicht verfügbar: Der Dienst ist nicht verfügbar oder der Eintrag fehlt, ist leer oder ungültig.`,"message.compaction.readFailed":`Zusammenfassung konnte nicht gelesen werden`,"message.compaction.landed":`Früherer Verlauf zu einer Zusammenfassung verdichtet`,"message.compaction.commandTitle":`kompakt`,"message.think":`Denken Sie nach`,"message.unknownSurface":`Unbekanntes Oberflächenereignis: {type}`,"message.unknownBlock":`Unbekannter Inhaltsblock`,"message.turnProcess.toolCalls.one":`Werkzeugaufruf {count}`,"message.turnProcess.toolCalls.other":`{count} Toolaufrufe`,"message.turnProcess.messages.one":`{count}-Nachricht`,"message.turnProcess.messages.other":`{count}-Nachrichten`,"message.turnProcess.subagents.one":`{count}-Subagent`,"message.turnProcess.subagents.other":`{count}-Subagenten`,"message.turnProcess.thoughtForAWhile":`Eine Weile nachgedacht`,"message.turnProcess.separator":` · `,"message.stopped":`Angehalten`,"message.branch":`Verzweigen Sie in ein neues Gespräch`,"message.branchUnavailable":`Nur verfügbar bei der letzten Nachricht einer abgeschlossenen Runde`,"message.retry.active":`Modellanforderung wird erneut versucht`,"message.retry.cancelled":`Wiederholungsversuch der Modellanforderung abgebrochen`,"message.retry.started":`Modellanfrage erneut versucht`,"message.continuation.requested":`Fortsetzung der Generierung angefordert`,"message.retry.scheduled":`Warten auf erneuten Versuch der Modellanforderung`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Wiederholungsverzögerung: `,"message.retry.failure":`Fehlergrund: `,"message.retry.inspect":`Inspizieren`,"message.failure.auth":`Der API-Schlüssel ist ungültig`,"message.taskStopped":`Aufgabe gestoppt`,"message.failure.accountSignedOut":`Gestoppt, weil Sie sich von DeepSeek abgemeldet haben.`,"message.failure.interrupted":`Der DSH-Prozess wurde beendet, bevor dieser Zug beendet war (z. B. wurde er beendet, stürzte ab oder es kam zu einer Zeitüberschreitung beim Herunterfahren), sodass der Zug geschlossen wurde, als DSH neu gestartet wurde. Unvollendete Werkzeugaufrufe haben unbekannte Ergebnisse.`,"message.failure.accountSignInRequired":`Melden Sie sich bei DeepSeek an und stellen Sie sicher, dass das Anforderungsziel die Kontoauthentifizierung unterstützt.`,"message.failure.quota":`Anforderungskontingent ausgeschöpft.`,"message.turnError":`Diese Runde ist fehlgeschlagen`,"message.maxTokens":`Ausgabe-Token-Limit erreicht`,"message.maxTokens.hint":`Die Antwort wurde abgeschnitten; Frühere Ausgaben bleiben in der Konversation erhalten. Senden Sie „Weiter“, um das Modell fortzusetzen.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Rundenverbrauch`,"message.turnUsage.consumed":`Verwendung {total}`,"message.turnUsage.model":`Anbieter / Modell`,"message.turnUsage.cacheHit":`Cache-Treffer`,"message.turnUsage.input":`Nicht zwischengespeicherte Eingabe`,"message.turnUsage.cacheRead":`Zwischengespeicherte Eingabe`,"message.turnUsage.cacheWrite":`Cache-Schreiben`,"message.turnUsage.output":`Ausgabe`,"message.turnUsage.reasoning":` ({tokens}-Argumentation)`,"message.turnUsage.count":`{count}-Token`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Laufen…`,"command.failed":`Der Befehl ist fehlgeschlagen`,"command.done":`Abgeschlossen`,"command.title":`Befehl`,"row.running":`Laufen`,"row.failed":`Fehlgeschlagen`,"json.truncated":`… gekürzt, {total} Zeichen insgesamt`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const ru={"message.stepProcess.thinking":`Анализ запроса`,"message.stepProcess.thinkingNext":`{title}, обдумывание следующего шага`,"message.stepProcess.read":`Чтение файлов`,"message.stepProcess.readImage":`Чтение изображений`,"message.stepProcess.write":`Запись файлов`,"message.stepProcess.search":`Поиск кода`,"message.stepProcess.edit":`Редактирование файлов`,"message.stepProcess.commands":`Запуск команд`,"message.stepProcess.code":`Запуск кода`,"message.stepProcess.webSearch":`Поиск в Интернете`,"message.stepProcess.webFetch":`Посещение веб-страниц`,"message.stepProcess.subagents":`Координирующие субагенты`,"message.stepProcess.plan":`Обновление плана`,"message.stepProcess.questions":`Жду ваших действий`,"message.stepProcess.tools":`Вызов инструментов`,"message.stepProcess.prepare.read":`Подготовка к чтению файлов`,"message.stepProcess.prepare.readImage":`Подготовка к чтению изображений`,"message.stepProcess.prepare.write":`Подготовка к записи файлов`,"message.stepProcess.prepare.search":`Подготовка к поиску кода`,"message.stepProcess.prepare.edit":`Подготовка к редактированию файлов`,"message.stepProcess.prepare.commands":`Подготовка к выполнению команд`,"message.stepProcess.prepare.code":`Подготовка к запуску кода`,"message.stepProcess.prepare.webSearch":`Подготовка к поиску в Интернете`,"message.stepProcess.prepare.webFetch":`Подготовка к посещению веб-страниц`,"message.stepProcess.prepare.subagents":`Подготовка к координации субагентов`,"message.stepProcess.prepare.plan":`Подготовка к обновлению плана`,"message.stepProcess.prepare.questions":`Подготовка вопросов`,"message.stepProcess.prepare.tools":`Подготовка вызовов инструментов`,"message.stepProcess.done.thinking":`Анализ завершен`,"message.stepProcess.done.read":`Чтение файлов`,"message.stepProcess.done.readImage":`Чтение изображений`,"message.stepProcess.done.write":`Написал файлы`,"message.stepProcess.done.search":`Искомый код`,"message.stepProcess.done.edit":`Отредактированные файлы`,"message.stepProcess.done.commands":`Выполнение команд`,"message.stepProcess.done.code":`Выполненный код`,"message.stepProcess.done.webSearch":`Искал в Интернете`,"message.stepProcess.done.webFetch":`Посещенные веб-страницы`,"message.stepProcess.done.subagents":`Координированные субагенты`,"message.stepProcess.done.plan":`Обновлен план`,"message.stepProcess.done.questions":`Задаваемые вопросы`,"message.stepProcess.done.tools":`Вызываемые инструменты`,"message.stepProcess.done.context":`Контекст внедрён`,"message.stepProcess.joinTwo":`{first} и {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title} и т. д.`,"message.trigger.request":`Запрошено выполнение`,"message.trigger.goal":`Постоянная цель`,"message.trigger.agent":`Сообщение о задаче получено`,"message.trigger.team":`Сообщение команды получено`,"message.trigger.subagent":`Статус подзадачи обновлен`,"message.trigger.subagent.completed":`Работа субагента завершена`,"message.trigger.subagent.aborted":`Работа субагента остановлена`,"message.trigger.subagent.error":`Работа субагента завершилась с ошибкой`,"message.trigger.subagent.maxTokens":`Субагент достиг лимита токенов`,"message.trigger.subagent.refusal":`Субагент отказался выполнять задачу`,"message.trigger.subagent.unknown":`Работа субагента неожиданно завершилась`,"message.trigger.github":`Событие GitHub получено`,"message.trigger.webhook":`Получено внешнее событие`,"message.trigger.schedule":`Задача автоматизации`,"message.trigger.job":`Фоновая задача обновлена.`,"message.trigger.plugin":`Статус плагина обновлен`,"message.trigger.explanation":`Это уведомление вызвало такой ответ.`,"message.turnProcess.worked":`Завершено`,"message.turnProcess.took":`Завершено в `,"message.turnProcess.failed":`Не удалось`,"view.chat":`Чат`,"image.open":`Посмотреть полное изображение`,"image.loading":`Загрузка изображения…`,"image.failed":`Предварительный просмотр изображения недоступен.`,"image.dialog":`Предварительный просмотр изображения`,"image.close":`Закрыть предварительный просмотр изображения`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`Ходов: {turns}, шагов: {steps}`,"stats.cacheHit":`Попадание в кэш: {percent}%`,"stats.dialog.title":`Статистика сеансов`,"stats.dialog.usageTitle":`Использование токена`,"stats.dialog.llmTime":`время магистратуры`,"stats.dialog.toolTime":`Время работы инструмента`,"stats.dialog.ttft":`Среднее время до первого токена (TTFT)`,"stats.dialog.speed":`Токенов в секунду (TPS)`,"chat.loadingHistory":`Загрузка истории…`,"chat.loadError":`Не удалось загрузить историю: {message} ({code})`,"chat.loadOlder":`Загрузить раньше`,"chat.loadingOlder":`Загрузка истории`,"chat.processingOlder":`Обработка`,"chat.retryOlder":`Повторить загрузку`,"chat.historyStart":`Начало разговора`,"chat.toBottom":`Вернуться к низу`,"chat.deepDiving":`Глубокое размышление`,"chat.deepDivingFor":`Глубокое размышление в течение {duration} ···`,"chat.turnNavigation.label":`Навигация по ходам`,"chat.turnNavigation.jump":`Перейти к ходу {turn}`,"chat.turnNavigation.jumpLoad":`Загрузить ход {turn} и перейти к нему`,"chat.turnNavigation.turn":`Ход {turn}`,"settings.performance.title":`Производительность и использование`,"settings.performance.description":`Выберите, какой объем информации о производительности и использовании показывать`,"settings.performance.compact":`Компактный`,"settings.performance.detailed":`Подробный`,"settings.links.title":`Открыть ссылки на чат в`,"settings.links.description":`Выберите, где открывать веб-ссылки`,"settings.links.sidebar":`Боковая панель в приложении`,"settings.links.newTab":`Браузер по умолчанию`,"settings.transcript.title":`Детали работы`,"settings.transcript.description":`Выберите, насколько подробно следует отображать вызовы инструментов.`,"settings.collapse.title":`Когда сворачивать детали работы`,"settings.collapse.description":`Выберите, когда автоматически сворачивать сведения о работе`,"settings.collapse.completion":`По завершении`,"settings.collapse.nextInput":`В следующем сообщении`,"settings.foldedReplies.title":`Ответы после сворачивания`,"settings.foldedReplies.description":`Выберите, какие ответы помощника останутся видимыми, когда сведения о работе будут свернуты.`,"settings.foldedReplies.all":`Все ответы`,"settings.foldedReplies.final":`Только окончательный ответ`,"settings.transcript.compact":`Компактный`,"settings.transcript.standard":`Стандартный`,"settings.transcript.detailed":`Подробный`,"settings.transcript.verbose":`Многословный`,"fileOpen.title":`Не удалось открыть файл`,"fileOpen.unknown":`Не удалось открыть этот файл`,"message.extraBlock":`Дополнительный блок контента`,"message.systemPrompt":`Системная подсказка`,"message.systemPromptUpdate":`Обновление системного запроса`,"message.systemSection.added":`Добавлено {name}`,"message.systemSection.updated":`Обновлено {name}`,"message.systemSection.cleared":`Очищено {name}`,"message.systemSection.reordered":`Порядок изменён {name}`,"message.systemSection.removed":`Удалено {name}`,"message.systemSection.unchanged":`Без изменений {name}`,"message.systemPromptReset":`Заменяет все предыдущие инструкции`,"message.systemPromptSections":`Разделов: {count}`,"message.toolAdded":`Добавлен инструмент: {name}.`,"message.toolRemoved":`Инструмент удален: {name}.`,"message.toolsAdded":`Добавлено: {names}`,"message.toolsAddedCount":`{count} добавлен`,"message.toolsChanged":`{added} добавлен, {removed} удален.`,"message.toolsRemoved":`Удалено: {names}.`,"message.toolsRemovedCount":`{count} удален.`,"message.toolsUpdated":`Инструменты обновлены`,"message.contextInjection":`Внедрение контекста`,"message.contextRecall":`Отзыв сеанса`,"message.referenceSummary":`Ссылка на сессию · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`загружен`,"message.context.instructions.added":`добавлено`,"message.context.instructions.updated":`обновлено`,"message.context.instructions.removed":`удалено`,"message.context.catalog.replaced":`Каталог замены`,"message.context.catalog.more":`… {count} ещё`,"message.context.snapshot.supersedes":`Заменяет предыдущие снимки`,"message.context.relay.from":`Из сеанса {session}`,"message.context.recall.counts":`{retained} сохранен · {omitted} опущен`,"message.context.recall.truncated":`усеченный`,"message.compaction":`Контекст сжат`,"message.inheritedHistory":`Выше — унаследованная история`,"message.compaction.running":`Сжатие контекста…`,"message.compaction.completed":`Сжатые элементы истории {items} (токены ~{tokens})`,"message.compaction.open":`Открыть сводку сжатия на боковой панели`,"message.compaction.notFound":`Сводка недоступна: сервис недоступен либо запись отсутствует, пуста или недействительна.`,"message.compaction.readFailed":`Не удалось прочитать сводку`,"message.compaction.landed":`Ранняя история сжата в сводку`,"message.compaction.commandTitle":`компактный`,"message.think":`Подумайте`,"message.unknownSurface":`Неизвестное событие на поверхности: {type}.`,"message.unknownBlock":`Неизвестный блок контента`,"message.turnProcess.toolCalls.one":`{count} вызов инструмента`,"message.turnProcess.toolCalls.other":`{count} вызовов инструментов`,"message.turnProcess.messages.one":`Сообщение {count}`,"message.turnProcess.messages.other":`Сообщения {count}`,"message.turnProcess.subagents.one":`Субагент {count}`,"message.turnProcess.subagents.other":`Субагенты {count}`,"message.turnProcess.thoughtForAWhile":`Размышлял некоторое время`,"message.turnProcess.separator":` · `,"message.stopped":`Остановлено`,"message.branch":`Перейти к новому разговору`,"message.branchUnavailable":`Доступно только в последнем сообщении о завершенном ходу.`,"message.retry.active":`Повторный запрос модели`,"message.retry.cancelled":`Повтор запроса модели отменен.`,"message.retry.started":`Повторный запрос модели`,"message.continuation.requested":`Запрошено продолжение генерации`,"message.retry.scheduled":`Ожидание повторного запроса модели`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Задержка повтора: `,"message.retry.failure":`Причина неисправности: `,"message.retry.inspect":`Осмотреть`,"message.failure.auth":`Ключ API недействителен.`,"message.taskStopped":`Задача остановлена`,"message.failure.accountSignedOut":`Остановлено, поскольку вы вышли из DeepSeek.`,"message.failure.interrupted":`Процесс DSH завершился до завершения этого хода (например, был завершен, произошел сбой или истекло время ожидания при завершении работы), поэтому ход был закрыт при перезапуске DSH. Незавершенные вызовы инструментов имеют неизвестные результаты.`,"message.failure.accountSignInRequired":`Войдите в DeepSeek и убедитесь, что пункт назначения запроса поддерживает аутентификацию учетной записи.`,"message.failure.quota":`Квота запросов исчерпана.`,"message.turnError":`Этот ход завершился ошибкой`,"message.maxTokens":`Достигнут предел выходных токенов`,"message.maxTokens.hint":`Ответ был прерван; более ранний вывод сохраняется в разговоре. Отправьте «продолжить», чтобы модель возобновила работу.`,"message.tokensPerSecond":`{tps} ток/с`,"message.turnUsage.title":`Использование ресурсов за ход`,"message.turnUsage.consumed":`Использование {total}`,"message.turnUsage.model":`Поставщик/модель`,"message.turnUsage.cacheHit":`Попадание в кэш`,"message.turnUsage.input":`Некэшированный ввод`,"message.turnUsage.cacheRead":`Кэшированный ввод`,"message.turnUsage.cacheWrite":`Запись в кэш`,"message.turnUsage.output":`Выход`,"message.turnUsage.reasoning":` (рассуждение {tokens})`,"message.turnUsage.count":`{count} ток`,"duration.secondUnit":`с`,"duration.minuteUnit":`м `,"duration.hourUnit":`ч `,"command.running":`Бег…`,"command.failed":`Команда не выполнена`,"command.done":`Завершено`,"command.title":`Команда`,"row.running":`Бег`,"row.failed":`Не удалось`,"json.truncated":`… усечено, всего символов {total}`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const pt={"message.stepProcess.thinking":`Analisando a solicitação`,"message.stepProcess.thinkingNext":`{title}, pensando no próximo passo`,"message.stepProcess.read":`Lendo arquivos`,"message.stepProcess.readImage":`Lendo imagens`,"message.stepProcess.write":`Gravando arquivos`,"message.stepProcess.search":`Pesquisando código`,"message.stepProcess.edit":`Editando arquivos`,"message.stepProcess.commands":`Executando comandos`,"message.stepProcess.code":`Executando código`,"message.stepProcess.webSearch":`Pesquisando na web`,"message.stepProcess.webFetch":`Visitando páginas da web`,"message.stepProcess.subagents":`Coordenando subagentes`,"message.stepProcess.plan":`Atualizando o plano`,"message.stepProcess.questions":`Esperando por sua ação`,"message.stepProcess.tools":`Ferramentas de chamada`,"message.stepProcess.prepare.read":`Preparando-se para ler arquivos`,"message.stepProcess.prepare.readImage":`Preparando-se para ler imagens`,"message.stepProcess.prepare.write":`Preparando-se para gravar arquivos`,"message.stepProcess.prepare.search":`Preparando-se para pesquisar o código`,"message.stepProcess.prepare.edit":`Preparando-se para editar arquivos`,"message.stepProcess.prepare.commands":`Preparando para executar comandos`,"message.stepProcess.prepare.code":`Preparando-se para executar o código`,"message.stepProcess.prepare.webSearch":`Preparando-se para pesquisar na web`,"message.stepProcess.prepare.webFetch":`Preparando-se para visitar páginas da web`,"message.stepProcess.prepare.subagents":`Preparando-se para coordenar subagentes`,"message.stepProcess.prepare.plan":`Preparando-se para atualizar o plano`,"message.stepProcess.prepare.questions":`Preparando perguntas`,"message.stepProcess.prepare.tools":`Preparando chamadas de ferramenta`,"message.stepProcess.done.thinking":`Análise concluída`,"message.stepProcess.done.read":`Ler arquivos`,"message.stepProcess.done.readImage":`Ler imagens`,"message.stepProcess.done.write":`Escreveu arquivos`,"message.stepProcess.done.search":`Código pesquisado`,"message.stepProcess.done.edit":`Arquivos editados`,"message.stepProcess.done.commands":`Comandos executados`,"message.stepProcess.done.code":`Código executado`,"message.stepProcess.done.webSearch":`Pesquisei na web`,"message.stepProcess.done.webFetch":`Páginas da web visitadas`,"message.stepProcess.done.subagents":`Subagentes coordenados`,"message.stepProcess.done.plan":`Atualizado o plano`,"message.stepProcess.done.questions":`Perguntas feitas`,"message.stepProcess.done.tools":`Ferramentas chamadas`,"message.stepProcess.done.context":`Contexto injetado`,"message.stepProcess.joinTwo":`{first} e {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Execução solicitada`,"message.trigger.goal":`Objetivo contínuo`,"message.trigger.agent":`Mensagem de tarefa recebida`,"message.trigger.team":`Mensagem da equipe recebida`,"message.trigger.subagent":`Status da subtarefa atualizado`,"message.trigger.subagent.completed":`Execução do subagente concluída`,"message.trigger.subagent.aborted":`Execução do subagente interrompida`,"message.trigger.subagent.error":`Falha na execução do subagente`,"message.trigger.subagent.maxTokens":`O subagente atingiu o limite de tokens`,"message.trigger.subagent.refusal":`O subagente recusou a tarefa`,"message.trigger.subagent.unknown":`A execução do subagente terminou inesperadamente`,"message.trigger.github":`GitHub evento recebido`,"message.trigger.webhook":`Evento externo recebido`,"message.trigger.schedule":`Tarefa de automação`,"message.trigger.job":`Tarefa em segundo plano atualizada`,"message.trigger.plugin":`Status do plug-in atualizado`,"message.trigger.explanation":`Esta notificação desencadeou esta resposta.`,"message.turnProcess.worked":`Concluído`,"message.turnProcess.took":`Concluído em `,"message.turnProcess.failed":`Falha`,"view.chat":`Chat`,"image.open":`Ver imagem completa`,"image.loading":`Carregando imagem…`,"image.failed":`Visualização da imagem indisponível`,"image.dialog":`Visualização da imagem`,"image.close":`Fechar visualização da imagem`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turnos, {steps} etapas`,"stats.cacheHit":`Acertos no cache: {percent}%`,"stats.dialog.title":`Estatísticas da sessão`,"stats.dialog.usageTitle":`Uso de token`,"stats.dialog.llmTime":`Horário do LLM`,"stats.dialog.toolTime":`Tempo da ferramenta`,"stats.dialog.ttft":`Tempo médio para o primeiro token (TTFT)`,"stats.dialog.speed":`Tokens por segundo (TPS)`,"chat.loadingHistory":`Carregando histórico…`,"chat.loadError":`Falha ao carregar o histórico: {message} ({code})`,"chat.loadOlder":`Carregar mais cedo`,"chat.loadingOlder":`Carregando anteriores`,"chat.processingOlder":`Processando`,"chat.retryOlder":`Tentar novamente`,"chat.historyStart":`Início da conversa`,"chat.toBottom":`De volta ao fundo`,"chat.deepDiving":`Raciocínio profundo`,"chat.deepDivingFor":`Raciocínio profundo há {duration} ···`,"chat.turnNavigation.label":`Navegação entre turnos`,"chat.turnNavigation.jump":`Ir para o turno {turn}`,"chat.turnNavigation.jumpLoad":`Carregar e ir para o turno {turn}`,"chat.turnNavigation.turn":`Turno {turn}`,"settings.performance.title":`Desempenho e uso`,"settings.performance.description":`Escolha quantas informações de desempenho e uso serão exibidas`,"settings.performance.compact":`Compacto`,"settings.performance.detailed":`Detalhado`,"settings.links.title":`Abra links de bate-papo em`,"settings.links.description":`Escolha onde abrir links da web`,"settings.links.sidebar":`Barra lateral no aplicativo`,"settings.links.newTab":`Navegador padrão`,"settings.transcript.title":`Detalhes do trabalho`,"settings.transcript.description":`Escolha quantos detalhes serão exibidos nas chamadas de ferramenta`,"settings.collapse.title":`Quando recolher detalhes do trabalho`,"settings.collapse.description":`Escolha quando recolher automaticamente os detalhes do trabalho`,"settings.collapse.completion":`Na conclusão`,"settings.collapse.nextInput":`Na próxima mensagem`,"settings.foldedReplies.title":`Respostas após o recolhimento`,"settings.foldedReplies.description":`Escolha quais respostas do assistente permanecerão visíveis quando os detalhes do trabalho forem recolhidos`,"settings.foldedReplies.all":`Todas as respostas`,"settings.foldedReplies.final":`Apenas resposta final`,"settings.transcript.compact":`Compacto`,"settings.transcript.standard":`Padrão`,"settings.transcript.detailed":`Detalhado`,"settings.transcript.verbose":`Verboso`,"fileOpen.title":`Não foi possível abrir o arquivo`,"fileOpen.unknown":`Não foi possível abrir este arquivo`,"message.extraBlock":`Bloco de conteúdo extra`,"message.systemPrompt":`Alerta do sistema`,"message.systemPromptUpdate":`Atualização imediata do sistema`,"message.systemSection.added":`Adicionado {name}`,"message.systemSection.updated":`Atualizado {name}`,"message.systemSection.cleared":`Limpo {name}`,"message.systemSection.reordered":`Reordenado {name}`,"message.systemSection.removed":`Removido {name}`,"message.systemSection.unchanged":`Inalterado {name}`,"message.systemPromptReset":`Substitui todas as instruções anteriores`,"message.systemPromptSections":`{count} seções`,"message.toolAdded":`Ferramenta adicionada: {name}`,"message.toolRemoved":`Ferramenta removida: {name}`,"message.toolsAdded":`Adicionado: {names}`,"message.toolsAddedCount":`{count} adicionado`,"message.toolsChanged":`{added} adicionado, {removed} removido`,"message.toolsRemoved":`Removido: {names}`,"message.toolsRemovedCount":`{count} removido`,"message.toolsUpdated":`Ferramentas atualizadas`,"message.contextInjection":`Injeção de contexto`,"message.contextRecall":`Recuperação de sessão`,"message.referenceSummary":`Sessão referenciada · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`carregado`,"message.context.instructions.added":`adicionado`,"message.context.instructions.updated":`atualizado`,"message.context.instructions.removed":`removido`,"message.context.catalog.replaced":`Catálogo de substituição`,"message.context.catalog.more":`… {count} mais`,"message.context.snapshot.supersedes":`Substitui instantâneos anteriores`,"message.context.relay.from":`Da sessão {session}`,"message.context.recall.counts":`{retained} mantido · {omitted} omitido`,"message.context.recall.truncated":`truncado`,"message.compaction":`Contexto compactado`,"message.inheritedHistory":`Histórico herdado acima`,"message.compaction.running":`Contexto compactado…`,"message.compaction.completed":`{items} itens de histórico compactados (~{tokens} tokens)`,"message.compaction.open":`Ver o resumo da compactação na barra lateral`,"message.compaction.notFound":`Resumo indisponível: o serviço está indisponível ou o registro está ausente, vazio ou inválido.`,"message.compaction.readFailed":`Não foi possível ler o resumo`,"message.compaction.landed":`Histórico anterior condensado em um resumo`,"message.compaction.commandTitle":`compacto`,"message.think":`Pense`,"message.unknownSurface":`Evento de superfície desconhecido: {type}`,"message.unknownBlock":`Bloco de conteúdo desconhecido`,"message.turnProcess.toolCalls.one":`{count} chamada de ferramenta`,"message.turnProcess.toolCalls.other":`{count} chamadas de ferramenta`,"message.turnProcess.messages.one":`{count} mensagem`,"message.turnProcess.messages.other":`{count} mensagens`,"message.turnProcess.subagents.one":`{count} subagente`,"message.turnProcess.subagents.other":`{count} subagentes`,"message.turnProcess.thoughtForAWhile":`Pensou por um tempo`,"message.turnProcess.separator":` · `,"message.stopped":`Parado`,"message.branch":`Ramifique para uma nova conversa`,"message.branchUnavailable":`Disponível apenas na última mensagem de um turno concluído`,"message.retry.active":`Tentando novamente a solicitação de modelo`,"message.retry.cancelled":`Nova tentativa de solicitação de modelo cancelada`,"message.retry.started":`Solicitação de modelo repetida`,"message.continuation.requested":`Continuação da geração solicitada`,"message.retry.scheduled":`Aguardando para tentar novamente a solicitação de modelo`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Atraso na nova tentativa: `,"message.retry.failure":`Motivo da falha: `,"message.retry.inspect":`Inspecionar`,"message.failure.auth":`A chave API é inválida`,"message.taskStopped":`Tarefa interrompida`,"message.failure.accountSignedOut":`Interrompido porque você saiu de DeepSeek.`,"message.failure.interrupted":`O processo DSH foi encerrado antes do término deste turno (por exemplo, ele foi eliminado, travou ou expirou durante o desligamento), portanto, o turno foi encerrado quando DSH foi reiniciado. Chamadas de ferramentas inacabadas têm resultados desconhecidos.`,"message.failure.accountSignInRequired":`Faça login em DeepSeek e verifique se o destino da solicitação suporta autenticação de conta.`,"message.failure.quota":`Cota de solicitação esgotada.`,"message.turnError":`Este turno falhou`,"message.maxTokens":`Limite de token de saída atingido`,"message.maxTokens.hint":`A resposta foi cortada; a saída anterior é preservada na conversa. Envie "continuar" para permitir que o modelo seja retomado.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Uso do turno`,"message.turnUsage.consumed":`Uso {total}`,"message.turnUsage.model":`Provedor/modelo`,"message.turnUsage.cacheHit":`Acertos no cache`,"message.turnUsage.input":`Entrada sem cache`,"message.turnUsage.cacheRead":`Entrada em cache`,"message.turnUsage.cacheWrite":`Gravação em cache`,"message.turnUsage.output":`Saída`,"message.turnUsage.reasoning":` ({tokens} raciocínio)`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Correndo…`,"command.failed":`Falha no comando`,"command.done":`Concluído`,"command.title":`Comando`,"row.running":`Correndo`,"row.failed":`Falha`,"json.truncated":`… truncado, {total} caracteres no total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};function compactionRows(ctx){const compactionPreview=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(false);const t=ctx.locale.bind(NS);let lifetime;ctx.inject([`documentPreviews`],scope=>scope.effect(()=>{const controller=new AbortController;lifetime=controller;compactionPreview.set(true);return()=>{controller.abort();lifetime=void 0;compactionPreview.set(false)}}));return sessionId=>({hooks:{compactionPreview},async openCompaction(summarySeq,signal){if(lifetime===void 0)return null;const child=ctx.sessions.subagentAddress(sessionId);const address=child===void 0?{kind:`session`,sessionId}:{kind:`subagent`,...child};const active=AbortSignal.any([signal,lifetime.signal]);const cancelled=()=>active.aborted;if(cancelled())return null;let result;try{result=await ctx.remote.session.events({address,throughSeq:summarySeq,maxMessages:1},active)}catch(_error){return cancelled()?null:t(`message.compaction.readFailed`)}if(cancelled())return null;if(!result.ok)return t(`message.compaction.readFailed`);const event=result.value.records.find(entry=>entry.event.seq===summarySeq)?.event;const text=event&&summaryText(event);if(text===void 0)return t(`message.compaction.notFound`);const identity=address.kind===`session`?[address.sessionId]:[address.parentSessionId,address.childSessionId,address.mode];ctx.sidebarRight.openContent(`compaction-summary`,{summaryMarkdown:text},{key:JSON.stringify([...identity,summarySeq])});return null}})}function summaryText(event){if(event.type!==`compaction/summary`)return void 0;const data=event.data;if(typeof data!==`object`||data===null||!(`summary`in data)||!Array.isArray(data.summary))return void 0;const text=[];const blocks=data.summary;for(const block of blocks){if(typeof block!==`object`||block===null||!(`type`in block))return void 0;if(block.type!==`text`)continue;if(!(`text`in block)||typeof block.text!==`string`)return void 0;text.push(block.text)}const markdown=text.join(``);return markdown.trim()===``?void 0:markdown}function reasoningText(text){if(text[0]!==`<`)return text;const opening=`<signature>`;if(opening.startsWith(text))return``;if(!text.startsWith(opening))return text;const end=text.indexOf(`</signature>`,11);if(end===-1)return``;let start=end+12;while(start<text.length)if(text[start]===`
13
+ `||c===`\r`||c===` `}function isHex(c){return c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`}var PartialArguments=class PartialArguments{static EMPTY=PartialArguments.fromObject({});static fromText(text){const view=new PartialArguments;view.append(text);view.sealed=true;return view}static fromObject(value){const view=new PartialArguments;view.object=typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{};view.sealed=true;return view}chunks=[];object;sealed=false;#ends=[];#size=0;#consumed=0;#mode=`root`;#escape=false;#keyStart=0;#keyEscaped=false;#key=``;#current=null;#nestedEnds=[];#nestedInString=false;#invalidAt;#invalidValue=false;#entries=new Map;#order=[];#reads=new Map;get isSealed(){return this.sealed}get invalid(){this.scan();return this.#mode===`invalid`||this.#invalidValue}append(fragment){if(this.sealed)throw new Error(`PartialArguments: cannot append to a sealed view`);if(fragment.length===0)return;this.chunks.push(fragment);this.#size+=fragment.length;this.#ends.push(this.#size)}settle(text){if(this.object!==void 0||text.length!==this.#size)return PartialArguments.fromText(text);let offset=0;for(const chunk of this.chunks){if(!text.startsWith(chunk,offset))return PartialArguments.fromText(text);offset+=chunk.length}this.chunks=text.length===0?[]:[text];this.#ends=text.length===0?[]:[text.length];this.sealed=true;return this}refresh(){if(this.#reads.size===0)return false;this.scan();let changed=false;let completions=false;for(const read of this.#reads.values()){if(read.completion){completions=true;continue}changed=this.refreshRead(read)||changed}if(completions){for(const read of this.#reads.values())if(read.completion)changed=this.refreshRead(read)||changed}if(this.sealed)this.#reads.clear();return changed}refreshRead(read){const now=read.answer();if(Object.is(now,read.last))return false;read.last=now;return true}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),keys=>keys.length)}has(key){return this.remember(`has`,key,()=>this.hasNow(key))}complete(key){return this.remember(`complete`,key,()=>this.completeNow(key))}stringLength(key,options){const step=Math.max(1,Math.floor(options?.step??1));const offset=options?.offset??0;return this.remember(`length:${step}:${offset}`,key,()=>this.lengthNow(key),length=>length===void 0?void 0:Math.ceil((length+offset)/step))}stringExceeds(key,maxLength){const limit=Math.max(0,Math.floor(maxLength));return this.remember(`exceeds:${limit}`,key,()=>(this.lengthNow(key,limit+1)??0)>limit)}text(key){return this.remember(`text`,key,()=>this.textNow(key))}textPrefix(key,maxLength){const limit=Math.max(1,Math.floor(maxLength));return this.remember(`prefix:${limit}`,key,()=>this.textPrefixNow(key,limit))}value(key){return this.remember(`value`,key,()=>this.valueNow(key))}remember(kind,key,read,comparison){this.scan();const result=read();if(!this.sealed){const id=`${kind}/${key}`;if(!this.#reads.has(id))this.#reads.set(id,{completion:kind===`complete`,answer:comparison===void 0?read:()=>comparison(read()),last:comparison===void 0?result:comparison(result)})}return result}closedNow(){return this.sealed||this.#mode===`closed`||this.#mode===`invalid`}keysNow(){return this.object===void 0?this.#order:Object.keys(this.object)}hasNow(key){return this.object===void 0?this.#entries.has(key):Object.hasOwn(this.object,key)}completeNow(key){if(this.object!==void 0)return Object.hasOwn(this.object,key);const entry=this.#entries.get(key);return entry!==void 0&&entry.end>=0&&(entry.kind===`string`?entry.invalidAt===void 0:!entry.invalid)}lengthNow(key,limit=Number.POSITIVE_INFINITY){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.length:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text!==void 0&&entry.text.at===entry.end)return entry.text.length;const read=entry.length??={at:entry.start,length:0,text:``};this.readString(entry,read,limit,false);return read.length}textNow(key){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text===void 0&&entry.end>=0&&entry.needsDecoding&&entry.invalidAt===void 0){let text;try{text=JSON.parse(`"${this.slice(entry.start,entry.end)}"`)}catch(_error){}if(text!==void 0)entry.text={at:entry.end,length:text.length,text}}const read=entry.text??={at:entry.start,length:0,text:``};this.readString(entry,read,Number.POSITIVE_INFINITY,true);return read.text}textPrefixNow(key,maxLength){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.slice(0,maxLength):void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;const prefixes=entry.prefixes??=new Map;let read=prefixes.get(maxLength);if(read===void 0){read={at:entry.start,length:0,text:``};prefixes.set(maxLength,read)}this.readString(entry,read,maxLength,true);return read.text}valueNow(key){if(this.object!==void 0){if(!Object.hasOwn(this.object,key))return void 0;const field=this.object[key];return typeof field===`string`?void 0:field}const entry=this.#entries.get(key);if(entry?.kind!==`value`||entry.end<0||entry.invalid)return void 0;if(entry.parsed===void 0)try{entry.parsed=JSON.parse(this.slice(entry.start,entry.end))}catch(_error){entry.invalid=true;this.#invalidValue=true}return entry.parsed}chunkAt(at){let low=0;let high=this.#ends.length;while(low<high){const mid=low+high>>>1;if(this.#ends[mid]<=at)low=mid+1;else high=mid}return low}slice(start,end){if(start>=end)return``;const first=this.chunkAt(start);const last=this.chunkAt(end-1);const base=first===0?0:this.#ends[first-1];if(first===last)return this.chunks[first].slice(start-base,end-base);const parts=[this.chunks[first].slice(start-base)];for(let i=first+1;i<last;i++)parts.push(this.chunks[i]);parts.push(this.chunks[last].slice(0,end-this.#ends[last-1]));return parts.join(``)}readString(entry,read,limit,materialize){const end=Math.min(entry.end<0?this.#consumed:entry.end,entry.invalidAt??Number.POSITIVE_INFINITY,this.#invalidAt??Number.POSITIVE_INFINITY);if(!entry.needsDecoding){const length=Math.min(end-read.at,limit-read.length);if(length<=0)return;if(materialize)read.text+=this.slice(read.at,read.at+length);read.at+=length;read.length+=length;return}let chunkIndex=this.chunkAt(read.at);while(read.at<end&&read.length<limit){const base=chunkIndex===0?0:this.#ends[chunkIndex-1];const chunk=this.chunks[chunkIndex];const remaining=chunk.slice(read.at-base,Math.min(chunk.length,end-base));const boundary=remaining.search(CONTENT_ESCAPE);const length=Math.min(boundary<0?remaining.length:boundary,limit-read.length);if(length>0){if(materialize)read.text+=remaining.slice(0,length);read.at+=length;read.length+=length;if(read.at===base+chunk.length)chunkIndex++;continue}const type=remaining.length>1?remaining[1]:read.at+1<end?this.chunks[chunkIndex+1][0]:void 0;let decoded;let width=2;if(remaining[0]===`\\`&&type===void 0&&entry.end<0)return;if(remaining[0]===`\\`&&type===`u`){const hex=this.slice(read.at+2,Math.min(end,read.at+6));let valid=true;for(let i=0;i<hex.length;i++)if(!isHex(hex[i]))valid=false;if(valid){if(hex.length<4&&entry.end<0)return;if(hex.length===4)decoded=String.fromCharCode(Number.parseInt(hex,16))}width=6}else if(remaining[0]===`\\`&&type!==void 0)decoded=SIMPLE_ESCAPES[type];if(decoded===void 0){entry.invalidAt=read.at;this.#invalidValue=true;return}if(materialize)read.text+=decoded;read.length++;read.at+=width;while(chunkIndex<this.chunks.length&&read.at>=this.#ends[chunkIndex])chunkIndex++}}scan(){if(this.object!==void 0||this.#consumed===this.#size)return;for(let i=this.chunkAt(this.#consumed);i<this.chunks.length&&this.#invalidAt===void 0;i++){const pending=this.chunks[i];const base=i===0?0:this.#ends[i-1];for(let index=this.#consumed-base;index<pending.length&&this.#mode!==`invalid`;index++){if(this.#mode===`string`||this.#mode===`nested`&&this.#nestedInString){const end=this.stringBoundary(pending,index);this.#consumed+=end-index;index=end;if(index===pending.length)break}this.step(pending[index],this.#consumed);this.#consumed++}}}stringBoundary(fragment,start){let at=start;while(true){const quote=fragment.indexOf(`"`,at);const end=quote<0?fragment.length:quote;if(this.#mode===`string`){const entry=this.#current;if(!entry.needsDecoding&&CONTENT_ESCAPE.test(fragment.slice(at,end)))entry.needsDecoding=true}let slashStart=end;while(slashStart>at&&fragment[slashStart-1]===`\\`)slashStart--;const escaped=(end-slashStart)%2===1!==(slashStart===at&&this.#escape);this.#escape=quote<0&&escaped;if(quote<0||!escaped)return end;at=quote+1}}step(c,at){switch(this.#mode){case`root`:if(isWhitespace(c))return;if(c===`{`){this.#mode=`key-or-end`;return}this.fail();return;case`key-or-end`:if(isWhitespace(c))return;if(c===`}`){this.#mode=`closed`;return}if(c===`"`){this.beginKey(at);return}this.fail();return;case`key-only`:if(isWhitespace(c))return;if(c===`"`){this.beginKey(at);return}this.fail();return;case`key`:this.stepKey(c,at);return;case`colon`:if(isWhitespace(c))return;if(c===`:`){this.#mode=`value`;return}this.fail();return;case`value`:this.beginValue(c,at);return;case`string`:{const entry=this.#current;entry.end=at;this.#current=null;this.#mode=`comma-or-end`;return}case`scalar`:this.stepScalar(c,at);return;case`nested`:this.stepNested(c,at);return;case`comma-or-end`:if(isWhitespace(c))return;if(c===`,`){this.#mode=`key-only`;return}if(c===`}`){this.#mode=`closed`;return}this.fail();return;case`closed`:if(isWhitespace(c))return;this.fail();return;case`invalid`:return;default:assertNever(this.#mode)}}fail(){this.#invalidAt=this.#consumed;this.#mode=`invalid`;this.#current=null}beginKey(at){this.#mode=`key`;this.#keyStart=at+1;this.#keyEscaped=false;this.#escape=false}stepKey(c,at){if(c<` `){this.fail();return}if(this.#escape){this.#escape=false;return}if(c===`\\`){this.#escape=true;this.#keyEscaped=true;return}if(c!==`"`)return;const raw=this.slice(this.#keyStart,at);if(this.#keyEscaped)try{this.#key=JSON.parse(`"${raw}"`)}catch(_error){this.fail();return}else this.#key=raw;this.#mode=`colon`}open(entry){if(!this.#entries.has(this.#key))this.#order.push(this.#key);this.#entries.set(this.#key,entry);this.#current=entry}beginValue(c,at){if(isWhitespace(c))return;if(c===`"`){this.open({kind:`string`,start:at+1,end:-1,needsDecoding:false,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0});this.#escape=false;this.#mode=`string`;return}if(c===`}`||c===`,`||c===`:`||c===`]`){this.fail();return}this.open({kind:`value`,start:at,end:-1,parsed:void 0,invalid:false});if(c===`{`||c===`[`){this.#mode=`nested`;this.#nestedEnds=[c===`{`?`}`:`]`];this.#nestedInString=false;this.#escape=false;return}this.#mode=`scalar`}stepScalar(c,at){if(c!==`,`&&c!==`}`&&!isWhitespace(c))return;this.closeValue(at);this.#mode=c===`,`?`key-only`:c===`}`?`closed`:`comma-or-end`}stepNested(c,at){if(this.#nestedInString){this.#nestedInString=false;return}if(c===`"`){this.#nestedInString=true;return}if(c===`{`||c===`[`){this.#nestedEnds.push(c===`{`?`}`:`]`);return}if(c===`}`||c===`]`){if(this.#nestedEnds.pop()!==c){this.fail();return}if(this.#nestedEnds.length===0){this.closeValue(at+1);this.#mode=`comma-or-end`}}}closeValue(end){const entry=this.#current;entry.end=end;this.#current=null}};function assertNever(value,context){const rendered=JSON.stringify(value)??String(value);throw new Error(`unreachable variant${context?` in ${context}`:``}: ${rendered}`)}function hasAssistantReplyContent(blocks){return blocks.some(block=>{if(block.kind===`reasoning`||block.kind===`tool-call`)return false;if(block.kind===`text`)return block.text.trim()!==``;return true})}function sameTurnProcessSpec(left,right){return left.turn===right.turn&&left.controlAnchorSeq===right.controlAnchorSeq&&left.processStartSeq===right.processStartSeq&&left.answerAnchorSeq===right.answerAnchorSeq&&left.answerStep===right.answerStep&&left.inlineReasoning===right.inlineReasoning&&left.messageCount===right.messageCount&&left.toolCallCount===right.toolCallCount&&left.subagentCount===right.subagentCount}function isSubagentDelegationTool(name){return name===`subagent`||name.startsWith(`subagent_`)}function turnProcessAlwaysOpen(node){const location=node?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return false;const reason=location.turn.end?.data.reason.kind;return location.turn.status===`open`||reason===`aborted`||reason===`interrupted`||reason===`error`}function storedTurnProcessEntry(state,turn){return state.turnProcesses.find(entry=>entry.turn===turn)}function turnProcessOpen(state,spec,defaultOpen){const stored=storedTurnProcessEntry(state,spec.turn);if(stored===void 0||stored.answerStep!==(spec.answerStep??0))return defaultOpen;return stored.collapsed!==true}function createChatStore(){return(0,_deepseek_ai_dsh_client_store.defineStore)({init:()=>({turnProcesses:[]}),actions:{setTurnProcessOpen:(draft,turn,answerStep,open)=>{const index=draft.turnProcesses.findIndex(entry=>entry.turn===turn);const next=open?{turn,answerStep}:{turn,answerStep,collapsed:true};if(index<0)draft.turnProcesses.push(next);else draft.turnProcesses[index]=next}}})}function stepRunsGrouped(grouping,turnOpen,deferCollapse){return grouping===`collapsed`||grouping===`history`&&!turnOpen&&!deferCollapse}function processTitle(summary,t){const labels=summary.counts.slice(0,3).map(({kind})=>t(`message.stepProcess.done.${kind}`));const first=labels[0];if(first===void 0)return t(`message.stepProcess.done.thinking`);const continuation=label=>label.charAt(0).toLowerCase()+label.slice(1);const second=labels[1];if(second===void 0)return first;if(labels.length===2){const prefix=t(`message.stepProcess.sharedPrefix`);return t(`message.stepProcess.joinTwo`,{first,second:continuation(prefix!==``&&first.startsWith(prefix)&&second.startsWith(prefix)?second.slice(prefix.length):second)})}const title=[first,...labels.slice(1).map(continuation)].join(t(`message.stepProcess.comma`));return summary.counts.length>3?t(`message.stepProcess.more`,{title}):title}function thinkingTitle(summary,t){const first=summary.counts[0];if(first===void 0||first.kind===`context`)return t(`message.stepProcess.thinking`);return t(`message.stepProcess.thinkingNext`,{title:processTitle(summary,t)})}function turnDataOf(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.data:void 0}function turnOf$1(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.turn:void 0}const ChatNodeSeat=(0,react.memo)(function ChatNodeSeat({nodeKey,groupPart,useChatNode,useChatNodeProcess,usePresentation,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,useStore,actions,renderSlot,t,useChatNodeBottom,deferCollapse,useGroupAction}){const bottom=useChatNodeBottom(nodeKey);const node=useChatNode(nodeKey);const routedNode=node;const turn=turnOf$1(routedNode);const processPresentation=useChatNodeProcess(nodeKey);const processSpec=processPresentation?.spec;const storedOpen=useStore(state=>processSpec!==void 0&&turnProcessOpen(state,processSpec,bottom===true&&deferCollapse));const liveProcess=processPresentation!==void 0&&!processPresentation.turnClosed;const interleavedInput=processPresentation?.hasInterleavedInput===true;const alwaysOpen=liveProcess||interleavedInput||turnProcessAlwaysOpen(routedNode);const processOpen=alwaysOpen||storedOpen;const setOpen=(0,react.useCallback)(open=>{if(processSpec!==void 0&&!alwaysOpen)actions.setTurnProcessOpen(processSpec.turn,processSpec.answerStep??0,open)},[actions,processSpec,alwaysOpen]);const foldCompleted=usePresentation(policy=>policy.foldCompletedTurns);const keepReplies=usePresentation(policy=>policy.foldedReplies===`all`);const processWindowReady=processSpec!==void 0&&processPresentation!==void 0&&foldCompleted&&processPresentation.turn===processSpec.turn&&(processPresentation.turnStarted||processPresentation.turnClosed);const replyRow=keepReplies&&routedNode?.kind===`assistant-step`&&groupPart!==`reasoning`&&hasAssistantReplyContent(routedNode.data.blocks);const processMember=routedNode!==void 0&&processWindowReady&&!replyRow&&!isAtOrOutside(routedNode,`turn`)&&routedNode.anchorSeq>=processSpec.processStartSeq&&(liveProcess||processSpec.answerAnchorSeq===null||routedNode.anchorSeq<processSpec.answerAnchorSeq||groupPart===`reasoning`&&routedNode.kind===`assistant-step`&&routedNode.data.step===processSpec.answerStep);const processAnswer=routedNode!==void 0&&processWindowReady&&!liveProcess&&groupPart!==`reasoning`&&routedNode.kind===`assistant-step`&&routedNode.data.step===processSpec.answerStep;const ownsDisclosure=routedNode?.kind===`turn-process`||processAnswer||replyRow;const foldable=processWindowReady&&(liveProcess||processMember||ownsDisclosure);const turnProcess=(0,react.useMemo)(()=>processSpec===void 0?void 0:{spec:processSpec,foldable,hasContent:!interleavedInput&&(processSpec.inlineReasoning||(keepReplies?processPresentation?.hasNonReplyProcess===true:processPresentation?.hasExternalProcess===true)),open:processOpen,setOpen},[foldable,interleavedInput,keepReplies,processOpen,processSpec,processPresentation?.hasExternalProcess,processPresentation?.hasNonReplyProcess,setOpen]);const processHidden=routedNode?.kind===`turn-process`&&foldCompleted&&!foldable||foldable&&processMember&&!processOpen;const revealProcess=(0,react.useCallback)(()=>{if(processMember)setOpen(true)},[processMember,setOpen]);const truncatedLabel=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);const wrapperRef=useGroupAction(processHidden,revealProcess);const[disclosureReset]=(0,react.useState)(()=>(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(0));const turnData=turnDataOf(routedNode);const hookContext=(0,react.useMemo)(()=>({turnData,disclosureReset,useGroupAction,usePresentation}),[turnData,disclosureReset,useGroupAction,usePresentation]);(0,react.useEffect)(()=>{if(processMember&&processHidden&&wrapperRef.current!==null&&hiddenOrCollapsing(wrapperRef.current))disclosureReset.set(disclosureReset.getSnapshot()+1)},[processMember,processHidden,wrapperRef,disclosureReset]);const turnOpen=routedNode?.location.kind===`turn`||routedNode?.location.kind===`step`?routedNode.location.turn.status===`open`:false;const stepRunsGroupedHere=usePresentation(policy=>stepRunsGrouped(policy.stepGrouping,turnOpen,bottom===true&&deferCollapse));const owner=(0,react.useMemo)(()=>node===void 0?null:{...groupPart===void 0?{}:{groupPart},cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,turnProcess,stepRunsGrouped:stepRunsGroupedHere},[node,groupPart,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage,turnProcess,stepRunsGroupedHere]);if(routedNode===void 0||owner===null)return null;const routedOwner={...owner,node:routedNode};const flowKey=groupPart===void 0||groupPart===`response`?routedNode.key:JSON.stringify([routedNode.key,groupPart]);return(0,react_jsx_runtime.jsx)(`div`,{ref:wrapperRef,className:ChatView_module_css_default.flowItem,"data-chat-anchor-key":flowKey,"data-chat-flow-key":flowKey,"data-chat-paging-anchor":routedNode.kind!==`turn-process`||void 0,"data-chat-node-key":routedNode.key,"data-chat-group-part":groupPart,"data-chat-flow-kind":routedNode.kind,"data-chat-turn":turn,"data-turn-process-member":processMember||void 0,"data-turn-process-hidden":processHidden||void 0,children:renderSlot(`conversation.chat.node`,routedOwner,{entryKey:routedNode.kind,hookContext,fallback:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownSurface`,{type:routedNode.kind}),payload:routedNode.data,truncatedLabel})})})});function chatRenderKey(entry){switch(entry.kind){case`node`:return JSON.stringify([`node`,entry.key,entry.groupPart??null]);case`group`:return JSON.stringify([`group`,entry.key]);default:return assertNever(entry)}}function useDisclosure(version=0){const[expandedVersion,setExpandedVersion]=(0,react.useState)(null);return{expanded:expandedVersion===version,setExpanded:(0,react.useCallback)(open=>{setExpandedVersion(open?version:null)},[version]),toggle:(0,react.useCallback)(()=>{setExpandedVersion(previous=>previous===version?null:version)},[version])}}function bindDisclosure(reset){const subscribe=listener=>reset.subscribe(listener);const getSnapshot=()=>reset.getSnapshot();return function useBoundDisclosure(){return useDisclosure((0,react.useSyncExternalStore)(subscribe,getSnapshot))}}const AT_REST={canScrollUp:false,canScrollDown:false};const SCROLL_KEYS=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function useProcessScroll(bodyRef,contentRef,open,grouped){const follow=useScrollFollow(false,1);const initialPosition=(0,react.useRef)(null);const[edges,setEdges]=(0,react.useState)(AT_REST);const initialize=(0,react.useCallback)(position=>{initialPosition.current=position},[]);const sync=(0,react.useCallback)(cause=>{const body=bodyRef.current;let next=AT_REST;if(body!==null&&body.closest(`[hidden], [data-group-expanded-mode]`)===null){let metrics=scrollMetrics(body);const initial=cause===`resize`?initialPosition.current:null;if(initial!==null){metrics=follow.jump(body,metrics,initial===`bottom`?metrics.floor:0);if(initial===`top`)follow.setFollowing(false);initialPosition.current=null}else{const wasAnimating=follow.animating;if(cause===`scrollend`)follow.settle(metrics);else follow.sample(metrics);if(follow.active&&(cause===`resize`||cause===`scrollend`&&wasAnimating))metrics=follow.toBottom(body,metrics,`smooth`)}next={canScrollUp:metrics.top>1,canScrollDown:metrics.top<metrics.floor-1}}else follow.reset();setEdges(previous=>previous.canScrollUp===next.canScrollUp&&previous.canScrollDown===next.canScrollDown?previous:next)},[bodyRef,follow]);const interrupt=(0,react.useCallback)(()=>{const body=bodyRef.current;if(body!==null&&follow.animating)follow.interrupt(body,scrollMetrics(body))},[bodyRef,follow]);const events=(0,react.useMemo)(()=>({onScroll:()=>{sync(`scroll`)},onWheel:interrupt,onTouchStart:interrupt,onPointerDown:interrupt,onKeyDown:event=>{if(!event.defaultPrevented&&SCROLL_KEYS.has(event.key))interrupt()}}),[interrupt,sync]);(0,react.useLayoutEffect)(()=>{interrupt();follow.reset();if(!grouped||!open)initialPosition.current=null},[follow,grouped,interrupt,open]);(0,react.useLayoutEffect)(()=>{const body=bodyRef.current;if(body===null||!open||typeof ResizeObserver===`undefined`)return;const unbind=follow.bind(body);const observer=new ResizeObserver(()=>{sync(`resize`)});const onScrollEnd=event=>{if(event.target===body)sync(`scrollend`)};body.addEventListener(`scrollend`,onScrollEnd);observer.observe(body);if(contentRef.current!==null)observer.observe(contentRef.current);return()=>{unbind();observer.disconnect();body.removeEventListener(`scrollend`,onScrollEnd)}},[bodyRef,contentRef,follow,open,sync]);return{edges,events,initialize}}var ChatGroupSeat_module_css_default={"activityIcon":`O_Ebla_activityIcon`,"body":`O_Ebla_body`,"chevron":`O_Ebla_chevron`,"content":`O_Ebla_content`,"expandedBody":`O_Ebla_expandedBody`,"fadeBottom":`O_Ebla_fadeBottom`,"fadeTop":`O_Ebla_fadeTop`,"label":`O_Ebla_label`,"leading":`O_Ebla_leading`,"root":`O_Ebla_root`,"title":`O_Ebla_title`};const PROCESS_TITLE_MINIMUM_MS=150;const PROCESS_ICONS={thinking:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconThinkOutlineRegular,{}),read:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),readImage:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),search:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconSearchOutlineRegular,{size:14}),edit:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconEditOutlineRegular,{size:14}),write:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconEditOutlineRegular,{size:14}),commands:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{}),code:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCodeOutlineRegular,{size:14}),webSearch:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconGlobeOutlineRegular,{}),webFetch:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),subagents:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconAgentPresetOutlineRegular,{size:14}),plan:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconPlanOutlineRegular,{}),questions:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconQuestionOutlineRegular,{}),tools:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconSparkleRegular,{size:14}),context:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,{size:14})};function sameLiveProcessTitle(left,right){return left.activity===right.activity&&left.detail===right.detail&&left.preparing===right.preparing&&left.thinking===right.thinking}function useStableLiveProcessTitle(desired,active){const[displayed,setDisplayed]=(0,react.useState)(desired);const displayedRef=(0,react.useRef)(displayed);const desiredRef=(0,react.useRef)(desired);const displayedAtRef=(0,react.useRef)(Date.now());(0,react.useEffect)(()=>{desiredRef.current=desired;if(!active||sameLiveProcessTitle(displayedRef.current,desired))return;const remaining=PROCESS_TITLE_MINIMUM_MS-(Date.now()-displayedAtRef.current);const commit=()=>{const next=desiredRef.current;displayedRef.current=next;displayedAtRef.current=Date.now();setDisplayed(next)};if(remaining<=0){commit();return}const timer=setTimeout(commit,remaining);return()=>{clearTimeout(timer)}},[active,desired.activity,desired.detail,desired.preparing,desired.thinking]);return active?displayed:desired}const GroupMembers=(0,react.memo)(function GroupMembers({members,...props}){return members.map(member=>(0,react.createElement)(ChatNodeSeat,{...props,key:chatRenderKey(member),nodeKey:member.key,...member.groupPart===void 0?{}:{groupPart:member.groupPart}}))});const ProcessGroupHeader=(0,react.memo)(function ProcessGroupHeader({groupKey,useChatGroup,usePresentation,t,open,bodyId,toggle}){const data=useChatGroup(groupKey,group=>group?.data);const detailed=usePresentation(policy=>data?.closed===false&&policy.liveProcessDetail);const live=useStableLiveProcessTitle({activity:data?.summary.running??`thinking`,detail:data?.summary.runningDetail??``,preparing:data?.summary.preparing===true,thinking:data===void 0||data.closed||data.summary.running!==void 0?``:thinkingTitle(data.summary,t)},data!==void 0&&!data.closed);if(data===void 0)return null;const label=data.closed?processTitle(data.summary,t):live.preparing?t(`message.stepProcess.prepare.${live.activity===`thinking`?`tools`:live.activity}`):live.activity===`thinking`?live.thinking:t(`message.stepProcess.${live.activity}`);const detail=detailed&&!data.closed?live.detail:``;const title=detail===``?label:`${label}${t(`message.turnProcess.separator`)}${detail}`;const activity=data.closed?data.summary.counts[0]?.kind??`thinking`:live.activity;return(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:ChatGroupSeat_module_css_default.title,"aria-expanded":open,"aria-controls":bodyId,"data-process-activity":activity,onClick:event=>{event.currentTarget.focus();toggle()},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:ChatGroupSeat_module_css_default.leading,"aria-hidden":`true`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChatGroupSeat_module_css_default.activityIcon,"data-step-process-icon":true,children:PROCESS_ICONS[activity]}),(0,react_jsx_runtime.jsx)(`span`,{className:ChatGroupSeat_module_css_default.chevron,"data-step-process-chevron":true,children:open?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronUpOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{})})]}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{active:!data.closed,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{className:ChatGroupSeat_module_css_default.label,children:title})})]})});const ChatGroupSeat=(0,react.memo)(function ChatGroupSeat({groupKey,useChatGroup,useGroupHeaderAction,...props}){const members=useChatGroup(groupKey,group=>group?.members);const turn=useChatGroup(groupKey,group=>group?.data.turn);const closed=useChatGroup(groupKey,group=>group?.data.closed);const foldCompleted=props.usePresentation(policy=>policy.foldCompletedTurns);const{expanded:open,setExpanded:setOpen}=useDisclosure();const firstKey=members?.[0]?.key??``;const deferCollapse=props.useChatNodeBottom(firstKey)===true&&props.deferCollapse;const presentation=props.useChatNodeProcess(firstKey);const turnLocation=props.useChatNode(firstKey,node=>{const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0});const grouped=props.usePresentation(policy=>stepRunsGrouped(policy.stepGrouping,turnLocation?.status===`open`,deferCollapse));const reason=turnLocation?.end?.data.reason.kind;const alwaysOpen=presentation?.turnClosed===false||presentation?.hasInterleavedInput===true||reason===`aborted`||reason===`interrupted`||reason===`error`;const spec=presentation?.spec;const selectOpen=(0,react.useCallback)(state=>spec!==void 0&&turnProcessOpen(state,spec,deferCollapse),[spec,deferCollapse]);const storedOpen=props.useStore(selectOpen);const outerHidden=foldCompleted&&presentation?.turnClosed===true&&spec!==void 0&&!alwaysOpen&&!storedOpen;const revealOuter=(0,react.useCallback)(()=>{if(spec!==void 0&&!alwaysOpen)props.actions.setTurnProcessOpen(spec.turn,spec.answerStep??0,true)},[props.actions,spec,alwaysOpen]);const rootRef=props.useGroupAction(outerHidden,revealOuter);const headerRef=(0,react.useRef)(null);const deferCompletedTurns=props.usePresentation(policy=>policy.collapseTiming===`next-input`);useGroupHeaderAction(headerRef,!grouped||deferCompletedTurns&&outerHidden);(0,react.useEffect)(()=>{if(outerHidden&&rootRef.current!==null&&hiddenOrCollapsing(rootRef.current))setOpen(false)},[outerHidden,rootRef,setOpen]);const reveal=(0,react.useCallback)(()=>{setOpen(true)},[setOpen]);const bodyRef=props.useGroupAction(grouped&&!open,reveal);const contentRef=(0,react.useRef)(null);const bodyId=(0,react.useId)();const{edges,events,initialize}=useProcessScroll(bodyRef,contentRef,open,grouped);const toggle=(0,react.useCallback)(()=>{if(!open)initialize(closed===false?`bottom`:`top`);setOpen(!open)},[closed,initialize,open,setOpen]);const shownCap=!grouped?false:open?true:void 0;const[closingCap,setClosingCap]=(0,react.useState)(shownCap??true);if(shownCap!==void 0&&shownCap!==closingCap)setClosingCap(shownCap);if(members===void 0)return null;const capped=grouped&&(!deferCompletedTurns||(shownCap??closingCap));const classes=[ChatGroupSeat_module_css_default.body,!capped?ChatGroupSeat_module_css_default.expandedBody:``,capped&&edges.canScrollUp?ChatGroupSeat_module_css_default.fadeTop:``,capped&&edges.canScrollDown?ChatGroupSeat_module_css_default.fadeBottom:``];return(0,react_jsx_runtime.jsxs)(`div`,{ref:rootRef,className:ChatGroupSeat_module_css_default.root,"data-chat-group-key":groupKey,"data-chat-flow-key":groupKey,"data-chat-anchor-key":`group:${groupKey}`,"data-chat-turn":turn,"data-chat-paging-anchor":grouped&&!open||void 0,"data-step-process":true,"data-group-expanded-mode":!grouped||void 0,children:[(0,react_jsx_runtime.jsx)(`div`,{ref:headerRef,children:(0,react_jsx_runtime.jsx)(ProcessGroupHeader,{groupKey,useChatGroup,usePresentation:props.usePresentation,t:props.t,open,bodyId,toggle})}),(0,react_jsx_runtime.jsx)(`div`,{ref:bodyRef,id:bodyId,className:classes.join(` `),"data-step-process-body":true,"data-scroll-up":edges.canScrollUp||void 0,"data-scroll-down":edges.canScrollDown||void 0,...events,children:(0,react_jsx_runtime.jsx)(`div`,{ref:contentRef,className:ChatGroupSeat_module_css_default.content,"data-step-process-content":true,"data-chat-flow":``,children:(0,react_jsx_runtime.jsx)(GroupMembers,{...props,members})})})]})});var accessibility_module_css_default={"visuallyHidden":`TTCZqG_visuallyHidden`};var CommandStatusRow_module_css_default={"body":`kWGFkG_body`,"leading":`kWGFkG_leading`,"root":`kWGFkG_root`,"separator":`kWGFkG_separator`,"summary":`kWGFkG_summary`,"title":`kWGFkG_title`};const COMMAND_ICON=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{size:14});const CommandStatusRow=(0,react.memo)(function CommandStatusRow({title,state,summary,body,t}){const[expanded,setExpanded]=(0,react.useState)(false);const running=state===`running`;const open=expanded&&body!==null;const toggle=(0,react.useCallback)(()=>{setExpanded(value=>!value)},[]);const collapsedContent=(0,react.useMemo)(()=>(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:CommandStatusRow_module_css_default.separator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:CommandStatusRow_module_css_default.summary,"data-error":state===`error`||void 0,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{children:summary})})]}),[state,summary]);const content=(0,react.useMemo)(()=>open?(0,react_jsx_runtime.jsx)(`pre`,{className:CommandStatusRow_module_css_default.body,"data-error":state===`error`||void 0,children:body}):void 0,[body,open,state]);return(0,react_jsx_runtime.jsxs)(`div`,{className:CommandStatusRow_module_css_default.root,"data-variant":`others`,"data-state":state,children:[state===`running`&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.running`)}),state===`error`&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.failed`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{leadingClassName:CommandStatusRow_module_css_default.leading,titleClassName:CommandStatusRow_module_css_default.title,icon:COMMAND_ICON,title,running,open,expandable:body!==null,expandOnRowClick:true,keepContentWhenOpen:true,onToggle:toggle,collapsedContent,children:content})]})});var MessageItem_module_css_default={"attachmentRow":`Sixlwa_attachmentRow`,"compactionButton":`Sixlwa_compactionButton`,"compactionContextIcon":`Sixlwa_compactionContextIcon`,"compactionLeading":`Sixlwa_compactionLeading`,"compactionOpenIcon":`Sixlwa_compactionOpenIcon`,"compactionRow":`Sixlwa_compactionRow`,"compactionSep":`Sixlwa_compactionSep`,"compactionSummary":`Sixlwa_compactionSummary`,"compactionTitle":`Sixlwa_compactionTitle`,"contextRow":`Sixlwa_contextRow`,"fileCard":`Sixlwa_fileCard`,"fileContent":`Sixlwa_fileContent`,"fileIcon":`Sixlwa_fileIcon`,"fileMeta":`Sixlwa_fileMeta`,"fileName":`Sixlwa_fileName`,"inheritedHistoryCaption":`Sixlwa_inheritedHistoryCaption`,"inheritedHistoryIcon":`Sixlwa_inheritedHistoryIcon`,"inheritedHistoryLabel":`Sixlwa_inheritedHistoryLabel`,"inheritedHistoryLine":`Sixlwa_inheritedHistoryLine`,"inheritedHistoryRow":`Sixlwa_inheritedHistoryRow`,"maxTokensTitle":`Sixlwa_maxTokensTitle`,"referenceSummary":`Sixlwa_referenceSummary`,"retryBesideGroups":`Sixlwa_retryBesideGroups`,"retryDetailLabel":`Sixlwa_retryDetailLabel`,"retryDetails":`Sixlwa_retryDetails`,"retryLeading":`Sixlwa_retryLeading`,"retryProgress":`Sixlwa_retryProgress`,"retryRow":`Sixlwa_retryRow`,"retrySeparator":`Sixlwa_retrySeparator`,"retryTitle":`Sixlwa_retryTitle`,"turnErrorCode":`Sixlwa_turnErrorCode`,"turnErrorCopy":`Sixlwa_turnErrorCopy`,"turnErrorDot":`Sixlwa_turnErrorDot`,"turnErrorMessage":`Sixlwa_turnErrorMessage`,"turnErrorRow":`Sixlwa_turnErrorRow`,"turnErrorTitle":`Sixlwa_turnErrorTitle`,"userRow":`Sixlwa_userRow`,"userStack":`Sixlwa_userStack`};const CompactionItem=(0,react.memo)(function CompactionItem({node,openCompaction,title,fallbackSummary,t}){const summarySeq=node.summaryEventSeq;const available=openCompaction!==void 0&&summarySeq!==null;const pending=(0,react.useRef)(null);const[opening,setOpening]=(0,react.useState)(false);const[failure,setFailure]=(0,react.useState)(null);(0,react.useEffect)(()=>{pending.current=null;setOpening(false);setFailure(null);return()=>{pending.current?.abort()}},[node.seq,summarySeq,openCompaction]);const open=async()=>{if(!available||pending.current!==null)return;const controller=new AbortController;pending.current=controller;setOpening(true);setFailure(null);try{const result=await openCompaction(summarySeq,controller.signal);if(!controller.signal.aborted)setFailure(result)}catch(error){if(!controller.signal.aborted)setFailure(error instanceof Error?error.message:String(error))}finally{if(pending.current===controller)pending.current=null;if(!controller.signal.aborted)setOpening(false)}};const summary=node.shadowedItemCount!==null&&node.shadowedTokenCount!==null?t(`message.compaction.completed`,{items:node.shadowedItemCount,tokens:node.shadowedTokenCount}):fallbackSummary??t(`message.compaction.landed`);const action=t(`message.compaction.open`);return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.compactionRow,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:action,side:`top`,portal:true,delayMs:200,disabled:!available,children:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:MessageItem_module_css_default.compactionButton,disabled:!available||opening,"aria-busy":opening,"data-compaction-seq":node.seq,onClick:()=>{open()},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.compactionLeading,"aria-hidden":true,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionContextIcon,"data-compaction-icon":`context`,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconApiOutlineRegular,{})}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionOpenIcon,"data-compaction-icon":`open`,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronRightOutlineRegular,{})})]}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionTitle,children:title??t(`message.compaction`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionSep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.compactionSummary,children:summary}),available&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:action})]})}),failure!==null&&(0,react_jsx_runtime.jsx)(`p`,{role:`alert`,children:failure})]})});var ContextBody_module_css_default={"catalogNotice":`ZkiH0q_catalogNotice`,"entries":`ZkiH0q_entries`,"entry":`ZkiH0q_entry`,"entryDescription":`ZkiH0q_entryDescription`,"entryName":`ZkiH0q_entryName`,"field":`ZkiH0q_field`,"fieldKey":`ZkiH0q_fieldKey`,"fieldValue":`ZkiH0q_fieldValue`,"fields":`ZkiH0q_fields`,"file":`ZkiH0q_file`,"fileAction":`ZkiH0q_fileAction`,"filePath":`ZkiH0q_filePath`,"files":`ZkiH0q_files`,"recall":`ZkiH0q_recall`,"recallCounts":`ZkiH0q_recallCounts`,"recallLabel":`ZkiH0q_recallLabel`,"recalls":`ZkiH0q_recalls`,"relaySender":`ZkiH0q_relaySender`,"section":`ZkiH0q_section`,"sectionName":`ZkiH0q_sectionName`,"sectionNotice":`ZkiH0q_sectionNotice`,"sectionText":`ZkiH0q_sectionText`,"sections":`ZkiH0q_sections`,"text":`ZkiH0q_text`};const MAX_CHARS=2e4;const MAX_ENTRIES=200;function asRecord$1(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:null}function contentRuns(content){const runs=[];for(const block of content){if(block.type!==`text`){runs.push({block});continue}const last=runs[runs.length-1];if(last!==void 0&&`text`in last)last.text+=block.text;else runs.push({text:block.text})}return runs}function unknownBlocks(content){return contentRuns(content).flatMap(run=>`block`in run?[run.block]:[])}function boundedText(text,t){return text.length>MAX_CHARS?`${text.slice(0,MAX_CHARS)}\n${t(`json.truncated`,{total:text.length})}`:text}function fieldValue(value,t){return boundedText(typeof value===`string`?value:typeof value===`number`||typeof value===`boolean`?String(value):JSON.stringify(value),t)}function SourceFields({source,formRendered,t}){const record=asRecord$1(source);if(record===null)return null;const hidden=formRendered?[`kind`,`form`]:[`kind`];const rows=Object.entries(record).filter(([key])=>!hidden.includes(key));if(rows.length===0)return null;return(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.fields,"data-context-fields":true,children:rows.map(([key,value])=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.field,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.fieldKey,children:key}),(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.fieldValue,children:fieldValue(value,t)})]},key))})}function UnknownBlocks({blocks,t}){const truncatedLabel=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children:blocks.map((block,index)=>(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:block,truncatedLabel},index))})}function ModelFacingContent({content,t}){const truncatedLabel=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children:contentRuns(content).map((run,index)=>`text`in run?run.text!==``&&(0,react_jsx_runtime.jsx)(`pre`,{className:ContextBody_module_css_default.text,"data-context-text":true,children:boundedText(run.text,t)},index):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:run.block,truncatedLabel},index))})}function OpaqueBody({content,source,t}){return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t}),(0,react_jsx_runtime.jsx)(SourceFields,{source,formRendered:false,t})]})}function instructionChanges(source){const record=asRecord$1(source);const list=record===null?void 0:record[`changes`];if(!Array.isArray(list))return null;const changes=[];const seen=new Set;for(const entry of list){const change=asRecord$1(entry);if(change===null)return null;const path=change[`path`];if(typeof path!==`string`||path===``)return null;const action=change[`action`];if(action!==`set`&&action!==`replace`&&action!==`remove`)return null;const digest=change[`digest`];if(seen.has(path))continue;seen.add(path);changes.push({action,path,...typeof digest===`string`?{digest}:{}})}return changes.length===0?null:changes}function instructionAction(action,baseline){if(action===`remove`)return`message.context.instructions.removed`;if(baseline)return`message.context.instructions.loaded`;return action===`set`?`message.context.instructions.added`:`message.context.instructions.updated`}function InstructionsBody({content,source,t}){const changes=instructionChanges(source);if(changes===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});const baseline=asRecord$1(source)?.[`baseline`]===true;return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.files,"data-context-files":true,children:changes.map(change=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.file,title:change.digest,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.filePath,children:change.path}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.fileAction,children:t(instructionAction(change.action,baseline))})]},change.path))}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function catalogEntries(source){const record=asRecord$1(source);const list=record===null?void 0:record[`entries`];if(!Array.isArray(list))return null;const entries=[];for(const item of list){const entry=asRecord$1(item);if(entry===null)return null;const name=entry[`name`];const description=entry[`description`];if(typeof name!==`string`||name===``||typeof description!==`string`)return null;entries.push({name,description})}return entries}function CatalogBody({content,source,t}){const entries=catalogEntries(source);if(entries===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});const update=asRecord$1(source)?.[`update`]===true;const shown=entries.slice(0,MAX_ENTRIES);const rest=unknownBlocks(content);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[update&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-catalog-update":true,children:t(`message.context.catalog.replaced`)}),(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.entries,"data-context-entries":true,children:shown.map((entry,index)=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.entry,children:[(0,react_jsx_runtime.jsx)(`code`,{className:ContextBody_module_css_default.entryName,children:entry.name}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.entryDescription,children:entry.description})]},index))}),shown.length<entries.length&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-entries-truncated":true,children:t(`message.context.catalog.more`,{count:entries.length-shown.length})}),(0,react_jsx_runtime.jsx)(UnknownBlocks,{blocks:rest,t})]})}function snapshotSections(source){const record=asRecord$1(source);const list=record===null?void 0:record[`sections`];if(!Array.isArray(list))return null;const sections=[];for(const item of list){const section=asRecord$1(item);if(section===null)return null;const name=section[`name`];const text=section[`text`];if(typeof name!==`string`||name===``||typeof text!==`string`)return null;sections.push({name,text})}return sections.length===0?null:sections}function SnapshotBody({content,source,t}){const sections=snapshotSections(source);if(sections===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-context-snapshot-supersedes":true,children:t(`message.context.snapshot.supersedes`)}),(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.sections,"data-context-sections":true,children:sections.map((section,index)=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.section,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.sectionName,children:section.name}),(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionText,children:boundedText(section.text,t)})]},index))})]})}function SystemSectionsBody({message,t}){return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[message.reset&&(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-system-reset":true,children:t(`message.systemPromptReset`)}),message.notices.map((notice,index)=>(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.catalogNotice,"data-system-notice":true,children:boundedText(notice,t)},index)),(0,react_jsx_runtime.jsx)(`dl`,{className:ContextBody_module_css_default.sections,"data-system-sections":true,children:message.changes.map(change=>(0,react_jsx_runtime.jsxs)(`div`,{className:ContextBody_module_css_default.section,"data-system-section":change.change,children:[(0,react_jsx_runtime.jsx)(`dt`,{className:ContextBody_module_css_default.sectionName,children:t(`message.systemSection.${change.change}`,{name:change.name})}),change.notices.map((notice,index)=>(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionNotice,"data-system-notice":true,children:boundedText(notice,t)},index)),change.text!==``&&(0,react_jsx_runtime.jsx)(`dd`,{className:ContextBody_module_css_default.sectionText,children:boundedText(change.text,t)})]},change.name))})]})}function NoticeBody({content,t}){return(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})}function RelayBody({content,source,t}){const sender=relaySender(source);if(sender===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`p`,{className:ContextBody_module_css_default.relaySender,"data-context-relay-sender":true,children:t(`message.context.relay.from`,{session:sender})}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function relaySender(source){const sender=asRecord$1(source)?.[`senderSessionId`];return typeof sender===`string`&&sender!==``?sender:null}function recalledSessions(source){const record=asRecord$1(source);const list=record===null?void 0:record[`references`];if(!Array.isArray(list))return null;const sessions=[];for(const item of list){const reference=asRecord$1(item);if(reference===null)return null;const label=reference[`label`];const retained=reference[`retainedMessages`];const omitted=reference[`omittedMessages`];const truncated=reference[`truncated`];if(typeof label!==`string`||label===``||typeof retained!==`number`||typeof omitted!==`number`||typeof truncated!==`boolean`)return null;sessions.push({label,retained,omitted,truncated})}return sessions.length===0?null:sessions}function RecallBody({content,source,t}){const sessions=recalledSessions(source);if(sessions===null)return(0,react_jsx_runtime.jsx)(OpaqueBody,{content,source,t});return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`ul`,{className:ContextBody_module_css_default.recalls,"data-context-recalls":true,children:sessions.map((session,index)=>(0,react_jsx_runtime.jsxs)(`li`,{className:ContextBody_module_css_default.recall,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallLabel,children:session.label}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallCounts,children:t(`message.context.recall.counts`,{retained:session.retained,omitted:session.omitted})}),session.truncated&&(0,react_jsx_runtime.jsx)(`span`,{className:ContextBody_module_css_default.recallCounts,children:t(`message.context.recall.truncated`)})]},index))}),(0,react_jsx_runtime.jsx)(ModelFacingContent,{content,t})]})}function noticeSummary(source){const summary=asRecord$1(source)?.[`summary`];return typeof summary===`string`&&summary!==``?summary:null}function contextBody(form,props){const opaque={rendered:null,summary:null,body:(0,react_jsx_runtime.jsx)(OpaqueBody,{...props})};switch(form){case`instructions`:return instructionChanges(props.source)===null?opaque:{rendered:`instructions`,summary:null,body:(0,react_jsx_runtime.jsx)(InstructionsBody,{...props})};case`catalog`:return catalogEntries(props.source)===null?opaque:{rendered:`catalog`,summary:null,body:(0,react_jsx_runtime.jsx)(CatalogBody,{...props})};case`snapshot`:return snapshotSections(props.source)===null?opaque:{rendered:`snapshot`,summary:null,body:(0,react_jsx_runtime.jsx)(SnapshotBody,{...props})};case`notice`:{const summary=noticeSummary(props.source);return summary===null?opaque:{rendered:`notice`,summary,body:(0,react_jsx_runtime.jsx)(NoticeBody,{...props})}}case`relay`:return relaySender(props.source)===null?opaque:{rendered:`relay`,summary:null,body:(0,react_jsx_runtime.jsx)(RelayBody,{...props})};case`recall`:return recalledSessions(props.source)===null?opaque:{rendered:`recall`,summary:null,body:(0,react_jsx_runtime.jsx)(RecallBody,{...props})};case null:return opaque;default:throw new Error(`unreachable context form: ${String(form)}`)}}var ContextInjectionRow_module_css_default={"body":`XrJvXW_body`,"chevron":`XrJvXW_chevron`,"root":`XrJvXW_root`,"sep":`XrJvXW_sep`,"source":`XrJvXW_source`,"summary":`XrJvXW_summary`,"toolChanges":`XrJvXW_toolChanges`};function ContextInjectionRow({content,source,producer,form,t}){const[open,setOpen]=(0,react.useState)(false);const toggleOpen=(0,react.useCallback)(()=>{setOpen(value=>!value)},[]);const{rendered,summary,body}=contextBody(form,{content,source,t});const toolBlocks=content.length>0&&content.every(block=>block.type===`tool-addition`||block.type===`tool-removal`)?content:void 0;const added=toolBlocks?.flatMap(block=>block.type===`tool-addition`?[block.toolName]:[])??[];const removed=toolBlocks?.flatMap(block=>block.type===`tool-removal`?[block.toolName]:[])??[];const single=toolBlocks?.length===1?toolBlocks[0]:void 0;const toolSummary=toolBlocks===void 0||single!==void 0?null:added.length>0&&removed.length>0?t(`message.toolsChanged`,{added:added.length,removed:removed.length}):added.length>0?t(`message.toolsAddedCount`,{count:added.length}):t(`message.toolsRemovedCount`,{count:removed.length});return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{className:ContextInjectionRow_module_css_default.root,icon:toolBlocks!==void 0?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}):producer.role===`recall`?(0,react_jsx_runtime.jsx)(`span`,{"data-context-recall-icon":true,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.ReferenceIconRegular,{kind:`session`})}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,{size:14}),chevronClassName:ContextInjectionRow_module_css_default.chevron,title:single!==void 0?t(single.type===`tool-addition`?`message.toolAdded`:`message.toolRemoved`,{name:single.toolName}):t(toolBlocks!==void 0?`message.toolsUpdated`:producer.role===`recall`?`message.contextRecall`:`message.contextInjection`),collapsedContent:toolSummary!==null?(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,children:toolSummary})]}):toolBlocks!==void 0||producer.label===null?void 0:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.source,"data-context-source":true,children:producer.label}),summary!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,"data-context-summary":true,children:summary})]})]}),keepContentWhenOpen:true,open:open&&single===void 0,expandable:single===void 0,expandOnRowClick:true,onToggle:toggleOpen,children:(0,react_jsx_runtime.jsx)(`div`,{className:ContextInjectionRow_module_css_default.body,"data-context-injection-body":true,"data-context-form":rendered??void 0,children:toolBlocks===void 0?body:(0,react_jsx_runtime.jsxs)(`div`,{className:ContextInjectionRow_module_css_default.toolChanges,children:[added.length>0&&(0,react_jsx_runtime.jsx)(`div`,{children:t(`message.toolsAdded`,{names:added.join(`, `)})}),removed.length>0&&(0,react_jsx_runtime.jsx)(`div`,{children:t(`message.toolsRemoved`,{names:removed.join(`, `)})})]})})})}const LIVE_RUN_CLOCK_INTERVAL_MS=1e3;function pad2(n){return String(n).padStart(2,`0`)}function startOfLocalDay(ms){const d=new Date(ms);d.setHours(0,0,0,0);return d.getTime()}function msUntilNextLocalMidnight(ms){const next=new Date(ms);next.setHours(24,0,0,0);return Math.max(next.getTime()-ms,1)}function formatRunDuration(ms,t){const total=Math.max(0,Math.floor(ms/1e3));const hours=Math.floor(total/3600);const minutes=Math.floor(total/60)%60;const seconds=total%60;const parts=[];if(hours>0)parts.push({text:String(hours),numeric:true},{text:t(`duration.hourUnit`),numeric:false});if(total>=60)parts.push({text:String(minutes),numeric:true},{text:t(`duration.minuteUnit`),numeric:false});parts.push({text:String(seconds),numeric:true},{text:t(`duration.secondUnit`),numeric:false});return parts}function formatTokensPerSecond(tps){const clamped=Math.max(0,tps);return clamped>=10?String(Math.round(clamped)):String(Math.round(clamped*10)/10)}function formatMessageClock(time,t,now=Date.now()){const d=new Date(time);const n=new Date(now);const clock=`${pad2(d.getHours())}:${pad2(d.getMinutes())}`;if(d.getFullYear()===n.getFullYear()&&d.getMonth()===n.getMonth()&&d.getDate()===n.getDate())return clock;const params={y:d.getFullYear(),m:d.getMonth()+1,d:d.getDate()};return`${d.getFullYear()===n.getFullYear()?t(`clock.md`,params):t(`clock.ymd`,params)} ${clock}`}function useCalendarDay(){const[day,setDay]=(0,react.useState)(()=>startOfLocalDay(Date.now()));(0,react.useEffect)(()=>{let timer;const arm=()=>{const now=Date.now();setDay(startOfLocalDay(now));timer=setTimeout(arm,msUntilNextLocalMidnight(now))};timer=setTimeout(arm,msUntilNextLocalMidnight(Date.now()));return()=>{clearTimeout(timer)}},[]);return day}var MessageIconActions_module_css_default={"action":`xzv4MW_action`,"actions":`xzv4MW_actions`,"endInfo":`xzv4MW_endInfo`,"timeEnd":`xzv4MW_timeEnd`,"timeStart":`xzv4MW_timeStart`,"visuallyHidden":`xzv4MW_visuallyHidden`};function MessageIconActions({text,time,clock,onBranch,branchUnavailable=false,className,extraActions,usageAction,t}){const day=useCalendarDay();const reasonId=(0,react.useId)();const{copied,onCopy}=(0,_deepseek_ai_dsh_client_ui_primitives_client.useClipboardCopy)(text);const clockEl=time===void 0?null:(0,react_jsx_runtime.jsx)(`span`,{className:clock===`start`?MessageIconActions_module_css_default.timeStart:MessageIconActions_module_css_default.timeEnd,children:formatMessageClock(time,t,day)});return(0,react_jsx_runtime.jsxs)(`div`,{className:className===void 0?MessageIconActions_module_css_default.actions:`${MessageIconActions_module_css_default.actions} ${className}`,"data-clock":clock,children:[clock===`start`?clockEl:null,(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:copied?t(`copied`):t(`copy`),side:`bottom`,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:MessageIconActions_module_css_default.action,"aria-label":copied?t(`copied`):t(`copy`),onClick:onCopy,children:copied?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCheckOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconCopyOutlineRegular,{})})}),extraActions,onBranch!==void 0&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:branchUnavailable?t(`message.branchUnavailable`):t(`message.branch`),side:`bottom`,openOnClick:branchUnavailable,children:(0,react_jsx_runtime.jsx)(`button`,{type:`button`,className:MessageIconActions_module_css_default.action,"aria-label":t(`message.branch`),"aria-disabled":branchUnavailable||void 0,"aria-describedby":branchUnavailable?reasonId:void 0,"data-unavailable":branchUnavailable||void 0,onClick:branchUnavailable?void 0:onBranch,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,{})})}),onBranch!==void 0&&branchUnavailable&&(0,react_jsx_runtime.jsx)(`span`,{id:reasonId,className:MessageIconActions_module_css_default.visuallyHidden,children:t(`message.branchUnavailable`)}),clock===`end`?(0,react_jsx_runtime.jsxs)(`span`,{className:MessageIconActions_module_css_default.endInfo,children:[usageAction,clockEl]}):usageAction]})}const EMPTY_TEXT_FACTS={};function contentParts(content){const texts=[];const attachments=[];const rest=[];for(const block of content){const b=block;if(b.type===`text`&&typeof b.text===`string`)texts.push(b.text);else if(b.type===`image`&&b.attachment!==void 0)attachments.push({type:`image`,image:{attachment:b.attachment}});else if(b.type===`file`&&b.attachment!==void 0)attachments.push({type:`file`,file:b.attachment});else rest.push(block)}return{text:texts.join(``),attachments,rest}}function retrySeconds(milliseconds){return Math.max(1,Math.ceil(milliseconds/1e3))}function failureMessage(message,code,t){if(code===`ACCOUNT_SIGNED_OUT`)return t(`message.failure.accountSignedOut`);if(code===`INTERRUPTED`)return t(`message.failure.interrupted`);if(code===`ACCOUNT_SIGN_IN_REQUIRED`)return t(`message.failure.accountSignInRequired`);if(code===`QUOTA`||code===`ACCOUNT_QUOTA`)return t(`message.failure.quota`);return code===`AUTH`?t(`message.failure.auth`):message}function retryIcon(node,failed){if(node.failure.code===`EMPTY_RESPONSE`)return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWarningOutlineRegular,{});return failed?(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWifiOffOutlineRegular,{}):(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWifiOutlineRegular,{})}function ModelRetryItem({node,active,inFlight,failed,grouped,inspect,t}){const[open,setOpen]=(0,react.useState)(false);const toggle=(0,react.useCallback)(()=>{setOpen(value=>!value)},[]);const deadline=(0,react.useMemo)(()=>Date.now()+node.delayMs,[node.delayMs,node.seq]);const scheduledSeconds=retrySeconds(node.delayMs);const maximum=node.mode===`normal`?node.maxRetries:`∞`;const[countdown,setCountdown]=(0,react.useState)(()=>({deadline,seconds:retrySeconds(deadline-Date.now())}));const remainingSeconds=countdown.deadline===deadline?countdown.seconds:retrySeconds(deadline-Date.now());(0,react.useEffect)(()=>{if(!active)return;const updateCountdown=()=>{const next=retrySeconds(deadline-Date.now());setCountdown(current=>current.deadline===deadline&&current.seconds===next?current:{deadline,seconds:next});return next};if(updateCountdown()===1)return;const timer=window.setInterval(()=>{if(updateCountdown()===1)window.clearInterval(timer)},250);return()=>{window.clearInterval(timer)}},[active,deadline]);const retrying=active||inFlight;const label=retrying?t(`message.retry.active`):node.retryState===`cancelled`?t(`message.retry.cancelled`):node.retryState===`started`?t(`message.retry.started`):t(`message.retry.scheduled`);const seconds=active?remainingSeconds:scheduledSeconds;const status=t(`message.retry.status`,{label,retry:node.retry,maximum,seconds});const title=t(`message.retry.title`,{label,retry:node.retry,maximum});const remaining=t(`message.retry.countdown`,{seconds});return(0,react_jsx_runtime.jsxs)(`div`,{className:grouped?MessageItem_module_css_default.retryBesideGroups:void 0,"data-retry-row":true,"data-inspect-scope":true,"data-active":retrying||void 0,"data-failed":failed||void 0,children:[(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-atomic":`true`,children:status}),(0,react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{icon:retryIcon(node,failed),title,rowClassName:MessageItem_module_css_default.retryRow,leadingClassName:MessageItem_module_css_default.retryLeading,titleClassName:MessageItem_module_css_default.retryTitle,running:retrying,open,expandable:true,expandOnRowClick:true,keepContentWhenOpen:true,onToggle:toggle,collapsedContent:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retrySeparator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryProgress,children:remaining})]}),children:[(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.retryDetails,children:[(0,react_jsx_runtime.jsxs)(`div`,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryDetailLabel,children:t(`message.retry.delay`)}),t(`duration.milliseconds`,{milliseconds:Math.round(node.delayMs)})]}),(0,react_jsx_runtime.jsxs)(`div`,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.retryDetailLabel,children:t(`message.retry.failure`)}),failureMessage(node.failure.message,node.failure.code,t)]})]}),inspect!==void 0&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.InspectButton,{label:t(`message.retry.inspect`),onClick:inspect})]})]})}function TurnErrorItem({node,t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorRow,role:`status`,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.StateDot,{state:`error`,className:MessageItem_module_css_default.turnErrorDot}),(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorCopy,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorTitle,children:node.code===`ACCOUNT_SIGNED_OUT`||node.code===`INTERRUPTED`?t(`message.taskStopped`):t(`message.turnError`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorMessage,children:failureMessage(node.message,node.code,t)})]}),node.code!==void 0&&node.code!==`INTERRUPTED`&&(0,react_jsx_runtime.jsx)(`code`,{className:MessageItem_module_css_default.turnErrorCode,children:node.code})]})}function TurnMaxTokensItem({t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorRow,role:`status`,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.StateDot,{state:`warning`,className:MessageItem_module_css_default.turnErrorDot}),(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.turnErrorCopy,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.maxTokensTitle,children:t(`message.maxTokens`)}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.turnErrorMessage,children:t(`message.maxTokens.hint`)})]})]})}const UNDECORATED_ROW={kind:`user`,data:{source:null}};const NO_MESSAGE_SOURCE=()=>null;function UserStyleBubble({node,renderSlotChain,content,loadImage,renderFactorySlot,actions,pending=false,echo=false,batchStart=false,referenceLabels,skillNames,previewAttachments,facts:inputFacts=EMPTY_TEXT_FACTS,interactive=false}){const parts=(0,react.useMemo)(()=>contentParts(content),[content]);const prepared=(0,react.useMemo)(()=>({text:parts.text,attachments:previewAttachments??parts.attachments,extraBlocks:parts.rest,...referenceLabels===void 0?{}:{referenceLabels}}),[parts,previewAttachments,referenceLabels]);const facts=(0,react.useMemo)(()=>({...inputFacts,...referenceLabels===void 0?{}:{sessionLabels:referenceLabels},...skillNames===void 0?{}:{skillNames}}),[inputFacts,referenceLabels,skillNames]);return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.userRow,"data-pending-steering":pending||void 0,"data-submission-echo":echo||void 0,"data-chat-steering-batch":batchStart?`start`:void 0,children:[renderSlotChain(`conversation.chat.user.before`,{source:node.data.source,kind:node.kind},{fallback:null}),renderFactorySlot(`conversation.chat.user.content`,{content:prepared,loadImage,facts,interactive}),actions?.(prepared.text)]})}function PendingSteeringBubble({content,loadImage,renderFactorySlot,t}){return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node:UNDECORATED_ROW,renderSlotChain:NO_MESSAGE_SOURCE,content,renderFactorySlot,loadImage,pending:true,actions:(0,react.useCallback)(text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,clock:`start`,className:MessageItem_module_css_default.actions,t}),[t])})}function PendingSubmissionBubble({submission,loadImage,renderFactorySlot,t}){const content=(0,react.useMemo)(()=>submission.text===``?[]:[{type:`text`,text:submission.text}],[submission.text]);const previewAttachments=(0,react.useMemo)(()=>submission.attachments.map(attachment=>attachment.type===`image`?{type:`image`,image:{preview:{url:attachment.value.previewUrl,...attachment.value.name===void 0?{}:{name:attachment.value.name},...attachment.value.width===void 0?{}:{width:attachment.value.width},...attachment.value.height===void 0?{}:{height:attachment.value.height}}}}:{type:`file`,file:attachment.value}),[submission.attachments]);const renderActions=(0,react.useCallback)(text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,time:submission.time,clock:`start`,className:MessageItem_module_css_default.actions,t}),[submission.time,t]);return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node:UNDECORATED_ROW,renderSlotChain:NO_MESSAGE_SOURCE,content,previewAttachments,renderFactorySlot,loadImage,pending:submission.placement===`steering`,echo:true,actions:renderActions})}const UserMessageNodeView=(0,react.memo)(function UserMessageNodeView({node,renderFactorySlot,loadImage,renderSlotChain,renderSlot,t}){const data=node.data;const userActions=node.kind===`user`&&data.messageId!==void 0?renderSlot(`conversation.chat.user-actions`,{messageId:data.messageId}):null;const renderActions=(0,react.useCallback)(text=>(0,react_jsx_runtime.jsx)(MessageIconActions,{text,time:data.time,clock:`start`,className:MessageItem_module_css_default.actions,extraActions:userActions,t}),[data.time,t,userActions]);return(0,react_jsx_runtime.jsx)(UserStyleBubble,{node,renderSlotChain,content:data.content,interactive:true,renderFactorySlot,loadImage,batchStart:node.kind===`steering`&&node.data.batchStart===true,...data.referenceLabels===void 0?{}:{referenceLabels:data.referenceLabels},...data.skillNames===void 0?{}:{skillNames:data.skillNames},actions:renderActions})});const ContextMessageNodeView=(0,react.memo)(function ContextMessageNodeView({node,t}){const data=node.data;return(0,react_jsx_runtime.jsx)(ContextInjectionRow,{content:data.content,source:data.source,producer:data.producer,form:data.form,t})});const CompactionNodeView=(0,react.memo)(function CompactionNodeView({node,openCompaction,useCompactionPreview,t}){const available=useCompactionPreview(value=>value);const data=node.data;if(data.kind===`compaction-progress`){const title=t(`message.compaction.commandTitle`);if(data.status===`running`)return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title,state:`running`,summary:t(`message.compaction.running`),body:null,t});const error=data.status===`interrupted`?t(`message.taskStopped`):data.error;return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title,state:error===void 0?`ok`:`error`,summary:error??t(`command.done`),body:error?.includes(`
14
+ `)?error:null,t})}return(0,react_jsx_runtime.jsx)(CompactionItem,{node:data,openCompaction:available?openCompaction:void 0,t})});const InheritedHistoryNodeView=(0,react.memo)(function InheritedHistoryNodeView({t}){return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.inheritedHistoryRow,role:`separator`,"aria-label":t(`message.inheritedHistory`),children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLine,"aria-hidden":true}),(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.inheritedHistoryCaption,"aria-hidden":true,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,{className:MessageItem_module_css_default.inheritedHistoryIcon}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLabel,children:t(`message.inheritedHistory`)})]}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.inheritedHistoryLine,"aria-hidden":true})]})});const RetryNodeView=(0,react.memo)(function RetryNodeView({node,inspectRequest,stepRunsGrouped,t}){const{current,failed,inFlight}=node.data;const inspect=(0,react.useMemo)(()=>inspectRequest===void 0?void 0:()=>{inspectRequest(current.turn,current.step)},[inspectRequest,current.turn,current.step]);return(0,react_jsx_runtime.jsx)(ModelRetryItem,{node:current,active:current.retryState===`scheduled`,inFlight,failed,grouped:stepRunsGrouped===true,inspect,t})});const TurnErrorNodeView=(0,react.memo)(function TurnErrorNodeView({node,t}){return(0,react_jsx_runtime.jsx)(TurnErrorItem,{node:node.data,t})});const TurnMaxTokensNodeView=(0,react.memo)(function TurnMaxTokensNodeView({t}){return(0,react_jsx_runtime.jsx)(TurnMaxTokensItem,{t})});const UnknownNodeView=(0,react.memo)(function UnknownNodeView({node,t}){const data=node.data;const truncatedLabel=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);return(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.contextRow,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownSurface`,{type:data.type}),payload:data.data,truncatedLabel})})});const REST_PATH=`M8.844 13.742C8.967 12.328 8.45 10.4 8.45 9.65C8.45 8.94 8.88 8.43 9.6 8.43C11.285 8.43 12.106 8.281 12.685 8.104C13.71 7.791 14.585 6.768 15.055 5.945C15.137 5.803 14.99 5.641 14.829 5.671C13.829 5.86 12.828 5.376 11.827 4.978C10.659 4.514 9.491 4.707 8.935 4.876C8.805 4.915 8.658 4.819 8.636 4.686C8.468 3.643 7.405 2.615 5.498 2.238C4.54 2.048 3.748 1.574 3.347 1.202C3.252 1.113 3.088 1.125 3.03 1.242C2.628 2.059 2.168 3.82 5.248 6.115C5.82 6.494 6.31 6.785 6.574 7.637C6.72 8.104 6.157 9.168 6.061 9.368C5.157 11.27 5.089 12.19 4.926 13.742`;function RunningWhaleTail(){return(0,react_jsx_runtime.jsxs)(`span`,{className:ChatView_module_css_default.runningIcon,"aria-hidden":`true`,children:[(0,react_jsx_runtime.jsx)(`span`,{className:ChatView_module_css_default.runningWhaleAnimated}),(0,react_jsx_runtime.jsx)(`svg`,{className:ChatView_module_css_default.runningWhaleStill,width:`100%`,height:`100%`,viewBox:`0 0 16 16`,fill:`none`,children:(0,react_jsx_runtime.jsx)(`path`,{d:REST_PATH,stroke:`currentColor`,strokeWidth:1})})]})}const RunningStatus=(0,react.memo)(function RunningStatus({startTime,paused,holding=false,t}){const[now,setNow]=(0,react.useState)(Date.now);(0,react.useEffect)(()=>{if(startTime===void 0||paused||holding)return;setNow(Date.now());const timer=setInterval(()=>{setNow(Date.now())},LIVE_RUN_CLOCK_INTERVAL_MS);return()=>{clearInterval(timer)}},[startTime,paused,holding]);const label=startTime===void 0?t(`chat.deepDiving`):t(`chat.deepDivingFor`,{duration:formatRunDuration(Math.max(1e3,now-startTime),t).map(part=>part.text).join(``)});return(0,react_jsx_runtime.jsxs)(`div`,{className:ChatView_module_css_default.running,"data-chat-running":true,"data-holding":holding?``:void 0,"aria-hidden":holding||void 0,children:[holding?null:(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:t(`chat.deepDiving`)}),(0,react_jsx_runtime.jsx)(`span`,{className:ChatView_module_css_default.runningDivider,"aria-hidden":`true`}),(0,react_jsx_runtime.jsxs)(`span`,{className:ChatView_module_css_default.runningContent,children:[(0,react_jsx_runtime.jsx)(RunningWhaleTail,{}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{active:!holding,className:ChatView_module_css_default.runningText,children:label})]})]})});function isLocalSubmission(item){return`requestId`in item}function isTranscriptEcho(item){return isLocalSubmission(item)&&item.placement===`transcript`}const ChatFlow=(0,react.memo)(function ChatFlow({entries,pendingInputs,lastInputTurn,deferCollapse,useSession,useChat,useChatNode,useChatNodeBottom,useChatNodeProcess,useChatGroup,usePresentation,useConnectionState,useStore,actions,renderSlot,renderFactorySlot,t,useGroupAction,useGroupHeaderAction,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage}){const nodeStore=useChat(snapshot=>snapshot.nodes);const running=useSession(snapshot=>snapshot.running);const disconnected=useConnectionState(state=>state===`disconnected`||state===`connecting`);const latestTurnAnchor=useChat(snapshot=>snapshot.navigation.items().at(-1)?.anchorKey);const runningStartTime=useChatNode(latestTurnAnchor??``,node=>{const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.status===`open`?location.turn.start?.time:void 0:void 0});const latestTurnOpen=useChatNode(latestTurnAnchor??``,node=>{const location=node?.location;return(location?.kind===`turn`||location?.kind===`step`)&&location.turn.status===`open`});const holding=!running&&latestTurnOpen;const seatProps={nodeStore,useChatNode,useChatNodeBottom,useChatNodeProcess,usePresentation,useStore,actions,renderSlot,t,useGroupAction,deferCollapse,cwd,openFile,inspectCall,inspectRequest,forkAt,loadImage};const rows=entries.map(entry=>{switch(entry.kind){case`node`:return(0,react.createElement)(ChatNodeSeat,{...seatProps,key:chatRenderKey(entry),nodeKey:entry.key,...entry.groupPart===void 0?{}:{groupPart:entry.groupPart}});case`group`:return(0,react.createElement)(ChatGroupSeat,{...seatProps,key:chatRenderKey(entry),groupKey:entry.key,useChatGroup,useGroupHeaderAction});default:return assertNever(entry)}});const firstTranscript=pendingInputs.findIndex(isTranscriptEcho);const leadingRows=[];const openingRows=[];const pendingRows=[];for(const[index,item]of pendingInputs.entries()){const row=isLocalSubmission(item)?(0,react_jsx_runtime.jsx)(PendingSubmissionBubble,{submission:item,loadImage,renderFactorySlot,t},item.requestId):(0,react_jsx_runtime.jsx)(PendingSteeringBubble,{content:item.content,loadImage,renderFactorySlot,t},item.id);if(index<=firstTranscript)leadingRows.push(row);else if(isTranscriptEcho(item))openingRows.push(row);else pendingRows.push(row)}const tail=entries.at(-1);const node=tail?.kind===`node`?nodeStore.get(tail.key):void 0;if(node?.kind===`turn-process`&&node.location.kind===`turn`&&node.location.turn.status===`open`&&node.location.turn.turn!==lastInputTurn)rows.splice(rows.length-1,0,...leadingRows.splice(0));return[...rows,...leadingRows,...openingRows,...running||holding?[(0,react_jsx_runtime.jsx)(RunningStatus,{startTime:runningStartTime,paused:disconnected,holding,t},`running`)]:[],...pendingRows]});const NS=`chat`;const zh={"message.stepProcess.thinking":`正在分析请求`,"message.stepProcess.thinkingNext":`{title},正在思考下一步`,"message.stepProcess.read":`正在读取文件`,"message.stepProcess.readImage":`正在读取图片`,"message.stepProcess.write":`正在写入文件`,"message.stepProcess.search":`正在搜索代码`,"message.stepProcess.edit":`正在编辑文件`,"message.stepProcess.commands":`正在运行命令`,"message.stepProcess.code":`正在运行代码`,"message.stepProcess.webSearch":`正在搜索网页`,"message.stepProcess.webFetch":`正在访问网页`,"message.stepProcess.subagents":`正在协调子智能体`,"message.stepProcess.plan":`正在更新计划`,"message.stepProcess.questions":`等待你的操作`,"message.stepProcess.tools":`正在调用工具`,"message.stepProcess.prepare.read":`准备读取文件`,"message.stepProcess.prepare.readImage":`准备读取图片`,"message.stepProcess.prepare.write":`准备写入文件`,"message.stepProcess.prepare.search":`准备搜索代码`,"message.stepProcess.prepare.edit":`准备编辑文件`,"message.stepProcess.prepare.commands":`准备运行命令`,"message.stepProcess.prepare.code":`准备运行代码`,"message.stepProcess.prepare.webSearch":`准备搜索网页`,"message.stepProcess.prepare.webFetch":`准备访问网页`,"message.stepProcess.prepare.subagents":`准备协调子智能体`,"message.stepProcess.prepare.plan":`准备更新计划`,"message.stepProcess.prepare.questions":`准备提问`,"message.stepProcess.prepare.tools":`准备调用工具`,"message.stepProcess.done.thinking":`已完成分析`,"message.stepProcess.done.read":`已读取文件`,"message.stepProcess.done.readImage":`已读取图片`,"message.stepProcess.done.write":`已写入文件`,"message.stepProcess.done.search":`已搜索代码`,"message.stepProcess.done.edit":`修改了文件`,"message.stepProcess.done.commands":`执行了命令`,"message.stepProcess.done.code":`运行了代码`,"message.stepProcess.done.webSearch":`已搜索网页`,"message.stepProcess.done.webFetch":`已访问网页`,"message.stepProcess.done.subagents":`已协调子智能体`,"message.stepProcess.done.plan":`更新了计划`,"message.stepProcess.done.questions":`向用户提出了问题`,"message.stepProcess.done.tools":`已调用工具`,"message.stepProcess.done.context":`已注入上下文`,"message.stepProcess.joinTwo":`{first}并{second}`,"message.stepProcess.comma":`,`,"message.stepProcess.sharedPrefix":`已`,"message.stepProcess.more":`{title}等`,"message.trigger.request":`收到执行请求`,"message.trigger.goal":`继续执行目标`,"message.trigger.agent":`收到任务消息`,"message.trigger.team":`收到团队消息`,"message.trigger.subagent":`子任务状态更新`,"message.trigger.subagent.completed":`子智能体已完成任务`,"message.trigger.subagent.aborted":`子智能体任务已停止`,"message.trigger.subagent.error":`子智能体执行失败`,"message.trigger.subagent.maxTokens":`子智能体已达 token 上限`,"message.trigger.subagent.refusal":`子智能体拒绝执行`,"message.trigger.subagent.unknown":`子智能体异常结束`,"message.trigger.github":`收到 GitHub 事件`,"message.trigger.webhook":`收到外部事件`,"message.trigger.schedule":`自动化任务`,"message.trigger.job":`后台任务状态更新`,"message.trigger.plugin":`插件状态更新`,"message.trigger.explanation":`这条通知触发了本轮回复。`,"message.turnProcess.worked":`已完成`,"message.turnProcess.took":`已完成,用时 `,"message.turnProcess.failed":`处理失败`,"view.chat":`对话`,"image.open":`查看大图`,"image.loading":`加载图片…`,"image.failed":`图片无法预览`,"image.dialog":`图片预览`,"image.close":`关闭图片预览`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}秒`,"duration.compactMinutes":`{minutes}分{seconds}秒`,"duration.milliseconds":`{milliseconds}毫秒`,"stats.counts":`{turns} 轮 {steps} 步`,"stats.cacheHit":`缓存命中 {percent}%`,"stats.dialog.title":`会话统计`,"stats.dialog.usageTitle":`Token 用量`,"stats.dialog.llmTime":`模型用时`,"stats.dialog.toolTime":`工具调用用时`,"stats.dialog.ttft":`首 token 平均(TTFT)`,"stats.dialog.speed":`输出速度(TPS)`,"chat.loadingHistory":`载入历史…`,"chat.loadError":`历史加载失败:{message}({code})`,"chat.loadOlder":`加载更早`,"chat.loadingOlder":`正在加载`,"chat.processingOlder":`正在处理`,"chat.retryOlder":`重新加载`,"chat.historyStart":`已到会话开头`,"chat.toBottom":`回到底部`,"chat.deepDiving":`深度求索中`,"chat.deepDivingFor":`深度求索中,用时 {duration} ···`,"chat.turnNavigation.label":`轮次导航`,"chat.turnNavigation.jump":`跳转到第 {turn} 轮`,"chat.turnNavigation.jumpLoad":`加载并跳转到第 {turn} 轮`,"chat.turnNavigation.turn":`第 {turn} 轮`,"settings.performance.title":`性能与用量`,"settings.performance.description":`选择性能与用量信息展示的详细程度`,"settings.performance.compact":`简洁`,"settings.performance.detailed":`详细`,"settings.links.title":`网页链接默认打开方式`,"settings.links.description":`对话中网页链接的打开位置`,"settings.links.sidebar":`应用内侧边栏`,"settings.links.newTab":`默认浏览器`,"settings.transcript.title":`工作步骤展示`,"settings.transcript.description":`选择希望看到多少工具调用细节`,"settings.collapse.title":`工作步骤收起时机`,"settings.collapse.description":`选择何时自动收起工作步骤`,"settings.collapse.completion":`回答结束后`,"settings.collapse.nextInput":`下次有新消息时`,"settings.foldedReplies.title":`收起后显示的回复`,"settings.foldedReplies.description":`工作步骤收起后,保留哪些助手回复`,"settings.foldedReplies.all":`全部回复`,"settings.foldedReplies.final":`仅最终回答`,"settings.transcript.compact":`简洁`,"settings.transcript.standard":`标准`,"settings.transcript.detailed":`详细`,"settings.transcript.verbose":`完全展开`,"fileOpen.title":`无法打开文件`,"fileOpen.unknown":`无法打开此文件`,"message.extraBlock":`附加内容块`,"message.systemPrompt":`系统提示词`,"message.systemPromptUpdate":`系统提示词更新`,"message.systemSection.added":`新增 {name}`,"message.systemSection.updated":`更新 {name}`,"message.systemSection.cleared":`清空 {name}`,"message.systemSection.reordered":`调整顺序 {name}`,"message.systemSection.removed":`移除 {name}`,"message.systemSection.unchanged":`未变化 {name}`,"message.systemPromptReset":`取代此前的全部指令`,"message.systemPromptSections":`{count} 个章节`,"message.toolAdded":`已添加工具:{name}`,"message.toolRemoved":`已移除工具:{name}`,"message.toolsAdded":`新增:{names}`,"message.toolsAddedCount":`新增 {count} 个`,"message.toolsChanged":`新增 {added} 个,移除 {removed} 个`,"message.toolsRemoved":`移除:{names}`,"message.toolsRemovedCount":`移除 {count} 个`,"message.toolsUpdated":`工具已更新`,"message.contextInjection":`上下文注入`,"message.contextRecall":`跨会话召回`,"message.referenceSummary":`引用会话 · {labels}`,"message.referenceSeparator":`、`,"message.context.instructions.loaded":`已载入`,"message.context.instructions.added":`已新增`,"message.context.instructions.updated":`已更新`,"message.context.instructions.removed":`已移除`,"message.context.catalog.replaced":`替换目录`,"message.context.catalog.more":`…还有 {count} 条`,"message.context.snapshot.supersedes":`取代先前的快照`,"message.context.relay.from":`来自会话 {session}`,"message.context.recall.counts":`保留 {retained} 条 · 省略 {omitted} 条`,"message.context.recall.truncated":`已截断`,"message.compaction":`上下文已压缩`,"message.inheritedHistory":`以上为继承的历史消息`,"message.compaction.running":`正在压缩…`,"message.compaction.completed":`已压缩 {items} 条历史记录(约 {tokens} tokens)`,"message.compaction.open":`在侧栏查看压缩摘要`,"message.compaction.notFound":`摘要不可用:预览服务不可用,或摘要记录缺失、为空或无效。`,"message.compaction.readFailed":`无法读取摘要`,"message.compaction.landed":`较早的历史已压缩为摘要`,"message.compaction.commandTitle":`compact`,"message.think":`思考`,"message.unknownSurface":`未知 surface 事件:{type}`,"message.unknownBlock":`未知内容块`,"message.turnProcess.toolCalls.one":`{count} 次工具调用`,"message.turnProcess.toolCalls.other":`{count} 次工具调用`,"message.turnProcess.messages.one":`{count} 条消息`,"message.turnProcess.messages.other":`{count} 条消息`,"message.turnProcess.subagents.one":`{count} 个 subagent`,"message.turnProcess.subagents.other":`{count} 个 subagent`,"message.turnProcess.thoughtForAWhile":`已思考`,"message.turnProcess.separator":` · `,"message.stopped":`已停止`,"message.branch":`在新对话中分支`,"message.branchUnavailable":`仅可从已完成轮次的最后一条消息分支`,"message.retry.active":`正在重试模型请求`,"message.retry.cancelled":`模型请求重试已取消`,"message.retry.started":`已重试模型请求`,"message.continuation.requested":`已请求继续生成`,"message.retry.scheduled":`等待重试模型请求`,"message.retry.status":`{label}({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label}({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`重试延迟:`,"message.retry.failure":`失败原因:`,"message.retry.inspect":`查看`,"message.failure.auth":`API 密钥无效`,"message.taskStopped":`任务已停止`,"message.failure.accountSignedOut":`任务已因退出 DeepSeek 登录而停止。`,"message.failure.interrupted":`DSH 进程在本轮完成前退出(例如被强制结束、崩溃或关闭超时),重新启动后本轮已中止。未完成的工具调用结果未知。`,"message.failure.accountSignInRequired":`请先登录 DeepSeek,并确认请求地址支持账号认证。`,"message.failure.quota":`当前请求的额度已用尽`,"message.turnError":`本轮运行失败`,"message.maxTokens":`已达到输出 token 上限`,"message.maxTokens.hint":`回答被截断,已有输出保留在对话中。发送“继续”可让模型接着输出。`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`本轮用量`,"message.turnUsage.consumed":`用量 {total}`,"message.turnUsage.model":`提供方 / 模型`,"message.turnUsage.cacheHit":`缓存命中`,"message.turnUsage.input":`未缓存输入`,"message.turnUsage.cacheRead":`缓存读取`,"message.turnUsage.cacheWrite":`缓存写入`,"message.turnUsage.output":`输出`,"message.turnUsage.reasoning":`(其中推理 {tokens})`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`秒`,"duration.minuteUnit":`分`,"duration.hourUnit":`小时`,"command.running":`执行中…`,"command.failed":`指令失败`,"command.done":`已完成`,"command.title":`指令`,"row.running":`运行中`,"row.failed":`失败`,"json.truncated":`… 已截断,共 {total} 字符`,"clock.md":`{m}月{d}日`,"clock.ymd":`{y}年{m}月{d}日`};const en={"message.stepProcess.thinking":`Analyzing the request`,"message.stepProcess.thinkingNext":`{title}, thinking about the next step`,"message.stepProcess.read":`Reading files`,"message.stepProcess.readImage":`Reading images`,"message.stepProcess.write":`Writing files`,"message.stepProcess.search":`Searching code`,"message.stepProcess.edit":`Editing files`,"message.stepProcess.commands":`Running commands`,"message.stepProcess.code":`Running code`,"message.stepProcess.webSearch":`Searching the web`,"message.stepProcess.webFetch":`Visiting web pages`,"message.stepProcess.subagents":`Coordinating subagents`,"message.stepProcess.plan":`Updating the plan`,"message.stepProcess.questions":`Waiting for your action`,"message.stepProcess.tools":`Calling tools`,"message.stepProcess.prepare.read":`Preparing to read files`,"message.stepProcess.prepare.readImage":`Preparing to read images`,"message.stepProcess.prepare.write":`Preparing to write files`,"message.stepProcess.prepare.search":`Preparing to search code`,"message.stepProcess.prepare.edit":`Preparing to edit files`,"message.stepProcess.prepare.commands":`Preparing to run commands`,"message.stepProcess.prepare.code":`Preparing to run code`,"message.stepProcess.prepare.webSearch":`Preparing to search the web`,"message.stepProcess.prepare.webFetch":`Preparing to visit web pages`,"message.stepProcess.prepare.subagents":`Preparing to coordinate subagents`,"message.stepProcess.prepare.plan":`Preparing to update the plan`,"message.stepProcess.prepare.questions":`Preparing questions`,"message.stepProcess.prepare.tools":`Preparing tool calls`,"message.stepProcess.done.thinking":`Analysis completed`,"message.stepProcess.done.read":`Read files`,"message.stepProcess.done.readImage":`Read images`,"message.stepProcess.done.write":`Wrote files`,"message.stepProcess.done.search":`Searched code`,"message.stepProcess.done.edit":`Edited files`,"message.stepProcess.done.commands":`Ran commands`,"message.stepProcess.done.code":`Ran code`,"message.stepProcess.done.webSearch":`Searched the web`,"message.stepProcess.done.webFetch":`Visited web pages`,"message.stepProcess.done.subagents":`Coordinated subagents`,"message.stepProcess.done.plan":`Updated the plan`,"message.stepProcess.done.questions":`Asked questions`,"message.stepProcess.done.tools":`Called tools`,"message.stepProcess.done.context":`Injected context`,"message.stepProcess.joinTwo":`{first} and {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Execution requested`,"message.trigger.goal":`Continuing goal`,"message.trigger.agent":`Task message received`,"message.trigger.team":`Team message received`,"message.trigger.subagent":`Subtask status updated`,"message.trigger.subagent.completed":`Subagent run completed`,"message.trigger.subagent.aborted":`Subagent run stopped`,"message.trigger.subagent.error":`Subagent run failed`,"message.trigger.subagent.maxTokens":`Subagent reached the token limit`,"message.trigger.subagent.refusal":`Subagent declined the task`,"message.trigger.subagent.unknown":`Subagent run ended unexpectedly`,"message.trigger.github":`GitHub event received`,"message.trigger.webhook":`External event received`,"message.trigger.schedule":`Automation task`,"message.trigger.job":`Background task updated`,"message.trigger.plugin":`Plugin status updated`,"message.trigger.explanation":`This notification triggered this response.`,"message.turnProcess.worked":`Completed`,"message.turnProcess.took":`Completed in `,"message.turnProcess.failed":`Failed`,"view.chat":`Chat`,"image.open":`View full image`,"image.loading":`Loading image…`,"image.failed":`Image preview unavailable`,"image.dialog":`Image preview`,"image.close":`Close image preview`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turns {steps} steps`,"stats.cacheHit":`Cache hit {percent}%`,"stats.dialog.title":`Session statistics`,"stats.dialog.usageTitle":`Token usage`,"stats.dialog.llmTime":`LLM time`,"stats.dialog.toolTime":`Tool time`,"stats.dialog.ttft":`Avg time to first token (TTFT)`,"stats.dialog.speed":`Tokens per second (TPS)`,"chat.loadingHistory":`Loading history…`,"chat.loadError":`Failed to load history: {message} ({code})`,"chat.loadOlder":`Load earlier`,"chat.loadingOlder":`Loading earlier`,"chat.processingOlder":`Processing`,"chat.retryOlder":`Retry loading`,"chat.historyStart":`Start of conversation`,"chat.toBottom":`Back to bottom`,"chat.deepDiving":`Deep diving`,"chat.deepDivingFor":`Deep diving for {duration} ···`,"chat.turnNavigation.label":`Turn navigation`,"chat.turnNavigation.jump":`Jump to turn {turn}`,"chat.turnNavigation.jumpLoad":`Load and jump to turn {turn}`,"chat.turnNavigation.turn":`Turn {turn}`,"settings.performance.title":`Performance & usage`,"settings.performance.description":`Choose how much performance and usage information to show`,"settings.performance.compact":`Compact`,"settings.performance.detailed":`Detailed`,"settings.links.title":`Open chat links in`,"settings.links.description":`Choose where to open web links`,"settings.links.sidebar":`In-App Sidebar`,"settings.links.newTab":`Default Browser`,"settings.transcript.title":`Work details`,"settings.transcript.description":`Choose how much detail to show for tool calls`,"settings.collapse.title":`When to Collapse Work Details`,"settings.collapse.description":`Choose when to automatically collapse work details`,"settings.collapse.completion":`On completion`,"settings.collapse.nextInput":`On next message`,"settings.foldedReplies.title":`Replies After Collapse`,"settings.foldedReplies.description":`Choose which assistant replies stay visible when work details collapse`,"settings.foldedReplies.all":`All replies`,"settings.foldedReplies.final":`Final answer only`,"settings.transcript.compact":`Compact`,"settings.transcript.standard":`Standard`,"settings.transcript.detailed":`Detailed`,"settings.transcript.verbose":`Verbose`,"fileOpen.title":`Couldn’t open file`,"fileOpen.unknown":`Couldn’t open this file`,"message.extraBlock":`Extra content block`,"message.systemPrompt":`System prompt`,"message.systemPromptUpdate":`System prompt update`,"message.systemSection.added":`Added {name}`,"message.systemSection.updated":`Updated {name}`,"message.systemSection.cleared":`Cleared {name}`,"message.systemSection.reordered":`Reordered {name}`,"message.systemSection.removed":`Removed {name}`,"message.systemSection.unchanged":`Unchanged {name}`,"message.systemPromptReset":`Replaces all earlier instructions`,"message.systemPromptSections":`{count} sections`,"message.toolAdded":`Tool added: {name}`,"message.toolRemoved":`Tool removed: {name}`,"message.toolsAdded":`Added: {names}`,"message.toolsAddedCount":`{count} added`,"message.toolsChanged":`{added} added, {removed} removed`,"message.toolsRemoved":`Removed: {names}`,"message.toolsRemovedCount":`{count} removed`,"message.toolsUpdated":`Tools updated`,"message.contextInjection":`Context injection`,"message.contextRecall":`Session recall`,"message.referenceSummary":`Referenced session · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`loaded`,"message.context.instructions.added":`added`,"message.context.instructions.updated":`updated`,"message.context.instructions.removed":`removed`,"message.context.catalog.replaced":`Replacement catalog`,"message.context.catalog.more":`… {count} more`,"message.context.snapshot.supersedes":`Supersedes earlier snapshots`,"message.context.relay.from":`From session {session}`,"message.context.recall.counts":`{retained} kept · {omitted} omitted`,"message.context.recall.truncated":`truncated`,"message.compaction":`Context compacted`,"message.inheritedHistory":`Inherited history above`,"message.compaction.running":`Compacting context…`,"message.compaction.completed":`Compacted {items} history items (~{tokens} tokens)`,"message.compaction.open":`View compaction summary in the sidebar`,"message.compaction.notFound":`Summary unavailable: the preview service is unavailable, or the summary record is missing, empty or invalid.`,"message.compaction.readFailed":`Unable to read the summary`,"message.compaction.landed":`Earlier history condensed into a summary`,"message.compaction.commandTitle":`compact`,"message.think":`Think`,"message.unknownSurface":`Unknown surface event: {type}`,"message.unknownBlock":`Unknown content block`,"message.turnProcess.toolCalls.one":`{count} tool call`,"message.turnProcess.toolCalls.other":`{count} tool calls`,"message.turnProcess.messages.one":`{count} message`,"message.turnProcess.messages.other":`{count} messages`,"message.turnProcess.subagents.one":`{count} subagent`,"message.turnProcess.subagents.other":`{count} subagents`,"message.turnProcess.thoughtForAWhile":`Thought for a while`,"message.turnProcess.separator":` · `,"message.stopped":`Stopped`,"message.branch":`Branch into a new conversation`,"message.branchUnavailable":`Available only on the last message of a completed turn`,"message.retry.active":`Retrying model request`,"message.retry.cancelled":`Model request retry cancelled`,"message.retry.started":`Retried model request`,"message.continuation.requested":`Requested to continue generation`,"message.retry.scheduled":`Waiting to retry model request`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Retry delay: `,"message.retry.failure":`Failure reason: `,"message.retry.inspect":`Inspect`,"message.failure.auth":`API key is invalid`,"message.taskStopped":`Task stopped`,"message.failure.accountSignedOut":`Stopped because you signed out of DeepSeek.`,"message.failure.interrupted":`The DSH process exited before this turn finished (for example, it was killed, crashed, or timed out while shutting down), so the turn was closed when DSH restarted. Unfinished tool calls have unknown outcomes.`,"message.failure.accountSignInRequired":`Sign in to DeepSeek and ensure the request destination supports account authentication.`,"message.failure.quota":`Request quota exhausted.`,"message.turnError":`This turn failed`,"message.maxTokens":`Output token limit reached`,"message.maxTokens.hint":`The reply was cut off; earlier output is preserved in the conversation. Send "continue" to let the model resume.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Turn usage`,"message.turnUsage.consumed":`Usage {total}`,"message.turnUsage.model":`Provider / model`,"message.turnUsage.cacheHit":`Cache hit`,"message.turnUsage.input":`Uncached input`,"message.turnUsage.cacheRead":`Cached input`,"message.turnUsage.cacheWrite":`Cache write`,"message.turnUsage.output":`Output`,"message.turnUsage.reasoning":` ({tokens} reasoning)`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Running…`,"command.failed":`Command failed`,"command.done":`Completed`,"command.title":`Command`,"row.running":`Running`,"row.failed":`Failed`,"json.truncated":`… truncated, {total} characters total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const ja={"message.stepProcess.thinking":`リクエストを分析中`,"message.stepProcess.thinkingNext":`{title}、次のステップを検討中`,"message.stepProcess.read":`ファイルを読み取り中`,"message.stepProcess.readImage":`画像を読み取り中`,"message.stepProcess.write":`ファイルを書き込み中`,"message.stepProcess.search":`コードを検索中`,"message.stepProcess.edit":`ファイルを編集中`,"message.stepProcess.commands":`コマンドを実行中`,"message.stepProcess.code":`コードを実行中`,"message.stepProcess.webSearch":`ウェブを検索中`,"message.stepProcess.webFetch":`ウェブページを閲覧中`,"message.stepProcess.subagents":`サブエージェントを調整中`,"message.stepProcess.plan":`計画を更新中`,"message.stepProcess.questions":`操作を待機中`,"message.stepProcess.tools":`ツールを呼び出し中`,"message.stepProcess.prepare.read":`ファイル読み取りの準備中`,"message.stepProcess.prepare.readImage":`画像読み取りの準備中`,"message.stepProcess.prepare.write":`ファイル書き込みの準備中`,"message.stepProcess.prepare.search":`コード検索の準備中`,"message.stepProcess.prepare.edit":`ファイル編集の準備中`,"message.stepProcess.prepare.commands":`コマンド実行の準備中`,"message.stepProcess.prepare.code":`コード実行の準備中`,"message.stepProcess.prepare.webSearch":`ウェブ検索の準備中`,"message.stepProcess.prepare.webFetch":`ウェブページ閲覧の準備中`,"message.stepProcess.prepare.subagents":`サブエージェント調整の準備中`,"message.stepProcess.prepare.plan":`計画更新の準備中`,"message.stepProcess.prepare.questions":`質問の準備中`,"message.stepProcess.prepare.tools":`ツール呼び出しの準備中`,"message.stepProcess.done.thinking":`分析完了`,"message.stepProcess.done.read":`ファイルを読み取りました`,"message.stepProcess.done.readImage":`画像を読み取りました`,"message.stepProcess.done.write":`ファイルを書き込みました`,"message.stepProcess.done.search":`コードを検索しました`,"message.stepProcess.done.edit":`ファイルを編集しました`,"message.stepProcess.done.commands":`コマンドを実行しました`,"message.stepProcess.done.code":`コードを実行しました`,"message.stepProcess.done.webSearch":`ウェブを検索しました`,"message.stepProcess.done.webFetch":`ウェブページを閲覧しました`,"message.stepProcess.done.subagents":`サブエージェントを調整しました`,"message.stepProcess.done.plan":`計画を更新しました`,"message.stepProcess.done.questions":`質問しました`,"message.stepProcess.done.tools":`ツールを呼び出しました`,"message.stepProcess.done.context":`コンテキストを注入しました`,"message.stepProcess.joinTwo":`{first}と{second}`,"message.stepProcess.comma":`、`,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}など`,"message.trigger.request":`実行が要求されました`,"message.trigger.goal":`目標を継続中`,"message.trigger.agent":`タスクメッセージを受信しました`,"message.trigger.team":`チームメッセージを受信しました`,"message.trigger.subagent":`サブタスクの状態が更新されました`,"message.trigger.subagent.completed":`サブエージェントの実行が完了しました`,"message.trigger.subagent.aborted":`サブエージェントの実行が停止しました`,"message.trigger.subagent.error":`サブエージェントの実行が失敗しました`,"message.trigger.subagent.maxTokens":`サブエージェントがトークンの上限に達しました`,"message.trigger.subagent.refusal":`サブエージェントがタスクを拒否しました`,"message.trigger.subagent.unknown":`サブエージェントの実行が予期せず終了しました`,"message.trigger.github":`GitHubイベントを受信しました`,"message.trigger.webhook":`外部イベントを受信しました`,"message.trigger.schedule":`自動化タスク`,"message.trigger.job":`バックグラウンドタスクが更新されました`,"message.trigger.plugin":`プラグインの状態が更新されました`,"message.trigger.explanation":`この通知がこの応答のトリガーとなりました。`,"message.turnProcess.worked":`完了`,"message.turnProcess.took":`完了まで `,"message.turnProcess.failed":`失敗`,"view.chat":`チャット`,"image.open":`画像を全画面表示`,"image.loading":`画像を読み込み中…`,"image.failed":`画像プレビューを利用できません`,"image.dialog":`画像プレビュー`,"image.close":`画像プレビューを閉じる`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}秒`,"duration.compactMinutes":`{minutes}分{seconds}秒`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns}ターン {steps}ステップ`,"stats.cacheHit":`キャッシュヒット {percent}%`,"stats.dialog.title":`セッション統計`,"stats.dialog.usageTitle":`トークン使用量`,"stats.dialog.llmTime":`LLM時間`,"stats.dialog.toolTime":`ツール時間`,"stats.dialog.ttft":`平均初回トークン時間(TTFT)`,"stats.dialog.speed":`毎秒トークン数(TPS)`,"chat.loadingHistory":`履歴を読み込み中…`,"chat.loadError":`履歴の読み込みに失敗しました: {message}({code})`,"chat.loadOlder":`以前を読み込む`,"chat.loadingOlder":`読み込み中`,"chat.processingOlder":`処理中`,"chat.retryOlder":`再読み込み`,"chat.historyStart":`会話の先頭です`,"chat.toBottom":`最下部へ戻る`,"chat.deepDiving":`深掘り中`,"chat.deepDivingFor":`{duration} の間深く分析中 ···`,"chat.turnNavigation.label":`ターン移動`,"chat.turnNavigation.jump":`ターン {turn} へ移動`,"chat.turnNavigation.jumpLoad":`読み込んでターン {turn} へ移動`,"chat.turnNavigation.turn":`ターン {turn}`,"settings.performance.title":`パフォーマンスと使用状況`,"settings.performance.description":`パフォーマンスと使用状況の表示量を選択`,"settings.performance.compact":`コンパクト`,"settings.performance.detailed":`詳細`,"settings.links.title":`チャットリンクを開く場所`,"settings.links.description":`Web リンクを開く場所を選択`,"settings.links.sidebar":`アプリ内サイドバー`,"settings.links.newTab":`既定のブラウザー`,"settings.transcript.title":`作業の詳細`,"settings.transcript.description":`ツール呼び出しの表示詳細度を選択`,"settings.collapse.title":`作業詳細を折りたたむタイミング`,"settings.collapse.description":`作業詳細を自動で折りたたむタイミングを選択`,"settings.collapse.completion":`完了時`,"settings.collapse.nextInput":`次のメッセージ送信時`,"settings.foldedReplies.title":`折りたたみ後の返信`,"settings.foldedReplies.description":`作業詳細の折りたたみ時に表示するアシスタントの返信を選択`,"settings.foldedReplies.all":`すべての返信`,"settings.foldedReplies.final":`最終回答のみ`,"settings.transcript.compact":`コンパクト`,"settings.transcript.standard":`標準`,"settings.transcript.detailed":`詳細`,"settings.transcript.verbose":`冗長`,"fileOpen.title":`ファイルを開けませんでした`,"fileOpen.unknown":`このファイルを開けませんでした`,"message.extraBlock":`追加のコンテンツブロック`,"message.systemPrompt":`システムプロンプト`,"message.systemPromptUpdate":`システムプロンプトの更新`,"message.systemSection.added":`追加 {name}`,"message.systemSection.updated":`更新 {name}`,"message.systemSection.cleared":`クリア {name}`,"message.systemSection.reordered":`並べ替え {name}`,"message.systemSection.removed":`削除 {name}`,"message.systemSection.unchanged":`変更なし {name}`,"message.systemPromptReset":`以前の指示をすべて置き換えます`,"message.systemPromptSections":`{count} セクション`,"message.toolAdded":`ツールを追加: {name}`,"message.toolRemoved":`ツールを削除: {name}`,"message.toolsAdded":`追加: {names}`,"message.toolsAddedCount":`{count} 件追加`,"message.toolsChanged":`{added} 件追加、{removed} 件削除`,"message.toolsRemoved":`削除: {names}`,"message.toolsRemovedCount":`{count} 件削除`,"message.toolsUpdated":`ツールを更新しました`,"message.contextInjection":`コンテキスト注入`,"message.contextRecall":`セッションの呼び出し`,"message.referenceSummary":`参照セッション · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`読み込み済み`,"message.context.instructions.added":`追加済み`,"message.context.instructions.updated":`更新済み`,"message.context.instructions.removed":`削除済み`,"message.context.catalog.replaced":`置換カタログ`,"message.context.catalog.more":`… 他 {count} 件`,"message.context.snapshot.supersedes":`以前のスナップショットを置き換えます`,"message.context.relay.from":`セッション {session} から`,"message.context.recall.counts":`{retained} 件保持 · {omitted} 件除外`,"message.context.recall.truncated":`切り詰め済み`,"message.compaction":`コンテキストを圧縮しました`,"message.inheritedHistory":`ここまでは引き継いだ履歴です`,"message.compaction.running":`コンテキストを圧縮中…`,"message.compaction.completed":`履歴 {items} 件を圧縮しました(約 {tokens} トークン)`,"message.compaction.open":`圧縮の要約をサイドバーで表示`,"message.compaction.notFound":`要約を利用できません。プレビューサービスが利用できないか、要約が存在しない、空、または無効です。`,"message.compaction.readFailed":`要約を読み込めません`,"message.compaction.landed":`以前の履歴を要約に圧縮しました`,"message.compaction.commandTitle":`compact`,"message.think":`思考`,"message.unknownSurface":`不明なサーフェスイベント: {type}`,"message.unknownBlock":`不明なコンテンツブロック`,"message.turnProcess.toolCalls.one":`ツール呼び出し {count} 件`,"message.turnProcess.toolCalls.other":`ツール呼び出し {count} 件`,"message.turnProcess.messages.one":`メッセージ {count} 件`,"message.turnProcess.messages.other":`メッセージ {count} 件`,"message.turnProcess.subagents.one":`サブエージェント {count} 件`,"message.turnProcess.subagents.other":`サブエージェント {count} 件`,"message.turnProcess.thoughtForAWhile":`しばらく思考しました`,"message.turnProcess.separator":` · `,"message.stopped":`停止しました`,"message.branch":`新しい会話に分岐`,"message.branchUnavailable":`完了したターンの最後のメッセージでのみ利用できます`,"message.retry.active":`モデルリクエストを再試行中`,"message.retry.cancelled":`モデルリクエストの再試行をキャンセルしました`,"message.retry.started":`モデルリクエストを再試行しました`,"message.continuation.requested":`生成の続行をリクエストしました`,"message.retry.scheduled":`モデルリクエストの再試行待ちです`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}秒`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}秒`,"message.retry.delay":`再試行までの待機時間: `,"message.retry.failure":`失敗理由: `,"message.retry.inspect":`検査`,"message.failure.auth":`APIキーが無効です`,"message.taskStopped":`タスクを停止しました`,"message.failure.accountSignedOut":`DeepSeekからログアウトしたため停止しました。`,"message.failure.interrupted":`このターンが完了する前にDSHプロセスが終了したため(強制終了、クラッシュ、シャットダウン中のタイムアウトなど)、DSHの再起動時にターンは閉じられました。未完了のツール呼び出しの結果は不明です。`,"message.failure.accountSignInRequired":`DeepSeekにログインし、リクエスト先がアカウント認証に対応していることを確認してください。`,"message.failure.quota":`リクエストのクォータを使い切りました。`,"message.turnError":`このターンは失敗しました`,"message.maxTokens":`出力トークンの上限に達しました`,"message.maxTokens.hint":`応答が途中で打ち切られました。それまでの出力は会話に保持されています。「続けて」と送信するとモデルが再開します。`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`ターンの使用量`,"message.turnUsage.consumed":`使用量 {total}`,"message.turnUsage.model":`プロバイダー / モデル`,"message.turnUsage.cacheHit":`キャッシュヒット`,"message.turnUsage.input":`未キャッシュの入力`,"message.turnUsage.cacheRead":`キャッシュ済み入力`,"message.turnUsage.cacheWrite":`キャッシュ書き込み`,"message.turnUsage.output":`出力`,"message.turnUsage.reasoning":` (推論 {tokens})`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`秒`,"duration.minuteUnit":`分 `,"duration.hourUnit":`時間 `,"command.running":`実行中…`,"command.failed":`コマンドが失敗しました`,"command.done":`完了`,"command.title":`コマンド`,"row.running":`実行中`,"row.failed":`失敗`,"json.truncated":`… 省略表示、全{total}文字`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const es={"message.stepProcess.thinking":`Analizando la solicitud`,"message.stepProcess.thinkingNext":`{title}, pensando en el siguiente paso`,"message.stepProcess.read":`Leyendo archivos`,"message.stepProcess.readImage":`Leyendo imágenes`,"message.stepProcess.write":`Escribir archivos`,"message.stepProcess.search":`código de búsqueda`,"message.stepProcess.edit":`Editar archivos`,"message.stepProcess.commands":`Ejecutar comandos`,"message.stepProcess.code":`Código en ejecución`,"message.stepProcess.webSearch":`buscando en la web`,"message.stepProcess.webFetch":`Visitar páginas web`,"message.stepProcess.subagents":`Subagentes coordinadores`,"message.stepProcess.plan":`Actualizando el plan`,"message.stepProcess.questions":`Esperando tu acción`,"message.stepProcess.tools":`herramientas de llamada`,"message.stepProcess.prepare.read":`Preparándose para leer archivos`,"message.stepProcess.prepare.readImage":`Preparándose para leer imágenes`,"message.stepProcess.prepare.write":`Preparándose para escribir archivos`,"message.stepProcess.prepare.search":`Preparándose para buscar el código`,"message.stepProcess.prepare.edit":`Preparándose para editar archivos`,"message.stepProcess.prepare.commands":`Preparándose para ejecutar comandos`,"message.stepProcess.prepare.code":`Preparándose para ejecutar código`,"message.stepProcess.prepare.webSearch":`Preparándose para buscar en la web`,"message.stepProcess.prepare.webFetch":`Preparándose para visitar páginas web`,"message.stepProcess.prepare.subagents":`Preparándose para coordinar subagentes`,"message.stepProcess.prepare.plan":`Preparándose para actualizar el plan`,"message.stepProcess.prepare.questions":`Preparando preguntas`,"message.stepProcess.prepare.tools":`Preparando llamadas a herramientas`,"message.stepProcess.done.thinking":`Análisis completado`,"message.stepProcess.done.read":`leer archivos`,"message.stepProcess.done.readImage":`Leer imágenes`,"message.stepProcess.done.write":`Escribió archivos`,"message.stepProcess.done.search":`código buscado`,"message.stepProcess.done.edit":`Archivos editados`,"message.stepProcess.done.commands":`Comandos ejecutados`,"message.stepProcess.done.code":`código ejecutado`,"message.stepProcess.done.webSearch":`Busqué en la web`,"message.stepProcess.done.webFetch":`Paginas web visitadas`,"message.stepProcess.done.subagents":`Subagentes coordinados`,"message.stepProcess.done.plan":`Actualizado el plan`,"message.stepProcess.done.questions":`preguntas hechas`,"message.stepProcess.done.tools":`herramientas llamadas`,"message.stepProcess.done.context":`Contexto inyectado`,"message.stepProcess.joinTwo":`{first} y {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Ejecución solicitada`,"message.trigger.goal":`Objetivo continuo`,"message.trigger.agent":`Mensaje de tarea recibido`,"message.trigger.team":`Mensaje del equipo recibido`,"message.trigger.subagent":`Estado de subtarea actualizado`,"message.trigger.subagent.completed":`Ejecución del subagente completada`,"message.trigger.subagent.aborted":`Ejecución del subagente detenida`,"message.trigger.subagent.error":`La ejecución del subagente falló`,"message.trigger.subagent.maxTokens":`El subagente alcanzó el límite de tokens`,"message.trigger.subagent.refusal":`El subagente rechazó la tarea`,"message.trigger.subagent.unknown":`La ejecución del subagente terminó de forma inesperada`,"message.trigger.github":`Evento GitHub recibido`,"message.trigger.webhook":`Evento externo recibido`,"message.trigger.schedule":`Tarea de automatización`,"message.trigger.job":`Tarea en segundo plano actualizada`,"message.trigger.plugin":`Estado del complemento actualizado`,"message.trigger.explanation":`Esta notificación desencadenó esta respuesta.`,"message.turnProcess.worked":`Completado`,"message.turnProcess.took":`Completado en `,"message.turnProcess.failed":`Fallido`,"view.chat":`Chat`,"image.open":`Ver imagen completa`,"image.loading":`Cargando imagen…`,"image.failed":`Vista previa de la imagen no disponible`,"image.dialog":`Vista previa de la imagen`,"image.close":`Cerrar vista previa de la imagen`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turnos, {steps} pasos`,"stats.cacheHit":`Aciertos de caché: {percent}%`,"stats.dialog.title":`Estadísticas de sesión`,"stats.dialog.usageTitle":`Uso de tokens`,"stats.dialog.llmTime":`tiempo de maestría`,"stats.dialog.toolTime":`tiempo de herramienta`,"stats.dialog.ttft":`Tiempo promedio hasta el primer token (TTFT)`,"stats.dialog.speed":`Fichas por segundo (TPS)`,"chat.loadingHistory":`Cargando historial…`,"chat.loadError":`No se pudo cargar el historial: {message} ({code})`,"chat.loadOlder":`Cargar antes`,"chat.loadingOlder":`Cargando anteriores`,"chat.processingOlder":`Procesando`,"chat.retryOlder":`Reintentar carga`,"chat.historyStart":`Inicio de la conversación`,"chat.toBottom":`Volver al fondo`,"chat.deepDiving":`Razonamiento profundo`,"chat.deepDivingFor":`Razonando a fondo durante {duration} ···`,"chat.turnNavigation.label":`Navegación por turnos`,"chat.turnNavigation.jump":`Ir al turno {turn}`,"chat.turnNavigation.jumpLoad":`Cargar e ir al turno {turn}`,"chat.turnNavigation.turn":`Turno {turn}`,"settings.performance.title":`Rendimiento y uso`,"settings.performance.description":`Elija cuánta información de rendimiento y uso desea mostrar`,"settings.performance.compact":`Compacto`,"settings.performance.detailed":`Detallado`,"settings.links.title":`Abrir enlaces de chat en`,"settings.links.description":`Elija dónde abrir enlaces web`,"settings.links.sidebar":`Barra lateral en la aplicación`,"settings.links.newTab":`Navegador predeterminado`,"settings.transcript.title":`Detalles del trabajo`,"settings.transcript.description":`Elija cuántos detalles mostrar para las llamadas de herramientas`,"settings.collapse.title":`Cuándo contraer los detalles del trabajo`,"settings.collapse.description":`Elija cuándo contraer automáticamente los detalles del trabajo`,"settings.collapse.completion":`Al finalizar`,"settings.collapse.nextInput":`En el siguiente mensaje`,"settings.foldedReplies.title":`Respuestas después del plegado`,"settings.foldedReplies.description":`Elija qué respuestas del asistente permanecen visibles cuando los detalles del trabajo colapsan`,"settings.foldedReplies.all":`Todas las respuestas`,"settings.foldedReplies.final":`Solo respuesta final`,"settings.transcript.compact":`Compacto`,"settings.transcript.standard":`Estándar`,"settings.transcript.detailed":`Detallado`,"settings.transcript.verbose":`Detallado`,"fileOpen.title":`No se pudo abrir el archivo`,"fileOpen.unknown":`No se pudo abrir este archivo`,"message.extraBlock":`Bloque de contenido adicional`,"message.systemPrompt":`Aviso del sistema`,"message.systemPromptUpdate":`Actualización del mensaje del sistema`,"message.systemSection.added":`Añadido {name}`,"message.systemSection.updated":`Actualizado {name}`,"message.systemSection.cleared":`Vaciado {name}`,"message.systemSection.reordered":`Reordenado {name}`,"message.systemSection.removed":`Eliminado {name}`,"message.systemSection.unchanged":`Sin cambios {name}`,"message.systemPromptReset":`Reemplaza todas las instrucciones anteriores`,"message.systemPromptSections":`{count} secciones`,"message.toolAdded":`Herramienta agregada: {name}`,"message.toolRemoved":`Herramienta eliminada: {name}`,"message.toolsAdded":`Añadido: {names}`,"message.toolsAddedCount":`{count} añadido`,"message.toolsChanged":`{added} agregado, {removed} eliminado`,"message.toolsRemoved":`Eliminado: {names}`,"message.toolsRemovedCount":`{count} eliminado`,"message.toolsUpdated":`Herramientas actualizadas`,"message.contextInjection":`inyección de contexto`,"message.contextRecall":`Recuerdo de sesión`,"message.referenceSummary":`Sesión referenciada · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`cargado`,"message.context.instructions.added":`añadido`,"message.context.instructions.updated":`actualizado`,"message.context.instructions.removed":`eliminado`,"message.context.catalog.replaced":`Catálogo de repuestos`,"message.context.catalog.more":`… {count} más`,"message.context.snapshot.supersedes":`Reemplaza instantáneas anteriores`,"message.context.relay.from":`De la sesión {session}`,"message.context.recall.counts":`{retained} mantenido · {omitted} omitido`,"message.context.recall.truncated":`truncado`,"message.compaction":`Contexto compactado`,"message.inheritedHistory":`Historial heredado arriba`,"message.compaction.running":`Contexto de compactación…`,"message.compaction.completed":`Elementos del historial {items} compactados (~tokens {tokens})`,"message.compaction.open":`Ver el resumen de compactación en la barra lateral`,"message.compaction.notFound":`Resumen no disponible: el servicio no está disponible o el registro falta, está vacío o no es válido.`,"message.compaction.readFailed":`No se pudo leer el resumen`,"message.compaction.landed":`Historial anterior condensado en un resumen`,"message.compaction.commandTitle":`compacto`,"message.think":`pensar`,"message.unknownSurface":`Evento de superficie desconocido: {type}`,"message.unknownBlock":`Bloque de contenido desconocido`,"message.turnProcess.toolCalls.one":`Llamada a la herramienta {count}`,"message.turnProcess.toolCalls.other":`Llamadas a herramientas {count}`,"message.turnProcess.messages.one":`Mensaje {count}`,"message.turnProcess.messages.other":`Mensajes {count}`,"message.turnProcess.subagents.one":`Subagente {count}`,"message.turnProcess.subagents.other":`Subagentes {count}`,"message.turnProcess.thoughtForAWhile":`Razonó durante un tiempo`,"message.turnProcess.separator":` · `,"message.stopped":`Detenido`,"message.branch":`Pasar a una nueva conversación`,"message.branchUnavailable":`Disponible solo en el último mensaje de un turno completado`,"message.retry.active":`Reintentando solicitud de modelo`,"message.retry.cancelled":`Reintento de solicitud de modelo cancelado`,"message.retry.started":`Solicitud de modelo reintentada`,"message.continuation.requested":`Se ha solicitado continuar la generación`,"message.retry.scheduled":`Esperando para volver a intentar la solicitud de modelo`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Retraso de reintento: `,"message.retry.failure":`Razón del fracaso: `,"message.retry.inspect":`Inspeccionar`,"message.failure.auth":`La clave API no es válida`,"message.taskStopped":`Tarea detenida`,"message.failure.accountSignedOut":`Se detuvo porque cerró sesión en DeepSeek.`,"message.failure.interrupted":`El proceso DSH salió antes de que terminara este turno (por ejemplo, se detuvo, se estrelló o se agotó el tiempo de espera mientras se apagaba), por lo que el turno se cerró cuando se reinició DSH. Las llamadas a herramientas inacabadas tienen resultados desconocidos.`,"message.failure.accountSignInRequired":`Inicie sesión en DeepSeek y asegúrese de que el destino de la solicitud admita la autenticación de la cuenta.`,"message.failure.quota":`Solicitud de cupo agotado.`,"message.turnError":`Este turno falló`,"message.maxTokens":`Se alcanzó el límite del token de salida`,"message.maxTokens.hint":`La respuesta fue cortada; La salida anterior se conserva en la conversación. Envíe "continuar" para permitir que se reanude el modelo.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Uso del turno`,"message.turnUsage.consumed":`Uso {total}`,"message.turnUsage.model":`Proveedor / modelo`,"message.turnUsage.cacheHit":`Aciertos de caché`,"message.turnUsage.input":`Entrada sin caché`,"message.turnUsage.cacheRead":`Entrada en caché`,"message.turnUsage.cacheWrite":`escritura en caché`,"message.turnUsage.output":`Salida`,"message.turnUsage.reasoning":` (razonamiento {tokens})`,"message.turnUsage.count":`Tok {count}`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Corriendo…`,"command.failed":`El comando falló`,"command.done":`Completado`,"command.title":`Comando`,"row.running":`corriendo`,"row.failed":`Fallido`,"json.truncated":`… truncado, caracteres {total} en total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const fr={"message.stepProcess.thinking":`Analyser la demande`,"message.stepProcess.thinkingNext":`{title}, réflexion sur l'étape suivante`,"message.stepProcess.read":`Lecture de fichiers`,"message.stepProcess.readImage":`Lire des images`,"message.stepProcess.write":`Écriture de fichiers`,"message.stepProcess.search":`Recherche de code`,"message.stepProcess.edit":`Modification de fichiers`,"message.stepProcess.commands":`Exécuter des commandes`,"message.stepProcess.code":`Exécution du code`,"message.stepProcess.webSearch":`Recherche sur le Web`,"message.stepProcess.webFetch":`Visiter des pages Web`,"message.stepProcess.subagents":`Sous-agents de coordination`,"message.stepProcess.plan":`Mise à jour du plan`,"message.stepProcess.questions":`En attendant votre action`,"message.stepProcess.tools":`Outils d'appel`,"message.stepProcess.prepare.read":`Préparation à la lecture de fichiers`,"message.stepProcess.prepare.readImage":`Se préparer à lire des images`,"message.stepProcess.prepare.write":`Préparation à l'écriture de fichiers`,"message.stepProcess.prepare.search":`Préparation à la recherche de code`,"message.stepProcess.prepare.edit":`Préparation à la modification de fichiers`,"message.stepProcess.prepare.commands":`Préparation à l'exécution de commandes`,"message.stepProcess.prepare.code":`Préparation à l'exécution du code`,"message.stepProcess.prepare.webSearch":`Se préparer à effectuer une recherche sur le Web`,"message.stepProcess.prepare.webFetch":`Se préparer à visiter des pages Web`,"message.stepProcess.prepare.subagents":`Se préparer à coordonner les sous-agents`,"message.stepProcess.prepare.plan":`Préparation de la mise à jour du plan`,"message.stepProcess.prepare.questions":`Préparation des questions`,"message.stepProcess.prepare.tools":`Préparation des appels d'outils`,"message.stepProcess.done.thinking":`Analyse terminée`,"message.stepProcess.done.read":`Lire des fichiers`,"message.stepProcess.done.readImage":`Lire des images`,"message.stepProcess.done.write":`A écrit des fichiers`,"message.stepProcess.done.search":`Code recherché`,"message.stepProcess.done.edit":`Fichiers modifiés`,"message.stepProcess.done.commands":`Commandes exécutées`,"message.stepProcess.done.code":`Code exécuté`,"message.stepProcess.done.webSearch":`J'ai cherché sur le Web`,"message.stepProcess.done.webFetch":`Pages Web visitées`,"message.stepProcess.done.subagents":`Sous-agents coordonnés`,"message.stepProcess.done.plan":`Plan mis à jour`,"message.stepProcess.done.questions":`Questions posées`,"message.stepProcess.done.tools":`Outils appelés`,"message.stepProcess.done.context":`Contexte injecté`,"message.stepProcess.joinTwo":`{first} et {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Exécution demandée`,"message.trigger.goal":`Objectif continu`,"message.trigger.agent":`Message de tâche reçu`,"message.trigger.team":`Message d'équipe reçu`,"message.trigger.subagent":`Statut de la sous-tâche mis à jour`,"message.trigger.subagent.completed":`Exécution du sous-agent terminée`,"message.trigger.subagent.aborted":`Exécution du sous-agent arrêtée`,"message.trigger.subagent.error":`Échec de l’exécution du sous-agent`,"message.trigger.subagent.maxTokens":`Le sous-agent a atteint la limite de jetons`,"message.trigger.subagent.refusal":`Le sous-agent a refusé la tâche`,"message.trigger.subagent.unknown":`L’exécution du sous-agent s’est terminée de façon inattendue`,"message.trigger.github":`Événement GitHub reçu`,"message.trigger.webhook":`Événement externe reçu`,"message.trigger.schedule":`Tâche d'automatisation`,"message.trigger.job":`Tâche en arrière-plan mise à jour`,"message.trigger.plugin":`Statut du plugin mis à jour`,"message.trigger.explanation":`Cette notification a déclenché cette réponse.`,"message.turnProcess.worked":`Terminé`,"message.turnProcess.took":`Terminé en `,"message.turnProcess.failed":`Échec`,"view.chat":`Discussion`,"image.open":`Voir l'image complète`,"image.loading":`Chargement de l'image…`,"image.failed":`Aperçu de l'image indisponible`,"image.dialog":`Aperçu de l'image`,"image.close":`Fermer l'aperçu de l'image`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} tours, {steps} étapes`,"stats.cacheHit":`Taux de réussite du cache : {percent} %`,"stats.dialog.title":`Statistiques de session`,"stats.dialog.usageTitle":`Utilisation des jetons`,"stats.dialog.llmTime":`Temps LLM`,"stats.dialog.toolTime":`Temps d'outil`,"stats.dialog.ttft":`Temps moyen jusqu'au premier jeton (TTFT)`,"stats.dialog.speed":`Jetons par seconde (TPS)`,"chat.loadingHistory":`Chargement de l'historique…`,"chat.loadError":`Échec du chargement de l'historique\xA0: {message} ({code})`,"chat.loadOlder":`Charger plus tôt`,"chat.loadingOlder":`Chargement en cours`,"chat.processingOlder":`Traitement en cours`,"chat.retryOlder":`Réessayer`,"chat.historyStart":`Début de la conversation`,"chat.toBottom":`Retour en bas`,"chat.deepDiving":`Réflexion approfondie`,"chat.deepDivingFor":`Réflexion approfondie depuis {duration} ···`,"chat.turnNavigation.label":`Navigation entre les tours`,"chat.turnNavigation.jump":`Aller au tour {turn}`,"chat.turnNavigation.jumpLoad":`Charger et aller au tour {turn}`,"chat.turnNavigation.turn":`Tour {turn}`,"settings.performance.title":`Performances et utilisation`,"settings.performance.description":`Choisissez la quantité d'informations sur les performances et l'utilisation à afficher`,"settings.performance.compact":`Compacte`,"settings.performance.detailed":`Détaillé`,"settings.links.title":`Ouvrir les liens de discussion dans`,"settings.links.description":`Choisissez où ouvrir les liens Web`,"settings.links.sidebar":`Barre latérale dans l'application`,"settings.links.newTab":`Navigateur par défaut`,"settings.transcript.title":`Détails du travail`,"settings.transcript.description":`Choisissez le niveau de détails à afficher pour les appels d'outils`,"settings.collapse.title":`Quand réduire les détails du travail`,"settings.collapse.description":`Choisissez quand réduire automatiquement les détails du travail`,"settings.collapse.completion":`À la fin`,"settings.collapse.nextInput":`Au prochain message`,"settings.foldedReplies.title":`Réponses après le repli`,"settings.foldedReplies.description":`Choisissez quelles réponses de l'assistant restent visibles lorsque les détails du travail sont réduits`,"settings.foldedReplies.all":`Toutes les réponses`,"settings.foldedReplies.final":`Réponse finale seulement`,"settings.transcript.compact":`Compacte`,"settings.transcript.standard":`Norme`,"settings.transcript.detailed":`Détaillé`,"settings.transcript.verbose":`Verbeux`,"fileOpen.title":`Impossible d'ouvrir le fichier`,"fileOpen.unknown":`Impossible d'ouvrir ce fichier`,"message.extraBlock":`Bloc de contenu supplémentaire`,"message.systemPrompt":`Invite système`,"message.systemPromptUpdate":`Mise à jour de l'invite du système`,"message.systemSection.added":`Ajouté {name}`,"message.systemSection.updated":`Mis à jour {name}`,"message.systemSection.cleared":`Vidé {name}`,"message.systemSection.reordered":`Réordonné {name}`,"message.systemSection.removed":`Supprimé {name}`,"message.systemSection.unchanged":`Inchangé {name}`,"message.systemPromptReset":`Remplace toutes les instructions précédentes`,"message.systemPromptSections":`{count} sections`,"message.toolAdded":`Outil ajouté\xA0: {name}`,"message.toolRemoved":`Outil supprimé\xA0: {name}`,"message.toolsAdded":`Ajouté\xA0: {names}`,"message.toolsAddedCount":`{count} ajouté`,"message.toolsChanged":`{added} ajouté, {removed} supprimé`,"message.toolsRemoved":`Supprimé\xA0: {names}`,"message.toolsRemovedCount":`{count} supprimé`,"message.toolsUpdated":`Outils mis à jour`,"message.contextInjection":`Injection de contexte`,"message.contextRecall":`Rappel de session`,"message.referenceSummary":`Séance référencée · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`chargé`,"message.context.instructions.added":`ajouté`,"message.context.instructions.updated":`mis à jour`,"message.context.instructions.removed":`supprimé`,"message.context.catalog.replaced":`Catalogue de remplacement`,"message.context.catalog.more":`… {count} plus`,"message.context.snapshot.supersedes":`Remplace les instantanés précédents`,"message.context.relay.from":`De la séance {session}`,"message.context.recall.counts":`{retained} conservé · {omitted} omis`,"message.context.recall.truncated":`tronqué`,"message.compaction":`Contexte compacté`,"message.inheritedHistory":`Historique hérité ci-dessus`,"message.compaction.running":`Contexte de compactage…`,"message.compaction.completed":`Éléments d'historique {items} compactés (~jetons {tokens})`,"message.compaction.open":`Afficher le résumé de compactage dans le panneau latéral`,"message.compaction.notFound":`Résumé indisponible : le service est indisponible ou le résumé est absent, vide ou invalide.`,"message.compaction.readFailed":`Impossible de lire le résumé`,"message.compaction.landed":`Historique antérieur condensé en résumé`,"message.compaction.commandTitle":`compacte`,"message.think":`Pensez`,"message.unknownSurface":`Événement de surface inconnu\xA0: {type}`,"message.unknownBlock":`Bloc de contenu inconnu`,"message.turnProcess.toolCalls.one":`Appel d'outil {count}`,"message.turnProcess.toolCalls.other":`Appels d'outil {count}`,"message.turnProcess.messages.one":`Message {count}`,"message.turnProcess.messages.other":`Messages {count}`,"message.turnProcess.subagents.one":`Sous-agent {count}`,"message.turnProcess.subagents.other":`Sous-agents {count}`,"message.turnProcess.thoughtForAWhile":`Réflexion pendant un moment`,"message.turnProcess.separator":` · `,"message.stopped":`Arrêté`,"message.branch":`Lancez-vous dans une nouvelle conversation`,"message.branchUnavailable":`Disponible uniquement sur le dernier message d'un tour terminé`,"message.retry.active":`Nouvelle tentative de demande de modèle`,"message.retry.cancelled":`Nouvelle tentative de demande de modèle annulée`,"message.retry.started":`Demande de modèle réessayée`,"message.continuation.requested":`Suite de la génération demandée`,"message.retry.scheduled":`En attente de réessayer la demande de modèle`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds} s`,"message.retry.delay":`Délai de nouvelle tentative\xA0: `,"message.retry.failure":`Raison de l'échec\xA0: `,"message.retry.inspect":`Inspecter`,"message.failure.auth":`La clé API n'est pas valide`,"message.taskStopped":`Tâche arrêtée`,"message.failure.accountSignedOut":`Arrêté car vous vous êtes déconnecté de DeepSeek.`,"message.failure.interrupted":`Le processus DSH s'est terminé avant la fin de ce tour (par exemple, il a été arrêté, s'est écrasé ou a expiré lors de l'arrêt), de sorte que le tour a été fermé lorsque DSH a redémarré. Les appels d’outils inachevés ont des résultats inconnus.`,"message.failure.accountSignInRequired":`Connectez-vous à DeepSeek et assurez-vous que la destination de la demande prend en charge l'authentification du compte.`,"message.failure.quota":`Quota de demandes épuisé.`,"message.turnError":`Ce tour a échoué`,"message.maxTokens":`Limite de jetons de sortie atteinte`,"message.maxTokens.hint":`La réponse fut coupée ; la sortie antérieure est conservée dans la conversation. Envoyez «\xA0continuer\xA0» pour laisser le modèle reprendre.`,"message.tokensPerSecond":`{tps} jetons/s`,"message.turnUsage.title":`Consommation du tour`,"message.turnUsage.consumed":`Utilisation {total}`,"message.turnUsage.model":`Fournisseur / modèle`,"message.turnUsage.cacheHit":`Taux de réussite du cache`,"message.turnUsage.input":`Entrée non mise en cache`,"message.turnUsage.cacheRead":`Entrée en cache`,"message.turnUsage.cacheWrite":`Écriture en cache`,"message.turnUsage.output":`Sortie`,"message.turnUsage.reasoning":` (raisonnement {tokens})`,"message.turnUsage.count":`Jeton {count}`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Courir…`,"command.failed":`La commande a échoué`,"command.done":`Terminé`,"command.title":`Commande`,"row.running":`Courir`,"row.failed":`Échec`,"json.truncated":`… tronqué, nombre total de caractères {total}`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const de={"message.stepProcess.thinking":`Analyse der Anfrage`,"message.stepProcess.thinkingNext":`{title}, Überlegung zum nächsten Schritt`,"message.stepProcess.read":`Dateien lesen`,"message.stepProcess.readImage":`Bilder lesen`,"message.stepProcess.write":`Dateien schreiben`,"message.stepProcess.search":`Code wird gesucht`,"message.stepProcess.edit":`Bearbeiten von Dateien`,"message.stepProcess.commands":`Befehle ausführen`,"message.stepProcess.code":`Ausführen von Code`,"message.stepProcess.webSearch":`Suche im Internet`,"message.stepProcess.webFetch":`Besuch von Webseiten`,"message.stepProcess.subagents":`Koordinierende Unteragenten`,"message.stepProcess.plan":`Aktualisierung des Plans`,"message.stepProcess.questions":`Ich warte auf Ihre Aktion`,"message.stepProcess.tools":`Aufrufende Werkzeuge`,"message.stepProcess.prepare.read":`Vorbereitung zum Lesen von Dateien`,"message.stepProcess.prepare.readImage":`Vorbereitung zum Lesen von Bildern`,"message.stepProcess.prepare.write":`Vorbereitung zum Schreiben von Dateien`,"message.stepProcess.prepare.search":`Vorbereiten der Codesuche`,"message.stepProcess.prepare.edit":`Vorbereitung zum Bearbeiten von Dateien`,"message.stepProcess.prepare.commands":`Vorbereitung zum Ausführen von Befehlen`,"message.stepProcess.prepare.code":`Vorbereiten, Code auszuführen`,"message.stepProcess.prepare.webSearch":`Bereiten Sie sich auf die Suche im Internet vor`,"message.stepProcess.prepare.webFetch":`Vorbereitung auf den Besuch von Webseiten`,"message.stepProcess.prepare.subagents":`Vorbereitung zur Koordinierung von Subagenten`,"message.stepProcess.prepare.plan":`Vorbereitung zur Aktualisierung des Plans`,"message.stepProcess.prepare.questions":`Fragen vorbereiten`,"message.stepProcess.prepare.tools":`Toolaufrufe vorbereiten`,"message.stepProcess.done.thinking":`Analyse abgeschlossen`,"message.stepProcess.done.read":`Dateien lesen`,"message.stepProcess.done.readImage":`Bilder lesen`,"message.stepProcess.done.write":`Dateien geschrieben`,"message.stepProcess.done.search":`Gesuchter Code`,"message.stepProcess.done.edit":`Bearbeitete Dateien`,"message.stepProcess.done.commands":`Befehle ausgeführt`,"message.stepProcess.done.code":`Code ausgeführt`,"message.stepProcess.done.webSearch":`Habe das Internet durchsucht`,"message.stepProcess.done.webFetch":`Besuchte Webseiten`,"message.stepProcess.done.subagents":`Koordinierte Unteragenten`,"message.stepProcess.done.plan":`Plan aktualisiert`,"message.stepProcess.done.questions":`Gestellte Fragen`,"message.stepProcess.done.tools":`Werkzeuge genannt`,"message.stepProcess.done.context":`Kontext injiziert`,"message.stepProcess.joinTwo":`{first} und {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title} usw.`,"message.trigger.request":`Ausführung beantragt`,"message.trigger.goal":`Weiterführendes Ziel`,"message.trigger.agent":`Aufgabennachricht erhalten`,"message.trigger.team":`Teamnachricht erhalten`,"message.trigger.subagent":`Unteraufgabenstatus aktualisiert`,"message.trigger.subagent.completed":`Ausführung des Subagenten abgeschlossen`,"message.trigger.subagent.aborted":`Ausführung des Subagenten gestoppt`,"message.trigger.subagent.error":`Ausführung des Subagenten fehlgeschlagen`,"message.trigger.subagent.maxTokens":`Subagent hat das Token-Limit erreicht`,"message.trigger.subagent.refusal":`Subagent hat die Aufgabe abgelehnt`,"message.trigger.subagent.unknown":`Ausführung des Subagenten unerwartet beendet`,"message.trigger.github":`GitHub-Ereignis empfangen`,"message.trigger.webhook":`Externes Ereignis empfangen`,"message.trigger.schedule":`Automatisierungsaufgabe`,"message.trigger.job":`Hintergrundaufgabe aktualisiert`,"message.trigger.plugin":`Plugin-Status aktualisiert`,"message.trigger.explanation":`Diese Benachrichtigung hat diese Reaktion ausgelöst.`,"message.turnProcess.worked":`Abgeschlossen`,"message.turnProcess.took":`Fertiggestellt in `,"message.turnProcess.failed":`Fehlgeschlagen`,"view.chat":`Chat`,"image.open":`Vollständiges Bild anzeigen`,"image.loading":`Bild wird geladen…`,"image.failed":`Bildvorschau nicht verfügbar`,"image.dialog":`Bildvorschau`,"image.close":`Bildvorschau schließen`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} Runden, {steps} Schritte`,"stats.cacheHit":`Cache-Treffer: {percent}%`,"stats.dialog.title":`Sitzungsstatistiken`,"stats.dialog.usageTitle":`Token-Nutzung`,"stats.dialog.llmTime":`LLM-Zeit`,"stats.dialog.toolTime":`Werkzeugzeit`,"stats.dialog.ttft":`Durchschnittliche Zeit bis zum ersten Token (TTFT)`,"stats.dialog.speed":`Token pro Sekunde (TPS)`,"chat.loadingHistory":`Verlauf wird geladen…`,"chat.loadError":`Fehler beim Laden des Verlaufs: {message} ({code})`,"chat.loadOlder":`Früher laden`,"chat.loadingOlder":`Wird geladen`,"chat.processingOlder":`Wird verarbeitet`,"chat.retryOlder":`Erneut laden`,"chat.historyStart":`Anfang der Unterhaltung`,"chat.toBottom":`Zurück nach unten`,"chat.deepDiving":`Gründliches Nachdenken`,"chat.deepDivingFor":`Gründliches Nachdenken seit {duration} ···`,"chat.turnNavigation.label":`Rundennavigation`,"chat.turnNavigation.jump":`Zu Runde {turn} springen`,"chat.turnNavigation.jumpLoad":`Runde {turn} laden und öffnen`,"chat.turnNavigation.turn":`Runde {turn}`,"settings.performance.title":`Leistung und Nutzung`,"settings.performance.description":`Wählen Sie aus, wie viele Leistungs- und Nutzungsinformationen angezeigt werden sollen`,"settings.performance.compact":`Kompakt`,"settings.performance.detailed":`Ausführlich`,"settings.links.title":`Öffnen Sie Chat-Links in`,"settings.links.description":`Wählen Sie aus, wo Weblinks geöffnet werden sollen`,"settings.links.sidebar":`In-App-Seitenleiste`,"settings.links.newTab":`Standardbrowser`,"settings.transcript.title":`Arbeitsdetails`,"settings.transcript.description":`Wählen Sie aus, wie viele Details für Werkzeugaufrufe angezeigt werden sollen`,"settings.collapse.title":`Wann Arbeitsdetails minimiert werden sollten`,"settings.collapse.description":`Wählen Sie aus, wann Arbeitsdetails automatisch ausgeblendet werden sollen`,"settings.collapse.completion":`Nach Fertigstellung`,"settings.collapse.nextInput":`Bei der nächsten Nachricht`,"settings.foldedReplies.title":`Antworten nach dem Einklappen`,"settings.foldedReplies.description":`Wählen Sie aus, welche Assistentenantworten sichtbar bleiben, wenn die Arbeitsdetails ausgeblendet werden`,"settings.foldedReplies.all":`Alle Antworten`,"settings.foldedReplies.final":`Nur die endgültige Antwort`,"settings.transcript.compact":`Kompakt`,"settings.transcript.standard":`Standard`,"settings.transcript.detailed":`Ausführlich`,"settings.transcript.verbose":`Ausführlich`,"fileOpen.title":`Datei konnte nicht geöffnet werden`,"fileOpen.unknown":`Diese Datei konnte nicht geöffnet werden`,"message.extraBlock":`Zusätzlicher Inhaltsblock`,"message.systemPrompt":`Systemaufforderung`,"message.systemPromptUpdate":`Aktualisierung der Systemaufforderung`,"message.systemSection.added":`Hinzugefügt {name}`,"message.systemSection.updated":`Aktualisiert {name}`,"message.systemSection.cleared":`Geleert {name}`,"message.systemSection.reordered":`Neu angeordnet {name}`,"message.systemSection.removed":`Entfernt {name}`,"message.systemSection.unchanged":`Unverändert {name}`,"message.systemPromptReset":`Ersetzt alle früheren Anweisungen`,"message.systemPromptSections":`{count} Abschnitte`,"message.toolAdded":`Tool hinzugefügt: {name}`,"message.toolRemoved":`Entferntes Werkzeug: {name}`,"message.toolsAdded":`Hinzugefügt: {names}`,"message.toolsAddedCount":`{count} hinzugefügt`,"message.toolsChanged":`{added} hinzugefügt, {removed} entfernt`,"message.toolsRemoved":`Entfernt: {names}`,"message.toolsRemovedCount":`{count} entfernt`,"message.toolsUpdated":`Werkzeuge aktualisiert`,"message.contextInjection":`Kontextinjektion`,"message.contextRecall":`Sitzungsrückruf`,"message.referenceSummary":`Referenzierte Sitzung · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`geladen`,"message.context.instructions.added":`hinzugefügt`,"message.context.instructions.updated":`aktualisiert`,"message.context.instructions.removed":`entfernt`,"message.context.catalog.replaced":`Ersatzkatalog`,"message.context.catalog.more":`… {count} mehr`,"message.context.snapshot.supersedes":`Ersetzt frühere Schnappschüsse`,"message.context.relay.from":`Aus der Sitzung {session}`,"message.context.recall.counts":`{retained} beibehalten · {omitted} weggelassen`,"message.context.recall.truncated":`abgeschnitten`,"message.compaction":`Kontext verdichtet`,"message.inheritedHistory":`Übernommener Verlauf oben`,"message.compaction.running":`Kontext verdichten…`,"message.compaction.completed":`Komprimierte {items}-Verlaufselemente (~{tokens}-Tokens)`,"message.compaction.open":`Zusammenfassung der Komprimierung in der Seitenleiste anzeigen`,"message.compaction.notFound":`Zusammenfassung nicht verfügbar: Der Dienst ist nicht verfügbar oder der Eintrag fehlt, ist leer oder ungültig.`,"message.compaction.readFailed":`Zusammenfassung konnte nicht gelesen werden`,"message.compaction.landed":`Früherer Verlauf zu einer Zusammenfassung verdichtet`,"message.compaction.commandTitle":`kompakt`,"message.think":`Denken Sie nach`,"message.unknownSurface":`Unbekanntes Oberflächenereignis: {type}`,"message.unknownBlock":`Unbekannter Inhaltsblock`,"message.turnProcess.toolCalls.one":`Werkzeugaufruf {count}`,"message.turnProcess.toolCalls.other":`{count} Toolaufrufe`,"message.turnProcess.messages.one":`{count}-Nachricht`,"message.turnProcess.messages.other":`{count}-Nachrichten`,"message.turnProcess.subagents.one":`{count}-Subagent`,"message.turnProcess.subagents.other":`{count}-Subagenten`,"message.turnProcess.thoughtForAWhile":`Eine Weile nachgedacht`,"message.turnProcess.separator":` · `,"message.stopped":`Angehalten`,"message.branch":`Verzweigen Sie in ein neues Gespräch`,"message.branchUnavailable":`Nur verfügbar bei der letzten Nachricht einer abgeschlossenen Runde`,"message.retry.active":`Modellanforderung wird erneut versucht`,"message.retry.cancelled":`Wiederholungsversuch der Modellanforderung abgebrochen`,"message.retry.started":`Modellanfrage erneut versucht`,"message.continuation.requested":`Fortsetzung der Generierung angefordert`,"message.retry.scheduled":`Warten auf erneuten Versuch der Modellanforderung`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Wiederholungsverzögerung: `,"message.retry.failure":`Fehlergrund: `,"message.retry.inspect":`Inspizieren`,"message.failure.auth":`Der API-Schlüssel ist ungültig`,"message.taskStopped":`Aufgabe gestoppt`,"message.failure.accountSignedOut":`Gestoppt, weil Sie sich von DeepSeek abgemeldet haben.`,"message.failure.interrupted":`Der DSH-Prozess wurde beendet, bevor dieser Zug beendet war (z. B. wurde er beendet, stürzte ab oder es kam zu einer Zeitüberschreitung beim Herunterfahren), sodass der Zug geschlossen wurde, als DSH neu gestartet wurde. Unvollendete Werkzeugaufrufe haben unbekannte Ergebnisse.`,"message.failure.accountSignInRequired":`Melden Sie sich bei DeepSeek an und stellen Sie sicher, dass das Anforderungsziel die Kontoauthentifizierung unterstützt.`,"message.failure.quota":`Anforderungskontingent ausgeschöpft.`,"message.turnError":`Diese Runde ist fehlgeschlagen`,"message.maxTokens":`Ausgabe-Token-Limit erreicht`,"message.maxTokens.hint":`Die Antwort wurde abgeschnitten; Frühere Ausgaben bleiben in der Konversation erhalten. Senden Sie „Weiter“, um das Modell fortzusetzen.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Rundenverbrauch`,"message.turnUsage.consumed":`Verwendung {total}`,"message.turnUsage.model":`Anbieter / Modell`,"message.turnUsage.cacheHit":`Cache-Treffer`,"message.turnUsage.input":`Nicht zwischengespeicherte Eingabe`,"message.turnUsage.cacheRead":`Zwischengespeicherte Eingabe`,"message.turnUsage.cacheWrite":`Cache-Schreiben`,"message.turnUsage.output":`Ausgabe`,"message.turnUsage.reasoning":` ({tokens}-Argumentation)`,"message.turnUsage.count":`{count}-Token`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Laufen…`,"command.failed":`Der Befehl ist fehlgeschlagen`,"command.done":`Abgeschlossen`,"command.title":`Befehl`,"row.running":`Laufen`,"row.failed":`Fehlgeschlagen`,"json.truncated":`… gekürzt, {total} Zeichen insgesamt`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const ru={"message.stepProcess.thinking":`Анализ запроса`,"message.stepProcess.thinkingNext":`{title}, обдумывание следующего шага`,"message.stepProcess.read":`Чтение файлов`,"message.stepProcess.readImage":`Чтение изображений`,"message.stepProcess.write":`Запись файлов`,"message.stepProcess.search":`Поиск кода`,"message.stepProcess.edit":`Редактирование файлов`,"message.stepProcess.commands":`Запуск команд`,"message.stepProcess.code":`Запуск кода`,"message.stepProcess.webSearch":`Поиск в Интернете`,"message.stepProcess.webFetch":`Посещение веб-страниц`,"message.stepProcess.subagents":`Координирующие субагенты`,"message.stepProcess.plan":`Обновление плана`,"message.stepProcess.questions":`Жду ваших действий`,"message.stepProcess.tools":`Вызов инструментов`,"message.stepProcess.prepare.read":`Подготовка к чтению файлов`,"message.stepProcess.prepare.readImage":`Подготовка к чтению изображений`,"message.stepProcess.prepare.write":`Подготовка к записи файлов`,"message.stepProcess.prepare.search":`Подготовка к поиску кода`,"message.stepProcess.prepare.edit":`Подготовка к редактированию файлов`,"message.stepProcess.prepare.commands":`Подготовка к выполнению команд`,"message.stepProcess.prepare.code":`Подготовка к запуску кода`,"message.stepProcess.prepare.webSearch":`Подготовка к поиску в Интернете`,"message.stepProcess.prepare.webFetch":`Подготовка к посещению веб-страниц`,"message.stepProcess.prepare.subagents":`Подготовка к координации субагентов`,"message.stepProcess.prepare.plan":`Подготовка к обновлению плана`,"message.stepProcess.prepare.questions":`Подготовка вопросов`,"message.stepProcess.prepare.tools":`Подготовка вызовов инструментов`,"message.stepProcess.done.thinking":`Анализ завершен`,"message.stepProcess.done.read":`Чтение файлов`,"message.stepProcess.done.readImage":`Чтение изображений`,"message.stepProcess.done.write":`Написал файлы`,"message.stepProcess.done.search":`Искомый код`,"message.stepProcess.done.edit":`Отредактированные файлы`,"message.stepProcess.done.commands":`Выполнение команд`,"message.stepProcess.done.code":`Выполненный код`,"message.stepProcess.done.webSearch":`Искал в Интернете`,"message.stepProcess.done.webFetch":`Посещенные веб-страницы`,"message.stepProcess.done.subagents":`Координированные субагенты`,"message.stepProcess.done.plan":`Обновлен план`,"message.stepProcess.done.questions":`Задаваемые вопросы`,"message.stepProcess.done.tools":`Вызываемые инструменты`,"message.stepProcess.done.context":`Контекст внедрён`,"message.stepProcess.joinTwo":`{first} и {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title} и т. д.`,"message.trigger.request":`Запрошено выполнение`,"message.trigger.goal":`Постоянная цель`,"message.trigger.agent":`Сообщение о задаче получено`,"message.trigger.team":`Сообщение команды получено`,"message.trigger.subagent":`Статус подзадачи обновлен`,"message.trigger.subagent.completed":`Работа субагента завершена`,"message.trigger.subagent.aborted":`Работа субагента остановлена`,"message.trigger.subagent.error":`Работа субагента завершилась с ошибкой`,"message.trigger.subagent.maxTokens":`Субагент достиг лимита токенов`,"message.trigger.subagent.refusal":`Субагент отказался выполнять задачу`,"message.trigger.subagent.unknown":`Работа субагента неожиданно завершилась`,"message.trigger.github":`Событие GitHub получено`,"message.trigger.webhook":`Получено внешнее событие`,"message.trigger.schedule":`Задача автоматизации`,"message.trigger.job":`Фоновая задача обновлена.`,"message.trigger.plugin":`Статус плагина обновлен`,"message.trigger.explanation":`Это уведомление вызвало такой ответ.`,"message.turnProcess.worked":`Завершено`,"message.turnProcess.took":`Завершено в `,"message.turnProcess.failed":`Не удалось`,"view.chat":`Чат`,"image.open":`Посмотреть полное изображение`,"image.loading":`Загрузка изображения…`,"image.failed":`Предварительный просмотр изображения недоступен.`,"image.dialog":`Предварительный просмотр изображения`,"image.close":`Закрыть предварительный просмотр изображения`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`Ходов: {turns}, шагов: {steps}`,"stats.cacheHit":`Попадание в кэш: {percent}%`,"stats.dialog.title":`Статистика сеансов`,"stats.dialog.usageTitle":`Использование токена`,"stats.dialog.llmTime":`время магистратуры`,"stats.dialog.toolTime":`Время работы инструмента`,"stats.dialog.ttft":`Среднее время до первого токена (TTFT)`,"stats.dialog.speed":`Токенов в секунду (TPS)`,"chat.loadingHistory":`Загрузка истории…`,"chat.loadError":`Не удалось загрузить историю: {message} ({code})`,"chat.loadOlder":`Загрузить раньше`,"chat.loadingOlder":`Загрузка истории`,"chat.processingOlder":`Обработка`,"chat.retryOlder":`Повторить загрузку`,"chat.historyStart":`Начало разговора`,"chat.toBottom":`Вернуться к низу`,"chat.deepDiving":`Глубокое размышление`,"chat.deepDivingFor":`Глубокое размышление в течение {duration} ···`,"chat.turnNavigation.label":`Навигация по ходам`,"chat.turnNavigation.jump":`Перейти к ходу {turn}`,"chat.turnNavigation.jumpLoad":`Загрузить ход {turn} и перейти к нему`,"chat.turnNavigation.turn":`Ход {turn}`,"settings.performance.title":`Производительность и использование`,"settings.performance.description":`Выберите, какой объем информации о производительности и использовании показывать`,"settings.performance.compact":`Компактный`,"settings.performance.detailed":`Подробный`,"settings.links.title":`Открыть ссылки на чат в`,"settings.links.description":`Выберите, где открывать веб-ссылки`,"settings.links.sidebar":`Боковая панель в приложении`,"settings.links.newTab":`Браузер по умолчанию`,"settings.transcript.title":`Детали работы`,"settings.transcript.description":`Выберите, насколько подробно следует отображать вызовы инструментов.`,"settings.collapse.title":`Когда сворачивать детали работы`,"settings.collapse.description":`Выберите, когда автоматически сворачивать сведения о работе`,"settings.collapse.completion":`По завершении`,"settings.collapse.nextInput":`В следующем сообщении`,"settings.foldedReplies.title":`Ответы после сворачивания`,"settings.foldedReplies.description":`Выберите, какие ответы помощника останутся видимыми, когда сведения о работе будут свернуты.`,"settings.foldedReplies.all":`Все ответы`,"settings.foldedReplies.final":`Только окончательный ответ`,"settings.transcript.compact":`Компактный`,"settings.transcript.standard":`Стандартный`,"settings.transcript.detailed":`Подробный`,"settings.transcript.verbose":`Многословный`,"fileOpen.title":`Не удалось открыть файл`,"fileOpen.unknown":`Не удалось открыть этот файл`,"message.extraBlock":`Дополнительный блок контента`,"message.systemPrompt":`Системная подсказка`,"message.systemPromptUpdate":`Обновление системного запроса`,"message.systemSection.added":`Добавлено {name}`,"message.systemSection.updated":`Обновлено {name}`,"message.systemSection.cleared":`Очищено {name}`,"message.systemSection.reordered":`Порядок изменён {name}`,"message.systemSection.removed":`Удалено {name}`,"message.systemSection.unchanged":`Без изменений {name}`,"message.systemPromptReset":`Заменяет все предыдущие инструкции`,"message.systemPromptSections":`Разделов: {count}`,"message.toolAdded":`Добавлен инструмент: {name}.`,"message.toolRemoved":`Инструмент удален: {name}.`,"message.toolsAdded":`Добавлено: {names}`,"message.toolsAddedCount":`{count} добавлен`,"message.toolsChanged":`{added} добавлен, {removed} удален.`,"message.toolsRemoved":`Удалено: {names}.`,"message.toolsRemovedCount":`{count} удален.`,"message.toolsUpdated":`Инструменты обновлены`,"message.contextInjection":`Внедрение контекста`,"message.contextRecall":`Отзыв сеанса`,"message.referenceSummary":`Ссылка на сессию · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`загружен`,"message.context.instructions.added":`добавлено`,"message.context.instructions.updated":`обновлено`,"message.context.instructions.removed":`удалено`,"message.context.catalog.replaced":`Каталог замены`,"message.context.catalog.more":`… {count} ещё`,"message.context.snapshot.supersedes":`Заменяет предыдущие снимки`,"message.context.relay.from":`Из сеанса {session}`,"message.context.recall.counts":`{retained} сохранен · {omitted} опущен`,"message.context.recall.truncated":`усеченный`,"message.compaction":`Контекст сжат`,"message.inheritedHistory":`Выше — унаследованная история`,"message.compaction.running":`Сжатие контекста…`,"message.compaction.completed":`Сжатые элементы истории {items} (токены ~{tokens})`,"message.compaction.open":`Открыть сводку сжатия на боковой панели`,"message.compaction.notFound":`Сводка недоступна: сервис недоступен либо запись отсутствует, пуста или недействительна.`,"message.compaction.readFailed":`Не удалось прочитать сводку`,"message.compaction.landed":`Ранняя история сжата в сводку`,"message.compaction.commandTitle":`компактный`,"message.think":`Подумайте`,"message.unknownSurface":`Неизвестное событие на поверхности: {type}.`,"message.unknownBlock":`Неизвестный блок контента`,"message.turnProcess.toolCalls.one":`{count} вызов инструмента`,"message.turnProcess.toolCalls.other":`{count} вызовов инструментов`,"message.turnProcess.messages.one":`Сообщение {count}`,"message.turnProcess.messages.other":`Сообщения {count}`,"message.turnProcess.subagents.one":`Субагент {count}`,"message.turnProcess.subagents.other":`Субагенты {count}`,"message.turnProcess.thoughtForAWhile":`Размышлял некоторое время`,"message.turnProcess.separator":` · `,"message.stopped":`Остановлено`,"message.branch":`Перейти к новому разговору`,"message.branchUnavailable":`Доступно только в последнем сообщении о завершенном ходу.`,"message.retry.active":`Повторный запрос модели`,"message.retry.cancelled":`Повтор запроса модели отменен.`,"message.retry.started":`Повторный запрос модели`,"message.continuation.requested":`Запрошено продолжение генерации`,"message.retry.scheduled":`Ожидание повторного запроса модели`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Задержка повтора: `,"message.retry.failure":`Причина неисправности: `,"message.retry.inspect":`Осмотреть`,"message.failure.auth":`Ключ API недействителен.`,"message.taskStopped":`Задача остановлена`,"message.failure.accountSignedOut":`Остановлено, поскольку вы вышли из DeepSeek.`,"message.failure.interrupted":`Процесс DSH завершился до завершения этого хода (например, был завершен, произошел сбой или истекло время ожидания при завершении работы), поэтому ход был закрыт при перезапуске DSH. Незавершенные вызовы инструментов имеют неизвестные результаты.`,"message.failure.accountSignInRequired":`Войдите в DeepSeek и убедитесь, что пункт назначения запроса поддерживает аутентификацию учетной записи.`,"message.failure.quota":`Квота запросов исчерпана.`,"message.turnError":`Этот ход завершился ошибкой`,"message.maxTokens":`Достигнут предел выходных токенов`,"message.maxTokens.hint":`Ответ был прерван; более ранний вывод сохраняется в разговоре. Отправьте «продолжить», чтобы модель возобновила работу.`,"message.tokensPerSecond":`{tps} ток/с`,"message.turnUsage.title":`Использование ресурсов за ход`,"message.turnUsage.consumed":`Использование {total}`,"message.turnUsage.model":`Поставщик/модель`,"message.turnUsage.cacheHit":`Попадание в кэш`,"message.turnUsage.input":`Некэшированный ввод`,"message.turnUsage.cacheRead":`Кэшированный ввод`,"message.turnUsage.cacheWrite":`Запись в кэш`,"message.turnUsage.output":`Выход`,"message.turnUsage.reasoning":` (рассуждение {tokens})`,"message.turnUsage.count":`{count} ток`,"duration.secondUnit":`с`,"duration.minuteUnit":`м `,"duration.hourUnit":`ч `,"command.running":`Бег…`,"command.failed":`Команда не выполнена`,"command.done":`Завершено`,"command.title":`Команда`,"row.running":`Бег`,"row.failed":`Не удалось`,"json.truncated":`… усечено, всего символов {total}`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};const pt={"message.stepProcess.thinking":`Analisando a solicitação`,"message.stepProcess.thinkingNext":`{title}, pensando no próximo passo`,"message.stepProcess.read":`Lendo arquivos`,"message.stepProcess.readImage":`Lendo imagens`,"message.stepProcess.write":`Gravando arquivos`,"message.stepProcess.search":`Pesquisando código`,"message.stepProcess.edit":`Editando arquivos`,"message.stepProcess.commands":`Executando comandos`,"message.stepProcess.code":`Executando código`,"message.stepProcess.webSearch":`Pesquisando na web`,"message.stepProcess.webFetch":`Visitando páginas da web`,"message.stepProcess.subagents":`Coordenando subagentes`,"message.stepProcess.plan":`Atualizando o plano`,"message.stepProcess.questions":`Esperando por sua ação`,"message.stepProcess.tools":`Ferramentas de chamada`,"message.stepProcess.prepare.read":`Preparando-se para ler arquivos`,"message.stepProcess.prepare.readImage":`Preparando-se para ler imagens`,"message.stepProcess.prepare.write":`Preparando-se para gravar arquivos`,"message.stepProcess.prepare.search":`Preparando-se para pesquisar o código`,"message.stepProcess.prepare.edit":`Preparando-se para editar arquivos`,"message.stepProcess.prepare.commands":`Preparando para executar comandos`,"message.stepProcess.prepare.code":`Preparando-se para executar o código`,"message.stepProcess.prepare.webSearch":`Preparando-se para pesquisar na web`,"message.stepProcess.prepare.webFetch":`Preparando-se para visitar páginas da web`,"message.stepProcess.prepare.subagents":`Preparando-se para coordenar subagentes`,"message.stepProcess.prepare.plan":`Preparando-se para atualizar o plano`,"message.stepProcess.prepare.questions":`Preparando perguntas`,"message.stepProcess.prepare.tools":`Preparando chamadas de ferramenta`,"message.stepProcess.done.thinking":`Análise concluída`,"message.stepProcess.done.read":`Ler arquivos`,"message.stepProcess.done.readImage":`Ler imagens`,"message.stepProcess.done.write":`Escreveu arquivos`,"message.stepProcess.done.search":`Código pesquisado`,"message.stepProcess.done.edit":`Arquivos editados`,"message.stepProcess.done.commands":`Comandos executados`,"message.stepProcess.done.code":`Código executado`,"message.stepProcess.done.webSearch":`Pesquisei na web`,"message.stepProcess.done.webFetch":`Páginas da web visitadas`,"message.stepProcess.done.subagents":`Subagentes coordenados`,"message.stepProcess.done.plan":`Atualizado o plano`,"message.stepProcess.done.questions":`Perguntas feitas`,"message.stepProcess.done.tools":`Ferramentas chamadas`,"message.stepProcess.done.context":`Contexto injetado`,"message.stepProcess.joinTwo":`{first} e {second}`,"message.stepProcess.comma":`, `,"message.stepProcess.sharedPrefix":``,"message.stepProcess.more":`{title}, etc.`,"message.trigger.request":`Execução solicitada`,"message.trigger.goal":`Objetivo contínuo`,"message.trigger.agent":`Mensagem de tarefa recebida`,"message.trigger.team":`Mensagem da equipe recebida`,"message.trigger.subagent":`Status da subtarefa atualizado`,"message.trigger.subagent.completed":`Execução do subagente concluída`,"message.trigger.subagent.aborted":`Execução do subagente interrompida`,"message.trigger.subagent.error":`Falha na execução do subagente`,"message.trigger.subagent.maxTokens":`O subagente atingiu o limite de tokens`,"message.trigger.subagent.refusal":`O subagente recusou a tarefa`,"message.trigger.subagent.unknown":`A execução do subagente terminou inesperadamente`,"message.trigger.github":`GitHub evento recebido`,"message.trigger.webhook":`Evento externo recebido`,"message.trigger.schedule":`Tarefa de automação`,"message.trigger.job":`Tarefa em segundo plano atualizada`,"message.trigger.plugin":`Status do plug-in atualizado`,"message.trigger.explanation":`Esta notificação desencadeou esta resposta.`,"message.turnProcess.worked":`Concluído`,"message.turnProcess.took":`Concluído em `,"message.turnProcess.failed":`Falha`,"view.chat":`Chat`,"image.open":`Ver imagem completa`,"image.loading":`Carregando imagem…`,"image.failed":`Visualização da imagem indisponível`,"image.dialog":`Visualização da imagem`,"image.close":`Fechar visualização da imagem`,"number.groupSeparator":`,`,"duration.compactSeconds":`{seconds}s`,"duration.compactMinutes":`{minutes}m{seconds}s`,"duration.milliseconds":`{milliseconds}ms`,"stats.counts":`{turns} turnos, {steps} etapas`,"stats.cacheHit":`Acertos no cache: {percent}%`,"stats.dialog.title":`Estatísticas da sessão`,"stats.dialog.usageTitle":`Uso de token`,"stats.dialog.llmTime":`Horário do LLM`,"stats.dialog.toolTime":`Tempo da ferramenta`,"stats.dialog.ttft":`Tempo médio para o primeiro token (TTFT)`,"stats.dialog.speed":`Tokens por segundo (TPS)`,"chat.loadingHistory":`Carregando histórico…`,"chat.loadError":`Falha ao carregar o histórico: {message} ({code})`,"chat.loadOlder":`Carregar mais cedo`,"chat.loadingOlder":`Carregando anteriores`,"chat.processingOlder":`Processando`,"chat.retryOlder":`Tentar novamente`,"chat.historyStart":`Início da conversa`,"chat.toBottom":`De volta ao fundo`,"chat.deepDiving":`Raciocínio profundo`,"chat.deepDivingFor":`Raciocínio profundo há {duration} ···`,"chat.turnNavigation.label":`Navegação entre turnos`,"chat.turnNavigation.jump":`Ir para o turno {turn}`,"chat.turnNavigation.jumpLoad":`Carregar e ir para o turno {turn}`,"chat.turnNavigation.turn":`Turno {turn}`,"settings.performance.title":`Desempenho e uso`,"settings.performance.description":`Escolha quantas informações de desempenho e uso serão exibidas`,"settings.performance.compact":`Compacto`,"settings.performance.detailed":`Detalhado`,"settings.links.title":`Abra links de bate-papo em`,"settings.links.description":`Escolha onde abrir links da web`,"settings.links.sidebar":`Barra lateral no aplicativo`,"settings.links.newTab":`Navegador padrão`,"settings.transcript.title":`Detalhes do trabalho`,"settings.transcript.description":`Escolha quantos detalhes serão exibidos nas chamadas de ferramenta`,"settings.collapse.title":`Quando recolher detalhes do trabalho`,"settings.collapse.description":`Escolha quando recolher automaticamente os detalhes do trabalho`,"settings.collapse.completion":`Na conclusão`,"settings.collapse.nextInput":`Na próxima mensagem`,"settings.foldedReplies.title":`Respostas após o recolhimento`,"settings.foldedReplies.description":`Escolha quais respostas do assistente permanecerão visíveis quando os detalhes do trabalho forem recolhidos`,"settings.foldedReplies.all":`Todas as respostas`,"settings.foldedReplies.final":`Apenas resposta final`,"settings.transcript.compact":`Compacto`,"settings.transcript.standard":`Padrão`,"settings.transcript.detailed":`Detalhado`,"settings.transcript.verbose":`Verboso`,"fileOpen.title":`Não foi possível abrir o arquivo`,"fileOpen.unknown":`Não foi possível abrir este arquivo`,"message.extraBlock":`Bloco de conteúdo extra`,"message.systemPrompt":`Alerta do sistema`,"message.systemPromptUpdate":`Atualização imediata do sistema`,"message.systemSection.added":`Adicionado {name}`,"message.systemSection.updated":`Atualizado {name}`,"message.systemSection.cleared":`Limpo {name}`,"message.systemSection.reordered":`Reordenado {name}`,"message.systemSection.removed":`Removido {name}`,"message.systemSection.unchanged":`Inalterado {name}`,"message.systemPromptReset":`Substitui todas as instruções anteriores`,"message.systemPromptSections":`{count} seções`,"message.toolAdded":`Ferramenta adicionada: {name}`,"message.toolRemoved":`Ferramenta removida: {name}`,"message.toolsAdded":`Adicionado: {names}`,"message.toolsAddedCount":`{count} adicionado`,"message.toolsChanged":`{added} adicionado, {removed} removido`,"message.toolsRemoved":`Removido: {names}`,"message.toolsRemovedCount":`{count} removido`,"message.toolsUpdated":`Ferramentas atualizadas`,"message.contextInjection":`Injeção de contexto`,"message.contextRecall":`Recuperação de sessão`,"message.referenceSummary":`Sessão referenciada · {labels}`,"message.referenceSeparator":`, `,"message.context.instructions.loaded":`carregado`,"message.context.instructions.added":`adicionado`,"message.context.instructions.updated":`atualizado`,"message.context.instructions.removed":`removido`,"message.context.catalog.replaced":`Catálogo de substituição`,"message.context.catalog.more":`… {count} mais`,"message.context.snapshot.supersedes":`Substitui instantâneos anteriores`,"message.context.relay.from":`Da sessão {session}`,"message.context.recall.counts":`{retained} mantido · {omitted} omitido`,"message.context.recall.truncated":`truncado`,"message.compaction":`Contexto compactado`,"message.inheritedHistory":`Histórico herdado acima`,"message.compaction.running":`Contexto compactado…`,"message.compaction.completed":`{items} itens de histórico compactados (~{tokens} tokens)`,"message.compaction.open":`Ver o resumo da compactação na barra lateral`,"message.compaction.notFound":`Resumo indisponível: o serviço está indisponível ou o registro está ausente, vazio ou inválido.`,"message.compaction.readFailed":`Não foi possível ler o resumo`,"message.compaction.landed":`Histórico anterior condensado em um resumo`,"message.compaction.commandTitle":`compacto`,"message.think":`Pense`,"message.unknownSurface":`Evento de superfície desconhecido: {type}`,"message.unknownBlock":`Bloco de conteúdo desconhecido`,"message.turnProcess.toolCalls.one":`{count} chamada de ferramenta`,"message.turnProcess.toolCalls.other":`{count} chamadas de ferramenta`,"message.turnProcess.messages.one":`{count} mensagem`,"message.turnProcess.messages.other":`{count} mensagens`,"message.turnProcess.subagents.one":`{count} subagente`,"message.turnProcess.subagents.other":`{count} subagentes`,"message.turnProcess.thoughtForAWhile":`Pensou por um tempo`,"message.turnProcess.separator":` · `,"message.stopped":`Parado`,"message.branch":`Ramifique para uma nova conversa`,"message.branchUnavailable":`Disponível apenas na última mensagem de um turno concluído`,"message.retry.active":`Tentando novamente a solicitação de modelo`,"message.retry.cancelled":`Nova tentativa de solicitação de modelo cancelada`,"message.retry.started":`Solicitação de modelo repetida`,"message.continuation.requested":`Continuação da geração solicitada`,"message.retry.scheduled":`Aguardando para tentar novamente a solicitação de modelo`,"message.retry.status":`{label} ({retry}/{maximum}) · {seconds}s`,"message.retry.title":`{label} ({retry}/{maximum})`,"message.retry.countdown":`{seconds}s`,"message.retry.delay":`Atraso na nova tentativa: `,"message.retry.failure":`Motivo da falha: `,"message.retry.inspect":`Inspecionar`,"message.failure.auth":`A chave API é inválida`,"message.taskStopped":`Tarefa interrompida`,"message.failure.accountSignedOut":`Interrompido porque você saiu de DeepSeek.`,"message.failure.interrupted":`O processo DSH foi encerrado antes do término deste turno (por exemplo, ele foi eliminado, travou ou expirou durante o desligamento), portanto, o turno foi encerrado quando DSH foi reiniciado. Chamadas de ferramentas inacabadas têm resultados desconhecidos.`,"message.failure.accountSignInRequired":`Faça login em DeepSeek e verifique se o destino da solicitação suporta autenticação de conta.`,"message.failure.quota":`Cota de solicitação esgotada.`,"message.turnError":`Este turno falhou`,"message.maxTokens":`Limite de token de saída atingido`,"message.maxTokens.hint":`A resposta foi cortada; a saída anterior é preservada na conversa. Envie "continuar" para permitir que o modelo seja retomado.`,"message.tokensPerSecond":`{tps} tok/s`,"message.turnUsage.title":`Uso do turno`,"message.turnUsage.consumed":`Uso {total}`,"message.turnUsage.model":`Provedor/modelo`,"message.turnUsage.cacheHit":`Acertos no cache`,"message.turnUsage.input":`Entrada sem cache`,"message.turnUsage.cacheRead":`Entrada em cache`,"message.turnUsage.cacheWrite":`Gravação em cache`,"message.turnUsage.output":`Saída`,"message.turnUsage.reasoning":` ({tokens} raciocínio)`,"message.turnUsage.count":`{count} tok`,"duration.secondUnit":`s`,"duration.minuteUnit":`m `,"duration.hourUnit":`h `,"command.running":`Correndo…`,"command.failed":`Falha no comando`,"command.done":`Concluído`,"command.title":`Comando`,"row.running":`Correndo`,"row.failed":`Falha`,"json.truncated":`… truncado, {total} caracteres no total`,"clock.md":`{m}/{d}`,"clock.ymd":`{y}-{m}-{d}`};function compactionRows(ctx){const compactionPreview=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(false);const t=ctx.locale.bind(NS);let lifetime;ctx.inject([`documentPreviews`],scope=>scope.effect(()=>{const controller=new AbortController;lifetime=controller;compactionPreview.set(true);return()=>{controller.abort();lifetime=void 0;compactionPreview.set(false)}}));return sessionId=>({hooks:{compactionPreview},async openCompaction(summarySeq,signal){if(lifetime===void 0)return null;const child=ctx.sessions.subagentAddress(sessionId);const address=child===void 0?{kind:`session`,sessionId}:{kind:`subagent`,...child};const active=AbortSignal.any([signal,lifetime.signal]);const cancelled=()=>active.aborted;if(cancelled())return null;let result;try{result=await ctx.remote.session.events({address,throughSeq:summarySeq,maxMessages:1},active)}catch(_error){return cancelled()?null:t(`message.compaction.readFailed`)}if(cancelled())return null;if(!result.ok)return t(`message.compaction.readFailed`);const event=result.value.records.find(entry=>entry.event.seq===summarySeq)?.event;const text=event&&summaryText(event);if(text===void 0)return t(`message.compaction.notFound`);const identity=address.kind===`session`?[address.sessionId]:[address.parentSessionId,address.childSessionId,address.mode];ctx.sidebarRight.openContent(`compaction-summary`,{summaryMarkdown:text},{key:JSON.stringify([...identity,summarySeq])});return null}})}function summaryText(event){if(event.type!==`compaction/summary`)return void 0;const data=event.data;if(typeof data!==`object`||data===null||!(`summary`in data)||!Array.isArray(data.summary))return void 0;const text=[];const blocks=data.summary;for(const block of blocks){if(typeof block!==`object`||block===null||!(`type`in block))return void 0;if(block.type!==`text`)continue;if(!(`text`in block)||typeof block.text!==`string`)return void 0;text.push(block.text)}const markdown=text.join(``);return markdown.trim()===``?void 0:markdown}function reasoningText(text){if(text[0]!==`<`)return text;const opening=`<signature>`;if(opening.startsWith(text))return``;if(!text.startsWith(opening))return text;const end=text.indexOf(`</signature>`,11);if(end===-1)return``;let start=end+12;while(start<text.length)if(text[start]===`
15
15
  `)start++;else if(text[start]===`\r`&&text[start+1]===`
16
16
  `)start+=2;else break;return text.slice(start)}var ReasoningRow_module_css_default={"leading":`lcKema_leading`,"root":`lcKema_root`,"row":`lcKema_row`,"separator":`lcKema_separator`,"summary":`lcKema_summary`,"summaryText":`lcKema_summaryText`,"thinkBody":`lcKema_thinkBody`,"title":`lcKema_title`};const THINK_ICON=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconThinkOutlineRegular,{size:14});function firstLine(text){const newline=text.indexOf(`
17
17
  `);return newline===-1?text:text.slice(0,newline)}function latestCompletedParagraphFirstLine(text){let summary=``;let paragraphStart=0;const separator=/\r?\n(?:[\t ]*\r?\n)+/g;while(true){const nextParagraph=separator.exec(text);const paragraphEnd=nextParagraph===null?text.length:nextParagraph.index+nextParagraph[0].indexOf(`
18
18
  `);const newline=text.indexOf(`
19
- `,paragraphStart);if(newline!==-1&&newline<=paragraphEnd){const candidate=text.slice(paragraphStart,newline).trim();if(candidate!==``)summary=candidate}if(nextParagraph===null)return summary;paragraphStart=nextParagraph.index+nextParagraph[0].length}}const ReasoningRow=(0,react.memo)(function ReasoningRow({text:rawText,running,textInteractionSource=false,usePresentation,useDisclosure,renderSlot,t}){const{expanded,toggle}=useDisclosure();const{text,hidden}=(0,react.useMemo)(()=>{const text=reasoningText(rawText);return{text,hidden:text!==rawText&&text.trim()===``}},[rawText]);const summaryText=running?latestCompletedParagraphFirstLine(text):firstLine(text);const summary=(0,react.useMemo)(()=>summaryText.replaceAll(`**`,``),[summaryText]);const preview=usePresentation(policy=>!expanded&&summary!==``&&(running||policy.settledReasoningPreview));const collapsedContent=(0,react.useMemo)(()=>(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.separator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.summary,"data-streaming":running||void 0,children:(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.summaryText,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{children:summary})})})]}),[running,summary]);const content=(0,react.useMemo)(()=>expanded?(0,react_jsx_runtime.jsx)(`div`,{className:ReasoningRow_module_css_default.thinkBody,"data-text-interaction-source":textInteractionSource&&!running?``:void 0,children:renderSlot(`conversation.chat.reasoning.body`,{rawText,text,running})}):void 0,[expanded,renderSlot,running,rawText,text,textInteractionSource]);if(hidden)return null;return(0,react_jsx_runtime.jsxs)(`div`,{className:ReasoningRow_module_css_default.root,"data-variant":`think`,"data-state":running?`running`:`ok`,"data-expanded":expanded||void 0,"data-preview":preview||void 0,children:[running&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.running`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{rowClassName:ReasoningRow_module_css_default.row,leadingClassName:ReasoningRow_module_css_default.leading,titleClassName:ReasoningRow_module_css_default.title,icon:THINK_ICON,title:t(`message.think`),running,open:expanded,expandable:true,expandOnRowClick:true,onToggle:toggle,collapsedContent,children:content})]})});var AssistantMarkdown_module_css_default={"actions":`hWmORq_actions`,"body":`hWmORq_body`,"reasoning":`hWmORq_reasoning`,"root":`hWmORq_root`,"stopped":`hWmORq_stopped`};function localPathMediaUrl(base,value){let path;try{path=decodeURIComponent(value.split(/[?#]/u)[0]??``)}catch{return}return fileMediaUrl(base,path)}const AssistantMarkdown=(0,react.memo)(function AssistantMarkdown({blocks,streaming,textInteractionSource=false,interrupted,loadImage,groupPart,useDisclosure,reasoningHidden=false,usePresentation,revealProcess,mentions,renderSlot,useGroupAction,t}){const labels=(0,react.useMemo)(()=>markdownLabels(t),[t]);const pathImages=(0,react.useMemo)(()=>{return{resolve:value=>localPathMediaUrl(document.baseURI,value)}},[]);const last=blocks.length-1;if(!(streaming||interrupted===true||blocks.some(block=>block.kind!==`tool-call`)))return null;const rendered=[];for(let i=0;i<blocks.length;i++){const block=blocks[i];if(block===void 0)continue;if(groupPart===`reasoning`&&block.kind!==`reasoning`)continue;if(groupPart===`response`&&block.kind===`reasoning`)continue;switch(block.kind){case`text`:rendered.push((0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownText,{text:block.text,streaming,labels,fileMentions:mentions,pathImages,textInteractionSource},i));break;case`reasoning`:if(block.text.trim()===``)break;rendered.push((0,react_jsx_runtime.jsx)(ProcessReasoning,{hidden:reasoningHidden,reveal:revealProcess,useGroupAction,children:(0,react_jsx_runtime.jsx)(ReasoningRow,{text:block.text,running:streaming&&i===last,usePresentation,useDisclosure,renderSlot,textInteractionSource,t})},i));break;case`image`:{const start=i;const group=[block];while(i+1<blocks.length){const next=blocks[i+1];if(next===void 0||next.kind!==`image`)break;group.push(next);i+=1}rendered.push((0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlot(`conversation.chat.message.images`,{images:group.map(({attachment})=>({attachment})),loadImage,align:`start`})},start));break}case`tool-call`:break;default:rendered.push((0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:block.block,truncatedLabel:total=>t(`json.truncated`,{total})},i))}}return(0,react_jsx_runtime.jsx)(`div`,{className:AssistantMarkdown_module_css_default.root,"data-streaming":streaming||void 0,children:(0,react_jsx_runtime.jsxs)(`div`,{className:AssistantMarkdown_module_css_default.body,children:[rendered,interrupted&&(groupPart===void 0||groupPart===`response`||!blocks.some(block=>block.kind!==`reasoning`&&block.kind!==`tool-call`))&&(0,react_jsx_runtime.jsx)(`span`,{className:AssistantMarkdown_module_css_default.stopped,children:t(`message.stopped`)})]})})});function ProcessReasoning({hidden,reveal,useGroupAction,children}){return(0,react_jsx_runtime.jsx)(`div`,{ref:useGroupAction(hidden,reveal??NOOP),className:AssistantMarkdown_module_css_default.reasoning,"data-turn-process-inline":hidden||void 0,children})}const NOOP=()=>{};const AssistantNodeView=(0,react.memo)(function AssistantNodeView({node,groupPart,useDisclosure,useGroupAction,useTurnData,turnProcess,openFile,loadImage,fileMentions,usePresentation,renderSlot,t,sessionId,useContextMenu,resolveFilePath}){const{getTriggerProps}=useContextMenu();const getFileTriggerProps=(0,react.useCallback)(path=>getTriggerProps(()=>({kind:`file`,value:{sessionId,path:resolveFilePath(path)}})),[getTriggerProps,sessionId,resolveFilePath]);const data=node.data;const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;const tail=useTurnData(`turn-tail`);const owner=(0,react.useMemo)(()=>{if(turn?.status!==`closed`||data.finalNode===void 0)return void 0;if(tail?.closing?.finalNode.seq!==data.finalNode.seq)return void 0;return{turn,seq:data.finalNode.seq,openFile}},[data.finalNode,openFile,tail,turn]);const mentions=(0,react.useMemo)(()=>owner===void 0?void 0:fileMentions(owner,getFileTriggerProps),[fileMentions,owner,getFileTriggerProps]);const keepReplies=usePresentation(policy=>policy.foldedReplies===`all`);const reasoningHidden=turnProcess!==void 0&&turnProcess.foldable&&(keepReplies?groupPart!==`reasoning`:turnProcess.spec.answerStep===data.step&&turnProcess.spec.inlineReasoning)&&!turnProcess.open;const revealProcess=(0,react.useCallback)(()=>{turnProcess?.setOpen(true)},[turnProcess]);return(0,react_jsx_runtime.jsx)(AssistantMarkdown,{blocks:data.blocks,groupPart,useDisclosure,streaming:data.status===`running`,textInteractionSource:data.status===`settled`&&data.finalNode?.messageId!==void 0,interrupted:data.status===`interrupted`,loadImage,reasoningHidden,useGroupAction,usePresentation,renderSlot,revealProcess,mentions,t})});const GenericCommandCard=(0,react.memo)(function GenericCommandCard({node,t,runningSummary}){const text=node.outcome?.text;const summary=node.outcome===null?runningSummary??t(`command.running`):text??(node.outcome.kind===`error`?t(`command.failed`):t(`command.done`));return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title:node.name??t(`command.title`),state:node.outcome===null?`running`:node.outcome.kind===`error`?`error`:`ok`,summary,body:text!==void 0&&text.includes(`
20
- `)?text:null,t})});function CompactionCommandCard({node,compaction,openCompaction,t}){if(compaction!==void 0)return(0,react_jsx_runtime.jsx)(CompactionItem,{node:compaction,openCompaction,title:t(`message.compaction.commandTitle`),fallbackSummary:node.outcome?.text??null,t});if(node.outcome!==null)return(0,react_jsx_runtime.jsx)(GenericCommandCard,{node,t});return(0,react_jsx_runtime.jsx)(GenericCommandCard,{node,t,runningSummary:t(`message.compaction.running`)})}const CommandNodeView=(0,react.memo)(function CommandNodeView({node,renderSlot,t}){const command=node.data;const owner=(0,react.useMemo)(()=>({node:command}),[command]);return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.callRow,children:renderSlot(`conversation.chat.commandview`,owner,{entryKey:command.name??``,fallback:(0,react_jsx_runtime.jsx)(GenericCommandCard,{...owner,t})})})});const ManualCompactionNodeView=(0,react.memo)(function ManualCompactionNodeView({node,openCompaction,useCompactionPreview,t}){const available=useCompactionPreview(value=>value);const data=node.data;return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.callRow,children:(0,react_jsx_runtime.jsx)(CompactionCommandCard,{node:data.command,...data.compaction===null?{}:{compaction:data.compaction},openCompaction:available?openCompaction:void 0,t})})});const ReasoningContent=(0,react.memo)(function ReasoningContent({text,running,labels,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownText,{text,streaming:running,labels:(0,react.useMemo)(()=>labels??markdownLabels(t),[labels,t]),variant:`compact`})});function DefaultReasoningBody({text,running,renderFactorySlot}){return renderFactorySlot(`conversation.chat.reasoning.content`,{text,running})}function SystemPromptRow({text,update=false,message,t}){const[open,setOpen]=(0,react.useState)(false);const names=message?.changes.map(change=>change.name)??[];const summary=names.length>2?t(`message.systemPromptSections`,{count:names.length}):names.join(`, `);return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{className:ContextInjectionRow_module_css_default.root,icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),chevronClassName:ContextInjectionRow_module_css_default.chevron,title:t(update?`message.systemPromptUpdate`:`message.systemPrompt`),collapsedContent:summary===``?void 0:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,"data-system-sources":true,children:summary})]}),keepContentWhenOpen:true,open,expandable:true,expandOnRowClick:true,onToggle:()=>{setOpen(value=>!value)},children:(0,react_jsx_runtime.jsx)(`div`,{className:ContextInjectionRow_module_css_default.body,"data-system-prompt-body":true,children:message===void 0?(0,react_jsx_runtime.jsx)(OpaqueBody,{content:[{type:`text`,text}],source:null,t}):(0,react_jsx_runtime.jsx)(SystemSectionsBody,{message,t})})})}const SystemPromptNodeView=(0,react.memo)(function SystemPromptNodeView({node,t}){return(0,react_jsx_runtime.jsx)(SystemPromptRow,{text:node.data.text,update:node.data.update===true,message:node.data.message,t})});var TurnProcessNodeView_module_css_default={"chevron":`l_V-RG_chevron`,"durationNumber":`l_V-RG_durationNumber`,"label":`l_V-RG_label`,"root":`l_V-RG_root`};const TurnProcessNodeView=(0,react.memo)(function TurnProcessNodeView({node,turnProcess,t}){if(turnProcess===void 0)throw new Error(`turn-process node requires Turn process owner state`);const open=!turnProcess.foldable||turnProcess.open;const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;if(turn?.status!==`closed`)return null;const canCollapse=turnProcess.foldable&&turnProcess.hasContent&&!turnProcessAlwaysOpen(node);const reason=turn.end?.data.reason.kind;const stopped=reason===`aborted`||reason===`interrupted`;const elapsedMs=turn.start===void 0||turn.end===void 0?void 0:Math.max(1e3,turn.end.time-turn.start.time);const duration=elapsedMs===void 0||stopped||reason===`error`?void 0:formatRunDuration(elapsedMs,t);const label=stopped?t(`message.stopped`):reason===`error`?t(`message.turnProcess.failed`):duration===void 0?t(`message.turnProcess.worked`):t(`message.turnProcess.took`);const announcement=stopped?t(`message.stopped`):reason===`error`?t(`message.turnProcess.failed`):t(`message.turnProcess.worked`);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:announcement}),(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:TurnProcessNodeView_module_css_default.root,"data-open":open||void 0,"data-turn-process":node.data.turn,"data-turn-process-messages":node.data.messageCount,"data-turn-process-tool-calls":node.data.toolCallCount,"data-turn-process-subagents":node.data.subagentCount,disabled:!canCollapse,"aria-expanded":turnProcess.hasContent?open:void 0,onClick:event=>{event.currentTarget.focus();turnProcess.setOpen(!open)},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:TurnProcessNodeView_module_css_default.label,children:[label,duration?.map((part,index)=>(0,react_jsx_runtime.jsx)(`span`,{className:part.numeric?TurnProcessNodeView_module_css_default.durationNumber:void 0,children:part.text},index))]}),canCollapse&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{className:TurnProcessNodeView_module_css_default.chevron})]})]})});function formatTokens(value,t){const scaled=candidate=>candidate>=100?String(Math.round(candidate)):String(Math.round(candidate*10)/10);if(value<1e3)return String(value);if(value<1e6)return t(`number.thousand`,{value:scaled(value/1e3)});return t(`number.million`,{value:scaled(value/1e6)})}function formatExactTokens(value,t){const digits=String(value);const groups=[];for(let end=digits.length;end>0;end-=3)groups.unshift(digits.slice(Math.max(0,end-3),end));return groups.join(t(`number.groupSeparator`))}function roundedPercentUnits(cacheReadTokens,denominator,decimalPlaces){const scale=(decimalPlaces===0?1:10)*100;const doubledScale=scale*2;const denominatorQuotient=Math.floor(denominator/doubledScale);const denominatorRemainder=denominator%doubledScale;let lower=0;let upper=scale;while(lower<upper){const candidate=Math.floor((lower+upper+1)/2);const factor=candidate*2-1;if(cacheReadTokens>=factor*denominatorQuotient+Math.ceil(factor*denominatorRemainder/doubledScale))lower=candidate;else upper=candidate-1}return lower}function displayPercentUnits(units,decimalPlaces){if(decimalPlaces===0)return String(units);const whole=Math.floor(units/10);const tenths=units%10;return tenths===0?String(whole):`${whole}.${tenths}`}function formatCacheHitPercent(cacheReadTokens,promptTokens,decimalPlaces=0){if(promptTokens===0)return null;const missedInputTokens=promptTokens-cacheReadTokens;if(missedInputTokens===0)return`100`;const roundedUnits=roundedPercentUnits(cacheReadTokens,promptTokens,decimalPlaces);if(roundedUnits<(decimalPlaces===0?100:1e3))return displayPercentUnits(roundedUnits,decimalPlaces);let distinguishingPlaces=1;let scaledDoubleGap=missedInputTokens*200;const denominatorTens=Math.floor(promptTokens/10);while(scaledDoubleGap<=denominatorTens){scaledDoubleGap*=10;distinguishingPlaces+=1}const denominatorOnes=promptTokens%10;let roundedLoss=5;for(let loss=1;loss<5;loss+=1){const factor=loss*2+1;const threshold=factor*denominatorTens+Math.floor(factor*denominatorOnes/10);if(scaledDoubleGap<=threshold){roundedLoss=loss;break}}return`99.${`9`.repeat(distinguishingPlaces-1)}${10-roundedLoss}`}function useStatDialog(){const[open,setOpen]=(0,react.useState)(false);const rootRef=(0,react.useRef)(null);const panelRef=(0,react.useRef)(null);const anchorName=`--dsh-stat-${(0,react.useId)().replace(/[^\w-]/g,``)}`;(0,_deepseek_ai_dsh_client_ui_primitives_client.useDismissOnOutsidePointer)(rootRef,open,setOpen,panelRef);(0,react.useEffect)(()=>{if(!open)return;const onKeyDown=e=>{if(e.key===`Escape`)setOpen(false)};const onClick=e=>{if(e.target instanceof Node&&rootRef.current?.contains(e.target)!==true&&panelRef.current?.contains(e.target)!==true)setOpen(false)};document.addEventListener(`keydown`,onKeyDown);document.addEventListener(`click`,onClick,true);return()=>{document.removeEventListener(`keydown`,onKeyDown);document.removeEventListener(`click`,onClick,true)}},[open,setOpen]);return{open,setOpen,rootRef,panelRef,anchorName}}var TurnUsagePanel_module_css_default={"label":`Q51KRG_label`,"root":`Q51KRG_root`,"trigger":`Q51KRG_trigger`};var stat_dialog_module_css_default={"details":`bRhRbq_details`,"panel":`bRhRbq_panel`,"reasoning":`bRhRbq_reasoning`,"route":`bRhRbq_route`,"title":`bRhRbq_title`,"titleLabel":`bRhRbq_titleLabel`,"titleRule":`bRhRbq_titleRule`,"titleValue":`bRhRbq_titleValue`};function formatCompactCount(value,t){return t(`message.turnUsage.count`,{count:formatTokens(value,t)})}function formatExactCount(value,t){return t(`message.turnUsage.count`,{count:formatExactTokens(value,t)})}function TurnUsagePanel({usage,t}){const{open,setOpen,rootRef,panelRef,anchorName}=useStatDialog();const cacheHit=usage.cacheReadTokens===void 0?null:formatCacheHitPercent(usage.cacheReadTokens,usage.totalTokens-usage.outputTokens,1);const total=formatCompactCount(usage.totalTokens,t);const routes=usage.routes?.map(route=>`${route.provider}/${route.model}`).join(`, `)??``;return(0,react_jsx_runtime.jsxs)(`span`,{ref:rootRef,style:{anchorName},className:TurnUsagePanel_module_css_default.root,children:[(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:TurnUsagePanel_module_css_default.trigger,"aria-haspopup":`dialog`,"aria-expanded":open,onClick:()=>{setOpen(!open)},children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{}),(0,react_jsx_runtime.jsx)(`span`,{className:TurnUsagePanel_module_css_default.label,children:t(`message.turnUsage.consumed`,{total})})]}),open&&(0,react_dom.createPortal)((0,react_jsx_runtime.jsxs)(`div`,{ref:panelRef,className:stat_dialog_module_css_default.panel,role:`dialog`,"aria-label":t(`message.turnUsage.title`),style:{positionAnchor:anchorName},children:[(0,react_jsx_runtime.jsxs)(`div`,{className:stat_dialog_module_css_default.title,children:[(0,react_jsx_runtime.jsxs)(`span`,{className:stat_dialog_module_css_default.titleLabel,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{}),t(`message.turnUsage.title`)]}),(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.titleValue,children:formatExactCount(usage.totalTokens,t)})]}),(0,react_jsx_runtime.jsx)(`div`,{className:stat_dialog_module_css_default.titleRule,"aria-hidden":true}),(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-turn-usage-details":true,children:[routes!==``&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.model`)}),(0,react_jsx_runtime.jsx)(`dd`,{className:stat_dialog_module_css_default.route,children:routes})]}),cacheHit!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheHit`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:`${cacheHit}%`})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.input`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.uncachedInputTokens,t)}),usage.cacheReadTokens!==void 0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheRead`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.cacheReadTokens,t)})]}),usage.cacheWriteTokens!==void 0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheWrite`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.cacheWriteTokens,t)})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.output`)}),(0,react_jsx_runtime.jsxs)(`dd`,{children:[formatExactCount(usage.outputTokens,t),usage.reasoningTokens!==void 0&&(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.reasoning,children:t(`message.turnUsage.reasoning`,{tokens:formatExactCount(usage.reasoningTokens,t)})})]})]})]}),document.body)]})}function assistantText(blocks){return blocks.flatMap(block=>block.kind===`text`?[block.text]:[]).join(``)}var TurnTailNodeView_module_css_default={"actions":`TS9iAW_actions`,"root":`TS9iAW_root`};function lastContent(snapshot,turn,skipWarning){const keys=snapshot.locations.getTurn(turn);for(let index=keys.length-1;index>=0;index--){const node=snapshot.nodes.get(keys[index]);if(node===void 0||node.kind===`turn-tail`||node.kind===`turn-process`||skipWarning&&node.kind===`turn-max-tokens`)continue;return node}}const TurnTailNodeView=(0,react.memo)(function TurnTailNodeView({node,openFile,forkAt,renderSlot,t,useAccess,useChat,usePerformanceUsage}){const detailed=usePerformanceUsage(mode=>mode)===`detailed`;const forkAllowed=useAccess(`session/fork`);const data=node.data;const hasLaterChatNode=useChat(snapshot=>(lastContent(snapshot,data.turn,true)?.anchorSeq??-1)>(data.closing?.finalNode.seq??data.seq));const endsWithResponse=useChat(snapshot=>{if(snapshot.timeline.turnOrder.at(-1)!==data.turn)return false;const last=lastContent(snapshot,data.turn,false);const block=last?.kind===`assistant-step`?last.data.blocks.findLast(candidate=>candidate.kind!==`text`&&candidate.kind!==`reasoning`||candidate.text.trim()!==``):void 0;return block!==void 0&&hasAssistantReplyContent([block])});const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;if(turn===void 0)return null;const closing=data.closing;const tail=renderSlot(`conversation.chat.turnTail`,{turn,seq:closing?.finalNode.seq??data.seq,openFile});if(closing===null)return tail===null?null:(0,react_jsx_runtime.jsx)(`div`,{className:TurnTailNodeView_module_css_default.root,"data-turn-tail":data.turn,children:tail});const messageId=closing.finalNode.messageId;const assistantActions=messageId===void 0?null:renderSlot(`conversation.chat.assistant-actions`,{messageId});return(0,react_jsx_runtime.jsxs)(`div`,{className:TurnTailNodeView_module_css_default.root,"data-turn-tail":data.turn,"data-actions-reveal":endsWithResponse?`always`:`hover`,children:[tail,(0,react_jsx_runtime.jsx)(MessageIconActions,{text:assistantText(closing.blocks),time:closing.time,clock:`end`,onBranch:forkAllowed?()=>{forkAt(data.seq)}:void 0,branchUnavailable:data.branchUnavailable||hasLaterChatNode,className:TurnTailNodeView_module_css_default.actions,extraActions:assistantActions,usageAction:detailed&&data.tokenUsage!==void 0?(0,react_jsx_runtime.jsx)(TurnUsagePanel,{usage:data.tokenUsage,t}):null,t})]})});function record(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{}}function field(source,key){return typeof source[key]===`string`?source[key]:``}function subagentTitle(reason){if(typeof reason!==`string`||reason===``)return`message.trigger.subagent`;switch(reason){case`completed`:return`message.trigger.subagent.completed`;case`aborted`:return`message.trigger.subagent.aborted`;case`error`:return`message.trigger.subagent.error`;case`max-tokens`:return`message.trigger.subagent.maxTokens`;case`refusal`:return`message.trigger.subagent.refusal`;default:return`message.trigger.subagent.unknown`}}function turnTriggerDetails(node){const source=record(node.source);const kind=field(source,`kind`);let title=`message.trigger.request`;let icon=`request`;switch(kind){case`retry`:if(node.content.length===0)return{title:`message.continuation.requested`,icon:`continue`,compact:true};break;case`goal`:title=`message.trigger.goal`;icon=`goal`;break;case`agent-message`:title=`message.trigger.agent`;icon=`agent`;break;case`team-message`:title=`message.trigger.team`;icon=`team`;break;case`subagent-settled`:title=subagentTitle(source.stopReason);icon=`subagent`;break;case`webhook`:{const github=field(source,`provider`)===`github`;title=github?`message.trigger.github`:`message.trigger.webhook`;icon=github?`github`:`webhook`;break}case`schedule`:title=`message.trigger.schedule`;icon=`schedule`;break;case`tool-jobs`:title=`message.trigger.job`;icon=`job`;break;case`cordis-host-runner`:title=`message.trigger.plugin`;icon=`plugin`;break;default:break}return{title,icon}}var TurnTriggerNodeView_module_css_default={"body":`oz9t_a_body`,"chevron":`oz9t_a_chevron`,"content":`oz9t_a_content`,"continuation":`oz9t_a_continuation`,"explanation":`oz9t_a_explanation`,"header":`oz9t_a_header`,"icon":`oz9t_a_icon`,"openChevron":`oz9t_a_openChevron`,"root":`oz9t_a_root`,"time":`oz9t_a_time`,"title":`oz9t_a_title`};const TRIGGER_ICONS={continue:_deepseek_ai_dsh_client_ui_primitives_client.IconPlayOutlineRegular,request:_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,goal:_deepseek_ai_dsh_client_ui_primitives_client.IconGoalOutlineRegular,agent:_deepseek_ai_dsh_client_ui_primitives_client.IconPaperPlaneOutlineRegular,team:_deepseek_ai_dsh_client_ui_primitives_client.IconAgentPresetOutlineRegular,subagent:_deepseek_ai_dsh_client_ui_primitives_client.IconUsersOutlineRegular,github:_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,webhook:_deepseek_ai_dsh_client_ui_primitives_client.IconGlobeOutlineRegular,schedule:_deepseek_ai_dsh_client_ui_primitives_client.IconClockOutlineRegular,job:_deepseek_ai_dsh_client_ui_primitives_client.IconQueueOutlineRegular,plugin:_deepseek_ai_dsh_client_ui_primitives_client.IconCordisPluginOutlineRegular};function TurnTriggerNodeView({node,t}){const[open,setOpen]=(0,react.useState)(false);const bodyId=(0,react.useId)();const details=turnTriggerDetails(node.data);const TriggerIcon=TRIGGER_ICONS[details.icon];if(details.compact)return(0,react_jsx_runtime.jsxs)(`div`,{className:TurnTriggerNodeView_module_css_default.continuation,"data-generation-continuation":true,children:[(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.icon,"aria-hidden":true,children:(0,react_jsx_runtime.jsx)(TriggerIcon,{size:14})}),(0,react_jsx_runtime.jsx)(`span`,{children:t(details.title)})]});const date=new Date(node.data.time);const time=formatMessageClock(node.data.time,t);return(0,react_jsx_runtime.jsxs)(`section`,{className:TurnTriggerNodeView_module_css_default.root,"data-turn-trigger":true,children:[(0,react_jsx_runtime.jsxs)(`button`,{className:TurnTriggerNodeView_module_css_default.header,type:`button`,"aria-expanded":open,"aria-controls":bodyId,onClick:()=>{setOpen(!open)},children:[(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.icon,"aria-hidden":true,children:(0,react_jsx_runtime.jsx)(TriggerIcon,{size:14})}),(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.title,children:t(details.title)}),(0,react_jsx_runtime.jsx)(`time`,{className:TurnTriggerNodeView_module_css_default.time,dateTime:date.toISOString(),children:time}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{size:12,className:open?TurnTriggerNodeView_module_css_default.openChevron:TurnTriggerNodeView_module_css_default.chevron})]}),open&&(0,react_jsx_runtime.jsxs)(`div`,{id:bodyId,className:TurnTriggerNodeView_module_css_default.body,children:[(0,react_jsx_runtime.jsx)(`p`,{className:TurnTriggerNodeView_module_css_default.explanation,children:t(`message.trigger.explanation`)}),(0,react_jsx_runtime.jsx)(`div`,{className:TurnTriggerNodeView_module_css_default.content,children:(0,react_jsx_runtime.jsx)(NoticeBody,{content:node.data.content,source:node.data.source,t})})]})]})}function registerChatNodeRenderers(ctx,performanceUsage,presentation){const injectCompaction=compactionRows(ctx);ctx.effect(()=>ctx.slots.registerFactory({name:`conversation.chat.reasoning.content`,scope:`root`,locale:NS},ReasoningContent));ctx.slots.inject(`conversation.chat.reasoning.body`,()=>ctx.slots.register({name:`conversation.chat.reasoning.body`,priority:100},DefaultReasoningBody));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`user`,locale:NS,children:{"conversation.chat.user.before":{kind:`chain`,scope:`session`}}},UserMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`steering`,locale:NS,inject:()=>({renderSlotChain:()=>null})},UserMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`context`,locale:NS},ContextMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-trigger`,locale:NS},TurnTriggerNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`system-prompt`,locale:NS},SystemPromptNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`assistant-step`,locale:NS,children:{"conversation.chat.reasoning.body":{kind:`single`,scope:`session`},"conversation.chat.message.images":{kind:`single`,scope:`session`}},inject:sessionId=>({hooks:{presentation},resolveFilePath:sessionFilePath(ctx,sessionId),fileMentions:(owner,getFileTriggerProps)=>ctx.get(`chatFileMentions`)?.forClosing(owner,sessionId,getFileTriggerProps)})},AssistantNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`command`,locale:NS,children:{"conversation.chat.commandview":{kind:`keyed`,scope:`session`}}},CommandNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`manual-compaction`,locale:NS,inject:injectCompaction},ManualCompactionNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`compaction`,locale:NS,inject:injectCompaction},CompactionNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`inherited-history`,locale:NS},InheritedHistoryNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`model-retry`,locale:NS},RetryNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-error`,locale:NS},TurnErrorNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-max-tokens`,locale:NS},TurnMaxTokensNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-process`,locale:NS},TurnProcessNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-tail`,locale:NS,inject:()=>({hooks:{performanceUsage}}),children:{"conversation.chat.turnTail":{kind:`list`,scope:`session`},"conversation.chat.assistant-actions":{kind:`list`,scope:`session`}}},TurnTailNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`unknown`,locale:NS},UnknownNodeView))}const EMPTY_LABELS=[];function UserContent({content,loadImage,facts,interactive=false,ellipsis=false,renderSlot,renderFactorySlot,t}){const{text,attachments,extraBlocks,referenceLabels=EMPTY_LABELS}=content;const compactImages=attachments.length>1;const truncated=total=>t(`json.truncated`,{total});const showBubble=text!==``||extraBlocks.length>0;return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.userStack,children:[attachments.length>0&&(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.attachmentRow,"data-message-attachments":true,children:attachments.map((attachment,index)=>attachment.type===`image`?(0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlot(`conversation.chat.user.images`,{images:[attachment.image],loadImage,align:`end`,compact:compactImages})},`image:${index}`):(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.fileCard,title:attachment.file.name,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FileTypeIcon,{path:attachment.file.name,className:MessageItem_module_css_default.fileIcon}),(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.fileContent,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.fileName,children:attachment.file.name}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.fileMeta,children:[(0,_deepseek_ai_dsh_client_ui_primitives_client.fileExtension)(attachment.file.name).toUpperCase().slice(0,8),(0,_deepseek_ai_dsh_client_ui_primitives_client.fileSizeText)(attachment.file.bytes)].filter(Boolean).join(` `)})]})]},`file:${index}`))}),showBubble&&(0,react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives_client.UserMessageBubble,{"data-message-bubble":``,"data-text-interaction-source":``,children:[renderFactorySlot(`conversation.user.text`,{text,facts,interactive,ellipsis}),extraBlocks.map((block,index)=>(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.extraBlock`),payload:block,truncatedLabel:truncated},index))]}),referenceLabels.length>0&&(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.referenceSummary,children:t(`message.referenceSummary`,{labels:referenceLabels.join(t(`message.referenceSeparator`))})})]})}function usageOutputTokens(usage){if(typeof usage!==`object`||usage===null)return null;const value=usage.outputTokens;return typeof value===`number`&&Number.isFinite(value)&&value>=0?value:null}function assistantStepReading(node){const timing=node.timing;return{ttftMs:timing!==void 0&&timing.stepStartTime!==null&&timing.firstTokenTime!==null?Math.max(0,timing.firstTokenTime-timing.stepStartTime):null,decodeMs:timing!==void 0&&timing.firstTokenTime!==null?Math.max(0,timing.completedTime-timing.firstTokenTime):null,outputTokens:usageOutputTokens(node.usage)}}var StatsPills_module_css_default={"anchor":`bOPqQW_anchor`,"label":`bOPqQW_label`,"pill":`bOPqQW_pill`,"sep":`bOPqQW_sep`};function deriveStats(nodes){const turns=new Set;let steps=0;let llmMs=0;let toolMs=0;let ttftMs=0;let ttftSteps=0;let decodeMs=0;let decodeTokens=0;for(const node of nodes){if(node.kind===`tool-result`){if(node.callTime!==null)toolMs+=Math.max(0,node.time-node.callTime);continue}if(node.kind!==`assistant`)continue;turns.add(node.turn);steps+=1;if(node.timing!==void 0&&node.timing.stepStartTime!==null)llmMs+=Math.max(0,node.timing.completedTime-node.timing.stepStartTime);const reading=assistantStepReading(node);if(reading.ttftMs!==null){ttftMs+=reading.ttftMs;ttftSteps+=1}if(reading.decodeMs!==null&&reading.outputTokens!==null){decodeMs+=reading.decodeMs;decodeTokens+=reading.outputTokens}}return{turns:turns.size,steps,llmMs,toolMs,ttftMs,ttftSteps,decodeMs,decodeTokens}}function formatDuration(ms,t){const s=ms/1e3;if(s<60)return t(`duration.compactSeconds`,{seconds:Math.round(s*10)/10});const whole=Math.round(s);return t(`duration.compactMinutes`,{minutes:Math.floor(whole/60),seconds:whole%60})}function cacheHitPercent(usage){const denominator=billedInputTokens(usage);return formatCacheHitPercent(usage.cacheReadTokens,denominator)}function billedInputTokens(usage){return usage.uncachedInputTokens+usage.cacheReadTokens+usage.cacheWriteTokens}function exactCount(value,t){return t(`message.turnUsage.count`,{count:formatExactTokens(value,t)})}function reading(first,second){if(second===null)return{label:first,text:first};return{label:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[first,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.sep,"aria-hidden":true,children:`·`}),second]}),text:`${first} · ${second}`}}function useSessionStats(useChat,useProjection){const settledNodes=useChat(s=>s.legacy.nodes);const projected=useProjection(`sessionStats`);return(0,react.useMemo)(()=>projected??deriveStats(settledNodes),[projected,settledNodes])}function decodeSpeed(stats,t){return t(`message.tokensPerSecond`,{tps:formatTokensPerSecond(stats.decodeTokens/(stats.decodeMs/1e3))})}const FULL_READING_TOOLTIP={side:`top`,portal:true,delayMs:200,onlyWhenClipped:true};function PlainPill({stat,icon,label,text}){return(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.anchor,"data-composer-stat":stat,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:text,...FULL_READING_TOOLTIP,openOnClick:true,children:(0,react_jsx_runtime.jsxs)(`span`,{className:StatsPills_module_css_default.pill,children:[icon,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.label,children:label})]})})})}function DialogPill({stat,icon,label,text,title,titleValue,children}){const{open,setOpen,rootRef,panelRef,anchorName}=useStatDialog();return(0,react_jsx_runtime.jsxs)(`span`,{ref:rootRef,style:{anchorName},className:StatsPills_module_css_default.anchor,"data-composer-stat":stat,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:text,...FULL_READING_TOOLTIP,disabled:open,children:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:StatsPills_module_css_default.pill,"aria-haspopup":`dialog`,"aria-expanded":open,"aria-label":text,onClick:()=>{setOpen(!open)},children:[icon,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.label,children:label})]})}),open&&(0,react_dom.createPortal)((0,react_jsx_runtime.jsxs)(`div`,{ref:panelRef,className:stat_dialog_module_css_default.panel,role:`dialog`,"aria-label":title,style:{positionAnchor:anchorName},children:[(0,react_jsx_runtime.jsxs)(`div`,{className:stat_dialog_module_css_default.title,children:[(0,react_jsx_runtime.jsxs)(`span`,{className:stat_dialog_module_css_default.titleLabel,children:[icon,title]}),titleValue!==void 0&&(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.titleValue,children:titleValue})]}),(0,react_jsx_runtime.jsx)(`div`,{className:stat_dialog_module_css_default.titleRule,"aria-hidden":true}),children]}),document.body)]})}const ActivityPill=(0,react.memo)(function ActivityPill({useChat,useProjection,usePerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const stats=useSessionStats(useChat,useProjection);const speed=stats.decodeMs>0?decodeSpeed(stats,t):null;const icon=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconGaugeOutlineRegular,{});if(mode===`compact`)return speed===null?null:(0,react_jsx_runtime.jsx)(PlainPill,{stat:`activity`,icon,...reading(speed,null)});if(stats.steps===0)return null;const counts=t(`stats.counts`,{turns:stats.turns,steps:stats.steps});const content={stat:`activity`,icon,...reading(counts,speed)};if(stats.llmMs<=0&&stats.toolMs<=0&&stats.ttftSteps<=0&&speed===null)return(0,react_jsx_runtime.jsx)(PlainPill,{...content});return(0,react_jsx_runtime.jsx)(DialogPill,{...content,title:t(`stats.dialog.title`),titleValue:counts,children:(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-session-stats-details":true,children:[stats.llmMs>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.llmTime`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.llmMs,t)})]}),stats.toolMs>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.toolTime`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.toolMs,t)})]}),stats.ttftSteps>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.ttft`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.ttftMs/stats.ttftSteps,t)})]}),speed!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.speed`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:speed})]})]})})});const UsagePill=(0,react.memo)(function UsagePill({useProjection,usePerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const usage=useProjection(`tokenUsage`);if(usage===void 0||billedInputTokens(usage)===0&&usage.outputTokens===0)return null;const cacheHit=cacheHitPercent(usage);const cacheHitText=cacheHit!==null?t(`stats.cacheHit`,{percent:cacheHit}):null;const icon=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{});if(mode===`compact`)return cacheHitText===null?null:(0,react_jsx_runtime.jsx)(PlainPill,{stat:`usage`,icon,...reading(cacheHitText,null)});const total=billedInputTokens(usage)+usage.outputTokens;return(0,react_jsx_runtime.jsx)(DialogPill,{stat:`usage`,icon,...reading(t(`message.turnUsage.count`,{count:formatTokens(total,t)}),cacheHitText),title:t(`stats.dialog.usageTitle`),titleValue:exactCount(total,t),children:(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-session-stats-usage":true,children:[cacheHit!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheHit`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:`${cacheHit}%`})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.input`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.uncachedInputTokens,t)}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheRead`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.cacheReadTokens,t)}),usage.cacheWriteTokens!==0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheWrite`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.cacheWriteTokens,t)})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.output`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.outputTokens,t)})]})})});const CHAT_SYNTHETIC_SEQ_OFFSETS={interruptedAssistant:-.9,interruptedFollowup:-.8,processControl:-.1,maxTokensNotice:.05,finalizedFollowup:.1};function contextLocation(context){return context.start?.location??context.matches[0]?.location??{kind:`unresolved`}}function locationCoordinates(location){if(location.kind===`step`)return{turn:location.turn.turn,step:location.step.step};if(location.kind===`turn`)return{turn:location.turn.turn};return{}}function chatNode(context,kind,anchorSeq,data,options={}){return{key:context.key,kind,id:context.id,target:`chat`,anchorSeq,location:options.location??contextLocation(context),visibility:options.visibility??`visible`,groupTree:options.groupTree,data}}function asRecord(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:null}function readString(record,key){const value=record[key];return typeof value===`string`&&value.length>0?value:null}function collect(source,member,field){const list=source[member];if(!Array.isArray(list))return[];const seen=[];for(const entry of list){const record=asRecord(entry);const value=record===null?null:readString(record,field);if(value!==null&&!seen.includes(value))seen.push(value)}return seen}function joined(names){return names.length>0?names.join(`, `):null}const KNOWN_FORMS=[`instructions`,`catalog`,`snapshot`,`notice`,`relay`,`recall`];function contextForm(source){const record=asRecord(source);const form=record===null?null:readString(record,`form`);return form!==null&&KNOWN_FORMS.includes(form)?form:null}function contextProducer(source){const record=asRecord(source);const kind=record===null?null:readString(record,`kind`);if(record===null||kind===null)return{role:`inject`,label:null};switch(kind){case`session-reference`:return{role:`recall`,label:joined(collect(record,`references`,`label`))??kind};case`agent-instructions`:return{role:`inject`,label:joined(collect(record,`changes`,`path`))??kind};case`skill-invocation`:return{role:`inject`,label:readString(record,`name`)??kind};default:return{role:`inject`,label:kind}}}function sessionRecallLabels(source){const record=asRecord(source);if(record===null||readString(record,`kind`)!==`session-reference`)return[];return collect(record,`references`,`label`)}function skillInvocationName(source){const record=asRecord(source);if(record===null||readString(record,`kind`)!==`skill-invocation`)return null;return readString(record,`name`)}function toAssistantBlocks(content){return content.map(toAssistantBlock)}function toAssistantBlock(block){switch(block.type){case`text`:return{kind:`text`,text:block.text};case`reasoning`:return{kind:`reasoning`,text:block.text};case`image`:return{kind:`image`,attachment:block.attachment};case`tool-call`:return{kind:`tool-call`,callId:String(block.id),name:block.name,argsRaw:block.arguments};default:return{kind:`other`,block}}}function emptyAssistantBlock(blockType){switch(blockType){case`text`:return{kind:`text`,text:``};case`reasoning`:return{kind:`reasoning`,text:``};case`tool-call`:return{kind:`tool-call`,callId:``,name:``,argsRaw:``};default:return{kind:`other`,block:null}}}function displayFailure(failure){if(failure===null||typeof failure!==`object`)return{message:String(failure)};const record=failure;const code=typeof record.code===`string`?record.code:void 0;if(code===`AUTH`)return{code,message:``};return{...code===void 0?{}:{code},message:typeof record.message===`string`?record.message:JSON.stringify(failure)}}function isTokenDelta(chunk){switch(chunk.type){case`text-delta`:case`reasoning-delta`:return chunk.text!==``;case`tool-call-delta`:return chunk.argumentsDelta!==``||chunk.name!==void 0;default:return false}}function initialState(turn,step){return{turn,step,blocks:[],visibleByIndex:[],visibleBlocks:0,firstVisibleSeq:void 0,firstVisibleTime:void 0,firstTokenTime:void 0,final:void 0,usage:void 0}}function compactBlocks(blocks){return blocks.filter(block=>block!==void 0)}function blockIsVisible(block){if(block===void 0||block.kind===`tool-call`)return false;if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true}function hasVisibleContent(blocks){return blocks.some(blockIsVisible)}function hasInterruptionEvidence(blocks){return blocks.some(block=>{if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true})}function resetForRetry(state){return{...initialState(state.turn,state.step),firstTokenTime:state.firstTokenTime}}function updateChunk(state,chunk,seq,time){if(chunk.type===`tool-call-delta`){const previous=state.blocks[chunk.index];if(previous?.kind===`tool-call`&&previous.callId!==``&&(chunk.name===void 0||chunk.name===previous.name)&&(state.firstTokenTime!==void 0||!isTokenDelta(chunk)))return state}const blocks=[...state.blocks];let changedIndex=-1;let previousVisible=false;let nextVisible=false;switch(chunk.type){case`block-start`:changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]=emptyAssistantBlock(chunk.blockType);nextVisible=blockIsVisible(blocks[chunk.index]);break;case`text-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`text`,text:(previous?.kind===`text`?previous.text:``)+chunk.text};nextVisible=previous?.kind===`text`&&previousVisible||chunk.text.trim()!==``;break}case`reasoning-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`reasoning`,text:(previous?.kind===`reasoning`?previous.text:``)+chunk.text};nextVisible=previous?.kind===`reasoning`&&previousVisible||chunk.text.trim()!==``;break}case`tool-call-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`tool-call`,callId:(previous?.kind===`tool-call`?previous.callId:``)||String(chunk.id),name:chunk.name??(previous?.kind===`tool-call`?previous.name:``),argsRaw:previous?.kind===`tool-call`?previous.argsRaw:``};break}case`block-end`:changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]=toAssistantBlock(chunk.block);nextVisible=blockIsVisible(blocks[chunk.index]);break;case`usage`:return{...state,usage:chunk.usage};default:return state}const visibleBlocks=state.visibleBlocks-Number(previousVisible)+Number(nextVisible);let visibleByIndex=state.visibleByIndex;if(previousVisible!==nextVisible){const next=[...visibleByIndex];next[changedIndex]=nextVisible;visibleByIndex=next}const firstToken=isTokenDelta(chunk);return{...state,blocks,visibleByIndex,visibleBlocks,...visibleBlocks>0&&state.firstVisibleSeq===void 0?{firstVisibleSeq:seq,firstVisibleTime:time}:{},...firstToken&&state.firstTokenTime===void 0?{firstTokenTime:time}:{}}}function settleMessage(state,match,event){const blocks=toAssistantBlocks(event.data.message.content);const visibleByIndex=blocks.map(blockIsVisible);return{...state,blocks,visibleByIndex,visibleBlocks:visibleByIndex.reduce((count,visible)=>count+Number(visible),0),final:match,usage:event.data.usage}}function closedBoundary(location){if(location.kind===`step`&&location.step.status===`closed`&&location.step.end!==void 0)return location.step.end;if((location.kind===`step`||location.kind===`turn`)&&location.turn.status===`closed`&&location.turn.end!==void 0)return location.turn.end}function finalNode(state,context){const final=state.final;if(final?.event.type===`assistant/message`){const event=final.event;return{kind:`assistant`,seq:event.seq,messageId:event.data.message.id,time:event.time,turn:state.turn,step:state.step,blocks:toAssistantBlocks(event.data.message.content),usage:event.data.usage,timing:{stepStartTime:context.start?.event.time??null,firstTokenTime:state.firstTokenTime??null,completedTime:event.time},...event.data.interrupted===true?{interrupted:true}:{}}}const location=context.start?.location??context.matches.at(-1)?.location;const boundary=location===void 0?void 0:closedBoundary(location);if(boundary===void 0)return void 0;const blocks=compactBlocks(state.blocks);if(!hasInterruptionEvidence(blocks))return void 0;return{kind:`assistant`,seq:boundary.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedAssistant,time:boundary.time,turn:state.turn,step:state.step,blocks,interrupted:true}}function fallbackState$5(context){let state;for(const match of context.matches){if(match.event.type===`assistant/live-chunk`){state??=initialState(match.event.data.turn,match.event.data.step);state=updateChunk(state,match.event.data.chunk,match.event.seq,match.event.time);continue}if(match.event.type===`assistant/message`){state??=initialState(match.event.data.turn,match.event.data.step);state=settleMessage(state,match,match.event);continue}if(match.event.type===`llm/retry`&&state!==void 0)state=resetForRetry(state)}return state}function projectAssistant(context){const state=context.state??fallbackState$5(context);if(state===void 0)return void 0;const settled=finalNode(state,context);const blocks=settled?.blocks??compactBlocks(state.blocks);const visible=settled===void 0?state.visibleBlocks>0:hasVisibleContent(blocks);const status=settled?.interrupted===true?`interrupted`:settled===void 0?`running`:`settled`;const anchorSeq=(settled?.interrupted===true?settled.seq:state.firstVisibleSeq??settled?.seq)??context.matches[0]?.event.seq??0;const time=settled?.time??state.firstVisibleTime??context.matches[0]?.event.time??0;return{anchorSeq,visible,settled,data:{status,turn:state.turn,step:state.step,blocks,time,...state.usage===void 0?{}:{usage:state.usage},...settled===void 0?{}:{finalNode:settled}}}}function publishedAssistantData(context){const location=context.start?.location??context.matches.at(-1)?.location;return location?.kind===`step`?location.step.data.get(`assistant-step`):void 0}const assistantDefinition={kind:`assistant-step`,target:`chat`,match:event=>{if(event.type===`step/start`)return{id:`${event.data.turn}:${event.data.step}`,role:`start`};if(event.type===`assistant/live-chunk`||event.type===`assistant/message`&&event.surfaceOp===`append`)return{id:`${event.data.turn}:${event.data.step}`,role:`update`};if(event.type===`llm/retry`)return{id:`${event.data.turn}:${event.data.step}`,role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`step/start`)throw new Error(`assistant-step start requires step/start`);return initialState(match.event.data.turn,match.event.data.step)},update:(context,match)=>{if(match.event.type===`assistant/live-chunk`)return updateChunk(context.state,match.event.data.chunk,match.event.seq,match.event.time);if(match.event.type===`assistant/message`)return settleMessage(context.state,match,match.event);if(match.event.type===`llm/retry`)return resetForRetry(context.state);return context.state},publication:match=>{if(match.event.type===`step/start`)return`none`;if(match.event.type!==`assistant/live-chunk`)return`immediate`;const type=match.event.data.chunk.type;return type===`usage`||type===`finish`?`none`:`animation-frame`},buildLocationData:(context,scope)=>{if(scope!==`step`)return null;const projected=projectAssistant(context);if(projected===void 0)return null;return{kind:`step`,turn:projected.data.turn,step:projected.data.step,key:`assistant-step`,value:projected.data}},buildViewNode:context=>{const current=context.current.get(`chat`);const state=context.state??fallbackState$5(context);const data=publishedAssistantData(context);if(state===void 0||data===void 0)return current==null?null:{...current,visibility:`hidden`};const settled=data.finalNode;const visible=settled===void 0?state.visibleBlocks>0:hasVisibleContent(data.blocks);if(settled===void 0&&!visible&&current==null)return null;return chatNode(context,`assistant-step`,(settled?.interrupted===true?settled.seq:state.firstVisibleSeq??settled?.seq)??context.matches[0]?.event.seq??0,data,{visibility:settled?.interrupted===true||visible?`visible`:`hidden`})}};function registerAssistantConversationNode(ctx){const match=assistantDefinition.match.bind(assistantDefinition);ctx.uiConversation.events.register({...assistantDefinition,match:{"step/start":match,"assistant/live-chunk":match,"assistant/message":match,"llm/retry":match}})}function isSettledTool(block){return`kind`in block}function isRunningTool(block){return!isSettledTool(block)}function isVisibleChatNode(node){if(node.kind===`command`){if(node.data.name===`permission`)return false;if(node.data.name===`team`&&node.data.outcome?.kind!==`error`){const selection=node.data.args?.trim();if(selection===`on`||selection===`off`)return false}}return node.visibility===`visible`&&(node.kind!==`system-prompt`||node.data.message!==void 0)}const NO_TURNS=[];var GroupTreeSegments=class{position;openings=new Map;latestOpening;latestStart;constructor(position){this.position=position}track(previous,next){const before=this.openingTurn(previous);const after=this.openingTurn(next);if(before===after)return;if(before!==void 0&&this.adjust(before,-1)===0&&before===this.latestOpening)this.latestOpening=this.lastOpeningTurn();if(after!==void 0){this.adjust(after,1);if(this.latestOpening===void 0||after>this.latestOpening)this.latestOpening=after}}inLatest(turn){return turn!==void 0&&this.latestStart!==void 0&&turn>=this.latestStart}settle(turnOrder){const previous=this.latestStart;const start=this.latestOpening??turnOrder[0];if(start===previous)return NO_TURNS;this.latestStart=start;const bounded=previous!==void 0&&start!==void 0;const low=bounded?Math.min(previous,start):Number.NEGATIVE_INFINITY;const high=bounded?Math.max(previous,start):Number.POSITIVE_INFINITY;const changed=[];for(const turn of turnOrder.slice(turnOrder.findLastIndex(turn=>turn<low)+1)){if(turn>=high)break;changed.push(turn)}return changed}openingTurn(node){return node!==void 0&&isAtOrOutside(node,this.position)?locationCoordinates(node.location).turn:void 0}lastOpeningTurn(){let last;for(const turn of this.openings.keys())if(last===void 0||turn>last)last=turn;return last}adjust(turn,delta){const next=(this.openings.get(turn)??0)+delta;if(next>0)this.openings.set(turn,next);else this.openings.delete(turn);return next}};const PROMPT_PREVIEW_LIMIT=50;const RESPONSE_PREVIEW_LIMIT=120;function preview(parts,limit){let text=``;let unread=false;for(const part of parts){if(text.length>=limit*2){unread=true;break}const clipped=part.length>limit*2;const chunk=clipped?part.slice(0,limit*2):part;text+=text===``?chunk:` ${chunk}`;if(clipped){unread=true;break}}const normalized=text.replace(/\s+/g,` `).trim();if(normalized.length>limit-1)return`${normalized.slice(0,limit-1).trimEnd()}…`;return unread?`${normalized}…`:normalized}function promptText(node){if(node.kind!==`user`)return``;return preview(node.data.content.flatMap(block=>block.type===`text`?[block.text]:[]),PROMPT_PREVIEW_LIMIT)}function responseText(node){if(node.kind!==`assistant-step`)return``;return preview(node.data.blocks.flatMap(block=>block.kind===`text`?[block.text]:[]),RESPONSE_PREVIEW_LIMIT)}function sameTurnNavigationItem(left,right){if(left===void 0||right===void 0)return left===right;return left.turn===right.turn&&left.anchorKey===right.anchorKey&&left.prompt===right.prompt&&left.response===right.response}function turnNavigationItem(turn,locations,nodes){const loaded=locations.getTurn(turn).map(key=>nodes.get(key)).filter(node=>node!==void 0&&isVisibleChatNode(node));const user=loaded.find(node=>node.kind===`user`);const anchor=user??loaded[0];if(anchor===void 0)return void 0;const response=loaded.findLast(node=>responseText(node)!==``);return{turn,anchorKey:anchor.key,prompt:user===void 0?``:promptText(user),response:response===void 0?``:responseText(response)}}function nodeTurn(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.turn:void 0}function samePresentation(left,right){return left===right||left!==void 0&&right!==void 0&&left.spec===right.spec&&left.turn===right.turn&&left.turnStarted===right.turnStarted&&left.turnClosed===right.turnClosed&&left.hasExternalProcess===right.hasExternalProcess&&left.hasNonReplyProcess===right.hasNonReplyProcess&&left.hasInterleavedInput===right.hasInterleavedInput}function derivePresentation(turn,locations,nodes){const keys=locations.getTurn(turn);const control=keys.map(key=>nodes.get(key)).find(node=>node?.kind===`turn-process`);if(control===void 0)return void 0;const spec=control.data;const location=control.location;if(location.kind!==`turn`&&location.kind!==`step`)return void 0;let openingHumanAnchor;for(const key of keys){const node=nodes.get(key);if(node!==void 0&&isAtOrOutside(node,`input`)&&(spec.controlAnchorSeq===location.turn.start?.seq||node.anchorSeq<spec.controlAnchorSeq))openingHumanAnchor=Math.max(openingHumanAnchor??node.anchorSeq,node.anchorSeq)}let hasExternalProcess=false;let hasNonReplyProcess=false;let hasInterleavedInput=false;for(const key of keys){const node=nodes.get(key);if(node===void 0||!isVisibleChatNode(node)||node.kind===`turn-process`)continue;if(isAtOrOutside(node,`input`)&&(openingHumanAnchor===void 0||node.anchorSeq>openingHumanAnchor))hasInterleavedInput=true;if(isAtOrOutside(node,`turn`)||node.anchorSeq<spec.processStartSeq||spec.answerAnchorSeq!==null&&node.anchorSeq>=spec.answerAnchorSeq)continue;if(node.kind!==`assistant-step`||spec.answerStep===null||node.data.step!==spec.answerStep){hasExternalProcess=true;if(node.kind!==`assistant-step`||node.data.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``))hasNonReplyProcess=true}}return{turn,spec,turnStarted:location.turn.start!==void 0,turnClosed:location.turn.status===`closed`,hasExternalProcess,hasNonReplyProcess,hasInterleavedInput}}var ChatTurnProcessProjector=class{presentations=new Map;get(node){const turn=nodeTurn(node);return turn===void 0?void 0:this.presentations.get(turn)}replace(order,locations,nodes){const turns=new Set;for(const key of order){const turn=nodeTurn(nodes.get(key));if(turn!==void 0)turns.add(turn)}const changed=new Set;for(const turn of new Set([...this.presentations.keys(),...turns]))if(this.set(turn,turns.has(turn)?derivePresentation(turn,locations,nodes):void 0))changed.add(turn);return changed}update(turns,locations,nodes){const changed=new Set;for(const turn of turns)if(this.set(turn,derivePresentation(turn,locations,nodes)))changed.add(turn);return changed}set(turn,next){if(samePresentation(this.presentations.get(turn),next))return false;if(next===void 0)this.presentations.delete(turn);else this.presentations.set(turn,next);return true}};const EMPTY_KEYS=[];const EMPTY_TURNS=[];const EMPTY_ITEMS=[];const EMPTY_LIST=[];function sameReferences$1(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function cachedSource(sources,key,create){let source=sources.get(key);if(source===void 0){source=create();sources.set(key,source)}return source}var MutableChatSource=class{read;label;listeners=new Set;published;constructor(read,label){this.read=read;this.label=label;this.published=read()}getSnapshot=()=>this.read();subscribe=listener=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener)}};publish(){const next=this.getSnapshot();if(this.published===next)return;this.published=next;(0,_deepseek_ai_dsh_client_store.notifySubscribers)(this.listeners,this.label)}};var TurnKindNodes=class{nodes=new Map;current=EMPTY_LIST;dirty=false;observable;source(){return this.observable??=new MutableChatSource(()=>this.read(),`[ui-chat] turn kind nodes`)}set(node){const previous=this.nodes.get(node.key);this.nodes.set(node.key,node);if(previous!==void 0&&previous.data===node.data&&previous.anchorSeq===node.anchorSeq)return;this.dirty=true}delete(key){this.nodes.delete(key);this.dirty=true}publish(){this.observable?.publish()}read(){if(this.dirty){this.current=[...this.nodes.values()].sort((a,b)=>a.anchorSeq-b.anchorSeq).map(node=>node.data);this.dirty=false}return this.current}};var MutableChatNodeStore=class{byKey=new Map;turnProcesses=new ChatTurnProcessProjector;sources=new Map;processSources=new Map;bottomSources=new Map;exchanges=new GroupTreeSegments(`exchange`);dirtyKeys=new Set;dirtyBottomKeys=new Set;dirtyProcessKeys=new Set;turnKinds=new Map;dirtyTurnKinds=new Set;valuesCache=EMPTY_LIST;valuesDirty=false;get(key){return this.byKey.get(key)}source(key){return cachedSource(this.sources,key,()=>new MutableChatSource(()=>this.get(key),`[ui-chat] node source ${key}`))}bottomSource(key){return cachedSource(this.bottomSources,key,()=>new MutableChatSource(()=>{const node=this.get(key);return node!==void 0&&isVisibleChatNode(node)&&this.exchanges.inLatest(locationCoordinates(node.location).turn)},`[ui-chat] node bottom source ${key}`))}settleBottom(turnOrder,locations){for(const turn of this.exchanges.settle(turnOrder))for(const key of locations.getTurn(turn))this.dirtyBottomKeys.add(key)}turnDataSource(turn,kind){return this.turnKind(turn,kind).source()}turnKind(turn,kind){return cachedSource(cachedSource(this.turnKinds,turn,()=>new Map),kind,()=>new TurnKindNodes)}updateTurnKind(previous,next){const before=previous===void 0?void 0:locationCoordinates(previous.location).turn;const after=next===void 0?void 0:locationCoordinates(next.location).turn;if(previous!==void 0&&before!==void 0&&(before!==after||previous.kind!==next?.kind)){const collection=this.turnKind(before,previous.kind);collection.delete(previous.key);this.dirtyTurnKinds.add(collection)}if(next!==void 0&&after!==void 0){const collection=this.turnKind(after,next.kind);collection.set(next);this.dirtyTurnKinds.add(collection)}}processSource(key){return cachedSource(this.processSources,key,()=>new MutableChatSource(()=>this.process(key),`[ui-chat] node process source ${key}`))}process(key){return this.turnProcesses.get(this.get(key))}values(){if(this.valuesDirty){this.valuesCache=[...this.byKey.values()];this.valuesDirty=false}return this.valuesCache}replace(nodes){const previous=new Map(this.byKey);this.byKey.clear();for(const node of nodes){this.byKey.set(node.key,node);if(previous.get(node.key)!==node){this.updateTurnKind(previous.get(node.key),node);this.exchanges.track(previous.get(node.key),node);this.dirtyKeys.add(node.key);this.dirtyProcessKeys.add(node.key)}previous.delete(node.key)}for(const key of previous.keys()){this.updateTurnKind(previous.get(key),void 0);this.exchanges.track(previous.get(key),void 0);this.dirtyKeys.add(key);this.dirtyProcessKeys.add(key)}this.valuesCache=[...this.byKey.values()];this.valuesDirty=false}upsert(nodes){let changed=false;for(const node of nodes){if(this.byKey.get(node.key)===node)continue;this.updateTurnKind(this.byKey.get(node.key),node);this.exchanges.track(this.byKey.get(node.key),node);this.byKey.set(node.key,node);this.dirtyKeys.add(node.key);this.dirtyProcessKeys.add(node.key);changed=true}if(changed)this.valuesDirty=true}touchProcesses(turns,locations){for(const turn of turns)for(const key of locations.getTurn(turn))this.dirtyProcessKeys.add(key)}replaceProcesses(order,locations){this.touchProcesses(this.turnProcesses.replace(order,locations,this),locations)}updateProcesses(turns,locations){this.touchProcesses(this.turnProcesses.update(turns,locations,this),locations)}publish(){const dirty=[...this.dirtyKeys];const dirtyBottom=new Set([...this.dirtyBottomKeys,...dirty]);const dirtyProcesses=[...this.dirtyProcessKeys];const dirtyTurnKinds=[...this.dirtyTurnKinds];this.dirtyKeys.clear();this.dirtyBottomKeys.clear();this.dirtyProcessKeys.clear();this.dirtyTurnKinds.clear();for(const key of dirty)this.sources.get(key)?.publish();for(const key of dirtyBottom)this.bottomSources.get(key)?.publish();for(const key of dirtyProcesses)this.processSources.get(key)?.publish();for(const collection of dirtyTurnKinds)collection.publish()}};var MutableChatLocationIndex=class{turns=new Map;steps=new Map;positions=new Map;getTurn(turn){return this.turns.get(turn)??EMPTY_KEYS}getStep(turn,step){return this.steps.get(stepKey(turn,step))??EMPTY_KEYS}getPosition(key){return this.positions.get(key)}rebuild(order,store){const turns=new Map;const steps=new Map;const positions=new Map;const changedTurns=new Set;for(const[index,key]of order.entries()){const location=store.get(key)?.location;if(location===void 0)continue;const coordinates=locationCoordinates(location);const previous=this.positions.get(key);const position={turn:coordinates.turn,previous:order[index-1],next:order[index+1]};const unchanged=previous!==void 0&&previous.turn===position.turn&&previous.previous===position.previous&&previous.next===position.next;positions.set(key,unchanged?previous:position);if(!unchanged){if(previous?.turn!==void 0)changedTurns.add(previous.turn);if(position.turn!==void 0)changedTurns.add(position.turn)}if(coordinates.turn===void 0)continue;const turnKeys=turns.get(coordinates.turn)??[];turnKeys.push(key);turns.set(coordinates.turn,turnKeys);if(coordinates.step===void 0)continue;const step=stepKey(coordinates.turn,coordinates.step);const stepKeys=steps.get(step)??[];stepKeys.push(key);steps.set(step,stepKeys)}for(const[key,position]of this.positions)if(!positions.has(key)&&position.turn!==void 0)changedTurns.add(position.turn);this.positions=positions;this.turns=updateIndex(this.turns,turns);this.steps=updateIndex(this.steps,steps);return[...changedTurns]}touch(nodes){const turns=new Set;const steps=new Set;for(const node of nodes){const coordinates=locationCoordinates(node.location);if(coordinates.turn===void 0||!this.turns.get(coordinates.turn)?.includes(node.key))continue;turns.add(coordinates.turn);if(coordinates.step!==void 0)steps.add(stepKey(coordinates.turn,coordinates.step))}for(const turn of turns){const keys=this.turns.get(turn);if(keys===void 0)continue;this.turns.set(turn,[...keys])}for(const step of steps){const keys=this.steps.get(step);if(keys===void 0)continue;this.steps.set(step,[...keys])}}};function updateIndex(previous,nextMutable){const next=new Map;const keys=new Set([...previous.keys(),...nextMutable.keys()]);for(const key of keys){const before=previous.get(key)??EMPTY_KEYS;const candidate=nextMutable.get(key)??EMPTY_KEYS;const value=sameReferences$1(before,candidate)?before:candidate;if(candidate.length>0)next.set(key,value)}return next}var MutableTurnNavigationIndex=class{current=EMPTY_ITEMS;byTurn=new Map;items(){return this.current}rebuild(timeline,locations,nodes){const next=[];const byTurn=new Map;for(const turn of timeline.turnOrder){const derived=turnNavigationItem(turn,locations,nodes);if(derived===void 0)continue;const previous=this.byTurn.get(turn);const item=previous!==void 0&&sameTurnNavigationItem(previous,derived)?previous:derived;next.push(item);byTurn.set(turn,item)}this.byTurn=byTurn;if(!(next.length===this.current.length&&next.every((item,index)=>item===this.current[index])))this.current=next}touch(turns,locations,nodes){if(turns.size===0)return;const next=this.current.map(item=>{if(!turns.has(item.turn))return item;const derived=turnNavigationItem(item.turn,locations,nodes);if(derived===void 0||sameTurnNavigationItem(item,derived))return item;this.byTurn.set(item.turn,derived);return derived});if(next.some((item,index)=>item!==this.current[index]))this.current=next}};function stepKey(turn,step){return`${turn}:${step}`}function locationTurnStatus(location){return location.kind===`turn`||location.kind===`step`?location.turn.status:void 0}function processPresentationInputChanged(previous,next,structural){if(structural||previous===void 0)return true;if(locationTurnStatus(previous.location)!==locationTurnStatus(next.location))return true;if(previous.kind===`turn-process`&&next.kind===`turn-process`)return previous.data!==next.data;return previous.kind===`assistant-step`&&next.kind===`assistant-step`&&previous.data.step!==next.data.step}function turnProcessPresentations(nodes){const presentations=new Map;for(const raw of nodes){const node=raw;if(node.kind===`turn-process`)presentations.set(node.data.turn,{...presentations.get(node.data.turn),control:node})}for(const raw of nodes){const node=raw;const location=node.location;if(location.kind!==`turn`&&location.kind!==`step`)continue;const current=presentations.get(location.turn.turn)??{};const controlAnchor=current.control?.data.controlAnchorSeq;if(isAtOrOutside(node,`input`)&&controlAnchor!==void 0&&(controlAnchor===location.turn.start?.seq||node.anchorSeq<controlAnchor)){presentations.set(location.turn.turn,{...current,openingInputAnchor:Math.max(current.openingInputAnchor??node.anchorSeq,node.anchorSeq)});continue}if(isAtOrOutside(node,`turn`))continue;presentations.set(location.turn.turn,{...current,earliestProcessAnchor:Math.min(current.earliestProcessAnchor??node.anchorSeq,node.anchorSeq)})}return presentations}function presentationPosition(raw,presentations){const node=raw;const location=node.location;if(location.kind!==`turn`&&location.kind!==`step`)return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq};const presentation=presentations.get(location.turn.turn);if(presentation===void 0)return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq};const openingInputAnchor=presentation.openingInputAnchor;if(openingInputAnchor!==void 0&&node.anchorSeq<openingInputAnchor&&!isAtOrOutside(node,`turn`))return{anchor:openingInputAnchor,rank:2,originalAnchor:node.anchorSeq};if(presentation.control!==void 0&&node.key===presentation.control.key)return openingInputAnchor===void 0?{anchor:presentation.earliestProcessAnchor??node.anchorSeq,rank:-1,originalAnchor:node.anchorSeq}:{anchor:openingInputAnchor,rank:1,originalAnchor:node.anchorSeq};return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq}}function orderedVisibleChatNodes(nodes){const visible=nodes.filter(node=>isVisibleChatNode(node));const presentations=turnProcessPresentations(visible);return visible.sort((left,right)=>{const leftPosition=presentationPosition(left,presentations);const rightPosition=presentationPosition(right,presentations);return leftPosition.anchor-rightPosition.anchor||leftPosition.rank-rightPosition.rank||leftPosition.originalAnchor-rightPosition.originalAnchor||left.key.localeCompare(right.key)})}function referenceMessageSeq(node){const candidate=node;return candidate.kind===`user`||candidate.kind===`steering`?candidate.data.seq:void 0}function followingRecall(node){const candidate=node;if(candidate.kind!==`context`)return void 0;return{messageSeq:candidate.data.seq-1,labels:sessionRecallLabels(candidate.data.source)}}function withReferenceLabels(node,labels){const candidate=node;if(candidate.kind!==`user`&&candidate.kind!==`steering`)return node;const current=candidate.data.referenceLabels??EMPTY_KEYS;const hasLabels=Object.hasOwn(candidate.data,`referenceLabels`);if(sameReferences$1(current,labels)&&hasLabels===labels.length>0)return node;const data={...candidate.data};if(labels.length===0)delete data.referenceLabels;else data.referenceLabels=labels;return{...candidate,data}}var ReferenceLabelProjector=class{messagesBySeq=new Map;labelsByMessageSeq=new Map;replace(nodes){this.messagesBySeq.clear();this.labelsByMessageSeq.clear();for(const node of nodes){const messageSeq=referenceMessageSeq(node);if(messageSeq!==void 0)this.messagesBySeq.set(messageSeq,node.key);const recall=followingRecall(node);if(recall!==void 0&&recall.labels.length>0)this.labelsByMessageSeq.set(recall.messageSeq,recall.labels)}return nodes.map(node=>{const messageSeq=referenceMessageSeq(node);return messageSeq===void 0?node:withReferenceLabels(node,this.labelsByMessageSeq.get(messageSeq)??EMPTY_KEYS)})}apply(upserts,store){const byKey=new Map(upserts.map(node=>[node.key,node]));const affected=new Set;for(const node of upserts){const messageSeq=referenceMessageSeq(node);if(messageSeq!==void 0){this.messagesBySeq.set(messageSeq,node.key);affected.add(messageSeq)}const recall=followingRecall(node);if(recall===void 0)continue;const current=this.labelsByMessageSeq.get(recall.messageSeq);if(recall.labels.length===0)this.labelsByMessageSeq.delete(recall.messageSeq);else this.labelsByMessageSeq.set(recall.messageSeq,current!==void 0&&sameReferences$1(current,recall.labels)?current:recall.labels);affected.add(recall.messageSeq)}for(const messageSeq of affected){const key=this.messagesBySeq.get(messageSeq);if(key===void 0)continue;const node=byKey.get(key)??store.get(key);if(node===void 0)continue;byKey.set(key,withReferenceLabels(node,this.labelsByMessageSeq.get(messageSeq)??EMPTY_KEYS))}return[...byKey.values()]}};function withSkillNames(node,names){const candidate=node;if(candidate.kind!==`user`&&candidate.kind!==`steering`)return node;const current=candidate.data.skillNames??EMPTY_KEYS;const hasNames=Object.hasOwn(candidate.data,`skillNames`);if(sameReferences$1(current,names)&&hasNames===names.length>0)return node;const data={...candidate.data};if(names.length===0)delete data.skillNames;else data.skillNames=names;return{...candidate,data}}function slashEntryOf(node){const candidate=node;if(candidate.kind===`user`||candidate.kind===`steering`)return{key:node.key,seq:node.anchorSeq,kind:`message`,name:null};if(candidate.kind===`context`){const name=skillInvocationName(candidate.data.source);return name===null?null:{key:node.key,seq:node.anchorSeq,kind:`skill`,name}}return{key:node.key,seq:node.anchorSeq,kind:`boundary`,name:null}}function sameSlashEntry(left,right){return left.seq===right.seq&&left.kind===right.kind&&left.name===right.name}var SkillNameProjector=class{entries=new Map;sorted=[];replace(nodes){this.entries.clear();this.sorted=[];for(const node of nodes){const entry=slashEntryOf(node);if(entry===null)continue;this.entries.set(entry.key,entry);this.sorted.push(entry)}this.sorted.sort((left,right)=>left.seq-right.seq);const names=new Map;for(let index=0;index<this.sorted.length;index++){if(this.sorted[index]?.kind===`boundary`)continue;const end=this.runEnd(index);this.assignRun(index,end,names);index=end}return nodes.map(node=>withSkillNames(node,names.get(node.key)??EMPTY_KEYS))}apply(upserts,store){const dirty=[];for(const node of upserts){const next=slashEntryOf(node);const previous=this.entries.get(node.key);if(previous!==void 0){if(next!==null&&sameSlashEntry(previous,next)){if(next.kind===`message`)dirty.push(next.seq);continue}this.remove(previous);dirty.push(previous.seq)}if(next===null)continue;this.insert(next);dirty.push(next.seq)}if(dirty.length===0)return upserts;const names=new Map;for(const seq of dirty)this.collectAround(seq,names);const byKey=new Map(upserts.map(node=>[node.key,node]));for(const[key,list]of names){const node=byKey.get(key)??store.get(key);if(node===void 0)continue;const next=withSkillNames(node,list);if(next!==node||byKey.has(key))byKey.set(key,next)}return[...byKey.values()]}insert(entry){this.sorted.splice(this.lowerBound(entry.seq),0,entry);this.entries.set(entry.key,entry)}remove(entry){this.sorted.splice(this.sorted.indexOf(entry),1);this.entries.delete(entry.key)}lowerBound(seq){let low=0;let high=this.sorted.length;while(low<high){const middle=low+high>>>1;if((this.sorted[middle]?.seq??Number.POSITIVE_INFINITY)<seq)low=middle+1;else high=middle}return low}runEnd(index){let end=index;while(end+1<this.sorted.length&&this.sorted[end+1]?.kind!==`boundary`)end++;return end}runStart(index){let start=index;while(start-1>=0&&this.sorted[start-1]?.kind!==`boundary`)start--;return start}assignRun(start,end,names){const list=[];for(let index=start;index<=end;index++){const entry=this.sorted[index];if(entry?.kind===`skill`&&entry.name!==null&&!list.includes(entry.name))list.push(entry.name)}for(let index=start;index<=end;index++){const entry=this.sorted[index];if(entry?.kind===`message`)names.set(entry.key,list)}}collectAround(seq,names){const at=this.lowerBound(seq);const here=this.sorted[at];if(here!==void 0&&here.seq===seq&&here.kind!==`boundary`){this.assignRun(this.runStart(at),this.runEnd(at),names);return}if(at-1>=0&&this.sorted[at-1]?.kind!==`boundary`)this.assignRun(this.runStart(at-1),at-1,names);const right=here!==void 0&&here.seq===seq?at+1:at;if(right<this.sorted.length&&this.sorted[right]?.kind!==`boundary`)this.assignRun(right,this.runEnd(right),names)}};const EMPTY_CONTRIBUTION={anchorSeq:0,nodes:EMPTY_LIST,partial:null,running:null};function legacyContribution(raw){const node=raw;if(raw.visibility!==`visible`&&node.kind!==`assistant-step`)return EMPTY_CONTRIBUTION;switch(node.kind){case`user`:case`steering`:case`context`:case`command`:case`turn-error`:case`turn-max-tokens`:case`unknown`:return{anchorSeq:node.anchorSeq,nodes:[node.data],partial:null,running:null};case`compaction`:return node.data.kind===`compaction-progress`?EMPTY_CONTRIBUTION:{anchorSeq:node.anchorSeq,nodes:[node.data],partial:null,running:null};case`assistant-step`:{const data=node.data;if(data.status===`running`){if(raw.visibility!==`visible`)return EMPTY_CONTRIBUTION;return{anchorSeq:node.anchorSeq,nodes:EMPTY_LIST,partial:{turn:data.turn,step:data.step,blocks:data.blocks},running:null}}return{anchorSeq:node.anchorSeq,nodes:data.finalNode===void 0?EMPTY_LIST:[data.finalNode],partial:null,running:null}}case`tool-call`:{const root=node.data.root;return isRunningTool(root)?{anchorSeq:node.anchorSeq,nodes:EMPTY_LIST,partial:null,running:root}:{anchorSeq:node.anchorSeq,nodes:[root],partial:null,running:null}}case`manual-compaction`:{const data=node.data;return{anchorSeq:node.anchorSeq,nodes:data.compaction===null?[data.command]:[data.command,data.compaction],partial:null,running:null}}case`model-retry`:return{anchorSeq:node.anchorSeq,nodes:node.data.attempts,partial:null,running:null};case`turn-tail`:case`system-prompt`:return EMPTY_CONTRIBUTION;default:return EMPTY_CONTRIBUTION}}function sameContribution(left,right){return left!==void 0&&left.anchorSeq===right.anchorSeq&&left.partial?.blocks===right.partial?.blocks&&left.partial?.turn===right.partial?.turn&&left.partial?.step===right.partial?.step&&left.running===right.running&&sameReferences$1(left.nodes,right.nodes)}var LegacySliceBuilder=class{contributions=new Map;finalizedContributions=new Map;runningContributions=new Map;partialContributions=new Map;finalized=EMPTY_LIST;runningCalls=EMPTY_LIST;partial=null;timeline;turnTimings=new Map;turnEnds=new Map;replace(nodes,timeline){this.contributions.clear();this.finalizedContributions.clear();this.runningContributions.clear();this.partialContributions.clear();for(const node of nodes){const contribution=legacyContribution(node);this.contributions.set(node.key,contribution);this.indexContribution(node.key,contribution)}this.rebuildFinalized();this.rebuildRunning();this.rebuildPartial();this.updateTimeline(timeline);return this.snapshot()}apply(upserts,timeline){let finalizedChanged=false;let runningChanged=false;let partialChanged=false;for(const node of upserts){const contribution=legacyContribution(node);const previous=this.contributions.get(node.key);if(sameContribution(previous,contribution))continue;finalizedChanged||=finalizedContributionChanged(previous,contribution);runningChanged||=runningContributionChanged(previous,contribution);partialChanged||=partialContributionChanged(previous,contribution);this.contributions.set(node.key,contribution);this.indexContribution(node.key,contribution)}if(finalizedChanged)this.rebuildFinalized();if(runningChanged)this.rebuildRunning();if(partialChanged)this.rebuildPartial();this.updateTimeline(timeline);return this.snapshot()}indexContribution(key,contribution){updateContributionIndex(this.finalizedContributions,key,contribution,contribution.nodes.length>0);updateContributionIndex(this.runningContributions,key,contribution,contribution.running!==null);updateContributionIndex(this.partialContributions,key,contribution,contribution.partial!==null)}rebuildFinalized(){const finalized=[...this.finalizedContributions.values()].flatMap(value=>value.nodes).sort((left,right)=>left.seq-right.seq);if(!sameReferences$1(this.finalized,finalized))this.finalized=finalized}rebuildRunning(){const runningCalls=[...this.runningContributions.values()].sort((left,right)=>left.anchorSeq-right.anchorSeq).flatMap(value=>value.running===null?[]:[value.running]);if(!sameReferences$1(this.runningCalls,runningCalls))this.runningCalls=runningCalls}rebuildPartial(){const partial=[...this.partialContributions.values()].sort((left,right)=>left.anchorSeq-right.anchorSeq).findLast(value=>value.partial!==null)?.partial??null;if(this.partial?.blocks!==partial?.blocks||this.partial?.turn!==partial?.turn||this.partial?.step!==partial?.step)this.partial=partial}updateTimeline(timeline){if(this.timeline===timeline)return;this.timeline=timeline;const turnTimings=new Map;const turnEnds=new Map;for(const turn of timeline.turns.values()){if(turn.start!==void 0)turnTimings.set(turn.turn,{startTime:turn.start.time,...turn.end===void 0?{}:{endTime:turn.end.time}});if(turn.end!==void 0)turnEnds.set(turn.turn,turn.end.seq)}this.turnTimings=turnTimings;this.turnEnds=turnEnds}snapshot(){return{nodes:this.finalized,turnTimings:this.turnTimings,turnEnds:this.turnEnds,partial:this.partial,runningCalls:this.runningCalls}}};function updateContributionIndex(index,key,contribution,present){if(present)index.set(key,contribution);else index.delete(key)}function finalizedContributionChanged(previous,next){const previousNodes=previous?.nodes??EMPTY_LIST;return!sameReferences$1(previousNodes,next.nodes)||(previousNodes.length>0||next.nodes.length>0)&&previous?.anchorSeq!==next.anchorSeq}function runningContributionChanged(previous,next){return previous?.running!==next.running||(previous.running!==null||next.running!==null)&&previous.anchorSeq!==next.anchorSeq}function partialContributionChanged(previous,next){return previous?.partial?.blocks!==next.partial?.blocks||previous?.partial?.turn!==next.partial?.turn||previous?.partial?.step!==next.partial?.step||((previous?.partial??null)!==null||next.partial!==null)&&previous?.anchorSeq!==next.anchorSeq}var ChatSnapshotBuilder=class{store=new MutableChatNodeStore;locations=new MutableChatLocationIndex;navigation=new MutableTurnNavigationIndex;legacy=new LegacySliceBuilder;referenceLabels=new ReferenceLabelProjector;skillNames=new SkillNameProjector;order=EMPTY_KEYS;latestGroupInput;readGroupNode=key=>this.store.get(key);readGroupTurn=turn=>this.locations.getTurn(turn);readGroupPosition=key=>this.locations.getPosition(key);timeline=null;empty;constructor(){this.empty=this.snapshot({turnOrder:EMPTY_TURNS,turns:new Map});this.latestGroupInput={kind:`replace`,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:this.empty.timeline}}replace(input){const nodes=this.skillNames.replace(this.referenceLabels.replace(input.nodes));this.store.replace(nodes);this.order=orderedVisibleChatNodes(nodes).map(node=>node.key);this.locations.rebuild(this.order,this.store);this.store.replaceProcesses(this.order,this.locations);this.store.settleBottom(input.timeline.turnOrder,this.locations);this.navigation.rebuild(input.timeline,this.locations,this.store);this.timeline=input.timeline;this.latestGroupInput={kind:`replace`,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:input.timeline};return this.snapshot(input.timeline,this.legacy.replace(nodes,input.timeline))}apply(input){const upserts=this.skillNames.apply(this.referenceLabels.apply(input.upserts,this.store),this.store);const processTurns=new Set;let structural=false;const contentOnly=[];const changes=[];for(const node of upserts){const previous=this.store.get(node.key);if(previous!==node)changes.push({previous,current:node});const nodeStructural=previous===void 0||previous.kind!==node.kind||previous.anchorSeq!==node.anchorSeq||previous.visibility!==node.visibility||previous.groupTree!==node.groupTree||locationIdentity(previous.location)!==locationIdentity(node.location);structural||=nodeStructural;if(!nodeStructural)contentOnly.push(node);if(processPresentationInputChanged(previous,node,nodeStructural)){const previousTurn=previous===void 0?void 0:locationCoordinates(previous.location).turn;const nextTurn=locationCoordinates(node.location).turn;if(previousTurn!==void 0)processTurns.add(previousTurn);if(nextTurn!==void 0)processTurns.add(nextTurn)}}this.store.upsert(upserts);let changedTurnOrders=EMPTY_TURNS;if(structural){const next=orderedVisibleChatNodes(this.store.values()).map(node=>node.key);this.order=sameReferences$1(this.order,next)?this.order:next;changedTurnOrders=this.locations.rebuild(this.order,this.store)}this.locations.touch(contentOnly);this.store.updateProcesses(processTurns,this.locations);this.store.settleBottom(input.timeline.turnOrder,this.locations);if(structural||input.timeline!==this.timeline)this.navigation.rebuild(input.timeline,this.locations,this.store);else this.navigation.touch(turnsOf(contentOnly),this.locations,this.store);this.timeline=input.timeline;this.latestGroupInput={kind:`apply`,changes,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:input.timeline,changedTurns:input.changedTurns??EMPTY_TURNS,changedTurnOrders};return this.snapshot(input.timeline,this.legacy.apply(upserts,input.timeline))}groupInput(){return this.latestGroupInput}publish(){this.store.publish()}snapshot(timeline,legacy=this.legacy.replace(EMPTY_LIST,timeline)){return{order:this.order,nodes:this.store,locations:this.locations,navigation:this.navigation,timeline,legacy}}};function turnsOf(nodes){const turns=new Set;for(const node of nodes){const turn=locationCoordinates(node.location).turn;if(turn!==void 0)turns.add(turn)}return turns}function locationIdentity(location){const coordinates=locationCoordinates(location);return`${location.kind}:${coordinates.turn??``}:${coordinates.step??``}`}const chatViewDefinition={target:`chat`,create:()=>new ChatSnapshotBuilder,isActive:snapshot=>snapshot.order.some(key=>snapshot.nodes.get(key)?.kind!==`command`)};function registerChatConversationView(ctx){ctx.uiConversation.views.register(chatViewDefinition)}const SURFACE_EVENT_TYPES=new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function isSurfaceEvent(event){if(!SURFACE_EVENT_TYPES.has(event.type))return false;return event.surfaceOp!==void 0}function isAppendSurfaceEvent(event){return isSurfaceEvent(event)&&event.surfaceOp===`append`}function isReplacementSurfaceEvent(event){return isSurfaceEvent(event)&&event.surfaceOp!==`append`}const COMPACT_KIND=`compact-checkpoint`;function commandFromRun(match){if(match.event.type!==`command/run`)throw new Error(`command start requires command/run`);const data=match.event.data;return{kind:`command`,seq:match.event.seq,time:match.event.time,commandId:data.commandId,name:data.name,args:data.args??null,outcome:null}}function commandFromDone(match,previous){if(match.event.type!==`command/done`)throw new Error(`command update requires command/done`);const data=match.event.data;const sourceEventSeq=data.kind===`success`&&data.sourceEventSeq!==void 0&&Number.isSafeInteger(data.sourceEventSeq)&&data.sourceEventSeq>=0?data.sourceEventSeq:void 0;return{kind:`command`,seq:previous?.seq??match.event.seq,time:previous?.time??match.event.time,commandId:data.commandId,name:previous?.name??null,args:previous?.args??null,outcome:{kind:data.kind,...data.text===void 0?{}:{text:data.text},...sourceEventSeq===void 0?{}:{sourceEventSeq}}}}function compactSource(event){if(event.type!==`user/message`||!isReplacementSurfaceEvent(event))return void 0;const source=event.data.source;if(source.kind!==COMPACT_KIND||typeof source.compactionId!==`string`)return void 0;return{compactionId:source.compactionId,...source.sourceCommandId===void 0?{}:{sourceCommandId:source.sourceCommandId}}}function compactSummary(match,checkpoint){let shadowedItemCount=null;let shadowedTokenCount=null;if(match?.event.type===`compaction/summary`){const data=match.event.data;shadowedItemCount=Array.isArray(data.shadowedSeqs)&&data.shadowedSeqs.every(seq=>Number.isSafeInteger(seq)&&seq>=0)?data.shadowedSeqs.length:null;shadowedTokenCount=Number.isSafeInteger(data.shadowedTokenCount)&&data.shadowedTokenCount>=0?data.shadowedTokenCount:null}return{kind:`compaction`,seq:checkpoint.event.seq,time:checkpoint.event.time,summaryEventSeq:match?.event.seq??null,shadowedItemCount,shadowedTokenCount}}function fallbackState$4(context){const done=context.matches.find(match=>match.event.type===`command/done`);const checkpoint=context.matches.find(match=>compactSource(match.event)!==void 0);const summary=context.matches.find(match=>match.event.type===`compaction/summary`);if(checkpoint===void 0)return done===void 0?void 0:{command:commandFromDone(done)};const source=compactSource(checkpoint.event);if(source?.sourceCommandId===void 0)return done===void 0?void 0:{command:commandFromDone(done)};return{command:done===void 0?{kind:`command`,seq:checkpoint.event.seq,time:checkpoint.event.time,commandId:source.sourceCommandId,name:`compact`,args:null,outcome:null}:{...commandFromDone(done),name:`compact`},checkpoint,...summary===void 0?{}:{summary}}}function updateCompactionState(state,match){if(match.event.type===`compaction/summary`)return{...state,summary:match};if(compactSource(match.event)!==void 0)return{...state,checkpoint:match};return state}const commandDefinition={kind:`command`,target:`chat`,match:event=>{if(event.type===`command/run`)return{id:String(event.data.commandId),role:`start`};if(event.type===`command/done`)return{id:String(event.data.commandId),role:`update`};const checkpoint=compactSource(event);if(checkpoint?.sourceCommandId!==void 0)return{id:String(checkpoint.sourceCommandId),role:`update`};if(event.type===`compaction/start`||event.type===`compaction/summary`||event.type===`compaction/end`){if(event.data.sourceCommandId!==void 0)return{id:String(event.data.sourceCommandId),role:`update`}}return null},start:(_context,match)=>({command:commandFromRun(match)}),update:(context,match)=>{if(match.event.type===`command/done`)return{...context.state,command:commandFromDone(match,context.state.command)};return updateCompactionState(context.state,match)},buildViewNode:context=>{const state=context.state??fallbackState$4(context);if(state===void 0)return null;if(state.command.name!==`compact`)return chatNode(context,`command`,state.command.seq,state.command);const compaction=state.checkpoint===void 0?null:compactSummary(state.summary,state.checkpoint);const data={command:state.command,compaction};return chatNode(context,`manual-compaction`,compaction?.seq??state.command.seq,data)}};function registerCommandConversationNode(ctx){ctx.uiConversation.events.register(commandDefinition)}function fallbackState$3(context){const ended=context.matches.find(match=>match.event.type===`compaction/end`);const summary=context.matches.find(match=>match.event.type===`compaction/summary`);const checkpoint=context.matches.find(match=>compactSource(match.event)!==void 0);return{...ended===void 0?{}:{ended},...summary===void 0?{}:{summary},...checkpoint===void 0?{}:{checkpoint}}}const compactionDefinition={kind:`compaction`,target:`chat`,match:event=>{const checkpoint=compactSource(event);if(checkpoint!==void 0&&checkpoint.sourceCommandId===void 0)return{id:checkpoint.compactionId,role:`update`};if(event.type===`compaction/start`||event.type===`compaction/summary`||event.type===`compaction/end`){if(event.data.sourceCommandId!==void 0)return null;const compactionId=event.data.compactionId;if(typeof compactionId!==`string`||compactionId===``)return null;return{id:compactionId,role:event.type===`compaction/start`?`start`:`update`}}return null},start:()=>({}),update:(context,match)=>match.event.type===`compaction/end`?{...context.state,ended:match}:updateCompactionState(context.state,match),buildViewNode:context=>{const state=context.state??fallbackState$3(context);if(state.checkpoint===void 0){const anchor=context.start??state.ended;if(anchor===void 0)return null;const location=contextLocation(context);const closed=(location.kind===`turn`||location.kind===`step`)&&location.turn.status===`closed`;const ended=state.ended?.event;const progress=ended?.type===`compaction/end`?{kind:`compaction-progress`,status:`ended`,...ended.data.error===void 0?{}:{error:ended.data.error}}:{kind:`compaction-progress`,status:closed?`interrupted`:`running`};return chatNode(context,`compaction`,anchor.event.seq,progress)}const marker=compactSummary(state.summary,state.checkpoint);return chatNode(context,`compaction`,marker.seq,marker)}};function registerCompactionConversationNode(ctx){ctx.uiConversation.events.register(compactionDefinition)}const unknownFallbackDefinition={kind:`unknown-surface`,target:`chat`,match:event=>event.type!==`assistant/live-chunk`&&isAppendSurfaceEvent(event)?{id:String(event.seq),role:`start`}:null,start:(_context,match)=>({kind:`unknown`,seq:match.event.seq,time:match.event.time,type:match.event.type,data:match.event.data}),update:context=>context.state,buildViewNode:context=>context.state===void 0?null:chatNode(context,`unknown`,context.state.seq,context.state)};function registerUnknownConversationFallback(ctx){ctx.uiConversation.events.registerFallback(unknownFallbackDefinition)}const EMPTY_PENDING={kind:`snapshot`,ids:[]};const EMPTY_CURRENT_CLAIMED=new Set;function materializePending(state){const splices=[];let current=state;while(current.kind===`splice`){splices.push(current);current=current.previous}const pending=[...current.ids];for(const splice of splices.reverse())pending.splice(splice.start,splice.removedCount,...splice.inserted);return pending}function withoutInserted(claimed,inserted){let next;for(const{id}of inserted){if(!claimed.has(id))continue;next??=new Set(claimed);next.delete(id)}return next??claimed}function applySplice(previous,splice,seq){const priorPending=previous?.state.pending??EMPTY_PENDING;const inserted=splice.inserted;const removedCount=splice.removedCount??0;if(removedCount>0&&splice.outcome!==`canceled`){const pending=materializePending(priorPending);const removed=pending.splice(splice.start,removedCount,...inserted);return{pending:{kind:`snapshot`,ids:pending},currentClaimed:new Set(removed.map(message=>message.id)),claimSeq:seq,firstClaimedHuman:removed.find(message=>message.source.kind===`user`)?.id}}const currentClaimed=withoutInserted(previous?.state.currentClaimed??EMPTY_CURRENT_CLAIMED,inserted);return{pending:{kind:`splice`,previous:priorPending,start:splice.start,removedCount,inserted},currentClaimed,claimSeq:previous?.state.claimSeq??-1,firstClaimedHuman:previous?.state.firstClaimedHuman}}function inboxDefinition(target){const kind=`inbox-${target}`;return{kind,match:event=>event.type===`agent/inbox/spliced`&&event.data.target===target?{id:String(event.seq),role:`start`}:null,start:(_context,match,reader)=>{if(match.event.type!==`agent/inbox/spliced`)throw new Error(`inbox start requires agent/inbox/spliced`);return applySplice(reader.previous(kind),match.event.data,match.event.seq)},update:context=>context.state,publication:()=>`none`}}const nextStepInboxDefinition=inboxDefinition(`next-step`);const nextTurnInboxDefinition=inboxDefinition(`next-turn`);function registerInboxConversationNodes(ctx){ctx.uiConversation.events.register(nextStepInboxDefinition);ctx.uiConversation.events.register(nextTurnInboxDefinition)}const inheritedHistoryDefinition={kind:`inherited-history`,target:`chat`,match:event=>event.type===`session/end-seed`&&event.data.inherited===true?{id:`inherited-history`,role:`start`}:null,start:()=>null,update:()=>null,buildViewNode:context=>{const latest=context.matches.at(-1);if(latest===void 0)return null;return chatNode(context,`inherited-history`,latest.event.seq,{},{location:latest.location,groupTree:`turn`})}};function registerInheritedHistoryConversationNode(ctx){ctx.uiConversation.events.register(inheritedHistoryDefinition)}function isCompactionCheckpoint(event){if(event.type!==`user/message`||!isReplacementSurfaceEvent(event))return false;return event.data.source.kind===`compact-checkpoint`}function contextMessage(event,message){return{kind:`context`,seq:event.seq,time:event.time,content:message.content,source:message.source,producer:contextProducer(message.source),form:contextForm(message.source)}}function followsProcessEvidence(location,reader){if(location.kind!==`turn`&&location.kind!==`step`)return false;return reader.previous(`process-evidence`)?.state.turn===location.turn.turn}const messageDefinition={kind:`input-message`,target:`chat`,match:event=>{if(event.type===`user/message`)return isAppendSurfaceEvent(event)&&!isCompactionCheckpoint(event)?{id:String(event.data.id),role:`start`}:null;return null},start:(_context,match,reader)=>{const event=match.event;if(event.type!==`user/message`)throw new Error(`input-message start requires user/message`);if(event.data.source.kind!==`user`){const nextTurn=reader.previous(`inbox-next-turn`)?.state;const nextStep=reader.previous(`inbox-next-step`)?.state;const location=match.location;const turnStart=location.kind===`step`?location.turn.start?.seq:void 0;const idleSteer=location.kind===`step`&&location.step.step===1&&turnStart!==void 0&&(nextStep?.claimSeq??-1)>turnStart&&(nextTurn?.claimSeq??-1)<turnStart&&nextStep!==void 0&&nextStep.firstClaimedHuman===void 0&&nextStep.currentClaimed.has(String(event.data.id));return{...contextMessage(event,event.data),waking:nextTurn?.currentClaimed.has(String(event.data.id))===true||idleSteer}}const id=String(event.data.id);const claim=reader.previous(`inbox-next-step`)?.state;return claim?.currentClaimed.has(id)===true?{kind:`steering`,messageId:event.data.id,seq:event.seq,time:event.time,content:event.data.content,source:event.data.source,...claim.firstClaimedHuman===id&&followsProcessEvidence(match.location,reader)?{batchStart:true}:{}}:{kind:`user`,messageId:event.data.id,seq:event.seq,time:event.time,content:event.data.content,source:event.data.source}},update:context=>context.state,buildViewNode:context=>{if(context.state===void 0)return null;const location=contextLocation(context);if(context.state.kind===`context`&&context.start?.event.type===`user/message`&&context.start.event.data.source.kind===`retry`&&context.start.event.data.content.length===0)return chatNode(context,`turn-trigger`,context.state.seq,context.state,{location,groupTree:`input`});const waking=context.state.kind===`context`&&context.start?.event.type===`user/message`&&context.state.waking===true;const human=context.state.kind===`user`||context.state.kind===`steering`;const opensExchange=human&&location.kind===`step`&&location.step.step===1;return chatNode(context,waking?`turn-trigger`:context.state.kind,context.state.seq,context.state,{location,groupTree:opensExchange?`exchange`:human||waking?`input`:void 0})}};const developerMessageDefinition={...messageDefinition,kind:`developer-message`,match:event=>event.type===`developer/message`?{id:String(event.data.message.id),role:`start`}:null,start:(_context,match)=>{const event=match.event;if(event.type!==`developer/message`)throw new Error(`developer-message start requires developer/message`);return contextMessage(event,event.data.message)}};function registerMessageConversationNode(ctx){ctx.uiConversation.events.register(messageDefinition);ctx.uiConversation.events.register(developerMessageDefinition)}function requestPromptAnchor(match,previous,isInitial){if(match.location.kind!==`step`)return match.event.seq;if(previous===void 0&&!isInitial)return match.event.seq;if(previous?.turn===match.location.turn.turn&&previous.step===match.location.step.step)return match.event.seq;return match.location.step.step===1?match.location.turn.start?.seq??match.location.step.start?.seq??match.event.seq:match.location.step.start?.seq??match.event.seq}function stableRequestPromptAnchor(context,match,previous,isInitial){const current=context.current.get(`chat`);return current?.kind===`system-prompt`?current.anchorSeq:requestPromptAnchor(match,previous,isInitial)}function systemMessageDefinition(inspect){return{kind:`system-message`,target:`chat`,match:event=>event.type===`system/message`||`surfaceOp`in event&&event.surfaceOp!==`append`?{id:String(event.seq),role:`start`}:null,start:(_context,match,reader)=>{if(match.event.type===`assistant/live-chunk`)throw new Error(`system-message requires a durable event`);return inspect(reader.previous(`system-message`)?.state,match.event)},update:context=>context.state,buildViewNode:context=>{const state=context.state?.introduced;const sectioned=state?.update===true&&state.message!==void 0;if(state===void 0||state.text===``&&!sectioned||context.start?.event.type!==`system/message`||context.start.event.surfaceOp!==`append`){const current=context.current.get(`chat`);if(current?.kind!==`system-prompt`)return null;return chatNode(context,`system-prompt`,current.anchorSeq,current.data,{visibility:`hidden`})}return chatNode(context,`system-prompt`,state.update?state.seq:requestPromptAnchor(context.start,void 0,true),{text:state.text,...state.update?{update:true}:{},...state.update&&state.message!==void 0?{message:state.message}:{}})}}}function requestPromptDefinition(inspect){return{kind:`request-prompt`,target:`chat`,match:event=>event.type===`request/header`?{id:String(event.seq),role:`start`}:null,start:(context,match,reader)=>{if(match.event.type!==`request/header`)throw new Error(`request-prompt start requires request/header`);const previous=reader.previous(`request-prompt`)?.state;const systemContext=reader.previous(`system-message`);const system=systemContext?.state.effective;const location=match.location.kind===`step`?{turn:match.location.turn.turn,step:match.location.step.step}:{};const inspection=inspect(previous?.prompt,match.event,system);const change=inspection.change?.kind;const systemEvent=systemContext?.matches[0]?.event;const shownByUpdate=system!==void 0&&systemEvent?.type===`system/message`&&systemEvent.surfaceOp===`append`&&(system.update||previous===void 0)&&system.turn===location.turn&&system.step===location.step;return{anchorSeq:stableRequestPromptAnchor(context,match,previous,match.event.data.reason===`initial`),showsPrompt:!shownByUpdate&&(previous===void 0||match.event.data.reason!==`change`||match.event.data.startsSeries===true||change===`system`||change===`system-and-tools`),...location,...inspection}},update:context=>context.state,buildViewNode:context=>{const state=context.state;if(state===void 0)return null;const current=context.current.get(`chat`);const visible=state.showsPrompt&&state.prompt.system!==``;if(!visible&&current?.kind!==`system-prompt`)return null;return chatNode(context,`system-prompt`,state.anchorSeq,{text:state.prompt.system},{visibility:visible?`visible`:`hidden`})}}}function registerRequestPromptConversationNode(ctx){ctx.uiConversation.events.register(systemMessageDefinition((previous,event)=>ctx.uiConversation.inspectSystemPrompt(previous,event)));ctx.uiConversation.events.register(requestPromptDefinition((previous,event,system)=>ctx.uiConversation.inspectRequestPrompt(previous,event,system)))}function scheduledNode(match){if(match.event.type!==`llm/retry`)return void 0;return{kind:`model-retry`,seq:match.event.seq,time:match.event.time,retryState:`scheduled`,...match.event.data}}function isClosed(location){return location.kind===`step`&&location.step.status===`closed`||(location.kind===`step`||location.kind===`turn`)&&location.turn.status===`closed`}function finallyFailed(location,current){if(current.retryState!==`started`||location.kind!==`step`)return false;const turn=location.turn;return turn.end?.data.reason.kind===`error`&&turn.steps.at(-1)?.step===current.step}const retryDefinition={kind:`model-retry`,target:`chat`,match:event=>{if(event.type===`llm/retry`){const retryId=event.data.retryId;if(typeof retryId!==`string`||retryId===``)return null;return{id:retryId,role:event.data.retry===1?`start`:`update`}}if(event.type===`llm/retry-started`){const retryId=event.data.retryId;return typeof retryId===`string`&&retryId!==``?{id:retryId,role:`update`}:null}return null},start:(_context,match)=>{const node=scheduledNode(match);if(node===void 0)throw new Error(`model-retry start requires a valid llm/retry event`);return{turn:node.turn,step:node.step,attempts:[node]}},update:(context,match)=>{if(match.event.type===`llm/retry`){const node=scheduledNode(match);return node===void 0?context.state:{...context.state,attempts:[...context.state.attempts,node]}}if(match.event.type!==`llm/retry-started`)return context.state;const retry=match.event.data.retry;return{...context.state,attempts:context.state.attempts.map(attempt=>attempt.retry===retry?{...attempt,retryState:`started`}:attempt)}},buildViewNode:context=>{if(context.state===void 0||context.state.attempts.length===0)return null;const location=context.start?.location??context.matches[0]?.location??{kind:`unresolved`};const stateAttempts=context.state.attempts;const attempts=stateAttempts.map((attempt,index)=>index===stateAttempts.length-1&&attempt.retryState===`scheduled`&&isClosed(location)?{...attempt,retryState:`cancelled`}:attempt);const current=attempts.at(-1);if(current===void 0)return null;const currentLocation=context.matches.findLast(match=>match.event.seq===current.seq)?.location??location;const data={attempts,current,inFlight:current.retryState===`started`&&!isClosed(currentLocation),failed:finallyFailed(currentLocation,current)};return chatNode(context,`model-retry`,attempts[0]?.seq??current.seq,data,{groupTree:`process`})}};function registerRetryConversationNode(ctx){ctx.uiConversation.events.register(retryDefinition)}const MAX_DEPTH=256;function emptyDispatchTree(){return{children:new Map,parents:new Map}}const projectedBlocks=new WeakMap;function jsonArguments(value){return JSON.stringify(value)}function rootCall(match,previous){if(match.event.type!==`tool/call`)throw new Error(`tool-call start requires tool/call`);return{phase:`start`,callId:String(match.event.data.callId),name:match.event.data.name,argsRaw:match.event.data.arguments,args:previous===void 0?PartialArguments.fromText(match.event.data.arguments):previous.args.settle(match.event.data.arguments),turn:match.event.data.turn,step:match.event.data.step,time:match.event.time,subCalls:[]}}function applyDelta(state,match){const event=match.event;if(event.type!==`assistant/live-chunk`)return state;const chunk=event.data.chunk;const root=state.root;if(chunk.type===`block-end`&&chunk.block.type===`tool-call`){if(root===void 0||`kind`in root||root.phase!==`preparing`)return state;return{...state,root:{...root,name:chunk.block.name,args:root.args.settle(chunk.block.arguments)}}}if(chunk.type!==`tool-call-delta`)return state;if(root===void 0){if(!chunk.name)return state;const args=new PartialArguments;args.append(chunk.argumentsDelta);return{...state,root:{phase:`preparing`,callId:String(chunk.id),name:chunk.name,turn:event.data.turn,step:event.data.step,time:event.time,subCalls:[],args}}}if(`kind`in root||root.phase!==`preparing`||root.args.isSealed)return state;root.args.append(chunk.argumentsDelta);return state}function preparingBlock(root,current){const changed=root.args.refresh();if(!changed&&current!==void 0&&!(`kind`in current)&&current.phase===`preparing`&&current.name===root.name&&current.args===root.args)return current;return changed?{...root}:root}function rootResult(match,previous){if(match.event.type!==`tool/result`)return void 0;const message=match.event.data.message;return{kind:`tool-result`,seq:match.event.seq,time:match.event.time,callId:String(message.source.callId),name:previous?.name??``,args:previous?.args??PartialArguments.EMPTY,call:previous===void 0?null:{name:previous.name,argsRaw:previous.argsRaw},callTime:previous?.time??null,content:message.content,isError:message.isError===true,...match.event.data.error===void 0?{}:{error:match.event.data.error},meta:match.event.data.meta,subCalls:[]}}function childCall(match,data){return{phase:`start`,callId:data.subCallId,parentCallId:data.parentCallId,name:data.name,argsRaw:jsonArguments(data.arguments),args:PartialArguments.fromObject(data.arguments),turn:locationTurn(match),step:locationStep(match),time:match.event.time,subCalls:[]}}function childResult(match,data,previous){return{kind:`tool-result`,seq:match.event.seq,time:match.event.time,callId:data.subCallId,parentCallId:data.parentCallId,name:data.name,args:previous!==void 0&&!(`kind`in previous)?previous.args:PartialArguments.fromObject(data.arguments),call:{name:data.name,argsRaw:jsonArguments(data.arguments)},callTime:previous?.time??null,content:data.content??[],meta:data.meta,isError:data.isError===true,...data.error===void 0?{}:{error:data.error},subCalls:[]}}function locationTurn(match){return match.location.kind===`step`||match.location.kind===`turn`?match.location.turn.turn:0}function locationStep(match){return match.location.kind===`step`?match.location.step.step:0}function acceptsEdge(state,parent,child){if(parent===child||state.calls.parents.has(child))return false;let cursor=parent;let parentDepth=0;const ancestors=new Set;while(cursor!==void 0){if(cursor===child||ancestors.has(cursor))return false;ancestors.add(cursor);parentDepth++;cursor=state.calls.parents.get(cursor)}const pending=[{callId:child,depth:1}];const descendants=new Set;let subtreeDepth=0;for(const candidate of pending){if(descendants.has(candidate.callId))return false;descendants.add(candidate.callId);subtreeDepth=Math.max(subtreeDepth,candidate.depth);for(const nested of state.calls.children.get(candidate.callId)?.values()??[])pending.push({callId:nested.callId,depth:candidate.depth+1})}return parentDepth+subtreeDepth<=MAX_DEPTH}function updateDispatch(state,match){const event=match.event;if(event.type!==`tool/ptc-dispatch-start`&&event.type!==`tool/ptc-dispatch`)return state;const data=event.data;const parentCallId=String(data.parentCallId);const subCallId=String(data.subCallId);const previous=state.calls.children.get(parentCallId)?.get(subCallId);if(event.type===`tool/ptc-dispatch-start`){if(previous!==void 0||!acceptsEdge(state,parentCallId,subCallId))return state;attachChild(state.calls,parentCallId,childCall(match,data));return state}if(previous===void 0&&!acceptsEdge(state,parentCallId,subCallId))return state;attachChild(state.calls,parentCallId,childResult(match,data,previous));return state}function attachChild(calls,parentCallId,child){let siblings=calls.children.get(parentCallId);if(siblings===void 0){siblings=new Map;calls.children.set(parentCallId,siblings)}siblings.set(child.callId,child);calls.parents.set(child.callId,parentCallId)}function projectBlock(block,state,interruptedAt,visited=new Set,depth=1){if(!(`kind`in block)&&block.phase===`preparing`)return block;if(visited.has(block.callId)||depth>MAX_DEPTH)return{...block,subCalls:[]};const nextVisited=new Set(visited);nextVisited.add(block.callId);const attached=state.calls.children.get(block.callId);const children=(attached===void 0?block.subCalls:[...attached.values()]).map(child=>projectBlock(child,state,interruptedAt,nextVisited,depth+1));const interruptionSeq=`kind`in block?void 0:interruptedAt?.seq;const interruptionTime=`kind`in block?void 0:interruptedAt?.time;const cached=projectedBlocks.get(block);if(cached!==void 0&&cached.interruptionSeq===interruptionSeq&&cached.interruptionTime===interruptionTime&&sameReferences(cached.children,children))return cached.value;const projected=`kind`in block||interruptedAt===void 0?sameReferences(block.subCalls,children)?block:{...block,subCalls:children}:{kind:`tool-result`,seq:interruptedAt.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedFollowup,time:interruptedAt.time,callId:block.callId,...block.parentCallId===void 0?{}:{parentCallId:block.parentCallId},name:block.name,args:block.args,call:{name:block.name,argsRaw:block.argsRaw},callTime:block.time,content:[],isError:true,error:{name:`Interrupted`,code:`interrupted`},subCalls:children};projectedBlocks.set(block,{children,interruptionSeq,interruptionTime,value:projected});return projected}function sameReferences(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function interruption(context){const location=context.start?.location;if(location?.kind===`step`&&location.step.status===`closed`)return location.step.end;if((location?.kind===`step`||location?.kind===`turn`)&&location.turn.status===`closed`)return location.turn.end}function fallbackState$2(context){const match=context.matches.find(candidate=>candidate.event.type===`tool/result`);const root=match===void 0?void 0:rootResult(match);if(root===void 0)return void 0;let state={root,calls:emptyDispatchTree()};for(const candidate of context.matches)state=updateDispatch(state,candidate);return state}const toolDefinition={kind:`tool-call`,target:`chat`,match:event=>{if(event.type===`assistant/live-chunk`){const chunk=event.data.chunk;if(chunk.type===`block-end`&&chunk.block.type===`tool-call`)return{id:String(chunk.block.id),role:`start`};return chunk.type===`tool-call-delta`?{id:String(chunk.id),role:`start`}:null}if(event.type===`tool/call`)return{id:String(event.data.callId),role:`start`};if(event.type===`tool/result`&&isAppendSurfaceEvent(event))return{id:String(event.data.message.source.callId),role:`update`};if(event.type===`tool/ptc-dispatch-start`||event.type===`tool/ptc-dispatch`){const rootCallId=event.data.rootCallId;return typeof rootCallId===`string`&&rootCallId!==``?{id:rootCallId,role:`update`}:null}return null},start:(_context,match)=>{const state={root:void 0,calls:emptyDispatchTree()};return match.event.type===`tool/call`?{...state,root:rootCall(match)}:applyDelta(state,match)},update:(context,match)=>{if(match.event.type===`assistant/live-chunk`)return applyDelta(context.state,match);if(match.event.type===`tool/call`)return{...context.state,root:rootCall(match,context.state.root)};if(match.event.type===`tool/result`){const root=context.state.root;const result=rootResult(match,root!==void 0&&!(`kind`in root)&&root.phase===`start`?root:void 0);return result===void 0?context.state:{...context.state,root:result}}return updateDispatch(context.state,match)},publication:match=>match.event.type===`assistant/live-chunk`?`animation-frame`:`immediate`,buildViewNode:context=>{const current=context.current.get(`chat`);const state=context.state??fallbackState$2(context);if(state?.root===void 0)return current==null?null:current.visibility===`hidden`?current:{...current,visibility:`hidden`};const interruptedAt=interruption(context);const projected=projectBlock(!(`kind`in state.root)&&state.root.phase===`preparing`?preparingBlock(state.root,current?.data.root):state.root,state,interruptedAt);const anchor=context.start?.event.seq??(`kind`in state.root?state.root.seq:context.matches[0]?.event.seq??0);const visibility=!(`kind`in projected)&&projected.phase===`preparing`&&interruptedAt!==void 0?`hidden`:`visible`;const location=contextLocation(context);const data=current?.data.root===projected?current.data:{root:projected};if(current?.data===data&&current.anchorSeq===anchor&&current.visibility===visibility&&current.location===location)return current;return chatNode(context,`tool-call`,anchor,data,{visibility,location})}};function registerToolConversationNode(ctx){const match=toolDefinition.match.bind(toolDefinition);ctx.uiConversation.events.register({...toolDefinition,match:{"assistant/live-chunk":match,"tool/call":match,"tool/result":match,"tool/ptc-dispatch-start":match,"tool/ptc-dispatch":match}})}function lastStep$1(context){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return 0;return location.turn.steps.at(-1)?.step??0}function endFailure(reason){switch(reason.kind){case`error`:return reason.error;case`aborted`:return reason.reason.kind===`hook`&&reason.reason.reason===`deepseek-account/signed-out`?{message:`Stopped because you signed out of DeepSeek.`,code:`ACCOUNT_SIGNED_OUT`}:void 0;case`interrupted`:return{message:`The DSH process exited before this turn finished.`,code:`INTERRUPTED`};default:return}}function failureFrom(match){if(match.event.type!==`turn/end`)return void 0;const failure=endFailure(match.event.data.reason);if(failure===void 0)return void 0;const display=displayFailure(failure);return{seq:match.event.seq,time:match.event.time,message:display.message,...display.code===void 0?{}:{code:display.code}}}function fallbackState$1(context){const end=context.matches.find(match=>failureFrom(match)!==void 0);if(end?.event.type!==`turn/end`)return void 0;const failure=failureFrom(end);if(failure===void 0)return void 0;return{turn:end.event.data.turn,failure}}const turnErrorDefinition={kind:`turn-error`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};if(event.type===`turn/end`&&endFailure(event.data.reason)!==void 0)return{id:String(event.data.turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-error start requires turn/start`);return{turn:match.event.data.turn}},update:(context,match)=>{const failure=failureFrom(match);return failure===void 0?context.state:{...context.state,failure}},buildViewNode:context=>{const state=context.state??fallbackState$1(context);if(state?.failure===void 0)return null;const failure=state.failure;const node={kind:`turn-error`,seq:failure.seq,time:failure.time,turn:state.turn,step:lastStep$1(context),message:failure.message,...failure.code===void 0?{}:{code:failure.code}};return chatNode(context,`turn-error`,node.seq,node,{groupTree:`turn`})}};function registerTurnErrorConversationNode(ctx){ctx.uiConversation.events.register(turnErrorDefinition)}function lastStep(context){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return 0;return location.turn.steps.at(-1)?.step??0}function noticeAnchor(context,seq){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return seq;const closing=location.turn.data.get(`turn-tail`)?.closing;return closing===null||closing===void 0?seq:closing.finalNode.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.maxTokensNotice}function stateFrom(match){if(match.event.type!==`turn/end`||match.event.data.reason.kind!==`max-tokens`)return void 0;return{turn:match.event.data.turn,seq:match.event.seq,time:match.event.time}}const turnMaxTokensDefinition={kind:`turn-max-tokens`,target:`chat`,match:event=>{if(event.type===`turn/end`&&event.data.reason.kind===`max-tokens`)return{id:String(event.data.turn),role:`start`};return null},start:(_context,match)=>{const state=stateFrom(match);if(state===void 0)throw new Error(`turn-max-tokens start requires a max-tokens turn/end`);return state},update:context=>context.state,buildViewNode:context=>{const state=context.state;if(state===void 0)return null;const node={kind:`turn-max-tokens`,seq:state.seq,time:state.time,turn:state.turn,step:lastStep(context)};return chatNode(context,`turn-max-tokens`,noticeAnchor(context,state.seq),node,{groupTree:`turn`})}};function registerTurnMaxTokensConversationNode(ctx){ctx.uiConversation.events.register(turnMaxTokensDefinition)}function eventTurn(event){const data=event.data;return typeof data.turn===`number`?data.turn:void 0}function visibleChunk(chunk){if(chunk.type===`text-delta`||chunk.type===`reasoning-delta`)return chunk.text.trim()!==``;if(chunk.type===`block-start`)return chunk.blockType!==`text`&&chunk.blockType!==`reasoning`&&chunk.blockType!==`tool-call`;if(chunk.type!==`block-end`)return false;const block=chunk.block;if(block.type===`tool-call`)return false;if(block.type===`text`||block.type===`reasoning`)return block.text.trim()!==``;return true}function visibleAssistantEvent(event){if(event.type===`assistant/live-chunk`)return visibleChunk(event.data.chunk);if(event.type===`assistant/attempt`)return false;return event.type===`assistant/message`&&event.surfaceOp===`append`&&toAssistantBlocks(event.data.message.content).some(block=>{if(block.kind===`tool-call`)return false;if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true})}function processEvidence(event){if(visibleAssistantEvent(event)){if(event.type!==`assistant/live-chunk`&&event.type!==`assistant/message`&&event.type!==`assistant/attempt`)return void 0;return{kind:`assistant`,seq:event.seq,step:event.data.step}}if(event.type===`tool/call`||event.type===`tool/result`&&event.surfaceOp===`append`||event.type===`llm/retry`)return{kind:`other`,seq:event.seq}}function durableEvidenceStep(event){if(processEvidence(event)===void 0)return void 0;switch(event.type){case`assistant/message`:case`tool/call`:case`tool/result`:case`llm/retry`:return{turn:event.data.turn,step:event.data.step};default:return}}const processEvidenceDefinition={kind:`process-evidence`,match:event=>{const coordinates=durableEvidenceStep(event);return coordinates===void 0?null:{id:`${coordinates.turn}:${coordinates.step}`,role:`start`}},start:(_context,match)=>{const coordinates=durableEvidenceStep(match.event);if(coordinates===void 0)throw new Error(`process-evidence start requires durable process evidence`);return{turn:coordinates.turn}},update:context=>context.state,publication:()=>`none`};function turnLocation$1(context){const location=context.start?.location??context.matches.at(-1)?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0}function fallbackState(context){const turn=context.matches.map(match=>eventTurn(match.event)).find(candidate=>candidate!==void 0);if(turn===void 0)return void 0;let state={turn,assistantStartByStep:new Map,messageCountByStep:new Map,messageCount:0,toolCallCount:0,subagentCount:0};for(const match of context.matches)state=updateProcessState(state,match.event);return state}function isFinalAssistant(data){return data?.finalNode!==void 0}function latestAnswer(turn){const data=turn.steps.at(-1)?.data.get(`assistant-step`);if(!isFinalAssistant(data)||!hasAssistantReplyContent(data.blocks))return null;return data.blocks.some(block=>block.kind===`tool-call`)?null:data}function processSpec(state,turn){const controlAnchorSeq=state.controlAnchorSeq??turn.start?.seq;if(controlAnchorSeq===void 0)return null;const answer=latestAnswer(turn);const counts={messageCount:answer===null?state.messageCount:[...state.messageCountByStep].filter(([step])=>step<answer.step).reduce((total,[,count])=>total+count,0),toolCallCount:state.toolCallCount,subagentCount:state.subagentCount};if(answer===null)return{turn:turn.turn,controlAnchorSeq,processStartSeq:controlAnchorSeq,answerAnchorSeq:null,answerStep:null,inlineReasoning:false,...counts};const inlineReasoning=answer.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``);const earlierAssistantSeq=Math.min(...[...state.assistantStartByStep].filter(([step])=>step<answer.step).map(([,seq])=>seq));const externalProcessSeq=Math.min(state.otherStartSeq??Number.POSITIVE_INFINITY,earlierAssistantSeq);return{turn:turn.turn,controlAnchorSeq,processStartSeq:turn.start?.seq??(Number.isFinite(externalProcessSeq)?externalProcessSeq:answer.finalNode.seq),answerAnchorSeq:answer.finalNode.seq,answerStep:answer.step,inlineReasoning,...counts}}function updateProcessState(state,event){let current=state;if(event.type===`assistant/message`&&event.surfaceOp===`append`&&hasAssistantReplyContent(toAssistantBlocks(event.data.message.content))){const messageCountByStep=new Map(current.messageCountByStep);messageCountByStep.set(event.data.step,(messageCountByStep.get(event.data.step)??0)+1);current={...current,messageCountByStep,messageCount:current.messageCount+1}}if(event.type===`tool/call`){const subagent=isSubagentDelegationTool(event.data.name);current={...current,toolCallCount:current.toolCallCount+(subagent?0:1),subagentCount:current.subagentCount+(subagent?1:0)}}const evidence=processEvidence(event);if(evidence===void 0)return current;if(evidence.kind===`other`)return current.otherStartSeq===void 0?{...current,otherStartSeq:evidence.seq,controlAnchorSeq:Math.min(current.controlAnchorSeq??Number.POSITIVE_INFINITY,evidence.seq)}:current;if(current.assistantStartByStep.has(evidence.step))return current;const assistantStartByStep=new Map(current.assistantStartByStep);assistantStartByStep.set(evidence.step,evidence.seq);return{...current,assistantStartByStep,controlAnchorSeq:Math.min(current.controlAnchorSeq??Number.POSITIVE_INFINITY,evidence.seq)}}const turnProcessDefinition={kind:`turn-process`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};const turn=eventTurn(event);if(turn===void 0)return null;if(event.type===`assistant/live-chunk`||event.type===`assistant/message`||event.type===`tool/call`||event.type===`tool/result`||event.type===`llm/retry`||event.type===`step/start`||event.type===`step/end`||event.type===`turn/end`)return{id:String(turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-process start requires turn/start`);return{turn:match.event.data.turn,assistantStartByStep:new Map,messageCountByStep:new Map,messageCount:0,toolCallCount:0,subagentCount:0}},update:(context,match)=>updateProcessState(context.state,match.event),publication:match=>{if(match.event.type===`assistant/live-chunk`){const type=match.event.data.chunk.type;return type===`usage`||type===`finish`?`none`:`animation-frame`}return`immediate`},buildLocationData:(context,scope,previous)=>{if(scope!==`turn`)return null;const state=context.state??fallbackState(context);if(state===void 0)return null;const turn=turnLocation$1(context);if(turn===void 0)return null;const current=context.current.get(`chat`);const latestStep=turn.steps.at(-1);if(previous?.kind===`turn`&&previous.key===`turn-process`&&current?.kind===`turn-process`&&current.data.answerAnchorSeq===null&&current.data.controlAnchorSeq===state.controlAnchorSeq&&current.data.messageCount===state.messageCount&&current.data.toolCallCount===state.toolCallCount&&current.data.subagentCount===state.subagentCount&&turn.status!==`closed`&&latestStep?.status!==`closed`)return previous;const spec=processSpec(state,turn);if(spec===null)return null;if(previous?.kind===`turn`&&previous.turn===spec.turn&&previous.key===`turn-process`&&sameTurnProcessSpec(previous.value,spec))return previous;return{kind:`turn`,turn:turn.turn,key:`turn-process`,value:spec}},buildViewNode:context=>{const turn=turnLocation$1(context);const data=turn?.data.get(`turn-process`);if(turn===void 0||data===void 0)return null;const current=context.current.get(`chat`);const state=context.state;if(current?.kind===`turn-process`&&state!==void 0&&current.data.answerAnchorSeq===null&&current.data.controlAnchorSeq===state.controlAnchorSeq&&current.data.messageCount===state.messageCount&&current.data.toolCallCount===state.toolCallCount&&current.data.subagentCount===state.subagentCount&&turn.status!==`closed`&&turn.steps.at(-1)?.status!==`closed`&&current.location===(context.start?.location??context.matches[0]?.location))return current;return chatNode(context,`turn-process`,data.controlAnchorSeq+CHAT_SYNTHETIC_SEQ_OFFSETS.processControl,data,{groupTree:`turn`})}};function registerTurnProcess(ctx){const match=turnProcessDefinition.match.bind(turnProcessDefinition);ctx.uiConversation.events.register({...turnProcessDefinition,match:{"turn/start":match,"assistant/live-chunk":match,"assistant/message":match,"tool/call":match,"tool/result":match,"llm/retry":match,"step/start":match,"step/end":match,"turn/end":match}});const evidence=processEvidenceDefinition.match.bind(processEvidenceDefinition);ctx.uiConversation.events.register({...processEvidenceDefinition,match:{"assistant/message":evidence,"tool/call":evidence,"tool/result":evidence,"llm/retry":evidence}})}const LLM_FAILURE_CODES={ABORTED:{},ACCOUNT_QUOTA:{},ACCOUNT_SIGN_IN_REQUIRED:{},ACCOUNT_TOKEN_INVALID:{},AUTH:{},CLIENT_UPGRADE_REQUIRED:{},CONTENT_REFUSED:{},CONTEXT_WINDOW_EXCEEDED:{},DISCOVERY_FAILED:{},DISCOVERY_UNSUPPORTED:{},DUPLICATE_ADAPTER:{},DUPLICATE_DIRECTORY:{},DUPLICATE_DISCOVERY:{},EMPTY_RESPONSE:{retryChoice:true},FILES_API:{},IMAGE_OFFLOAD_REQUIRED:{},INVALID_ADAPTER:{},INVALID_CATALOG:{},INVALID_CONFIG:{},INVALID_CREDENTIAL:{},INVALID_DIRECTORY:{},INVALID_DISCOVERY:{},INVALID_MODEL_CONTEXT:{},INVALID_MODEL_INFO:{},INVALID_MODEL_MAX_TOKENS:{},INVALID_MODEL_REASONING:{},INVALID_PREPARED_CALL:{},INVALID_REPLAY_STATE:{},INVALID_REQUEST:{},INVALID_RESPONSE:{},INVALID_TOOL_ARGUMENTS:{retryChoice:true},MALFORMED_RESPONSE:{retryChoice:true},MISSING_CREDENTIAL:{},MODEL_SWITCH_COMPACTION_FAILED:{},MODEL_UNSUPPORTED:{},NO_ADAPTER:{},NO_CREDENTIAL_STORE:{},NO_DISCOVERY:{},PI_AI_ERROR:{},QUOTA:{retryChoice:true},RATE_LIMIT:{retryChoice:true},REGISTRATION_DISPOSED:{},REQUEST_EXTENSION:{},REQUEST_HEADERS:{},SERVER:{retryChoice:true},STREAM_CLOSED:{retryChoice:true},TIMEOUT:{retryChoice:true},TRANSPORT:{retryChoice:true},UNKNOWN:{},UNKNOWN_MODEL:{},UNSTORABLE_PROVIDER_ID:{},UNSUPPORTED_CONTENT:{},UNSUPPORTED_OPTION:{},UNSUPPORTED_REASONING_EFFORT:{}};const RETRY_CODE_CHOICES=Object.freeze(Object.keys(LLM_FAILURE_CODES).filter(code=>`retryChoice`in LLM_FAILURE_CODES[code]));const STRUCTURED_CONTEXT_OVERFLOW=new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]`+String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`,`i`);const TOO_LARGE_FOR_CONTEXT=new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?`+String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?`+String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`,`i`);const EXCEEDS_MODEL_CONTEXT=new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}`+String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}`+String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`,`i`);function lastAssistantStreamChunk(stream,type){for(let index=stream.length-1;index>=0;index-=1){const record=stream[index];if(record.type===`chunk`&&record.chunk.type===type)return record.chunk}}function isCount(value){return typeof value===`number`&&Number.isSafeInteger(value)&&value>=0}function safeSum(values){let total=0;for(const value of values){total+=value;if(!Number.isSafeInteger(total))return void 0}return total}function messageRoute(message){const{provider,model}=message.source;return provider.length>0&&model.length>0?{provider,model}:void 0}function streamUsage(stream){return lastAssistantStreamChunk(stream,`usage`)?.usage}function normalizeUsage(usage,route){const{inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,totalTokens}=usage;if(!isCount(inputTokens)||!isCount(outputTokens))return void 0;if(cacheReadTokens!==void 0&&!isCount(cacheReadTokens))return void 0;if(cacheWriteTokens!==void 0&&!isCount(cacheWriteTokens))return void 0;if(reasoningTokens!==void 0&&(!isCount(reasoningTokens)||reasoningTokens>outputTokens))return;const knownPrompt=safeSum([inputTokens,...cacheReadTokens===void 0?[]:[cacheReadTokens],...cacheWriteTokens===void 0?[]:[cacheWriteTokens]]);if(knownPrompt===void 0)return void 0;let exactTotal;if(totalTokens!==void 0){if(!isCount(totalTokens))return void 0;const exactPrompt=totalTokens-outputTokens;if(!isCount(exactPrompt)||exactPrompt<knownPrompt)return void 0;if(cacheReadTokens!==void 0&&cacheWriteTokens!==void 0&&exactPrompt!==knownPrompt)return;exactTotal=totalTokens}else{if(cacheReadTokens===void 0||cacheWriteTokens===void 0)return void 0;const derivedTotal=safeSum([knownPrompt,outputTokens]);if(derivedTotal===void 0)return void 0;exactTotal=derivedTotal}return{inputTokens,outputTokens,totalTokens:exactTotal,...cacheReadTokens===void 0?{}:{cacheReadTokens},...cacheWriteTokens===void 0?{}:{cacheWriteTokens},...reasoningTokens===void 0?{}:{reasoningTokens},...route===void 0?{}:{route}}}function aggregateAttempts(attempts){if(attempts.length===0)return void 0;const inputTokens=safeSum(attempts.map(attempt=>attempt.inputTokens));const outputTokens=safeSum(attempts.map(attempt=>attempt.outputTokens));const totalTokens=safeSum(attempts.map(attempt=>attempt.totalTokens));if(inputTokens===void 0||outputTokens===void 0||totalTokens===void 0)return void 0;const cacheRead=attempts.map(attempt=>attempt.cacheReadTokens);const cacheWrite=attempts.map(attempt=>attempt.cacheWriteTokens);const reasoning=attempts.map(attempt=>attempt.reasoningTokens);const cacheReadTokens=cacheRead.every(isCount)?safeSum(cacheRead):void 0;const cacheWriteTokens=cacheWrite.every(isCount)?safeSum(cacheWrite):void 0;const reasoningTokens=reasoning.every(isCount)?safeSum(reasoning):void 0;let routes;const attributed=attempts.map(attempt=>attempt.route);if(attributed.every(route=>route!==void 0)){const unique=new Map;for(const route of attributed)unique.set(`${route.provider}\0${route.model}`,route);routes=[...unique.values()]}return{uncachedInputTokens:inputTokens,outputTokens,totalTokens,...cacheReadTokens===void 0?{}:{cacheReadTokens},...cacheWriteTokens===void 0?{}:{cacheWriteTokens},...reasoningTokens===void 0?{}:{reasoningTokens},...routes===void 0?{}:{routes}}}function sameAttempt(state,turn,step){return state.turn===turn&&state.step===step}function deriveTurnTokenUsage(events){let state={kind:`idle`};const attempts=[];let turn;let sawEnd=false;let invalid=false;const closeOpen=route=>{if(state.kind!==`open`||state.sample===void 0)return false;const normalized=normalizeUsage(state.sample,route);if(normalized===void 0)return false;attempts.push(normalized);return true};for(const event of events){if(invalid)break;if(event.type===`turn/start`){if(turn!==void 0||state.kind!==`idle`)invalid=true;else turn=event.data.turn;continue}if(turn===void 0){invalid=true;break}if(event.type===`turn/end`){if(event.data.turn!==turn||state.kind!==`idle`||sawEnd)invalid=true;else sawEnd=true;continue}if(sawEnd){invalid=true;break}if(event.type===`step/start`){if(event.data.turn!==turn||state.kind!==`idle`)invalid=true;else state={kind:`open`,turn,step:event.data.step};continue}if(event.type===`llm/retry-started`){if(event.data.turn!==turn||state.kind!==`settled`||state.by!==`retry`||!sameAttempt(state,event.data.turn,event.data.step))invalid=true;else state={kind:`open`,turn,step:event.data.step};continue}if(event.type===`assistant/attempt`){if(event.data.turn!==turn||state.kind!==`open`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}const sample=streamUsage(event.data.stream)??state.sample;state={kind:`open`,turn,step:event.data.step,...sample===void 0?{}:{sample}};if(!closeOpen())invalid=true;else state={kind:`finishClosed`,turn,step:event.data.step};continue}if(event.type===`assistant/message`){if(event.data.turn!==turn||state.kind!==`open`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}const sample=event.data.usage??streamUsage(event.data.stream);if(sample!==void 0)state={...state,sample};if(!closeOpen(messageRoute(event.data.message)))invalid=true;else state={kind:`settled`,turn,step:event.data.step,by:`message`};continue}if(event.type===`llm/retry`){if(event.data.turn!==turn||state.kind===`idle`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}if(state.kind===`settled`||state.kind===`open`&&!closeOpen())invalid=true;if(!invalid)state={kind:`settled`,turn,step:event.data.step,by:`retry`};continue}if(event.type===`step/end`){if(event.data.turn!==turn||state.kind===`idle`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}if(state.kind===`open`&&!closeOpen())invalid=true;if(!invalid)state={kind:`idle`}}}return invalid||!sawEnd||state.kind!==`idle`?void 0:aggregateAttempts(attempts)}function isSessionEvent(event){return event.type!==`assistant/live-chunk`}function turnCoordinates(event){if(event.type===`assistant/message`||event.type===`assistant/attempt`||event.type===`assistant/live-chunk`||event.type===`step/start`||event.type===`step/end`)return{turn:event.data.turn,step:event.data.step};if(event.type===`llm/retry`||event.type===`llm/retry-started`)return{turn:event.data.turn,step:event.data.step}}function turnLocation(context){const location=context.start?.location??context.matches[0]?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0}function hasText(data){return data.finalNode!==void 0&&data.blocks.some(block=>block.kind===`text`&&block.text.trim()!==``)}function tailData(context){const end=context.state===void 0?context.matches.find(match=>match.event.type===`turn/end`):context.state.end;if(end?.event.type!==`turn/end`)return null;const turn=turnLocation(context);if(turn===void 0)return null;const finalized=turn.steps.map(step=>step.data.get(`assistant-step`)).filter(candidate=>candidate!==void 0).filter(candidate=>candidate.finalNode!==void 0).sort((left,right)=>left.finalNode.seq-right.finalNode.seq);const closing=finalized.findLast(hasText)??null;let latestTranscriptSeq=finalized.at(-1)?.finalNode.seq;for(const match of context.matches){const event=match.event;const candidate=event.type===`tool/call`||event.type===`tool/result`&&event.surfaceOp===`append`||event.type===`turn/end`&&event.data.reason.kind===`error`||event.type===`llm/retry`?event.seq:void 0;if(candidate!==void 0&&(latestTranscriptSeq===void 0||candidate>latestTranscriptSeq))latestTranscriptSeq=candidate}const tokenUsage=context.start?.event.type===`turn/start`?deriveTurnTokenUsage(context.matches.map(match=>match.event).filter(isSessionEvent)):void 0;return{turn:end.event.data.turn,seq:end.event.seq,time:end.event.time,closing,branchUnavailable:closing===null||latestTranscriptSeq!==closing.finalNode.seq,...tokenUsage===void 0?{}:{tokenUsage}}}const turnTailDefinition={kind:`turn-tail`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};if(event.type===`turn/end`)return{id:String(event.data.turn),role:`update`};if(event.type===`tool/call`||event.type===`tool/result`)return{id:String(event.data.turn),role:`update`};const coordinates=turnCoordinates(event);if(coordinates!==void 0)return{id:String(coordinates.turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-tail start requires turn/start`);return{turn:match.event.data.turn}},update:(context,match)=>match.event.type===`turn/end`?{...context.state,end:match}:context.state,publication:match=>match.event.type===`turn/end`?`immediate`:`none`,buildLocationData:(context,scope)=>{if(scope!==`turn`)return null;const value=tailData(context);return value===null?null:{kind:`turn`,turn:value.turn,key:`turn-tail`,value}},buildViewNode:context=>{const data=turnLocation(context)?.data.get(`turn-tail`);return data===void 0?null:chatNode(context,`turn-tail`,data.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.finalizedFollowup,data,{groupTree:`turn`})}};function registerTurnTailConversationNode(ctx){const match=turnTailDefinition.match.bind(turnTailDefinition);ctx.uiConversation.events.register({...turnTailDefinition,match:{"turn/start":match,"turn/end":match,"tool/call":match,"tool/result":match,"assistant/message":match,"assistant/attempt":match,"assistant/live-chunk":match,"step/start":match,"step/end":match,"llm/retry":match,"llm/retry-started":match}})}function activity(name){if(name===`read`)return`read`;if(name===`read_image`)return`readImage`;if(name===`grep`||name===`glob`||name.endsWith(`_inspect`))return`search`;if(name===`write`)return`write`;if(name===`edit`||name===`apply_patch`)return`edit`;if([`bash`,`pwsh`,`exec_command`,`write_stdin`].includes(name)||name.startsWith(`terminal_`))return`commands`;if(name===`run_code`||name===`cua_run_code`)return`code`;if(name===`web_search`)return`webSearch`;if(name===`web_fetch`)return`webFetch`;if(name===`subagent`||name.startsWith(`subagent_`))return`subagents`;if([`todo_write`,`create_goal`,`update_goal`,`get_goal`].includes(name))return`plan`;if(name===`ask_user_question`||name===`request_user_input`)return`questions`;return`tools`}const LIVE_TOOL_DETAIL_MAX_CHARS=160;const LIVE_TOOL_DETAIL_PREFIX_CHARS=512;const LIVE_TOOL_DETAIL_SEGMENTER=new Intl.Segmenter(void 0,{granularity:`grapheme`});const LIVE_TOOL_DETAIL_KEYS=[`title`,`description`,`objective`,`task`,`task_name`,`name`,`question`,`questions`,`prompt`,`message`,`command`,`cmd`,`queries`,`query`,`pattern`,`url`,`uri`,`file_path`,`path`,`target`,`action`,`status`];function normalizeLiveToolText(text){const normalized=text.replace(/\s+/g,` `).trim();if(normalized.length<=LIVE_TOOL_DETAIL_MAX_CHARS)return{text:normalized,truncated:false};const chars=[];for(const{segment}of LIVE_TOOL_DETAIL_SEGMENTER.segment(normalized)){if(chars.length===LIVE_TOOL_DETAIL_MAX_CHARS)return{text:`${chars.slice(0,LIVE_TOOL_DETAIL_MAX_CHARS-1).join(``).trimEnd()}…`,truncated:true};chars.push(segment)}return{text:normalized,truncated:false}}function normalizeLiveToolDetail(value){return normalizeLiveToolText(typeof value===`string`?value:Array.isArray(value)&&value.every(item=>typeof item===`string`)?value.join(`, `):``).text}function argumentTextDetail(args,key){let limit=LIVE_TOOL_DETAIL_PREFIX_CHARS;while(true){let prefix=args.textPrefix(key,limit);if(prefix===void 0)return void 0;const last=prefix.charCodeAt(prefix.length-1);if(last>=55296&&last<=56319){const extended=args.textPrefix(key,limit+1);const next=extended.charCodeAt(prefix.length);if(next>=56320&&next<=57343){prefix=extended;limit++}else if(extended.length===prefix.length&&!args.isSealed&&!args.complete(key))prefix=prefix.slice(0,-1)}const detail=normalizeLiveToolText(prefix);if(detail.truncated||!args.stringExceeds(key,limit))return detail.text;limit*=2}}function questionDetail(value){if(!Array.isArray(value))return``;for(const item of value){if(item===null||typeof item!==`object`)continue;const detail=normalizeLiveToolDetail(Reflect.get(item,`question`));if(detail!==``)return detail}return``}function liveReasoningDetail(nodes){for(let nodeIndex=nodes.length-1;nodeIndex>=0;nodeIndex--){const node=nodes[nodeIndex];if(node?.kind!==`assistant-step`||node.data.status!==`running`)continue;for(let blockIndex=node.data.blocks.length-1;blockIndex>=0;blockIndex--){const block=node.data.blocks[blockIndex];if(block?.kind!==`reasoning`)continue;const paragraphs=reasoningText(block.text).split(/\r?\n[\t ]*\r?\n/);for(let paragraphIndex=paragraphs.length-1;paragraphIndex>=0;paragraphIndex--){const detail=normalizeLiveToolDetail(paragraphs[paragraphIndex]?.replaceAll(`**`,``));if(detail!==``)return detail}}}return``}function liveToolDetail(name,args){for(const key of LIVE_TOOL_DETAIL_KEYS){if(!args.has(key))continue;const detail=key===`questions`?questionDetail(args.value(key)):argumentTextDetail(args,key)??normalizeLiveToolDetail(args.value(key));if(detail!==``)return detail}return args.closed()?normalizeLiveToolDetail(name):``}function processActivity(nodes){const counts=new Map;const seen=new Set;let running;let runningDetail=``;let runningTime=-Infinity;let preparing;const visit=tool=>{if(seen.has(tool.callId))return;seen.add(tool.callId);const call=isRunningTool(tool)?tool:tool.call;if(call!==null){const kind=activity(call.name);if(isRunningTool(tool)&&tool.time>=runningTime){running=kind;preparing=tool.phase===`preparing`;runningDetail=liveToolDetail(tool.name,tool.args);runningTime=tool.time}counts.set(kind,(counts.get(kind)??0)+1)}for(const child of tool.subCalls)visit(child)};for(const node of nodes)if(node.kind===`tool-call`)visit(node.data.root);if(running===void 0)runningDetail=liveReasoningDetail(nodes);if(nodes.length>0&&nodes.every(node=>node.kind===`context`))counts.set(`context`,nodes.length);return{counts:[...counts].map(([kind,count])=>({kind,count})).sort((a,b)=>b.count-a.count),running,runningDetail,...preparing?{preparing:true}:{}}}function turnOf(node){const location=node.location;return location.kind===`turn`||location.kind===`step`?location.turn.turn:void 0}function reasoning(node){return node.kind===`assistant-step`&&node.data.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``)}function reply(node){return node.kind===`assistant-step`&&hasAssistantReplyContent(node.data.blocks)}function sameSummary(left,right){return left.running===right.running&&left.runningDetail===right.runningDetail&&left.preparing===right.preparing&&left.counts.length===right.counts.length&&left.counts.every((value,index)=>value.kind===right.counts[index]?.kind&&value.count===right.counts[index].count)}function sameMembers(left,right){return left.length===right.length&&left.every((value,index)=>value.key===right[index]?.key&&value.groupPart===right[index].groupPart)}function structureChanged(previous,current){if(!isVisibleChatNode(current)&&(previous===void 0||!isVisibleChatNode(previous)))return false;return previous===void 0||previous.kind!==current.kind||turnOf(previous)!==turnOf(current)||isVisibleChatNode(previous)!==isVisibleChatNode(current)||previous.groupTree!==current.groupTree||reasoning(previous)!==reasoning(current)||reply(previous)!==reply(current)}function readNode(input,key){const node=input.readNode(key);if(node===void 0)throw new Error(`Chat grouping input is missing Node ${key}`);return node}var ProcessGroup=class{key;turn;members;nodes=[];snapshot;constructor(key,turn,members){this.key=key;this.turn=turn;this.members=members;this.snapshot={key,members,data:{turn,closed:false,summary:{counts:[],running:void 0,runningDetail:``}}}}refresh(input,closed){const nodes=this.members.map(member=>readNode(input,member.key));const unchanged=nodes.length===this.nodes.length&&nodes.every((node,index)=>node===this.nodes[index]);const previous=this.snapshot.data;const activity=unchanged&&previous.closed===closed?previous.summary:processActivity(nodes);const summary=closed?{counts:activity.counts,running:void 0,runningDetail:``}:activity;this.nodes=nodes;if(previous.closed!==closed||!sameSummary(previous.summary,summary))this.snapshot={key:this.key,members:this.members,data:{turn:this.turn,closed,summary}}}};var TurnGroups=class{turn;groups=new Map;membership=new Map;roots=new Map;constructor(turn){this.turn=turn}references(key){return this.roots.get(key)??[]}snapshots(){return[...this.groups.values()].map(group=>group.snapshot)}refresh(input,changed){const dirty=new Set;for(const node of changed){const group=this.membership.get(node);if(group!==void 0)dirty.add(group)}const ended=input.timeline.turns.get(this.turn)?.status===`closed`;if(ended){for(const group of this.groups.values())if(!group.snapshot.data.closed)dirty.add(group.key)}const upserts=[];for(const key of dirty){const group=this.groups.get(key);const previous=group.snapshot;group.refresh(input,previous.data.closed||ended);if(group.snapshot!==previous)upserts.push(group.snapshot)}return upserts}rebuild(input,added){const roots=new Map;const groups=new Map;const membership=new Map;let pending=[];const upserts=[];const emit=(key,entry)=>{roots.set(key,[...roots.get(key)??[],entry])};const flush=closed=>{const first=pending[0];if(first===void 0)return;const key=this.extendedGroup(pending,added)?.key??brandString(JSON.stringify([`process`,first.key,first.groupPart??null]));const previous=this.groups.get(key);const before=previous?.snapshot;const group=previous!==void 0&&sameMembers(previous.members,pending)?previous:new ProcessGroup(key,this.turn,pending);group.refresh(input,closed||input.timeline.turns.get(this.turn)?.status===`closed`);groups.set(group.key,group);emit(first.key,{kind:`group`,key:group.key});for(const member of pending)membership.set(member.key,group.key);if(group.snapshot!==before)upserts.push(group.snapshot);pending=[]};let previous;let followed=false;for(const key of input.readTurn(this.turn)){const position=readPosition(input,key);if(previous!==void 0&&position.previous!==previous)flush(true);previous=key;followed=position.next!==void 0;const node=readNode(input,key);if(isAtOrOutside(node,`process`)){flush(true);emit(key,{kind:`node`,key})}else if(node.kind===`assistant-step`){if(reasoning(node))pending.push({kind:`node`,key,groupPart:`reasoning`});if(reply(node)){flush(true);emit(key,{kind:`node`,key,groupPart:`response`})}}else pending.push({kind:`node`,key})}flush(followed);const removes=[...this.groups.keys()].filter(key=>!groups.has(key));this.groups=groups;this.membership=membership;this.roots=roots;return{upserts,removes}}extendedGroup(members,added){const offset=members.findIndex(member=>!added.has(member.key));const first=members[offset];if(first===void 0)return void 0;const key=this.membership.get(first.key);const previous=key===void 0?void 0:this.groups.get(key);if(previous===void 0||offset+previous.members.length>members.length)return void 0;for(let index=0;index<previous.members.length;index++){const before=previous.members[index];const after=members[offset+index];if(before.key!==after.key||before.groupPart!==after.groupPart)return void 0}for(let index=offset+previous.members.length;index<members.length;index++)if(!added.has(members[index].key))return void 0;return previous}};function readPosition(input,key){const position=input.readPosition(key);if(position===void 0)throw new Error(`Chat grouping order is missing position for Node ${key}`);return position}var ProcessState=class{turns=new Map;order=[];pending=null;accept(input){if(input.kind===`replace`){const previousKeys=new Set(this.order);const added=new Set(input.order.filter(key=>!previousKeys.has(key)));const turns=new Map;for(const key of input.order){const turn=readPosition(input,key).turn;if(turn===void 0||turns.has(turn))continue;const groups=this.turns.get(turn)??new TurnGroups(turn);groups.rebuild(input,added);turns.set(turn,groups)}this.turns=turns;this.order=input.order;this.pending={entries:this.rootEntries(input),groups:{kind:`replace`,snapshots:[...turns.values()].flatMap(turn=>turn.snapshots())}};return}const regroup=new Set(input.changedTurnOrders);const added=new Set;const changed=new Map;const touch=turn=>{let keys=changed.get(turn);if(keys===void 0){keys=new Set;changed.set(turn,keys)}return keys};for(const change of input.changes){const before=change.previous;const after=change.current;const turn=turnOf(after);if(before===void 0||!isVisibleChatNode(before))added.add(after.key);if(structureChanged(before,after)){const previousTurn=before===void 0?void 0:turnOf(before);if(previousTurn!==void 0)regroup.add(previousTurn);if(turn!==void 0)regroup.add(turn)}if(turn!==void 0)touch(turn).add(after.key)}for(const turn of input.changedTurns)touch(turn);const upserts=[];const removes=[];for(const turn of regroup){const groups=this.turns.get(turn)??new TurnGroups(turn);const update=groups.rebuild(input,added);upserts.push(...update.upserts);removes.push(...update.removes);if(input.readTurn(turn).length===0)this.turns.delete(turn);else this.turns.set(turn,groups)}for(const[turn,keys]of changed)if(!regroup.has(turn))upserts.push(...this.turns.get(turn)?.refresh(input,keys)??[]);const reordered=input.order!==this.order||regroup.size>0;this.order=input.order;const installed=new Set(upserts.map(group=>group.key));this.pending=reordered||upserts.length>0||removes.length>0?{...reordered?{entries:this.rootEntries(input)}:{},groups:{kind:`apply`,upserts,removes:removes.filter(key=>!installed.has(key))}}:null}rootEntries(input){return input.order.flatMap(key=>{const turn=readPosition(input,key).turn;if(turn===void 0)return[{kind:`node`,key}];const groups=this.turns.get(turn);if(groups===void 0)throw new Error(`Chat grouping order is missing Turn ${turn}`);return groups.references(key)})}output(){return this.pending}};const processGroupDefinition={kind:`process-groups`,target:`chat`,create:()=>new ProcessState,update:(context,input)=>{context.state.accept(input);return context.state},buildGroups:context=>context.state.output()};function registerConversationNodes(ctx){registerInboxConversationNodes(ctx);registerMessageConversationNode(ctx);registerRequestPromptConversationNode(ctx);registerAssistantConversationNode(ctx);registerTurnProcess(ctx);registerToolConversationNode(ctx);registerCommandConversationNode(ctx);registerCompactionConversationNode(ctx);registerInheritedHistoryConversationNode(ctx);registerRetryConversationNode(ctx);registerTurnErrorConversationNode(ctx);registerTurnMaxTokensConversationNode(ctx);registerTurnTailConversationNode(ctx);registerUnknownConversationFallback(ctx);registerChatConversationView(ctx);ctx.uiConversation.groups.register(processGroupDefinition)}function MathFenceLayer({code,streaming,children}){return streaming?children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceMathBlock,{code})}function DiffFenceLayer({lang,code,streaming,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceCodeBlock,{lang,code,streaming,labels:(0,react.useMemo)(()=>markdownLabels(t).code,[t]),diff:true})}function registerFenceLayers(ctx){ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`math`,id:`@deepseek-ai/dsh-client-ui-chat/fence/math`},MathFenceLayer));ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`diff`,id:`@deepseek-ai/dsh-client-ui-chat/fence/diff`,locale:NS},DiffFenceLayer));ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`patch`,id:`@deepseek-ai/dsh-client-ui-chat/fence/diff`,locale:NS},DiffFenceLayer))}function QuotaNoticeHost({useNotice,dismissNotice,keepNoticeOpen,renderSlotChain,t}){const notice=useNotice(current=>current);if(notice===null)return null;const owner={code:notice.code,message:t(`message.failure.quota`),dismiss:dismissNotice,keepOpen:keepNoticeOpen};return(0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlotChain(`shell.quota-notice`,owner,{fallback:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Toast,{text:owner.message,icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWarningOutlineRegular,{size:18}),onDone:dismissNotice})})},`quota-notice-${String(notice.seq)}`)}function isNullable(value){return value===null||value===void 0}function isPlainObject(data){return data&&typeof data===`object`&&!Array.isArray(data)}function filterKeys(object,filter){return Object.fromEntries(Object.entries(object).filter(([key,value])=>filter(key,value)))}function mapValues(object,transform){return Object.fromEntries(Object.entries(object).map(([key,value])=>[key,transform(value,key)]))}function pick(source,keys,forced){if(!keys)return{...source};const result={};for(const key of keys)if(forced||source[key]!==void 0)result[key]=source[key];return result}const write=Symbol.for(`cosmokit.volatile.write`);function snapshot(value,ancestors=new Set){if(typeof value===`function`)throw new TypeError(`volatile config cannot contain functions`);if(value===null||typeof value!==`object`)return value;if(ancestors.has(value))throw new TypeError(`volatile config cannot contain cycles`);ancestors.add(value);try{if(Array.isArray(value))return Object.freeze(value.map(item=>snapshot(item,ancestors)));if(Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new TypeError(`volatile config objects must be plain objects or arrays`);return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,item])=>[key,snapshot(item,ancestors)])))}finally{ancestors.delete(value)}}function createVolatile(value){let current=snapshot(value);return Object.freeze({get:()=>current,[write]:value=>{current=value}})}function isVolatile(value){return typeof value===`object`&&value!==null&&write in value}function is(type,value){if(arguments.length===1)return value=>is(type,value);return type in globalThis&&value instanceof globalThis[type]||Object.prototype.toString.call(value).slice(8,-1)===type}function isArrayBufferLike(value){return is(`ArrayBuffer`,value)||is(`SharedArrayBuffer`,value)}function isArrayBufferSource(value){return isArrayBufferLike(value)||ArrayBuffer.isView(value)}var Binary;(function(Binary){Binary.is=isArrayBufferLike;Binary.isSource=isArrayBufferSource;function fromSource(source){if(ArrayBuffer.isView(source))return source.buffer.slice(source.byteOffset,source.byteOffset+source.byteLength);else return source}Binary.fromSource=fromSource;function toBase64(source){source=fromSource(source);if(typeof Buffer!==`undefined`)return Buffer.from(source).toString(`base64`);let binary=``;const bytes=new Uint8Array(source);for(let i=0;i<bytes.byteLength;i++)binary+=String.fromCharCode(bytes[i]);return btoa(binary)}Binary.toBase64=toBase64;function fromBase64(source){if(typeof Buffer!==`undefined`)return fromSource(Buffer.from(source,`base64`));return Uint8Array.from(atob(source),c=>c.charCodeAt(0))}Binary.fromBase64=fromBase64;function toHex(source){source=fromSource(source);if(typeof Buffer!==`undefined`)return Buffer.from(source).toString(`hex`);return Array.from(new Uint8Array(source),byte=>byte.toString(16).padStart(2,`0`)).join(``)}Binary.toHex=toHex;function fromHex(source){if(typeof Buffer!==`undefined`)return fromSource(Buffer.from(source,`hex`));const hex=source.length%2===0?source:source.slice(0,source.length-1);const buffer=[];for(let i=0;i<hex.length;i+=2)buffer.push(parseInt(`${hex[i]}${hex[i+1]}`,16));return Uint8Array.from(buffer).buffer}Binary.fromHex=fromHex})(Binary||(Binary={}));const base64ToArrayBuffer=Binary.fromBase64;const arrayBufferToBase64=Binary.toBase64;const hexToArrayBuffer=Binary.fromHex;const arrayBufferToHex=Binary.toHex;function clone(source,refs=new Map){if(!source||typeof source!==`object`)return source;if(is(`Date`,source))return new Date(source.valueOf());if(is(`RegExp`,source))return new RegExp(source.source,source.flags);if(isArrayBufferLike(source))return source.slice(0);if(ArrayBuffer.isView(source))return source.buffer.slice(source.byteOffset,source.byteOffset+source.byteLength);const cached=refs.get(source);if(cached)return cached;if(Array.isArray(source)){const result=[];refs.set(source,result);source.forEach((value,index)=>{result[index]=Reflect.apply(clone,null,[value,refs])});return result}const result=Object.create(Object.getPrototypeOf(source));refs.set(source,result);for(const key of Reflect.ownKeys(source)){const descriptor={...Reflect.getOwnPropertyDescriptor(source,key)};if(`value`in descriptor)descriptor.value=Reflect.apply(clone,null,[descriptor.value,refs]);Reflect.defineProperty(result,key,descriptor)}return result}function deepEqual(a,b,strict){const ancestors=new Set;function compare(a,b){if(a===b)return true;if(isVolatile(a)||isVolatile(b))return isVolatile(a)&&isVolatile(b);if(!strict&&isNullable(a)&&isNullable(b))return true;if(typeof a!==typeof b||typeof a!==`object`||!a||!b)return false;if(ancestors.has(a))return false;function check(test,then){return test(a)?test(b)?then(a,b):false:test(b)?false:void 0}ancestors.add(a);try{return check(Array.isArray,(a,b)=>{if(a.length!==b.length)return false;for(let index=0;index<a.length;index++)if(!compare(a[index],b[index]))return false;return true})??check(is(`Date`),(a,b)=>a.valueOf()===b.valueOf())??check(is(`URL`),(a,b)=>a.href===b.href)??check(is(`RegExp`),(a,b)=>a.source===b.source&&a.flags===b.flags)??check(isArrayBufferLike,(a,b)=>{if(a.byteLength!==b.byteLength)return false;const viewA=new Uint8Array(a);const viewB=new Uint8Array(b);for(let i=0;i<viewA.length;i++)if(viewA[i]!==viewB[i])return false;return true})??((!strict||[a,b].every(value=>Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null))&&Object.keys({...a,...b}).every(key=>compare(a[key],b[key])))}finally{ancestors.delete(a)}}return compare(a,b)}var Time;(function(Time){Time.millisecond=1;Time.second=1e3;Time.minute=Time.second*60;Time.hour=Time.minute*60;Time.day=Time.hour*24;Time.week=Time.day*7;let timezoneOffset=new Date().getTimezoneOffset();function setTimezoneOffset(offset){timezoneOffset=offset}Time.setTimezoneOffset=setTimezoneOffset;function getTimezoneOffset(){return timezoneOffset}Time.getTimezoneOffset=getTimezoneOffset;function getDateNumber(date=new Date,offset){if(typeof date===`number`)date=new Date(date);if(offset===void 0)offset=timezoneOffset;return Math.floor((date.valueOf()/Time.minute-offset)/1440)}Time.getDateNumber=getDateNumber;function fromDateNumber(value,offset){const date=new Date(value*Time.day);if(offset===void 0)offset=timezoneOffset;return new Date(+date+offset*Time.minute)}Time.fromDateNumber=fromDateNumber;const numeric=/\d+(?:\.\d+)?/.source;const timeRegExp=new RegExp(`^${[`w(?:eek(?:s)?)?`,`d(?:ay(?:s)?)?`,`h(?:our(?:s)?)?`,`m(?:in(?:ute)?(?:s)?)?`,`s(?:ec(?:ond)?(?:s)?)?`].map(unit=>`(${numeric}${unit})?`).join(``)}$`);function parseTime(source){const capture=timeRegExp.exec(source);if(!capture)return 0;return(parseFloat(capture[1])*Time.week||0)+(parseFloat(capture[2])*Time.day||0)+(parseFloat(capture[3])*Time.hour||0)+(parseFloat(capture[4])*Time.minute||0)+(parseFloat(capture[5])*Time.second||0)}Time.parseTime=parseTime;function parseDate(date){const parsed=parseTime(date);if(parsed)date=Date.now()+parsed;else if(/^\d{1,2}(:\d{1,2}){1,2}$/.test(date))date=`${new Date().toLocaleDateString()}-${date}`;else if(/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date))date=`${new Date().getFullYear()}-${date}`;return date?new Date(date):new Date}Time.parseDate=parseDate;function format(ms){const abs=Math.abs(ms);if(abs>=Time.day-Time.hour/2)return Math.round(ms/Time.day)+`d`;else if(abs>=Time.hour-Time.minute/2)return Math.round(ms/Time.hour)+`h`;else if(abs>=Time.minute-Time.second/2)return Math.round(ms/Time.minute)+`m`;else if(abs>=Time.second)return Math.round(ms/Time.second)+`s`;return ms+`ms`}Time.format=format;function toDigits(source,length=2){return source.toString().padStart(length,`0`)}Time.toDigits=toDigits;function template(template,time=new Date){return template.replace(`yyyy`,time.getFullYear().toString()).replace(`yy`,time.getFullYear().toString().slice(2)).replace(`MM`,toDigits(time.getMonth()+1)).replace(`dd`,toDigits(time.getDate())).replace(`hh`,toDigits(time.getHours())).replace(`mm`,toDigits(time.getMinutes())).replace(`ss`,toDigits(time.getSeconds())).replace(`SSS`,toDigits(time.getMilliseconds(),3))}Time.template=template})(Time||(Time={}));const kSchema=Symbol.for(`schemastery`);const kValidationError=Symbol.for(`ValidationError`);globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;var ValidationError=class extends TypeError{options;name=`ValidationError`;constructor(message,options){let prefix=`$`;for(const segment of options.path||[])if(typeof segment===`string`)prefix+=`.`+segment;else if(typeof segment===`number`)prefix+=`[`+segment+`]`;else if(typeof segment===`symbol`)prefix+=`[Symbol(${segment.toString()})]`;if(prefix.startsWith(`.`))prefix=prefix.slice(1);super((prefix===`$`?``:`${prefix} `)+message);this.options=options}static is(error){return!!error?.[kValidationError]}};Object.defineProperty(ValidationError.prototype,kValidationError,{value:true});const Schema=function(options){const schema=function(data,options={}){return Schema.resolve(data,schema,options)[0]};if(options.refs){const refs=mapValues(options.refs,options=>new Schema(options));const getRef=uid=>refs[uid];for(const key in refs){const options=refs[key];options.sKey=getRef(options.sKey);options.inner=getRef(options.inner);options.list=options.list&&options.list.map(getRef);options.dict=options.dict&&mapValues(options.dict,getRef)}return refs[options.uid]}Object.assign(schema,options);if(typeof schema.callback===`string`)try{schema.callback=new Function(`return `+schema.callback)()}catch{}Object.defineProperty(schema,"uid",{value:globalThis.__schemastery_index__++});Object.setPrototypeOf(schema,Schema.prototype);schema.meta||={};schema.toString=schema.toString.bind(schema);return schema};Schema.prototype=Object.create(Function.prototype);Schema.prototype[kSchema]=true;Object.defineProperty(Schema.prototype,"~standard",{get(){return{version:1,vendor:`schemastery`,validate:value=>{try{return{value:Schema.resolve(value,this,{})[0]}}catch(error){if(ValidationError.is(error))return{issues:[{message:error.message,path:error.options.path}]};throw error}}}}});Schema.ValidationError=ValidationError;Schema.prototype.toJSON=function toJSON(){if(globalThis.__schemastery_refs__){globalThis.__schemastery_refs__[this.uid]??=JSON.parse(JSON.stringify({...this}));return this.uid}globalThis.__schemastery_refs__={[this.uid]:{...this}};globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));const result={uid:this.uid,refs:globalThis.__schemastery_refs__};globalThis.__schemastery_refs__=void 0;return result};Schema.prototype.set=function set(key,value){this.dict[key]=value;return this};Schema.prototype.push=function push(value){this.list.push(value);return this};function mergeDesc(original,messages){const result=typeof original===`string`?{"":original}:{...original};for(const locale in messages){const value=messages[locale];if(value?.$description||value?.$desc)result[locale]=value.$description||value.$desc;else if(typeof value===`string`)result[locale]=value}return result}function getInner(value){return value?.$value??value?.$inner}function extractKeys(data){return filterKeys(data??{},key=>!key.startsWith(`$`))}Schema.prototype.i18n=function i18n(messages){const schema=Schema(this);const desc=mergeDesc(schema.meta.description,messages);if(Object.keys(desc).length)schema.meta.description=desc;if(schema.dict)schema.dict=mapValues(schema.dict,(inner,key)=>{return inner.i18n(mapValues(messages,data=>getInner(data)?.[key]??data?.[key]))});if(schema.list)schema.list=schema.list.map((inner,index)=>{return inner.i18n(mapValues(messages,(data={})=>{if(Array.isArray(getInner(data)))return getInner(data)[index];if(Array.isArray(data))return data[index];return extractKeys(data)}))});if(schema.inner)schema.inner=schema.inner.i18n(mapValues(messages,data=>{if(getInner(data))return getInner(data);return extractKeys(data)}));if(schema.sKey)schema.sKey=schema.sKey.i18n(mapValues(messages,data=>data?.$key));return schema};Schema.prototype.extra=function extra(key,value){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema};for(const key of[`required`,`disabled`,`collapse`,`hidden`,`loose`])Object.assign(Schema.prototype,{[key](value=true){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema}});Schema.prototype.deprecated=function deprecated(){const schema=Schema(this);schema.meta.badges||=[];schema.meta.badges.push({text:`deprecated`,type:`danger`});return schema};Schema.prototype.experimental=function experimental(){const schema=Schema(this);schema.meta.badges||=[];schema.meta.badges.push({text:`experimental`,type:`warning`});return schema};Schema.prototype.pattern=function pattern(regexp){const schema=Schema(this);const pattern=pick(regexp,[`source`,`flags`]);schema.meta={...schema.meta,pattern};return schema};Schema.prototype.simplify=function simplify(value){if(isVolatile(value))value=value.get();if(deepEqual(value,this.meta.default,this.type===`dict`))return null;if(isNullable(value))return value;if(this.type===`object`||this.type===`dict`){const result={};for(const key in value){const item=(this.type===`object`?this.dict[key]:this.inner)?.simplify(value[key]);if(this.type===`dict`||!isNullable(item))result[key]=item}if(deepEqual(result,this.meta.default,this.type===`dict`))return null;return result}else if(this.type===`array`||this.type===`tuple`){const result=[];value.forEach((value,index)=>{const schema=this.type===`array`?this.inner:this.list[index];const item=schema?schema.simplify(value):value;result.push(item)});return result}else if(this.type===`intersect`){const result={};for(const item of this.list)Object.assign(result,item.simplify(value));return result}else if(this.type===`union`)for(const schema of this.list)try{Schema.resolve(value,schema,{});return schema.simplify(value)}catch{}return value};Schema.prototype.toString=function toString(inline){return formatters[this.type]?.(this,inline)??`Schema<${this.type}>`};Schema.prototype.role=function role(role,extra){const schema=Schema(this);schema.meta={...schema.meta,role,extra};return schema};for(const key of[`default`,`link`,`comment`,`description`,`max`,`min`,`step`])Object.assign(Schema.prototype,{[key](value){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema}});Schema.prototype.volatile=function volatile(){if(this.meta.volatile)throw new TypeError(`volatile schema is already wrapped`);return this.extra(`volatile`,true)};const resolvers={};const checkedVolatile=Symbol(`checked-volatile-schema`);function validateVolatileSchema(schema,path=[],blocked=false,seen=new Map){const states=seen.get(schema)??new Set;if(states.has(blocked))return;states.add(blocked);seen.set(schema,states);if(schema.meta?.volatile&&blocked)throw new ValidationError(`volatile fields require a fixed object path without an enclosing volatile field`,{path});const nested=blocked||!!schema.meta?.volatile;if(schema.dict)for(const[key,child]of Object.entries(schema.dict))validateVolatileSchema(child,[...path,key],nested,seen);if(schema.sKey)validateVolatileSchema(schema.sKey,[...path,`<key>`],true,seen);if(schema.inner&&(schema.type!==`lazy`||schema.inner[kSchema]))validateVolatileSchema(schema.inner,[...path,`*`],true,seen);if(schema.list)for(let index=0;index<schema.list.length;index++)validateVolatileSchema(schema.list[index],[...path,String(index)],true,seen)}Schema.extend=function extend(type,resolve){resolvers[type]=resolve};Schema.resolve=function resolve(data,schema,options={},strict=false){if(!schema)return[data];if(!options[checkedVolatile]){validateVolatileSchema(schema,options.path);options={...options,[checkedVolatile]:true}}if(schema.meta?.volatile){const inner=Schema(schema);inner.meta={...schema.meta,volatile:false};const[value,adapted]=Schema.resolve(data,inner,options,strict);try{return[createVolatile(value),adapted]}catch(error){throw new ValidationError(error instanceof Error?error.message:String(error),options)}}if(options.ignore?.(data,schema))return[data];if(isNullable(data)&&schema.type!==`lazy`){if(schema.meta.required)throw new ValidationError(`missing required value`,options);let current=schema;let fallback=schema.meta.default;while(current?.type===`intersect`&&isNullable(fallback)){current=current.list[0];fallback=current?.meta.default}if(isNullable(fallback))return[data];data=clone(fallback)}const callback=resolvers[schema.type];if(!callback)throw new ValidationError(`unsupported type "${schema.type}"`,options);try{return callback(data,schema,options,strict)}catch(error){if(!schema.meta.loose)throw error;return[schema.meta.default]}};Schema.from=function from(source){if(isNullable(source))return Schema.any();else if([`string`,`number`,`boolean`].includes(typeof source))return Schema.const(source).required();else if(source[kSchema])return source;else if(typeof source===`function`)switch(source){case String:return Schema.string().required();case Number:return Schema.number().required();case Boolean:return Schema.boolean().required();case Function:return Schema.function().required();default:return Schema.is(source).required()}else throw new TypeError(`cannot infer schema from ${source}`)};Schema.lazy=function lazy(builder){const toJSON=()=>{if(!schema.inner[kSchema]){schema.inner=schema.builder();schema.inner.meta={...schema.meta,...schema.inner.meta}}return schema.inner.toJSON()};const schema=new Schema({type:`lazy`,builder,inner:{toJSON}});return schema};Schema.natural=function natural(){return Schema.number().step(1).min(0)};Schema.percent=function percent(){return Schema.number().step(.01).min(0).max(1).role(`slider`)};Schema.date=function date(){return Schema.union([Schema.is(Date),Schema.transform(Schema.string().role(`datetime`),(value,options)=>{const date=new Date(value);if(isNaN(+date))throw new ValidationError(`invalid date "${value}"`,options);return date},true)])};Schema.regExp=function regExp(flag=``){return Schema.union([Schema.is(RegExp),Schema.transform(Schema.string().role(`regexp`,{flag}),(value,options)=>{try{return new RegExp(value,flag)}catch(e){throw new ValidationError(e.message,options)}},true)])};Schema.arrayBuffer=function arrayBuffer(encoding){return Schema.union([Schema.is(ArrayBuffer),Schema.is(SharedArrayBuffer),Schema.transform(Schema.any(),(value,options)=>{if(Binary.isSource(value))return Binary.fromSource(value);throw new ValidationError(`expected ArrayBufferSource but got ${value}`,options)},true),...encoding?[Schema.transform(Schema.string(),(value,options)=>{try{return encoding===`base64`?Binary.fromBase64(value):Binary.fromHex(value)}catch(e){throw new ValidationError(e.message,options)}},true)]:[]])};Schema.extend(`lazy`,(data,schema,options,strict)=>{if(!schema.inner[kSchema]){schema.inner=schema.builder();schema.inner.meta={...schema.meta,...schema.inner.meta};validateVolatileSchema(schema.inner,options.path,true)}return Schema.resolve(data,schema.inner,options,strict)});Schema.extend(`any`,data=>{return[data]});Schema.extend(`never`,(data,_,options)=>{throw new ValidationError(`expected nullable but got ${data}`,options)});Schema.extend(`const`,(data,{value},options)=>{if(deepEqual(data,value))return[value];throw new ValidationError(`expected ${value} but got ${data}`,options)});function checkWithinRange(data,meta,description,options,skipMin=false){const{max=Infinity,min=-Infinity}=meta;if(data>max)throw new ValidationError(`expected ${description} <= ${max} but got ${data}`,options);if(data<min&&!skipMin)throw new ValidationError(`expected ${description} >= ${min} but got ${data}`,options)}Schema.extend(`string`,(data,{meta},options)=>{if(typeof data!==`string`)throw new ValidationError(`expected string but got ${data}`,options);if(meta.pattern){const regexp=new RegExp(meta.pattern.source,meta.pattern.flags);if(!regexp.test(data))throw new ValidationError(`expect string to match regexp ${regexp}`,options)}checkWithinRange(data.length,meta,`string length`,options);return[data]});function decimalShift(data,digits){const str=data.toString();if(str.includes(`e`))return data*Math.pow(10,digits);const index=str.indexOf(`.`);if(index===-1)return data*Math.pow(10,digits);const frac=str.slice(index+1);const integer=str.slice(0,index);if(frac.length<=digits)return+(integer+frac.padEnd(digits,`0`));return+(integer+frac.slice(0,digits)+`.`+frac.slice(digits))}function isMultipleOf(data,min,step){step=Math.abs(step);if(!/^\d+\.\d+$/.test(step.toString()))return(data-min)%step===0;const index=step.toString().indexOf(`.`);const digits=step.toString().slice(index+1).length;return Math.abs(decimalShift(data,digits)-decimalShift(min,digits))%decimalShift(step,digits)===0}Schema.extend(`number`,(data,{meta},options)=>{if(typeof data!==`number`)throw new ValidationError(`expected number but got ${data}`,options);checkWithinRange(data,meta,`number`,options);const{step}=meta;if(step&&!isMultipleOf(data,meta.min??0,step))throw new ValidationError(`expected number multiple of ${step} but got ${data}`,options);return[data]});Schema.extend(`boolean`,(data,_,options)=>{if(typeof data===`boolean`)return[data];throw new ValidationError(`expected boolean but got ${data}`,options)});Schema.extend(`bitset`,(data,{bits,meta},options)=>{let value=0,keys=[];if(typeof data===`number`){value=data;for(const key in bits)if(data&bits[key])keys.push(key)}else if(Array.isArray(data)){keys=data;for(const key of keys){if(typeof key!==`string`)throw new ValidationError(`expected string but got ${key}`,options);if(key in bits)value|=bits[key]}}else throw new ValidationError(`expected number or array but got ${data}`,options);if(value===meta.default)return[value];return[value,keys]});Schema.extend(`function`,(data,_,options)=>{if(typeof data===`function`)return[data];throw new ValidationError(`expected function but got ${data}`,options)});Schema.extend(`is`,(data,{constructor},options)=>{if(typeof constructor===`function`){if(data instanceof constructor)return[data];throw new ValidationError(`expected ${constructor.name} but got ${data}`,options)}else{if(isNullable(data))throw new ValidationError(`expected ${constructor} but got ${data}`,options);let prototype=Object.getPrototypeOf(data);while(prototype){if(prototype.constructor?.name===constructor)return[data];prototype=Object.getPrototypeOf(prototype)}throw new ValidationError(`expected ${constructor} but got ${data}`,options)}});function property(data,key,schema,options){try{const[value,adapted]=Schema.resolve(data[key],schema,{...options,path:[...options.path||[],key]});if(adapted!==void 0)data[key]=adapted;return value}catch(e){if(!options?.autofix)throw e;delete data[key];return schema.meta.volatile?createVolatile(schema.meta.default):schema.meta.default}}Schema.extend(`array`,(data,{inner,meta},options)=>{if(!Array.isArray(data))throw new ValidationError(`expected array but got ${data}`,options);checkWithinRange(data.length,meta,`array length`,options,!isNullable(inner.meta.default));return[data.map((_,index)=>property(data,index,inner,options))]});Schema.extend(`dict`,(data,{inner,sKey},options,strict)=>{if(!isPlainObject(data))throw new ValidationError(`expected object but got ${data}`,options);const result={};for(const key in data){let rKey;try{rKey=Schema.resolve(key,sKey,options)[0]}catch(error){if(strict)continue;throw error}result[rKey]=property(data,key,inner,options);data[rKey]=data[key];if(key!==rKey)delete data[key]}return[result]});Schema.extend(`tuple`,(data,{list},options,strict)=>{if(!Array.isArray(data))throw new ValidationError(`expected array but got ${data}`,options);const result=list.map((inner,index)=>property(data,index,inner,options));if(strict)return[result];result.push(...data.slice(list.length));return[result]});function merge(result,data){for(const key in data){if(key in result)continue;result[key]=data[key]}}Schema.extend(`object`,(data,{dict},options,strict)=>{if(!isPlainObject(data))throw new ValidationError(`expected object but got ${data}`,options);const result={};for(const key in dict){const value=property(data,key,dict[key],options);if(!isNullable(value)||key in data)result[key]=value}if(!strict)merge(result,data);return[result]});Schema.extend(`union`,(data,{list,toString},options,strict)=>{const messages=[];for(const inner of list)try{return Schema.resolve(data,inner,options,strict)}catch(error){messages.push(error)}throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options)});Schema.extend(`intersect`,(data,{list,toString},options,strict)=>{if(!list.length)return[data];let result;for(const inner of list){const value=Schema.resolve(data,inner,options,true)[0];if(isNullable(value))continue;if(isNullable(result))result=value;else if(typeof result!==typeof value)throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options);else if(typeof value===`object`)merge(result??={},value);else if(result!==value)throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options)}if(!strict&&isPlainObject(data))merge(result,data);return[result]});Schema.extend(`transform`,(data,{inner,callback,preserve},options)=>{const[result,adapted=data]=Schema.resolve(data,inner,options,true);if(preserve)return[callback(result)];else return[callback(result),callback(adapted)]});const formatters={};function defineMethod(name,keys,format){formatters[name]=format;Object.assign(Schema,{[name](...args){const schema=new Schema({type:name});keys.forEach((key,index)=>{switch(key){case`sKey`:schema.sKey=args[index]??Schema.string();break;case`inner`:schema.inner=Schema.from(args[index]);break;case`list`:schema.list=args[index].map(Schema.from);break;case`dict`:schema.dict=mapValues(args[index],Schema.from);break;case`bits`:schema.bits={};for(const key in args[index]){if(typeof args[index][key]!==`number`)continue;schema.bits[key]=args[index][key]}break;case`callback`:{const callback=schema.callback=args[index];callback[`toJSON`]||=()=>callback.toString();break}case`constructor`:{const constructor=schema.constructor=args[index];if(typeof constructor===`function`)constructor[`toJSON`]||=()=>constructor[`name`];break}default:schema[key]=args[index]}});if(name===`object`||name===`dict`)schema.meta.default={};else if(name===`array`||name===`tuple`)schema.meta.default=[];else if(name===`bitset`)schema.meta.default=0;return schema}})}defineMethod(`is`,[`constructor`],({constructor})=>{if(typeof constructor===`function`)return constructor.name;else return constructor});defineMethod(`any`,[],()=>`any`);defineMethod(`never`,[],()=>`never`);defineMethod(`const`,[`value`],({value})=>typeof value===`string`?JSON.stringify(value):value);defineMethod(`string`,[],()=>`string`);defineMethod(`number`,[],()=>`number`);defineMethod(`boolean`,[],()=>`boolean`);defineMethod(`bitset`,[`bits`],()=>`bitset`);defineMethod(`function`,[],()=>`function`);defineMethod(`array`,[`inner`],({inner})=>`${inner.toString(true)}[]`);defineMethod(`dict`,[`inner`,`sKey`],({inner,sKey})=>`{ [key: ${sKey.toString()}]: ${inner.toString()} }`);defineMethod(`tuple`,[`list`],({list})=>`[${list.map(inner=>inner.toString()).join(`, `)}]`);defineMethod(`object`,[`dict`],({dict})=>{if(Object.keys(dict).length===0)return`{}`;return`{ ${Object.entries(dict).map(([key,inner])=>{return`${key}${inner.meta.required?``:`?`}: ${inner.toString()}`}).join(`, `)} }`});defineMethod(`union`,[`list`],({list},inline)=>{const result=list.map(({toString:format})=>format()).join(` | `);return inline?`(${result})`:result});defineMethod(`intersect`,[`list`],({list})=>{return`${list.map(inner=>inner.toString(true)).join(` & `)}`});defineMethod(`transform`,[`inner`,`callback`,`preserve`],({inner},isInner)=>inner.toString(isInner));const CHAT_SETTINGS_NAMESPACE=`ui-chat`;const TRANSCRIPT_VIEW_FIELD=`transcriptView`;const COLLAPSE_TIMING_FIELD=`collapseTiming`;const COLLAPSE_TIMINGS=[`completion`,`next-input`];const DEFAULT_COLLAPSE_TIMING=`completion`;const FOLDED_REPLIES_FIELD=`foldedReplies`;const FOLDED_REPLIES=[`all`,`final`];const DEFAULT_FOLDED_REPLIES=`all`;const TRANSCRIPT_VIEW_MODES=[`compact`,`standard`,`detailed`,`verbose`];const LEGACY_TRANSCRIPT_VIEW_MODE=`normal`;const LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE=`expanded`;const TRANSCRIPT_VIEW_SETTING_VALUES=[...TRANSCRIPT_VIEW_MODES,LEGACY_TRANSCRIPT_VIEW_MODE,LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE];const DEFAULT_TRANSCRIPT_VIEW_MODE=`detailed`;const PERFORMANCE_USAGE_MODES=[`compact`,`detailed`];const DEFAULT_PERFORMANCE_USAGE=`detailed`;const DEFAULT_LINK_OPENING=`sidebar`;const ChatSettingsFields={[COLLAPSE_TIMING_FIELD]:Schema.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING),[FOLDED_REPLIES_FIELD]:Schema.union([...FOLDED_REPLIES]).default(`all`),linkOpening:Schema.union([`sidebar`,`new-tab`]).default(DEFAULT_LINK_OPENING),performanceUsage:Schema.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE),[TRANSCRIPT_VIEW_FIELD]:Schema.union([...TRANSCRIPT_VIEW_SETTING_VALUES]).loose()};const ChatSettingsSchema=Schema.object(ChatSettingsFields);const POLICIES={compact:{mode:`compact`,foldCompletedTurns:true,stepGrouping:`collapsed`,liveProcessDetail:false,settledReasoningPreview:false},standard:{mode:`standard`,foldCompletedTurns:true,stepGrouping:`collapsed`,liveProcessDetail:true,settledReasoningPreview:true},detailed:{mode:`detailed`,foldCompletedTurns:true,stepGrouping:`history`,liveProcessDetail:true,settledReasoningPreview:true},verbose:{mode:`verbose`,foldCompletedTurns:false,stepGrouping:`none`,liveProcessDetail:false,settledReasoningPreview:true}};function withTiming(collapseTiming,foldedReplies){return{compact:{...POLICIES.compact,collapseTiming,foldedReplies},standard:{...POLICIES.standard,collapseTiming,foldedReplies},detailed:{...POLICIES.detailed,collapseTiming,foldedReplies},verbose:{...POLICIES.verbose,collapseTiming,foldedReplies}}}const TIMING_POLICIES={completion:{all:withTiming(`completion`,`all`),final:withTiming(`completion`,`final`)},"next-input":{all:withTiming(`next-input`,`all`),final:withTiming(`next-input`,`final`)}};function presentationPolicyFor(mode,collapseTiming=`completion`,foldedReplies=`all`){return TIMING_POLICIES[collapseTiming][foldedReplies][mode]}function derivePresentationPolicy(mode,collapseTiming,foldedReplies){return{getSnapshot:()=>presentationPolicyFor(mode.getSnapshot(),collapseTiming.getSnapshot(),foldedReplies.getSnapshot()),subscribe:listener=>{const unsubscribeMode=mode.subscribe(listener);const unsubscribeTiming=collapseTiming.subscribe(listener);const unsubscribeReplies=foldedReplies.subscribe(listener);return()=>{unsubscribeMode();unsubscribeTiming();unsubscribeReplies()}}}}var PreferenceRow_module_css_default={"chevron":`_2XZxNq_chevron`,"desc":`_2XZxNq_desc`,"row":`_2XZxNq_row`,"rowText":`_2XZxNq_rowText`,"selector":`_2XZxNq_selector`,"title":`_2XZxNq_title`};function PreferenceRow({title,description,value,selectedLabel,options,onSelect}){const[open,setOpen]=(0,react.useState)(false);const selectorRef=(0,react.useRef)(null);const closeMenu=()=>{setOpen(false)};const selectMode=id=>{selectorRef.current?.focus({preventScroll:true});closeMenu();onSelect(id)};const selector=(0,react_jsx_runtime.jsxs)(`button`,{ref:selectorRef,type:`button`,className:PreferenceRow_module_css_default.selector,"aria-haspopup":`menu`,"aria-expanded":open,onClick:()=>{setOpen(value=>!value)},children:[selectedLabel,(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{className:PreferenceRow_module_css_default.chevron})]});return(0,react_jsx_runtime.jsxs)(`div`,{className:PreferenceRow_module_css_default.row,children:[(0,react_jsx_runtime.jsxs)(`div`,{className:PreferenceRow_module_css_default.rowText,children:[(0,react_jsx_runtime.jsx)(`div`,{className:PreferenceRow_module_css_default.title,children:title}),(0,react_jsx_runtime.jsx)(`div`,{className:PreferenceRow_module_css_default.desc,children:description})]}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Menu,{open,onClose:closeMenu,items:options,selectedId:value,onSelect:selectMode,align:`end`,portal:true,anchor:selector})]})}const LABELS={compact:`settings.transcript.compact`,standard:`settings.transcript.standard`,detailed:`settings.transcript.detailed`,verbose:`settings.transcript.verbose`};const COLLAPSE_LABELS={completion:`settings.collapse.completion`,"next-input":`settings.collapse.nextInput`};const FOLDED_REPLY_LABELS={all:`settings.foldedReplies.all`,final:`settings.foldedReplies.final`};function TranscriptViewRow({useTranscriptView,setTranscriptView,useCollapseTiming,setCollapseTiming,useFoldedReplies,setFoldedReplies,t}){const mode=useTranscriptView(value=>value);const timing=useCollapseTiming(value=>value);const replies=useFoldedReplies(value=>value);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.transcript.title`),description:t(`settings.transcript.description`),value:mode,selectedLabel:t(LABELS[mode]),options:TRANSCRIPT_VIEW_MODES.map(id=>({id,label:t(LABELS[id])})),onSelect:value=>{setTranscriptView(value)}}),(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.collapse.title`),description:t(`settings.collapse.description`),value:timing,selectedLabel:t(COLLAPSE_LABELS[timing]),options:COLLAPSE_TIMINGS.map(id=>({id,label:t(COLLAPSE_LABELS[id])})),onSelect:value=>{setCollapseTiming(value)}}),mode!==`verbose`&&(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.foldedReplies.title`),description:t(`settings.foldedReplies.description`),value:replies,selectedLabel:t(FOLDED_REPLY_LABELS[replies]),options:FOLDED_REPLIES.map(id=>({id,label:t(FOLDED_REPLY_LABELS[id])})),onSelect:value=>{setFoldedReplies(value)}})]})}var TranscriptViewPolicy=class{host;defaultMode;unsubscribe;mode;collapseTiming=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(DEFAULT_COLLAPSE_TIMING);foldedReplies=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(`all`);constructor(host,defaultMode=DEFAULT_TRANSCRIPT_VIEW_MODE){this.host=host;this.defaultMode=defaultMode;this.mode=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(defaultMode);this.unsubscribe=host.subscribe(()=>{this.adopt()});this.adopt()}dispose(){this.unsubscribe()}setMode(mode){if(this.mode.getSnapshot()===mode)return;this.mode.set(mode);this.host.set(TRANSCRIPT_VIEW_FIELD,mode)}setCollapseTiming(timing){if(this.collapseTiming.getSnapshot()===timing)return;this.collapseTiming.set(timing);this.host.set(COLLAPSE_TIMING_FIELD,timing)}setFoldedReplies(replies){if(this.foldedReplies.getSnapshot()===replies)return;this.foldedReplies.set(replies);this.host.set(FOLDED_REPLIES_FIELD,replies)}adopt(){const section=this.host.getSnapshot().value;if(section===void 0)return;const saved=section.transcriptView;const mode=saved===`normal`||saved===`expanded`?`detailed`:saved??this.defaultMode;if(this.mode.getSnapshot()!==mode)this.mode.set(mode);const timing=section.collapseTiming??`completion`;if(this.collapseTiming.getSnapshot()!==timing)this.collapseTiming.set(timing);const replies=section.foldedReplies??`all`;if(this.foldedReplies.getSnapshot()!==replies)this.foldedReplies.set(replies)}};function LinkOpeningRow({useLinkOpening,useBrowserAvailable,setLinkOpening,t}){const destination=useLinkOpening(value=>value);if(!useBrowserAvailable(value=>value))return null;return(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.links.title`),description:t(`settings.links.description`),value:destination,selectedLabel:t(destination===`sidebar`?`settings.links.sidebar`:`settings.links.newTab`),options:[{id:`sidebar`,label:t(`settings.links.sidebar`)},{id:`new-tab`,label:t(`settings.links.newTab`)}],onSelect:value=>{setLinkOpening(value)}})}const OPTIONS=[{id:`compact`,label:`settings.performance.compact`},{id:`detailed`,label:`settings.performance.detailed`}];function PerformanceUsageRow({usePerformanceUsage,setPerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const selectedLabel=mode===`detailed`?`settings.performance.detailed`:`settings.performance.compact`;return(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.performance.title`),description:t(`settings.performance.description`),value:mode,selectedLabel:t(selectedLabel),options:OPTIONS.map(option=>({id:option.id,label:t(option.label)})),onSelect:value=>{setPerformanceUsage(value)}})}var PerformanceUsagePolicy=class{host;unsubscribe;mode=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(DEFAULT_PERFORMANCE_USAGE);constructor(host){this.host=host;const adopt=()=>{const accepted=host.getSnapshot().value?.performanceUsage;if(accepted!==void 0)this.mode.set(accepted)};this.unsubscribe=host.subscribe(adopt);adopt()}dispose(){this.unsubscribe()}setMode(mode){if(mode===this.mode.getSnapshot())return;this.mode.set(mode);this.host.set(`performanceUsage`,mode)}};const EMPTY_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};function useTurnDataValue(data,key){const source=data?.source(key)??EMPTY_SOURCE;return(0,react.useSyncExternalStore)(source.subscribe,source.getSnapshot)}const CHAT_FLOW_INJECT={hooks:{groupAction:(_standard,{motion})=>function useGroupAction(hidden,reveal){return useFlowHidden(hidden,reveal,motion)},groupHeaderAction:(_standard,{motion})=>function useGroupHeaderAction(ref,hidden){useMotionHidden(ref,hidden,motion)}}};const CHAT_NODE_INJECT={hooks:{turnData:(_standard,{turnData})=>function useTurnData(key){return useTurnDataValue(turnData,key)},disclosure:(_standard,{disclosureReset})=>bindDisclosure(disclosureReset),groupAction:(_standard,{useGroupAction})=>useGroupAction}};const inject=[`slots`,`sessions`,`uiWorkspace`,`uiSession`,`uiConversation`,`locale`,`configForms`,`connection`,`remote`,`remote.session`,`sidebarRight`,`fileDrag`];function apply(ctx){const quotaNotice=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);let quotaNoticeSeq=0;const quotaNoticeHolds=new Set;const chatSources=new WeakMap;const quotaSubscriptions=new Set;ctx.effect(()=>async()=>{await Promise.all([...quotaSubscriptions].map(dispose=>dispose()))},`ui-chat: live quota notices`);const chatSource=binding=>{let source=chatSources.get(binding);if(source===void 0){const dispose=binding.ctx.effect(()=>{const retainInfo=ctx.sessions.retainInfo(binding.sessionId);const retained=()=>ctx.sessions.binding(binding.sessionId)===binding&&(retainInfo.getSnapshot().retainedFacets?.conversation??0)>0;let stopEvents;const follow=()=>{if(!retained()){stopEvents?.();stopEvents=void 0;return}stopEvents??=binding.eventSource.subscribe(()=>{if(!retained())return;const{change}=binding.eventSource.getSnapshot();if(change.kind!==`append`)return;for(const{event}of change.entries){if(event.type!==`turn/end`||event.data.reason.kind!==`error`)continue;const{code}=event.data.reason.error;if(quotaNoticeHolds.size>0||code!==`QUOTA`&&code!==`ACCOUNT_QUOTA`)continue;quotaNotice.set({code,seq:++quotaNoticeSeq})}})};const stopRetained=retainInfo.subscribe(follow);follow();return()=>{stopRetained();stopEvents?.();chatSources.delete(binding);quotaSubscriptions.delete(dispose)}},`ui-chat: Provider binding quota notices`);quotaSubscriptions.add(dispose);const target=ctx.uiConversation.binding(binding).target(`chat`);source={getSnapshot:()=>target.getSnapshot()??EMPTY_CHAT_SNAPSHOT,subscribe:listener=>target.subscribe(listener)};chatSources.set(binding,source)}return source};registerConversationNodes(ctx);ctx.uiSession.provide({hooks:[`chat`],resolve:binding=>({hooks:{chat:chatSource(binding)}})});ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`ui-chat: dictionaries`);const t=ctx.locale.bind(NS);const chatStore=createChatStore();const chatScrollPositions=new Map;const chatSettings=ctx.configForms.get(CHAT_SETTINGS_NAMESPACE);const linkOpening=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(chatSettings.getSnapshot().value?.linkOpening??`sidebar`);ctx.effect(()=>chatSettings.subscribe(()=>{const accepted=chatSettings.getSnapshot().value?.linkOpening;if(accepted!==void 0)linkOpening.set(accepted)}));ctx.inject([`sidebarRightTabs`],scope=>{const tabs=scope.sidebarRightTabs;const browserAvailable={getSnapshot:()=>tabs.get(`browser`)!==void 0,subscribe:listener=>tabs.subscribe(listener)};scope.slots.inject(`settings.general.group.interaction.item`,()=>scope.slots.register({name:`settings.general.group.interaction.item`,id:`link-opening`,order:10,locale:NS,inject:()=>({hooks:{linkOpening,browserAvailable},setLinkOpening:destination=>{linkOpening.set(destination);chatSettings.set(`linkOpening`,destination).catch(_error=>{})}})},LinkOpeningRow))});const transcriptView=new TranscriptViewPolicy(chatSettings,`dshDesktop`in globalThis?`standard`:DEFAULT_TRANSCRIPT_VIEW_MODE);const presentation=derivePresentationPolicy(transcriptView.mode,transcriptView.collapseTiming,transcriptView.foldedReplies);const performancePolicy=new PerformanceUsagePolicy(chatSettings);ctx.effect(()=>()=>{transcriptView.dispose();performancePolicy.dispose()});const performanceUsage=performancePolicy.mode;registerChatNodeRenderers(ctx,performanceUsage,presentation);ctx.slots.registerFactory({name:`conversation.chat.user.content`,scope:`session`,locale:NS,children:{"conversation.chat.user.images":{kind:`single`,scope:`session`}}},UserContent);ctx.slots.inject(`settings.general.group.display.item`,()=>ctx.slots.register({name:`settings.general.group.display.item`,id:`performance-usage`,order:30,locale:NS,inject:()=>({hooks:{performanceUsage},setPerformanceUsage:mode=>{performancePolicy.setMode(mode)}})},PerformanceUsageRow));ctx.slots.inject(`settings.general.group.display.item`,()=>ctx.slots.register({name:`settings.general.group.display.item`,id:`transcript-view`,order:12,locale:NS,inject:()=>({hooks:{transcriptView:transcriptView.mode,collapseTiming:transcriptView.collapseTiming,foldedReplies:transcriptView.foldedReplies},setTranscriptView:mode=>{transcriptView.setMode(mode)},setCollapseTiming:timing=>{transcriptView.setCollapseTiming(timing)},setFoldedReplies:replies=>{transcriptView.setFoldedReplies(replies)}})},TranscriptViewRow));const connectionState=ctx.get(`connection`).state;const nodeSources=binding=>{const chat=chatSource(binding);const conversation=ctx.uiConversation.binding(binding);return{keyedHooks:{chatNode:key=>chat.getSnapshot().nodes.source(key),chatNodeBottom:key=>chat.getSnapshot().nodes.bottomSource(key),chatNodeProcess:key=>chat.getSnapshot().nodes.processSource(key),chatGroup:key=>conversation.snapshot.getSnapshot().views.grouped(`chat`)?.groupSource(key)}}};ctx.slots.inject(`conversation.chat.flow`,()=>ctx.slots.register({name:`conversation.chat.flow`,locale:NS,store:chatStore,children:{"conversation.chat.node":{kind:`keyed`,scope:`session`,inject:CHAT_NODE_INJECT}},inject:sessionId=>{const binding=ctx.sessions.binding(sessionId);if(binding===void 0)throw new Error(`ui-chat: unknown session "${sessionId}"`);return{...nodeSources(binding),hooks:{presentation,connectionState}}}},ChatFlow));ctx.slots.inject(`conversation.view`,()=>{return ctx.slots.register({name:`conversation.view`,id:`chat`,order:0,label:()=>t(`view.chat`),locale:NS,children:{"conversation.chat.flow":{kind:`single`,scope:`session`,inject:CHAT_FLOW_INJECT},"conversation.chat.text-interaction":{kind:`keyed`,scope:`session`},"conversation.chat.markdown.fence":{kind:`hoc`,scope:`session`},"conversation.chat.aside":{kind:`single`,scope:`session`}},store:chatStore,inject:sessionId=>{const binding=ctx.sessions.binding(sessionId);if(binding===void 0)throw new Error(`ui-chat: unknown session "${sessionId}"`);const session=binding.session;const chat=chatSource(binding);return{...nodeSources(binding),fileDrag:ctx.fileDrag.actions,hooks:{presentation,interactionIds:ctx.uiConversation.interactions},dispatchInteraction:gesture=>ctx.uiConversation.interactions.dispatch(sessionId,gesture),openFile:async(path,options)=>{const url=fileAddressFor(sessionId,sessionDirectory(ctx.sessions,sessionId),path);if(options?.line===void 0)ctx.sidebarRight.openResource(url);else ctx.sidebarRight.openResource(url,{params:{line:options.line}});await Promise.resolve()},resolveFilePath:sessionFilePath(ctx,sessionId),openExternalLink:url=>{if(linkOpening.getSnapshot()===`sidebar`&&ctx.get(`sidebarRightTabs`)?.get(`browser`)!==void 0)ctx.sidebarRight.openTab(`browser`,{params:{url}});else window.open(url,`_blank`,`noopener,noreferrer`)},loadOlder:()=>{session.loadOlder({deferConsumption:true})},consumeOlder:()=>session.consumeOlder(),loadThrough:seq=>session.loadThrough(seq),loadImage:Object.assign(attachment=>ctx.uiConversation.imageUrl(sessionId,attachment),{peek:attachment=>ctx.uiConversation.peekImageUrl(sessionId,attachment)}),chatScroll:{save:position=>{if(position===null)chatScrollPositions.delete(sessionId);else chatScrollPositions.set(sessionId,position)},read:()=>chatScrollPositions.get(sessionId)??null},forkAt:seq=>{const messageId=[...chat.getSnapshot().timeline.turns.values()].find(turn=>turn.end?.seq===seq)?.data.get(`turn-tail`)?.closing?.finalNode.messageId;ctx.uiWorkspace.forkSession(sessionId,childId=>{ctx.get(`productAnalytics`)?.track(`branch_session_click`,{session_id:childId,parent_session_id:sessionId,...messageId===void 0?{}:{parent_message_id:messageId},click_position:`footer`})},{atSeq:seq}).then(childId=>{ctx.uiWorkspace.openSession(childId)}).catch(()=>{})}}}},ChatView)});registerFenceLayers(ctx);ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`chat.quota-notice`,locale:NS,children:{"shell.quota-notice":{kind:`chain`,scope:`root`}},inject:()=>({hooks:{notice:quotaNotice},dismissNotice:()=>{quotaNoticeHolds.clear();quotaNotice.set(null)},keepNoticeOpen:()=>{if(quotaNotice.getSnapshot()===null)return()=>{};const token=Symbol(`ui-chat quota notice hold`);quotaNoticeHolds.add(token);return()=>{quotaNoticeHolds.delete(token)}}})},QuotaNoticeHost));const statPillInject=()=>({hooks:{performanceUsage}});ctx.slots.inject(`conversation.composer.dock`,function*(){yield ctx.slots.register({name:`conversation.composer.dock`,id:`activity`,order:0,locale:NS,inject:statPillInject},ActivityPill);yield ctx.slots.register({name:`conversation.composer.dock`,id:`usage`,order:1,locale:NS,inject:statPillInject},UsagePill)});ctx.slots.inject(`conversation.approval.detail`,()=>ctx.slots.register({name:`conversation.approval.detail`},ApprovalCommand))}exports.EMPTY_CHAT_SNAPSHOT=EMPTY_CHAT_SNAPSHOT;exports.apply=apply;exports.inject=inject;exports.isRunningTool=isRunningTool;exports.isSettledTool=isSettledTool;return module.exports},meta:()=>({stylesheets:{"src/client/chat/TurnNavigator.module.css":{text:context=>`.eGxaPq_slot{z-index:7;height:0;padding-inline:calc(var(--dsh-composer-side-clearance) + 16px);pointer-events:none;position:absolute;top:0;left:0;right:0;container-type:inline-size}.eGxaPq_slot:is([data-conversation-scroll] *){position:sticky}.eGxaPq_frame{--turn-rail-band:calc(var(--dsh-conversation-viewport-height,100dvh) - var(--dsh-composer-height,152px));--turn-preview-height:100px;top:calc(var(--turn-rail-band) / 2);width:28px;max-height:min(max(0px, calc(var(--turn-rail-band) - 64px)), 420px);contain:layout;cursor:pointer;pointer-events:auto;position:absolute;left:12px;transform:translateY(-50%)}.eGxaPq_scroller{max-height:inherit;overscroll-behavior:contain;scrollbar-width:none;position:relative;overflow-y:auto}.eGxaPq_scroller::-webkit-scrollbar{display:none}.eGxaPq_fadeTop{mask-image:linear-gradient(#0000 0,#000 24px 100%)}.eGxaPq_fadeBottom{mask-image:linear-gradient(#000 0 calc(100% - 24px),#0000 100%)}.eGxaPq_fadeTop.eGxaPq_fadeBottom{mask-image:linear-gradient(#0000 0,#000 24px calc(100% - 24px),#0000 100%)}.eGxaPq_marks{position:relative}.eGxaPq_mark{cursor:pointer;background:0 0;border:0;border-radius:8px;height:10px;padding:0;position:absolute;top:0;left:0;right:0}.eGxaPq_mark:before{background:var(--dsw-alias-border-l4);content:"";transform-origin:0;border-radius:2px;width:20px;height:2px;transition:transform .14s,background-color .14s;position:absolute;top:50%;left:0;transform:translateY(-50%)scaleX(.6)}.eGxaPq_markUnloaded:before{opacity:.6;transform:translateY(-50%)scaleX(.4)}.eGxaPq_markPreview:before{background:var(--dsw-alias-label-tertiary);transform:translateY(-50%)scaleX(.9)}.eGxaPq_markBusy:before{animation:1s ease-in-out infinite eGxaPq_dsh-turn-mark-busy}.eGxaPq_markActive:before{background:var(--dsw-alias-label-primary);transform:translateY(-50%)scaleX(1)}.eGxaPq_mark:focus-visible:before{background:var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));transform:translateY(-50%)scaleX(1)}.eGxaPq_mark:focus-visible{outline:none}.eGxaPq_mark:focus-visible:after{border-radius:inherit;outline:1px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:-1px;content:"";width:20px;position:absolute;inset:0 auto 0 0}.eGxaPq_preview{top:clamp(0px, calc(var(--turn-preview-center) - var(--turn-preview-height) / 2), calc(100% - var(--turn-preview-height)));box-sizing:border-box;width:min(300px,100cqw - 120px);max-height:var(--turn-preview-height);border-radius:var(--dsw-radius-lg);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1);box-shadow:var(--dsw-elevation-panel);pointer-events:none;border:0;padding:10px 12px;transition:top .14s cubic-bezier(.2,.8,.2,1);animation:.12s ease-out eGxaPq_dsh-turn-preview-enter;position:absolute;left:calc(100% + 10px);overflow:hidden}.eGxaPq_previewPrompt,.eGxaPq_previewResponse{-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.eGxaPq_previewPrompt{font:var(--dsw-font-xs-strong-13);-webkit-line-clamp:1}.eGxaPq_previewResponse{color:var(--dsw-alias-label-caption);font:var(--dsw-font-xxs-12);-webkit-line-clamp:3;margin-top:4px}@keyframes eGxaPq_dsh-turn-preview-enter{0%{opacity:0;transform:translate(-4px)}to{opacity:1;transform:translate(0)}}@keyframes eGxaPq_dsh-turn-mark-busy{0%,to{opacity:1}50%{opacity:.35}}@container (width<=900px){.eGxaPq_frame{display:none}}@media (prefers-reduced-motion:reduce){.eGxaPq_frame,.eGxaPq_scroller,.eGxaPq_mark:before,.eGxaPq_markBusy:before,.eGxaPq_preview{scroll-behavior:auto;transition:none;animation:none}}`},"src/client/chat/ChatView.module.css":{text:context=>`.EvIC1a_frame{flex-direction:column;flex:auto;min-height:0;display:flex;position:relative;container-type:inline-size}.EvIC1a_root{flex-direction:column;flex:auto;min-height:0;display:flex;position:relative;overflow:visible clip}.EvIC1a_scroll{min-height:0;padding:16px calc(var(--dsh-composer-side-clearance) + 16px);overscroll-behavior-y:none;flex:auto;overflow:clip auto;container-type:inline-size}.EvIC1a_root[data-chat-following-tail] .EvIC1a_scroll{overflow-anchor:none}.EvIC1a_frame:is([data-conversation-scroll] *),.EvIC1a_root:is([data-conversation-scroll] *){flex:none;height:auto;min-height:auto}.EvIC1a_scroll:is([data-conversation-scroll] *){flex:none;min-height:auto;overflow:clip visible}.EvIC1a_column{max-width:var(--dsh-chat-content-width);flex-direction:column;width:100%;margin:0 auto;display:flex;position:relative}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)))~:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))),.EvIC1a_column>.EvIC1a_older+[data-slot="conversation.chat.flow"]>:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))){margin-top:var(--dsh-chat-flow-gap,4px)}.EvIC1a_flowItem[data-chat-group-part=response],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-group-part=response]:not([hidden]):not(:empty)+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])),.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-group-key],.EvIC1a_flowItem:is([data-chat-flow-kind=compaction],[data-chat-flow-kind=manual-compaction],[data-chat-flow-kind=command],[data-chat-flow-kind=context],[data-chat-flow-kind=model-retry],[data-chat-flow-kind=turn-error],[data-chat-flow-kind=turn-max-tokens])):not([hidden])+.EvIC1a_flowItem[data-chat-flow-kind=user]{--dsh-chat-flow-gap:12px}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering],[data-chat-flow-kind=question-reply])+.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering],[data-chat-flow-kind=question-reply])+[hidden]+.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=question-reply]+.EvIC1a_flowItem[data-chat-group-part=response],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=question-reply]+[hidden]+.EvIC1a_flowItem[data-chat-group-part=response]{--dsh-chat-flow-gap:4px}.EvIC1a_flowItem{min-width:0}.EvIC1a_turnSpacer{height:0}.EvIC1a_column[data-chat-motion]>:not([data-chat-motion]),.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:margin-top .16s cubic-bezier(.4,0,.2,1)}.EvIC1a_column[data-input-fold]>:not([data-chat-motion]),.EvIC1a_column[data-input-fold]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:none}.EvIC1a_column[data-chat-motion]>[data-chat-flow-kind=turn-process],.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>[data-chat-flow-kind=turn-process]{transition:none}@media (prefers-reduced-motion:reduce){.EvIC1a_column[data-chat-motion]>:not([data-chat-motion]),.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:none}}.EvIC1a_flowItem[data-chat-flow-kind=turn-process],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=turn-process]:not(:empty,:has(>[data-slot="conversation.chat.node"]:empty))+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])),:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=turn-process]+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not([data-submission-echo],[data-pending-steering]):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])){--dsh-chat-flow-gap:16px}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>.EvIC1a_flowItem:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch=start]){--dsh-chat-flow-gap:calc(44px + var(--dsh-content-font-delta,0px))}.EvIC1a_running+[data-pending-steering]{--dsh-chat-flow-gap:0px}.EvIC1a_flowItem[data-chat-flow-kind=turn-tail]+.EvIC1a_running{display:none}@media (prefers-reduced-motion:no-preference){:where(.EvIC1a_column>[data-slot="conversation.chat.flow"]>.EvIC1a_flowItem[data-chat-flow-kind=steering])+.EvIC1a_running{animation:.14s cubic-bezier(.2,.8,.2,1) EvIC1a_running-enters-slot}.EvIC1a_column[data-input-fold] .EvIC1a_running{animation-duration:0s}}@keyframes EvIC1a_running-enters-slot{0%{opacity:0;translate:0 calc(-44px - var(--dsh-content-font-delta,0px))}40%{opacity:1}}.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)){height:0}.EvIC1a_callRow{border-radius:var(--dsw-radius-sm)}.EvIC1a_hint{color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.EvIC1a_running{--dsh-chat-flow-gap:12px;--dsw-alias-label-shimmer:var(--dsw-alias-label-deep-diving-shimmer);color:var(--dsw-alias-label-deep-diving);font-size:calc(var(--dsh-content-font-size,14px) - 2px);line-height:calc(22px + var(--dsh-content-font-delta,0px));flex-direction:column;align-items:flex-start;display:flex;position:relative}.EvIC1a_running[data-holding]{visibility:hidden;opacity:0}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:nth-last-child(2 of :not([hidden]):not([data-pending-steering]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)))):is(.EvIC1a_flowItem:not([data-chat-flow-kind=user]):not([data-chat-flow-kind=steering]):not([data-chat-flow-kind=turn-trigger]),[data-chat-group-key])~.EvIC1a_running>.EvIC1a_runningDivider{opacity:1}.EvIC1a_runningDivider{background:color-mix(in srgb, var(--dsw-alias-border-l1) 75%, var(--dsw-alias-border-l2));opacity:0;pointer-events:none;height:.5px;position:absolute;top:-4px;left:0;right:0}@media (prefers-reduced-motion:no-preference){.EvIC1a_runningDivider{transition:opacity .16s}}.EvIC1a_runningContent{min-width:0;height:calc(28px + var(--dsh-content-font-delta,0px));align-items:center;gap:6px;margin-top:4px;display:inline-flex}.EvIC1a_runningText{font-variant-numeric:tabular-nums;min-width:0}.EvIC1a_runningIcon{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px));contain:strict;flex:none;display:inline-flex;position:relative;overflow:hidden}.EvIC1a_runningWhaleAnimated{display:none;position:absolute;inset:0}.EvIC1a_runningWhaleStill{display:initial}@supports (mask-mode:alpha) and (mask-image:url('')){@media (prefers-reduced-motion:no-preference) and (forced-colors:none){.EvIC1a_runningWhaleAnimated{will-change:transform;background:currentColor;display:block;mask:url(`+context.asset(`plugins/@deepseek-ai/dsh-client-ui-chat/assets/running-whale%402x-06738fa29b2f.png`)+`) 50%/100% 100% no-repeat alpha}.EvIC1a_runningWhaleStill{display:none}}}.EvIC1a_openError{color:var(--dsw-alias-state-error-primary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.EvIC1a_older{overflow-anchor:none;justify-content:center;display:flex}.EvIC1a_older button{white-space:nowrap;border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-interactive-bg-hover-solid);cursor:pointer;border:none;padding:4px 12px;font-size:12px;line-height:18px;display:grid}.EvIC1a_older button>span{grid-area:1/1}.EvIC1a_historyHidden{visibility:hidden}.EvIC1a_older button:disabled{cursor:default;opacity:.6}.EvIC1a_asideSlot{z-index:9;height:0;transition:margin-inline-end var(--dsh-chat-end-reserve-transition,0s);pointer-events:none;--dsh-chat-aside-gutter:calc(var(--dsh-chat-end-inset,0px) + max(0px, (100% - var(--dsh-chat-end-inset,0px) - var(--dsh-chat-content-width,100%)) / 2));margin-inline-end:calc(-1 * var(--dsh-chat-end-inset,0px));position:absolute;top:0;left:0;right:0}.EvIC1a_asideSlot:is([data-conversation-scroll] *){position:sticky}.EvIC1a_toBottomSlot{z-index:8;height:0;padding-right:max(calc(var(--dsh-composer-side-clearance) + 16px), calc((100% - var(--dsh-chat-content-width)) / 2));pointer-events:none;justify-content:flex-end;display:flex;position:absolute;bottom:16px;left:0;right:0}.EvIC1a_toBottomSlot:is([data-conversation-scroll] *){bottom:calc(var(--dsh-composer-height,152px) + 16px);position:sticky}.EvIC1a_toBottom{--dsw-elevation-stroke-color:var(--dsw-alias-border-l3);corner-shape:round;width:34px;height:34px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-floating-fill);box-shadow:var(--dsw-elevation-panel);cursor:pointer;pointer-events:auto;border:0;border-radius:100px;justify-content:center;align-items:center;margin-top:-34px;padding:0;display:flex}@media (hover:hover){.EvIC1a_toBottom:hover{background:var(--dsw-alias-button-floating-hover)}}.EvIC1a_modalAction{min-width:72px}.EvIC1a_column>.EvIC1a_textInteraction{z-index:6;visibility:hidden;width:max-content;margin:0;position:absolute}`},"src/client/chat/ChatGroupSeat.module.css":{text:context=>`.O_Ebla_root{min-width:0}.O_Ebla_title{max-width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:6px;padding:0;transition:color .1s;display:flex}@media (hover:hover){.O_Ebla_title:hover{color:var(--dsw-alias-label-secondary)}}.O_Ebla_leading{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));color:inherit;flex:none;justify-content:center;align-items:center;display:inline-flex;position:relative}.O_Ebla_leading svg{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px))}.O_Ebla_leading svg[width="16"]{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px))}.O_Ebla_activityIcon,.O_Ebla_chevron{justify-content:center;align-items:center;transition:opacity .1s;display:inline-flex;position:absolute;inset:0}.O_Ebla_activityIcon{opacity:1}.O_Ebla_chevron,.O_Ebla_title:focus-visible .O_Ebla_activityIcon{opacity:0}@media (hover:hover){.O_Ebla_title:hover .O_Ebla_activityIcon{opacity:0}}.O_Ebla_title:focus-visible .O_Ebla_chevron{opacity:1}@media (hover:hover){.O_Ebla_title:hover .O_Ebla_chevron{opacity:1}}.O_Ebla_title[aria-expanded=true] .O_Ebla_activityIcon{opacity:0}.O_Ebla_title[aria-expanded=true] .O_Ebla_chevron{opacity:1}.O_Ebla_title[aria-expanded=true]{padding-bottom:8px}.O_Ebla_body{--dsh-chat-flow-gap:4px;overscroll-behavior-y:auto;scrollbar-gutter:stable;max-height:min(400px,50vh);overflow-y:auto}.O_Ebla_label{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}.O_Ebla_fadeTop{mask-image:linear-gradient(#0000 0,#000 24px 100%)}.O_Ebla_fadeBottom{mask-image:linear-gradient(#000 0 calc(100% - 24px),#0000 100%)}.O_Ebla_fadeTop.O_Ebla_fadeBottom{mask-image:linear-gradient(#0000 0,#000 24px calc(100% - 24px),#0000 100%)}@media (prefers-reduced-motion:reduce){.O_Ebla_title,.O_Ebla_activityIcon,.O_Ebla_chevron{transition:none}}.O_Ebla_content{flex-direction:column;display:flex}.O_Ebla_content>*{flex-shrink:0}.O_Ebla_content>:not([hidden]):not(:empty)~[data-chat-flow-key]:not([hidden]):not(:empty){margin-top:var(--dsh-chat-flow-gap,4px)}.O_Ebla_expandedBody{scrollbar-gutter:auto;max-height:none;overflow:visible}[data-chat-motion] .O_Ebla_content>[data-chat-flow-key]:not([data-chat-motion]){transition:margin-top .16s cubic-bezier(.4,0,.2,1)}@media (prefers-reduced-motion:reduce){[data-chat-motion] .O_Ebla_content>[data-chat-flow-key]:not([data-chat-motion]){transition:none}}`},"src/client/chat/accessibility.module.css":{text:context=>`.TTCZqG_visuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;width:1px;height:1px;position:absolute;overflow:hidden}`},"src/client/chat/CommandStatusRow.module.css":{text:context=>`.kWGFkG_root{flex-direction:column;display:flex}.kWGFkG_leading{flex-shrink:0}.kWGFkG_title{font-weight:400}.kWGFkG_separator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.kWGFkG_summary{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.kWGFkG_summary[data-error],.kWGFkG_body[data-error]{color:var(--dsw-alias-state-error-primary)}.kWGFkG_body{border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-markdown-code-block);max-height:260px;color:var(--dsw-alias-label-primary);font:var(--dsw-font-markdown-code-block-small);white-space:pre-wrap;margin:4px 0 4px 4px;padding:12px 16px;overflow:auto}`},"src/client/chat/MessageItem.module.css":{text:context=>`.Sixlwa_userRow{flex-direction:column;align-items:flex-end;gap:6px;display:flex}.Sixlwa_userStack{min-width:0;max-width:min(calc(var(--dsh-chat-content-width,748px) * .702), 82%);flex-direction:column;align-items:flex-end;gap:8px;display:flex}.Sixlwa_referenceSummary{color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.Sixlwa_contextRow{padding:2px 0}.Sixlwa_inheritedHistoryRow{align-items:center;gap:12px;padding:2px 0 20px;display:flex}.Sixlwa_inheritedHistoryLine{border-top:.5px solid var(--dsw-alias-border-l2);flex:1 1 0;min-width:16px}.Sixlwa_inheritedHistoryCaption{min-width:0;color:var(--dsw-alias-label-tertiary);flex:0 auto;align-items:center;gap:6px;display:flex}.Sixlwa_inheritedHistoryIcon{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px));flex:none}.Sixlwa_inheritedHistoryLabel{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:0 auto;overflow:hidden}.Sixlwa_compactionRow{padding:2px 0}.Sixlwa_compactionButton{width:100%;height:calc(24px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);min-width:0;color:var(--dsw-alias-label-tertiary);font:inherit;text-align:left;background:0 0;border:none;align-items:center;padding:0;transition:color .1s;display:flex}.Sixlwa_compactionButton:not(:disabled){cursor:pointer}@media (hover:hover){.Sixlwa_compactionButton:hover{color:var(--dsw-alias-label-secondary)}.Sixlwa_compactionButton:not(:disabled):hover{background:var(--dsw-alias-interactive-bg-hover)}}.Sixlwa_compactionLeading{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));color:inherit;flex:none;place-items:center;margin-right:6px;display:inline-grid}.Sixlwa_compactionLeading svg{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px))}.Sixlwa_compactionContextIcon,.Sixlwa_compactionOpenIcon{grid-area:1/1;justify-content:center;align-items:center;display:inline-flex}.Sixlwa_compactionOpenIcon,.Sixlwa_compactionButton:not(:disabled):focus-visible .Sixlwa_compactionContextIcon{opacity:0}@media (hover:hover){.Sixlwa_compactionButton:not(:disabled):hover .Sixlwa_compactionContextIcon{opacity:0}}.Sixlwa_compactionButton:not(:disabled):focus-visible .Sixlwa_compactionOpenIcon{opacity:1}@media (hover:hover){.Sixlwa_compactionButton:not(:disabled):hover .Sixlwa_compactionOpenIcon{opacity:1}}.Sixlwa_compactionTitle{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:inherit;flex:none}.Sixlwa_compactionSep{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.Sixlwa_compactionSummary{min-width:0;color:inherit;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}@media (prefers-reduced-motion:reduce){.Sixlwa_compactionButton{transition:none}}[data-disclosure-row].Sixlwa_retryRow{height:auto;min-height:calc(24px + var(--dsh-content-font-delta,0px));align-items:flex-start}[data-disclosure-row] .Sixlwa_retryLeading{margin-top:4px}[data-disclosure-row] .Sixlwa_retryTitle{font-size:var(--dsh-content-font-size-secondary,13px);white-space:normal;overflow-wrap:anywhere;flex:0 auto;min-width:0}.Sixlwa_retrySeparator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;align-self:center;width:2px;height:2px;margin:0 8px}.Sixlwa_retryProgress{overflow-wrap:anywhere;min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px))}.Sixlwa_retryBesideGroups [data-disclosure-row] .Sixlwa_retryTitle,.Sixlwa_retryBesideGroups .Sixlwa_retryProgress{font-size:var(--dsh-content-font-size,14px)}.Sixlwa_retryDetails{padding-left:calc(22px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px));gap:2px;margin-top:2px;display:grid}.Sixlwa_retryDetailLabel{color:var(--dsw-alias-label-secondary)}.Sixlwa_turnErrorRow{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));grid-template-columns:10px minmax(0,1fr) auto;align-items:start;gap:8px;padding:2px 0;display:grid}.Sixlwa_turnErrorDot{margin-top:5px}.Sixlwa_turnErrorCopy{overflow-wrap:anywhere;min-width:0}.Sixlwa_turnErrorTitle{color:var(--dsw-alias-state-error-primary);margin-right:6px;font-weight:600}.Sixlwa_turnErrorMessage{color:var(--dsw-alias-label-secondary)}.Sixlwa_turnErrorCode{color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-markdown-code-block-small)}.Sixlwa_maxTokensTitle{color:var(--dsw-alias-state-warn-primary);margin-right:6px;font-weight:600}.Sixlwa_attachmentRow{flex-wrap:wrap;justify-content:flex-end;gap:8px;max-width:100%;display:flex}.Sixlwa_fileCard{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-input-major,transparent);box-sizing:border-box;flex:0 0 240px;align-items:center;gap:10px;width:240px;min-height:64px;padding:8px 12px;display:inline-flex}.Sixlwa_fileIcon{flex:none;width:28px;height:28px}.Sixlwa_fileContent{flex-direction:column;flex:1;min-width:0;display:flex}.Sixlwa_fileName{white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-primary);font-size:14px;font-weight:500;line-height:22px;overflow:hidden}.Sixlwa_fileMeta{white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:15px;overflow:hidden}`},"src/client/chat/ContextBody.module.css":{text:context=>`.ZkiH0q_text{color:var(--dsw-alias-label-secondary);font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_fields{border-top:.5px solid var(--dsw-alias-border-l2);flex-direction:column;gap:2px;margin:8px 0 0;padding-top:8px;display:flex}.ZkiH0q_field{gap:8px;min-width:0;display:flex}.ZkiH0q_fieldKey{min-width:96px;color:var(--dsw-alias-label-caption);flex:none}.ZkiH0q_fieldValue{min-width:0;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;flex:auto;margin:0}.ZkiH0q_files{flex-wrap:wrap;gap:4px 12px;margin:0 0 8px;padding:0;list-style:none;display:flex}.ZkiH0q_file{align-items:baseline;gap:6px;min-width:0;display:flex}.ZkiH0q_filePath{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}.ZkiH0q_fileAction{color:var(--dsw-alias-label-caption)}.ZkiH0q_catalogNotice{color:var(--dsw-alias-label-caption);margin:0 0 6px}.ZkiH0q_entries{flex-direction:column;gap:4px;margin:0;padding:0;list-style:none;display:flex}.ZkiH0q_entry{gap:8px;min-width:0;display:flex}.ZkiH0q_entryName{color:var(--dsw-alias-label-secondary);flex:none}.ZkiH0q_entryDescription{min-width:0;color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.ZkiH0q_sections{flex-direction:column;gap:8px;margin:0;display:flex}.ZkiH0q_section{flex-direction:column;gap:2px;min-width:0;display:flex}.ZkiH0q_sectionName{color:var(--dsw-alias-label-caption)}.ZkiH0q_sectionText{color:var(--dsw-alias-label-secondary);white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_sectionNotice{color:var(--dsw-alias-label-caption);white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_relaySender{color:var(--dsw-alias-label-caption);overflow-wrap:anywhere;margin:0 0 6px}.ZkiH0q_recalls{flex-direction:column;gap:2px;margin:0 0 8px;padding:0;list-style:none;display:flex}.ZkiH0q_recall{gap:8px;min-width:0;display:flex}.ZkiH0q_recallLabel{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}.ZkiH0q_recallCounts{color:var(--dsw-alias-label-caption);flex:none}`},"src/client/chat/ContextInjectionRow.module.css":{text:context=>`.XrJvXW_root{min-width:0}.XrJvXW_root[data-open]{padding-bottom:4px}.XrJvXW_chevron{color:var(--dsw-alias-label-secondary)}.XrJvXW_sep{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.XrJvXW_source{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:none;overflow:hidden}.XrJvXW_summary{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.XrJvXW_body{box-sizing:border-box;width:calc(100% - 22px - var(--dsh-content-font-delta,0px));max-height:141px;margin:4px 0 0 calc(22px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-md);background:var(--dsw-alias-markdown-code-block);color:var(--dsw-alias-label-tertiary);font:400 11px/16px var(--ds-font-family-code);border:none;padding:10px 16px 12px 12px;overflow:auto}.XrJvXW_toolChanges{white-space:nowrap}`},"src/client/chat/MessageIconActions.module.css":{text:context=>`.xzv4MW_actions{height:calc(28px + var(--dsh-content-font-delta,0px));align-items:center;gap:8px;display:flex}.xzv4MW_timeStart{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);white-space:nowrap;padding-right:12px}.xzv4MW_timeEnd{font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:inherit;white-space:nowrap}.xzv4MW_endInfo{min-width:0;color:var(--dsw-alias-label-tertiary);align-items:center;gap:8px;margin-left:8px;display:inline-flex}@media (hover:hover){[data-actions-reveal=hover] .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])) .xzv4MW_actions{opacity:0;transition:opacity 80ms}[data-actions-reveal=hover]:hover .xzv4MW_actions,[data-actions-reveal=hover]:focus-within .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])):hover .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])):focus-within .xzv4MW_actions,[data-actions-reveal=hover] .xzv4MW_actions:has([data-action-ongoing]){opacity:1}}.xzv4MW_action{width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;justify-content:center;align-items:center;padding:6px;display:inline-flex}.xzv4MW_action svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}.xzv4MW_actions[data-clock=end] .xzv4MW_action svg{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));flex:none}@media (hover:hover){.xzv4MW_action:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}}.xzv4MW_action[data-unavailable]{cursor:default;opacity:.4}@media (hover:hover){.xzv4MW_action[data-unavailable]:hover{color:var(--dsw-alias-label-tertiary);background:0 0}}.xzv4MW_visuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;width:1px;height:1px;position:absolute;overflow:hidden}`},"src/client/chat/ReasoningRow.module.css":{text:context=>`.lcKema_root{flex-direction:column;display:flex}.lcKema_root:not([data-expanded]){contain:size layout;height:calc(24px + var(--dsh-content-font-delta,0px))}.lcKema_row{overflow:hidden}.lcKema_root[data-expanded] [data-open] [data-disclosure-header]{z-index:1;background:var(--dsw-alias-bg-base);position:sticky;top:0}.lcKema_leading{flex-shrink:0}.lcKema_title{font-weight:400}.lcKema_separator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.lcKema_summary{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));white-space:nowrap;flex:auto;overflow:hidden}.lcKema_summaryText{text-overflow:ellipsis;display:block;overflow:hidden}.lcKema_summary[data-streaming]{mask-image:linear-gradient(90deg,#000 calc(100% - 48px),#0000)}.lcKema_summary[data-streaming] .lcKema_summaryText{text-overflow:clip;overflow:visible}.lcKema_root:not([data-preview]) .lcKema_separator,.lcKema_root:not([data-preview]) .lcKema_summary{display:none}.lcKema_thinkBody{padding:4px 0 4px calc(22px + var(--dsh-content-font-delta,0px));min-width:0}`},"src/client/chat/AssistantMarkdown.module.css":{text:context=>`.hWmORq_root{font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-primary);flex-direction:column;display:flex}.hWmORq_body{--dsh-assistant-block-gap:16px;gap:var(--dsh-assistant-block-gap);flex-direction:column;display:flex}[data-chat-group-part=reasoning] .hWmORq_body{--dsh-assistant-block-gap:4px}.hWmORq_body .md-table-wide{--dsh-table-spare:max(0px, calc((100cqw - var(--dsh-chat-content-width)) / 2));width:calc(100% + var(--dsh-table-spare));max-width:none}.hWmORq_body .md-table-wide>table{z-index:1;position:relative}.hWmORq_body>[data-turn-process-inline][hidden],.hWmORq_body>.hWmORq_reasoning:empty{margin-bottom:calc(-1 * var(--dsh-assistant-block-gap))}.hWmORq_stopped{border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary);align-self:flex-start;padding:0 6px;font-size:11px;line-height:18px}.hWmORq_actions{margin-top:16px;margin-left:-6px}`},"src/client/chat/TurnProcessNodeView.module.css":{text:context=>`.l_V-RG_root{box-sizing:border-box;width:100%;min-width:0;height:calc(33px + var(--dsh-content-font-delta,0px));border:none;border-bottom:.5px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary);font:inherit;font-size:var(--dsh-content-font-size,14px);cursor:pointer;text-align:left;background:0 0;align-items:center;padding:0 0 8px;transition:color .1s;display:flex}.l_V-RG_root:disabled{cursor:default}@media (hover:hover){.l_V-RG_root:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}}.l_V-RG_chevron{width:14px;height:14px;color:inherit;flex:none;margin-left:4px;transition:transform .1s}.l_V-RG_root[data-open] .l_V-RG_chevron{transform:rotate(180deg)}.l_V-RG_label{min-width:0;font-size:inherit;line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.l_V-RG_durationNumber{font-family:var(--ds-font-family-code);font-variant-numeric:tabular-nums}@media (prefers-reduced-motion:reduce){.l_V-RG_root,.l_V-RG_chevron{transition:none}}`},"src/client/chat/TurnUsagePanel.module.css":{text:context=>`.Q51KRG_root{min-width:0;display:inline-flex}.Q51KRG_root+.Q51KRG_root{margin-left:-6px}.Q51KRG_trigger{min-width:0;height:calc(28px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-tertiary);font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);font-variant-numeric:tabular-nums;line-height:calc(24px + var(--dsh-content-font-delta,0px));white-space:nowrap;cursor:pointer;background:0 0;border:none;align-items:center;gap:4px;padding:6px 8px;display:inline-flex}.Q51KRG_label{text-overflow:ellipsis;min-width:0;overflow:hidden}.Q51KRG_trigger svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px));flex:none}.Q51KRG_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary)}@media (hover:hover){.Q51KRG_trigger:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary)}}@media (width<=480px){.Q51KRG_trigger{width:calc(28px + var(--dsh-content-font-delta,0px));justify-content:center;padding:6px}.Q51KRG_trigger .Q51KRG_label{display:none}.Q51KRG_root+.Q51KRG_root{margin-left:0}}`},"src/client/chat/stat-dialog.module.css":{text:context=>`.bRhRbq_panel{z-index:1100;box-sizing:border-box;border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-menu);width:max-content;min-width:min(300px,100vw - 24px);max-width:min(440px,100vw - 24px);backdrop-filter:var(--dsw-menu-backdrop-filter);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);cursor:default;max-height:calc(100dvh - 12px - max(12px, var(--dsh-frame-overlay-top,12px)));--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2);position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:calc(anchor(top) + 8px);left:anchor(left);position-try-fallbacks:--dsh-stat-window, --dsh-stat-opposite, --dsh-stat-wide-opposite, --dsh-stat-tall, --dsh-stat-viewport;border:0;place-self:end start;height:fit-content;min-height:0;margin:0;padding:16px;font-size:12px;line-height:18px;position:fixed;right:12px;overflow:hidden auto}.bRhRbq_title{color:var(--dsw-alias-label-primary);justify-content:space-between;gap:16px;margin-bottom:8px;font-weight:500;display:flex}.bRhRbq_titleRule{border-top:.5px solid var(--dsw-alias-border-l2);margin-bottom:10px}.bRhRbq_titleValue{font-variant-numeric:tabular-nums}.bRhRbq_titleLabel{align-items:center;gap:6px;min-width:0;display:inline-flex}.bRhRbq_titleLabel svg{flex:none;width:14px;height:14px}.bRhRbq_details{color:var(--dsw-alias-label-tertiary);grid-template-columns:minmax(76px,auto) minmax(0,1fr);gap:6px 16px;margin:0;display:grid}.bRhRbq_details dt,.bRhRbq_details dd{min-width:0;margin:0}.bRhRbq_details dd{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;text-align:right}.bRhRbq_details .bRhRbq_route{overflow-wrap:anywhere}.bRhRbq_reasoning{color:var(--dsw-alias-label-tertiary);white-space:nowrap}@position-try --dsh-stat-window{position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:calc(anchor(top) + 8px);left:12px;right:12px;margin:0;align-self:safe end;justify-self:safe end}@position-try --dsh-stat-opposite{top:calc(anchor(bottom) + 8px);bottom:12px;align-self:start}@position-try --dsh-stat-wide-opposite{top:calc(anchor(bottom) + 8px);bottom:12px;left:12px;right:12px;align-self:start;justify-self:safe end}@position-try --dsh-stat-tall{position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:12px;left:anchor(left);right:12px;margin:0;align-self:safe start;justify-self:start}@position-try --dsh-stat-viewport{position-area:none;inset:max(12px, var(--dsh-frame-overlay-top,12px)) 12px 12px;margin:0;align-self:safe start;justify-self:safe end}`},"src/client/chat/TurnTailNodeView.module.css":{text:context=>`.TS9iAW_root{flex-direction:column;gap:16px;display:flex}.TS9iAW_actions{margin-top:4px;margin-left:-6px}`},"src/client/chat/TurnTriggerNodeView.module.css":{text:context=>`.oz9t_a_root{border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-turn-trigger-bg,var(--dsw-alias-markdown-code-block));min-width:0;transition:background-color .1s}@media (hover:hover){.oz9t_a_root:hover{background:var(--dsw-alias-turn-trigger-bg-hover,var(--dsw-alias-interactive-bg-hover))}}.oz9t_a_header{width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:10px;padding:12px 16px;transition:color .1s;display:flex}@media (hover:hover){.oz9t_a_header:hover{color:var(--dsw-alias-label-secondary)}}.oz9t_a_icon{color:inherit;flex:none;display:inline-flex}.oz9t_a_continuation{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));overflow-wrap:anywhere;align-items:center;gap:6px;padding:2px 0;display:flex}.oz9t_a_title{overflow-wrap:anywhere;min-width:0;font-size:var(--dsh-content-font-size,14px);flex:1}.oz9t_a_time{color:inherit;font:var(--dsw-font-xxs-12);flex:none;margin-left:auto}.oz9t_a_chevron,.oz9t_a_openChevron{color:inherit;flex:none}.oz9t_a_openChevron{transform:rotate(180deg)}.oz9t_a_body{padding:0 16px 12px 40px}.oz9t_a_explanation{color:var(--dsw-alias-label-secondary);font:var(--dsw-font-xxs-12);margin:8px 0}.oz9t_a_content{white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;font:var(--dsw-font-xxs-12);overflow:auto}@media (prefers-reduced-motion:reduce){.oz9t_a_root,.oz9t_a_header{transition:none}}`},"src/client/chat/StatsPills.module.css":{text:context=>`.bOPqQW_anchor{min-width:0;font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));display:inline-flex}.bOPqQW_pill{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;line-height:inherit;white-space:nowrap;background:0 0;border:none;align-items:center;gap:6px;padding:1px 8px;display:inline-flex}.bOPqQW_pill svg{flex:none;width:14px;height:14px}button.bOPqQW_pill{cursor:pointer}button.bOPqQW_pill[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}@media (hover:hover){button.bOPqQW_pill:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}}.bOPqQW_label{text-overflow:ellipsis;min-width:0;overflow:hidden}.bOPqQW_sep{color:var(--dsw-alias-separator-primary);margin:0 6px}`},"src/client/settings/PreferenceRow.module.css":{text:context=>`._2XZxNq_row{border-bottom:.5px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}._2XZxNq_rowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}@media (width<=767px){html:not([data-windows-titlebar]):not([data-platform=darwin]) ._2XZxNq_rowText{padding-right:16px}}._2XZxNq_title{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}._2XZxNq_desc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}._2XZxNq_selector{border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform);height:36px;font:inherit;color:var(--dsw-alias-label-primary);cursor:pointer;border:none;align-items:center;gap:12px;padding:0 14px;font-size:14px;line-height:22px;display:inline-flex}@media (hover:hover){._2XZxNq_selector:hover{background:var(--dsw-alias-interactive-bg-hover)}}._2XZxNq_chevron{flex:none}`}}})});
19
+ `,paragraphStart);if(newline!==-1&&newline<=paragraphEnd){const candidate=text.slice(paragraphStart,newline).trim();if(candidate!==``)summary=candidate}if(nextParagraph===null)return summary;paragraphStart=nextParagraph.index+nextParagraph[0].length}}const ReasoningRow=(0,react.memo)(function ReasoningRow({text:rawText,running,textInteractionSource=false,usePresentation,useDisclosure,renderSlot,t}){const{expanded,toggle}=useDisclosure();const{text,hidden}=(0,react.useMemo)(()=>{const text=reasoningText(rawText);return{text,hidden:text!==rawText&&text.trim()===``}},[rawText]);const summaryText=running?latestCompletedParagraphFirstLine(text):firstLine(text);const summary=(0,react.useMemo)(()=>summaryText.replaceAll(`**`,``),[summaryText]);const preview=usePresentation(policy=>!expanded&&summary!==``&&(running||policy.settledReasoningPreview));const collapsedContent=(0,react.useMemo)(()=>(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.separator,"data-shimmer-decoration":true,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.summary,"data-streaming":running||void 0,children:(0,react_jsx_runtime.jsx)(`span`,{className:ReasoningRow_module_css_default.summaryText,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.TextShimmer,{children:summary})})})]}),[running,summary]);const content=(0,react.useMemo)(()=>expanded?(0,react_jsx_runtime.jsx)(`div`,{className:ReasoningRow_module_css_default.thinkBody,"data-text-interaction-source":textInteractionSource&&!running?``:void 0,children:renderSlot(`conversation.chat.reasoning.body`,{rawText,text,running})}):void 0,[expanded,renderSlot,running,rawText,text,textInteractionSource]);if(hidden)return null;return(0,react_jsx_runtime.jsxs)(`div`,{className:ReasoningRow_module_css_default.root,"data-variant":`think`,"data-state":running?`running`:`ok`,"data-expanded":expanded||void 0,"data-preview":preview||void 0,children:[running&&(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,children:t(`row.running`)}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{rowClassName:ReasoningRow_module_css_default.row,leadingClassName:ReasoningRow_module_css_default.leading,titleClassName:ReasoningRow_module_css_default.title,icon:THINK_ICON,title:t(`message.think`),running,open:expanded,expandable:true,expandOnRowClick:true,onToggle:toggle,collapsedContent,children:content})]})});var AssistantMarkdown_module_css_default={"actions":`hWmORq_actions`,"body":`hWmORq_body`,"reasoning":`hWmORq_reasoning`,"root":`hWmORq_root`,"stopped":`hWmORq_stopped`};function localPathMediaUrl(base,value){let path;try{path=decodeURIComponent(value.split(/[?#]/u)[0]??``)}catch{return}return fileMediaUrl(base,path)}const AssistantMarkdown=(0,react.memo)(function AssistantMarkdown({blocks,streaming,textInteractionSource=false,interrupted,loadImage,groupPart,useDisclosure,reasoningHidden=false,usePresentation,revealProcess,mentions,renderSlot,useGroupAction,t}){const labels=(0,react.useMemo)(()=>markdownLabels(t),[t]);const pathImages=(0,react.useMemo)(()=>{return{resolve:value=>localPathMediaUrl(document.baseURI,value)}},[]);const truncatedLabel=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);const last=blocks.length-1;if(!(streaming||interrupted===true||blocks.some(block=>block.kind!==`tool-call`)))return null;const rendered=[];for(let i=0;i<blocks.length;i++){const block=blocks[i];if(block===void 0)continue;if(groupPart===`reasoning`&&block.kind!==`reasoning`)continue;if(groupPart===`response`&&block.kind===`reasoning`)continue;switch(block.kind){case`text`:rendered.push((0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownText,{text:block.text,streaming,labels,fileMentions:mentions,pathImages,textInteractionSource},i));break;case`reasoning`:if(block.text.trim()===``)break;rendered.push((0,react_jsx_runtime.jsx)(ProcessReasoning,{hidden:reasoningHidden,reveal:revealProcess,useGroupAction,children:(0,react_jsx_runtime.jsx)(ReasoningRow,{text:block.text,running:streaming&&i===last,usePresentation,useDisclosure,renderSlot,textInteractionSource,t})},i));break;case`image`:{const start=i;const group=[block];while(i+1<blocks.length){const next=blocks[i+1];if(next===void 0||next.kind!==`image`)break;group.push(next);i+=1}rendered.push((0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlot(`conversation.chat.message.images`,{images:group.map(({attachment})=>({attachment})),loadImage,align:`start`})},start));break}case`tool-call`:break;default:rendered.push((0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.unknownBlock`),payload:block.block,truncatedLabel},i))}}return(0,react_jsx_runtime.jsx)(`div`,{className:AssistantMarkdown_module_css_default.root,"data-streaming":streaming||void 0,children:(0,react_jsx_runtime.jsxs)(`div`,{className:AssistantMarkdown_module_css_default.body,children:[rendered,interrupted&&(groupPart===void 0||groupPart===`response`||!blocks.some(block=>block.kind!==`reasoning`&&block.kind!==`tool-call`))&&(0,react_jsx_runtime.jsx)(`span`,{className:AssistantMarkdown_module_css_default.stopped,children:t(`message.stopped`)})]})})});function ProcessReasoning({hidden,reveal,useGroupAction,children}){return(0,react_jsx_runtime.jsx)(`div`,{ref:useGroupAction(hidden,reveal??NOOP),className:AssistantMarkdown_module_css_default.reasoning,"data-turn-process-inline":hidden||void 0,children})}const NOOP=()=>{};const AssistantNodeView=(0,react.memo)(function AssistantNodeView({node,groupPart,useDisclosure,useGroupAction,useTurnData,turnProcess,openFile,loadImage,fileMentions,usePresentation,renderSlot,t,sessionId,useContextMenu,resolveFilePath}){const{getTriggerProps}=useContextMenu();const getFileTriggerProps=(0,react.useCallback)(path=>getTriggerProps(()=>({kind:`file`,value:{sessionId,path:resolveFilePath(path)}})),[getTriggerProps,sessionId,resolveFilePath]);const data=node.data;const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;const tail=useTurnData(`turn-tail`);const owner=(0,react.useMemo)(()=>{if(turn?.status!==`closed`||data.finalNode===void 0)return void 0;if(tail?.closing?.finalNode.seq!==data.finalNode.seq)return void 0;return{turn,seq:data.finalNode.seq,openFile}},[data.finalNode,openFile,tail,turn]);const mentions=(0,react.useMemo)(()=>owner===void 0?void 0:fileMentions(owner,getFileTriggerProps),[fileMentions,owner,getFileTriggerProps]);const keepReplies=usePresentation(policy=>policy.foldedReplies===`all`);const reasoningHidden=turnProcess!==void 0&&turnProcess.foldable&&(keepReplies?groupPart!==`reasoning`:turnProcess.spec.answerStep===data.step&&turnProcess.spec.inlineReasoning)&&!turnProcess.open;const revealProcess=(0,react.useCallback)(()=>{turnProcess?.setOpen(true)},[turnProcess]);return(0,react_jsx_runtime.jsx)(AssistantMarkdown,{blocks:data.blocks,groupPart,useDisclosure,streaming:data.status===`running`,textInteractionSource:data.status===`settled`&&data.finalNode?.messageId!==void 0,interrupted:data.status===`interrupted`,loadImage,reasoningHidden,useGroupAction,usePresentation,renderSlot,revealProcess,mentions,t})});const GenericCommandCard=(0,react.memo)(function GenericCommandCard({node,t,runningSummary}){const text=node.outcome?.text;const summary=node.outcome===null?runningSummary??t(`command.running`):text??(node.outcome.kind===`error`?t(`command.failed`):t(`command.done`));return(0,react_jsx_runtime.jsx)(CommandStatusRow,{title:node.name??t(`command.title`),state:node.outcome===null?`running`:node.outcome.kind===`error`?`error`:`ok`,summary,body:text!==void 0&&text.includes(`
20
+ `)?text:null,t})});function CompactionCommandCard({node,compaction,openCompaction,t}){if(compaction!==void 0)return(0,react_jsx_runtime.jsx)(CompactionItem,{node:compaction,openCompaction,title:t(`message.compaction.commandTitle`),fallbackSummary:node.outcome?.text??null,t});if(node.outcome!==null)return(0,react_jsx_runtime.jsx)(GenericCommandCard,{node,t});return(0,react_jsx_runtime.jsx)(GenericCommandCard,{node,t,runningSummary:t(`message.compaction.running`)})}const CommandNodeView=(0,react.memo)(function CommandNodeView({node,renderSlot,t}){const command=node.data;const owner=(0,react.useMemo)(()=>({node:command}),[command]);return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.callRow,children:renderSlot(`conversation.chat.commandview`,owner,{entryKey:command.name??``,fallback:(0,react_jsx_runtime.jsx)(GenericCommandCard,{...owner,t})})})});const ManualCompactionNodeView=(0,react.memo)(function ManualCompactionNodeView({node,openCompaction,useCompactionPreview,t}){const available=useCompactionPreview(value=>value);const data=node.data;return(0,react_jsx_runtime.jsx)(`div`,{className:ChatView_module_css_default.callRow,children:(0,react_jsx_runtime.jsx)(CompactionCommandCard,{node:data.command,...data.compaction===null?{}:{compaction:data.compaction},openCompaction:available?openCompaction:void 0,t})})});const ReasoningContent=(0,react.memo)(function ReasoningContent({text,running,labels,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.MarkdownText,{text,streaming:running,labels:(0,react.useMemo)(()=>labels??markdownLabels(t),[labels,t]),variant:`compact`})});function DefaultReasoningBody({text,running,renderFactorySlot}){return renderFactorySlot(`conversation.chat.reasoning.content`,{text,running})}function SystemPromptRow({text,update=false,message,t}){const[open,setOpen]=(0,react.useState)(false);const toggleOpen=(0,react.useCallback)(()=>{setOpen(value=>!value)},[]);const names=message?.changes.map(change=>change.name)??[];const summary=names.length>2?t(`message.systemPromptSections`,{count:names.length}):names.join(`, `);return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.DisclosureRow,{className:ContextInjectionRow_module_css_default.root,icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconBrowseOutlineRegular,{size:14}),chevronClassName:ContextInjectionRow_module_css_default.chevron,title:t(update?`message.systemPromptUpdate`:`message.systemPrompt`),collapsedContent:summary===``?void 0:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.sep,"aria-hidden":true}),(0,react_jsx_runtime.jsx)(`span`,{className:ContextInjectionRow_module_css_default.summary,"data-system-sources":true,children:summary})]}),keepContentWhenOpen:true,open,expandable:true,expandOnRowClick:true,onToggle:toggleOpen,children:(0,react_jsx_runtime.jsx)(`div`,{className:ContextInjectionRow_module_css_default.body,"data-system-prompt-body":true,children:message===void 0?(0,react_jsx_runtime.jsx)(OpaqueBody,{content:[{type:`text`,text}],source:null,t}):(0,react_jsx_runtime.jsx)(SystemSectionsBody,{message,t})})})}const SystemPromptNodeView=(0,react.memo)(function SystemPromptNodeView({node,t}){return(0,react_jsx_runtime.jsx)(SystemPromptRow,{text:node.data.text,update:node.data.update===true,message:node.data.message,t})});var TurnProcessNodeView_module_css_default={"chevron":`l_V-RG_chevron`,"durationNumber":`l_V-RG_durationNumber`,"label":`l_V-RG_label`,"root":`l_V-RG_root`};const TurnProcessNodeView=(0,react.memo)(function TurnProcessNodeView({node,turnProcess,t}){if(turnProcess===void 0)throw new Error(`turn-process node requires Turn process owner state`);const open=!turnProcess.foldable||turnProcess.open;const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;if(turn?.status!==`closed`)return null;const canCollapse=turnProcess.foldable&&turnProcess.hasContent&&!turnProcessAlwaysOpen(node);const reason=turn.end?.data.reason.kind;const stopped=reason===`aborted`||reason===`interrupted`;const elapsedMs=turn.start===void 0||turn.end===void 0?void 0:Math.max(1e3,turn.end.time-turn.start.time);const duration=elapsedMs===void 0||stopped||reason===`error`?void 0:formatRunDuration(elapsedMs,t);const label=stopped?t(`message.stopped`):reason===`error`?t(`message.turnProcess.failed`):duration===void 0?t(`message.turnProcess.worked`):t(`message.turnProcess.took`);const announcement=stopped?t(`message.stopped`):reason===`error`?t(`message.turnProcess.failed`):t(`message.turnProcess.worked`);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`span`,{className:accessibility_module_css_default.visuallyHidden,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:announcement}),(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:TurnProcessNodeView_module_css_default.root,"data-open":open||void 0,"data-turn-process":node.data.turn,"data-turn-process-messages":node.data.messageCount,"data-turn-process-tool-calls":node.data.toolCallCount,"data-turn-process-subagents":node.data.subagentCount,disabled:!canCollapse,"aria-expanded":turnProcess.hasContent?open:void 0,onClick:event=>{event.currentTarget.focus();turnProcess.setOpen(!open)},children:[(0,react_jsx_runtime.jsxs)(`span`,{className:TurnProcessNodeView_module_css_default.label,children:[label,duration?.map((part,index)=>(0,react_jsx_runtime.jsx)(`span`,{className:part.numeric?TurnProcessNodeView_module_css_default.durationNumber:void 0,children:part.text},index))]}),canCollapse&&(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{className:TurnProcessNodeView_module_css_default.chevron})]})]})});function formatTokens(value,t){const scaled=candidate=>candidate>=100?String(Math.round(candidate)):String(Math.round(candidate*10)/10);if(value<1e3)return String(value);if(value<1e6)return t(`number.thousand`,{value:scaled(value/1e3)});return t(`number.million`,{value:scaled(value/1e6)})}function formatExactTokens(value,t){const digits=String(value);const groups=[];for(let end=digits.length;end>0;end-=3)groups.unshift(digits.slice(Math.max(0,end-3),end));return groups.join(t(`number.groupSeparator`))}function roundedPercentUnits(cacheReadTokens,denominator,decimalPlaces){const scale=(decimalPlaces===0?1:10)*100;const doubledScale=scale*2;const denominatorQuotient=Math.floor(denominator/doubledScale);const denominatorRemainder=denominator%doubledScale;let lower=0;let upper=scale;while(lower<upper){const candidate=Math.floor((lower+upper+1)/2);const factor=candidate*2-1;if(cacheReadTokens>=factor*denominatorQuotient+Math.ceil(factor*denominatorRemainder/doubledScale))lower=candidate;else upper=candidate-1}return lower}function displayPercentUnits(units,decimalPlaces){if(decimalPlaces===0)return String(units);const whole=Math.floor(units/10);const tenths=units%10;return tenths===0?String(whole):`${whole}.${tenths}`}function formatCacheHitPercent(cacheReadTokens,promptTokens,decimalPlaces=0){if(promptTokens===0)return null;const missedInputTokens=promptTokens-cacheReadTokens;if(missedInputTokens===0)return`100`;const roundedUnits=roundedPercentUnits(cacheReadTokens,promptTokens,decimalPlaces);if(roundedUnits<(decimalPlaces===0?100:1e3))return displayPercentUnits(roundedUnits,decimalPlaces);let distinguishingPlaces=1;let scaledDoubleGap=missedInputTokens*200;const denominatorTens=Math.floor(promptTokens/10);while(scaledDoubleGap<=denominatorTens){scaledDoubleGap*=10;distinguishingPlaces+=1}const denominatorOnes=promptTokens%10;let roundedLoss=5;for(let loss=1;loss<5;loss+=1){const factor=loss*2+1;const threshold=factor*denominatorTens+Math.floor(factor*denominatorOnes/10);if(scaledDoubleGap<=threshold){roundedLoss=loss;break}}return`99.${`9`.repeat(distinguishingPlaces-1)}${10-roundedLoss}`}function useStatDialog(){const[open,setOpen]=(0,react.useState)(false);const rootRef=(0,react.useRef)(null);const panelRef=(0,react.useRef)(null);const anchorName=`--dsh-stat-${(0,react.useId)().replace(/[^\w-]/g,``)}`;(0,_deepseek_ai_dsh_client_ui_primitives_client.useDismissOnOutsidePointer)(rootRef,open,setOpen,panelRef);(0,react.useEffect)(()=>{if(!open)return;const onKeyDown=e=>{if(e.key===`Escape`)setOpen(false)};const onClick=e=>{if(e.target instanceof Node&&rootRef.current?.contains(e.target)!==true&&panelRef.current?.contains(e.target)!==true)setOpen(false)};document.addEventListener(`keydown`,onKeyDown);document.addEventListener(`click`,onClick,true);return()=>{document.removeEventListener(`keydown`,onKeyDown);document.removeEventListener(`click`,onClick,true)}},[open,setOpen]);return{open,setOpen,rootRef,panelRef,anchorName}}var TurnUsagePanel_module_css_default={"label":`Q51KRG_label`,"root":`Q51KRG_root`,"trigger":`Q51KRG_trigger`};var stat_dialog_module_css_default={"details":`bRhRbq_details`,"panel":`bRhRbq_panel`,"reasoning":`bRhRbq_reasoning`,"route":`bRhRbq_route`,"title":`bRhRbq_title`,"titleLabel":`bRhRbq_titleLabel`,"titleRule":`bRhRbq_titleRule`,"titleValue":`bRhRbq_titleValue`};function formatCompactCount(value,t){return t(`message.turnUsage.count`,{count:formatTokens(value,t)})}function formatExactCount(value,t){return t(`message.turnUsage.count`,{count:formatExactTokens(value,t)})}function TurnUsagePanel({usage,t}){const{open,setOpen,rootRef,panelRef,anchorName}=useStatDialog();const cacheHit=usage.cacheReadTokens===void 0?null:formatCacheHitPercent(usage.cacheReadTokens,usage.totalTokens-usage.outputTokens,1);const total=formatCompactCount(usage.totalTokens,t);const routes=usage.routes?.map(route=>`${route.provider}/${route.model}`).join(`, `)??``;return(0,react_jsx_runtime.jsxs)(`span`,{ref:rootRef,style:{anchorName},className:TurnUsagePanel_module_css_default.root,children:[(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:TurnUsagePanel_module_css_default.trigger,"aria-haspopup":`dialog`,"aria-expanded":open,onClick:()=>{setOpen(!open)},children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{}),(0,react_jsx_runtime.jsx)(`span`,{className:TurnUsagePanel_module_css_default.label,children:t(`message.turnUsage.consumed`,{total})})]}),open&&(0,react_dom.createPortal)((0,react_jsx_runtime.jsxs)(`div`,{ref:panelRef,className:stat_dialog_module_css_default.panel,role:`dialog`,"aria-label":t(`message.turnUsage.title`),style:{positionAnchor:anchorName},children:[(0,react_jsx_runtime.jsxs)(`div`,{className:stat_dialog_module_css_default.title,children:[(0,react_jsx_runtime.jsxs)(`span`,{className:stat_dialog_module_css_default.titleLabel,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{}),t(`message.turnUsage.title`)]}),(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.titleValue,children:formatExactCount(usage.totalTokens,t)})]}),(0,react_jsx_runtime.jsx)(`div`,{className:stat_dialog_module_css_default.titleRule,"aria-hidden":true}),(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-turn-usage-details":true,children:[routes!==``&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.model`)}),(0,react_jsx_runtime.jsx)(`dd`,{className:stat_dialog_module_css_default.route,children:routes})]}),cacheHit!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheHit`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:`${cacheHit}%`})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.input`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.uncachedInputTokens,t)}),usage.cacheReadTokens!==void 0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheRead`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.cacheReadTokens,t)})]}),usage.cacheWriteTokens!==void 0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheWrite`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatExactCount(usage.cacheWriteTokens,t)})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.output`)}),(0,react_jsx_runtime.jsxs)(`dd`,{children:[formatExactCount(usage.outputTokens,t),usage.reasoningTokens!==void 0&&(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.reasoning,children:t(`message.turnUsage.reasoning`,{tokens:formatExactCount(usage.reasoningTokens,t)})})]})]})]}),document.body)]})}function assistantText(blocks){return blocks.flatMap(block=>block.kind===`text`?[block.text]:[]).join(``)}var TurnTailNodeView_module_css_default={"actions":`TS9iAW_actions`,"root":`TS9iAW_root`};function lastContent(snapshot,turn,skipWarning){const keys=snapshot.locations.getTurn(turn);for(let index=keys.length-1;index>=0;index--){const node=snapshot.nodes.get(keys[index]);if(node===void 0||node.kind===`turn-tail`||node.kind===`turn-process`||skipWarning&&node.kind===`turn-max-tokens`)continue;return node}}const TurnTailNodeView=(0,react.memo)(function TurnTailNodeView({node,openFile,forkAt,renderSlot,t,useAccess,useChat,usePerformanceUsage}){const detailed=usePerformanceUsage(mode=>mode)===`detailed`;const forkAllowed=useAccess(`session/fork`);const data=node.data;const hasLaterChatNode=useChat(snapshot=>(lastContent(snapshot,data.turn,true)?.anchorSeq??-1)>(data.closing?.finalNode.seq??data.seq));const endsWithResponse=useChat(snapshot=>{if(snapshot.timeline.turnOrder.at(-1)!==data.turn)return false;const last=lastContent(snapshot,data.turn,false);const block=last?.kind===`assistant-step`?last.data.blocks.findLast(candidate=>candidate.kind!==`text`&&candidate.kind!==`reasoning`||candidate.text.trim()!==``):void 0;return block!==void 0&&hasAssistantReplyContent([block])});const branchAction=(0,react.useCallback)(()=>{forkAt(data.seq)},[data.seq,forkAt]);const turn=node.location.kind===`turn`||node.location.kind===`step`?node.location.turn:void 0;if(turn===void 0)return null;const closing=data.closing;const tail=renderSlot(`conversation.chat.turnTail`,{turn,seq:closing?.finalNode.seq??data.seq,openFile});if(closing===null)return tail===null?null:(0,react_jsx_runtime.jsx)(`div`,{className:TurnTailNodeView_module_css_default.root,"data-turn-tail":data.turn,children:tail});const messageId=closing.finalNode.messageId;const assistantActions=messageId===void 0?null:renderSlot(`conversation.chat.assistant-actions`,{messageId});return(0,react_jsx_runtime.jsxs)(`div`,{className:TurnTailNodeView_module_css_default.root,"data-turn-tail":data.turn,"data-actions-reveal":endsWithResponse?`always`:`hover`,children:[tail,(0,react_jsx_runtime.jsx)(MessageIconActions,{text:assistantText(closing.blocks),time:closing.time,clock:`end`,onBranch:forkAllowed?branchAction:void 0,branchUnavailable:data.branchUnavailable||hasLaterChatNode,className:TurnTailNodeView_module_css_default.actions,extraActions:assistantActions,usageAction:detailed&&data.tokenUsage!==void 0?(0,react_jsx_runtime.jsx)(TurnUsagePanel,{usage:data.tokenUsage,t}):null,t})]})});function record(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{}}function field(source,key){return typeof source[key]===`string`?source[key]:``}function subagentTitle(reason){if(typeof reason!==`string`||reason===``)return`message.trigger.subagent`;switch(reason){case`completed`:return`message.trigger.subagent.completed`;case`aborted`:return`message.trigger.subagent.aborted`;case`error`:return`message.trigger.subagent.error`;case`max-tokens`:return`message.trigger.subagent.maxTokens`;case`refusal`:return`message.trigger.subagent.refusal`;default:return`message.trigger.subagent.unknown`}}function turnTriggerDetails(node){const source=record(node.source);const kind=field(source,`kind`);let title=`message.trigger.request`;let icon=`request`;switch(kind){case`retry`:if(node.content.length===0)return{title:`message.continuation.requested`,icon:`continue`,compact:true};break;case`goal`:title=`message.trigger.goal`;icon=`goal`;break;case`agent-message`:title=`message.trigger.agent`;icon=`agent`;break;case`team-message`:title=`message.trigger.team`;icon=`team`;break;case`subagent-settled`:title=subagentTitle(source.stopReason);icon=`subagent`;break;case`webhook`:{const github=field(source,`provider`)===`github`;title=github?`message.trigger.github`:`message.trigger.webhook`;icon=github?`github`:`webhook`;break}case`schedule`:title=`message.trigger.schedule`;icon=`schedule`;break;case`tool-jobs`:title=`message.trigger.job`;icon=`job`;break;case`cordis-host-runner`:title=`message.trigger.plugin`;icon=`plugin`;break;default:break}return{title,icon}}var TurnTriggerNodeView_module_css_default={"body":`oz9t_a_body`,"chevron":`oz9t_a_chevron`,"content":`oz9t_a_content`,"continuation":`oz9t_a_continuation`,"explanation":`oz9t_a_explanation`,"header":`oz9t_a_header`,"icon":`oz9t_a_icon`,"openChevron":`oz9t_a_openChevron`,"root":`oz9t_a_root`,"time":`oz9t_a_time`,"title":`oz9t_a_title`};const TRIGGER_ICONS={continue:_deepseek_ai_dsh_client_ui_primitives_client.IconPlayOutlineRegular,request:_deepseek_ai_dsh_client_ui_primitives_client.IconContextInjectionOutlineRegular,goal:_deepseek_ai_dsh_client_ui_primitives_client.IconGoalOutlineRegular,agent:_deepseek_ai_dsh_client_ui_primitives_client.IconPaperPlaneOutlineRegular,team:_deepseek_ai_dsh_client_ui_primitives_client.IconAgentPresetOutlineRegular,subagent:_deepseek_ai_dsh_client_ui_primitives_client.IconUsersOutlineRegular,github:_deepseek_ai_dsh_client_ui_primitives_client.IconBranchOutlineRegular,webhook:_deepseek_ai_dsh_client_ui_primitives_client.IconGlobeOutlineRegular,schedule:_deepseek_ai_dsh_client_ui_primitives_client.IconClockOutlineRegular,job:_deepseek_ai_dsh_client_ui_primitives_client.IconQueueOutlineRegular,plugin:_deepseek_ai_dsh_client_ui_primitives_client.IconCordisPluginOutlineRegular};function TurnTriggerNodeView({node,t}){const[open,setOpen]=(0,react.useState)(false);const bodyId=(0,react.useId)();const details=turnTriggerDetails(node.data);const TriggerIcon=TRIGGER_ICONS[details.icon];if(details.compact)return(0,react_jsx_runtime.jsxs)(`div`,{className:TurnTriggerNodeView_module_css_default.continuation,"data-generation-continuation":true,children:[(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.icon,"aria-hidden":true,children:(0,react_jsx_runtime.jsx)(TriggerIcon,{size:14})}),(0,react_jsx_runtime.jsx)(`span`,{children:t(details.title)})]});const date=new Date(node.data.time);const time=formatMessageClock(node.data.time,t);return(0,react_jsx_runtime.jsxs)(`section`,{className:TurnTriggerNodeView_module_css_default.root,"data-turn-trigger":true,children:[(0,react_jsx_runtime.jsxs)(`button`,{className:TurnTriggerNodeView_module_css_default.header,type:`button`,"aria-expanded":open,"aria-controls":bodyId,onClick:()=>{setOpen(!open)},children:[(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.icon,"aria-hidden":true,children:(0,react_jsx_runtime.jsx)(TriggerIcon,{size:14})}),(0,react_jsx_runtime.jsx)(`span`,{className:TurnTriggerNodeView_module_css_default.title,children:t(details.title)}),(0,react_jsx_runtime.jsx)(`time`,{className:TurnTriggerNodeView_module_css_default.time,dateTime:date.toISOString(),children:time}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{size:12,className:open?TurnTriggerNodeView_module_css_default.openChevron:TurnTriggerNodeView_module_css_default.chevron})]}),open&&(0,react_jsx_runtime.jsxs)(`div`,{id:bodyId,className:TurnTriggerNodeView_module_css_default.body,children:[(0,react_jsx_runtime.jsx)(`p`,{className:TurnTriggerNodeView_module_css_default.explanation,children:t(`message.trigger.explanation`)}),(0,react_jsx_runtime.jsx)(`div`,{className:TurnTriggerNodeView_module_css_default.content,children:(0,react_jsx_runtime.jsx)(NoticeBody,{content:node.data.content,source:node.data.source,t})})]})]})}function registerChatNodeRenderers(ctx,performanceUsage){const injectCompaction=compactionRows(ctx);ctx.effect(()=>ctx.slots.registerFactory({name:`conversation.chat.reasoning.content`,scope:`root`,locale:NS},ReasoningContent));ctx.slots.inject(`conversation.chat.reasoning.body`,()=>ctx.slots.register({name:`conversation.chat.reasoning.body`,priority:100},DefaultReasoningBody));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`user`,locale:NS,children:{"conversation.chat.user.before":{kind:`chain`,scope:`session`},"conversation.chat.user-actions":{kind:`list`,scope:`session`}}},UserMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`steering`,locale:NS,inject:()=>({renderSlotChain:()=>null,renderSlot:()=>null})},UserMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`context`,locale:NS},ContextMessageNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-trigger`,locale:NS},TurnTriggerNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`system-prompt`,locale:NS},SystemPromptNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`assistant-step`,locale:NS,children:{"conversation.chat.reasoning.body":{kind:`single`,scope:`session`},"conversation.chat.message.images":{kind:`single`,scope:`session`}},inject:sessionId=>({resolveFilePath:sessionFilePath(ctx,sessionId),fileMentions:(owner,getFileTriggerProps)=>ctx.get(`chatFileMentions`)?.forClosing(owner,sessionId,getFileTriggerProps)})},AssistantNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`command`,locale:NS,children:{"conversation.chat.commandview":{kind:`keyed`,scope:`session`}}},CommandNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`manual-compaction`,locale:NS,inject:injectCompaction},ManualCompactionNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`compaction`,locale:NS,inject:injectCompaction},CompactionNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`inherited-history`,locale:NS},InheritedHistoryNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`model-retry`,locale:NS},RetryNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-error`,locale:NS},TurnErrorNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-max-tokens`,locale:NS},TurnMaxTokensNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-process`,locale:NS},TurnProcessNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`turn-tail`,locale:NS,inject:()=>({hooks:{performanceUsage}}),children:{"conversation.chat.turnTail":{kind:`list`,scope:`session`},"conversation.chat.assistant-actions":{kind:`list`,scope:`session`}}},TurnTailNodeView));ctx.slots.inject(`conversation.chat.node`,()=>ctx.slots.register({name:`conversation.chat.node`,key:`unknown`,locale:NS},UnknownNodeView))}const EMPTY_LABELS=[];function UserContent({content,loadImage,facts,interactive=false,ellipsis=false,renderSlot,renderFactorySlot,t}){const{text,attachments,extraBlocks,referenceLabels=EMPTY_LABELS}=content;const compactImages=attachments.length>1;const truncated=(0,react.useCallback)(total=>t(`json.truncated`,{total}),[t]);const showBubble=text!==``||extraBlocks.length>0;return(0,react_jsx_runtime.jsxs)(`div`,{className:MessageItem_module_css_default.userStack,children:[attachments.length>0&&(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.attachmentRow,"data-message-attachments":true,children:attachments.map((attachment,index)=>attachment.type===`image`?(0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlot(`conversation.chat.user.images`,{images:[attachment.image],loadImage,align:`end`,compact:compactImages})},`image:${index}`):(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.fileCard,title:attachment.file.name,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FileTypeIcon,{path:attachment.file.name,className:MessageItem_module_css_default.fileIcon}),(0,react_jsx_runtime.jsxs)(`span`,{className:MessageItem_module_css_default.fileContent,children:[(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.fileName,children:attachment.file.name}),(0,react_jsx_runtime.jsx)(`span`,{className:MessageItem_module_css_default.fileMeta,children:[(0,_deepseek_ai_dsh_client_ui_primitives_client.fileExtension)(attachment.file.name).toUpperCase().slice(0,8),(0,_deepseek_ai_dsh_client_ui_primitives_client.fileSizeText)(attachment.file.bytes)].filter(Boolean).join(` `)})]})]},`file:${index}`))}),showBubble&&(0,react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives_client.UserMessageBubble,{"data-message-bubble":``,"data-text-interaction-source":``,children:[renderFactorySlot(`conversation.user.text`,{text,facts,interactive,ellipsis}),extraBlocks.map((block,index)=>(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.JsonBlock,{label:t(`message.extraBlock`),payload:block,truncatedLabel:truncated},index))]}),referenceLabels.length>0&&(0,react_jsx_runtime.jsx)(`div`,{className:MessageItem_module_css_default.referenceSummary,children:t(`message.referenceSummary`,{labels:referenceLabels.join(t(`message.referenceSeparator`))})})]})}function usageOutputTokens(usage){if(typeof usage!==`object`||usage===null)return null;const value=usage.outputTokens;return typeof value===`number`&&Number.isFinite(value)&&value>=0?value:null}function assistantStepReading(node){const timing=node.timing;return{ttftMs:timing!==void 0&&timing.stepStartTime!==null&&timing.firstTokenTime!==null?Math.max(0,timing.firstTokenTime-timing.stepStartTime):null,decodeMs:timing!==void 0&&timing.firstTokenTime!==null?Math.max(0,timing.completedTime-timing.firstTokenTime):null,outputTokens:usageOutputTokens(node.usage)}}var StatsPills_module_css_default={"anchor":`bOPqQW_anchor`,"label":`bOPqQW_label`,"pill":`bOPqQW_pill`,"sep":`bOPqQW_sep`};function deriveStats(nodes){const turns=new Set;let steps=0;let llmMs=0;let toolMs=0;let ttftMs=0;let ttftSteps=0;let decodeMs=0;let decodeTokens=0;for(const node of nodes){if(node.kind===`tool-result`){if(node.callTime!==null)toolMs+=Math.max(0,node.time-node.callTime);continue}if(node.kind!==`assistant`)continue;turns.add(node.turn);steps+=1;if(node.timing!==void 0&&node.timing.stepStartTime!==null)llmMs+=Math.max(0,node.timing.completedTime-node.timing.stepStartTime);const reading=assistantStepReading(node);if(reading.ttftMs!==null){ttftMs+=reading.ttftMs;ttftSteps+=1}if(reading.decodeMs!==null&&reading.outputTokens!==null){decodeMs+=reading.decodeMs;decodeTokens+=reading.outputTokens}}return{turns:turns.size,steps,llmMs,toolMs,ttftMs,ttftSteps,decodeMs,decodeTokens}}function formatDuration(ms,t){const s=ms/1e3;if(s<60)return t(`duration.compactSeconds`,{seconds:Math.round(s*10)/10});const whole=Math.round(s);return t(`duration.compactMinutes`,{minutes:Math.floor(whole/60),seconds:whole%60})}function cacheHitPercent(usage){const denominator=billedInputTokens(usage);return formatCacheHitPercent(usage.cacheReadTokens,denominator)}function billedInputTokens(usage){return usage.uncachedInputTokens+usage.cacheReadTokens+usage.cacheWriteTokens}function exactCount(value,t){return t(`message.turnUsage.count`,{count:formatExactTokens(value,t)})}function reading(first,second){if(second===null)return{label:first,text:first};return{label:(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[first,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.sep,"aria-hidden":true,children:`·`}),second]}),text:`${first} · ${second}`}}function useSessionStats(useChat,useProjection){const settledNodes=useChat(s=>s.legacy.nodes);const projected=useProjection(`sessionStats`);return(0,react.useMemo)(()=>projected??deriveStats(settledNodes),[projected,settledNodes])}function decodeSpeed(stats,t){return t(`message.tokensPerSecond`,{tps:formatTokensPerSecond(stats.decodeTokens/(stats.decodeMs/1e3))})}const FULL_READING_TOOLTIP={side:`top`,portal:true,delayMs:200,onlyWhenClipped:true};function PlainPill({stat,icon,label,text}){return(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.anchor,"data-composer-stat":stat,children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:text,...FULL_READING_TOOLTIP,openOnClick:true,children:(0,react_jsx_runtime.jsxs)(`span`,{className:StatsPills_module_css_default.pill,children:[icon,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.label,children:label})]})})})}function DialogPill({stat,icon,label,text,title,titleValue,children}){const{open,setOpen,rootRef,panelRef,anchorName}=useStatDialog();return(0,react_jsx_runtime.jsxs)(`span`,{ref:rootRef,style:{anchorName},className:StatsPills_module_css_default.anchor,"data-composer-stat":stat,children:[(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Tooltip,{label:text,...FULL_READING_TOOLTIP,disabled:open,children:(0,react_jsx_runtime.jsxs)(`button`,{type:`button`,className:StatsPills_module_css_default.pill,"aria-haspopup":`dialog`,"aria-expanded":open,"aria-label":text,onClick:()=>{setOpen(!open)},children:[icon,(0,react_jsx_runtime.jsx)(`span`,{className:StatsPills_module_css_default.label,children:label})]})}),open&&(0,react_dom.createPortal)((0,react_jsx_runtime.jsxs)(`div`,{ref:panelRef,className:stat_dialog_module_css_default.panel,role:`dialog`,"aria-label":title,style:{positionAnchor:anchorName},children:[(0,react_jsx_runtime.jsxs)(`div`,{className:stat_dialog_module_css_default.title,children:[(0,react_jsx_runtime.jsxs)(`span`,{className:stat_dialog_module_css_default.titleLabel,children:[icon,title]}),titleValue!==void 0&&(0,react_jsx_runtime.jsx)(`span`,{className:stat_dialog_module_css_default.titleValue,children:titleValue})]}),(0,react_jsx_runtime.jsx)(`div`,{className:stat_dialog_module_css_default.titleRule,"aria-hidden":true}),children]}),document.body)]})}const ActivityPill=(0,react.memo)(function ActivityPill({useChat,useProjection,usePerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const stats=useSessionStats(useChat,useProjection);const speed=stats.decodeMs>0?decodeSpeed(stats,t):null;const icon=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconGaugeOutlineRegular,{});if(mode===`compact`)return speed===null?null:(0,react_jsx_runtime.jsx)(PlainPill,{stat:`activity`,icon,...reading(speed,null)});if(stats.steps===0)return null;const counts=t(`stats.counts`,{turns:stats.turns,steps:stats.steps});const content={stat:`activity`,icon,...reading(counts,speed)};if(stats.llmMs<=0&&stats.toolMs<=0&&stats.ttftSteps<=0&&speed===null)return(0,react_jsx_runtime.jsx)(PlainPill,{...content});return(0,react_jsx_runtime.jsx)(DialogPill,{...content,title:t(`stats.dialog.title`),titleValue:counts,children:(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-session-stats-details":true,children:[stats.llmMs>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.llmTime`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.llmMs,t)})]}),stats.toolMs>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.toolTime`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.toolMs,t)})]}),stats.ttftSteps>0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.ttft`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:formatDuration(stats.ttftMs/stats.ttftSteps,t)})]}),speed!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`stats.dialog.speed`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:speed})]})]})})});const UsagePill=(0,react.memo)(function UsagePill({useProjection,usePerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const usage=useProjection(`tokenUsage`);if(usage===void 0||billedInputTokens(usage)===0&&usage.outputTokens===0)return null;const cacheHit=cacheHitPercent(usage);const cacheHitText=cacheHit!==null?t(`stats.cacheHit`,{percent:cacheHit}):null;const icon=(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconDatabaseOutlineRegular,{});if(mode===`compact`)return cacheHitText===null?null:(0,react_jsx_runtime.jsx)(PlainPill,{stat:`usage`,icon,...reading(cacheHitText,null)});const total=billedInputTokens(usage)+usage.outputTokens;return(0,react_jsx_runtime.jsx)(DialogPill,{stat:`usage`,icon,...reading(t(`message.turnUsage.count`,{count:formatTokens(total,t)}),cacheHitText),title:t(`stats.dialog.usageTitle`),titleValue:exactCount(total,t),children:(0,react_jsx_runtime.jsxs)(`dl`,{className:stat_dialog_module_css_default.details,"data-session-stats-usage":true,children:[cacheHit!==null&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheHit`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:`${cacheHit}%`})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.input`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.uncachedInputTokens,t)}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheRead`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.cacheReadTokens,t)}),usage.cacheWriteTokens!==0&&(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.cacheWrite`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.cacheWriteTokens,t)})]}),(0,react_jsx_runtime.jsx)(`dt`,{children:t(`message.turnUsage.output`)}),(0,react_jsx_runtime.jsx)(`dd`,{children:exactCount(usage.outputTokens,t)})]})})});const CHAT_SYNTHETIC_SEQ_OFFSETS={interruptedAssistant:-.9,interruptedFollowup:-.8,processControl:-.1,maxTokensNotice:.05,finalizedFollowup:.1};function contextLocation(context){return context.start?.location??context.matches[0]?.location??{kind:`unresolved`}}function locationCoordinates(location){if(location.kind===`step`)return{turn:location.turn.turn,step:location.step.step};if(location.kind===`turn`)return{turn:location.turn.turn};return{}}function chatNode(context,kind,anchorSeq,data,options={}){return{key:context.key,kind,id:context.id,target:`chat`,anchorSeq,location:options.location??contextLocation(context),visibility:options.visibility??`visible`,groupTree:options.groupTree,data}}function asRecord(value){return typeof value===`object`&&value!==null&&!Array.isArray(value)?value:null}function readString(record,key){const value=record[key];return typeof value===`string`&&value.length>0?value:null}function collect(source,member,field){const list=source[member];if(!Array.isArray(list))return[];const seen=[];for(const entry of list){const record=asRecord(entry);const value=record===null?null:readString(record,field);if(value!==null&&!seen.includes(value))seen.push(value)}return seen}function joined(names){return names.length>0?names.join(`, `):null}const KNOWN_FORMS=[`instructions`,`catalog`,`snapshot`,`notice`,`relay`,`recall`];function contextForm(source){const record=asRecord(source);const form=record===null?null:readString(record,`form`);return form!==null&&KNOWN_FORMS.includes(form)?form:null}function contextProducer(source){const record=asRecord(source);const kind=record===null?null:readString(record,`kind`);if(record===null||kind===null)return{role:`inject`,label:null};switch(kind){case`session-reference`:return{role:`recall`,label:joined(collect(record,`references`,`label`))??kind};case`agent-instructions`:return{role:`inject`,label:joined(collect(record,`changes`,`path`))??kind};case`skill-invocation`:return{role:`inject`,label:readString(record,`name`)??kind};default:return{role:`inject`,label:kind}}}function sessionRecallLabels(source){const record=asRecord(source);if(record===null||readString(record,`kind`)!==`session-reference`)return[];return collect(record,`references`,`label`)}function skillInvocationName(source){const record=asRecord(source);if(record===null||readString(record,`kind`)!==`skill-invocation`)return null;return readString(record,`name`)}function toAssistantBlocks(content){return content.map(toAssistantBlock)}function toAssistantBlock(block){switch(block.type){case`text`:return{kind:`text`,text:block.text};case`reasoning`:return{kind:`reasoning`,text:block.text};case`image`:return{kind:`image`,attachment:block.attachment};case`tool-call`:return{kind:`tool-call`,callId:String(block.id),name:block.name,argsRaw:block.arguments};default:return{kind:`other`,block}}}function emptyAssistantBlock(blockType){switch(blockType){case`text`:return{kind:`text`,text:``};case`reasoning`:return{kind:`reasoning`,text:``};case`tool-call`:return{kind:`tool-call`,callId:``,name:``,argsRaw:``};default:return{kind:`other`,block:null}}}function displayFailure(failure){if(failure===null||typeof failure!==`object`)return{message:String(failure)};const record=failure;const code=typeof record.code===`string`?record.code:void 0;if(code===`AUTH`)return{code,message:``};return{...code===void 0?{}:{code},message:typeof record.message===`string`?record.message:JSON.stringify(failure)}}function isTokenDelta(chunk){switch(chunk.type){case`text-delta`:case`reasoning-delta`:return chunk.text!==``;case`tool-call-delta`:return chunk.argumentsDelta!==``||chunk.name!==void 0;default:return false}}function initialState(turn,step){return{turn,step,blocks:[],visibleByIndex:[],visibleBlocks:0,firstVisibleSeq:void 0,firstVisibleTime:void 0,firstTokenTime:void 0,final:void 0,usage:void 0}}function compactBlocks(blocks){return blocks.filter(block=>block!==void 0)}function blockIsVisible(block){if(block===void 0||block.kind===`tool-call`)return false;if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true}function hasVisibleContent(blocks){return blocks.some(blockIsVisible)}function hasInterruptionEvidence(blocks){return blocks.some(block=>{if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true})}function resetForRetry(state){return{...initialState(state.turn,state.step),firstTokenTime:state.firstTokenTime}}function updateChunk(state,chunk,seq,time){if(chunk.type===`tool-call-delta`){const previous=state.blocks[chunk.index];if(previous?.kind===`tool-call`&&previous.callId!==``&&(chunk.name===void 0||chunk.name===previous.name)&&(state.firstTokenTime!==void 0||!isTokenDelta(chunk)))return state}const blocks=[...state.blocks];let changedIndex=-1;let previousVisible=false;let nextVisible=false;switch(chunk.type){case`block-start`:changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]=emptyAssistantBlock(chunk.blockType);nextVisible=blockIsVisible(blocks[chunk.index]);break;case`text-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`text`,text:(previous?.kind===`text`?previous.text:``)+chunk.text};nextVisible=previous?.kind===`text`&&previousVisible||chunk.text.trim()!==``;break}case`reasoning-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`reasoning`,text:(previous?.kind===`reasoning`?previous.text:``)+chunk.text};nextVisible=previous?.kind===`reasoning`&&previousVisible||chunk.text.trim()!==``;break}case`tool-call-delta`:{const previous=blocks[chunk.index];changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]={kind:`tool-call`,callId:(previous?.kind===`tool-call`?previous.callId:``)||String(chunk.id),name:chunk.name??(previous?.kind===`tool-call`?previous.name:``),argsRaw:previous?.kind===`tool-call`?previous.argsRaw:``};break}case`block-end`:changedIndex=chunk.index;previousVisible=state.visibleByIndex[chunk.index]===true;blocks[chunk.index]=toAssistantBlock(chunk.block);nextVisible=blockIsVisible(blocks[chunk.index]);break;case`usage`:return{...state,usage:chunk.usage};default:return state}const visibleBlocks=state.visibleBlocks-Number(previousVisible)+Number(nextVisible);let visibleByIndex=state.visibleByIndex;if(previousVisible!==nextVisible){const next=[...visibleByIndex];next[changedIndex]=nextVisible;visibleByIndex=next}const firstToken=isTokenDelta(chunk);return{...state,blocks,visibleByIndex,visibleBlocks,...visibleBlocks>0&&state.firstVisibleSeq===void 0?{firstVisibleSeq:seq,firstVisibleTime:time}:{},...firstToken&&state.firstTokenTime===void 0?{firstTokenTime:time}:{}}}function settleMessage(state,match,event){const blocks=toAssistantBlocks(event.data.message.content);const visibleByIndex=blocks.map(blockIsVisible);return{...state,blocks,visibleByIndex,visibleBlocks:visibleByIndex.reduce((count,visible)=>count+Number(visible),0),final:match,usage:event.data.usage}}function closedBoundary(location){if(location.kind===`step`&&location.step.status===`closed`&&location.step.end!==void 0)return location.step.end;if((location.kind===`step`||location.kind===`turn`)&&location.turn.status===`closed`&&location.turn.end!==void 0)return location.turn.end}function finalNode(state,context){const final=state.final;if(final?.event.type===`assistant/message`){const event=final.event;return{kind:`assistant`,seq:event.seq,messageId:event.data.message.id,time:event.time,turn:state.turn,step:state.step,blocks:toAssistantBlocks(event.data.message.content),usage:event.data.usage,timing:{stepStartTime:context.start?.event.time??null,firstTokenTime:state.firstTokenTime??null,completedTime:event.time},...event.data.interrupted===true?{interrupted:true}:{}}}const location=context.start?.location??context.matches.at(-1)?.location;const boundary=location===void 0?void 0:closedBoundary(location);if(boundary===void 0)return void 0;const blocks=compactBlocks(state.blocks);if(!hasInterruptionEvidence(blocks))return void 0;return{kind:`assistant`,seq:boundary.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedAssistant,time:boundary.time,turn:state.turn,step:state.step,blocks,interrupted:true}}function fallbackState$5(context){let state;for(const match of context.matches){if(match.event.type===`assistant/live-chunk`){state??=initialState(match.event.data.turn,match.event.data.step);state=updateChunk(state,match.event.data.chunk,match.event.seq,match.event.time);continue}if(match.event.type===`assistant/message`){state??=initialState(match.event.data.turn,match.event.data.step);state=settleMessage(state,match,match.event);continue}if(match.event.type===`llm/retry`&&state!==void 0)state=resetForRetry(state)}return state}function projectAssistant(context){const state=context.state??fallbackState$5(context);if(state===void 0)return void 0;const settled=finalNode(state,context);const blocks=settled?.blocks??compactBlocks(state.blocks);const visible=settled===void 0?state.visibleBlocks>0:hasVisibleContent(blocks);const status=settled?.interrupted===true?`interrupted`:settled===void 0?`running`:`settled`;const anchorSeq=(settled?.interrupted===true?settled.seq:state.firstVisibleSeq??settled?.seq)??context.matches[0]?.event.seq??0;const time=settled?.time??state.firstVisibleTime??context.matches[0]?.event.time??0;return{anchorSeq,visible,settled,data:{status,turn:state.turn,step:state.step,blocks,time,...state.usage===void 0?{}:{usage:state.usage},...settled===void 0?{}:{finalNode:settled}}}}function publishedAssistantData(context){const location=context.start?.location??context.matches.at(-1)?.location;return location?.kind===`step`?location.step.data.get(`assistant-step`):void 0}const assistantDefinition={kind:`assistant-step`,target:`chat`,match:event=>{if(event.type===`step/start`)return{id:`${event.data.turn}:${event.data.step}`,role:`start`};if(event.type===`assistant/live-chunk`||event.type===`assistant/message`&&event.surfaceOp===`append`)return{id:`${event.data.turn}:${event.data.step}`,role:`update`};if(event.type===`llm/retry`)return{id:`${event.data.turn}:${event.data.step}`,role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`step/start`)throw new Error(`assistant-step start requires step/start`);return initialState(match.event.data.turn,match.event.data.step)},update:(context,match)=>{if(match.event.type===`assistant/live-chunk`)return updateChunk(context.state,match.event.data.chunk,match.event.seq,match.event.time);if(match.event.type===`assistant/message`)return settleMessage(context.state,match,match.event);if(match.event.type===`llm/retry`)return resetForRetry(context.state);return context.state},publication:match=>{if(match.event.type===`step/start`)return`none`;if(match.event.type!==`assistant/live-chunk`)return`immediate`;const type=match.event.data.chunk.type;return type===`usage`||type===`finish`?`none`:`animation-frame`},buildLocationData:(context,scope)=>{if(scope!==`step`)return null;const projected=projectAssistant(context);if(projected===void 0)return null;return{kind:`step`,turn:projected.data.turn,step:projected.data.step,key:`assistant-step`,value:projected.data}},buildViewNode:context=>{const current=context.current.get(`chat`);const state=context.state??fallbackState$5(context);const data=publishedAssistantData(context);if(state===void 0||data===void 0)return current==null?null:{...current,visibility:`hidden`};const settled=data.finalNode;const visible=settled===void 0?state.visibleBlocks>0:hasVisibleContent(data.blocks);if(settled===void 0&&!visible&&current==null)return null;return chatNode(context,`assistant-step`,(settled?.interrupted===true?settled.seq:state.firstVisibleSeq??settled?.seq)??context.matches[0]?.event.seq??0,data,{visibility:settled?.interrupted===true||visible?`visible`:`hidden`})}};function registerAssistantConversationNode(ctx){const match=assistantDefinition.match.bind(assistantDefinition);ctx.uiConversation.events.register({...assistantDefinition,match:{"step/start":match,"assistant/live-chunk":match,"assistant/message":match,"llm/retry":match}})}function isSettledTool(block){return`kind`in block}function isRunningTool(block){return!isSettledTool(block)}function isVisibleChatNode(node){if(node.kind===`command`){if(node.data.name===`permission`)return false;if(node.data.name===`team`&&node.data.outcome?.kind!==`error`){const selection=node.data.args?.trim();if(selection===`on`||selection===`off`)return false}}return node.visibility===`visible`&&(node.kind!==`system-prompt`||node.data.message!==void 0)}const NO_TURNS=[];var GroupTreeSegments=class{position;openings=new Map;latestOpening;latestStart;constructor(position){this.position=position}track(previous,next){const before=this.openingTurn(previous);const after=this.openingTurn(next);if(before===after)return;if(before!==void 0&&this.adjust(before,-1)===0&&before===this.latestOpening)this.latestOpening=this.lastOpeningTurn();if(after!==void 0){this.adjust(after,1);if(this.latestOpening===void 0||after>this.latestOpening)this.latestOpening=after}}inLatest(turn){return turn!==void 0&&this.latestStart!==void 0&&turn>=this.latestStart}settle(turnOrder){const previous=this.latestStart;const start=this.latestOpening??turnOrder[0];if(start===previous)return NO_TURNS;this.latestStart=start;const bounded=previous!==void 0&&start!==void 0;const low=bounded?Math.min(previous,start):Number.NEGATIVE_INFINITY;const high=bounded?Math.max(previous,start):Number.POSITIVE_INFINITY;const changed=[];for(const turn of turnOrder.slice(turnOrder.findLastIndex(turn=>turn<low)+1)){if(turn>=high)break;changed.push(turn)}return changed}openingTurn(node){return node!==void 0&&isAtOrOutside(node,this.position)?locationCoordinates(node.location).turn:void 0}lastOpeningTurn(){let last;for(const turn of this.openings.keys())if(last===void 0||turn>last)last=turn;return last}adjust(turn,delta){const next=(this.openings.get(turn)??0)+delta;if(next>0)this.openings.set(turn,next);else this.openings.delete(turn);return next}};const PROMPT_PREVIEW_LIMIT=50;const RESPONSE_PREVIEW_LIMIT=120;function preview(parts,limit){let text=``;let unread=false;for(const part of parts){if(text.length>=limit*2){unread=true;break}const clipped=part.length>limit*2;const chunk=clipped?part.slice(0,limit*2):part;text+=text===``?chunk:` ${chunk}`;if(clipped){unread=true;break}}const normalized=text.replace(/\s+/g,` `).trim();if(normalized.length>limit-1)return`${normalized.slice(0,limit-1).trimEnd()}…`;return unread?`${normalized}…`:normalized}function promptText(node){if(node.kind!==`user`)return``;return preview(node.data.content.flatMap(block=>block.type===`text`?[block.text]:[]),PROMPT_PREVIEW_LIMIT)}function responseText(node){if(node.kind!==`assistant-step`)return``;return preview(node.data.blocks.flatMap(block=>block.kind===`text`?[block.text]:[]),RESPONSE_PREVIEW_LIMIT)}function sameTurnNavigationItem(left,right){if(left===void 0||right===void 0)return left===right;return left.turn===right.turn&&left.anchorKey===right.anchorKey&&left.prompt===right.prompt&&left.response===right.response}function turnNavigationItem(turn,locations,nodes){const loaded=locations.getTurn(turn).map(key=>nodes.get(key)).filter(node=>node!==void 0&&isVisibleChatNode(node));const user=loaded.find(node=>node.kind===`user`);const anchor=user??loaded[0];if(anchor===void 0)return void 0;const response=loaded.findLast(node=>responseText(node)!==``);return{turn,anchorKey:anchor.key,prompt:user===void 0?``:promptText(user),response:response===void 0?``:responseText(response)}}function nodeTurn(node){const location=node?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn.turn:void 0}function samePresentation(left,right){return left===right||left!==void 0&&right!==void 0&&left.spec===right.spec&&left.turn===right.turn&&left.turnStarted===right.turnStarted&&left.turnClosed===right.turnClosed&&left.hasExternalProcess===right.hasExternalProcess&&left.hasNonReplyProcess===right.hasNonReplyProcess&&left.hasInterleavedInput===right.hasInterleavedInput}function derivePresentation(turn,locations,nodes){const keys=locations.getTurn(turn);const control=keys.map(key=>nodes.get(key)).find(node=>node?.kind===`turn-process`);if(control===void 0)return void 0;const spec=control.data;const location=control.location;if(location.kind!==`turn`&&location.kind!==`step`)return void 0;let openingHumanAnchor;for(const key of keys){const node=nodes.get(key);if(node!==void 0&&isAtOrOutside(node,`input`)&&(spec.controlAnchorSeq===location.turn.start?.seq||node.anchorSeq<spec.controlAnchorSeq))openingHumanAnchor=Math.max(openingHumanAnchor??node.anchorSeq,node.anchorSeq)}let hasExternalProcess=false;let hasNonReplyProcess=false;let hasInterleavedInput=false;for(const key of keys){const node=nodes.get(key);if(node===void 0||!isVisibleChatNode(node)||node.kind===`turn-process`)continue;if(isAtOrOutside(node,`input`)&&(openingHumanAnchor===void 0||node.anchorSeq>openingHumanAnchor))hasInterleavedInput=true;if(isAtOrOutside(node,`turn`)||node.anchorSeq<spec.processStartSeq||spec.answerAnchorSeq!==null&&node.anchorSeq>=spec.answerAnchorSeq)continue;if(node.kind!==`assistant-step`||spec.answerStep===null||node.data.step!==spec.answerStep){hasExternalProcess=true;if(node.kind!==`assistant-step`||node.data.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``))hasNonReplyProcess=true}}return{turn,spec,turnStarted:location.turn.start!==void 0,turnClosed:location.turn.status===`closed`,hasExternalProcess,hasNonReplyProcess,hasInterleavedInput}}var ChatTurnProcessProjector=class{presentations=new Map;get(node){const turn=nodeTurn(node);return turn===void 0?void 0:this.presentations.get(turn)}replace(order,locations,nodes){const turns=new Set;for(const key of order){const turn=nodeTurn(nodes.get(key));if(turn!==void 0)turns.add(turn)}const changed=new Set;for(const turn of new Set([...this.presentations.keys(),...turns]))if(this.set(turn,turns.has(turn)?derivePresentation(turn,locations,nodes):void 0))changed.add(turn);return changed}update(turns,locations,nodes){const changed=new Set;for(const turn of turns)if(this.set(turn,derivePresentation(turn,locations,nodes)))changed.add(turn);return changed}set(turn,next){if(samePresentation(this.presentations.get(turn),next))return false;if(next===void 0)this.presentations.delete(turn);else this.presentations.set(turn,next);return true}};const EMPTY_KEYS=[];const EMPTY_TURNS=[];const EMPTY_ITEMS=[];const EMPTY_LIST=[];function sameReferences$1(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function cachedSource(sources,key,create){let source=sources.get(key);if(source===void 0){source=create();sources.set(key,source)}return source}var MutableChatSource=class{read;label;listeners=new Set;published;constructor(read,label){this.read=read;this.label=label;this.published=read()}getSnapshot=()=>this.read();subscribe=listener=>{this.listeners.add(listener);return()=>{this.listeners.delete(listener)}};publish(){const next=this.getSnapshot();if(this.published===next)return;this.published=next;(0,_deepseek_ai_dsh_client_store.notifySubscribers)(this.listeners,this.label)}};var TurnKindNodes=class{nodes=new Map;current=EMPTY_LIST;dirty=false;observable;source(){return this.observable??=new MutableChatSource(()=>this.read(),`[ui-chat] turn kind nodes`)}set(node){const previous=this.nodes.get(node.key);this.nodes.set(node.key,node);if(previous!==void 0&&previous.data===node.data&&previous.anchorSeq===node.anchorSeq)return;this.dirty=true}delete(key){this.nodes.delete(key);this.dirty=true}publish(){this.observable?.publish()}read(){if(this.dirty){this.current=[...this.nodes.values()].sort((a,b)=>a.anchorSeq-b.anchorSeq).map(node=>node.data);this.dirty=false}return this.current}};var MutableChatNodeStore=class{byKey=new Map;turnProcesses=new ChatTurnProcessProjector;sources=new Map;processSources=new Map;bottomSources=new Map;exchanges=new GroupTreeSegments(`exchange`);dirtyKeys=new Set;dirtyBottomKeys=new Set;dirtyProcessKeys=new Set;turnKinds=new Map;dirtyTurnKinds=new Set;valuesCache=EMPTY_LIST;valuesDirty=false;get(key){return this.byKey.get(key)}source(key){return cachedSource(this.sources,key,()=>new MutableChatSource(()=>this.get(key),`[ui-chat] node source ${key}`))}bottomSource(key){return cachedSource(this.bottomSources,key,()=>new MutableChatSource(()=>{const node=this.get(key);return node!==void 0&&isVisibleChatNode(node)&&this.exchanges.inLatest(locationCoordinates(node.location).turn)},`[ui-chat] node bottom source ${key}`))}settleBottom(turnOrder,locations){for(const turn of this.exchanges.settle(turnOrder))for(const key of locations.getTurn(turn))this.dirtyBottomKeys.add(key)}turnDataSource(turn,kind){return this.turnKind(turn,kind).source()}turnKind(turn,kind){return cachedSource(cachedSource(this.turnKinds,turn,()=>new Map),kind,()=>new TurnKindNodes)}updateTurnKind(previous,next){const before=previous===void 0?void 0:locationCoordinates(previous.location).turn;const after=next===void 0?void 0:locationCoordinates(next.location).turn;if(previous!==void 0&&before!==void 0&&(before!==after||previous.kind!==next?.kind)){const collection=this.turnKind(before,previous.kind);collection.delete(previous.key);this.dirtyTurnKinds.add(collection)}if(next!==void 0&&after!==void 0){const collection=this.turnKind(after,next.kind);collection.set(next);this.dirtyTurnKinds.add(collection)}}processSource(key){return cachedSource(this.processSources,key,()=>new MutableChatSource(()=>this.process(key),`[ui-chat] node process source ${key}`))}process(key){return this.turnProcesses.get(this.get(key))}values(){if(this.valuesDirty){this.valuesCache=[...this.byKey.values()];this.valuesDirty=false}return this.valuesCache}replace(nodes){const previous=new Map(this.byKey);this.byKey.clear();for(const node of nodes){this.byKey.set(node.key,node);if(previous.get(node.key)!==node){this.updateTurnKind(previous.get(node.key),node);this.exchanges.track(previous.get(node.key),node);this.dirtyKeys.add(node.key);this.dirtyProcessKeys.add(node.key)}previous.delete(node.key)}for(const key of previous.keys()){this.updateTurnKind(previous.get(key),void 0);this.exchanges.track(previous.get(key),void 0);this.dirtyKeys.add(key);this.dirtyProcessKeys.add(key)}this.valuesCache=[...this.byKey.values()];this.valuesDirty=false}upsert(nodes){let changed=false;for(const node of nodes){if(this.byKey.get(node.key)===node)continue;this.updateTurnKind(this.byKey.get(node.key),node);this.exchanges.track(this.byKey.get(node.key),node);this.byKey.set(node.key,node);this.dirtyKeys.add(node.key);this.dirtyProcessKeys.add(node.key);changed=true}if(changed)this.valuesDirty=true}touchProcesses(turns,locations){for(const turn of turns)for(const key of locations.getTurn(turn))this.dirtyProcessKeys.add(key)}replaceProcesses(order,locations){this.touchProcesses(this.turnProcesses.replace(order,locations,this),locations)}updateProcesses(turns,locations){this.touchProcesses(this.turnProcesses.update(turns,locations,this),locations)}publish(){const dirty=[...this.dirtyKeys];const dirtyBottom=new Set([...this.dirtyBottomKeys,...dirty]);const dirtyProcesses=[...this.dirtyProcessKeys];const dirtyTurnKinds=[...this.dirtyTurnKinds];this.dirtyKeys.clear();this.dirtyBottomKeys.clear();this.dirtyProcessKeys.clear();this.dirtyTurnKinds.clear();for(const key of dirty)this.sources.get(key)?.publish();for(const key of dirtyBottom)this.bottomSources.get(key)?.publish();for(const key of dirtyProcesses)this.processSources.get(key)?.publish();for(const collection of dirtyTurnKinds)collection.publish()}};var MutableChatLocationIndex=class{turns=new Map;steps=new Map;positions=new Map;getTurn(turn){return this.turns.get(turn)??EMPTY_KEYS}getStep(turn,step){return this.steps.get(stepKey(turn,step))??EMPTY_KEYS}getPosition(key){return this.positions.get(key)}rebuild(order,store){const turns=new Map;const steps=new Map;const positions=new Map;const changedTurns=new Set;for(const[index,key]of order.entries()){const location=store.get(key)?.location;if(location===void 0)continue;const coordinates=locationCoordinates(location);const previous=this.positions.get(key);const position={turn:coordinates.turn,previous:order[index-1],next:order[index+1]};const unchanged=previous!==void 0&&previous.turn===position.turn&&previous.previous===position.previous&&previous.next===position.next;positions.set(key,unchanged?previous:position);if(!unchanged){if(previous?.turn!==void 0)changedTurns.add(previous.turn);if(position.turn!==void 0)changedTurns.add(position.turn)}if(coordinates.turn===void 0)continue;const turnKeys=turns.get(coordinates.turn)??[];turnKeys.push(key);turns.set(coordinates.turn,turnKeys);if(coordinates.step===void 0)continue;const step=stepKey(coordinates.turn,coordinates.step);const stepKeys=steps.get(step)??[];stepKeys.push(key);steps.set(step,stepKeys)}for(const[key,position]of this.positions)if(!positions.has(key)&&position.turn!==void 0)changedTurns.add(position.turn);this.positions=positions;this.turns=updateIndex(this.turns,turns);this.steps=updateIndex(this.steps,steps);return[...changedTurns]}touch(nodes){const turns=new Set;const steps=new Set;for(const node of nodes){const coordinates=locationCoordinates(node.location);if(coordinates.turn===void 0||!this.turns.get(coordinates.turn)?.includes(node.key))continue;turns.add(coordinates.turn);if(coordinates.step!==void 0)steps.add(stepKey(coordinates.turn,coordinates.step))}for(const turn of turns){const keys=this.turns.get(turn);if(keys===void 0)continue;this.turns.set(turn,[...keys])}for(const step of steps){const keys=this.steps.get(step);if(keys===void 0)continue;this.steps.set(step,[...keys])}}};function updateIndex(previous,nextMutable){const next=new Map;const keys=new Set([...previous.keys(),...nextMutable.keys()]);for(const key of keys){const before=previous.get(key)??EMPTY_KEYS;const candidate=nextMutable.get(key)??EMPTY_KEYS;const value=sameReferences$1(before,candidate)?before:candidate;if(candidate.length>0)next.set(key,value)}return next}var MutableTurnNavigationIndex=class{current=EMPTY_ITEMS;byTurn=new Map;items(){return this.current}rebuild(timeline,locations,nodes){const next=[];const byTurn=new Map;for(const turn of timeline.turnOrder){const derived=turnNavigationItem(turn,locations,nodes);if(derived===void 0)continue;const previous=this.byTurn.get(turn);const item=previous!==void 0&&sameTurnNavigationItem(previous,derived)?previous:derived;next.push(item);byTurn.set(turn,item)}this.byTurn=byTurn;if(!(next.length===this.current.length&&next.every((item,index)=>item===this.current[index])))this.current=next}touch(turns,locations,nodes){if(turns.size===0)return;const next=this.current.map(item=>{if(!turns.has(item.turn))return item;const derived=turnNavigationItem(item.turn,locations,nodes);if(derived===void 0||sameTurnNavigationItem(item,derived))return item;this.byTurn.set(item.turn,derived);return derived});if(next.some((item,index)=>item!==this.current[index]))this.current=next}};function stepKey(turn,step){return`${turn}:${step}`}function locationTurnStatus(location){return location.kind===`turn`||location.kind===`step`?location.turn.status:void 0}function processPresentationInputChanged(previous,next,structural){if(structural||previous===void 0)return true;if(locationTurnStatus(previous.location)!==locationTurnStatus(next.location))return true;if(previous.kind===`turn-process`&&next.kind===`turn-process`)return previous.data!==next.data;return previous.kind===`assistant-step`&&next.kind===`assistant-step`&&previous.data.step!==next.data.step}function turnProcessPresentations(nodes){const presentations=new Map;for(const raw of nodes){const node=raw;if(node.kind===`turn-process`)presentations.set(node.data.turn,{...presentations.get(node.data.turn),control:node})}for(const raw of nodes){const node=raw;const location=node.location;if(location.kind!==`turn`&&location.kind!==`step`)continue;const current=presentations.get(location.turn.turn)??{};const controlAnchor=current.control?.data.controlAnchorSeq;if(isAtOrOutside(node,`input`)&&controlAnchor!==void 0&&(controlAnchor===location.turn.start?.seq||node.anchorSeq<controlAnchor)){presentations.set(location.turn.turn,{...current,openingInputAnchor:Math.max(current.openingInputAnchor??node.anchorSeq,node.anchorSeq)});continue}if(isAtOrOutside(node,`turn`))continue;presentations.set(location.turn.turn,{...current,earliestProcessAnchor:Math.min(current.earliestProcessAnchor??node.anchorSeq,node.anchorSeq)})}return presentations}function presentationPosition(raw,presentations){const node=raw;const location=node.location;if(location.kind!==`turn`&&location.kind!==`step`)return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq};const presentation=presentations.get(location.turn.turn);if(presentation===void 0)return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq};const openingInputAnchor=presentation.openingInputAnchor;if(openingInputAnchor!==void 0&&node.anchorSeq<openingInputAnchor&&!isAtOrOutside(node,`turn`))return{anchor:openingInputAnchor,rank:2,originalAnchor:node.anchorSeq};if(presentation.control!==void 0&&node.key===presentation.control.key)return openingInputAnchor===void 0?{anchor:presentation.earliestProcessAnchor??node.anchorSeq,rank:-1,originalAnchor:node.anchorSeq}:{anchor:openingInputAnchor,rank:1,originalAnchor:node.anchorSeq};return{anchor:node.anchorSeq,rank:0,originalAnchor:node.anchorSeq}}function orderedVisibleChatNodes(nodes){const visible=nodes.filter(node=>isVisibleChatNode(node));const presentations=turnProcessPresentations(visible);return visible.sort((left,right)=>{const leftPosition=presentationPosition(left,presentations);const rightPosition=presentationPosition(right,presentations);return leftPosition.anchor-rightPosition.anchor||leftPosition.rank-rightPosition.rank||leftPosition.originalAnchor-rightPosition.originalAnchor||left.key.localeCompare(right.key)})}function referenceMessageSeq(node){const candidate=node;return candidate.kind===`user`||candidate.kind===`steering`?candidate.data.seq:void 0}function followingRecall(node){const candidate=node;if(candidate.kind!==`context`)return void 0;return{messageSeq:candidate.data.seq-1,labels:sessionRecallLabels(candidate.data.source)}}function withReferenceLabels(node,labels){const candidate=node;if(candidate.kind!==`user`&&candidate.kind!==`steering`)return node;const current=candidate.data.referenceLabels??EMPTY_KEYS;const hasLabels=Object.hasOwn(candidate.data,`referenceLabels`);if(sameReferences$1(current,labels)&&hasLabels===labels.length>0)return node;const data={...candidate.data};if(labels.length===0)delete data.referenceLabels;else data.referenceLabels=labels;return{...candidate,data}}var ReferenceLabelProjector=class{messagesBySeq=new Map;labelsByMessageSeq=new Map;replace(nodes){this.messagesBySeq.clear();this.labelsByMessageSeq.clear();for(const node of nodes){const messageSeq=referenceMessageSeq(node);if(messageSeq!==void 0)this.messagesBySeq.set(messageSeq,node.key);const recall=followingRecall(node);if(recall!==void 0&&recall.labels.length>0)this.labelsByMessageSeq.set(recall.messageSeq,recall.labels)}return nodes.map(node=>{const messageSeq=referenceMessageSeq(node);return messageSeq===void 0?node:withReferenceLabels(node,this.labelsByMessageSeq.get(messageSeq)??EMPTY_KEYS)})}apply(upserts,store){const byKey=new Map(upserts.map(node=>[node.key,node]));const affected=new Set;for(const node of upserts){const messageSeq=referenceMessageSeq(node);if(messageSeq!==void 0){this.messagesBySeq.set(messageSeq,node.key);affected.add(messageSeq)}const recall=followingRecall(node);if(recall===void 0)continue;const current=this.labelsByMessageSeq.get(recall.messageSeq);if(recall.labels.length===0)this.labelsByMessageSeq.delete(recall.messageSeq);else this.labelsByMessageSeq.set(recall.messageSeq,current!==void 0&&sameReferences$1(current,recall.labels)?current:recall.labels);affected.add(recall.messageSeq)}for(const messageSeq of affected){const key=this.messagesBySeq.get(messageSeq);if(key===void 0)continue;const node=byKey.get(key)??store.get(key);if(node===void 0)continue;byKey.set(key,withReferenceLabels(node,this.labelsByMessageSeq.get(messageSeq)??EMPTY_KEYS))}return[...byKey.values()]}};function withSkillNames(node,names){const candidate=node;if(candidate.kind!==`user`&&candidate.kind!==`steering`)return node;const current=candidate.data.skillNames??EMPTY_KEYS;const hasNames=Object.hasOwn(candidate.data,`skillNames`);if(sameReferences$1(current,names)&&hasNames===names.length>0)return node;const data={...candidate.data};if(names.length===0)delete data.skillNames;else data.skillNames=names;return{...candidate,data}}function slashEntryOf(node){const candidate=node;if(candidate.kind===`user`||candidate.kind===`steering`)return{key:node.key,seq:node.anchorSeq,kind:`message`,name:null};if(candidate.kind===`context`){const name=skillInvocationName(candidate.data.source);return name===null?null:{key:node.key,seq:node.anchorSeq,kind:`skill`,name}}return{key:node.key,seq:node.anchorSeq,kind:`boundary`,name:null}}function sameSlashEntry(left,right){return left.seq===right.seq&&left.kind===right.kind&&left.name===right.name}var SkillNameProjector=class{entries=new Map;sorted=[];replace(nodes){this.entries.clear();this.sorted=[];for(const node of nodes){const entry=slashEntryOf(node);if(entry===null)continue;this.entries.set(entry.key,entry);this.sorted.push(entry)}this.sorted.sort((left,right)=>left.seq-right.seq);const names=new Map;for(let index=0;index<this.sorted.length;index++){if(this.sorted[index]?.kind===`boundary`)continue;const end=this.runEnd(index);this.assignRun(index,end,names);index=end}return nodes.map(node=>withSkillNames(node,names.get(node.key)??EMPTY_KEYS))}apply(upserts,store){const dirty=[];for(const node of upserts){const next=slashEntryOf(node);const previous=this.entries.get(node.key);if(previous!==void 0){if(next!==null&&sameSlashEntry(previous,next)){if(next.kind===`message`)dirty.push(next.seq);continue}this.remove(previous);dirty.push(previous.seq)}if(next===null)continue;this.insert(next);dirty.push(next.seq)}if(dirty.length===0)return upserts;const names=new Map;for(const seq of dirty)this.collectAround(seq,names);const byKey=new Map(upserts.map(node=>[node.key,node]));for(const[key,list]of names){const node=byKey.get(key)??store.get(key);if(node===void 0)continue;const next=withSkillNames(node,list);if(next!==node||byKey.has(key))byKey.set(key,next)}return[...byKey.values()]}insert(entry){this.sorted.splice(this.lowerBound(entry.seq),0,entry);this.entries.set(entry.key,entry)}remove(entry){this.sorted.splice(this.sorted.indexOf(entry),1);this.entries.delete(entry.key)}lowerBound(seq){let low=0;let high=this.sorted.length;while(low<high){const middle=low+high>>>1;if((this.sorted[middle]?.seq??Number.POSITIVE_INFINITY)<seq)low=middle+1;else high=middle}return low}runEnd(index){let end=index;while(end+1<this.sorted.length&&this.sorted[end+1]?.kind!==`boundary`)end++;return end}runStart(index){let start=index;while(start-1>=0&&this.sorted[start-1]?.kind!==`boundary`)start--;return start}assignRun(start,end,names){const list=[];for(let index=start;index<=end;index++){const entry=this.sorted[index];if(entry?.kind===`skill`&&entry.name!==null&&!list.includes(entry.name))list.push(entry.name)}for(let index=start;index<=end;index++){const entry=this.sorted[index];if(entry?.kind===`message`)names.set(entry.key,list)}}collectAround(seq,names){const at=this.lowerBound(seq);const here=this.sorted[at];if(here!==void 0&&here.seq===seq&&here.kind!==`boundary`){this.assignRun(this.runStart(at),this.runEnd(at),names);return}if(at-1>=0&&this.sorted[at-1]?.kind!==`boundary`)this.assignRun(this.runStart(at-1),at-1,names);const right=here!==void 0&&here.seq===seq?at+1:at;if(right<this.sorted.length&&this.sorted[right]?.kind!==`boundary`)this.assignRun(right,this.runEnd(right),names)}};const EMPTY_CONTRIBUTION={anchorSeq:0,nodes:EMPTY_LIST,partial:null,running:null};function legacyContribution(raw){const node=raw;if(raw.visibility!==`visible`&&node.kind!==`assistant-step`)return EMPTY_CONTRIBUTION;switch(node.kind){case`user`:case`steering`:case`context`:case`command`:case`turn-error`:case`turn-max-tokens`:case`unknown`:return{anchorSeq:node.anchorSeq,nodes:[node.data],partial:null,running:null};case`compaction`:return node.data.kind===`compaction-progress`?EMPTY_CONTRIBUTION:{anchorSeq:node.anchorSeq,nodes:[node.data],partial:null,running:null};case`assistant-step`:{const data=node.data;if(data.status===`running`){if(raw.visibility!==`visible`)return EMPTY_CONTRIBUTION;return{anchorSeq:node.anchorSeq,nodes:EMPTY_LIST,partial:{turn:data.turn,step:data.step,blocks:data.blocks},running:null}}return{anchorSeq:node.anchorSeq,nodes:data.finalNode===void 0?EMPTY_LIST:[data.finalNode],partial:null,running:null}}case`tool-call`:{const root=node.data.root;return isRunningTool(root)?{anchorSeq:node.anchorSeq,nodes:EMPTY_LIST,partial:null,running:root}:{anchorSeq:node.anchorSeq,nodes:[root],partial:null,running:null}}case`manual-compaction`:{const data=node.data;return{anchorSeq:node.anchorSeq,nodes:data.compaction===null?[data.command]:[data.command,data.compaction],partial:null,running:null}}case`model-retry`:return{anchorSeq:node.anchorSeq,nodes:node.data.attempts,partial:null,running:null};case`turn-tail`:case`system-prompt`:return EMPTY_CONTRIBUTION;default:return EMPTY_CONTRIBUTION}}function sameContribution(left,right){return left!==void 0&&left.anchorSeq===right.anchorSeq&&left.partial?.blocks===right.partial?.blocks&&left.partial?.turn===right.partial?.turn&&left.partial?.step===right.partial?.step&&left.running===right.running&&sameReferences$1(left.nodes,right.nodes)}var LegacySliceBuilder=class{contributions=new Map;finalizedContributions=new Map;runningContributions=new Map;partialContributions=new Map;finalized=EMPTY_LIST;runningCalls=EMPTY_LIST;partial=null;timeline;turnTimings=new Map;turnEnds=new Map;replace(nodes,timeline){this.contributions.clear();this.finalizedContributions.clear();this.runningContributions.clear();this.partialContributions.clear();for(const node of nodes){const contribution=legacyContribution(node);this.contributions.set(node.key,contribution);this.indexContribution(node.key,contribution)}this.rebuildFinalized();this.rebuildRunning();this.rebuildPartial();this.updateTimeline(timeline);return this.snapshot()}apply(upserts,timeline){let finalizedChanged=false;let runningChanged=false;let partialChanged=false;for(const node of upserts){const contribution=legacyContribution(node);const previous=this.contributions.get(node.key);if(sameContribution(previous,contribution))continue;finalizedChanged||=finalizedContributionChanged(previous,contribution);runningChanged||=runningContributionChanged(previous,contribution);partialChanged||=partialContributionChanged(previous,contribution);this.contributions.set(node.key,contribution);this.indexContribution(node.key,contribution)}if(finalizedChanged)this.rebuildFinalized();if(runningChanged)this.rebuildRunning();if(partialChanged)this.rebuildPartial();this.updateTimeline(timeline);return this.snapshot()}indexContribution(key,contribution){updateContributionIndex(this.finalizedContributions,key,contribution,contribution.nodes.length>0);updateContributionIndex(this.runningContributions,key,contribution,contribution.running!==null);updateContributionIndex(this.partialContributions,key,contribution,contribution.partial!==null)}rebuildFinalized(){const finalized=[...this.finalizedContributions.values()].flatMap(value=>value.nodes).sort((left,right)=>left.seq-right.seq);if(!sameReferences$1(this.finalized,finalized))this.finalized=finalized}rebuildRunning(){const runningCalls=[...this.runningContributions.values()].sort((left,right)=>left.anchorSeq-right.anchorSeq).flatMap(value=>value.running===null?[]:[value.running]);if(!sameReferences$1(this.runningCalls,runningCalls))this.runningCalls=runningCalls}rebuildPartial(){const partial=[...this.partialContributions.values()].sort((left,right)=>left.anchorSeq-right.anchorSeq).findLast(value=>value.partial!==null)?.partial??null;if(this.partial?.blocks!==partial?.blocks||this.partial?.turn!==partial?.turn||this.partial?.step!==partial?.step)this.partial=partial}updateTimeline(timeline){if(this.timeline===timeline)return;this.timeline=timeline;const turnTimings=new Map;const turnEnds=new Map;for(const turn of timeline.turns.values()){if(turn.start!==void 0)turnTimings.set(turn.turn,{startTime:turn.start.time,...turn.end===void 0?{}:{endTime:turn.end.time}});if(turn.end!==void 0)turnEnds.set(turn.turn,turn.end.seq)}this.turnTimings=turnTimings;this.turnEnds=turnEnds}snapshot(){return{nodes:this.finalized,turnTimings:this.turnTimings,turnEnds:this.turnEnds,partial:this.partial,runningCalls:this.runningCalls}}};function updateContributionIndex(index,key,contribution,present){if(present)index.set(key,contribution);else index.delete(key)}function finalizedContributionChanged(previous,next){const previousNodes=previous?.nodes??EMPTY_LIST;return!sameReferences$1(previousNodes,next.nodes)||(previousNodes.length>0||next.nodes.length>0)&&previous?.anchorSeq!==next.anchorSeq}function runningContributionChanged(previous,next){return previous?.running!==next.running||(previous.running!==null||next.running!==null)&&previous.anchorSeq!==next.anchorSeq}function partialContributionChanged(previous,next){return previous?.partial?.blocks!==next.partial?.blocks||previous?.partial?.turn!==next.partial?.turn||previous?.partial?.step!==next.partial?.step||((previous?.partial??null)!==null||next.partial!==null)&&previous?.anchorSeq!==next.anchorSeq}var ChatSnapshotBuilder=class{store=new MutableChatNodeStore;locations=new MutableChatLocationIndex;navigation=new MutableTurnNavigationIndex;legacy=new LegacySliceBuilder;referenceLabels=new ReferenceLabelProjector;skillNames=new SkillNameProjector;order=EMPTY_KEYS;latestGroupInput;readGroupNode=key=>this.store.get(key);readGroupTurn=turn=>this.locations.getTurn(turn);readGroupPosition=key=>this.locations.getPosition(key);timeline=null;empty;constructor(){this.empty=this.snapshot({turnOrder:EMPTY_TURNS,turns:new Map});this.latestGroupInput={kind:`replace`,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:this.empty.timeline}}replace(input){const nodes=this.skillNames.replace(this.referenceLabels.replace(input.nodes));this.store.replace(nodes);this.order=orderedVisibleChatNodes(nodes).map(node=>node.key);this.locations.rebuild(this.order,this.store);this.store.replaceProcesses(this.order,this.locations);this.store.settleBottom(input.timeline.turnOrder,this.locations);this.navigation.rebuild(input.timeline,this.locations,this.store);this.timeline=input.timeline;this.latestGroupInput={kind:`replace`,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:input.timeline};return this.snapshot(input.timeline,this.legacy.replace(nodes,input.timeline))}apply(input){const upserts=this.skillNames.apply(this.referenceLabels.apply(input.upserts,this.store),this.store);const processTurns=new Set;let structural=false;const contentOnly=[];const changes=[];for(const node of upserts){const previous=this.store.get(node.key);if(previous!==node)changes.push({previous,current:node});const nodeStructural=previous===void 0||previous.kind!==node.kind||previous.anchorSeq!==node.anchorSeq||previous.visibility!==node.visibility||previous.groupTree!==node.groupTree||locationIdentity(previous.location)!==locationIdentity(node.location);structural||=nodeStructural;if(!nodeStructural)contentOnly.push(node);if(processPresentationInputChanged(previous,node,nodeStructural)){const previousTurn=previous===void 0?void 0:locationCoordinates(previous.location).turn;const nextTurn=locationCoordinates(node.location).turn;if(previousTurn!==void 0)processTurns.add(previousTurn);if(nextTurn!==void 0)processTurns.add(nextTurn)}}this.store.upsert(upserts);let changedTurnOrders=EMPTY_TURNS;if(structural){const next=orderedVisibleChatNodes(this.store.values()).map(node=>node.key);this.order=sameReferences$1(this.order,next)?this.order:next;changedTurnOrders=this.locations.rebuild(this.order,this.store)}this.locations.touch(contentOnly);this.store.updateProcesses(processTurns,this.locations);this.store.settleBottom(input.timeline.turnOrder,this.locations);if(structural||input.timeline!==this.timeline)this.navigation.rebuild(input.timeline,this.locations,this.store);else this.navigation.touch(turnsOf(contentOnly),this.locations,this.store);this.timeline=input.timeline;this.latestGroupInput={kind:`apply`,changes,order:this.order,readNode:this.readGroupNode,readTurn:this.readGroupTurn,readPosition:this.readGroupPosition,timeline:input.timeline,changedTurns:input.changedTurns??EMPTY_TURNS,changedTurnOrders};return this.snapshot(input.timeline,this.legacy.apply(upserts,input.timeline))}groupInput(){return this.latestGroupInput}publish(){this.store.publish()}snapshot(timeline,legacy=this.legacy.replace(EMPTY_LIST,timeline)){return{order:this.order,nodes:this.store,locations:this.locations,navigation:this.navigation,timeline,legacy}}};function turnsOf(nodes){const turns=new Set;for(const node of nodes){const turn=locationCoordinates(node.location).turn;if(turn!==void 0)turns.add(turn)}return turns}function locationIdentity(location){const coordinates=locationCoordinates(location);return`${location.kind}:${coordinates.turn??``}:${coordinates.step??``}`}const chatViewDefinition={target:`chat`,create:()=>new ChatSnapshotBuilder,isActive:snapshot=>snapshot.order.some(key=>snapshot.nodes.get(key)?.kind!==`command`)};function registerChatConversationView(ctx){ctx.uiConversation.views.register(chatViewDefinition)}const COMPACT_KIND=`compact-checkpoint`;function commandFromRun(match){if(match.event.type!==`command/run`)throw new Error(`command start requires command/run`);const data=match.event.data;return{kind:`command`,seq:match.event.seq,time:match.event.time,commandId:data.commandId,name:data.name,args:data.args??null,outcome:null}}function commandFromDone(match,previous){if(match.event.type!==`command/done`)throw new Error(`command update requires command/done`);const data=match.event.data;const sourceEventSeq=data.kind===`success`&&data.sourceEventSeq!==void 0&&Number.isSafeInteger(data.sourceEventSeq)&&data.sourceEventSeq>=0?data.sourceEventSeq:void 0;return{kind:`command`,seq:previous?.seq??match.event.seq,time:previous?.time??match.event.time,commandId:data.commandId,name:previous?.name??null,args:previous?.args??null,outcome:{kind:data.kind,...data.text===void 0?{}:{text:data.text},...sourceEventSeq===void 0?{}:{sourceEventSeq}}}}function compactSource(event){if(event.type!==`user/message`||!isReplacementSurfaceEvent(event))return void 0;const source=event.data.source;if(source.kind!==COMPACT_KIND||typeof source.compactionId!==`string`)return void 0;return{compactionId:source.compactionId,...source.sourceCommandId===void 0?{}:{sourceCommandId:source.sourceCommandId}}}function compactSummary(match,checkpoint){let shadowedItemCount=null;let shadowedTokenCount=null;if(match?.event.type===`compaction/summary`){const data=match.event.data;shadowedItemCount=Array.isArray(data.shadowedSeqs)&&data.shadowedSeqs.every(seq=>Number.isSafeInteger(seq)&&seq>=0)?data.shadowedSeqs.length:null;shadowedTokenCount=Number.isSafeInteger(data.shadowedTokenCount)&&data.shadowedTokenCount>=0?data.shadowedTokenCount:null}return{kind:`compaction`,seq:checkpoint.event.seq,time:checkpoint.event.time,summaryEventSeq:match?.event.seq??null,shadowedItemCount,shadowedTokenCount}}function fallbackState$4(context){const done=context.matches.find(match=>match.event.type===`command/done`);const checkpoint=context.matches.find(match=>compactSource(match.event)!==void 0);const summary=context.matches.find(match=>match.event.type===`compaction/summary`);if(checkpoint===void 0)return done===void 0?void 0:{command:commandFromDone(done)};const source=compactSource(checkpoint.event);if(source?.sourceCommandId===void 0)return done===void 0?void 0:{command:commandFromDone(done)};return{command:done===void 0?{kind:`command`,seq:checkpoint.event.seq,time:checkpoint.event.time,commandId:source.sourceCommandId,name:`compact`,args:null,outcome:null}:{...commandFromDone(done),name:`compact`},checkpoint,...summary===void 0?{}:{summary}}}function updateCompactionState(state,match){if(match.event.type===`compaction/summary`)return{...state,summary:match};if(compactSource(match.event)!==void 0)return{...state,checkpoint:match};return state}const commandDefinition={kind:`command`,target:`chat`,match:event=>{if(event.type===`command/run`)return{id:String(event.data.commandId),role:`start`};if(event.type===`command/done`)return{id:String(event.data.commandId),role:`update`};const checkpoint=compactSource(event);if(checkpoint?.sourceCommandId!==void 0)return{id:String(checkpoint.sourceCommandId),role:`update`};if(event.type===`compaction/start`||event.type===`compaction/summary`||event.type===`compaction/end`){if(event.data.sourceCommandId!==void 0)return{id:String(event.data.sourceCommandId),role:`update`}}return null},start:(_context,match)=>({command:commandFromRun(match)}),update:(context,match)=>{if(match.event.type===`command/done`)return{...context.state,command:commandFromDone(match,context.state.command)};return updateCompactionState(context.state,match)},buildViewNode:context=>{const state=context.state??fallbackState$4(context);if(state===void 0)return null;if(state.command.name!==`compact`)return chatNode(context,`command`,state.command.seq,state.command);const compaction=state.checkpoint===void 0?null:compactSummary(state.summary,state.checkpoint);const data={command:state.command,compaction};return chatNode(context,`manual-compaction`,compaction?.seq??state.command.seq,data)}};function registerCommandConversationNode(ctx){ctx.uiConversation.events.register(commandDefinition)}function fallbackState$3(context){const ended=context.matches.find(match=>match.event.type===`compaction/end`);const summary=context.matches.find(match=>match.event.type===`compaction/summary`);const checkpoint=context.matches.find(match=>compactSource(match.event)!==void 0);return{...ended===void 0?{}:{ended},...summary===void 0?{}:{summary},...checkpoint===void 0?{}:{checkpoint}}}const compactionDefinition={kind:`compaction`,target:`chat`,match:event=>{const checkpoint=compactSource(event);if(checkpoint!==void 0&&checkpoint.sourceCommandId===void 0)return{id:checkpoint.compactionId,role:`update`};if(event.type===`compaction/start`||event.type===`compaction/summary`||event.type===`compaction/end`){if(event.data.sourceCommandId!==void 0)return null;const compactionId=event.data.compactionId;if(typeof compactionId!==`string`||compactionId===``)return null;return{id:compactionId,role:event.type===`compaction/start`?`start`:`update`}}return null},start:()=>({}),update:(context,match)=>match.event.type===`compaction/end`?{...context.state,ended:match}:updateCompactionState(context.state,match),buildViewNode:context=>{const state=context.state??fallbackState$3(context);if(state.checkpoint===void 0){const anchor=context.start??state.ended;if(anchor===void 0)return null;const location=contextLocation(context);const closed=(location.kind===`turn`||location.kind===`step`)&&location.turn.status===`closed`;const ended=state.ended?.event;const progress=ended?.type===`compaction/end`?{kind:`compaction-progress`,status:`ended`,...ended.data.error===void 0?{}:{error:ended.data.error}}:{kind:`compaction-progress`,status:closed?`interrupted`:`running`};return chatNode(context,`compaction`,anchor.event.seq,progress)}const marker=compactSummary(state.summary,state.checkpoint);return chatNode(context,`compaction`,marker.seq,marker)}};function registerCompactionConversationNode(ctx){ctx.uiConversation.events.register(compactionDefinition)}const unknownFallbackDefinition={kind:`unknown-surface`,target:`chat`,match:event=>event.type!==`assistant/live-chunk`&&isAppendSurfaceEvent(event)?{id:String(event.seq),role:`start`}:null,start:(_context,match)=>({kind:`unknown`,seq:match.event.seq,time:match.event.time,type:match.event.type,data:match.event.data}),update:context=>context.state,buildViewNode:context=>context.state===void 0?null:chatNode(context,`unknown`,context.state.seq,context.state)};function registerUnknownConversationFallback(ctx){ctx.uiConversation.events.registerFallback(unknownFallbackDefinition)}const EMPTY_PENDING={kind:`snapshot`,ids:[]};const EMPTY_CURRENT_CLAIMED=new Set;function materializePending(state){const splices=[];let current=state;while(current.kind===`splice`){splices.push(current);current=current.previous}const pending=[...current.ids];for(const splice of splices.reverse())pending.splice(splice.start,splice.removedCount,...splice.inserted);return pending}function withoutInserted(claimed,inserted){let next;for(const{id}of inserted){if(!claimed.has(id))continue;next??=new Set(claimed);next.delete(id)}return next??claimed}function applySplice(previous,splice,seq){const priorPending=previous?.state.pending??EMPTY_PENDING;const inserted=splice.inserted;const removedCount=splice.removedCount??0;if(removedCount>0&&splice.outcome!==`canceled`){const pending=materializePending(priorPending);const removed=pending.splice(splice.start,removedCount,...inserted);return{pending:{kind:`snapshot`,ids:pending},currentClaimed:new Set(removed.map(message=>message.id)),claimSeq:seq,firstClaimedHuman:removed.find(message=>message.source.kind===`user`)?.id}}const currentClaimed=withoutInserted(previous?.state.currentClaimed??EMPTY_CURRENT_CLAIMED,inserted);return{pending:{kind:`splice`,previous:priorPending,start:splice.start,removedCount,inserted},currentClaimed,claimSeq:previous?.state.claimSeq??-1,firstClaimedHuman:previous?.state.firstClaimedHuman}}function inboxDefinition(target){const kind=`inbox-${target}`;return{kind,match:event=>event.type===`agent/inbox/spliced`&&event.data.target===target?{id:String(event.seq),role:`start`}:null,start:(_context,match,reader)=>{if(match.event.type!==`agent/inbox/spliced`)throw new Error(`inbox start requires agent/inbox/spliced`);return applySplice(reader.previous(kind),match.event.data,match.event.seq)},update:context=>context.state,publication:()=>`none`}}const nextStepInboxDefinition=inboxDefinition(`next-step`);const nextTurnInboxDefinition=inboxDefinition(`next-turn`);function registerInboxConversationNodes(ctx){ctx.uiConversation.events.register(nextStepInboxDefinition);ctx.uiConversation.events.register(nextTurnInboxDefinition)}const inheritedHistoryDefinition={kind:`inherited-history`,target:`chat`,match:event=>event.type===`session/end-seed`&&event.data.inherited===true?{id:`inherited-history`,role:`start`}:null,start:()=>null,update:()=>null,buildViewNode:context=>{const latest=context.matches.at(-1);if(latest===void 0)return null;return chatNode(context,`inherited-history`,latest.event.seq,{},{location:latest.location,groupTree:`turn`})}};function registerInheritedHistoryConversationNode(ctx){ctx.uiConversation.events.register(inheritedHistoryDefinition)}function isCompactionCheckpoint(event){if(event.type!==`user/message`||!isReplacementSurfaceEvent(event))return false;return event.data.source.kind===`compact-checkpoint`}function contextMessage(event,message){return{kind:`context`,seq:event.seq,time:event.time,content:message.content,source:message.source,producer:contextProducer(message.source),form:contextForm(message.source)}}function followsProcessEvidence(location,reader){if(location.kind!==`turn`&&location.kind!==`step`)return false;return reader.previous(`process-evidence`)?.state.turn===location.turn.turn}const messageDefinition={kind:`input-message`,target:`chat`,match:event=>{if(event.type===`user/message`)return isAppendSurfaceEvent(event)&&!isCompactionCheckpoint(event)?{id:String(event.data.id),role:`start`}:null;return null},start:(_context,match,reader)=>{const event=match.event;if(event.type!==`user/message`)throw new Error(`input-message start requires user/message`);if(event.data.source.kind!==`user`){const nextTurn=reader.previous(`inbox-next-turn`)?.state;const nextStep=reader.previous(`inbox-next-step`)?.state;const location=match.location;const turnStart=location.kind===`step`?location.turn.start?.seq:void 0;const idleSteer=location.kind===`step`&&location.step.step===1&&turnStart!==void 0&&(nextStep?.claimSeq??-1)>turnStart&&(nextTurn?.claimSeq??-1)<turnStart&&nextStep!==void 0&&nextStep.firstClaimedHuman===void 0&&nextStep.currentClaimed.has(String(event.data.id));return{...contextMessage(event,event.data),waking:nextTurn?.currentClaimed.has(String(event.data.id))===true||idleSteer}}const id=String(event.data.id);const claim=reader.previous(`inbox-next-step`)?.state;return claim?.currentClaimed.has(id)===true?{kind:`steering`,messageId:event.data.id,seq:event.seq,time:event.time,content:event.data.content,source:event.data.source,...claim.firstClaimedHuman===id&&followsProcessEvidence(match.location,reader)?{batchStart:true}:{}}:{kind:`user`,messageId:event.data.id,seq:event.seq,time:event.time,content:event.data.content,source:event.data.source}},update:context=>context.state,buildViewNode:context=>{if(context.state===void 0)return null;const location=contextLocation(context);if(context.state.kind===`context`&&context.start?.event.type===`user/message`&&context.start.event.data.source.kind===`retry`&&context.start.event.data.content.length===0)return chatNode(context,`turn-trigger`,context.state.seq,context.state,{location,groupTree:`input`});const waking=context.state.kind===`context`&&context.start?.event.type===`user/message`&&context.state.waking===true;const human=context.state.kind===`user`||context.state.kind===`steering`;const opensExchange=human&&location.kind===`step`&&location.step.step===1;return chatNode(context,waking?`turn-trigger`:context.state.kind,context.state.seq,context.state,{location,groupTree:opensExchange?`exchange`:human||waking?`input`:void 0})}};const developerMessageDefinition={...messageDefinition,kind:`developer-message`,match:event=>event.type===`developer/message`?{id:String(event.data.message.id),role:`start`}:null,start:(_context,match)=>{const event=match.event;if(event.type!==`developer/message`)throw new Error(`developer-message start requires developer/message`);return contextMessage(event,event.data.message)}};function registerMessageConversationNode(ctx){ctx.uiConversation.events.register(messageDefinition);ctx.uiConversation.events.register(developerMessageDefinition)}function requestPromptAnchor(match,previous,isInitial){if(match.location.kind!==`step`)return match.event.seq;if(previous===void 0&&!isInitial)return match.event.seq;if(previous?.turn===match.location.turn.turn&&previous.step===match.location.step.step)return match.event.seq;return match.location.step.step===1?match.location.turn.start?.seq??match.location.step.start?.seq??match.event.seq:match.location.step.start?.seq??match.event.seq}function stableRequestPromptAnchor(context,match,previous,isInitial){const current=context.current.get(`chat`);return current?.kind===`system-prompt`?current.anchorSeq:requestPromptAnchor(match,previous,isInitial)}function systemMessageDefinition(inspect){return{kind:`system-message`,target:`chat`,match:event=>event.type===`system/message`||`surfaceOp`in event&&event.surfaceOp!==`append`?{id:String(event.seq),role:`start`}:null,start:(_context,match,reader)=>{if(match.event.type===`assistant/live-chunk`)throw new Error(`system-message requires a durable event`);return inspect(reader.previous(`system-message`)?.state,match.event)},update:context=>context.state,buildViewNode:context=>{const state=context.state?.introduced;const sectioned=state?.update===true&&state.message!==void 0;if(state===void 0||state.text===``&&!sectioned||context.start?.event.type!==`system/message`||context.start.event.surfaceOp!==`append`){const current=context.current.get(`chat`);if(current?.kind!==`system-prompt`)return null;return chatNode(context,`system-prompt`,current.anchorSeq,current.data,{visibility:`hidden`})}return chatNode(context,`system-prompt`,state.update?state.seq:requestPromptAnchor(context.start,void 0,true),{text:state.text,...state.update?{update:true}:{},...state.update&&state.message!==void 0?{message:state.message}:{}})}}}function requestPromptDefinition(inspect){return{kind:`request-prompt`,target:`chat`,match:event=>event.type===`request/header`?{id:String(event.seq),role:`start`}:null,start:(context,match,reader)=>{if(match.event.type!==`request/header`)throw new Error(`request-prompt start requires request/header`);const previous=reader.previous(`request-prompt`)?.state;const systemContext=reader.previous(`system-message`);const system=systemContext?.state.effective;const location=match.location.kind===`step`?{turn:match.location.turn.turn,step:match.location.step.step}:{};const inspection=inspect(previous?.prompt,match.event,system);const change=inspection.change?.kind;const systemEvent=systemContext?.matches[0]?.event;const shownByUpdate=system!==void 0&&systemEvent?.type===`system/message`&&systemEvent.surfaceOp===`append`&&(system.update||previous===void 0)&&system.turn===location.turn&&system.step===location.step;return{anchorSeq:stableRequestPromptAnchor(context,match,previous,match.event.data.reason===`initial`),showsPrompt:!shownByUpdate&&(previous===void 0||match.event.data.reason!==`change`||match.event.data.startsSeries===true||change===`system`||change===`system-and-tools`),...location,...inspection}},update:context=>context.state,buildViewNode:context=>{const state=context.state;if(state===void 0)return null;const current=context.current.get(`chat`);const visible=state.showsPrompt&&state.prompt.system!==``;if(!visible&&current?.kind!==`system-prompt`)return null;return chatNode(context,`system-prompt`,state.anchorSeq,{text:state.prompt.system},{visibility:visible?`visible`:`hidden`})}}}function registerRequestPromptConversationNode(ctx){ctx.uiConversation.events.register(systemMessageDefinition((previous,event)=>ctx.uiConversation.inspectSystemPrompt(previous,event)));ctx.uiConversation.events.register(requestPromptDefinition((previous,event,system)=>ctx.uiConversation.inspectRequestPrompt(previous,event,system)))}function scheduledNode(match){if(match.event.type!==`llm/retry`)return void 0;return{kind:`model-retry`,seq:match.event.seq,time:match.event.time,retryState:`scheduled`,...match.event.data}}function isClosed(location){return location.kind===`step`&&location.step.status===`closed`||(location.kind===`step`||location.kind===`turn`)&&location.turn.status===`closed`}function finallyFailed(location,current){if(current.retryState!==`started`||location.kind!==`step`)return false;const turn=location.turn;return turn.end?.data.reason.kind===`error`&&turn.steps.at(-1)?.step===current.step}const retryDefinition={kind:`model-retry`,target:`chat`,match:event=>{if(event.type===`llm/retry`){const retryId=event.data.retryId;if(typeof retryId!==`string`||retryId===``)return null;return{id:retryId,role:event.data.retry===1?`start`:`update`}}if(event.type===`llm/retry-started`){const retryId=event.data.retryId;return typeof retryId===`string`&&retryId!==``?{id:retryId,role:`update`}:null}return null},start:(_context,match)=>{const node=scheduledNode(match);if(node===void 0)throw new Error(`model-retry start requires a valid llm/retry event`);return{turn:node.turn,step:node.step,attempts:[node]}},update:(context,match)=>{if(match.event.type===`llm/retry`){const node=scheduledNode(match);return node===void 0?context.state:{...context.state,attempts:[...context.state.attempts,node]}}if(match.event.type!==`llm/retry-started`)return context.state;const retry=match.event.data.retry;return{...context.state,attempts:context.state.attempts.map(attempt=>attempt.retry===retry?{...attempt,retryState:`started`}:attempt)}},buildViewNode:context=>{if(context.state===void 0||context.state.attempts.length===0)return null;const location=context.start?.location??context.matches[0]?.location??{kind:`unresolved`};const stateAttempts=context.state.attempts;const attempts=stateAttempts.map((attempt,index)=>index===stateAttempts.length-1&&attempt.retryState===`scheduled`&&isClosed(location)?{...attempt,retryState:`cancelled`}:attempt);const current=attempts.at(-1);if(current===void 0)return null;const currentLocation=context.matches.findLast(match=>match.event.seq===current.seq)?.location??location;const data={attempts,current,inFlight:current.retryState===`started`&&!isClosed(currentLocation),failed:finallyFailed(currentLocation,current)};return chatNode(context,`model-retry`,attempts[0]?.seq??current.seq,data,{groupTree:`process`})}};function registerRetryConversationNode(ctx){ctx.uiConversation.events.register(retryDefinition)}const MAX_DEPTH=256;function emptyDispatchTree(){return{children:new Map,parents:new Map}}const projectedBlocks=new WeakMap;function jsonArguments(value){return JSON.stringify(value)}function rootCall(match,previous){if(match.event.type!==`tool/call`)throw new Error(`tool-call start requires tool/call`);return{phase:`start`,callId:String(match.event.data.callId),name:match.event.data.name,argsRaw:match.event.data.arguments,args:previous===void 0?PartialArguments.fromText(match.event.data.arguments):previous.args.settle(match.event.data.arguments),turn:match.event.data.turn,step:match.event.data.step,time:match.event.time,subCalls:[]}}function applyDelta(state,match){const event=match.event;if(event.type!==`assistant/live-chunk`)return state;const chunk=event.data.chunk;const root=state.root;if(chunk.type===`block-end`&&chunk.block.type===`tool-call`){if(root===void 0||`kind`in root||root.phase!==`preparing`)return state;return{...state,root:{...root,name:chunk.block.name,args:root.args.settle(chunk.block.arguments)}}}if(chunk.type!==`tool-call-delta`)return state;if(root===void 0){if(!chunk.name)return state;const args=new PartialArguments;args.append(chunk.argumentsDelta);return{...state,root:{phase:`preparing`,callId:String(chunk.id),name:chunk.name,turn:event.data.turn,step:event.data.step,time:event.time,subCalls:[],args}}}if(`kind`in root||root.phase!==`preparing`||root.args.isSealed)return state;root.args.append(chunk.argumentsDelta);return state}function preparingBlock(root,current){const changed=root.args.refresh();if(!changed&&current!==void 0&&!(`kind`in current)&&current.phase===`preparing`&&current.name===root.name&&current.args===root.args)return current;return changed?{...root}:root}function rootResult(match,previous){if(match.event.type!==`tool/result`)return void 0;const message=match.event.data.message;return{kind:`tool-result`,seq:match.event.seq,time:match.event.time,callId:String(message.source.callId),name:previous?.name??``,args:previous?.args??PartialArguments.EMPTY,call:previous===void 0?null:{name:previous.name,argsRaw:previous.argsRaw},callTime:previous?.time??null,content:message.content,isError:message.isError===true,...match.event.data.error===void 0?{}:{error:match.event.data.error},meta:match.event.data.meta,subCalls:[]}}function childCall(match,data){return{phase:`start`,callId:data.subCallId,parentCallId:data.parentCallId,name:data.name,argsRaw:jsonArguments(data.arguments),args:PartialArguments.fromObject(data.arguments),turn:locationTurn(match),step:locationStep(match),time:match.event.time,subCalls:[]}}function childResult(match,data,previous){return{kind:`tool-result`,seq:match.event.seq,time:match.event.time,callId:data.subCallId,parentCallId:data.parentCallId,name:data.name,args:previous!==void 0&&!(`kind`in previous)?previous.args:PartialArguments.fromObject(data.arguments),call:{name:data.name,argsRaw:jsonArguments(data.arguments)},callTime:previous?.time??null,content:data.content??[],meta:data.meta,isError:data.isError===true,...data.error===void 0?{}:{error:data.error},subCalls:[]}}function locationTurn(match){return match.location.kind===`step`||match.location.kind===`turn`?match.location.turn.turn:0}function locationStep(match){return match.location.kind===`step`?match.location.step.step:0}function acceptsEdge(state,parent,child){if(parent===child||state.calls.parents.has(child))return false;let cursor=parent;let parentDepth=0;const ancestors=new Set;while(cursor!==void 0){if(cursor===child||ancestors.has(cursor))return false;ancestors.add(cursor);parentDepth++;cursor=state.calls.parents.get(cursor)}const pending=[{callId:child,depth:1}];const descendants=new Set;let subtreeDepth=0;for(const candidate of pending){if(descendants.has(candidate.callId))return false;descendants.add(candidate.callId);subtreeDepth=Math.max(subtreeDepth,candidate.depth);for(const nested of state.calls.children.get(candidate.callId)?.values()??[])pending.push({callId:nested.callId,depth:candidate.depth+1})}return parentDepth+subtreeDepth<=MAX_DEPTH}function updateDispatch(state,match){const event=match.event;if(event.type!==`tool/ptc-dispatch-start`&&event.type!==`tool/ptc-dispatch`)return state;const data=event.data;const parentCallId=String(data.parentCallId);const subCallId=String(data.subCallId);const previous=state.calls.children.get(parentCallId)?.get(subCallId);if(event.type===`tool/ptc-dispatch-start`){if(previous!==void 0||!acceptsEdge(state,parentCallId,subCallId))return state;attachChild(state.calls,parentCallId,childCall(match,data));return state}if(previous===void 0&&!acceptsEdge(state,parentCallId,subCallId))return state;attachChild(state.calls,parentCallId,childResult(match,data,previous));return state}function attachChild(calls,parentCallId,child){let siblings=calls.children.get(parentCallId);if(siblings===void 0){siblings=new Map;calls.children.set(parentCallId,siblings)}siblings.set(child.callId,child);calls.parents.set(child.callId,parentCallId)}function projectBlock(block,state,interruptedAt,visited=new Set,depth=1){if(!(`kind`in block)&&block.phase===`preparing`)return block;if(visited.has(block.callId)||depth>MAX_DEPTH)return{...block,subCalls:[]};const nextVisited=new Set(visited);nextVisited.add(block.callId);const attached=state.calls.children.get(block.callId);const children=(attached===void 0?block.subCalls:[...attached.values()]).map(child=>projectBlock(child,state,interruptedAt,nextVisited,depth+1));const interruptionSeq=`kind`in block?void 0:interruptedAt?.seq;const interruptionTime=`kind`in block?void 0:interruptedAt?.time;const cached=projectedBlocks.get(block);if(cached!==void 0&&cached.interruptionSeq===interruptionSeq&&cached.interruptionTime===interruptionTime&&sameReferences(cached.children,children))return cached.value;const projected=`kind`in block||interruptedAt===void 0?sameReferences(block.subCalls,children)?block:{...block,subCalls:children}:{kind:`tool-result`,seq:interruptedAt.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedFollowup,time:interruptedAt.time,callId:block.callId,...block.parentCallId===void 0?{}:{parentCallId:block.parentCallId},name:block.name,args:block.args,call:{name:block.name,argsRaw:block.argsRaw},callTime:block.time,content:[],isError:true,error:{name:`Interrupted`,code:`interrupted`},subCalls:children};projectedBlocks.set(block,{children,interruptionSeq,interruptionTime,value:projected});return projected}function sameReferences(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function interruption(context){const location=context.start?.location;if(location?.kind===`step`&&location.step.status===`closed`)return location.step.end;if((location?.kind===`step`||location?.kind===`turn`)&&location.turn.status===`closed`)return location.turn.end}function fallbackState$2(context){const match=context.matches.find(candidate=>candidate.event.type===`tool/result`);const root=match===void 0?void 0:rootResult(match);if(root===void 0)return void 0;let state={root,calls:emptyDispatchTree()};for(const candidate of context.matches)state=updateDispatch(state,candidate);return state}const toolDefinition={kind:`tool-call`,target:`chat`,match:event=>{if(event.type===`assistant/live-chunk`){const chunk=event.data.chunk;if(chunk.type===`block-end`&&chunk.block.type===`tool-call`)return{id:String(chunk.block.id),role:`start`};return chunk.type===`tool-call-delta`?{id:String(chunk.id),role:`start`}:null}if(event.type===`tool/call`)return{id:String(event.data.callId),role:`start`};if(event.type===`tool/result`&&isAppendSurfaceEvent(event))return{id:String(event.data.message.source.callId),role:`update`};if(event.type===`tool/ptc-dispatch-start`||event.type===`tool/ptc-dispatch`){const rootCallId=event.data.rootCallId;return typeof rootCallId===`string`&&rootCallId!==``?{id:rootCallId,role:`update`}:null}return null},start:(_context,match)=>{const state={root:void 0,calls:emptyDispatchTree()};return match.event.type===`tool/call`?{...state,root:rootCall(match)}:applyDelta(state,match)},update:(context,match)=>{if(match.event.type===`assistant/live-chunk`)return applyDelta(context.state,match);if(match.event.type===`tool/call`)return{...context.state,root:rootCall(match,context.state.root)};if(match.event.type===`tool/result`){const root=context.state.root;const result=rootResult(match,root!==void 0&&!(`kind`in root)&&root.phase===`start`?root:void 0);return result===void 0?context.state:{...context.state,root:result}}return updateDispatch(context.state,match)},publication:match=>match.event.type===`assistant/live-chunk`?`animation-frame`:`immediate`,buildViewNode:context=>{const current=context.current.get(`chat`);const state=context.state??fallbackState$2(context);if(state?.root===void 0)return current==null?null:current.visibility===`hidden`?current:{...current,visibility:`hidden`};const interruptedAt=interruption(context);const projected=projectBlock(!(`kind`in state.root)&&state.root.phase===`preparing`?preparingBlock(state.root,current?.data.root):state.root,state,interruptedAt);const anchor=context.start?.event.seq??(`kind`in state.root?state.root.seq:context.matches[0]?.event.seq??0);const visibility=!(`kind`in projected)&&projected.phase===`preparing`&&interruptedAt!==void 0?`hidden`:`visible`;const location=contextLocation(context);const data=current?.data.root===projected?current.data:{root:projected};if(current?.data===data&&current.anchorSeq===anchor&&current.visibility===visibility&&current.location===location)return current;return chatNode(context,`tool-call`,anchor,data,{visibility,location})}};function registerToolConversationNode(ctx){const match=toolDefinition.match.bind(toolDefinition);ctx.uiConversation.events.register({...toolDefinition,match:{"assistant/live-chunk":match,"tool/call":match,"tool/result":match,"tool/ptc-dispatch-start":match,"tool/ptc-dispatch":match}})}function lastStep$1(context){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return 0;return location.turn.steps.at(-1)?.step??0}function endFailure(reason){switch(reason.kind){case`error`:return reason.error;case`aborted`:return reason.reason.kind===`hook`&&reason.reason.reason===`deepseek-account/signed-out`?{message:`Stopped because you signed out of DeepSeek.`,code:`ACCOUNT_SIGNED_OUT`}:void 0;case`interrupted`:return{message:`The DSH process exited before this turn finished.`,code:`INTERRUPTED`};default:return}}function failureFrom(match){if(match.event.type!==`turn/end`)return void 0;const failure=endFailure(match.event.data.reason);if(failure===void 0)return void 0;const display=displayFailure(failure);return{seq:match.event.seq,time:match.event.time,message:display.message,...display.code===void 0?{}:{code:display.code}}}function fallbackState$1(context){const end=context.matches.find(match=>failureFrom(match)!==void 0);if(end?.event.type!==`turn/end`)return void 0;const failure=failureFrom(end);if(failure===void 0)return void 0;return{turn:end.event.data.turn,failure}}const turnErrorDefinition={kind:`turn-error`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};if(event.type===`turn/end`&&endFailure(event.data.reason)!==void 0)return{id:String(event.data.turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-error start requires turn/start`);return{turn:match.event.data.turn}},update:(context,match)=>{const failure=failureFrom(match);return failure===void 0?context.state:{...context.state,failure}},buildViewNode:context=>{const state=context.state??fallbackState$1(context);if(state?.failure===void 0)return null;const failure=state.failure;const node={kind:`turn-error`,seq:failure.seq,time:failure.time,turn:state.turn,step:lastStep$1(context),message:failure.message,...failure.code===void 0?{}:{code:failure.code}};return chatNode(context,`turn-error`,node.seq,node,{groupTree:`turn`})}};function registerTurnErrorConversationNode(ctx){ctx.uiConversation.events.register(turnErrorDefinition)}function lastStep(context){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return 0;return location.turn.steps.at(-1)?.step??0}function noticeAnchor(context,seq){const location=context.start?.location??context.matches[0]?.location;if(location?.kind!==`turn`&&location?.kind!==`step`)return seq;const closing=location.turn.data.get(`turn-tail`)?.closing;return closing===null||closing===void 0?seq:closing.finalNode.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.maxTokensNotice}function stateFrom(match){if(match.event.type!==`turn/end`||match.event.data.reason.kind!==`max-tokens`)return void 0;return{turn:match.event.data.turn,seq:match.event.seq,time:match.event.time}}const turnMaxTokensDefinition={kind:`turn-max-tokens`,target:`chat`,match:event=>{if(event.type===`turn/end`&&event.data.reason.kind===`max-tokens`)return{id:String(event.data.turn),role:`start`};return null},start:(_context,match)=>{const state=stateFrom(match);if(state===void 0)throw new Error(`turn-max-tokens start requires a max-tokens turn/end`);return state},update:context=>context.state,buildViewNode:context=>{const state=context.state;if(state===void 0)return null;const node={kind:`turn-max-tokens`,seq:state.seq,time:state.time,turn:state.turn,step:lastStep(context)};return chatNode(context,`turn-max-tokens`,noticeAnchor(context,state.seq),node,{groupTree:`turn`})}};function registerTurnMaxTokensConversationNode(ctx){ctx.uiConversation.events.register(turnMaxTokensDefinition)}function eventTurn(event){const data=event.data;return typeof data.turn===`number`?data.turn:void 0}function visibleChunk(chunk){if(chunk.type===`text-delta`||chunk.type===`reasoning-delta`)return chunk.text.trim()!==``;if(chunk.type===`block-start`)return chunk.blockType!==`text`&&chunk.blockType!==`reasoning`&&chunk.blockType!==`tool-call`;if(chunk.type!==`block-end`)return false;const block=chunk.block;if(block.type===`tool-call`)return false;if(block.type===`text`||block.type===`reasoning`)return block.text.trim()!==``;return true}function visibleAssistantEvent(event){if(event.type===`assistant/live-chunk`)return visibleChunk(event.data.chunk);if(event.type===`assistant/attempt`)return false;return event.type===`assistant/message`&&event.surfaceOp===`append`&&toAssistantBlocks(event.data.message.content).some(block=>{if(block.kind===`tool-call`)return false;if(block.kind===`text`||block.kind===`reasoning`)return block.text.trim()!==``;return true})}function processEvidence(event){if(visibleAssistantEvent(event)){if(event.type!==`assistant/live-chunk`&&event.type!==`assistant/message`&&event.type!==`assistant/attempt`)return void 0;return{kind:`assistant`,seq:event.seq,step:event.data.step}}if(event.type===`tool/call`||event.type===`tool/result`&&event.surfaceOp===`append`||event.type===`llm/retry`)return{kind:`other`,seq:event.seq}}function durableEvidenceStep(event){if(processEvidence(event)===void 0)return void 0;switch(event.type){case`assistant/message`:case`tool/call`:case`tool/result`:case`llm/retry`:return{turn:event.data.turn,step:event.data.step};default:return}}const processEvidenceDefinition={kind:`process-evidence`,match:event=>{const coordinates=durableEvidenceStep(event);return coordinates===void 0?null:{id:`${coordinates.turn}:${coordinates.step}`,role:`start`}},start:(_context,match)=>{const coordinates=durableEvidenceStep(match.event);if(coordinates===void 0)throw new Error(`process-evidence start requires durable process evidence`);return{turn:coordinates.turn}},update:context=>context.state,publication:()=>`none`};function turnLocation$1(context){const location=context.start?.location??context.matches.at(-1)?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0}function fallbackState(context){const turn=context.matches.map(match=>eventTurn(match.event)).find(candidate=>candidate!==void 0);if(turn===void 0)return void 0;let state={turn,assistantStartByStep:new Map,messageCountByStep:new Map,messageCount:0,toolCallCount:0,subagentCount:0};for(const match of context.matches)state=updateProcessState(state,match.event);return state}function isFinalAssistant(data){return data?.finalNode!==void 0}function latestAnswer(turn){const data=turn.steps.at(-1)?.data.get(`assistant-step`);if(!isFinalAssistant(data)||!hasAssistantReplyContent(data.blocks))return null;return data.blocks.some(block=>block.kind===`tool-call`)?null:data}function processSpec(state,turn){const controlAnchorSeq=state.controlAnchorSeq??turn.start?.seq;if(controlAnchorSeq===void 0)return null;const answer=latestAnswer(turn);const counts={messageCount:answer===null?state.messageCount:[...state.messageCountByStep].filter(([step])=>step<answer.step).reduce((total,[,count])=>total+count,0),toolCallCount:state.toolCallCount,subagentCount:state.subagentCount};if(answer===null)return{turn:turn.turn,controlAnchorSeq,processStartSeq:controlAnchorSeq,answerAnchorSeq:null,answerStep:null,inlineReasoning:false,...counts};const inlineReasoning=answer.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``);const earlierAssistantSeq=Math.min(...[...state.assistantStartByStep].filter(([step])=>step<answer.step).map(([,seq])=>seq));const externalProcessSeq=Math.min(state.otherStartSeq??Number.POSITIVE_INFINITY,earlierAssistantSeq);return{turn:turn.turn,controlAnchorSeq,processStartSeq:turn.start?.seq??(Number.isFinite(externalProcessSeq)?externalProcessSeq:answer.finalNode.seq),answerAnchorSeq:answer.finalNode.seq,answerStep:answer.step,inlineReasoning,...counts}}function updateProcessState(state,event){let current=state;if(event.type===`assistant/message`&&event.surfaceOp===`append`&&hasAssistantReplyContent(toAssistantBlocks(event.data.message.content))){const messageCountByStep=new Map(current.messageCountByStep);messageCountByStep.set(event.data.step,(messageCountByStep.get(event.data.step)??0)+1);current={...current,messageCountByStep,messageCount:current.messageCount+1}}if(event.type===`tool/call`){const subagent=isSubagentDelegationTool(event.data.name);current={...current,toolCallCount:current.toolCallCount+(subagent?0:1),subagentCount:current.subagentCount+(subagent?1:0)}}const evidence=processEvidence(event);if(evidence===void 0)return current;if(evidence.kind===`other`)return current.otherStartSeq===void 0?{...current,otherStartSeq:evidence.seq,controlAnchorSeq:Math.min(current.controlAnchorSeq??Number.POSITIVE_INFINITY,evidence.seq)}:current;if(current.assistantStartByStep.has(evidence.step))return current;const assistantStartByStep=new Map(current.assistantStartByStep);assistantStartByStep.set(evidence.step,evidence.seq);return{...current,assistantStartByStep,controlAnchorSeq:Math.min(current.controlAnchorSeq??Number.POSITIVE_INFINITY,evidence.seq)}}const turnProcessDefinition={kind:`turn-process`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};const turn=eventTurn(event);if(turn===void 0)return null;if(event.type===`assistant/live-chunk`||event.type===`assistant/message`||event.type===`tool/call`||event.type===`tool/result`||event.type===`llm/retry`||event.type===`step/start`||event.type===`step/end`||event.type===`turn/end`)return{id:String(turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-process start requires turn/start`);return{turn:match.event.data.turn,assistantStartByStep:new Map,messageCountByStep:new Map,messageCount:0,toolCallCount:0,subagentCount:0}},update:(context,match)=>updateProcessState(context.state,match.event),publication:match=>{if(match.event.type===`assistant/live-chunk`){const type=match.event.data.chunk.type;return type===`usage`||type===`finish`?`none`:`animation-frame`}return`immediate`},buildLocationData:(context,scope,previous)=>{if(scope!==`turn`)return null;const state=context.state??fallbackState(context);if(state===void 0)return null;const turn=turnLocation$1(context);if(turn===void 0)return null;const current=context.current.get(`chat`);const latestStep=turn.steps.at(-1);if(previous?.kind===`turn`&&previous.key===`turn-process`&&current?.kind===`turn-process`&&current.data.answerAnchorSeq===null&&current.data.controlAnchorSeq===state.controlAnchorSeq&&current.data.messageCount===state.messageCount&&current.data.toolCallCount===state.toolCallCount&&current.data.subagentCount===state.subagentCount&&turn.status!==`closed`&&latestStep?.status!==`closed`)return previous;const spec=processSpec(state,turn);if(spec===null)return null;if(previous?.kind===`turn`&&previous.turn===spec.turn&&previous.key===`turn-process`&&sameTurnProcessSpec(previous.value,spec))return previous;return{kind:`turn`,turn:turn.turn,key:`turn-process`,value:spec}},buildViewNode:context=>{const turn=turnLocation$1(context);const data=turn?.data.get(`turn-process`);if(turn===void 0||data===void 0)return null;const current=context.current.get(`chat`);const state=context.state;if(current?.kind===`turn-process`&&state!==void 0&&current.data.answerAnchorSeq===null&&current.data.controlAnchorSeq===state.controlAnchorSeq&&current.data.messageCount===state.messageCount&&current.data.toolCallCount===state.toolCallCount&&current.data.subagentCount===state.subagentCount&&turn.status!==`closed`&&turn.steps.at(-1)?.status!==`closed`&&current.location===(context.start?.location??context.matches[0]?.location))return current;return chatNode(context,`turn-process`,data.controlAnchorSeq+CHAT_SYNTHETIC_SEQ_OFFSETS.processControl,data,{groupTree:`turn`})}};function registerTurnProcess(ctx){const match=turnProcessDefinition.match.bind(turnProcessDefinition);ctx.uiConversation.events.register({...turnProcessDefinition,match:{"turn/start":match,"assistant/live-chunk":match,"assistant/message":match,"tool/call":match,"tool/result":match,"llm/retry":match,"step/start":match,"step/end":match,"turn/end":match}});const evidence=processEvidenceDefinition.match.bind(processEvidenceDefinition);ctx.uiConversation.events.register({...processEvidenceDefinition,match:{"assistant/message":evidence,"tool/call":evidence,"tool/result":evidence,"llm/retry":evidence}})}const LLM_FAILURE_CODES={ABORTED:{},ACCOUNT_QUOTA:{},ACCOUNT_SIGN_IN_REQUIRED:{},ACCOUNT_TOKEN_INVALID:{},AUTH:{},CLIENT_UPGRADE_REQUIRED:{},CONTENT_REFUSED:{},CONTEXT_WINDOW_EXCEEDED:{},DISCOVERY_FAILED:{},DISCOVERY_UNSUPPORTED:{},DUPLICATE_ADAPTER:{},DUPLICATE_DIRECTORY:{},DUPLICATE_DISCOVERY:{},EMPTY_RESPONSE:{retryChoice:true},FILES_API:{},IMAGE_OFFLOAD_REQUIRED:{},INVALID_ADAPTER:{},INVALID_CATALOG:{},INVALID_CONFIG:{},INVALID_CREDENTIAL:{},INVALID_DIRECTORY:{},INVALID_DISCOVERY:{},INVALID_MODEL_CONTEXT:{},INVALID_MODEL_INFO:{},INVALID_MODEL_MAX_TOKENS:{},INVALID_MODEL_REASONING:{},INVALID_PREPARED_CALL:{},INVALID_REPLAY_STATE:{},INVALID_REQUEST:{},INVALID_RESPONSE:{},INVALID_TOOL_ARGUMENTS:{retryChoice:true},MALFORMED_RESPONSE:{retryChoice:true},MISSING_CREDENTIAL:{},MODEL_SWITCH_COMPACTION_FAILED:{},MODEL_UNSUPPORTED:{},NO_ADAPTER:{},NO_CREDENTIAL_STORE:{},NO_DISCOVERY:{},PI_AI_ERROR:{},QUOTA:{retryChoice:true},RATE_LIMIT:{retryChoice:true},REGISTRATION_DISPOSED:{},REQUEST_EXTENSION:{},REQUEST_HEADERS:{},SERVER:{retryChoice:true},STREAM_CLOSED:{retryChoice:true},TIMEOUT:{retryChoice:true},TRANSPORT:{retryChoice:true},UNKNOWN:{},UNKNOWN_MODEL:{},UNSTORABLE_PROVIDER_ID:{},UNSUPPORTED_CONTENT:{},UNSUPPORTED_OPTION:{},UNSUPPORTED_REASONING_EFFORT:{}};const RETRY_CODE_CHOICES=Object.freeze(Object.keys(LLM_FAILURE_CODES).filter(code=>`retryChoice`in LLM_FAILURE_CODES[code]));const STRUCTURED_CONTEXT_OVERFLOW=new RegExp(String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]`+String.raw`(?:exceed(?:ed|s)?|overflow(?:ed)?|limit[\s_-]exceeded)(?:$|[^a-z0-9])`,`i`);const TOO_LARGE_FOR_CONTEXT=new RegExp(String.raw`\b(?:request|prompt|input|messages?)\s+(?:is\s+|are\s+)?`+String.raw`too\s+(?:large|long)\s+for\s+(?:(?:this|the)\s+)?`+String.raw`(?:model(?:'s)?\s+)?context(?:\s+window)?\b`,`i`);const EXCEEDS_MODEL_CONTEXT=new RegExp(String.raw`\b(?:input|prompt|request|messages?)\b.{0,40}`+String.raw`\b(?:exceed(?:s|ed)?|overflows?|is\s+larger\s+than)\b.{0,40}`+String.raw`\b(?:the\s+)?(?:model(?:'s)?\s+)?context(?:\s+(?:length|window))?\b`,`i`);function lastAssistantStreamChunk(stream,type){for(let index=stream.length-1;index>=0;index-=1){const record=stream[index];if(record.type===`chunk`&&record.chunk.type===type)return record.chunk}}function isCount(value){return typeof value===`number`&&Number.isSafeInteger(value)&&value>=0}function safeSum(values){let total=0;for(const value of values){total+=value;if(!Number.isSafeInteger(total))return void 0}return total}function messageRoute(message){const{provider,model}=message.source;return provider.length>0&&model.length>0?{provider,model}:void 0}function streamUsage(stream){return lastAssistantStreamChunk(stream,`usage`)?.usage}function normalizeUsage(usage,route){const{inputTokens,outputTokens,cacheReadTokens,cacheWriteTokens,reasoningTokens,totalTokens}=usage;if(!isCount(inputTokens)||!isCount(outputTokens))return void 0;if(cacheReadTokens!==void 0&&!isCount(cacheReadTokens))return void 0;if(cacheWriteTokens!==void 0&&!isCount(cacheWriteTokens))return void 0;if(reasoningTokens!==void 0&&(!isCount(reasoningTokens)||reasoningTokens>outputTokens))return;const knownPrompt=safeSum([inputTokens,...cacheReadTokens===void 0?[]:[cacheReadTokens],...cacheWriteTokens===void 0?[]:[cacheWriteTokens]]);if(knownPrompt===void 0)return void 0;let exactTotal;if(totalTokens!==void 0){if(!isCount(totalTokens))return void 0;const exactPrompt=totalTokens-outputTokens;if(!isCount(exactPrompt)||exactPrompt<knownPrompt)return void 0;if(cacheReadTokens!==void 0&&cacheWriteTokens!==void 0&&exactPrompt!==knownPrompt)return;exactTotal=totalTokens}else{if(cacheReadTokens===void 0||cacheWriteTokens===void 0)return void 0;const derivedTotal=safeSum([knownPrompt,outputTokens]);if(derivedTotal===void 0)return void 0;exactTotal=derivedTotal}return{inputTokens,outputTokens,totalTokens:exactTotal,...cacheReadTokens===void 0?{}:{cacheReadTokens},...cacheWriteTokens===void 0?{}:{cacheWriteTokens},...reasoningTokens===void 0?{}:{reasoningTokens},...route===void 0?{}:{route}}}function aggregateAttempts(attempts){if(attempts.length===0)return void 0;const inputTokens=safeSum(attempts.map(attempt=>attempt.inputTokens));const outputTokens=safeSum(attempts.map(attempt=>attempt.outputTokens));const totalTokens=safeSum(attempts.map(attempt=>attempt.totalTokens));if(inputTokens===void 0||outputTokens===void 0||totalTokens===void 0)return void 0;const cacheRead=attempts.map(attempt=>attempt.cacheReadTokens);const cacheWrite=attempts.map(attempt=>attempt.cacheWriteTokens);const reasoning=attempts.map(attempt=>attempt.reasoningTokens);const cacheReadTokens=cacheRead.every(isCount)?safeSum(cacheRead):void 0;const cacheWriteTokens=cacheWrite.every(isCount)?safeSum(cacheWrite):void 0;const reasoningTokens=reasoning.every(isCount)?safeSum(reasoning):void 0;let routes;const attributed=attempts.map(attempt=>attempt.route);if(attributed.every(route=>route!==void 0)){const unique=new Map;for(const route of attributed)unique.set(`${route.provider}\0${route.model}`,route);routes=[...unique.values()]}return{uncachedInputTokens:inputTokens,outputTokens,totalTokens,...cacheReadTokens===void 0?{}:{cacheReadTokens},...cacheWriteTokens===void 0?{}:{cacheWriteTokens},...reasoningTokens===void 0?{}:{reasoningTokens},...routes===void 0?{}:{routes}}}function sameAttempt(state,turn,step){return state.turn===turn&&state.step===step}function deriveTurnTokenUsage(events){let state={kind:`idle`};const attempts=[];let turn;let sawEnd=false;let invalid=false;const closeOpen=route=>{if(state.kind!==`open`||state.sample===void 0)return false;const normalized=normalizeUsage(state.sample,route);if(normalized===void 0)return false;attempts.push(normalized);return true};for(const event of events){if(invalid)break;if(event.type===`turn/start`){if(turn!==void 0||state.kind!==`idle`)invalid=true;else turn=event.data.turn;continue}if(turn===void 0){invalid=true;break}if(event.type===`turn/end`){if(event.data.turn!==turn||state.kind!==`idle`||sawEnd)invalid=true;else sawEnd=true;continue}if(sawEnd){invalid=true;break}if(event.type===`step/start`){if(event.data.turn!==turn||state.kind!==`idle`)invalid=true;else state={kind:`open`,turn,step:event.data.step};continue}if(event.type===`llm/retry-started`){if(event.data.turn!==turn||state.kind!==`settled`||state.by!==`retry`||!sameAttempt(state,event.data.turn,event.data.step))invalid=true;else state={kind:`open`,turn,step:event.data.step};continue}if(event.type===`assistant/attempt`){if(event.data.turn!==turn||state.kind!==`open`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}const sample=streamUsage(event.data.stream)??state.sample;state={kind:`open`,turn,step:event.data.step,...sample===void 0?{}:{sample}};if(!closeOpen())invalid=true;else state={kind:`finishClosed`,turn,step:event.data.step};continue}if(event.type===`assistant/message`){if(event.data.turn!==turn||state.kind!==`open`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}const sample=event.data.usage??streamUsage(event.data.stream);if(sample!==void 0)state={...state,sample};if(!closeOpen(messageRoute(event.data.message)))invalid=true;else state={kind:`settled`,turn,step:event.data.step,by:`message`};continue}if(event.type===`llm/retry`){if(event.data.turn!==turn||state.kind===`idle`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}if(state.kind===`settled`||state.kind===`open`&&!closeOpen())invalid=true;if(!invalid)state={kind:`settled`,turn,step:event.data.step,by:`retry`};continue}if(event.type===`step/end`){if(event.data.turn!==turn||state.kind===`idle`||!sameAttempt(state,event.data.turn,event.data.step)){invalid=true;continue}if(state.kind===`open`&&!closeOpen())invalid=true;if(!invalid)state={kind:`idle`}}}return invalid||!sawEnd||state.kind!==`idle`?void 0:aggregateAttempts(attempts)}function isSessionEvent(event){return event.type!==`assistant/live-chunk`}function turnCoordinates(event){if(event.type===`assistant/message`||event.type===`assistant/attempt`||event.type===`assistant/live-chunk`||event.type===`step/start`||event.type===`step/end`)return{turn:event.data.turn,step:event.data.step};if(event.type===`llm/retry`||event.type===`llm/retry-started`)return{turn:event.data.turn,step:event.data.step}}function turnLocation(context){const location=context.start?.location??context.matches[0]?.location;return location?.kind===`turn`||location?.kind===`step`?location.turn:void 0}function hasText(data){return data.finalNode!==void 0&&data.blocks.some(block=>block.kind===`text`&&block.text.trim()!==``)}function tailData(context){const end=context.state===void 0?context.matches.find(match=>match.event.type===`turn/end`):context.state.end;if(end?.event.type!==`turn/end`)return null;const turn=turnLocation(context);if(turn===void 0)return null;const finalized=turn.steps.map(step=>step.data.get(`assistant-step`)).filter(candidate=>candidate!==void 0).filter(candidate=>candidate.finalNode!==void 0).sort((left,right)=>left.finalNode.seq-right.finalNode.seq);const closing=finalized.findLast(hasText)??null;let latestTranscriptSeq=finalized.at(-1)?.finalNode.seq;for(const match of context.matches){const event=match.event;const candidate=event.type===`tool/call`||event.type===`tool/result`&&event.surfaceOp===`append`||event.type===`turn/end`&&event.data.reason.kind===`error`||event.type===`llm/retry`?event.seq:void 0;if(candidate!==void 0&&(latestTranscriptSeq===void 0||candidate>latestTranscriptSeq))latestTranscriptSeq=candidate}const tokenUsage=context.start?.event.type===`turn/start`?deriveTurnTokenUsage(context.matches.map(match=>match.event).filter(isSessionEvent)):void 0;return{turn:end.event.data.turn,seq:end.event.seq,time:end.event.time,closing,branchUnavailable:closing===null||latestTranscriptSeq!==closing.finalNode.seq,...tokenUsage===void 0?{}:{tokenUsage}}}const turnTailDefinition={kind:`turn-tail`,target:`chat`,match:event=>{if(event.type===`turn/start`)return{id:String(event.data.turn),role:`start`};if(event.type===`turn/end`)return{id:String(event.data.turn),role:`update`};if(event.type===`tool/call`||event.type===`tool/result`)return{id:String(event.data.turn),role:`update`};const coordinates=turnCoordinates(event);if(coordinates!==void 0)return{id:String(coordinates.turn),role:`update`};return null},start:(_context,match)=>{if(match.event.type!==`turn/start`)throw new Error(`turn-tail start requires turn/start`);return{turn:match.event.data.turn}},update:(context,match)=>match.event.type===`turn/end`?{...context.state,end:match}:context.state,publication:match=>match.event.type===`turn/end`?`immediate`:`none`,buildLocationData:(context,scope)=>{if(scope!==`turn`)return null;const value=tailData(context);return value===null?null:{kind:`turn`,turn:value.turn,key:`turn-tail`,value}},buildViewNode:context=>{const data=turnLocation(context)?.data.get(`turn-tail`);return data===void 0?null:chatNode(context,`turn-tail`,data.seq+CHAT_SYNTHETIC_SEQ_OFFSETS.finalizedFollowup,data,{groupTree:`turn`})}};function registerTurnTailConversationNode(ctx){const match=turnTailDefinition.match.bind(turnTailDefinition);ctx.uiConversation.events.register({...turnTailDefinition,match:{"turn/start":match,"turn/end":match,"tool/call":match,"tool/result":match,"assistant/message":match,"assistant/attempt":match,"assistant/live-chunk":match,"step/start":match,"step/end":match,"llm/retry":match,"llm/retry-started":match}})}function activity(name){if(name===`read`)return`read`;if(name===`read_image`)return`readImage`;if(name===`grep`||name===`glob`||name.endsWith(`_inspect`))return`search`;if(name===`write`)return`write`;if(name===`edit`||name===`apply_patch`)return`edit`;if([`bash`,`pwsh`,`exec_command`,`write_stdin`].includes(name)||name.startsWith(`terminal_`))return`commands`;if(name===`run_code`||name===`cua_run_code`)return`code`;if(name===`web_search`)return`webSearch`;if(name===`web_fetch`)return`webFetch`;if(name===`subagent`||name.startsWith(`subagent_`))return`subagents`;if([`todo_write`,`create_goal`,`update_goal`,`get_goal`].includes(name))return`plan`;if(name===`ask_user_question`||name===`request_user_input`)return`questions`;return`tools`}const LIVE_TOOL_DETAIL_MAX_CHARS=160;const LIVE_TOOL_DETAIL_PREFIX_CHARS=512;const LIVE_TOOL_DETAIL_SEGMENTER=new Intl.Segmenter(void 0,{granularity:`grapheme`});const LIVE_TOOL_DETAIL_KEYS=[`title`,`description`,`objective`,`task`,`task_name`,`name`,`question`,`questions`,`prompt`,`message`,`command`,`cmd`,`queries`,`query`,`pattern`,`url`,`uri`,`file_path`,`path`,`target`,`action`,`status`];function normalizeLiveToolText(text){const normalized=text.replace(/\s+/g,` `).trim();if(normalized.length<=LIVE_TOOL_DETAIL_MAX_CHARS)return{text:normalized,truncated:false};const chars=[];for(const{segment}of LIVE_TOOL_DETAIL_SEGMENTER.segment(normalized)){if(chars.length===LIVE_TOOL_DETAIL_MAX_CHARS)return{text:`${chars.slice(0,LIVE_TOOL_DETAIL_MAX_CHARS-1).join(``).trimEnd()}…`,truncated:true};chars.push(segment)}return{text:normalized,truncated:false}}function normalizeLiveToolDetail(value){return normalizeLiveToolText(typeof value===`string`?value:Array.isArray(value)&&value.every(item=>typeof item===`string`)?value.join(`, `):``).text}function argumentTextDetail(args,key){let limit=LIVE_TOOL_DETAIL_PREFIX_CHARS;while(true){let prefix=args.textPrefix(key,limit);if(prefix===void 0)return void 0;const last=prefix.charCodeAt(prefix.length-1);if(last>=55296&&last<=56319){const extended=args.textPrefix(key,limit+1);const next=extended.charCodeAt(prefix.length);if(next>=56320&&next<=57343){prefix=extended;limit++}else if(extended.length===prefix.length&&!args.isSealed&&!args.complete(key))prefix=prefix.slice(0,-1)}const detail=normalizeLiveToolText(prefix);if(detail.truncated||!args.stringExceeds(key,limit))return detail.text;limit*=2}}function questionDetail(value){if(!Array.isArray(value))return``;for(const item of value){if(item===null||typeof item!==`object`)continue;const detail=normalizeLiveToolDetail(Reflect.get(item,`question`));if(detail!==``)return detail}return``}function liveReasoningDetail(nodes){for(let nodeIndex=nodes.length-1;nodeIndex>=0;nodeIndex--){const node=nodes[nodeIndex];if(node?.kind!==`assistant-step`||node.data.status!==`running`)continue;for(let blockIndex=node.data.blocks.length-1;blockIndex>=0;blockIndex--){const block=node.data.blocks[blockIndex];if(block?.kind!==`reasoning`)continue;const paragraphs=reasoningText(block.text).split(/\r?\n[\t ]*\r?\n/);for(let paragraphIndex=paragraphs.length-1;paragraphIndex>=0;paragraphIndex--){const detail=normalizeLiveToolDetail(paragraphs[paragraphIndex]?.replaceAll(`**`,``));if(detail!==``)return detail}}}return``}function liveToolDetail(name,args){for(const key of LIVE_TOOL_DETAIL_KEYS){if(!args.has(key))continue;const detail=key===`questions`?questionDetail(args.value(key)):argumentTextDetail(args,key)??normalizeLiveToolDetail(args.value(key));if(detail!==``)return detail}return args.closed()?normalizeLiveToolDetail(name):``}function processActivity(nodes){const counts=new Map;const seen=new Set;let running;let runningDetail=``;let runningTime=-Infinity;let preparing;const visit=tool=>{if(seen.has(tool.callId))return;seen.add(tool.callId);const call=isRunningTool(tool)?tool:tool.call;if(call!==null){const kind=activity(call.name);if(isRunningTool(tool)&&tool.time>=runningTime){running=kind;preparing=tool.phase===`preparing`;runningDetail=liveToolDetail(tool.name,tool.args);runningTime=tool.time}counts.set(kind,(counts.get(kind)??0)+1)}for(const child of tool.subCalls)visit(child)};for(const node of nodes)if(node.kind===`tool-call`)visit(node.data.root);if(running===void 0)runningDetail=liveReasoningDetail(nodes);if(nodes.length>0&&nodes.every(node=>node.kind===`context`))counts.set(`context`,nodes.length);return{counts:[...counts].map(([kind,count])=>({kind,count})).sort((a,b)=>b.count-a.count),running,runningDetail,...preparing?{preparing:true}:{}}}function turnOf(node){const location=node.location;return location.kind===`turn`||location.kind===`step`?location.turn.turn:void 0}function reasoning(node){return node.kind===`assistant-step`&&node.data.blocks.some(block=>block.kind===`reasoning`&&block.text.trim()!==``)}function reply(node){return node.kind===`assistant-step`&&hasAssistantReplyContent(node.data.blocks)}function sameSummary(left,right){return left.running===right.running&&left.runningDetail===right.runningDetail&&left.preparing===right.preparing&&left.counts.length===right.counts.length&&left.counts.every((value,index)=>value.kind===right.counts[index]?.kind&&value.count===right.counts[index].count)}function sameMembers(left,right){return left.length===right.length&&left.every((value,index)=>value.key===right[index]?.key&&value.groupPart===right[index].groupPart)}function structureChanged(previous,current){if(!isVisibleChatNode(current)&&(previous===void 0||!isVisibleChatNode(previous)))return false;return previous===void 0||previous.kind!==current.kind||turnOf(previous)!==turnOf(current)||isVisibleChatNode(previous)!==isVisibleChatNode(current)||previous.groupTree!==current.groupTree||reasoning(previous)!==reasoning(current)||reply(previous)!==reply(current)}function readNode(input,key){const node=input.readNode(key);if(node===void 0)throw new Error(`Chat grouping input is missing Node ${key}`);return node}var ProcessGroup=class{key;turn;members;nodes=[];snapshot;constructor(key,turn,members){this.key=key;this.turn=turn;this.members=members;this.snapshot={key,members,data:{turn,closed:false,summary:{counts:[],running:void 0,runningDetail:``}}}}refresh(input,closed){const nodes=this.members.map(member=>readNode(input,member.key));const unchanged=nodes.length===this.nodes.length&&nodes.every((node,index)=>node===this.nodes[index]);const previous=this.snapshot.data;const activity=unchanged&&previous.closed===closed?previous.summary:processActivity(nodes);const summary=closed?{counts:activity.counts,running:void 0,runningDetail:``}:activity;this.nodes=nodes;if(previous.closed!==closed||!sameSummary(previous.summary,summary))this.snapshot={key:this.key,members:this.members,data:{turn:this.turn,closed,summary}}}};var TurnGroups=class{turn;groups=new Map;membership=new Map;roots=new Map;constructor(turn){this.turn=turn}references(key){return this.roots.get(key)??[]}snapshots(){return[...this.groups.values()].map(group=>group.snapshot)}refresh(input,changed){const dirty=new Set;for(const node of changed){const group=this.membership.get(node);if(group!==void 0)dirty.add(group)}const ended=input.timeline.turns.get(this.turn)?.status===`closed`;if(ended){for(const group of this.groups.values())if(!group.snapshot.data.closed)dirty.add(group.key)}const upserts=[];for(const key of dirty){const group=this.groups.get(key);const previous=group.snapshot;group.refresh(input,previous.data.closed||ended);if(group.snapshot!==previous)upserts.push(group.snapshot)}return upserts}rebuild(input,added){const roots=new Map;const groups=new Map;const membership=new Map;let pending=[];const upserts=[];const emit=(key,entry)=>{roots.set(key,[...roots.get(key)??[],entry])};const flush=closed=>{const first=pending[0];if(first===void 0)return;const key=this.extendedGroup(pending,added)?.key??brandString(JSON.stringify([`process`,first.key,first.groupPart??null]));const previous=this.groups.get(key);const before=previous?.snapshot;const group=previous!==void 0&&sameMembers(previous.members,pending)?previous:new ProcessGroup(key,this.turn,pending);group.refresh(input,closed||input.timeline.turns.get(this.turn)?.status===`closed`);groups.set(group.key,group);emit(first.key,{kind:`group`,key:group.key});for(const member of pending)membership.set(member.key,group.key);if(group.snapshot!==before)upserts.push(group.snapshot);pending=[]};let previous;let followed=false;for(const key of input.readTurn(this.turn)){const position=readPosition(input,key);if(previous!==void 0&&position.previous!==previous)flush(true);previous=key;followed=position.next!==void 0;const node=readNode(input,key);if(isAtOrOutside(node,`process`)){flush(true);emit(key,{kind:`node`,key})}else if(node.kind===`assistant-step`){if(reasoning(node))pending.push({kind:`node`,key,groupPart:`reasoning`});if(reply(node)){flush(true);emit(key,{kind:`node`,key,groupPart:`response`})}}else pending.push({kind:`node`,key})}flush(followed);const removes=[...this.groups.keys()].filter(key=>!groups.has(key));this.groups=groups;this.membership=membership;this.roots=roots;return{upserts,removes}}extendedGroup(members,added){const offset=members.findIndex(member=>!added.has(member.key));const first=members[offset];if(first===void 0)return void 0;const key=this.membership.get(first.key);const previous=key===void 0?void 0:this.groups.get(key);if(previous===void 0||offset+previous.members.length>members.length)return void 0;for(let index=0;index<previous.members.length;index++){const before=previous.members[index];const after=members[offset+index];if(before.key!==after.key||before.groupPart!==after.groupPart)return void 0}for(let index=offset+previous.members.length;index<members.length;index++)if(!added.has(members[index].key))return void 0;return previous}};function readPosition(input,key){const position=input.readPosition(key);if(position===void 0)throw new Error(`Chat grouping order is missing position for Node ${key}`);return position}var ProcessState=class{turns=new Map;order=[];pending=null;accept(input){if(input.kind===`replace`){const previousKeys=new Set(this.order);const added=new Set(input.order.filter(key=>!previousKeys.has(key)));const turns=new Map;for(const key of input.order){const turn=readPosition(input,key).turn;if(turn===void 0||turns.has(turn))continue;const groups=this.turns.get(turn)??new TurnGroups(turn);groups.rebuild(input,added);turns.set(turn,groups)}this.turns=turns;this.order=input.order;this.pending={entries:this.rootEntries(input),groups:{kind:`replace`,snapshots:[...turns.values()].flatMap(turn=>turn.snapshots())}};return}const regroup=new Set(input.changedTurnOrders);const added=new Set;const changed=new Map;const touch=turn=>{let keys=changed.get(turn);if(keys===void 0){keys=new Set;changed.set(turn,keys)}return keys};for(const change of input.changes){const before=change.previous;const after=change.current;const turn=turnOf(after);if(before===void 0||!isVisibleChatNode(before))added.add(after.key);if(structureChanged(before,after)){const previousTurn=before===void 0?void 0:turnOf(before);if(previousTurn!==void 0)regroup.add(previousTurn);if(turn!==void 0)regroup.add(turn)}if(turn!==void 0)touch(turn).add(after.key)}for(const turn of input.changedTurns)touch(turn);const upserts=[];const removes=[];for(const turn of regroup){const groups=this.turns.get(turn)??new TurnGroups(turn);const update=groups.rebuild(input,added);upserts.push(...update.upserts);removes.push(...update.removes);if(input.readTurn(turn).length===0)this.turns.delete(turn);else this.turns.set(turn,groups)}for(const[turn,keys]of changed)if(!regroup.has(turn))upserts.push(...this.turns.get(turn)?.refresh(input,keys)??[]);const reordered=input.order!==this.order||regroup.size>0;this.order=input.order;const installed=new Set(upserts.map(group=>group.key));this.pending=reordered||upserts.length>0||removes.length>0?{...reordered?{entries:this.rootEntries(input)}:{},groups:{kind:`apply`,upserts,removes:removes.filter(key=>!installed.has(key))}}:null}rootEntries(input){return input.order.flatMap(key=>{const turn=readPosition(input,key).turn;if(turn===void 0)return[{kind:`node`,key}];const groups=this.turns.get(turn);if(groups===void 0)throw new Error(`Chat grouping order is missing Turn ${turn}`);return groups.references(key)})}output(){return this.pending}};const processGroupDefinition={kind:`process-groups`,target:`chat`,create:()=>new ProcessState,update:(context,input)=>{context.state.accept(input);return context.state},buildGroups:context=>context.state.output()};function registerConversationNodes(ctx){registerInboxConversationNodes(ctx);registerMessageConversationNode(ctx);registerRequestPromptConversationNode(ctx);registerAssistantConversationNode(ctx);registerTurnProcess(ctx);registerToolConversationNode(ctx);registerCommandConversationNode(ctx);registerCompactionConversationNode(ctx);registerInheritedHistoryConversationNode(ctx);registerRetryConversationNode(ctx);registerTurnErrorConversationNode(ctx);registerTurnMaxTokensConversationNode(ctx);registerTurnTailConversationNode(ctx);registerUnknownConversationFallback(ctx);registerChatConversationView(ctx);ctx.uiConversation.groups.register(processGroupDefinition)}function MathFenceLayer({code,streaming,children}){return streaming?children:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceMathBlock,{code})}function DiffFenceLayer({lang,code,streaming,t}){return(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.FenceCodeBlock,{lang,code,streaming,labels:(0,react.useMemo)(()=>markdownLabels(t).code,[t]),diff:true})}function registerFenceLayers(ctx){ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`math`,id:`@deepseek-ai/dsh-client-ui-chat/fence/math`},MathFenceLayer));ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`diff`,id:`@deepseek-ai/dsh-client-ui-chat/fence/diff`,locale:NS},DiffFenceLayer));ctx.slots.inject(`conversation.chat.markdown.fence`,()=>ctx.slots.register({name:`conversation.chat.markdown.fence`,key:`patch`,id:`@deepseek-ai/dsh-client-ui-chat/fence/diff`,locale:NS},DiffFenceLayer))}function QuotaNoticeHost({useNotice,dismissNotice,keepNoticeOpen,renderSlotChain,t}){const notice=useNotice(current=>current);if(notice===null)return null;const owner={code:notice.code,message:t(`message.failure.quota`),dismiss:dismissNotice,keepOpen:keepNoticeOpen};return(0,react_jsx_runtime.jsx)(react.Fragment,{children:renderSlotChain(`shell.quota-notice`,owner,{fallback:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Toast,{text:owner.message,icon:(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconWarningOutlineRegular,{size:18}),onDone:dismissNotice})})},`quota-notice-${String(notice.seq)}`)}function isNullable(value){return value===null||value===void 0}function isPlainObject(data){return data&&typeof data===`object`&&!Array.isArray(data)}function filterKeys(object,filter){return Object.fromEntries(Object.entries(object).filter(([key,value])=>filter(key,value)))}function mapValues(object,transform){return Object.fromEntries(Object.entries(object).map(([key,value])=>[key,transform(value,key)]))}function pick(source,keys,forced){if(!keys)return{...source};const result={};for(const key of keys)if(forced||source[key]!==void 0)result[key]=source[key];return result}const write=Symbol.for(`cosmokit.volatile.write`);function snapshot(value,ancestors=new Set){if(typeof value===`function`)throw new TypeError(`volatile config cannot contain functions`);if(value===null||typeof value!==`object`)return value;if(ancestors.has(value))throw new TypeError(`volatile config cannot contain cycles`);ancestors.add(value);try{if(Array.isArray(value))return Object.freeze(value.map(item=>snapshot(item,ancestors)));if(Object.getPrototypeOf(value)!==Object.prototype&&Object.getPrototypeOf(value)!==null)throw new TypeError(`volatile config objects must be plain objects or arrays`);return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,item])=>[key,snapshot(item,ancestors)])))}finally{ancestors.delete(value)}}function createVolatile(value){let current=snapshot(value);return Object.freeze({get:()=>current,[write]:value=>{current=value}})}function isVolatile(value){return typeof value===`object`&&value!==null&&write in value}function is(type,value){if(arguments.length===1)return value=>is(type,value);return type in globalThis&&value instanceof globalThis[type]||Object.prototype.toString.call(value).slice(8,-1)===type}function isArrayBufferLike(value){return is(`ArrayBuffer`,value)||is(`SharedArrayBuffer`,value)}function isArrayBufferSource(value){return isArrayBufferLike(value)||ArrayBuffer.isView(value)}var Binary;(function(Binary){Binary.is=isArrayBufferLike;Binary.isSource=isArrayBufferSource;function fromSource(source){if(ArrayBuffer.isView(source))return source.buffer.slice(source.byteOffset,source.byteOffset+source.byteLength);else return source}Binary.fromSource=fromSource;function toBase64(source){source=fromSource(source);if(typeof Buffer!==`undefined`)return Buffer.from(source).toString(`base64`);let binary=``;const bytes=new Uint8Array(source);for(let i=0;i<bytes.byteLength;i++)binary+=String.fromCharCode(bytes[i]);return btoa(binary)}Binary.toBase64=toBase64;function fromBase64(source){if(typeof Buffer!==`undefined`)return fromSource(Buffer.from(source,`base64`));return Uint8Array.from(atob(source),c=>c.charCodeAt(0))}Binary.fromBase64=fromBase64;function toHex(source){source=fromSource(source);if(typeof Buffer!==`undefined`)return Buffer.from(source).toString(`hex`);return Array.from(new Uint8Array(source),byte=>byte.toString(16).padStart(2,`0`)).join(``)}Binary.toHex=toHex;function fromHex(source){if(typeof Buffer!==`undefined`)return fromSource(Buffer.from(source,`hex`));const hex=source.length%2===0?source:source.slice(0,source.length-1);const buffer=[];for(let i=0;i<hex.length;i+=2)buffer.push(parseInt(`${hex[i]}${hex[i+1]}`,16));return Uint8Array.from(buffer).buffer}Binary.fromHex=fromHex})(Binary||(Binary={}));const base64ToArrayBuffer=Binary.fromBase64;const arrayBufferToBase64=Binary.toBase64;const hexToArrayBuffer=Binary.fromHex;const arrayBufferToHex=Binary.toHex;function clone(source,refs=new Map){if(!source||typeof source!==`object`)return source;if(is(`Date`,source))return new Date(source.valueOf());if(is(`RegExp`,source))return new RegExp(source.source,source.flags);if(isArrayBufferLike(source))return source.slice(0);if(ArrayBuffer.isView(source))return source.buffer.slice(source.byteOffset,source.byteOffset+source.byteLength);const cached=refs.get(source);if(cached)return cached;if(Array.isArray(source)){const result=[];refs.set(source,result);source.forEach((value,index)=>{result[index]=Reflect.apply(clone,null,[value,refs])});return result}const result=Object.create(Object.getPrototypeOf(source));refs.set(source,result);for(const key of Reflect.ownKeys(source)){const descriptor={...Reflect.getOwnPropertyDescriptor(source,key)};if(`value`in descriptor)descriptor.value=Reflect.apply(clone,null,[descriptor.value,refs]);Reflect.defineProperty(result,key,descriptor)}return result}function deepEqual(a,b,strict){const ancestors=new Set;function compare(a,b){if(a===b)return true;if(isVolatile(a)||isVolatile(b))return isVolatile(a)&&isVolatile(b);if(!strict&&isNullable(a)&&isNullable(b))return true;if(typeof a!==typeof b||typeof a!==`object`||!a||!b)return false;if(ancestors.has(a))return false;function check(test,then){return test(a)?test(b)?then(a,b):false:test(b)?false:void 0}ancestors.add(a);try{return check(Array.isArray,(a,b)=>{if(a.length!==b.length)return false;for(let index=0;index<a.length;index++)if(!compare(a[index],b[index]))return false;return true})??check(is(`Date`),(a,b)=>a.valueOf()===b.valueOf())??check(is(`URL`),(a,b)=>a.href===b.href)??check(is(`RegExp`),(a,b)=>a.source===b.source&&a.flags===b.flags)??check(isArrayBufferLike,(a,b)=>{if(a.byteLength!==b.byteLength)return false;const viewA=new Uint8Array(a);const viewB=new Uint8Array(b);for(let i=0;i<viewA.length;i++)if(viewA[i]!==viewB[i])return false;return true})??((!strict||[a,b].every(value=>Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null))&&Object.keys({...a,...b}).every(key=>compare(a[key],b[key])))}finally{ancestors.delete(a)}}return compare(a,b)}var Time;(function(Time){Time.millisecond=1;Time.second=1e3;Time.minute=Time.second*60;Time.hour=Time.minute*60;Time.day=Time.hour*24;Time.week=Time.day*7;let timezoneOffset=new Date().getTimezoneOffset();function setTimezoneOffset(offset){timezoneOffset=offset}Time.setTimezoneOffset=setTimezoneOffset;function getTimezoneOffset(){return timezoneOffset}Time.getTimezoneOffset=getTimezoneOffset;function getDateNumber(date=new Date,offset){if(typeof date===`number`)date=new Date(date);if(offset===void 0)offset=timezoneOffset;return Math.floor((date.valueOf()/Time.minute-offset)/1440)}Time.getDateNumber=getDateNumber;function fromDateNumber(value,offset){const date=new Date(value*Time.day);if(offset===void 0)offset=timezoneOffset;return new Date(+date+offset*Time.minute)}Time.fromDateNumber=fromDateNumber;const numeric=/\d+(?:\.\d+)?/.source;const timeRegExp=new RegExp(`^${[`w(?:eek(?:s)?)?`,`d(?:ay(?:s)?)?`,`h(?:our(?:s)?)?`,`m(?:in(?:ute)?(?:s)?)?`,`s(?:ec(?:ond)?(?:s)?)?`].map(unit=>`(${numeric}${unit})?`).join(``)}$`);function parseTime(source){const capture=timeRegExp.exec(source);if(!capture)return 0;return(parseFloat(capture[1])*Time.week||0)+(parseFloat(capture[2])*Time.day||0)+(parseFloat(capture[3])*Time.hour||0)+(parseFloat(capture[4])*Time.minute||0)+(parseFloat(capture[5])*Time.second||0)}Time.parseTime=parseTime;function parseDate(date){const parsed=parseTime(date);if(parsed)date=Date.now()+parsed;else if(/^\d{1,2}(:\d{1,2}){1,2}$/.test(date))date=`${new Date().toLocaleDateString()}-${date}`;else if(/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date))date=`${new Date().getFullYear()}-${date}`;return date?new Date(date):new Date}Time.parseDate=parseDate;function format(ms){const abs=Math.abs(ms);if(abs>=Time.day-Time.hour/2)return Math.round(ms/Time.day)+`d`;else if(abs>=Time.hour-Time.minute/2)return Math.round(ms/Time.hour)+`h`;else if(abs>=Time.minute-Time.second/2)return Math.round(ms/Time.minute)+`m`;else if(abs>=Time.second)return Math.round(ms/Time.second)+`s`;return ms+`ms`}Time.format=format;function toDigits(source,length=2){return source.toString().padStart(length,`0`)}Time.toDigits=toDigits;function template(template,time=new Date){return template.replace(`yyyy`,time.getFullYear().toString()).replace(`yy`,time.getFullYear().toString().slice(2)).replace(`MM`,toDigits(time.getMonth()+1)).replace(`dd`,toDigits(time.getDate())).replace(`hh`,toDigits(time.getHours())).replace(`mm`,toDigits(time.getMinutes())).replace(`ss`,toDigits(time.getSeconds())).replace(`SSS`,toDigits(time.getMilliseconds(),3))}Time.template=template})(Time||(Time={}));const kSchema=Symbol.for(`schemastery`);const kValidationError=Symbol.for(`ValidationError`);globalThis.__schemastery_index__??=0;globalThis.__schemastery_refs__=void 0;var ValidationError=class extends TypeError{options;name=`ValidationError`;constructor(message,options){let prefix=`$`;for(const segment of options.path||[])if(typeof segment===`string`)prefix+=`.`+segment;else if(typeof segment===`number`)prefix+=`[`+segment+`]`;else if(typeof segment===`symbol`)prefix+=`[Symbol(${segment.toString()})]`;if(prefix.startsWith(`.`))prefix=prefix.slice(1);super((prefix===`$`?``:`${prefix} `)+message);this.options=options}static is(error){return!!error?.[kValidationError]}};Object.defineProperty(ValidationError.prototype,kValidationError,{value:true});const Schema=function(options){const schema=function(data,options={}){return Schema.resolve(data,schema,options)[0]};if(options.refs){const refs=mapValues(options.refs,options=>new Schema(options));const getRef=uid=>refs[uid];for(const key in refs){const options=refs[key];options.sKey=getRef(options.sKey);options.inner=getRef(options.inner);options.list=options.list&&options.list.map(getRef);options.dict=options.dict&&mapValues(options.dict,getRef)}return refs[options.uid]}Object.assign(schema,options);if(typeof schema.callback===`string`)try{schema.callback=new Function(`return `+schema.callback)()}catch{}Object.defineProperty(schema,"uid",{value:globalThis.__schemastery_index__++});Object.setPrototypeOf(schema,Schema.prototype);schema.meta||={};schema.toString=schema.toString.bind(schema);return schema};Schema.prototype=Object.create(Function.prototype);Schema.prototype[kSchema]=true;Object.defineProperty(Schema.prototype,"~standard",{get(){return{version:1,vendor:`schemastery`,validate:value=>{try{return{value:Schema.resolve(value,this,{})[0]}}catch(error){if(ValidationError.is(error))return{issues:[{message:error.message,path:error.options.path}]};throw error}}}}});Schema.ValidationError=ValidationError;Schema.prototype.toJSON=function toJSON(){if(globalThis.__schemastery_refs__){globalThis.__schemastery_refs__[this.uid]??=JSON.parse(JSON.stringify({...this}));return this.uid}globalThis.__schemastery_refs__={[this.uid]:{...this}};globalThis.__schemastery_refs__[this.uid]=JSON.parse(JSON.stringify({...this}));const result={uid:this.uid,refs:globalThis.__schemastery_refs__};globalThis.__schemastery_refs__=void 0;return result};Schema.prototype.set=function set(key,value){this.dict[key]=value;return this};Schema.prototype.push=function push(value){this.list.push(value);return this};function mergeDesc(original,messages){const result=typeof original===`string`?{"":original}:{...original};for(const locale in messages){const value=messages[locale];if(value?.$description||value?.$desc)result[locale]=value.$description||value.$desc;else if(typeof value===`string`)result[locale]=value}return result}function getInner(value){return value?.$value??value?.$inner}function extractKeys(data){return filterKeys(data??{},key=>!key.startsWith(`$`))}Schema.prototype.i18n=function i18n(messages){const schema=Schema(this);const desc=mergeDesc(schema.meta.description,messages);if(Object.keys(desc).length)schema.meta.description=desc;if(schema.dict)schema.dict=mapValues(schema.dict,(inner,key)=>{return inner.i18n(mapValues(messages,data=>getInner(data)?.[key]??data?.[key]))});if(schema.list)schema.list=schema.list.map((inner,index)=>{return inner.i18n(mapValues(messages,(data={})=>{if(Array.isArray(getInner(data)))return getInner(data)[index];if(Array.isArray(data))return data[index];return extractKeys(data)}))});if(schema.inner)schema.inner=schema.inner.i18n(mapValues(messages,data=>{if(getInner(data))return getInner(data);return extractKeys(data)}));if(schema.sKey)schema.sKey=schema.sKey.i18n(mapValues(messages,data=>data?.$key));return schema};Schema.prototype.extra=function extra(key,value){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema};for(const key of[`required`,`disabled`,`collapse`,`hidden`,`loose`])Object.assign(Schema.prototype,{[key](value=true){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema}});Schema.prototype.deprecated=function deprecated(){const schema=Schema(this);schema.meta.badges||=[];schema.meta.badges.push({text:`deprecated`,type:`danger`});return schema};Schema.prototype.experimental=function experimental(){const schema=Schema(this);schema.meta.badges||=[];schema.meta.badges.push({text:`experimental`,type:`warning`});return schema};Schema.prototype.pattern=function pattern(regexp){const schema=Schema(this);const pattern=pick(regexp,[`source`,`flags`]);schema.meta={...schema.meta,pattern};return schema};Schema.prototype.simplify=function simplify(value){if(isVolatile(value))value=value.get();if(deepEqual(value,this.meta.default,this.type===`dict`))return null;if(isNullable(value))return value;if(this.type===`object`||this.type===`dict`){const result={};for(const key in value){const item=(this.type===`object`?this.dict[key]:this.inner)?.simplify(value[key]);if(this.type===`dict`||!isNullable(item))result[key]=item}if(deepEqual(result,this.meta.default,this.type===`dict`))return null;return result}else if(this.type===`array`||this.type===`tuple`){const result=[];value.forEach((value,index)=>{const schema=this.type===`array`?this.inner:this.list[index];const item=schema?schema.simplify(value):value;result.push(item)});return result}else if(this.type===`intersect`){const result={};for(const item of this.list)Object.assign(result,item.simplify(value));return result}else if(this.type===`union`)for(const schema of this.list)try{Schema.resolve(value,schema,{});return schema.simplify(value)}catch{}return value};Schema.prototype.toString=function toString(inline){return formatters[this.type]?.(this,inline)??`Schema<${this.type}>`};Schema.prototype.role=function role(role,extra){const schema=Schema(this);schema.meta={...schema.meta,role,extra};return schema};for(const key of[`default`,`link`,`comment`,`description`,`max`,`min`,`step`])Object.assign(Schema.prototype,{[key](value){const schema=Schema(this);schema.meta={...schema.meta,[key]:value};return schema}});Schema.prototype.volatile=function volatile(){if(this.meta.volatile)throw new TypeError(`volatile schema is already wrapped`);return this.extra(`volatile`,true)};const resolvers={};const checkedVolatile=Symbol(`checked-volatile-schema`);function validateVolatileSchema(schema,path=[],blocked=false,seen=new Map){const states=seen.get(schema)??new Set;if(states.has(blocked))return;states.add(blocked);seen.set(schema,states);if(schema.meta?.volatile&&blocked)throw new ValidationError(`volatile fields require a fixed object path without an enclosing volatile field`,{path});const nested=blocked||!!schema.meta?.volatile;if(schema.dict)for(const[key,child]of Object.entries(schema.dict))validateVolatileSchema(child,[...path,key],nested,seen);if(schema.sKey)validateVolatileSchema(schema.sKey,[...path,`<key>`],true,seen);if(schema.inner&&(schema.type!==`lazy`||schema.inner[kSchema]))validateVolatileSchema(schema.inner,[...path,`*`],true,seen);if(schema.list)for(let index=0;index<schema.list.length;index++)validateVolatileSchema(schema.list[index],[...path,String(index)],true,seen)}Schema.extend=function extend(type,resolve){resolvers[type]=resolve};Schema.resolve=function resolve(data,schema,options={},strict=false){if(!schema)return[data];if(!options[checkedVolatile]){validateVolatileSchema(schema,options.path);options={...options,[checkedVolatile]:true}}if(schema.meta?.volatile){const inner=Schema(schema);inner.meta={...schema.meta,volatile:false};const[value,adapted]=Schema.resolve(data,inner,options,strict);try{return[createVolatile(value),adapted]}catch(error){throw new ValidationError(error instanceof Error?error.message:String(error),options)}}if(options.ignore?.(data,schema))return[data];if(isNullable(data)&&schema.type!==`lazy`){if(schema.meta.required)throw new ValidationError(`missing required value`,options);let current=schema;let fallback=schema.meta.default;while(current?.type===`intersect`&&isNullable(fallback)){current=current.list[0];fallback=current?.meta.default}if(isNullable(fallback))return[data];data=clone(fallback)}const callback=resolvers[schema.type];if(!callback)throw new ValidationError(`unsupported type "${schema.type}"`,options);try{return callback(data,schema,options,strict)}catch(error){if(!schema.meta.loose)throw error;return[schema.meta.default]}};Schema.from=function from(source){if(isNullable(source))return Schema.any();else if([`string`,`number`,`boolean`].includes(typeof source))return Schema.const(source).required();else if(source[kSchema])return source;else if(typeof source===`function`)switch(source){case String:return Schema.string().required();case Number:return Schema.number().required();case Boolean:return Schema.boolean().required();case Function:return Schema.function().required();default:return Schema.is(source).required()}else throw new TypeError(`cannot infer schema from ${source}`)};Schema.lazy=function lazy(builder){const toJSON=()=>{if(!schema.inner[kSchema]){schema.inner=schema.builder();schema.inner.meta={...schema.meta,...schema.inner.meta}}return schema.inner.toJSON()};const schema=new Schema({type:`lazy`,builder,inner:{toJSON}});return schema};Schema.natural=function natural(){return Schema.number().step(1).min(0)};Schema.percent=function percent(){return Schema.number().step(.01).min(0).max(1).role(`slider`)};Schema.date=function date(){return Schema.union([Schema.is(Date),Schema.transform(Schema.string().role(`datetime`),(value,options)=>{const date=new Date(value);if(isNaN(+date))throw new ValidationError(`invalid date "${value}"`,options);return date},true)])};Schema.regExp=function regExp(flag=``){return Schema.union([Schema.is(RegExp),Schema.transform(Schema.string().role(`regexp`,{flag}),(value,options)=>{try{return new RegExp(value,flag)}catch(e){throw new ValidationError(e.message,options)}},true)])};Schema.arrayBuffer=function arrayBuffer(encoding){return Schema.union([Schema.is(ArrayBuffer),Schema.is(SharedArrayBuffer),Schema.transform(Schema.any(),(value,options)=>{if(Binary.isSource(value))return Binary.fromSource(value);throw new ValidationError(`expected ArrayBufferSource but got ${value}`,options)},true),...encoding?[Schema.transform(Schema.string(),(value,options)=>{try{return encoding===`base64`?Binary.fromBase64(value):Binary.fromHex(value)}catch(e){throw new ValidationError(e.message,options)}},true)]:[]])};Schema.extend(`lazy`,(data,schema,options,strict)=>{if(!schema.inner[kSchema]){schema.inner=schema.builder();schema.inner.meta={...schema.meta,...schema.inner.meta};validateVolatileSchema(schema.inner,options.path,true)}return Schema.resolve(data,schema.inner,options,strict)});Schema.extend(`any`,data=>{return[data]});Schema.extend(`never`,(data,_,options)=>{throw new ValidationError(`expected nullable but got ${data}`,options)});Schema.extend(`const`,(data,{value},options)=>{if(deepEqual(data,value))return[value];throw new ValidationError(`expected ${value} but got ${data}`,options)});function checkWithinRange(data,meta,description,options,skipMin=false){const{max=Infinity,min=-Infinity}=meta;if(data>max)throw new ValidationError(`expected ${description} <= ${max} but got ${data}`,options);if(data<min&&!skipMin)throw new ValidationError(`expected ${description} >= ${min} but got ${data}`,options)}Schema.extend(`string`,(data,{meta},options)=>{if(typeof data!==`string`)throw new ValidationError(`expected string but got ${data}`,options);if(meta.pattern){const regexp=new RegExp(meta.pattern.source,meta.pattern.flags);if(!regexp.test(data))throw new ValidationError(`expect string to match regexp ${regexp}`,options)}checkWithinRange(data.length,meta,`string length`,options);return[data]});function decimalShift(data,digits){const str=data.toString();if(str.includes(`e`))return data*Math.pow(10,digits);const index=str.indexOf(`.`);if(index===-1)return data*Math.pow(10,digits);const frac=str.slice(index+1);const integer=str.slice(0,index);if(frac.length<=digits)return+(integer+frac.padEnd(digits,`0`));return+(integer+frac.slice(0,digits)+`.`+frac.slice(digits))}function isMultipleOf(data,min,step){step=Math.abs(step);if(!/^\d+\.\d+$/.test(step.toString()))return(data-min)%step===0;const index=step.toString().indexOf(`.`);const digits=step.toString().slice(index+1).length;return Math.abs(decimalShift(data,digits)-decimalShift(min,digits))%decimalShift(step,digits)===0}Schema.extend(`number`,(data,{meta},options)=>{if(typeof data!==`number`)throw new ValidationError(`expected number but got ${data}`,options);checkWithinRange(data,meta,`number`,options);const{step}=meta;if(step&&!isMultipleOf(data,meta.min??0,step))throw new ValidationError(`expected number multiple of ${step} but got ${data}`,options);return[data]});Schema.extend(`boolean`,(data,_,options)=>{if(typeof data===`boolean`)return[data];throw new ValidationError(`expected boolean but got ${data}`,options)});Schema.extend(`bitset`,(data,{bits,meta},options)=>{let value=0,keys=[];if(typeof data===`number`){value=data;for(const key in bits)if(data&bits[key])keys.push(key)}else if(Array.isArray(data)){keys=data;for(const key of keys){if(typeof key!==`string`)throw new ValidationError(`expected string but got ${key}`,options);if(key in bits)value|=bits[key]}}else throw new ValidationError(`expected number or array but got ${data}`,options);if(value===meta.default)return[value];return[value,keys]});Schema.extend(`function`,(data,_,options)=>{if(typeof data===`function`)return[data];throw new ValidationError(`expected function but got ${data}`,options)});Schema.extend(`is`,(data,{constructor},options)=>{if(typeof constructor===`function`){if(data instanceof constructor)return[data];throw new ValidationError(`expected ${constructor.name} but got ${data}`,options)}else{if(isNullable(data))throw new ValidationError(`expected ${constructor} but got ${data}`,options);let prototype=Object.getPrototypeOf(data);while(prototype){if(prototype.constructor?.name===constructor)return[data];prototype=Object.getPrototypeOf(prototype)}throw new ValidationError(`expected ${constructor} but got ${data}`,options)}});function property(data,key,schema,options){try{const[value,adapted]=Schema.resolve(data[key],schema,{...options,path:[...options.path||[],key]});if(adapted!==void 0)data[key]=adapted;return value}catch(e){if(!options?.autofix)throw e;delete data[key];return schema.meta.volatile?createVolatile(schema.meta.default):schema.meta.default}}Schema.extend(`array`,(data,{inner,meta},options)=>{if(!Array.isArray(data))throw new ValidationError(`expected array but got ${data}`,options);checkWithinRange(data.length,meta,`array length`,options,!isNullable(inner.meta.default));return[data.map((_,index)=>property(data,index,inner,options))]});Schema.extend(`dict`,(data,{inner,sKey},options,strict)=>{if(!isPlainObject(data))throw new ValidationError(`expected object but got ${data}`,options);const result={};for(const key in data){let rKey;try{rKey=Schema.resolve(key,sKey,options)[0]}catch(error){if(strict)continue;throw error}result[rKey]=property(data,key,inner,options);data[rKey]=data[key];if(key!==rKey)delete data[key]}return[result]});Schema.extend(`tuple`,(data,{list},options,strict)=>{if(!Array.isArray(data))throw new ValidationError(`expected array but got ${data}`,options);const result=list.map((inner,index)=>property(data,index,inner,options));if(strict)return[result];result.push(...data.slice(list.length));return[result]});function merge(result,data){for(const key in data){if(key in result)continue;result[key]=data[key]}}Schema.extend(`object`,(data,{dict},options,strict)=>{if(!isPlainObject(data))throw new ValidationError(`expected object but got ${data}`,options);const result={};for(const key in dict){const value=property(data,key,dict[key],options);if(!isNullable(value)||key in data)result[key]=value}if(!strict)merge(result,data);return[result]});Schema.extend(`union`,(data,{list,toString},options,strict)=>{const messages=[];for(const inner of list)try{return Schema.resolve(data,inner,options,strict)}catch(error){messages.push(error)}throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options)});Schema.extend(`intersect`,(data,{list,toString},options,strict)=>{if(!list.length)return[data];let result;for(const inner of list){const value=Schema.resolve(data,inner,options,true)[0];if(isNullable(value))continue;if(isNullable(result))result=value;else if(typeof result!==typeof value)throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options);else if(typeof value===`object`)merge(result??={},value);else if(result!==value)throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`,options)}if(!strict&&isPlainObject(data))merge(result,data);return[result]});Schema.extend(`transform`,(data,{inner,callback,preserve},options)=>{const[result,adapted=data]=Schema.resolve(data,inner,options,true);if(preserve)return[callback(result)];else return[callback(result),callback(adapted)]});const formatters={};function defineMethod(name,keys,format){formatters[name]=format;Object.assign(Schema,{[name](...args){const schema=new Schema({type:name});keys.forEach((key,index)=>{switch(key){case`sKey`:schema.sKey=args[index]??Schema.string();break;case`inner`:schema.inner=Schema.from(args[index]);break;case`list`:schema.list=args[index].map(Schema.from);break;case`dict`:schema.dict=mapValues(args[index],Schema.from);break;case`bits`:schema.bits={};for(const key in args[index]){if(typeof args[index][key]!==`number`)continue;schema.bits[key]=args[index][key]}break;case`callback`:{const callback=schema.callback=args[index];callback[`toJSON`]||=()=>callback.toString();break}case`constructor`:{const constructor=schema.constructor=args[index];if(typeof constructor===`function`)constructor[`toJSON`]||=()=>constructor[`name`];break}default:schema[key]=args[index]}});if(name===`object`||name===`dict`)schema.meta.default={};else if(name===`array`||name===`tuple`)schema.meta.default=[];else if(name===`bitset`)schema.meta.default=0;return schema}})}defineMethod(`is`,[`constructor`],({constructor})=>{if(typeof constructor===`function`)return constructor.name;else return constructor});defineMethod(`any`,[],()=>`any`);defineMethod(`never`,[],()=>`never`);defineMethod(`const`,[`value`],({value})=>typeof value===`string`?JSON.stringify(value):value);defineMethod(`string`,[],()=>`string`);defineMethod(`number`,[],()=>`number`);defineMethod(`boolean`,[],()=>`boolean`);defineMethod(`bitset`,[`bits`],()=>`bitset`);defineMethod(`function`,[],()=>`function`);defineMethod(`array`,[`inner`],({inner})=>`${inner.toString(true)}[]`);defineMethod(`dict`,[`inner`,`sKey`],({inner,sKey})=>`{ [key: ${sKey.toString()}]: ${inner.toString()} }`);defineMethod(`tuple`,[`list`],({list})=>`[${list.map(inner=>inner.toString()).join(`, `)}]`);defineMethod(`object`,[`dict`],({dict})=>{if(Object.keys(dict).length===0)return`{}`;return`{ ${Object.entries(dict).map(([key,inner])=>{return`${key}${inner.meta.required?``:`?`}: ${inner.toString()}`}).join(`, `)} }`});defineMethod(`union`,[`list`],({list},inline)=>{const result=list.map(({toString:format})=>format()).join(` | `);return inline?`(${result})`:result});defineMethod(`intersect`,[`list`],({list})=>{return`${list.map(inner=>inner.toString(true)).join(` & `)}`});defineMethod(`transform`,[`inner`,`callback`,`preserve`],({inner},isInner)=>inner.toString(isInner));const CHAT_SETTINGS_NAMESPACE=`ui-chat`;const TRANSCRIPT_VIEW_FIELD=`transcriptView`;const COLLAPSE_TIMING_FIELD=`collapseTiming`;const COLLAPSE_TIMINGS=[`completion`,`next-input`];const DEFAULT_COLLAPSE_TIMING=`completion`;const FOLDED_REPLIES_FIELD=`foldedReplies`;const FOLDED_REPLIES=[`all`,`final`];const DEFAULT_FOLDED_REPLIES=`all`;const TRANSCRIPT_VIEW_MODES=[`compact`,`standard`,`detailed`,`verbose`];const LEGACY_TRANSCRIPT_VIEW_MODE=`normal`;const LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE=`expanded`;const TRANSCRIPT_VIEW_SETTING_VALUES=[...TRANSCRIPT_VIEW_MODES,LEGACY_TRANSCRIPT_VIEW_MODE,LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE];const DEFAULT_TRANSCRIPT_VIEW_MODE=`detailed`;const PERFORMANCE_USAGE_MODES=[`compact`,`detailed`];const DEFAULT_PERFORMANCE_USAGE=`detailed`;const DEFAULT_LINK_OPENING=`sidebar`;const ChatSettingsFields={[COLLAPSE_TIMING_FIELD]:Schema.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING),[FOLDED_REPLIES_FIELD]:Schema.union([...FOLDED_REPLIES]).default(`all`),linkOpening:Schema.union([`sidebar`,`new-tab`]).default(DEFAULT_LINK_OPENING),performanceUsage:Schema.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE),[TRANSCRIPT_VIEW_FIELD]:Schema.union([...TRANSCRIPT_VIEW_SETTING_VALUES]).loose()};const ChatSettingsSchema=Schema.object(ChatSettingsFields);const POLICIES={compact:{mode:`compact`,foldCompletedTurns:true,stepGrouping:`collapsed`,liveProcessDetail:false,settledReasoningPreview:false,programCallsOpen:false},standard:{mode:`standard`,foldCompletedTurns:true,stepGrouping:`collapsed`,liveProcessDetail:true,settledReasoningPreview:true,programCallsOpen:false},detailed:{mode:`detailed`,foldCompletedTurns:true,stepGrouping:`history`,liveProcessDetail:true,settledReasoningPreview:true,programCallsOpen:false},verbose:{mode:`verbose`,foldCompletedTurns:false,stepGrouping:`none`,liveProcessDetail:false,settledReasoningPreview:true,programCallsOpen:true}};function withTiming(collapseTiming,foldedReplies){return{compact:{...POLICIES.compact,collapseTiming,foldedReplies},standard:{...POLICIES.standard,collapseTiming,foldedReplies},detailed:{...POLICIES.detailed,collapseTiming,foldedReplies},verbose:{...POLICIES.verbose,collapseTiming,foldedReplies}}}const TIMING_POLICIES={completion:{all:withTiming(`completion`,`all`),final:withTiming(`completion`,`final`)},"next-input":{all:withTiming(`next-input`,`all`),final:withTiming(`next-input`,`final`)}};function presentationPolicyFor(mode,collapseTiming=`completion`,foldedReplies=`all`){return TIMING_POLICIES[collapseTiming][foldedReplies][mode]}function derivePresentationPolicy(mode,collapseTiming,foldedReplies){return{getSnapshot:()=>presentationPolicyFor(mode.getSnapshot(),collapseTiming.getSnapshot(),foldedReplies.getSnapshot()),subscribe:listener=>{const unsubscribeMode=mode.subscribe(listener);const unsubscribeTiming=collapseTiming.subscribe(listener);const unsubscribeReplies=foldedReplies.subscribe(listener);return()=>{unsubscribeMode();unsubscribeTiming();unsubscribeReplies()}}}}var PreferenceRow_module_css_default={"chevron":`_2XZxNq_chevron`,"desc":`_2XZxNq_desc`,"row":`_2XZxNq_row`,"rowText":`_2XZxNq_rowText`,"selector":`_2XZxNq_selector`,"title":`_2XZxNq_title`};function PreferenceRow({title,description,value,selectedLabel,options,onSelect}){const[open,setOpen]=(0,react.useState)(false);const selectorRef=(0,react.useRef)(null);const closeMenu=(0,react.useCallback)(()=>{setOpen(false)},[]);const selectMode=(0,react.useCallback)(id=>{selectorRef.current?.focus({preventScroll:true});closeMenu();onSelect(id)},[closeMenu,onSelect]);const selector=(0,react_jsx_runtime.jsxs)(`button`,{ref:selectorRef,type:`button`,className:PreferenceRow_module_css_default.selector,"aria-haspopup":`menu`,"aria-expanded":open,onClick:()=>{setOpen(value=>!value)},children:[selectedLabel,(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.IconChevronDownOutlineRegular,{className:PreferenceRow_module_css_default.chevron})]});return(0,react_jsx_runtime.jsxs)(`div`,{className:PreferenceRow_module_css_default.row,children:[(0,react_jsx_runtime.jsxs)(`div`,{className:PreferenceRow_module_css_default.rowText,children:[(0,react_jsx_runtime.jsx)(`div`,{className:PreferenceRow_module_css_default.title,children:title}),(0,react_jsx_runtime.jsx)(`div`,{className:PreferenceRow_module_css_default.desc,children:description})]}),(0,react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives_client.Menu,{open,onClose:closeMenu,items:options,selectedId:value,onSelect:selectMode,align:`end`,portal:true,anchor:selector})]})}const LABELS={compact:`settings.transcript.compact`,standard:`settings.transcript.standard`,detailed:`settings.transcript.detailed`,verbose:`settings.transcript.verbose`};const COLLAPSE_LABELS={completion:`settings.collapse.completion`,"next-input":`settings.collapse.nextInput`};const FOLDED_REPLY_LABELS={all:`settings.foldedReplies.all`,final:`settings.foldedReplies.final`};function TranscriptViewRow({useTranscriptView,setTranscriptView,useCollapseTiming,setCollapseTiming,useFoldedReplies,setFoldedReplies,t}){const mode=useTranscriptView(value=>value);const timing=useCollapseTiming(value=>value);const replies=useFoldedReplies(value=>value);const selectMode=(0,react.useCallback)(value=>{setTranscriptView(value)},[setTranscriptView]);const selectTiming=(0,react.useCallback)(value=>{setCollapseTiming(value)},[setCollapseTiming]);const selectReplies=(0,react.useCallback)(value=>{setFoldedReplies(value)},[setFoldedReplies]);return(0,react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment,{children:[(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.transcript.title`),description:t(`settings.transcript.description`),value:mode,selectedLabel:t(LABELS[mode]),options:TRANSCRIPT_VIEW_MODES.map(id=>({id,label:t(LABELS[id])})),onSelect:selectMode}),(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.collapse.title`),description:t(`settings.collapse.description`),value:timing,selectedLabel:t(COLLAPSE_LABELS[timing]),options:COLLAPSE_TIMINGS.map(id=>({id,label:t(COLLAPSE_LABELS[id])})),onSelect:selectTiming}),mode!==`verbose`&&(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.foldedReplies.title`),description:t(`settings.foldedReplies.description`),value:replies,selectedLabel:t(FOLDED_REPLY_LABELS[replies]),options:FOLDED_REPLIES.map(id=>({id,label:t(FOLDED_REPLY_LABELS[id])})),onSelect:selectReplies})]})}var TranscriptViewPolicy=class{host;defaultMode;unsubscribe;mode;collapseTiming=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(DEFAULT_COLLAPSE_TIMING);foldedReplies=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(`all`);constructor(host,defaultMode=DEFAULT_TRANSCRIPT_VIEW_MODE){this.host=host;this.defaultMode=defaultMode;this.mode=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(defaultMode);this.unsubscribe=host.subscribe(()=>{this.adopt()});this.adopt()}dispose(){this.unsubscribe()}setMode(mode){if(this.mode.getSnapshot()===mode)return;this.mode.set(mode);this.host.set(TRANSCRIPT_VIEW_FIELD,mode)}setCollapseTiming(timing){if(this.collapseTiming.getSnapshot()===timing)return;this.collapseTiming.set(timing);this.host.set(COLLAPSE_TIMING_FIELD,timing)}setFoldedReplies(replies){if(this.foldedReplies.getSnapshot()===replies)return;this.foldedReplies.set(replies);this.host.set(FOLDED_REPLIES_FIELD,replies)}adopt(){const section=this.host.getSnapshot().value;if(section===void 0)return;const saved=section.transcriptView;const mode=saved===`normal`||saved===`expanded`?`detailed`:saved??this.defaultMode;if(this.mode.getSnapshot()!==mode)this.mode.set(mode);const timing=section.collapseTiming??`completion`;if(this.collapseTiming.getSnapshot()!==timing)this.collapseTiming.set(timing);const replies=section.foldedReplies??`all`;if(this.foldedReplies.getSnapshot()!==replies)this.foldedReplies.set(replies)}};function LinkOpeningRow({useLinkOpening,useBrowserAvailable,setLinkOpening,t}){const destination=useLinkOpening(value=>value);const browserAvailable=useBrowserAvailable(value=>value);const selectOpening=(0,react.useCallback)(value=>{setLinkOpening(value)},[setLinkOpening]);if(!browserAvailable)return null;return(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.links.title`),description:t(`settings.links.description`),value:destination,selectedLabel:t(destination===`sidebar`?`settings.links.sidebar`:`settings.links.newTab`),options:[{id:`sidebar`,label:t(`settings.links.sidebar`)},{id:`new-tab`,label:t(`settings.links.newTab`)}],onSelect:selectOpening})}const OPTIONS=[{id:`compact`,label:`settings.performance.compact`},{id:`detailed`,label:`settings.performance.detailed`}];function PerformanceUsageRow({usePerformanceUsage,setPerformanceUsage,t}){const mode=usePerformanceUsage(value=>value);const selectMode=(0,react.useCallback)(value=>{setPerformanceUsage(value)},[setPerformanceUsage]);const selectedLabel=mode===`detailed`?`settings.performance.detailed`:`settings.performance.compact`;return(0,react_jsx_runtime.jsx)(PreferenceRow,{title:t(`settings.performance.title`),description:t(`settings.performance.description`),value:mode,selectedLabel:t(selectedLabel),options:OPTIONS.map(option=>({id:option.id,label:t(option.label)})),onSelect:selectMode})}var PerformanceUsagePolicy=class{host;unsubscribe;mode=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(DEFAULT_PERFORMANCE_USAGE);constructor(host){this.host=host;const adopt=()=>{const accepted=host.getSnapshot().value?.performanceUsage;if(accepted!==void 0)this.mode.set(accepted)};this.unsubscribe=host.subscribe(adopt);adopt()}dispose(){this.unsubscribe()}setMode(mode){if(mode===this.mode.getSnapshot())return;this.mode.set(mode);this.host.set(`performanceUsage`,mode)}};const EMPTY_SOURCE={getSnapshot:()=>void 0,subscribe:()=>()=>{}};function useTurnDataValue(data,key){const source=data?.source(key)??EMPTY_SOURCE;return(0,react.useSyncExternalStore)(source.subscribe,source.getSnapshot)}const CHAT_FLOW_INJECT={hooks:{groupAction:(_standard,{motion})=>function useGroupAction(hidden,reveal){return useFlowHidden(hidden,reveal,motion)},groupHeaderAction:(_standard,{motion})=>function useGroupHeaderAction(ref,hidden){useMotionHidden(ref,hidden,motion)}}};const CHAT_NODE_INJECT={hooks:{turnData:(_standard,{turnData})=>function useTurnData(key){return useTurnDataValue(turnData,key)},disclosure:(_standard,{disclosureReset})=>bindDisclosure(disclosureReset),groupAction:(_standard,{useGroupAction})=>useGroupAction,presentation:(_standard,{usePresentation})=>usePresentation}};const inject=[`slots`,`sessions`,`uiWorkspace`,`uiSession`,`uiConversation`,`locale`,`configForms`,`connection`,`remote`,`remote.session`,`sidebarRight`,`fileDrag`];function apply(ctx){const quotaNotice=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(null);let quotaNoticeSeq=0;const quotaNoticeHolds=new Set;const chatSources=new WeakMap;const quotaSubscriptions=new Set;ctx.effect(()=>async()=>{await Promise.all([...quotaSubscriptions].map(dispose=>dispose()))},`ui-chat: live quota notices`);const chatSource=binding=>{let source=chatSources.get(binding);if(source===void 0){const dispose=binding.ctx.effect(()=>{const retainInfo=ctx.sessions.retainInfo(binding.sessionId);const retained=()=>ctx.sessions.binding(binding.sessionId)===binding&&(retainInfo.getSnapshot().retainedFacets?.conversation??0)>0;let stopEvents;const follow=()=>{if(!retained()){stopEvents?.();stopEvents=void 0;return}stopEvents??=binding.eventSource.subscribe(()=>{if(!retained())return;const{change}=binding.eventSource.getSnapshot();if(change.kind!==`append`)return;for(const{event}of change.entries){if(event.type!==`turn/end`||event.data.reason.kind!==`error`)continue;const{code}=event.data.reason.error;if(quotaNoticeHolds.size>0||code!==`QUOTA`&&code!==`ACCOUNT_QUOTA`)continue;quotaNotice.set({code,seq:++quotaNoticeSeq})}})};const stopRetained=retainInfo.subscribe(follow);follow();return()=>{stopRetained();stopEvents?.();chatSources.delete(binding);quotaSubscriptions.delete(dispose)}},`ui-chat: Provider binding quota notices`);quotaSubscriptions.add(dispose);const target=ctx.uiConversation.binding(binding).target(`chat`);source={getSnapshot:()=>target.getSnapshot()??EMPTY_CHAT_SNAPSHOT,subscribe:listener=>target.subscribe(listener)};chatSources.set(binding,source)}return source};registerConversationNodes(ctx);ctx.uiSession.provide({hooks:[`chat`],resolve:binding=>({hooks:{chat:chatSource(binding)}})});ctx.effect(()=>ctx.locale.register(NS,{zh,en,ja,es,fr,de,ru,pt}),`ui-chat: dictionaries`);const t=ctx.locale.bind(NS);const chatStore=createChatStore();const chatScrollPositions=new Map;const chatSettings=ctx.configForms.get(CHAT_SETTINGS_NAMESPACE);const linkOpening=(0,_deepseek_ai_dsh_client_store.createSnapshotStore)(chatSettings.getSnapshot().value?.linkOpening??`sidebar`);ctx.effect(()=>chatSettings.subscribe(()=>{const accepted=chatSettings.getSnapshot().value?.linkOpening;if(accepted!==void 0)linkOpening.set(accepted)}));ctx.inject([`sidebarRightTabs`],scope=>{const tabs=scope.sidebarRightTabs;const browserAvailable={getSnapshot:()=>tabs.get(`browser`)!==void 0,subscribe:listener=>tabs.subscribe(listener)};scope.slots.inject(`settings.general.group.interaction.item`,()=>scope.slots.register({name:`settings.general.group.interaction.item`,id:`link-opening`,order:10,locale:NS,inject:()=>({hooks:{linkOpening,browserAvailable},setLinkOpening:destination=>{linkOpening.set(destination);chatSettings.set(`linkOpening`,destination).catch(_error=>{})}})},LinkOpeningRow))});const transcriptView=new TranscriptViewPolicy(chatSettings,`dshDesktop`in globalThis?`standard`:DEFAULT_TRANSCRIPT_VIEW_MODE);const presentation=derivePresentationPolicy(transcriptView.mode,transcriptView.collapseTiming,transcriptView.foldedReplies);const performancePolicy=new PerformanceUsagePolicy(chatSettings);ctx.effect(()=>()=>{transcriptView.dispose();performancePolicy.dispose()});const performanceUsage=performancePolicy.mode;registerChatNodeRenderers(ctx,performanceUsage);ctx.slots.registerFactory({name:`conversation.chat.user.content`,scope:`session`,locale:NS,children:{"conversation.chat.user.images":{kind:`single`,scope:`session`}}},UserContent);ctx.slots.inject(`settings.general.group.display.item`,()=>ctx.slots.register({name:`settings.general.group.display.item`,id:`performance-usage`,order:30,locale:NS,inject:()=>({hooks:{performanceUsage},setPerformanceUsage:mode=>{performancePolicy.setMode(mode)}})},PerformanceUsageRow));ctx.slots.inject(`settings.general.group.display.item`,()=>ctx.slots.register({name:`settings.general.group.display.item`,id:`transcript-view`,order:12,locale:NS,inject:()=>({hooks:{transcriptView:transcriptView.mode,collapseTiming:transcriptView.collapseTiming,foldedReplies:transcriptView.foldedReplies},setTranscriptView:mode=>{transcriptView.setMode(mode)},setCollapseTiming:timing=>{transcriptView.setCollapseTiming(timing)},setFoldedReplies:replies=>{transcriptView.setFoldedReplies(replies)}})},TranscriptViewRow));const connectionState=ctx.get(`connection`).state;const nodeSources=binding=>{const chat=chatSource(binding);const conversation=ctx.uiConversation.binding(binding);return{keyedHooks:{chatNode:key=>chat.getSnapshot().nodes.source(key),chatNodeBottom:key=>chat.getSnapshot().nodes.bottomSource(key),chatNodeProcess:key=>chat.getSnapshot().nodes.processSource(key),chatGroup:key=>conversation.snapshot.getSnapshot().views.grouped(`chat`)?.groupSource(key)}}};ctx.slots.inject(`conversation.chat.flow`,()=>ctx.slots.register({name:`conversation.chat.flow`,locale:NS,store:chatStore,children:{"conversation.chat.node":{kind:`keyed`,scope:`session`,inject:CHAT_NODE_INJECT}},inject:sessionId=>{const binding=ctx.sessions.binding(sessionId);if(binding===void 0)throw new Error(`ui-chat: unknown session "${sessionId}"`);return{...nodeSources(binding),hooks:{presentation,connectionState}}}},ChatFlow));ctx.slots.inject(`conversation.view`,()=>{return ctx.slots.register({name:`conversation.view`,id:`chat`,order:0,label:()=>t(`view.chat`),locale:NS,children:{"conversation.chat.flow":{kind:`single`,scope:`session`,inject:CHAT_FLOW_INJECT},"conversation.chat.text-interaction":{kind:`keyed`,scope:`session`},"conversation.chat.markdown.fence":{kind:`hoc`,scope:`session`},"conversation.chat.aside":{kind:`single`,scope:`session`}},store:chatStore,inject:sessionId=>{const binding=ctx.sessions.binding(sessionId);if(binding===void 0)throw new Error(`ui-chat: unknown session "${sessionId}"`);const session=binding.session;const chat=chatSource(binding);return{...nodeSources(binding),fileDrag:ctx.fileDrag.actions,hooks:{presentation,interactionIds:ctx.uiConversation.interactions},dispatchInteraction:gesture=>ctx.uiConversation.interactions.dispatch(sessionId,gesture),openFile:async(path,options)=>{const url=fileAddressFor(sessionId,sessionDirectory(ctx.sessions,sessionId),path);if(options?.line===void 0)ctx.sidebarRight.openResource(url);else ctx.sidebarRight.openResource(url,{params:{line:options.line}});await Promise.resolve()},resolveFilePath:sessionFilePath(ctx,sessionId),openExternalLink:url=>{if(linkOpening.getSnapshot()===`sidebar`&&ctx.get(`sidebarRightTabs`)?.get(`browser`)!==void 0)ctx.sidebarRight.openTab(`browser`,{params:{url}});else window.open(url,`_blank`,`noopener,noreferrer`)},loadOlder:()=>{session.loadOlder({deferConsumption:true})},consumeOlder:()=>session.consumeOlder(),loadThrough:seq=>session.loadThrough(seq),loadImage:Object.assign(attachment=>ctx.uiConversation.imageUrl(sessionId,attachment),{peek:attachment=>ctx.uiConversation.peekImageUrl(sessionId,attachment)}),chatScroll:{save:position=>{if(position===null)chatScrollPositions.delete(sessionId);else chatScrollPositions.set(sessionId,position)},read:()=>chatScrollPositions.get(sessionId)??null},forkAt:seq=>{const messageId=[...chat.getSnapshot().timeline.turns.values()].find(turn=>turn.end?.seq===seq)?.data.get(`turn-tail`)?.closing?.finalNode.messageId;ctx.uiWorkspace.forkSession(sessionId,childId=>{ctx.get(`productAnalytics`)?.track(`branch_session_click`,{session_id:childId,parent_session_id:sessionId,...messageId===void 0?{}:{parent_message_id:messageId},click_position:`footer`})},{atSeq:seq}).then(childId=>{ctx.uiWorkspace.openSession(childId)}).catch(()=>{})}}}},ChatView)});registerFenceLayers(ctx);ctx.slots.inject(`shell.overlay`,()=>ctx.slots.register({name:`shell.overlay`,id:`chat.quota-notice`,locale:NS,children:{"shell.quota-notice":{kind:`chain`,scope:`root`}},inject:()=>({hooks:{notice:quotaNotice},dismissNotice:()=>{quotaNoticeHolds.clear();quotaNotice.set(null)},keepNoticeOpen:()=>{if(quotaNotice.getSnapshot()===null)return()=>{};const token=Symbol(`ui-chat quota notice hold`);quotaNoticeHolds.add(token);return()=>{quotaNoticeHolds.delete(token)}}})},QuotaNoticeHost));const statPillInject=()=>({hooks:{performanceUsage}});ctx.slots.inject(`conversation.composer.dock`,function*(){yield ctx.slots.register({name:`conversation.composer.dock`,id:`activity`,order:0,locale:NS,inject:statPillInject},ActivityPill);yield ctx.slots.register({name:`conversation.composer.dock`,id:`usage`,order:1,locale:NS,inject:statPillInject},UsagePill)});ctx.slots.inject(`conversation.approval.detail`,()=>ctx.slots.register({name:`conversation.approval.detail`},ApprovalCommand))}exports.EMPTY_CHAT_SNAPSHOT=EMPTY_CHAT_SNAPSHOT;exports.apply=apply;exports.inject=inject;exports.isRunningTool=isRunningTool;exports.isSettledTool=isSettledTool;return module.exports},meta:()=>({stylesheets:{"src/client/chat/TurnNavigator.module.css":{text:context=>`.eGxaPq_slot{--dsh-chat-end-inset:initial;z-index:7;height:0;padding-inline:calc(var(--dsh-composer-side-clearance) + 16px);pointer-events:none;position:absolute;top:0;left:0;right:0;container-type:inline-size}.eGxaPq_slot:is([data-conversation-scroll] *){position:sticky}.eGxaPq_frame{--turn-rail-band:calc(var(--dsh-conversation-viewport-height,100dvh) - var(--dsh-composer-height,152px));--turn-preview-height:100px;top:calc(var(--turn-rail-band) / 2);width:28px;max-height:min(max(0px, calc(var(--turn-rail-band) - 64px)), 420px);contain:layout;cursor:pointer;pointer-events:auto;position:absolute;left:12px;transform:translateY(-50%)}.eGxaPq_scroller{--dsh-composer-height:initial;--dsh-conversation-viewport-height:initial;--turn-rail-band:initial;max-height:inherit;overscroll-behavior:contain;scrollbar-width:none;position:relative;overflow-y:auto}.eGxaPq_scroller::-webkit-scrollbar{display:none}.eGxaPq_fadeTop{mask-image:linear-gradient(#0000 0,#000 24px 100%)}.eGxaPq_fadeBottom{mask-image:linear-gradient(#000 0 calc(100% - 24px),#0000 100%)}.eGxaPq_fadeTop.eGxaPq_fadeBottom{mask-image:linear-gradient(#0000 0,#000 24px calc(100% - 24px),#0000 100%)}.eGxaPq_marks{position:relative}.eGxaPq_mark{cursor:pointer;background:0 0;border:0;border-radius:8px;height:10px;padding:0;position:absolute;top:0;left:0;right:0}.eGxaPq_mark:before{background:var(--dsw-alias-border-l4);content:"";transform-origin:0;border-radius:2px;width:20px;height:2px;transition:transform .14s,background-color .14s;position:absolute;top:50%;left:0;transform:translateY(-50%)scaleX(.6)}.eGxaPq_markUnloaded:before{opacity:.6;transform:translateY(-50%)scaleX(.4)}.eGxaPq_markPreview:before{background:var(--dsw-alias-label-tertiary);transform:translateY(-50%)scaleX(.9)}.eGxaPq_markBusy:before{animation:1s ease-in-out infinite eGxaPq_dsh-turn-mark-busy}.eGxaPq_markActive:before{background:var(--dsw-alias-label-primary);transform:translateY(-50%)scaleX(1)}.eGxaPq_mark:focus-visible:before{background:var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));transform:translateY(-50%)scaleX(1)}.eGxaPq_mark:focus-visible{outline:none}.eGxaPq_mark:focus-visible:after{border-radius:inherit;outline:1px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:-1px;content:"";width:20px;position:absolute;inset:0 auto 0 0}.eGxaPq_preview{top:clamp(0px, calc(var(--turn-preview-center) - var(--turn-preview-height) / 2), calc(100% - var(--turn-preview-height)));box-sizing:border-box;width:min(300px,100cqw - 120px);max-height:var(--turn-preview-height);border-radius:var(--dsw-radius-lg);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1);box-shadow:var(--dsw-elevation-panel);pointer-events:none;border:0;padding:10px 12px;transition:top .14s cubic-bezier(.2,.8,.2,1);animation:.12s ease-out eGxaPq_dsh-turn-preview-enter;position:absolute;left:calc(100% + 10px);overflow:hidden}.eGxaPq_previewPrompt,.eGxaPq_previewResponse{-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.eGxaPq_previewPrompt{font:var(--dsw-font-xs-strong-13);-webkit-line-clamp:1}.eGxaPq_previewResponse{color:var(--dsw-alias-label-caption);font:var(--dsw-font-xxs-12);-webkit-line-clamp:3;margin-top:4px}@keyframes eGxaPq_dsh-turn-preview-enter{0%{opacity:0;transform:translate(-4px)}to{opacity:1;transform:translate(0)}}@keyframes eGxaPq_dsh-turn-mark-busy{0%,to{opacity:1}50%{opacity:.35}}@container (width<=900px){.eGxaPq_frame{display:none}}@media (prefers-reduced-motion:reduce){.eGxaPq_frame,.eGxaPq_scroller,.eGxaPq_mark:before,.eGxaPq_markBusy:before,.eGxaPq_preview{scroll-behavior:auto;transition:none;animation:none}}`},"src/client/chat/ChatView.module.css":{text:context=>`.EvIC1a_frame{flex-direction:column;flex:auto;min-height:0;display:flex;position:relative;container-type:inline-size}.EvIC1a_root{--dsh-composer-height:initial;--dsh-conversation-viewport-height:initial;--dsh-chat-end-inset:initial;flex-direction:column;flex:auto;min-height:0;display:flex;position:relative;overflow:visible clip}.EvIC1a_scroll{min-height:0;padding:16px calc(var(--dsh-composer-side-clearance) + 16px);overscroll-behavior-y:none;flex:auto;overflow:clip auto;container-type:inline-size}.EvIC1a_root[data-chat-following-tail] .EvIC1a_scroll{overflow-anchor:none}.EvIC1a_frame:is([data-conversation-scroll] *),.EvIC1a_root:is([data-conversation-scroll] *){flex:none;height:auto;min-height:auto}.EvIC1a_scroll:is([data-conversation-scroll] *){flex:none;min-height:auto;overflow:clip visible}.EvIC1a_column{max-width:var(--dsh-chat-content-width);flex-direction:column;width:100%;margin:0 auto;display:flex;position:relative}@property --dsh-chat-flow-gap{syntax:"<length>";inherits:false;initial-value:4px}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)))~:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))),.EvIC1a_column>.EvIC1a_older+[data-slot="conversation.chat.flow"]>:not([hidden]):not(.EvIC1a_textInteraction):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))){margin-top:var(--dsh-chat-flow-gap,4px)}.EvIC1a_flowItem[data-chat-group-part=response],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-group-part=response]:not([hidden]):not(:empty)+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])),.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-group-key],.EvIC1a_flowItem:is([data-chat-flow-kind=compaction],[data-chat-flow-kind=manual-compaction],[data-chat-flow-kind=command],[data-chat-flow-kind=context],[data-chat-flow-kind=model-retry],[data-chat-flow-kind=turn-error],[data-chat-flow-kind=turn-max-tokens])):not([hidden])+.EvIC1a_flowItem[data-chat-flow-kind=user]{--dsh-chat-flow-gap:12px}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering],[data-chat-flow-kind=question-reply])+.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering],[data-chat-flow-kind=question-reply])+[hidden]+.EvIC1a_flowItem[data-chat-flow-kind=question-reply],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=question-reply]+.EvIC1a_flowItem[data-chat-group-part=response],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=question-reply]+[hidden]+.EvIC1a_flowItem[data-chat-group-part=response]{--dsh-chat-flow-gap:4px}.EvIC1a_flowItem{min-width:0}.EvIC1a_turnSpacer{height:0}.EvIC1a_column[data-chat-motion]>:not([data-chat-motion]),.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:margin-top .16s cubic-bezier(.4,0,.2,1)}.EvIC1a_column[data-input-fold]>:not([data-chat-motion]),.EvIC1a_column[data-input-fold]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:none}.EvIC1a_column[data-chat-motion]>[data-chat-flow-kind=turn-process],.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>[data-chat-flow-kind=turn-process]{transition:none}@media (prefers-reduced-motion:reduce){.EvIC1a_column[data-chat-motion]>:not([data-chat-motion]),.EvIC1a_column[data-chat-motion]>[data-slot="conversation.chat.flow"]>:not([data-chat-motion]){transition:none}}.EvIC1a_flowItem[data-chat-flow-kind=turn-process],:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=turn-process]:not(:empty,:has(>[data-slot="conversation.chat.node"]:empty))+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])),:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>[data-chat-flow-kind=turn-process]+:not([hidden]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty))):not(.EvIC1a_running):not([data-submission-echo],[data-pending-steering]):not(:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch])){--dsh-chat-flow-gap:16px}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>.EvIC1a_flowItem:has(>[data-slot="conversation.chat.node"]>[data-chat-steering-batch=start]){--dsh-chat-flow-gap:calc(44px + var(--dsh-content-font-delta,0px))}.EvIC1a_running+[data-pending-steering]{--dsh-chat-flow-gap:0px}.EvIC1a_flowItem[data-chat-flow-kind=turn-tail]+.EvIC1a_running{display:none}@media (prefers-reduced-motion:no-preference){:where(.EvIC1a_column>[data-slot="conversation.chat.flow"]>.EvIC1a_flowItem[data-chat-flow-kind=steering])+.EvIC1a_running{animation:.14s cubic-bezier(.2,.8,.2,1) EvIC1a_running-enters-slot}.EvIC1a_column[data-input-fold] .EvIC1a_running{animation-duration:0s}}@keyframes EvIC1a_running-enters-slot{0%{opacity:0;translate:0 calc(-44px - var(--dsh-content-font-delta,0px))}40%{opacity:1}}.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)){height:0}.EvIC1a_callRow{border-radius:var(--dsw-radius-sm)}.EvIC1a_hint{color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.EvIC1a_running{--dsh-chat-flow-gap:12px;--dsw-alias-label-shimmer:var(--dsw-alias-label-deep-diving-shimmer);color:var(--dsw-alias-label-deep-diving);font-size:calc(var(--dsh-content-font-size,14px) - 2px);line-height:calc(22px + var(--dsh-content-font-delta,0px));-webkit-user-select:none;user-select:none;flex-direction:column;align-items:flex-start;display:flex;position:relative}.EvIC1a_running[data-holding]{visibility:hidden;opacity:0}:is(.EvIC1a_column,[data-slot="conversation.chat.flow"])>:nth-last-child(2 of :not([hidden]):not([data-pending-steering]):not(.EvIC1a_flowItem:is(:empty,:has(>[data-slot="conversation.chat.node"]:empty)))):is(.EvIC1a_flowItem:not([data-chat-flow-kind=user]):not([data-chat-flow-kind=steering]):not([data-chat-flow-kind=turn-trigger]),[data-chat-group-key])~.EvIC1a_running>.EvIC1a_runningDivider{opacity:1}.EvIC1a_runningDivider{background:color-mix(in srgb, var(--dsw-alias-border-l1) 75%, var(--dsw-alias-border-l2));opacity:0;pointer-events:none;height:.5px;position:absolute;top:-4px;left:0;right:0}@media (prefers-reduced-motion:no-preference){.EvIC1a_runningDivider{transition:opacity .16s}}.EvIC1a_runningContent{min-width:0;height:calc(28px + var(--dsh-content-font-delta,0px));align-items:center;gap:6px;margin-top:4px;display:inline-flex}.EvIC1a_runningText{font-variant-numeric:tabular-nums;min-width:0}.EvIC1a_runningIcon{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px));contain:strict;flex:none;display:inline-flex;position:relative;overflow:hidden}.EvIC1a_runningWhaleAnimated{display:none;position:absolute;inset:0}.EvIC1a_runningWhaleStill{display:initial}@supports (mask-mode:alpha) and (mask-image:url('')){@media (prefers-reduced-motion:no-preference) and (forced-colors:none){.EvIC1a_runningWhaleAnimated{will-change:transform;background:currentColor;display:block;mask:url(`+context.asset(`plugins/@deepseek-ai/dsh-client-ui-chat/assets/running-whale%402x-06738fa29b2f.png`)+`) 50%/100% 100% no-repeat alpha}.EvIC1a_runningWhaleStill{display:none}}}.EvIC1a_openError{color:var(--dsw-alias-state-error-primary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.EvIC1a_older{overflow-anchor:none;justify-content:center;display:flex}.EvIC1a_older button{white-space:nowrap;border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-interactive-bg-hover-solid);cursor:pointer;border:none;padding:4px 12px;font-size:12px;line-height:18px;display:grid}.EvIC1a_older button>span{grid-area:1/1}.EvIC1a_historyHidden{visibility:hidden}.EvIC1a_older button:disabled{cursor:default;opacity:.6}.EvIC1a_asideSlot{z-index:9;height:0;pointer-events:none;--dsh-chat-aside-gutter:calc(var(--dsh-chat-end-inset,0px) + max(0px, (100% - var(--dsh-chat-end-inset,0px) - var(--dsh-chat-content-width,100%)) / 2));margin-inline-end:calc(-1 * var(--dsh-chat-end-inset,0px));position:absolute;top:0;left:0;right:0;container-type:inline-size}.EvIC1a_asideSlot:has([data-session-panel-moving]){transition:margin-inline-end .16s cubic-bezier(.4,0,.2,1)}.EvIC1a_asideSlot:is([data-conversation-scroll] *){position:sticky}.EvIC1a_toBottomSlot{z-index:8;height:0;padding-right:max(calc(var(--dsh-composer-side-clearance) + 16px), calc((100% - var(--dsh-chat-content-width)) / 2));pointer-events:none;justify-content:flex-end;display:flex;position:absolute;bottom:16px;left:0;right:0}.EvIC1a_toBottomSlot:is([data-conversation-scroll] *){bottom:calc(var(--dsh-composer-height,152px) + 16px);position:sticky}.EvIC1a_toBottom{--dsw-elevation-stroke-color:var(--dsw-alias-border-l3);corner-shape:round;width:34px;height:34px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-button-floating-fill);box-shadow:var(--dsw-elevation-panel);cursor:pointer;pointer-events:auto;border:0;border-radius:100px;justify-content:center;align-items:center;margin-top:-34px;padding:0;display:flex}@media (hover:hover){.EvIC1a_toBottom:hover{background:var(--dsw-alias-button-floating-hover)}}.EvIC1a_modalAction{min-width:72px}.EvIC1a_column>.EvIC1a_textInteraction{z-index:6;visibility:hidden;width:max-content;margin:0;position:absolute}`},"src/client/chat/ChatGroupSeat.module.css":{text:context=>`.O_Ebla_root{min-width:0}.O_Ebla_title{max-width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:6px;padding:0;transition:color .1s;display:flex}@media (hover:hover){.O_Ebla_title:hover{color:var(--dsw-alias-label-secondary)}}.O_Ebla_leading{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));color:inherit;flex:none;justify-content:center;align-items:center;display:inline-flex;position:relative}.O_Ebla_leading svg{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px))}.O_Ebla_leading svg[width="16"]{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px))}.O_Ebla_activityIcon,.O_Ebla_chevron{justify-content:center;align-items:center;transition:opacity .1s;display:inline-flex;position:absolute;inset:0}.O_Ebla_activityIcon{opacity:1}.O_Ebla_chevron,.O_Ebla_title:focus-visible .O_Ebla_activityIcon{opacity:0}@media (hover:hover){.O_Ebla_title:hover .O_Ebla_activityIcon{opacity:0}}.O_Ebla_title:focus-visible .O_Ebla_chevron{opacity:1}@media (hover:hover){.O_Ebla_title:hover .O_Ebla_chevron{opacity:1}}.O_Ebla_title[aria-expanded=true] .O_Ebla_activityIcon{opacity:0}.O_Ebla_title[aria-expanded=true] .O_Ebla_chevron{opacity:1}.O_Ebla_title[aria-expanded=true]{padding-bottom:8px}.O_Ebla_body{overscroll-behavior-y:auto;scrollbar-gutter:stable;max-height:min(400px,50vh);overflow-y:auto}.O_Ebla_label{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden}.O_Ebla_fadeTop{mask-image:linear-gradient(#0000 0,#000 24px 100%)}.O_Ebla_fadeBottom{mask-image:linear-gradient(#000 0 calc(100% - 24px),#0000 100%)}.O_Ebla_fadeTop.O_Ebla_fadeBottom{mask-image:linear-gradient(#0000 0,#000 24px calc(100% - 24px),#0000 100%)}@media (prefers-reduced-motion:reduce){.O_Ebla_title,.O_Ebla_activityIcon,.O_Ebla_chevron{transition:none}}.O_Ebla_content{flex-direction:column;display:flex}.O_Ebla_content>*{flex-shrink:0}.O_Ebla_content>:not([hidden]):not(:empty)~[data-chat-flow-key]:not([hidden]):not(:empty){margin-top:4px}.O_Ebla_expandedBody{scrollbar-gutter:auto;max-height:none;overflow:visible}[data-chat-motion] .O_Ebla_content>[data-chat-flow-key]:not([data-chat-motion]){transition:margin-top .16s cubic-bezier(.4,0,.2,1)}@media (prefers-reduced-motion:reduce){[data-chat-motion] .O_Ebla_content>[data-chat-flow-key]:not([data-chat-motion]){transition:none}}`},"src/client/chat/accessibility.module.css":{text:context=>`.TTCZqG_visuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;width:1px;height:1px;position:absolute;overflow:hidden}`},"src/client/chat/CommandStatusRow.module.css":{text:context=>`.kWGFkG_root{flex-direction:column;display:flex}.kWGFkG_leading{flex-shrink:0}.kWGFkG_title{font-weight:400}.kWGFkG_separator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.kWGFkG_summary{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.kWGFkG_summary[data-error],.kWGFkG_body[data-error]{color:var(--dsw-alias-state-error-primary)}.kWGFkG_body{border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-markdown-code-block);max-height:260px;color:var(--dsw-alias-label-primary);font:var(--dsw-font-markdown-code-block-small);white-space:pre-wrap;margin:4px 0 4px 4px;padding:12px 16px;overflow:auto}`},"src/client/chat/MessageItem.module.css":{text:context=>`.Sixlwa_userRow{flex-direction:column;align-items:flex-end;gap:6px;display:flex}.Sixlwa_userStack{min-width:0;max-width:min(calc(var(--dsh-chat-content-width,748px) * .702), 82%);flex-direction:column;align-items:flex-end;gap:8px;display:flex}.Sixlwa_referenceSummary{color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px))}.Sixlwa_contextRow{padding:2px 0}.Sixlwa_inheritedHistoryRow{align-items:center;gap:12px;padding:2px 0 20px;display:flex}.Sixlwa_inheritedHistoryLine{border-top:.5px solid var(--dsw-alias-border-l2);flex:1 1 0;min-width:16px}.Sixlwa_inheritedHistoryCaption{min-width:0;color:var(--dsw-alias-label-tertiary);flex:0 auto;align-items:center;gap:6px;display:flex}.Sixlwa_inheritedHistoryIcon{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px));flex:none}.Sixlwa_inheritedHistoryLabel{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:0 auto;overflow:hidden}.Sixlwa_compactionRow{padding:2px 0}.Sixlwa_compactionButton{width:100%;height:calc(24px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);min-width:0;color:var(--dsw-alias-label-tertiary);font:inherit;text-align:left;background:0 0;border:none;align-items:center;padding:0;transition:color .1s;display:flex}.Sixlwa_compactionButton:not(:disabled){cursor:pointer}@media (hover:hover){.Sixlwa_compactionButton:hover{color:var(--dsw-alias-label-secondary)}.Sixlwa_compactionButton:not(:disabled):hover{background:var(--dsw-alias-interactive-bg-hover)}}.Sixlwa_compactionLeading{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));color:inherit;flex:none;place-items:center;margin-right:6px;display:inline-grid}.Sixlwa_compactionLeading svg{width:calc(14px + var(--dsh-content-font-delta,0px));height:calc(14px + var(--dsh-content-font-delta,0px))}.Sixlwa_compactionContextIcon,.Sixlwa_compactionOpenIcon{grid-area:1/1;justify-content:center;align-items:center;display:inline-flex}.Sixlwa_compactionOpenIcon,.Sixlwa_compactionButton:not(:disabled):focus-visible .Sixlwa_compactionContextIcon{opacity:0}@media (hover:hover){.Sixlwa_compactionButton:not(:disabled):hover .Sixlwa_compactionContextIcon{opacity:0}}.Sixlwa_compactionButton:not(:disabled):focus-visible .Sixlwa_compactionOpenIcon{opacity:1}@media (hover:hover){.Sixlwa_compactionButton:not(:disabled):hover .Sixlwa_compactionOpenIcon{opacity:1}}.Sixlwa_compactionTitle{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:inherit;flex:none}.Sixlwa_compactionSep{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.Sixlwa_compactionSummary{min-width:0;color:inherit;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}@media (prefers-reduced-motion:reduce){.Sixlwa_compactionButton{transition:none}}[data-disclosure-row].Sixlwa_retryRow{height:auto;min-height:calc(24px + var(--dsh-content-font-delta,0px));align-items:flex-start}[data-disclosure-row] .Sixlwa_retryLeading{margin-top:4px}[data-disclosure-row] .Sixlwa_retryTitle{font-size:var(--dsh-content-font-size-secondary,13px);white-space:normal;overflow-wrap:anywhere;flex:0 auto;min-width:0}.Sixlwa_retrySeparator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;align-self:center;width:2px;height:2px;margin:0 8px}.Sixlwa_retryProgress{overflow-wrap:anywhere;min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px))}.Sixlwa_retryBesideGroups [data-disclosure-row] .Sixlwa_retryTitle,.Sixlwa_retryBesideGroups .Sixlwa_retryProgress{font-size:var(--dsh-content-font-size,14px)}.Sixlwa_retryDetails{padding-left:calc(22px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(18px + var(--dsh-content-font-delta-secondary,0px));gap:2px;margin-top:2px;display:grid}.Sixlwa_retryDetailLabel{color:var(--dsw-alias-label-secondary)}.Sixlwa_turnErrorRow{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));grid-template-columns:10px minmax(0,1fr) auto;align-items:start;gap:8px;padding:2px 0;display:grid}.Sixlwa_turnErrorDot{margin-top:5px}.Sixlwa_turnErrorCopy{overflow-wrap:anywhere;min-width:0}.Sixlwa_turnErrorTitle{color:var(--dsw-alias-state-error-primary);margin-right:6px;font-weight:600}.Sixlwa_turnErrorMessage{color:var(--dsw-alias-label-secondary)}.Sixlwa_turnErrorCode{color:var(--dsw-alias-label-tertiary);font:var(--dsw-font-markdown-code-block-small)}.Sixlwa_maxTokensTitle{color:var(--dsw-alias-state-warn-primary);margin-right:6px;font-weight:600}.Sixlwa_attachmentRow{flex-wrap:wrap;justify-content:flex-end;gap:8px;max-width:100%;display:flex}.Sixlwa_fileCard{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-input-major,transparent);box-sizing:border-box;flex:0 0 240px;align-items:center;gap:10px;width:240px;min-height:64px;padding:8px 12px;display:inline-flex}.Sixlwa_fileIcon{flex:none;width:28px;height:28px}.Sixlwa_fileContent{flex-direction:column;flex:1;min-width:0;display:flex}.Sixlwa_fileName{white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-primary);font-size:14px;font-weight:500;line-height:22px;overflow:hidden}.Sixlwa_fileMeta{white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:15px;overflow:hidden}`},"src/client/chat/ContextBody.module.css":{text:context=>`.ZkiH0q_text{color:var(--dsw-alias-label-secondary);font:inherit;white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_fields{border-top:.5px solid var(--dsw-alias-border-l2);flex-direction:column;gap:2px;margin:8px 0 0;padding-top:8px;display:flex}.ZkiH0q_field{gap:8px;min-width:0;display:flex}.ZkiH0q_fieldKey{min-width:96px;color:var(--dsw-alias-label-caption);flex:none}.ZkiH0q_fieldValue{min-width:0;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;flex:auto;margin:0}.ZkiH0q_files{flex-wrap:wrap;gap:4px 12px;margin:0 0 8px;padding:0;list-style:none;display:flex}.ZkiH0q_file{align-items:baseline;gap:6px;min-width:0;display:flex}.ZkiH0q_filePath{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}.ZkiH0q_fileAction{color:var(--dsw-alias-label-caption)}.ZkiH0q_catalogNotice{color:var(--dsw-alias-label-caption);margin:0 0 6px}.ZkiH0q_entries{flex-direction:column;gap:4px;margin:0;padding:0;list-style:none;display:flex}.ZkiH0q_entry{gap:8px;min-width:0;display:flex}.ZkiH0q_entryName{color:var(--dsw-alias-label-secondary);flex:none}.ZkiH0q_entryDescription{min-width:0;color:var(--dsw-alias-label-tertiary);text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.ZkiH0q_sections{flex-direction:column;gap:8px;margin:0;display:flex}.ZkiH0q_section{flex-direction:column;gap:2px;min-width:0;display:flex}.ZkiH0q_sectionName{color:var(--dsw-alias-label-caption)}.ZkiH0q_sectionText{color:var(--dsw-alias-label-secondary);white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_sectionNotice{color:var(--dsw-alias-label-caption);white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.ZkiH0q_relaySender{color:var(--dsw-alias-label-caption);overflow-wrap:anywhere;margin:0 0 6px}.ZkiH0q_recalls{flex-direction:column;gap:2px;margin:0 0 8px;padding:0;list-style:none;display:flex}.ZkiH0q_recall{gap:8px;min-width:0;display:flex}.ZkiH0q_recallLabel{color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}.ZkiH0q_recallCounts{color:var(--dsw-alias-label-caption);flex:none}`},"src/client/chat/ContextInjectionRow.module.css":{text:context=>`.XrJvXW_root{min-width:0}.XrJvXW_root[data-open]{padding-bottom:4px}.XrJvXW_chevron{color:var(--dsw-alias-label-secondary)}.XrJvXW_sep{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.XrJvXW_source{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:none;overflow:hidden}.XrJvXW_summary{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;flex:auto;overflow:hidden}.XrJvXW_body{box-sizing:border-box;width:calc(100% - 22px - var(--dsh-content-font-delta,0px));max-height:141px;margin:4px 0 0 calc(22px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-md);background:var(--dsw-alias-markdown-code-block);color:var(--dsw-alias-label-tertiary);font:400 11px/16px var(--ds-font-family-code);border:none;padding:10px 16px 12px 12px;overflow:auto}.XrJvXW_toolChanges{white-space:nowrap}`},"src/client/chat/MessageIconActions.module.css":{text:context=>`.xzv4MW_actions{height:calc(28px + var(--dsh-content-font-delta,0px));align-items:center;gap:8px;display:flex}.xzv4MW_timeStart{font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-tertiary);white-space:nowrap;padding-right:12px}.xzv4MW_timeEnd{font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:inherit;white-space:nowrap}.xzv4MW_endInfo{min-width:0;color:var(--dsw-alias-label-tertiary);align-items:center;gap:8px;margin-left:8px;display:inline-flex}@media (hover:hover){[data-actions-reveal=hover] .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])) .xzv4MW_actions{opacity:0;transition:opacity 80ms}[data-actions-reveal=hover]:hover .xzv4MW_actions,[data-actions-reveal=hover]:focus-within .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])):hover .xzv4MW_actions,:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering]):has(~:is([data-chat-flow-kind=user],[data-chat-flow-kind=steering])):focus-within .xzv4MW_actions,[data-actions-reveal=hover] .xzv4MW_actions:has([data-action-ongoing]){opacity:1}}.xzv4MW_action{width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-tertiary);cursor:pointer;background:0 0;border:none;justify-content:center;align-items:center;padding:6px;display:inline-flex}.xzv4MW_action svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}.xzv4MW_actions[data-clock=end] .xzv4MW_action svg{width:calc(16px + var(--dsh-content-font-delta,0px));height:calc(16px + var(--dsh-content-font-delta,0px));flex:none}@media (hover:hover){.xzv4MW_action:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}}.xzv4MW_action[data-unavailable]{cursor:default;opacity:.4}@media (hover:hover){.xzv4MW_action[data-unavailable]:hover{color:var(--dsw-alias-label-tertiary);background:0 0}}.xzv4MW_visuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;width:1px;height:1px;position:absolute;overflow:hidden}`},"src/client/chat/ReasoningRow.module.css":{text:context=>`.lcKema_root{flex-direction:column;display:flex}.lcKema_root:not([data-expanded]){contain:size layout;height:calc(24px + var(--dsh-content-font-delta,0px))}.lcKema_row{overflow:hidden}.lcKema_root[data-expanded] [data-open] [data-disclosure-header]{z-index:1;background:var(--dsw-alias-bg-base);position:sticky;top:0}.lcKema_leading{flex-shrink:0}.lcKema_title{font-weight:400}.lcKema_separator{background:var(--dsw-alias-label-caption);border-radius:1px;flex:none;width:2px;height:2px;margin:0 8px}.lcKema_summary{min-width:0;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));white-space:nowrap;flex:auto;overflow:hidden}.lcKema_summaryText{text-overflow:ellipsis;display:block;overflow:hidden}.lcKema_summary[data-streaming]{mask-image:linear-gradient(90deg,#000 calc(100% - 48px),#0000)}.lcKema_summary[data-streaming] .lcKema_summaryText{text-overflow:clip;overflow:visible}.lcKema_root:not([data-preview]) .lcKema_separator,.lcKema_root:not([data-preview]) .lcKema_summary{display:none}.lcKema_thinkBody{padding:4px 0 4px calc(22px + var(--dsh-content-font-delta,0px));min-width:0}`},"src/client/chat/AssistantMarkdown.module.css":{text:context=>`.hWmORq_root{font-size:var(--dsh-content-font-size,14px);line-height:calc(24px + var(--dsh-content-font-delta,0px));color:var(--dsw-alias-label-primary);flex-direction:column;display:flex}.hWmORq_body{--dsh-assistant-block-gap:16px;gap:var(--dsh-assistant-block-gap);flex-direction:column;display:flex}[data-chat-group-part=reasoning] .hWmORq_body{--dsh-assistant-block-gap:4px}.hWmORq_body .md-table-wide{--dsh-table-spare:max(0px, calc((100cqw - var(--dsh-chat-content-width)) / 2));width:calc(100% + var(--dsh-table-spare));max-width:none}.hWmORq_body .md-table-wide>table{z-index:1;position:relative}.hWmORq_body>[data-turn-process-inline][hidden],.hWmORq_body>.hWmORq_reasoning:empty{margin-bottom:calc(-1 * var(--dsh-assistant-block-gap))}.hWmORq_stopped{border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary);align-self:flex-start;padding:0 6px;font-size:11px;line-height:18px}.hWmORq_actions{margin-top:16px;margin-left:-6px}`},"src/client/chat/TurnProcessNodeView.module.css":{text:context=>`.l_V-RG_root{box-sizing:border-box;width:100%;min-width:0;height:calc(33px + var(--dsh-content-font-delta,0px));border:none;border-bottom:.5px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary);font:inherit;font-size:var(--dsh-content-font-size,14px);cursor:pointer;text-align:left;background:0 0;align-items:center;padding:0 0 8px;transition:color .1s;display:flex}.l_V-RG_root:disabled{cursor:default}@media (hover:hover){.l_V-RG_root:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}}.l_V-RG_chevron{width:14px;height:14px;color:inherit;flex:none;margin-left:4px;transition:transform .1s}.l_V-RG_root[data-open] .l_V-RG_chevron{transform:rotate(180deg)}.l_V-RG_label{min-width:0;font-size:inherit;line-height:calc(24px + var(--dsh-content-font-delta,0px));text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.l_V-RG_durationNumber{font-family:var(--ds-font-family-code);font-variant-numeric:tabular-nums}@media (prefers-reduced-motion:reduce){.l_V-RG_root,.l_V-RG_chevron{transition:none}}`},"src/client/chat/TurnUsagePanel.module.css":{text:context=>`.Q51KRG_root{min-width:0;display:inline-flex}.Q51KRG_root+.Q51KRG_root{margin-left:-6px}.Q51KRG_trigger{min-width:0;height:calc(28px + var(--dsh-content-font-delta,0px));border-radius:var(--dsw-radius-sm);color:var(--dsw-alias-label-tertiary);font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);font-variant-numeric:tabular-nums;line-height:calc(24px + var(--dsh-content-font-delta,0px));white-space:nowrap;cursor:pointer;background:0 0;border:none;align-items:center;gap:4px;padding:6px 8px;display:inline-flex}.Q51KRG_label{text-overflow:ellipsis;min-width:0;overflow:hidden}.Q51KRG_trigger svg{width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px));flex:none}.Q51KRG_trigger[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary)}@media (hover:hover){.Q51KRG_trigger:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-tertiary)}}@media (width<=480px){.Q51KRG_trigger{width:calc(28px + var(--dsh-content-font-delta,0px));justify-content:center;padding:6px}.Q51KRG_trigger .Q51KRG_label{display:none}.Q51KRG_root+.Q51KRG_root{margin-left:0}}`},"src/client/chat/stat-dialog.module.css":{text:context=>`.bRhRbq_panel{z-index:1100;box-sizing:border-box;border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-menu);width:max-content;min-width:min(300px,100vw - 24px);max-width:min(440px,100vw - 24px);backdrop-filter:var(--dsw-menu-backdrop-filter);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);cursor:default;max-height:calc(100dvh - 12px - max(12px, var(--dsh-frame-overlay-top,12px)));--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2);position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:calc(anchor(top) + 8px);left:anchor(left);position-try-fallbacks:--dsh-stat-window, --dsh-stat-opposite, --dsh-stat-wide-opposite, --dsh-stat-tall, --dsh-stat-viewport;border:0;place-self:end start;height:fit-content;min-height:0;margin:0;padding:16px;font-size:12px;line-height:18px;position:fixed;right:12px;overflow:hidden auto}.bRhRbq_title{color:var(--dsw-alias-label-primary);justify-content:space-between;gap:16px;margin-bottom:8px;font-weight:500;display:flex}.bRhRbq_titleRule{border-top:.5px solid var(--dsw-alias-border-l2);margin-bottom:10px}.bRhRbq_titleValue{font-variant-numeric:tabular-nums}.bRhRbq_titleLabel{align-items:center;gap:6px;min-width:0;display:inline-flex}.bRhRbq_titleLabel svg{flex:none;width:14px;height:14px}.bRhRbq_details{color:var(--dsw-alias-label-tertiary);grid-template-columns:minmax(76px,auto) minmax(0,1fr);gap:6px 16px;margin:0;display:grid}.bRhRbq_details dt,.bRhRbq_details dd{min-width:0;margin:0}.bRhRbq_details dd{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;text-align:right}.bRhRbq_details .bRhRbq_route{overflow-wrap:anywhere}.bRhRbq_reasoning{color:var(--dsw-alias-label-tertiary);white-space:nowrap}@position-try --dsh-stat-window{position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:calc(anchor(top) + 8px);left:12px;right:12px;margin:0;align-self:safe end;justify-self:safe end}@position-try --dsh-stat-opposite{top:calc(anchor(bottom) + 8px);bottom:12px;align-self:start}@position-try --dsh-stat-wide-opposite{top:calc(anchor(bottom) + 8px);bottom:12px;left:12px;right:12px;align-self:start;justify-self:safe end}@position-try --dsh-stat-tall{position-area:none;top:max(12px, var(--dsh-frame-overlay-top,12px));bottom:12px;left:anchor(left);right:12px;margin:0;align-self:safe start;justify-self:start}@position-try --dsh-stat-viewport{position-area:none;inset:max(12px, var(--dsh-frame-overlay-top,12px)) 12px 12px;margin:0;align-self:safe start;justify-self:safe end}`},"src/client/chat/TurnTailNodeView.module.css":{text:context=>`.TS9iAW_root{flex-direction:column;gap:16px;display:flex}.TS9iAW_actions{margin-top:4px;margin-left:-6px}`},"src/client/chat/TurnTriggerNodeView.module.css":{text:context=>`.oz9t_a_root{border:.5px solid var(--dsw-alias-border-l1);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-turn-trigger-bg,var(--dsw-alias-markdown-code-block));min-width:0;transition:background-color .1s}@media (hover:hover){.oz9t_a_root:hover{background:var(--dsw-alias-turn-trigger-bg-hover,var(--dsw-alias-interactive-bg-hover))}}.oz9t_a_header{width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;text-align:left;cursor:pointer;background:0 0;border:0;align-items:center;gap:10px;padding:12px 16px;transition:color .1s;display:flex}@media (hover:hover){.oz9t_a_header:hover{color:var(--dsw-alias-label-secondary)}}.oz9t_a_icon{color:inherit;flex:none;display:inline-flex}.oz9t_a_continuation{min-width:0;color:var(--dsw-alias-label-tertiary);font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));overflow-wrap:anywhere;align-items:center;gap:6px;padding:2px 0;display:flex}.oz9t_a_title{overflow-wrap:anywhere;min-width:0;font-size:var(--dsh-content-font-size,14px);flex:1}.oz9t_a_time{color:inherit;font:var(--dsw-font-xxs-12);flex:none;margin-left:auto}.oz9t_a_chevron,.oz9t_a_openChevron{color:inherit;flex:none}.oz9t_a_openChevron{transform:rotate(180deg)}.oz9t_a_body{padding:0 16px 12px 40px}.oz9t_a_explanation{color:var(--dsw-alias-label-secondary);font:var(--dsw-font-xxs-12);margin:8px 0}.oz9t_a_content{white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;font:var(--dsw-font-xxs-12);overflow:auto}@media (prefers-reduced-motion:reduce){.oz9t_a_root,.oz9t_a_header{transition:none}}`},"src/client/chat/StatsPills.module.css":{text:context=>`.bOPqQW_anchor{min-width:0;font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));display:inline-flex}.bOPqQW_pill{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;line-height:inherit;white-space:nowrap;background:0 0;border:none;align-items:center;gap:6px;padding:1px 8px;display:inline-flex}.bOPqQW_pill svg{flex:none;width:14px;height:14px}button.bOPqQW_pill{cursor:pointer}button.bOPqQW_pill[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}@media (hover:hover){button.bOPqQW_pill:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}}.bOPqQW_label{text-overflow:ellipsis;min-width:0;overflow:hidden}.bOPqQW_sep{color:var(--dsw-alias-separator-primary);margin:0 6px}`},"src/client/settings/PreferenceRow.module.css":{text:context=>`._2XZxNq_row{border-bottom:.5px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}._2XZxNq_rowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}@media (width<=767px){html:not([data-windows-titlebar]):not([data-platform=darwin]) ._2XZxNq_rowText{padding-right:16px}}._2XZxNq_title{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}._2XZxNq_desc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}._2XZxNq_selector{border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform);height:36px;font:inherit;color:var(--dsw-alias-label-primary);cursor:pointer;border:none;align-items:center;gap:12px;padding:0 14px;font-size:14px;line-height:22px;display:inline-flex}@media (hover:hover){._2XZxNq_selector:hover{background:var(--dsw-alias-interactive-bg-hover)}}._2XZxNq_chevron{flex:none}`}}})});
21
21
  //# sourceMappingURL=client.js.map