@deepseek-ai/dsh-client-ui-chat 0.2.2-rc.1 → 0.2.2-rc.2

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 (355) hide show
  1. package/README.i18n.yaml +16 -16
  2. package/README.md +17 -5
  3. package/README.zh.md +17 -5
  4. package/lib/client.js +18 -15587
  5. package/lib/client.js.map +1 -0
  6. package/lib/types/chat-settings.d.ts.map +1 -0
  7. package/lib/types/chat-settings.js.map +1 -0
  8. package/lib/types/client/apply.d.ts.map +1 -0
  9. package/lib/types/client/apply.js.map +1 -0
  10. package/lib/types/client/chat/ApprovalCommand.d.ts +4 -3
  11. package/lib/types/client/chat/ApprovalCommand.d.ts.map +1 -0
  12. package/lib/types/client/chat/ApprovalCommand.js.map +1 -0
  13. package/lib/types/client/chat/AssistantMarkdown.d.ts.map +1 -0
  14. package/lib/types/client/chat/AssistantMarkdown.js.map +1 -0
  15. package/lib/types/client/chat/AssistantNodeView.d.ts.map +1 -0
  16. package/lib/types/client/chat/AssistantNodeView.js.map +1 -0
  17. package/lib/types/client/chat/ChatFlow.d.ts.map +1 -0
  18. package/lib/types/client/chat/ChatFlow.js.map +1 -0
  19. package/lib/types/client/chat/ChatGroupSeat.d.ts.map +1 -0
  20. package/lib/types/client/chat/ChatGroupSeat.js.map +1 -0
  21. package/lib/types/client/chat/ChatNodeSeat.d.ts.map +1 -0
  22. package/lib/types/client/chat/ChatNodeSeat.js.map +1 -0
  23. package/lib/types/client/chat/ChatView.d.ts +1 -1
  24. package/lib/types/client/chat/ChatView.d.ts.map +1 -0
  25. package/lib/types/client/chat/ChatView.js.map +1 -0
  26. package/lib/types/client/chat/CommandNodeView.d.ts.map +1 -0
  27. package/lib/types/client/chat/CommandNodeView.js.map +1 -0
  28. package/lib/types/client/chat/CompactionCommandCard.d.ts.map +1 -0
  29. package/lib/types/client/chat/CompactionCommandCard.js.map +1 -0
  30. package/lib/types/client/chat/CompactionItem.d.ts.map +1 -0
  31. package/lib/types/client/chat/CompactionItem.js.map +1 -0
  32. package/lib/types/client/chat/ContextBody.d.ts.map +1 -0
  33. package/lib/types/client/chat/ContextBody.js.map +1 -0
  34. package/lib/types/client/chat/ContextInjectionRow.d.ts.map +1 -0
  35. package/lib/types/client/chat/ContextInjectionRow.js.map +1 -0
  36. package/lib/types/client/chat/GenericCommandCard.d.ts.map +1 -0
  37. package/lib/types/client/chat/GenericCommandCard.js.map +1 -0
  38. package/lib/types/client/chat/MessageIconActions.d.ts.map +1 -0
  39. package/lib/types/client/chat/MessageIconActions.js.map +1 -0
  40. package/lib/types/client/chat/MessageItem.d.ts.map +1 -0
  41. package/lib/types/client/chat/MessageItem.js.map +1 -0
  42. package/lib/types/client/chat/QuotaNoticeHost.d.ts.map +1 -0
  43. package/lib/types/client/chat/QuotaNoticeHost.js.map +1 -0
  44. package/lib/types/client/chat/ReasoningContent.d.ts.map +1 -0
  45. package/lib/types/client/chat/ReasoningContent.js.map +1 -0
  46. package/lib/types/client/chat/ReasoningRow.d.ts.map +1 -0
  47. package/lib/types/client/chat/ReasoningRow.js.map +1 -0
  48. package/lib/types/client/chat/RunningStatus.d.ts.map +1 -0
  49. package/lib/types/client/chat/RunningStatus.js.map +1 -0
  50. package/lib/types/client/chat/RunningWhaleTail.d.ts.map +1 -0
  51. package/lib/types/client/chat/RunningWhaleTail.js.map +1 -0
  52. package/lib/types/client/chat/StatsPills.d.ts.map +1 -0
  53. package/lib/types/client/chat/StatsPills.js.map +1 -0
  54. package/lib/types/client/chat/SystemPromptRow.d.ts.map +1 -0
  55. package/lib/types/client/chat/SystemPromptRow.js.map +1 -0
  56. package/lib/types/client/chat/TurnNavigator.d.ts.map +1 -0
  57. package/lib/types/client/chat/TurnNavigator.js.map +1 -0
  58. package/lib/types/client/chat/TurnProcessNodeView.d.ts.map +1 -0
  59. package/lib/types/client/chat/TurnProcessNodeView.js.map +1 -0
  60. package/lib/types/client/chat/TurnTailNodeView.d.ts.map +1 -0
  61. package/lib/types/client/chat/TurnTailNodeView.js.map +1 -0
  62. package/lib/types/client/chat/TurnTriggerNodeView.d.ts.map +1 -0
  63. package/lib/types/client/chat/TurnTriggerNodeView.js.map +1 -0
  64. package/lib/types/client/chat/TurnUsagePanel.d.ts.map +1 -0
  65. package/lib/types/client/chat/TurnUsagePanel.js.map +1 -0
  66. package/lib/types/client/chat/UserContent.d.ts.map +1 -0
  67. package/lib/types/client/chat/UserContent.js.map +1 -0
  68. package/lib/types/client/chat/flow-motion.d.ts +2 -0
  69. package/lib/types/client/chat/flow-motion.d.ts.map +1 -0
  70. package/lib/types/client/chat/flow-motion.js.map +1 -0
  71. package/lib/types/client/chat/message-chrome.d.ts.map +1 -0
  72. package/lib/types/client/chat/message-chrome.js.map +1 -0
  73. package/lib/types/client/chat/register-node-renderers.d.ts.map +1 -0
  74. package/lib/types/client/chat/register-node-renderers.js.map +1 -0
  75. package/lib/types/client/chat/render-entry.d.ts.map +1 -0
  76. package/lib/types/client/chat/render-entry.js.map +1 -0
  77. package/lib/types/client/chat/searchable-hidden.d.ts.map +1 -0
  78. package/lib/types/client/chat/searchable-hidden.js.map +1 -0
  79. package/lib/types/client/chat/stat-dialog.d.ts +5 -10
  80. package/lib/types/client/chat/stat-dialog.d.ts.map +1 -0
  81. package/lib/types/client/chat/stat-dialog.js.map +1 -0
  82. package/lib/types/client/chat/step-process.d.ts.map +1 -0
  83. package/lib/types/client/chat/step-process.js.map +1 -0
  84. package/lib/types/client/chat/text-interaction.d.ts.map +1 -0
  85. package/lib/types/client/chat/text-interaction.js.map +1 -0
  86. package/lib/types/client/chat/text-selection.d.ts.map +1 -0
  87. package/lib/types/client/chat/text-selection.js.map +1 -0
  88. package/lib/types/client/chat/token-format.d.ts.map +1 -0
  89. package/lib/types/client/chat/token-format.js.map +1 -0
  90. package/lib/types/client/chat/turn-assistant.d.ts.map +1 -0
  91. package/lib/types/client/chat/turn-assistant.js.map +1 -0
  92. package/lib/types/client/chat/turn-rail-items.d.ts.map +1 -0
  93. package/lib/types/client/chat/turn-rail-items.js.map +1 -0
  94. package/lib/types/client/chat/turn-trigger.d.ts +3 -2
  95. package/lib/types/client/chat/turn-trigger.d.ts.map +1 -0
  96. package/lib/types/client/chat/turn-trigger.js.map +1 -0
  97. package/lib/types/client/chat/use-calendar-day.d.ts.map +1 -0
  98. package/lib/types/client/chat/use-calendar-day.js.map +1 -0
  99. package/lib/types/client/chat/use-chat-navigation.d.ts +21 -5
  100. package/lib/types/client/chat/use-chat-navigation.d.ts.map +1 -0
  101. package/lib/types/client/chat/use-chat-navigation.js.map +1 -0
  102. package/lib/types/client/chat/use-chat-reading.d.ts.map +1 -0
  103. package/lib/types/client/chat/use-chat-reading.js.map +1 -0
  104. package/lib/types/client/chat/use-chat-scroll.d.ts +5 -2
  105. package/lib/types/client/chat/use-chat-scroll.d.ts.map +1 -0
  106. package/lib/types/client/chat/use-chat-scroll.js.map +1 -0
  107. package/lib/types/client/chat/use-chat-viewport.d.ts +53 -0
  108. package/lib/types/client/chat/use-chat-viewport.d.ts.map +1 -0
  109. package/lib/types/client/chat/use-chat-viewport.js.map +1 -0
  110. package/lib/types/client/chat/use-disclosure.d.ts.map +1 -0
  111. package/lib/types/client/chat/use-disclosure.js.map +1 -0
  112. package/lib/types/client/chat/use-process-scroll.d.ts.map +1 -0
  113. package/lib/types/client/chat/use-process-scroll.js.map +1 -0
  114. package/lib/types/client/chat/use-scroll-follow.d.ts.map +1 -0
  115. package/lib/types/client/chat/use-scroll-follow.js.map +1 -0
  116. package/lib/types/client/chat/use-turn-data.d.ts.map +1 -0
  117. package/lib/types/client/chat/use-turn-data.js.map +1 -0
  118. package/lib/types/client/contract/assistant-content.d.ts.map +1 -0
  119. package/lib/types/client/contract/assistant-content.js.map +1 -0
  120. package/lib/types/client/contract/chat-nodes.d.ts.map +1 -0
  121. package/lib/types/client/contract/chat-nodes.js.map +1 -0
  122. package/lib/types/client/contract/chat-visibility.d.ts +2 -2
  123. package/lib/types/client/contract/chat-visibility.d.ts.map +1 -0
  124. package/lib/types/client/contract/chat-visibility.js.map +1 -0
  125. package/lib/types/client/contract/group-tree.d.ts.map +1 -0
  126. package/lib/types/client/contract/group-tree.js.map +1 -0
  127. package/lib/types/client/contract/process-groups.d.ts +6 -3
  128. package/lib/types/client/contract/process-groups.d.ts.map +1 -0
  129. package/lib/types/client/contract/process-groups.js.map +1 -0
  130. package/lib/types/client/contract/slots.d.ts +11 -2
  131. package/lib/types/client/contract/slots.d.ts.map +1 -0
  132. package/lib/types/client/contract/slots.js.map +1 -0
  133. package/lib/types/client/contract/snapshot.d.ts.map +1 -0
  134. package/lib/types/client/contract/snapshot.js.map +1 -0
  135. package/lib/types/client/contract/store.d.ts.map +1 -0
  136. package/lib/types/client/contract/store.js.map +1 -0
  137. package/lib/types/client/contract/turn-metrics.d.ts.map +1 -0
  138. package/lib/types/client/contract/turn-metrics.js.map +1 -0
  139. package/lib/types/client/contract/turn-process.d.ts.map +1 -0
  140. package/lib/types/client/contract/turn-process.js.map +1 -0
  141. package/lib/types/client/conversation-nodes/assistant.d.ts.map +1 -0
  142. package/lib/types/client/conversation-nodes/assistant.js.map +1 -0
  143. package/lib/types/client/conversation-nodes/chat-snapshot-builder.d.ts.map +1 -0
  144. package/lib/types/client/conversation-nodes/chat-snapshot-builder.js.map +1 -0
  145. package/lib/types/client/conversation-nodes/command.d.ts.map +1 -0
  146. package/lib/types/client/conversation-nodes/command.js.map +1 -0
  147. package/lib/types/client/conversation-nodes/common.d.ts.map +1 -0
  148. package/lib/types/client/conversation-nodes/common.js.map +1 -0
  149. package/lib/types/client/conversation-nodes/compaction.d.ts.map +1 -0
  150. package/lib/types/client/conversation-nodes/compaction.js.map +1 -0
  151. package/lib/types/client/conversation-nodes/event-projection.d.ts.map +1 -0
  152. package/lib/types/client/conversation-nodes/event-projection.js.map +1 -0
  153. package/lib/types/client/conversation-nodes/fallback.d.ts.map +1 -0
  154. package/lib/types/client/conversation-nodes/fallback.js.map +1 -0
  155. package/lib/types/client/conversation-nodes/group-tree-segments.d.ts.map +1 -0
  156. package/lib/types/client/conversation-nodes/group-tree-segments.js.map +1 -0
  157. package/lib/types/client/conversation-nodes/inbox.d.ts.map +1 -0
  158. package/lib/types/client/conversation-nodes/inbox.js.map +1 -0
  159. package/lib/types/client/conversation-nodes/message.d.ts +1 -1
  160. package/lib/types/client/conversation-nodes/message.d.ts.map +1 -0
  161. package/lib/types/client/conversation-nodes/message.js.map +1 -0
  162. package/lib/types/client/conversation-nodes/process-activity.d.ts +1 -0
  163. package/lib/types/client/conversation-nodes/process-activity.d.ts.map +1 -0
  164. package/lib/types/client/conversation-nodes/process-activity.js.map +1 -0
  165. package/lib/types/client/conversation-nodes/process-groups.d.ts.map +1 -0
  166. package/lib/types/client/conversation-nodes/process-groups.js.map +1 -0
  167. package/lib/types/client/conversation-nodes/register.d.ts.map +1 -0
  168. package/lib/types/client/conversation-nodes/register.js.map +1 -0
  169. package/lib/types/client/conversation-nodes/request-prompt.d.ts.map +1 -0
  170. package/lib/types/client/conversation-nodes/request-prompt.js.map +1 -0
  171. package/lib/types/client/conversation-nodes/retry.d.ts.map +1 -0
  172. package/lib/types/client/conversation-nodes/retry.js.map +1 -0
  173. package/lib/types/client/conversation-nodes/tool.d.ts.map +1 -0
  174. package/lib/types/client/conversation-nodes/tool.js.map +1 -0
  175. package/lib/types/client/conversation-nodes/turn-error.d.ts.map +1 -0
  176. package/lib/types/client/conversation-nodes/turn-error.js.map +1 -0
  177. package/lib/types/client/conversation-nodes/turn-max-tokens.d.ts.map +1 -0
  178. package/lib/types/client/conversation-nodes/turn-max-tokens.js.map +1 -0
  179. package/lib/types/client/conversation-nodes/turn-navigation.d.ts.map +1 -0
  180. package/lib/types/client/conversation-nodes/turn-navigation.js.map +1 -0
  181. package/lib/types/client/conversation-nodes/turn-process-presentation.d.ts.map +1 -0
  182. package/lib/types/client/conversation-nodes/turn-process-presentation.js.map +1 -0
  183. package/lib/types/client/conversation-nodes/turn-process.d.ts.map +1 -0
  184. package/lib/types/client/conversation-nodes/turn-process.js.map +1 -0
  185. package/lib/types/client/conversation-nodes/turn-tail.d.ts.map +1 -0
  186. package/lib/types/client/conversation-nodes/turn-tail.js.map +1 -0
  187. package/lib/types/client/fence/FenceLayers.d.ts +21 -0
  188. package/lib/types/client/fence/FenceLayers.d.ts.map +1 -0
  189. package/lib/types/client/fence/FenceLayers.js.map +1 -0
  190. package/lib/types/client/fence/register.d.ts +10 -0
  191. package/lib/types/client/fence/register.d.ts.map +1 -0
  192. package/lib/types/client/fence/register.js.map +1 -0
  193. package/lib/types/client/file-path.d.ts.map +1 -0
  194. package/lib/types/client/file-path.js.map +1 -0
  195. package/lib/types/client/index.d.ts +1 -1
  196. package/lib/types/client/index.d.ts.map +1 -0
  197. package/lib/types/client/index.js.map +1 -0
  198. package/lib/types/client/locale.d.ts +96 -0
  199. package/lib/types/client/locale.d.ts.map +1 -0
  200. package/lib/types/client/locale.js.map +1 -0
  201. package/lib/types/client/markdown-labels.d.ts.map +1 -0
  202. package/lib/types/client/markdown-labels.js.map +1 -0
  203. package/lib/types/client/model/conversation-context.d.ts.map +1 -0
  204. package/lib/types/client/model/conversation-context.js.map +1 -0
  205. package/lib/types/client/model/steering-history.d.ts.map +1 -0
  206. package/lib/types/client/model/steering-history.js.map +1 -0
  207. package/lib/types/client/model/tool-call-tree.d.ts.map +1 -0
  208. package/lib/types/client/model/tool-call-tree.js.map +1 -0
  209. package/lib/types/client/performance-usage.d.ts.map +1 -0
  210. package/lib/types/client/performance-usage.js.map +1 -0
  211. package/lib/types/client/presentation-policy.d.ts.map +1 -0
  212. package/lib/types/client/presentation-policy.js.map +1 -0
  213. package/lib/types/client/reasoning-text.d.ts.map +1 -0
  214. package/lib/types/client/reasoning-text.js.map +1 -0
  215. package/lib/types/client/settings/LinkOpeningRow.d.ts.map +1 -0
  216. package/lib/types/client/settings/LinkOpeningRow.js.map +1 -0
  217. package/lib/types/client/settings/PerformanceUsageRow.d.ts.map +1 -0
  218. package/lib/types/client/settings/PerformanceUsageRow.js.map +1 -0
  219. package/lib/types/client/settings/PreferenceRow.d.ts.map +1 -0
  220. package/lib/types/client/settings/PreferenceRow.js.map +1 -0
  221. package/lib/types/client/settings/TranscriptViewRow.d.ts.map +1 -0
  222. package/lib/types/client/settings/TranscriptViewRow.js.map +1 -0
  223. package/lib/types/client/stores.d.ts.map +1 -0
  224. package/lib/types/client/stores.js.map +1 -0
  225. package/lib/types/client/transcript-view.d.ts.map +1 -0
  226. package/lib/types/client/transcript-view.js.map +1 -0
  227. package/lib/types/index.d.ts.map +1 -0
  228. package/lib/types/index.js.map +1 -0
  229. package/package.json +44 -41
  230. package/src/chat-settings.ts +98 -0
  231. package/src/client/apply.ts +355 -0
  232. package/src/client/assets/running-whale@2x.png +0 -0
  233. package/src/client/chat/ApprovalCommand.tsx +42 -0
  234. package/src/client/chat/AssistantMarkdown.module.css +88 -0
  235. package/src/client/chat/AssistantMarkdown.tsx +170 -0
  236. package/src/client/chat/AssistantNodeView.tsx +67 -0
  237. package/src/client/chat/ChatFlow.tsx +100 -0
  238. package/src/client/chat/ChatGroupSeat.module.css +166 -0
  239. package/src/client/chat/ChatGroupSeat.tsx +208 -0
  240. package/src/client/chat/ChatNodeSeat.tsx +179 -0
  241. package/src/client/chat/ChatView.module.css +426 -0
  242. package/src/client/chat/ChatView.tsx +351 -0
  243. package/src/client/chat/CommandNodeView.tsx +40 -0
  244. package/src/client/chat/CompactionCommandCard.tsx +26 -0
  245. package/src/client/chat/CompactionItem.tsx +76 -0
  246. package/src/client/chat/ContextBody.module.css +161 -0
  247. package/src/client/chat/ContextBody.tsx +592 -0
  248. package/src/client/chat/ContextInjectionRow.module.css +68 -0
  249. package/src/client/chat/ContextInjectionRow.tsx +94 -0
  250. package/src/client/chat/GenericCommandCard.module.css +49 -0
  251. package/src/client/chat/GenericCommandCard.tsx +75 -0
  252. package/src/client/chat/MessageIconActions.module.css +116 -0
  253. package/src/client/chat/MessageIconActions.tsx +90 -0
  254. package/src/client/chat/MessageItem.module.css +360 -0
  255. package/src/client/chat/MessageItem.tsx +410 -0
  256. package/src/client/chat/QuotaNoticeHost.tsx +27 -0
  257. package/src/client/chat/ReasoningContent.tsx +26 -0
  258. package/src/client/chat/ReasoningRow.module.css +77 -0
  259. package/src/client/chat/ReasoningRow.tsx +112 -0
  260. package/src/client/chat/RunningStatus.tsx +48 -0
  261. package/src/client/chat/RunningWhaleTail.tsx +19 -0
  262. package/src/client/chat/StatsPills.module.css +63 -0
  263. package/src/client/chat/StatsPills.tsx +348 -0
  264. package/src/client/chat/SystemPromptRow.tsx +50 -0
  265. package/src/client/chat/TurnNavigator.module.css +223 -0
  266. package/src/client/chat/TurnNavigator.tsx +295 -0
  267. package/src/client/chat/TurnProcessNodeView.module.css +62 -0
  268. package/src/client/chat/TurnProcessNodeView.tsx +62 -0
  269. package/src/client/chat/TurnTailNodeView.module.css +12 -0
  270. package/src/client/chat/TurnTailNodeView.tsx +81 -0
  271. package/src/client/chat/TurnTriggerNodeView.module.css +50 -0
  272. package/src/client/chat/TurnTriggerNodeView.tsx +57 -0
  273. package/src/client/chat/TurnUsagePanel.module.css +79 -0
  274. package/src/client/chat/TurnUsagePanel.tsx +110 -0
  275. package/src/client/chat/UserContent.tsx +60 -0
  276. package/src/client/chat/accessibility.module.css +8 -0
  277. package/src/client/chat/flow-motion.ts +556 -0
  278. package/src/client/chat/message-chrome.ts +100 -0
  279. package/src/client/chat/register-node-renderers.ts +100 -0
  280. package/src/client/chat/render-entry.ts +16 -0
  281. package/src/client/chat/searchable-hidden.ts +45 -0
  282. package/src/client/chat/stat-dialog.module.css +149 -0
  283. package/src/client/chat/stat-dialog.ts +55 -0
  284. package/src/client/chat/step-process.ts +28 -0
  285. package/src/client/chat/text-interaction.ts +298 -0
  286. package/src/client/chat/text-selection.ts +180 -0
  287. package/src/client/chat/token-format.ts +98 -0
  288. package/src/client/chat/turn-assistant.ts +10 -0
  289. package/src/client/chat/turn-rail-items.ts +89 -0
  290. package/src/client/chat/turn-trigger.ts +88 -0
  291. package/src/client/chat/use-calendar-day.ts +25 -0
  292. package/src/client/chat/use-chat-navigation.ts +309 -0
  293. package/src/client/chat/use-chat-reading.ts +283 -0
  294. package/src/client/chat/use-chat-scroll.ts +209 -0
  295. package/src/client/chat/use-chat-viewport.ts +1130 -0
  296. package/src/client/chat/use-disclosure.ts +35 -0
  297. package/src/client/chat/use-process-scroll.ts +88 -0
  298. package/src/client/chat/use-scroll-follow.ts +182 -0
  299. package/src/client/chat/use-turn-data.ts +23 -0
  300. package/src/client/contract/assistant-content.ts +15 -0
  301. package/src/client/contract/chat-nodes.ts +135 -0
  302. package/src/client/contract/chat-visibility.ts +20 -0
  303. package/src/client/contract/group-tree.ts +37 -0
  304. package/src/client/contract/process-groups.ts +30 -0
  305. package/src/client/contract/slots.ts +508 -0
  306. package/src/client/contract/snapshot.ts +171 -0
  307. package/src/client/contract/store.ts +17 -0
  308. package/src/client/contract/turn-metrics.ts +43 -0
  309. package/src/client/contract/turn-process.ts +58 -0
  310. package/src/client/conversation-nodes/README.i18n.yaml +64 -0
  311. package/src/client/conversation-nodes/README.md +338 -0
  312. package/src/client/conversation-nodes/README.zh.md +338 -0
  313. package/src/client/conversation-nodes/assistant.ts +384 -0
  314. package/src/client/conversation-nodes/chat-snapshot-builder.ts +1244 -0
  315. package/src/client/conversation-nodes/command.ts +227 -0
  316. package/src/client/conversation-nodes/common.ts +83 -0
  317. package/src/client/conversation-nodes/compaction.ts +65 -0
  318. package/src/client/conversation-nodes/event-projection.ts +179 -0
  319. package/src/client/conversation-nodes/fallback.ts +41 -0
  320. package/src/client/conversation-nodes/group-tree-segments.ts +91 -0
  321. package/src/client/conversation-nodes/inbox.ts +148 -0
  322. package/src/client/conversation-nodes/message.ts +182 -0
  323. package/src/client/conversation-nodes/process-activity.ts +170 -0
  324. package/src/client/conversation-nodes/process-groups.ts +303 -0
  325. package/src/client/conversation-nodes/register.ts +38 -0
  326. package/src/client/conversation-nodes/request-prompt.ts +169 -0
  327. package/src/client/conversation-nodes/retry.ts +97 -0
  328. package/src/client/conversation-nodes/tool.ts +371 -0
  329. package/src/client/conversation-nodes/turn-error.ts +120 -0
  330. package/src/client/conversation-nodes/turn-max-tokens.ts +82 -0
  331. package/src/client/conversation-nodes/turn-navigation.ts +97 -0
  332. package/src/client/conversation-nodes/turn-process-presentation.ts +149 -0
  333. package/src/client/conversation-nodes/turn-process.ts +374 -0
  334. package/src/client/conversation-nodes/turn-tail.ts +164 -0
  335. package/src/client/fence/FenceLayers.tsx +33 -0
  336. package/src/client/fence/register.ts +22 -0
  337. package/src/client/file-path.ts +19 -0
  338. package/src/client/index.ts +69 -0
  339. package/src/client/locale.ts +1695 -0
  340. package/src/client/markdown-labels.ts +16 -0
  341. package/src/client/model/conversation-context.ts +24 -0
  342. package/src/client/model/steering-history.ts +64 -0
  343. package/src/client/model/tool-call-tree.ts +204 -0
  344. package/src/client/performance-usage.ts +34 -0
  345. package/src/client/presentation-policy.ts +109 -0
  346. package/src/client/reasoning-text.ts +25 -0
  347. package/src/client/settings/LinkOpeningRow.tsx +47 -0
  348. package/src/client/settings/PerformanceUsageRow.tsx +46 -0
  349. package/src/client/settings/PreferenceRow.module.css +66 -0
  350. package/src/client/settings/PreferenceRow.tsx +59 -0
  351. package/src/client/settings/TranscriptViewRow.tsx +93 -0
  352. package/src/client/stores.ts +62 -0
  353. package/src/client/transcript-view.ts +81 -0
  354. package/src/css-modules.d.ts +6 -0
  355. package/src/index.ts +45 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["#mode","#invalidValue","#size","#ends","#reads","#order","#entries","#consumed","#invalidAt","#nestedInString","#current","#escape","#keyStart","#keyEscaped","#key","#nestedEnds","valueMap"],"sources":["../../../packages/util/workspace-path/lib/index.js","../../../packages/client/ui-chat/src/client/contract/snapshot.ts","../../../packages/client/ui-chat/src/client/chat/ApprovalCommand.tsx","../../../packages/client/ui-chat/src/client/file-path.ts","../../../packages/client/ui-chat/src/client/contract/group-tree.ts","../../../packages/client/ui-chat/src/client/markdown-labels.ts","../../../packages/client/ui-chat/src/client/chat/TurnNavigator.tsx","../../../packages/util/brand/lib/index.js","../../../packages/core/session/src/types.ts","../../../packages/client/ui-chat/src/client/chat/turn-rail-items.ts","../../../packages/client/ui-chat/src/client/chat/text-selection.ts","../../../packages/client/ui-chat/src/client/chat/text-interaction.ts","../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts","../../../packages/client/ui-chat/src/client/chat/use-scroll-follow.ts","../../../packages/client/ui-chat/src/client/chat/use-chat-reading.ts","../../../packages/client/ui-chat/src/client/chat/searchable-hidden.ts","../../../packages/client/ui-chat/src/client/chat/flow-motion.ts","../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts","../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts","../../../packages/client/ui-chat/src/client/chat/ChatView.tsx","../../../packages/util/values/lib/index.js","../../../packages/client/ui-chat/src/client/contract/assistant-content.ts","../../../packages/client/ui-chat/src/client/contract/turn-process.ts","../../../packages/client/ui-chat/src/client/stores.ts","../../../packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx","../../../packages/client/ui-chat/src/client/chat/render-entry.ts","../../../packages/client/ui-chat/src/client/chat/step-process.ts","../../../packages/client/ui-chat/src/client/chat/use-disclosure.ts","../../../packages/client/ui-chat/src/client/chat/use-process-scroll.ts","../../../packages/client/ui-chat/src/client/chat/ChatGroupSeat.tsx","../../../packages/client/ui-chat/src/client/chat/CompactionItem.tsx","../../../packages/client/ui-chat/src/client/chat/ContextBody.tsx","../../../packages/client/ui-chat/src/client/chat/ContextInjectionRow.tsx","../../../packages/client/ui-chat/src/client/chat/message-chrome.ts","../../../packages/client/ui-chat/src/client/chat/use-calendar-day.ts","../../../packages/client/ui-chat/src/client/chat/MessageIconActions.tsx","../../../packages/client/ui-chat/src/client/chat/MessageItem.tsx","../../../packages/client/ui-chat/src/client/chat/RunningWhaleTail.tsx","../../../packages/client/ui-chat/src/client/chat/RunningStatus.tsx","../../../packages/client/ui-chat/src/client/chat/ChatFlow.tsx","../../../packages/client/ui-chat/src/client/locale.ts","../../../packages/client/ui-chat/src/client/reasoning-text.ts","../../../packages/client/ui-chat/src/client/chat/ReasoningRow.tsx","../../../packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx","../../../packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx","../../../packages/client/ui-chat/src/client/chat/GenericCommandCard.tsx","../../../packages/client/ui-chat/src/client/chat/CompactionCommandCard.tsx","../../../packages/client/ui-chat/src/client/chat/CommandNodeView.tsx","../../../packages/client/ui-chat/src/client/chat/ReasoningContent.tsx","../../../packages/client/ui-chat/src/client/chat/SystemPromptRow.tsx","../../../packages/client/ui-chat/src/client/chat/TurnProcessNodeView.tsx","../../../packages/client/ui-chat/src/client/chat/token-format.ts","../../../packages/client/ui-chat/src/client/chat/stat-dialog.ts","../../../packages/client/ui-chat/src/client/chat/TurnUsagePanel.tsx","../../../packages/client/ui-chat/src/client/chat/turn-assistant.ts","../../../packages/client/ui-chat/src/client/chat/TurnTailNodeView.tsx","../../../packages/client/ui-chat/src/client/chat/turn-trigger.ts","../../../packages/client/ui-chat/src/client/chat/TurnTriggerNodeView.tsx","../../../packages/client/ui-chat/src/client/chat/register-node-renderers.ts","../../../packages/client/ui-chat/src/client/chat/UserContent.tsx","../../../packages/client/ui-chat/src/client/contract/turn-metrics.ts","../../../packages/client/ui-chat/src/client/chat/StatsPills.tsx","../../../packages/client/ui-chat/src/client/conversation-nodes/common.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/event-projection.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/assistant.ts","../../../packages/client/ui-chat/src/client/contract/chat-nodes.ts","../../../packages/client/ui-chat/src/client/contract/chat-visibility.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/group-tree-segments.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-navigation.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-process-presentation.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts","../../../packages/core/session/src/surface.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/command.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/compaction.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/fallback.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/inbox.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/message.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/retry.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/tool.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-error.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-max-tokens.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-process.ts","../../../packages/llm/llm/src/assistant-stream.ts","../../../packages/llm/token-meter/src/turn-usage.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/process-groups.ts","../../../packages/client/ui-chat/src/client/conversation-nodes/register.ts","../../../packages/client/ui-chat/src/client/fence/FenceLayers.tsx","../../../packages/client/ui-chat/src/client/fence/register.ts","../../../packages/client/ui-chat/src/client/chat/QuotaNoticeHost.tsx","../../../../vendor/cosmokit/lib/index.js","../../../../vendor/schemastery/lib/index.mjs","../../../packages/client/ui-chat/src/chat-settings.ts","../../../packages/client/ui-chat/src/client/presentation-policy.ts","../../../packages/client/ui-chat/src/client/settings/PreferenceRow.tsx","../../../packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx","../../../packages/client/ui-chat/src/client/transcript-view.ts","../../../packages/client/ui-chat/src/client/settings/LinkOpeningRow.tsx","../../../packages/client/ui-chat/src/client/settings/PerformanceUsageRow.tsx","../../../packages/client/ui-chat/src/client/performance-usage.ts","../../../packages/client/ui-chat/src/client/chat/use-turn-data.ts","../../../packages/client/ui-chat/src/client/apply.ts"],"sourcesContent":["//#region lib/types/file-address.js\n/**\n* The `dsh-resource://file/…` address grammar: how a file is named across the\n* Sidebar and the resource model, built and parsed without touching a\n* filesystem.\n* @module\n*/\n/** The scheme and type every file address opens with. */\nconst FILE_ADDRESS_PREFIX = \"dsh-resource://file/\";\n/** Component-encode one id or path segment, keeping `:` literal for drive letters. */\nfunction encodeSegment(segment) {\n\treturn encodeURIComponent(segment).replace(/%3A/gi, \":\");\n}\n/** Encode a `/`-separated path segment by segment. */\nfunction encodePath(path) {\n\treturn path.split(\"/\").map(encodeSegment).join(\"/\");\n}\n/** Whether a decoded first path segment is a Windows drive (`C:`). */\nfunction isDriveSegment(segment) {\n\treturn segment !== void 0 && /^[A-Za-z]:$/.test(segment);\n}\n/**\n* Build the address of a file read through one Session.\n* @param sessionId - the Session whose Host workspace resolves the path.\n* @param path - absolute or workspace-relative path; backslashes are normalized to `/`, and leading `./` prefixes are dropped.\n* @returns the `dsh-resource://file/session/<sessionId>/<path>` address.\n*/\nfunction sessionFileAddress(sessionId, path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\").replace(/^(?:\\.\\/)+/, \"\");\n\treturn `${FILE_ADDRESS_PREFIX}session/${encodeSegment(sessionId)}/${encodePath(normalized)}`;\n}\n/**\n* Build the address of a file by its absolute path.\n* @param path - absolute path; backslashes are normalized to `/` and the leading `/` is dropped,\n* except that a UNC path (`\\\\server\\share`) keeps one empty first segment.\n* @returns the `dsh-resource://file/absolute/<path>` address.\n*/\nfunction absoluteFileAddress(path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\tconst unc = normalized.startsWith(\"//\");\n\tconst absolute = normalized.replace(/^\\/+/, \"\");\n\treturn `${FILE_ADDRESS_PREFIX}absolute/${unc ? \"/\" : \"\"}${encodePath(absolute)}`;\n}\n/**\n* Read a file address back into its parts without resolving `.` or `..`.\n* Query and fragment suffixes are ignored; encoded path segments are decoded.\n* @param address - a candidate address.\n* @returns the parts, or `undefined` when the string is not a `dsh-resource://file/` URI in a known scope with a path, or a segment is not validly encoded.\n*/\nfunction parseFileAddress(address) {\n\ttry {\n\t\tif (!address.startsWith(FILE_ADDRESS_PREFIX)) return void 0;\n\t\tconst end = address.search(/[?#]/);\n\t\tconst [scope, ...rest] = address.slice(20, end === -1 ? void 0 : end).split(\"/\");\n\t\tif (scope === \"session\") {\n\t\t\tconst [id, ...segments] = rest;\n\t\t\tif (id === void 0 || id === \"\" || segments.length === 0) return void 0;\n\t\t\treturn {\n\t\t\t\tscope,\n\t\t\t\tsessionId: decodeURIComponent(id),\n\t\t\t\tpath: segments.map(decodeURIComponent).join(\"/\")\n\t\t\t};\n\t\t}\n\t\tif (scope === \"absolute\") {\n\t\t\tconst unc = rest[0] === \"\" && rest.length > 1;\n\t\t\tconst segments = (unc ? rest.slice(1) : rest).map(decodeURIComponent);\n\t\t\tif (segments.length === 0 || segments[0] === \"\") return void 0;\n\t\t\tif (unc) return {\n\t\t\t\tscope,\n\t\t\t\tpath: `//${segments.join(\"/\")}`\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tscope,\n\t\t\t\tpath: isDriveSegment(segments[0]) ? segments.join(\"/\") : `/${segments.join(\"/\")}`\n\t\t\t};\n\t\t}\n\t\treturn;\n\t} catch {\n\t\treturn;\n\t}\n}\n//#endregion\n//#region lib/types/index.js\n/**\n* Browser-safe Workspace path and display helpers.\n* @module @deepseek-ai/dsh-util-workspace-path\n*/\n/** Whether a path uses a Windows drive or UNC prefix. */\nfunction isWindowsStylePath(value) {\n\treturn /^[A-Za-z]:[/\\\\]/.test(value) || value.startsWith(\"\\\\\\\\\");\n}\n/**\n* Whether a path is absolute in either spelling the Host accepts: POSIX (`/a/b`) or Windows drive or UNC.\n* @param path - the path to classify.\n* @returns `true` for an absolute path; `false` for a Workspace-relative one.\n*/\nfunction isAbsoluteWorkspacePath(path) {\n\treturn path.startsWith(\"/\") || isWindowsStylePath(path);\n}\n/**\n* Resolve a Workspace-relative path into the Host-facing spelling used by path operations.\n* @param cwd - Session Workspace root, when known.\n* @param path - Absolute or Workspace-relative path; leading `./` segments are dropped when joining.\n* @returns an absolute path when a Workspace root is available, otherwise the original path.\n*/\nfunction resolveWorkspacePath(cwd, path) {\n\tif (isAbsoluteWorkspacePath(path)) return path;\n\tif (cwd === void 0 || cwd === \"\") return path;\n\tconst separator = isWindowsStylePath(cwd) && cwd.includes(\"\\\\\") ? \"\\\\\" : \"/\";\n\treturn `${cwd.replace(/[/\\\\]+$/, \"\")}${separator}${path.replace(/^(?:\\.?[/\\\\])+/, \"\")}`;\n}\n/**\n* Abbreviate a POSIX home directory for display.\n* @param path - Absolute or already-short display path.\n* @param home - Host account home; absent skips abbreviation.\n* @returns `~` or `~/…` for the POSIX home and its descendants, otherwise `path`.\n*/\nfunction abbreviateHomePath(path, home) {\n\tif (home === void 0 || home === \"\") return path;\n\tif (isWindowsStylePath(path) || isWindowsStylePath(home)) return path;\n\tconst root = home.replace(/\\/+$/, \"\");\n\tif (root === \"\" || root === \"/\") return path;\n\tif (path.replace(/\\/+$/, \"\") === root) return \"~\";\n\tif (path.startsWith(`${root}/`)) return `~${path.slice(root.length)}`;\n\treturn path;\n}\n/**\n* Read the final non-empty segment of a Workspace path for display.\n* Workspace-label surfaces use this helper instead of deriving another basename.\n* @param path - Workspace directory path using POSIX or Windows separators.\n* @returns the final segment, or an empty string for a separator-only path.\n*/\nfunction workspaceTitleOf(path) {\n\tconst trimmed = path.replace(/[/\\\\]+$/, \"\");\n\tconst separator = Math.max(trimmed.lastIndexOf(\"/\"), trimmed.lastIndexOf(\"\\\\\"));\n\treturn trimmed.slice(separator + 1);\n}\n/**\n* Split a path for display: the directories through their last separator, and\n* the final segment after it. Both `/` and `\\` separate, so a Windows path\n* splits where its own segments end; trailing separators are dropped first, so\n* a directory path names its own last segment. A path with no separator, or a\n* separator-only path, is all name.\n* @param path - file or directory path using POSIX or Windows separators.\n* @returns the directory prefix (possibly empty) and the final segment.\n*/\nfunction pathPartsOf(path) {\n\tconst trimmed = path.replace(/[/\\\\]+$/, \"\");\n\tif (trimmed === \"\") return {\n\t\tdirectory: \"\",\n\t\tname: path\n\t};\n\tconst cut = Math.max(trimmed.lastIndexOf(\"/\"), trimmed.lastIndexOf(\"\\\\\")) + 1;\n\treturn {\n\t\tdirectory: trimmed.slice(0, cut),\n\t\tname: trimmed.slice(cut)\n\t};\n}\n/**\n* The address for a path as a caller holds it: a relative path, or an absolute\n* path inside the Session's workspace, becomes a `session`-scoped address; an\n* absolute path outside it, or one whose workspace root is unknown, keeps its\n* absolute path in that Session's address.\n* @param sessionId - the Session the path is read in.\n* @param cwd - that Session's workspace root, when known.\n* @param path - absolute or workspace-relative path, in either separator spelling.\n* @returns the `dsh-resource://file/…` address.\n*/\nfunction fileAddressFor(sessionId, cwd, path) {\n\tconst normalized = path.replace(/\\\\/g, \"/\");\n\tif (!isAbsoluteWorkspacePath(normalized)) return sessionFileAddress(sessionId, normalized);\n\tconst root = cwd === void 0 ? \"\" : cwd.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n\tif (root !== \"\" && normalized === root) return sessionFileAddress(sessionId, \"\");\n\tif (root !== \"\" && normalized.startsWith(`${root}/`)) return sessionFileAddress(sessionId, normalized.slice(root.length + 1));\n\treturn sessionFileAddress(sessionId, normalized);\n}\n/**\n* Strip the workspace root from a workspace-rooted absolute path (display only).\n* @param text - the path to shorten.\n* @param cwd - session workspace root; absent or empty leaves the path unchanged.\n* @returns the path relative to the workspace root, or unchanged when it is not rooted there.\n*/\nfunction relativizeToCwd(text, cwd) {\n\tif (cwd === void 0 || cwd === \"\") return text;\n\tconst root = cwd.replace(/[/\\\\]+$/, \"\");\n\tif (text.startsWith(`${root}/`) || text.startsWith(`${root}\\\\`)) return text.slice(root.length + 1);\n\treturn text;\n}\n/**\n* Address a decoded absolute file path through the authenticated file route.\n* @param base - HTTP(S) application base, including its deployment prefix, or `dsh-app://app/`.\n* @param path - Native file path; URL escapes in authored Markdown must already be decoded.\n* @returns File URL, or undefined for unsupported transports and non-absolute paths.\n*/\nfunction fileMediaUrl(base, path) {\n\tif (!/^https?:/u.test(base) && !base.startsWith(\"dsh-app://app/\") || !isAbsoluteWorkspacePath(path) || /^[/\\\\]{2}/u.test(path) || /[\\u0000-\\u001f\\u007f]/u.test(path)) return void 0;\n\treturn new URL(`api/file?path=${encodeURIComponent(path)}`, base).href;\n}\n//#endregion\nexport { abbreviateHomePath, absoluteFileAddress, fileAddressFor, fileMediaUrl, isAbsoluteWorkspacePath, parseFileAddress, pathPartsOf, relativizeToCwd, resolveWorkspacePath, sessionFileAddress, workspaceTitleOf };\n","import type {\n ConversationNode, ConversationTimelineSnapshot, PartialAssistant, RunningToolCall,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNodeDataMap, ChatNodeKind } from './chat-nodes.ts'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { TurnProcessSpec } from './turn-process.ts'\n\nexport type {\n AssistantBlock, AssistantMessageNode, AssistantProviderMetadataView, AssistantRequestConfig,\n AssistantTiming, CommandNode, CompactionSummaryNode, ContextMessageNode, ConversationNode,\n ModelRetryNode, PartialAssistant, PreparingToolCall, RunningToolCall, StartedToolCall, SteeringMessageNode, TodoItem,\n ToolArgs, ToolCallBlock, ToolResultNode, TurnErrorNode, TurnMaxTokensNode, UnknownSurfaceNode,\n UserMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** Per-key observable used by one mounted Chat Node Seat. */\nexport interface ChatNodeSource {\n /** @returns the current Node for this source's stable key. */\n readonly getSnapshot: () => ChatConversationViewNode | undefined\n /** @param listener - callback for changes to this key. @returns the unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void\n}\n\n/** Per-key observable for the Turn-process presentation surrounding one Chat Node. */\nexport interface ChatNodeProcessSource {\n /** @returns the current presentation, or absence outside a projected Turn process. */\n readonly getSnapshot: () => ChatTurnProcessPresentation | undefined\n /** @param listener - callback for presentation changes. @returns the unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void\n}\n\n/** Stable live per-key reader for Chat nodes. */\nexport interface ChatNodeStore {\n /** @param key - stable Conversation Context key. @returns current Node, when visible or hidden. */\n get(key: string): ChatConversationViewNode | undefined\n /** @param key - stable Conversation Context key. @returns its identity-stable observable source. */\n source(key: string): ChatNodeSource\n /**\n * @param key - Chat Node identity.\n * @returns whether the visible Node belongs to the latest loaded exchange (see `ChatConversationViewNode.groupTree`).\n */\n bottomSource(key: string): ObservableSnapshot<boolean>\n /**\n * Observe one Turn's data for a single Node kind, including hidden Nodes, in anchor order.\n * Other Turns and kinds do not notify this source.\n * @param turn - resolved owning Turn.\n * @param kind - business Node kind.\n * @returns an identity-stable source whose array changes only with its members.\n */\n turnDataSource<Kind extends ChatNodeKind>(turn: number, kind: Kind): ObservableSnapshot<readonly ChatNodeDataMap[Kind][]>\n /** @param key - stable Conversation Context key. @returns its Turn-process presentation source. */\n processSource(key: string): ChatNodeProcessSource\n /** @returns all currently materialized Nodes without imposing render order. */\n values(): readonly ChatConversationViewNode[]\n}\n\n/** One loaded Turn projected into the compact Chat navigation rail. */\nexport interface TurnNavigationItem {\n readonly turn: number\n /** Stable Conversation Context key the rail scrolls to. */\n readonly anchorKey: string\n /** Bounded prompt preview; empty when the loaded window starts mid-Turn. */\n readonly prompt: string\n /** Bounded assistant-response preview; empty until the Turn answers. */\n readonly response: string\n}\n\n/** Stable live navigation projection of the loaded Turns. */\nexport interface ChatTurnNavigationIndex {\n /**\n * Loaded Turns that have a visible anchor, in timeline order. The array\n * identity changes exactly when a Turn enters, leaves, or changes preview,\n * so a renderer can select it directly as its change signal.\n * @returns current navigation items.\n */\n items(): readonly TurnNavigationItem[]\n}\n\n/** Stable live Location index for Chat nodes. */\nexport interface ChatLocationNodeIndex {\n /** @param turn - owning turn. @returns ordered Chat Node keys in the turn. */\n getTurn(turn: number): readonly string[]\n /** @param turn - owning turn. @param step - owning step. @returns ordered Chat Node keys in the step. */\n getStep(turn: number, step: number): readonly string[]\n}\n\n/** Cross-Node presentation facts derived for one Turn process. */\nexport interface ChatTurnProcessPresentation {\n readonly turn: number\n readonly spec: TurnProcessSpec\n /** Whether the loaded window contains this Turn's `turn/start`; folding is decided per Turn on this fact. */\n readonly turnStarted: boolean\n readonly turnClosed: boolean\n readonly hasExternalProcess: boolean\n /** Like `hasExternalProcess`, but a reply from another Step counts only through its reasoning. */\n readonly hasNonReplyProcess: boolean\n /** A visible input after process output prevents one disclosure from hiding its surrounding groups. */\n readonly hasInterleavedInput: boolean\n}\n\n/** Compatibility projection backing the composer stats pills (StatsPills.tsx) and the legacy top-level snapshot fields. */\nexport interface LegacyConversationSlice {\n readonly nodes: readonly ConversationNode[]\n readonly turnTimings: ReadonlyMap<number, { readonly startTime: number; readonly endTime?: number }>\n readonly turnEnds: ReadonlyMap<number, number>\n readonly partial: PartialAssistant | null\n readonly runningCalls: readonly RunningToolCall[]\n}\n\n/** Incremental Chat publication with immutable order and stable live keyed readers. */\nexport interface ChatSnapshot {\n readonly order: readonly string[]\n readonly nodes: ChatNodeStore\n readonly locations: ChatLocationNodeIndex\n readonly navigation: ChatTurnNavigationIndex\n readonly timeline: ConversationTimelineSnapshot\n readonly legacy: LegacyConversationSlice\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationViewSnapshotMap {\n chat: ChatSnapshot\n }\n}\n\nconst EMPTY_LIST: readonly never[] = []\nconst EMPTY_TIMELINE: ConversationTimelineSnapshot = { turnOrder: EMPTY_LIST, turns: new Map() }\nconst EMPTY_NODE_SOURCE: ChatNodeSource = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\nconst EMPTY_BOTTOM_SOURCE: ObservableSnapshot<boolean> = {\n getSnapshot: () => false,\n subscribe: () => () => {},\n}\nconst EMPTY_NODE_PROCESS_SOURCE: ChatNodeProcessSource = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\nconst EMPTY_TURN_NODE_SOURCE: ObservableSnapshot<readonly never[]> = {\n getSnapshot: () => EMPTY_LIST,\n subscribe: () => () => {},\n}\n\n/** Empty Chat target used before a view builder is registered. */\nexport const EMPTY_CHAT_SNAPSHOT: ChatSnapshot = {\n order: EMPTY_LIST,\n nodes: {\n get: () => undefined,\n source: () => EMPTY_NODE_SOURCE,\n bottomSource: () => EMPTY_BOTTOM_SOURCE,\n turnDataSource: () => EMPTY_TURN_NODE_SOURCE,\n processSource: () => EMPTY_NODE_PROCESS_SOURCE,\n values: () => EMPTY_LIST,\n },\n locations: {\n getTurn: () => EMPTY_LIST,\n getStep: () => EMPTY_LIST,\n },\n navigation: {\n items: () => EMPTY_LIST,\n },\n timeline: EMPTY_TIMELINE,\n legacy: {\n nodes: EMPTY_LIST,\n turnTimings: new Map(),\n turnEnds: new Map(),\n partial: null,\n runningCalls: EMPTY_LIST,\n },\n}\n","/** Chat-owned approval detail resolving a correlated Tool call's command. */\nimport type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type {} from '@deepseek-ai/dsh-client-ui-approval/client'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\n\ninterface ApprovalToolCall {\n readonly callId: string\n readonly name: string\n readonly argsRaw: string\n}\n\n/**\n * Extract the command line from a correlated Tool call: a shell `command`, or the text `terminal_send` types into a terminal.\n * @param call - Tool call name and arguments, when a correlated call exists.\n * @returns command text, or undefined for absent, empty, malformed, or unrelated arguments.\n */\nexport function commandOf(call: ApprovalToolCall | undefined): string | undefined {\n if (call === undefined) return undefined\n try {\n const args = JSON.parse(call.argsRaw) as Record<string, unknown>\n const command = call.name === 'terminal_send' ? args.text : args.command\n return typeof command === 'string' && command.length > 0 ? command : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Render the command of the Chat Tool node correlated with an approval.\n * @param props - Approval identity and Session-standard Chat selector hook.\n * @returns command text when the correlated call carries one.\n */\nexport function ApprovalCommand({ callId, useChat }: PropsRuntime<'conversation.approval.detail'>) {\n const command = useChat((snapshot) => {\n for (const node of snapshot.nodes.values()) {\n const root = node.kind === 'tool-call' ? (node as ChatNode<'tool-call'>).data.root : undefined\n if (root !== undefined && root.callId === callId && !('kind' in root) && root.phase === 'start') return commandOf(root)\n }\n return undefined\n })\n return command ?? null\n}\n","/** Gesture-time path resolution for Chat-owned file references. */\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\nimport { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'\nimport type {} from '@deepseek-ai/dsh-api-session-controller/client'\n\n/**\n * Bind path resolution to the originating Session without capturing its current directory.\n * @param ctx - Chat plugin context.\n * @param sessionId - Original Session identity.\n * @returns Resolver using the live working directory, falling back to the workspace root.\n */\nexport function sessionFilePath(ctx: Context, sessionId: SessionId): (path: string) => string {\n return (path) => {\n const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd\n const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined\n return resolveWorkspacePath(current ?? cwd, path)\n }\n}\n","import type { ChatConversationViewNode } from './chat-nodes.ts'\n\n/**\n * Chat group-tree positions from the outermost inward; a Node at a position\n * also has the effect of every inner position.\n * - `exchange`: the Node's Turn opens an exchange, the run of Turns that lasts\n * until the next opening Turn.\n * - `input`: the Node is an input of its Turn. An input before the Turn's\n * process is the Turn's opening input; a later one is interleaved and keeps\n * the whole Turn open.\n * - `turn`: the Node stays in its Turn outside the Turn's process disclosure.\n * - `process`: the Node stays in the process disclosure outside step runs.\n * - absent: the Node joins the step run around it.\n *\n * The Definition that builds a Node chooses its position, and step runs, the\n * process disclosure, and Turn inputs are selected by position. An\n * `assistant-step` Node places its rows without one: its reasoning row joins\n * the step run and its reply row stands outside it.\n *\n * Whole-Turn folding also exempts reply rows: with the default Replies After\n * Collapse choice every `assistant-step` reply row stays visible, and with\n * Final answer only just the final answer's reply row does. Reasoning rows\n * stay in the folded process in both choices.\n */\nexport type ChatGroupTree = 'exchange' | 'input' | 'turn' | 'process'\n\nconst DEPTH: Readonly<Record<ChatGroupTree, number>> = { exchange: 0, input: 1, turn: 2, process: 3 }\n\n/**\n * Test whether a Node stands at a group-tree position or outside it.\n * @param node - Chat Node.\n * @param position - group-tree position to compare against.\n * @returns whether the Node's position is `position` or an outer one.\n */\nexport function isAtOrOutside(node: Pick<ChatConversationViewNode, 'groupTree'>, position: ChatGroupTree): boolean {\n return node.groupTree !== undefined && DEPTH[node.groupTree] <= DEPTH[position]\n}\n","/** Localized copy adapters for Cordis-free Markdown primitives. */\n\nimport type { MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from './contract/slots.ts'\n\n/**\n * Build the complete Markdown chrome copy for one locale revision.\n * @param t - Chat locale seat.\n * @returns Labels for code fences and footnotes.\n */\nexport function markdownLabels(t: ChatViewSlotProps['t']): MarkdownLabels {\n return {\n code: { copyLabel: t('copy'), copiedLabel: t('copied'), toolbarLabels: { codeLabel: t('codeBlock.title'), wrapLabel: t('codeBlock.wrap'), unwrapLabel: t('codeBlock.unwrap') } },\n footnotes: t('markdown.footnotes'),\n }\n}\n","/** Fixed-pitch virtual turn rail with independent activation and scroll controls. */\nimport {\n forwardRef, memo, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState,\n type CSSProperties, type ForwardedRef,\n} from 'react'\nimport { defaultRangeExtractor, elementScroll, observeElementOffset, useVirtualizer, type Range } from '@tanstack/react-virtual'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { TurnRailItem } from './turn-rail-items.ts'\nimport css from './TurnNavigator.module.css'\n\ninterface TurnNavigatorProps {\n readonly items: readonly TurnRailItem[]\n readonly activeTurn: number | null\n /** Turn whose jump is still paging history in; its mark pulses. */\n readonly busyTurn: number | null\n readonly onNavigate: (item: TurnRailItem) => void\n readonly t: ChatViewSlotProps['t']\n}\n\n/** Imperative controls for known turns; unknown turn numbers are ignored. */\nexport interface TurnNavigatorHandle {\n /** @param turn - turn to activate through the navigation callback. */\n activateTurn(turn: number): void\n /** @param turn - turn to center in the rail without navigating the transcript. */\n scrollToTurn(turn: number): void\n}\n\n/** Fixed pitch between neighbouring marks; overflow scrolls inside the frame. */\nconst TURN_SPACING_PX = 10\n/** Rail padding above the first mark and below the last one, per end. */\nconst RAIL_INSET_PX = 6\n/** Fade band the mask reserves at a scrollable end. */\nconst FADE_PX = 24\n\nfunction preferredScrollBehavior(): 'auto' | 'smooth' {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n ? 'auto'\n : 'smooth'\n}\n\ninterface TurnMarkProps extends Pick<TurnNavigatorProps, 'onNavigate' | 't'> {\n readonly item: TurnRailItem\n readonly index: number\n readonly active: boolean\n readonly busy: boolean\n readonly previewId: string | undefined\n readonly registerElement: (element: HTMLButtonElement | null) => void\n readonly onPreview: (turn: number | null) => void\n readonly onFocusChange: (turn: number | null) => void\n}\n\nconst TurnMark = memo(function TurnMark({\n item, index, active, busy, previewId, registerElement, onNavigate, onPreview, onFocusChange, t,\n}: TurnMarkProps) {\n const classes = [css.mark]\n if (item.anchor.kind === 'unloaded') classes.push(css.markUnloaded)\n if (active) classes.push(css.markActive)\n else if (previewId !== undefined) classes.push(css.markPreview)\n if (busy) classes.push(css.markBusy)\n return (\n <button\n ref={registerElement}\n data-index={index}\n type=\"button\"\n className={classes.join(' ')}\n aria-label={t(\n item.anchor.kind === 'loaded' ? 'chat.turnNavigation.jump' : 'chat.turnNavigation.jumpLoad',\n { turn: item.turn },\n )}\n aria-current={active ? 'true' : undefined}\n aria-busy={busy ? 'true' : undefined}\n aria-describedby={previewId}\n onPointerMove={() => { onPreview(item.turn) }}\n onClick={() => { onNavigate(item) }}\n onFocus={() => { onFocusChange(item.turn) }}\n onBlur={() => { onFocusChange(null) }}\n />\n )\n})\n\nfunction TurnNavigatorRail(\n { items, activeTurn, busyTurn, onNavigate, t }: TurnNavigatorProps,\n ref: ForwardedRef<TurnNavigatorHandle>,\n) {\n const [previewTurn, setPreviewTurn] = useState<number | null>(null)\n const [focusedTurn, setFocusedTurn] = useState<number | null>(null)\n const scrollerRef = useRef<HTMLDivElement | null>(null)\n const initialization = useRef({\n placed: false,\n index: 0,\n follow: null as { index: number; count: number; height: number } | null,\n publishOffset: null as ((offset: number, scrolling: boolean) => void) | null,\n })\n /** While the pointer works the rail, follow must not move it under the hand. */\n const pointerInsideRef = useRef(false)\n const previewId = useId()\n const turnIndexes = useMemo(() => {\n const indexes = new Map<number, number>()\n items.forEach((item, index) => { indexes.set(item.turn, index) })\n return indexes\n }, [items])\n const activeIndex = activeTurn === null ? undefined : turnIndexes.get(activeTurn)\n useLayoutEffect(() => { initialization.current.index = activeIndex ?? 0 }, [activeIndex])\n const focusedIndex = focusedTurn === null ? undefined : turnIndexes.get(focusedTurn)\n const previewIndex = previewTurn === null ? undefined : turnIndexes.get(previewTurn)\n const onFocusChange = useCallback((turn: number | null) => {\n setFocusedTurn(turn)\n setPreviewTurn(turn)\n }, [])\n const virtualizer = useVirtualizer<HTMLDivElement, HTMLButtonElement>({\n count: items.length,\n enabled: items.length >= 2,\n directDomUpdates: true,\n directDomUpdatesMode: 'transform',\n useScrollendEvent: true,\n getScrollElement: useCallback(() => scrollerRef.current, []),\n getItemKey: useCallback((index: number) => items[index]?.turn ?? index, [items]),\n estimateSize: () => TURN_SPACING_PX,\n measureElement: () => TURN_SPACING_PX,\n initialRect: { width: 0, height: 0 },\n initialOffset: 0,\n scrollToFn: (offset, options, instance) => {\n if (initialization.current.placed) elementScroll(offset, options, instance)\n },\n observeElementOffset: (instance, notify) => {\n initialization.current.publishOffset = notify\n const dispose = observeElementOffset(instance, notify)\n return () => {\n dispose?.()\n initialization.current.placed = false\n initialization.current.follow = null\n initialization.current.publishOffset = null\n }\n },\n observeElementRect: (instance, notify) => {\n const element = instance.scrollElement\n const Observer = instance.targetWindow?.ResizeObserver\n if (element === null || Observer === undefined) return\n const observer = new Observer(([entry]) => {\n if (entry === undefined) return\n const box = entry.borderBoxSize[0]\n const rect = {\n width: Math.round(box?.inlineSize ?? entry.contentRect.width),\n height: Math.round(box?.blockSize ?? entry.contentRect.height),\n }\n const initial = initialization.current\n if (!initial.placed && rect.height > 0) {\n const max = Math.max(0, instance.getTotalSize() - rect.height)\n const center = initial.index * TURN_SPACING_PX + RAIL_INSET_PX\n const target = Math.max(0, Math.min(max, center - rect.height / 2))\n initial.placed = true\n initial.follow = { index: initial.index, count: instance.options.count, height: rect.height }\n element.scrollTop = target\n initial.publishOffset?.(target, false)\n }\n notify(rect)\n })\n observer.observe(element, { box: 'border-box' })\n return () => { observer.disconnect() }\n },\n paddingStart: RAIL_INSET_PX - TURN_SPACING_PX / 2,\n paddingEnd: RAIL_INSET_PX - TURN_SPACING_PX / 2,\n scrollPaddingStart: FADE_PX,\n scrollPaddingEnd: FADE_PX,\n overscan: 3,\n rangeExtractor: useCallback((range: Range) => {\n const indexes = defaultRangeExtractor(range)\n if (focusedIndex !== undefined) {\n const last = Math.min(range.count - 1, focusedIndex + 1)\n for (let index = Math.max(0, focusedIndex - 1); index <= last; index++) {\n if (!indexes.includes(index)) indexes.push(index)\n }\n indexes.sort((left, right) => left - right)\n }\n return indexes\n }, [focusedIndex]),\n })\n const scrollTop = virtualizer.scrollOffset ?? 0\n const viewHeight = virtualizer.scrollRect?.height ?? 0\n const virtualItems = virtualizer.getVirtualItems()\n\n const scrollToIndex = useCallback((\n index: number, reveal: 'if-needed' | 'always', behavior: 'auto' | 'smooth' | 'instant' = preferredScrollBehavior(),\n ): void => {\n const item = virtualizer.measurementsCache[index]\n const height = virtualizer.scrollRect?.height ?? 0\n if (item === undefined || height <= 0) return\n const current = virtualizer.scrollOffset ?? 0\n const center = item.start + item.size / 2\n if (reveal === 'if-needed') {\n const { scrollPaddingStart, scrollPaddingEnd } = virtualizer.options\n if (center >= current + scrollPaddingStart && center <= current + height - scrollPaddingEnd) return\n }\n const target = center - height / 2\n const max = Math.max(0, virtualizer.getTotalSize() - height)\n const delta = Math.max(0, Math.min(max, target)) - current\n if (delta !== 0) virtualizer.scrollBy(delta, { behavior })\n }, [virtualizer])\n\n useImperativeHandle(ref, (): TurnNavigatorHandle => ({\n activateTurn(turn) {\n const index = turnIndexes.get(turn)\n const item = index === undefined ? undefined : items[index]\n if (item !== undefined) onNavigate(item)\n },\n scrollToTurn(turn) {\n const index = turnIndexes.get(turn)\n if (index !== undefined) scrollToIndex(index, 'always')\n },\n }), [items, turnIndexes, onNavigate, scrollToIndex])\n\n useEffect(() => {\n if (viewHeight <= 0) {\n initialization.current.follow = null\n return\n }\n if (activeIndex === undefined || pointerInsideRef.current) return\n const previous = initialization.current.follow\n if (previous?.index === activeIndex && previous.count === items.length && previous.height === viewHeight) return\n initialization.current.follow = { index: activeIndex, count: items.length, height: viewHeight }\n const behavior = previous?.count === items.length && previous.height === viewHeight\n ? preferredScrollBehavior()\n : 'instant'\n scrollToIndex(activeIndex, 'if-needed', behavior)\n }, [activeIndex, items.length, viewHeight, scrollToIndex])\n\n if (items.length < 2) return null\n const preview = previewIndex === undefined ? undefined : items[previewIndex]\n const previewPosition = virtualItems.find(item => item.index === previewIndex)\n const fadeClasses = [css.scroller]\n if (scrollTop > 1) fadeClasses.push(css.fadeTop)\n if (scrollTop < virtualizer.getTotalSize() - viewHeight - 1) fadeClasses.push(css.fadeBottom)\n return (\n <div className={css.slot}>\n <nav\n className={css.frame}\n aria-label={t('chat.turnNavigation.label')}\n onPointerEnter={() => { pointerInsideRef.current = true }}\n onPointerLeave={() => {\n pointerInsideRef.current = false\n setPreviewTurn(null)\n }}\n >\n <div ref={scrollerRef} className={fadeClasses.join(' ')}>\n <div ref={virtualizer.containerRef} className={css.marks}>\n {virtualItems.map(({ index, key }) => {\n const item = items[index]\n if (item === undefined) return null\n return (\n <TurnMark\n key={key}\n item={item}\n index={index}\n active={item.turn === activeTurn}\n busy={item.turn === busyTurn}\n previewId={item.turn === previewTurn ? previewId : undefined}\n registerElement={virtualizer.measureElement}\n onNavigate={onNavigate}\n onPreview={setPreviewTurn}\n onFocusChange={onFocusChange}\n t={t}\n />\n )\n })}\n </div>\n </div>\n {preview !== undefined && previewPosition !== undefined && (\n <div\n id={previewId}\n role=\"tooltip\"\n className={css.preview}\n style={{\n '--turn-preview-center': `${String(previewPosition.start + previewPosition.size / 2 - scrollTop)}px`,\n } as CSSProperties}\n >\n <div className={css.previewPrompt}>\n {preview.prompt || t('chat.turnNavigation.turn', { turn: preview.turn })}\n </div>\n {preview.response !== '' && <div className={css.previewResponse}>{preview.response}</div>}\n </div>\n )}\n </nav>\n </div>\n )\n}\n\n/**\n * Fixed-pitch rail of every known Turn — loaded marks scroll, unloaded marks\n * page history in first — with hover and focus previews. Overflow scrolls\n * inside the frame, gradient fades marking each scrollable end, and the\n * active mark centers only outside the fade-free band while the pointer is\n * elsewhere. Previews follow pointer movement or focus, not scrolling under\n * a stationary pointer.\n */\nexport const TurnNavigator = memo(forwardRef(TurnNavigatorRail))\n","//#region lib/types/index.js\n/**\n* Duplicate-install-safe nominal primitive helpers.\n*\n* A brand makes structurally identical strings or numbers non-interchangeable\n* at the type level: a `SessionId` cannot be passed where a `ToolCallId` is\n* expected, and an event sequence cannot be passed as a log offset. Comparison,\n* logging, and serialization retain the underlying primitive behavior.\n*\n* This package owns no concrete domain value and keeps no runtime identity or mutable\n* state, so independently installed copies produce interchangeable values.\n*\n* @module @deepseek-ai/dsh-brand\n*/\n/**\n* Apply a compile-time string brand without changing the value.\n* @param value - string admitted by the domain that owns the target brand.\n* @returns the same string with the requested compile-time brand.\n*/\nfunction brandString(value) {\n\treturn value;\n}\n/**\n* Apply a compile-time number brand without changing the value.\n* @param value - number admitted by the domain that owns the target brand.\n* @returns the same number with the requested compile-time brand.\n*/\nfunction brandNumber(value) {\n\treturn value;\n}\n//#endregion\nexport { brandNumber, brandString };\n","import { brandNumber, brandString, type Branded, type BrandedNumber } from '@deepseek-ai/dsh-brand'\nimport type {\n AssistantMessage,\n DeveloperMessage,\n AssistantStreamRecord,\n ToolCallId,\n LlmCallConfig,\n LlmCallConfigAdapterDefaults,\n LlmFailure,\n SystemMessage,\n SystemPromptUpdate,\n TokenUsage,\n ToolResultMessage,\n ToolSchema,\n UserMessage,\n} from '@deepseek-ai/dsh-llm'\nimport type { TypertResource } from '@deepseek-ai/dsh-typert-protocol'\nimport type { JsonValue } from '@deepseek-ai/dsh-util-values'\n\n/** Identifies one session in the store (and its persistence artifacts). */\nexport type SessionId = Branded<'SessionId'>\n\n/**\n * Brand a string as a {@link SessionId}.\n * @param id - the raw session id string.\n * @returns the same string with the session-id brand.\n */\nexport function SessionId(id: string): SessionId {\n return brandString<SessionId>(id)\n}\n\n/** Sequence number of one existing event in a Session log. */\nexport type SessionSeq = BrandedNumber<'SessionSeq'>\n\n/**\n * Admit a numeric value as an existing Session event position.\n * @param value - non-negative safe integer admitted by the owning log operation.\n * @returns the same number with the Session-sequence brand.\n */\nexport function SessionSeq(value: number): SessionSeq {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`SessionSeq must be a non-negative safe integer, got ${String(value)}`)\n }\n return brandNumber<SessionSeq>(value)\n}\n\n/** A Session log gap, prefix length, or read offset, which may equal the event count. */\nexport type SessionLogOffset = BrandedNumber<'SessionLogOffset'>\n\n/**\n * Admit a numeric value as a Session log offset.\n * @param value - non-negative safe integer used as a gap or prefix length.\n * @returns the same number with the Session-log-offset brand.\n */\nexport function SessionLogOffset(value: number): SessionLogOffset {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(value)}`)\n }\n return brandNumber<SessionLogOffset>(value)\n}\n\n/** Inclusive Session event watermark, or `-1` before any event exists. */\nexport type SessionSeqCursor = SessionSeq | -1\n\n/** One existing Session event position, or explicit absence. */\nexport type OptionalSessionSeq = SessionSeq | null\n\n/**\n * Current logical Session format version, stamped into every newly written\n * {@link SessionHeader}. Current Session and persistence code accept only this\n * value; header-only readers classify supported historical formats, while an\n * event-body read composes the build-static adjacent chain and publishes only\n * this final generation before constructing a Session.\n *\n * The version is a single monotonic integer with no major/minor split. Retain\n * it when older readers resume correctly, preserve safely ignorable records,\n * or refuse required features before execution, mutation, or tail repair.\n * New readers must preserve historical meanings, including logs mixing old\n * and new record representations. Bump when an existing discriminator cannot\n * prevent unsafe interpretation; a structural difference alone is insufficient.\n * Unknown fields and values require evidence of the released reader's actual\n * admission behavior. The per-event {@link SessionEvent.ignorable} marker\n * governs unknown event types, not arbitrary nested payload changes.\n * Same-version readers retain earlier representations: the adjacent migration\n * chain does not run when stored and current versions match. A subsequent\n * migration must account for all supported representations of its source.\n * Compatibility review and the retained migration obligations are recorded in\n * `.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md`.\n */\nexport const SESSION_FORMAT_VERSION = 4\n\n/**\n * Immutable validated storage metadata, kept outside the conversation event log.\n */\nexport interface SessionHeader {\n /**\n * Current logical format version, stamped from {@link SESSION_FORMAT_VERSION}.\n * Historical physical headers are translated before entering this interface.\n */\n readonly version: typeof SESSION_FORMAT_VERSION\n /** The session's id (mirrors the {@link Session}'s id). */\n readonly id: SessionId\n /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */\n readonly createdAt: number\n /** Absolute working directory the session was created in (if any). */\n readonly cwd?: string\n /**\n * Direct creator of a subagent Session. Ordinary forks omit this field;\n * historical ordinary forks may retain their source id here. Presence alone\n * does not classify a Session as a subagent; use `origin` for that distinction.\n */\n readonly parentSession?: SessionId\n /**\n * Whether this Session contains a fork-inherited event prefix. The exact prefix\n * length is Session state rather than ordinary header metadata.\n */\n readonly isSeeded: boolean\n /**\n * Coarse product classification for a session created as a subagent child.\n * This is presentation metadata, not proof that the child is continuable.\n */\n readonly origin?: 'subagent'\n /**\n * Delegation depth: absent (zero) for a top-level session, parent depth + 1\n * for a subagent child. Persisted so a recursion budget survives restart and\n * resume — a runtime-only depth would reset a resumed child to top-level.\n */\n readonly delegationDepth?: number\n /**\n * Id of the agent preset this session's agent was composed from, when the\n * deployment composes per session. Durable because the preset decides the\n * session's tools and prompt: a resume that restored a different composition\n * would replay history the model can no longer act on.\n */\n readonly agentPreset?: string\n}\n\n/**\n * Options for creating a {@link Session} via the store. `seed` replays/forks\n * an existing event log; `meta` carries the caller-supplied storage fields the\n * store folds into a {@link SessionHeader}.\n */\nexport interface CreateSessionOptions {\n /** Initial replay or fork history supplied at construction. */\n readonly seed?: readonly SessionEvent[]\n /**\n * Exact fork-inherited prefix length when `meta.isSeeded` is true. The\n * constructor appends the child-owned tagged marker at the cut unless\n * the seed already includes it followed by child-owned fork closers.\n */\n readonly inheritedEventCount?: SessionLogOffset\n /**\n * Storage metadata read once before publication. `isSeeded` marks fork\n * lineage; supplying replay history alone does not make it inherited.\n */\n readonly meta?: {\n readonly cwd?: string\n readonly parentSession?: SessionId\n readonly createdAt?: number\n readonly isSeeded?: boolean\n readonly origin?: 'subagent'\n readonly delegationDepth?: number\n readonly agentPreset?: string\n }\n}\n\n/**\n * Aliasing state of an adoptable Session seed. `shared-frozen` permits deeply\n * frozen aliases plus independently owned unfrozen values in the same seed.\n */\nexport type SessionSeedEventState = 'detached' | 'shared-frozen'\n\n/**\n * Adoptable storage values transferred to {@link SessionStore.prepare}\n * without another copy or freeze pass.\n */\nexport interface RestoredSessionOptions {\n /** Events that are independently owned or already deeply frozen. */\n readonly seed: SessionEvent[]\n /** Independently owned storage metadata to validate and freeze in place. */\n readonly meta: SessionHeader\n /** Exact number of fork-inherited leading events decoded from storage. */\n readonly inheritedEventCount: SessionLogOffset\n /** Aliasing state carried from the operation that produced the seed. */\n readonly eventState: SessionSeedEventState\n}\n\n/** Inputs accepted while constructing an unpublished Session. */\nexport type PrepareSessionOptions =\n | (CreateSessionOptions & { readonly eventState?: undefined })\n | RestoredSessionOptions\n\n/** Why an active agent driver was cancelled. */\nexport type AgentCancelCause =\n | { readonly kind: 'user' }\n | { readonly kind: 'parent' }\n | { readonly kind: 'hook'; readonly reason: string }\n | { readonly kind: 'disposed' }\n\n/** Durable cancellation cause, including imports whose original coarse record carried no cause. */\nexport type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy' }\n\n/**\n * Why a turn ended. Merge-extensible sum type.\n */\nexport interface TurnEndReasonMap {\n completed: { kind: 'completed' }\n /** A cancellation request interrupted the live turn. */\n aborted: { kind: 'aborted'; reason: TurnEndCancelCause }\n\n blocked: { kind: 'blocked' }\n /**\n * The turn failed. `error` is always a structured failure: the `LlmError`\n * facts verbatim, or `{ message: errorChain(error), code }` flattened from\n * any other error, where `code` is `TOOL_ACTIVATION_FAILED` for a failed\n * tool condition and `UNKNOWN` otherwise.\n */\n error: { kind: 'error'; error: LlmFailure }\n /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */\n 'max-tokens': { kind: 'max-tokens' }\n /**\n * A crash-orphaned turn was closed after the fact: agent-loop resume appends\n * this closer for a stored log whose last turn never ended, and session-query\n * synthesizes it on cold reads. The loop never emits this marker live, and\n * the events recorded before the crash remain intact.\n */\n interrupted: { kind: 'interrupted' }\n /**\n * Fork-seed construction closed a turn that was still open at the fork\n * boundary in the source session. Only fork seeds carry this marker — the\n * loop never emits it — and the source events before the boundary remain\n * intact in the child.\n */\n forked: { kind: 'forked' }\n}\n\n/** The union over {@link TurnEndReasonMap} — why a turn ended; plugins extend it by merging variants into the map. */\nexport type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap]\n\n/**\n * Logged request state outside derived history: call config and tools. The\n * system prompt is derived history — surface node 0, a `system/message` event.\n * The latest full `request/header` snapshot reconstructs the header; canonical\n * empty optional fields are absent.\n */\nexport interface EpochHeader {\n /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */\n config: LlmCallConfig\n /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */\n adapterDefaults?: LlmCallConfigAdapterDefaults\n /** Assembled tool schemas; absent for a tool-less request. */\n tools?: ToolSchema[]\n /** Retired request text; system prompts belong to system/message events.\n * @persistenceReserved\n */\n system?: never\n}\n\n/** Registration-bound metadata for one resolved model route. */\nexport interface RequestContext {\n /** Registered provider route the metadata belongs to. */\n provider: string\n /** Provider-owned model id the metadata belongs to. */\n model: string\n /** Maximum combined request and response context in tokens, when advertised. */\n contextWindow?: number\n /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */\n systemPromptUpdate?: SystemPromptUpdate\n}\n\n/**\n * Why a `request/header` snapshot was appended: `'initial'` — the log's first\n * header (a new conversation); `'resume'` — a loop instance's first request\n * over a log that already has header events (process restart, fork seed);\n * `'change'` — a later request used a different header; `'series'` — an unchanged\n * header began an explicitly distinct message series or followed a surface\n * replacement. Other reasons carry `startsSeries` when a new series coincides.\n */\nexport type RequestHeaderReason = 'initial' | 'resume' | 'change' | 'series'\n\n/**\n * The merge-extensible, append-only source of truth for an agent interaction.\n * Message history is derived from this log. Every event is lossless JSON and\n * sequence numbers stay contiguous. Assistant attempt events embed their exact\n * compact raw streams so persistence stores one durable settlement per attempt.\n */\nexport interface SessionEventMap {\n /**\n * Opens turn `turn` before the loop claims queued input or runs pre-step.\n * Rejection, empty input, cancellation, or failure may close it with no\n * step; otherwise the following identified `user/message` event or batch\n * records the messages entering the step.\n */\n 'turn/start': { turn: number }\n /**\n * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn\n * with no entered step has no `step/start` or `step/end`. The loop does not await a\n * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the\n * per-request durability checkpoint, and consumers that read storage after\n * `whenIdle()` flush themselves. Success commits the turn; rejection is\n * reported live and does not prevent later work.\n */\n 'turn/end': { turn: number; reason: TurnEndReason }\n /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */\n 'step/start': { turn: number; step: number }\n /** Closes step `step` of turn `turn`. */\n 'step/end': { turn: number; step: number }\n /**\n * A user-role message on the model-visible surface: a direct human prompt\n * (the queued message claimed for this turn), a synthetic `agent.inject()`\n * context (file-change notices, subdir AGENTS.md, skill content, cron\n * notifications, …), or an entered goal continuation round. All three\n * project their `content` verbatim; `source` tells them apart.\n */\n 'user/message': UserMessage\n /** An incremental agent session change admitted at the named turn and step. */\n 'developer/message': {\n turn: number\n step: number\n message: DeveloperMessage\n /** Earlier request/header defining every tool addition; required exactly when additions are present. */\n headerSeq?: SessionSeq\n }\n /**\n * The rendered system prompt on the model-visible surface. The loop appends\n * the first one as surface node 0 before the step's first `user/message`.\n * A prepared in-history route can append nonempty changes in a continuing\n * series. An incapable route, or a new series whose effective text differs,\n * normalizes text to the first system node; a series start whose latest\n * surviving node already holds the rendering leaves it in place.\n * Normalization empties nonempty later nodes, then rewrites the head if\n * needed, through logged per-node replacements. An empty rendering always\n * clears all active system nodes, leaving no older instructions model-visible.\n * Empty later nodes are dormant and project to no message; an empty head with\n * no active later node records \"no system prompt\". Restored nonempty text follows\n * the same route and series rule; empty nodes never restore older text.\n */\n 'system/message': { turn: number; step: number; message: SystemMessage }\n /**\n * Assembled assistant message for one step (derived history uses this).\n * Carries the step's `usage` when the adapter reported token accounting, so\n * the model output and its accounting travel together (there is no separate\n * usage record). `usage` is absent when the adapter reported none. A turn\n * cancelled mid-stream finalizes its delivered text/reasoning prefix as this\n * event with `interrupted: true`; undispatched tool calls are absent. The\n * marker distinguishes that prefix without re-deriving interruption from turn\n * boundaries. An aborted turn with no such event streamed no visible content.\n */\n 'assistant/message': {\n turn: number\n step: number\n message: AssistantMessage\n /** Exact timed model stream, compacted without joining delta boundaries. */\n stream: AssistantStreamRecord[]\n usage?: TokenUsage\n interrupted?: true\n }\n /**\n * One model attempt that committed no surface message. The embedded stream\n * preserves a failed, retried, cancelled, or stream-error attempt that\n * reached settlement without fabricating model-visible history.\n */\n 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[] }\n /**\n * The model requested one tool invocation: `name` with the raw `arguments`\n * JSON string exactly as the model produced it (unparsed). `callId` pairs the\n * call with its `tool/result`.\n */\n 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string }\n /**\n * A completed tool call's model-facing result, optional internal failure\n * identity and user-facing reason, and optional tool-private `meta`\n * presentation payload. The reason remains outside the model-facing message.\n * `meta` is\n * opaque to the core (the producing tool owns its shape and reads it back in\n * `presentResult`) but MUST be JSON-serializable: `Session.append`\n * runtime-validates all event data with `isJsonValue`, so a non-serializable\n * `meta` is rejected at the source, and the durable log reproduces the\n * identical card on replay. Absent\n * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time\n * contextual diff here).\n */\n 'tool/result': {\n turn: number\n step: number\n message: ToolResultMessage\n /**\n * Optional failure identity and raw user-facing reason, outside model content;\n * allowed only when the message has `isError: true`.\n */\n error?: { name: string; code: string; reason?: string }\n meta?: JsonValue\n }\n /**\n * Full header for the next request, appended inside its step before dispatch.\n * It is log-only; the latest snapshot reconstructs the request header.\n */\n 'request/header': {\n header: EpochHeader\n reason: RequestHeaderReason\n /** This request begins a distinct model-message series, independently of the header reason. */\n startsSeries?: true\n }\n /**\n * Route metadata for the next request, logged only when the route, capacity,\n * or system prompt update mode changes. It does not participate in request\n * reconstruction or header equality. Prompt admission uses the bound prepared\n * call's capability, not this snapshot from an earlier request.\n */\n 'request/context': RequestContext\n /**\n * Separates inherited or restored history from later lifecycle-owned work.\n * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork\n * seed can already contain its tagged marker and child-owned synthetic\n * closers before construction.\n *\n * A fresh fork child owns one `{ inherited: true }` marker at its exact\n * inherited-prefix cut, even when that prefix ends in an ancestor marker.\n * `buildForkSeed` appends that marker before any synthetic closers; the\n * `Session` constructor supplies it when given only the inherited prefix.\n * The last tagged marker is the current Session's cut; untagged markers\n * keep ordinary restore and replay lifecycle boundaries.\n *\n * Only the `Session` constructor and `buildForkSeed` may create this marker.\n * Session append does not reject other writers, so a plugin appending one\n * would silently classify every live bracket before it as seed history.\n *\n * An owner of a standalone open/close bracket (`compaction/start` …\n * `compaction/end`) reads it because seed history and live work are otherwise\n * byte-identical: an unmatched opening marker before this event belongs to\n * an ended lifecycle, whatever ended it. NOT a liveness signal about other\n * writers — a concurrently live session holds its own boundary elsewhere,\n * so tolerating concurrent writers needs a signal beyond the log.\n */\n 'session/end-seed': { inherited?: true }\n}\n\n/** The appendable event-type keys of {@link SessionEventMap}, plugin-merged extensions included. */\nexport type SessionEventType = keyof SessionEventMap\n\n/**\n * The subset of {@link SessionEventType} values whose events produce LLM\n * messages and are eligible to appear on the ordered surface. Only these\n * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite\n * earlier sources through {@link SessionEvent.sourceEventSeqs}.\n */\nexport type SurfaceEventType =\n | 'system/message'\n | 'developer/message'\n | 'user/message'\n | 'assistant/message'\n | 'tool/result'\n\n/** A message-producing event carrying its required surface operation. */\nexport type SurfaceEvent = SessionEvent<SurfaceEventType>\n\n/**\n * How a session event entered the ordered surface. Only valid on\n * {@link SurfaceEventType} events.\n *\n * - `'append'`: added to the tail — normal path for user/assistant/tool\n * messages.\n * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq`\n * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as\n * surface nodes in the current surface. `startSeq === endSeq` replaces a single\n * node. The node's {@link SessionEvent.sourceEventSeqs} must include every\n * shadowed surface node. Used by compaction; any surface-replacing producer\n * may use it.\n */\nexport type SurfaceOp =\n | 'append'\n | { op: 'replace'; startSeq: SessionSeq; endSeq: SessionSeq }\n\n/**\n * Surface placement and cited source-event seqs for {@link Session.append}. Required on\n * message-producing events and forbidden on log-only events.\n */\nexport type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {\n surfaceOp: SurfaceOp\n} & (T extends 'assistant/message' ? {\n /** Assistant messages embed their provider stream instead of citing source events. */\n sourceEventSeqs?: never\n} : {\n /** Complete non-empty set of known earlier source-event seqs. */\n sourceEventSeqs?: SessionSeq[]\n})\n\n/** One positional event call proposed for append, without assigned sequence or time. */\nexport type SessionEventInput = {\n [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent<K>] : []]\n}[SessionEventType]\n\n/**\n * One immutable entry in the session log.\n *\n * A proper discriminated union over `type` (not independent `type`/`data`\n * unions), so `switch (event.type)` narrows `event.data` without casts.\n *\n * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:\n * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`,\n * `assistant/message`, `tool/result`).\n * Non-surface events (boundary markers, attempts, errors) never carry\n * surface metadata — the compiler enforces this at `Session.append()`\n * call sites.\n */\nexport type SessionEvent<T extends SessionEventType = SessionEventType> = {\n [K in SessionEventType]: {\n type: K\n /** Monotonic sequence number within the session. */\n seq: SessionSeq\n /** Unix epoch milliseconds. */\n time: number\n data: SessionEventMap[K]\n /**\n * Marks an event a reader may safely skip when it does not recognize\n * `type`. Absent means required: a reader meeting an unrecognized type\n * without this marker MUST refuse to reconstruct the session instead of\n * silently dropping the event, because an unrecognized required event may\n * change how the rest of the log is interpreted. A writer sets `true` only\n * on purely informational records whose loss cannot affect reconstruction;\n * defaulting to required means a forgotten marker over-refuses (an\n * inconvenience) rather than silently resuming a gutted session.\n */\n ignorable?: true\n } & (K extends SurfaceEventType ? SurfaceIntent<K> : {\n surfaceOp?: never\n sourceEventSeqs?: never\n })\n}[T]\n\n/**\n * Event type of an experimental plugin record: `plugin:` followed by\n * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,\n * each starting with a letter or digit. A record type is never a\n * {@link SessionEventMap} member.\n */\nexport type PluginRecordType = `plugin:${string}`\n\n/**\n * Payloads written by experimental packages, keyed by their `plugin:` record\n * names. Packages augment this map to type writes and enter the current plugin\n * record catalog; these declarations do not enter {@link SessionEventMap} or\n * released persistence schemas. Stored records still require owner validation.\n */\nexport interface PluginRecordMap {}\n\n/**\n * One committed experimental plugin record, read from the log by\n * `pluginRecordOf`. The record's owner validates `data` before use, because a\n * restored record carries whatever JSON an earlier build of its owner wrote,\n * or a V3 event that a format migration renamed into the `plugin:` namespace held.\n */\nexport interface PluginRecord {\n /** The record type, chosen by the owning plugin. */\n readonly type: PluginRecordType\n /** The record's position in the Session log. */\n readonly seq: SessionSeq\n /** Unix epoch milliseconds at append. */\n readonly time: number\n /** The JSON payload as committed. */\n readonly data: unknown\n}\n\ndeclare module '@deepseek-ai/dsh-typert-protocol' {\n interface TypertResourceMap {\n /** One Session; the Session Controller registers its default `sessionId` wire field. */\n session: TypertResource<SessionId>\n }\n\n interface RemoteErrorDetailsMap {\n /** The named Session does not exist; produced by every layer that resolves a SessionId. */\n 'session/not-found': { readonly sessionId: SessionId }\n }\n}\n","/**\n * View-layer union of the host turn outline and the loaded rail items. The\n * conversation snapshot never carries projection values, so this merge is the\n * one place the rail's two sources meet: the `turnOutline` projection names\n * every turn of the session, and the loaded window supplies anchors and\n * richer previews for the turns it holds.\n */\n\nimport type {} from '@deepseek-ai/dsh-session-turn-outline/client'\nimport { SessionSeq } from '@deepseek-ai/dsh-session/types'\nimport type { TurnNavigationItem } from '../contract/snapshot.ts'\n\n/** One rail mark: a loaded Turn scrolls to its row; an unloaded one pages history through its seq first. */\nexport interface TurnRailItem {\n readonly turn: number\n /** Bounded prompt preview (loaded window first, outline fallback). */\n readonly prompt: string\n /** Bounded response preview (loaded window first, outline fallback). */\n readonly response: string\n /** How the rail reaches the Turn. */\n readonly anchor:\n | { readonly kind: 'loaded'; readonly key: string }\n | { readonly kind: 'unloaded'; readonly seq: SessionSeq }\n}\n\nconst EMPTY_ITEMS: readonly TurnRailItem[] = []\n\n/**\n * Structurally narrow one wire outline entry (projection values cross the\n * wire). `turn` and `seq` are the load-bearing fields — a mark cannot exist\n * or jump without them — so their damage drops the entry; the previews are\n * decorative, so a malformed one degrades to `''` and the turn stays\n * navigable by number.\n */\nfunction outlineEntry(value: unknown): { turn: number; seq: SessionSeq; prompt: string; response: string } | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const entry = value as { turn?: unknown; seq?: unknown; prompt?: unknown; response?: unknown }\n if (typeof entry.turn !== 'number' || !Number.isSafeInteger(entry.turn) || entry.turn < 0) return undefined\n if (typeof entry.seq !== 'number' || !Number.isSafeInteger(entry.seq) || entry.seq < 0 || Object.is(entry.seq, -0)) return undefined\n return {\n turn: entry.turn,\n seq: SessionSeq(entry.seq),\n prompt: typeof entry.prompt === 'string' ? entry.prompt : '',\n response: typeof entry.response === 'string' ? entry.response : '',\n }\n}\n\n/** Wire outline entries, or none when the projection is absent or malformed. */\nfunction outlineEntries(outline: unknown): readonly unknown[] {\n return Array.isArray(outline) ? outline : EMPTY_ITEMS\n}\n\n/**\n * Merge the host outline with the loaded rail items into the full ladder.\n * A turn present in both sides keeps the loaded anchor, taking an outline\n * preview only where the window's own is empty (a mid-Turn window head, or a\n * turn whose loaded nodes carry no text); turns on one side only pass\n * through. Result ascends by turn.\n * @param loaded - loaded-window rail items (timeline order).\n * @param outline - `turnOutline` projection value, treated as wire data.\n * @returns every known turn, ascending; a stable empty array when none.\n */\nexport function mergeTurnRailItems(\n loaded: readonly TurnNavigationItem[],\n outline: unknown,\n): readonly TurnRailItem[] {\n const byTurn = new Map<number, TurnRailItem>()\n for (const raw of outlineEntries(outline)) {\n const entry = outlineEntry(raw)\n if (entry === undefined) continue\n byTurn.set(entry.turn, {\n turn: entry.turn,\n prompt: entry.prompt,\n response: entry.response,\n anchor: { kind: 'unloaded', seq: entry.seq },\n })\n }\n for (const item of loaded) {\n const preview = byTurn.get(item.turn)\n byTurn.set(item.turn, {\n turn: item.turn,\n prompt: item.prompt !== '' ? item.prompt : preview?.prompt ?? '',\n response: item.response !== '' ? item.response : preview?.response ?? '',\n anchor: { kind: 'loaded', key: item.anchorKey },\n })\n }\n if (byTurn.size === 0) return EMPTY_ITEMS\n return [...byTurn.values()].sort((left, right) => left.turn - right.turn)\n}\n","/** DOM selection validation and visible-text projection, independent of business actions. */\n\nconst PROJECTED_BLOCK_TAGS = new Set([\n 'ADDRESS', 'ARTICLE', 'ASIDE', 'BLOCKQUOTE', 'DD', 'DIV', 'DL', 'DT', 'FIGCAPTION',\n 'FIGURE', 'FOOTER', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'LI', 'MAIN',\n 'NAV', 'OL', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TFOOT', 'THEAD', 'TR', 'UL',\n])\nconst PROJECTED_CELL_TAGS = new Set(['TD', 'TH'])\n\nfunction excluded(element: Element): boolean {\n if (element.matches('.katex-mathml, [data-text-interaction-exclude], [hidden], .sr-only')) return true\n if (element.matches('[aria-hidden=\"true\"]') && !element.matches('.katex-html')) return true\n return element.tagName === 'BUTTON' && element.parentElement?.tagName !== 'CODE'\n}\n\nfunction projectedBoundary(node: Node): '\\n' | '\\t' | '' {\n if (!(node instanceof Element)) return ''\n if (PROJECTED_CELL_TAGS.has(node.tagName)) return '\\t'\n return PROJECTED_BLOCK_TAGS.has(node.tagName) ? '\\n' : ''\n}\n\nfunction projectedSeparator(previous: Node, current: Node): '\\n' | '\\t' | '' {\n const left = projectedBoundary(previous)\n const right = projectedBoundary(current)\n if (left === '\\n' || right === '\\n') return '\\n'\n return left === '\\t' || right === '\\t' ? '\\t' : ''\n}\n\ninterface ProjectedText {\n readonly text: string\n readonly offsets: readonly number[]\n}\n\nfunction projectedText(node: Text): ProjectedText {\n const source = node.data\n const parent = node.parentElement\n const view = node.ownerDocument.defaultView\n const whiteSpace = parent === null || view === null ? '' : view.getComputedStyle(parent).whiteSpace\n const preservesBreaks = whiteSpace === 'pre' || whiteSpace === 'pre-wrap'\n || whiteSpace === 'pre-line' || whiteSpace === 'break-spaces'\n const offsets = new Array<number>(source.length + 1).fill(0)\n const structuralWhitespace = !preservesBreaks\n && /^[\\t\\n\\f\\r ]*$/u.test(source)\n && [node.previousSibling, node.nextSibling].some(\n sibling => sibling !== null && projectedBoundary(sibling) !== '',\n )\n if (structuralWhitespace) return { text: '', offsets }\n let text = ''\n let cursor = 0\n if (!preservesBreaks && node.previousSibling instanceof HTMLElement\n && node.previousSibling.tagName === 'BR' && source.startsWith('\\n')) {\n cursor = 1\n }\n while (cursor < source.length) {\n const softBreak = preservesBreaks ? null : /^[ \\t]*[\\r\\n]+[ \\t]*/u.exec(source.slice(cursor))\n if (softBreak !== null) {\n const end = cursor + softBreak[0].length\n for (let index = cursor; index < end; index++) offsets[index] = text.length\n text += ' '\n offsets[end] = text.length\n cursor = end\n continue\n }\n offsets[cursor] = text.length\n text += source.charAt(cursor)\n cursor += 1\n offsets[cursor] = text.length\n }\n return { text, offsets }\n}\n\ninterface ProjectedTextSpan {\n readonly node: Text\n readonly start: number\n readonly offsets: readonly number[]\n}\n\ninterface ProjectedFragment {\n readonly text: string\n readonly spans: readonly ProjectedTextSpan[]\n readonly boundaries: readonly (readonly [Node, readonly number[]])[]\n}\n\nfunction projectedFragment(node: Node): ProjectedFragment {\n if (node.nodeType === Node.TEXT_NODE) {\n const projected = projectedText(node as Text)\n return {\n text: projected.text,\n spans: projected.offsets.length <= 1\n ? []\n : [{ node: node as Text, start: 0, offsets: projected.offsets }],\n boundaries: [],\n }\n }\n if (!(node instanceof Element)) {\n return { text: '', spans: [], boundaries: [] }\n }\n if (excluded(node)) return { text: '', spans: [], boundaries: [] }\n if (node.tagName === 'BR') return { text: '\\n', spans: [], boundaries: [] }\n let text = ''\n let previous: Node | null = null\n const spans: ProjectedTextSpan[] = []\n const boundaries: Array<readonly [Node, readonly number[]]> = []\n const offsets = new Array<number>(node.childNodes.length + 1).fill(0)\n for (const [index, child] of [...node.childNodes].entries()) {\n const fragment = projectedFragment(child)\n if (fragment.text !== '' && previous !== null) {\n const separator = projectedSeparator(previous, child)\n const needsSeparator = separator === '\\n'\n ? !text.endsWith('\\n') && !fragment.text.startsWith('\\n')\n : separator === '\\t' && !/[\\t\\n]$/u.test(text) && !/^[\\t\\n]/u.test(fragment.text)\n if (needsSeparator) text += separator\n }\n offsets[index] = text.length\n const base = text.length\n text += fragment.text\n for (const span of fragment.spans) {\n spans.push({ node: span.node, start: base + span.start, offsets: span.offsets })\n }\n for (const [owner, childOffsets] of fragment.boundaries) {\n boundaries.push([owner, childOffsets.map(offset => base + offset)])\n }\n if (fragment.text !== '') previous = child\n offsets[index + 1] = text.length\n }\n boundaries.push([node, offsets])\n return { text, spans, boundaries }\n}\n\nfunction projectedOffset(\n projection: ProjectedFragment,\n container: Node,\n offset: number,\n): number | null {\n if (container.nodeType === Node.TEXT_NODE) {\n const span = projection.spans.find(candidate => candidate.node === container)\n const projected = span?.offsets[offset]\n return span === undefined || projected === undefined ? null : span.start + projected\n }\n const boundaries = projection.boundaries.find(([owner]) => owner === container)?.[1]\n return boundaries?.[offset] ?? null\n}\n\n/** One browser range contained by an enabled text source. */\nexport interface TextSelection {\n readonly source: HTMLElement\n readonly range: Range\n}\n\n/**\n * Find a single noncollapsed selection inside one enabled source.\n * @param root - mounted interaction area.\n * @param selection - browser selection in that area's document.\n * @returns the selected source and range, or null across sources and excluded content.\n */\nexport function readTextSelection(root: HTMLElement, selection: Selection | null): TextSelection | null {\n if (selection === null || selection.rangeCount !== 1 || selection.isCollapsed) return null\n const range = selection.getRangeAt(0)\n const sourceOf = (node: Node): HTMLElement | null =>\n (node instanceof Element ? node : node.parentElement)?.closest<HTMLElement>('[data-text-interaction-source]') ?? null\n const source = sourceOf(range.startContainer)\n if (source === null || source !== sourceOf(range.endContainer) || !root.contains(source)\n || source.closest('[hidden], [inert], [data-text-interaction-exclude]') !== null) return null\n return { source, range }\n}\n\n/**\n * Project selected DOM text with visible block boundaries and without renderer chrome.\n * @param selection - range and its source, obtained through readTextSelection.\n * @returns trimmed visible text; empty or excluded selections return null.\n */\nexport function selectedText(selection: TextSelection): string | null {\n const { source, range } = selection\n const projection = projectedFragment(source)\n const start = projectedOffset(projection, range.startContainer, range.startOffset)\n const end = projectedOffset(projection, range.endContainer, range.endOffset)\n if (start === null || end === null) return null\n const text = projection.text.slice(start, end).trim()\n return text === '' ? null : text\n}\n","/** Area-local text gestures, action ownership, dismissal, and content-relative placement. */\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'\nimport type { RefObject } from 'react'\nimport { readTextSelection, selectedText } from './text-selection.ts'\nimport type { TextSelection } from './text-selection.ts'\n\nimport type {\n TextInteractionGesture, TextInteractionSurface, TextInteractionTrigger,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** Current area-owned surface and its actions. */\nexport interface TextInteractionBinding extends Omit<TextInteractionSurface, 'trigger'> {\n readonly active: { readonly id: string; readonly trigger: TextInteractionTrigger } | null\n}\n\ninterface Target {\n readonly source: HTMLElement\n readonly selection: TextSelection | null\n readonly text: string | null\n readonly point: { readonly x: number; readonly y: number } | null\n}\n\ninterface Bounds { left: number; top: number; right: number; bottom: number }\n\nfunction rectBounds(rect: DOMRect): Bounds {\n return { left: rect.left, top: rect.top, right: rect.left + rect.width, bottom: rect.top + rect.height }\n}\n\nfunction intersects(a: Bounds, b: Bounds): boolean {\n return a.right > b.left && a.left < b.right && a.bottom > b.top && a.top < b.bottom\n}\n\nfunction sameRange(a: Range | null, b: Range | null): boolean {\n return a === b || (a !== null && b !== null && a.startContainer === b.startContainer\n && a.startOffset === b.startOffset && a.endContainer === b.endContainer && a.endOffset === b.endOffset)\n}\n\nfunction available(root: HTMLElement, target: Target): boolean {\n if (!root.isConnected || !root.contains(target.source) || !target.source.hasAttribute('data-text-interaction-source')) return false\n const view = root.ownerDocument.defaultView\n /* v8 ignore if -- Mounted browser content always has an owner window. */\n if (view === null) return false\n for (let node: HTMLElement | null = target.source; node !== null; node = node.parentElement) {\n const style = view.getComputedStyle(node)\n if (node.hidden || node.inert || node.hasAttribute('data-text-interaction-exclude')\n || style.display === 'none' || style.visibility === 'hidden') return false\n }\n return target.selection === null || (target.source.contains(target.selection.range.startContainer)\n && target.source.contains(target.selection.range.endContainer) && selectedText(target.selection) === target.text)\n}\n\nfunction composerSeat(root: HTMLElement): HTMLElement | null {\n return root.closest('[data-conversation-scroll]')?.querySelector<HTMLElement>('[data-composer-seat]') ?? null\n}\n\nfunction visibleBounds(root: HTMLElement, source: HTMLElement, view: Window): Bounds {\n const rootRect = rectBounds(root.getBoundingClientRect())\n const bounds: Bounds = {\n left: Math.max(0, rootRect.left), right: Math.min(view.innerWidth, rootRect.right), top: 0, bottom: view.innerHeight,\n }\n for (let node: HTMLElement | null = source; node !== null; node = node.parentElement) {\n const style = view.getComputedStyle(node)\n const rect = rectBounds(node.getBoundingClientRect())\n if (/(auto|scroll|hidden|clip)/u.test(style.overflowX)) {\n bounds.left = Math.max(bounds.left, rect.left)\n bounds.right = Math.min(bounds.right, rect.right)\n }\n if (/(auto|scroll|hidden|clip)/u.test(style.overflowY)) {\n bounds.top = Math.max(bounds.top, rect.top)\n bounds.bottom = Math.min(bounds.bottom, rect.bottom)\n }\n }\n const composer = composerSeat(root)?.getBoundingClientRect()\n if (composer !== undefined && composer.height > 0\n && composer.right > bounds.left && composer.left < bounds.right) {\n bounds.bottom = Math.min(bounds.bottom, composer.top)\n }\n return bounds\n}\n\n/**\n * Own text interactions for one positioned content area and its local surface.\n * @param rootRef - existing content element with position: relative.\n * @param surfaceRef - absolute surface inside that element; only the selected Slot consumer is mounted.\n * @param dispatchInteraction - framework-injected plugin gesture dispatch.\n * @param registeredIds - live registered owners used to dismiss removed plugins.\n * @returns current owner and area-local selection actions.\n */\nexport function useTextInteraction(\n rootRef: RefObject<HTMLElement>, surfaceRef: RefObject<HTMLElement>,\n dispatchInteraction: (gesture: TextInteractionGesture) => string | null,\n registeredIds: readonly string[],\n): TextInteractionBinding {\n const target = useRef<Target | null>(null)\n const [active, setActive] = useState<TextInteractionBinding['active']>(null)\n const dismiss = useCallback(() => {\n target.current = null\n if (surfaceRef.current !== null) surfaceRef.current.style.visibility = 'hidden'\n setActive(null)\n }, [surfaceRef])\n useEffect(dismiss, [registeredIds, dispatchInteraction, dismiss])\n const readText = useCallback(() => {\n const root = rootRef.current\n const current = target.current\n if (root === null || current === null || !available(root, current)) return null\n return current.selection === null ? null : selectedText(current.selection)\n }, [rootRef])\n const clearSelection = useCallback(() => { rootRef.current?.ownerDocument.getSelection()?.removeAllRanges() }, [rootRef])\n\n const place = useCallback(() => {\n const root = rootRef.current\n const surface = surfaceRef.current\n const current = target.current\n if (root === null || surface === null || current === null) return\n if (!available(root, current)) { dismiss(); return }\n const view = root.ownerDocument.defaultView\n /* v8 ignore if -- Mounted browser content always has an owner window. */\n if (view === null) return\n const visible = visibleBounds(root, current.source, view)\n const selectionRects = current.selection === null ? [] : [...current.selection.range.getClientRects()]\n const fallback = current.selection?.range.getBoundingClientRect() ?? current.source.getBoundingClientRect()\n const rects = selectionRects.length === 0 ? [fallback] : selectionRects\n const sourceRect = current.source.getBoundingClientRect()\n const pointX = current.point === null ? 0 : sourceRect.left + current.point.x - current.source.scrollLeft\n const pointY = current.point === null ? 0 : sourceRect.top + current.point.y - current.source.scrollTop\n const anchor = current.point === null\n ? rects.map(rectBounds).find(rect => intersects(rect, visible))\n : { left: pointX, right: pointX + 1, top: pointY, bottom: pointY + 1 }\n if (anchor === undefined || !intersects(anchor, visible) || visible.right <= visible.left || visible.bottom <= visible.top) {\n surface.style.visibility = 'hidden'\n return\n }\n const gap = 8\n surface.style.maxWidth = `${visible.right - visible.left}px`\n surface.style.maxHeight = `${visible.bottom - visible.top}px`\n const size = surface.getBoundingClientRect()\n const x = current.point === null\n ? (Math.max(anchor.left, visible.left) + Math.min(anchor.right, visible.right) - size.width) / 2\n : anchor.left\n const above = anchor.top - gap - size.height\n const below = anchor.bottom + gap\n const preferredY = current.point === null && above >= visible.top ? above : below\n const left = Math.max(visible.left, Math.min(x, visible.right - size.width))\n const top = Math.max(visible.top, Math.min(preferredY, visible.bottom - size.height))\n const rootRect = root.getBoundingClientRect()\n const scaleX = root.offsetWidth === 0 ? 1 : rootRect.width / root.offsetWidth\n const scaleY = root.offsetHeight === 0 ? 1 : rootRect.height / root.offsetHeight\n surface.style.left = `${(left - rootRect.left) / scaleX - root.clientLeft + root.scrollLeft}px`\n surface.style.top = `${(top - rootRect.top) / scaleY - root.clientTop + root.scrollTop}px`\n surface.style.visibility = 'visible'\n }, [dismiss, rootRef, surfaceRef])\n\n // The surface's measured dimensions are needed after its Slot owner renders, before paint.\n useLayoutEffect(place, [active, place])\n useEffect(() => {\n const root = rootRef.current\n const surface = surfaceRef.current\n if (root === null || surface === null) return\n const document = root.ownerDocument\n const view = document.defaultView\n /* v8 ignore if -- Mounted browser content always has an owner window. */\n if (view === null) return\n let pointerSelecting = false\n let keyboardSelecting = false\n let selectionChangedDuringGesture = false\n let previousRange: Range | null = null\n let frame: number | undefined\n const schedulePlacement = (): void => {\n if (target.current === null || frame !== undefined) return\n frame = view.requestAnimationFrame(() => { frame = undefined; place() })\n }\n const dispatch = (trigger: TextInteractionTrigger, next: Target, event: Event): void => {\n if (!available(root, next)) return\n const id = dispatchInteraction({\n trigger, hasSelection: next.selection !== null,\n readText: () => next.text,\n preventDefault: () => { event.preventDefault() },\n })\n if (id === null) return\n target.current = next\n setActive({ id, trigger })\n }\n const updateSelection = (event: Event): void => {\n if (pointerSelecting || keyboardSelecting) { selectionChangedDuringGesture = true; return }\n if (target.current !== null && target.current.point !== null) return\n if (target.current !== null && surface.contains(document.activeElement)) return\n const selection = readTextSelection(root, document.getSelection())\n const range = selection?.range ?? null\n if (!selectionChangedDuringGesture && sameRange(previousRange, range)) return\n selectionChangedDuringGesture = false\n previousRange = range?.cloneRange() ?? null\n dismiss()\n if (selection === null) return\n const text = selectedText(selection)\n if (text === null) return\n dispatch('selection', { source: selection.source, selection: { ...selection, range: selection.range.cloneRange() }, text, point: null }, event)\n }\n const insideSurface = (event: Event): boolean => event.composedPath().includes(surface)\n const pointerDown = (event: PointerEvent): void => {\n if (insideSurface(event)) return\n const selection = document.getSelection()\n previousRange = selection?.rangeCount === 1 ? selection.getRangeAt(0).cloneRange() : null\n dismiss()\n selectionChangedDuringGesture = false\n pointerSelecting = event.button === 0 && event.target instanceof Node && root.contains(event.target)\n }\n const pointerUp = (event: PointerEvent): void => {\n if (!pointerSelecting) return\n pointerSelecting = false\n updateSelection(event)\n }\n const cancel = (): void => { pointerSelecting = false; keyboardSelecting = false; dismiss() }\n const keyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') { cancel(); return }\n if (insideSurface(event) || !(event.target instanceof Node) || !root.contains(event.target)) return\n if (event.key === 'Shift' || event.shiftKey) { keyboardSelecting = true; dismiss() }\n }\n const keyUp = (event: KeyboardEvent): void => {\n if (!keyboardSelecting || (event.key !== 'Shift' && event.shiftKey)) return\n keyboardSelecting = false\n updateSelection(event)\n }\n const contextMenu = (event: MouseEvent): void => {\n if (insideSurface(event)) return\n const element = event.target instanceof Element ? event.target : null\n const source = element?.closest<HTMLElement>('[data-text-interaction-source]')\n if (source === undefined || source === null || !root.contains(source)\n || element?.closest('[data-text-interaction-exclude], button, input, textarea, [contenteditable=\"true\"]')) return\n pointerSelecting = false\n dismiss()\n const selected = readTextSelection(root, document.getSelection())\n const keyboard = event.clientX === 0 && event.clientY === 0\n const inSelection = selected?.source === source && (keyboard || [...selected.range.getClientRects()].some(rect =>\n event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom))\n const selection = inSelection ? selected : null\n const bounds = source.getBoundingClientRect()\n dispatch('contextmenu', {\n source, selection: selection === null ? null : { ...selection, range: selection.range.cloneRange() },\n text: selection === null ? null : selectedText(selection),\n point: {\n x: (keyboard ? 0 : event.clientX - bounds.left) + source.scrollLeft,\n y: (keyboard ? 0 : event.clientY - bounds.top) + source.scrollTop,\n },\n }, event)\n }\n document.addEventListener('selectionchange', updateSelection)\n document.addEventListener('pointerdown', pointerDown, true)\n document.addEventListener('pointerup', pointerUp)\n document.addEventListener('pointercancel', cancel)\n document.addEventListener('keydown', keyDown)\n document.addEventListener('keyup', keyUp)\n document.addEventListener('scroll', schedulePlacement, true)\n root.addEventListener('contextmenu', contextMenu)\n view.addEventListener('resize', schedulePlacement)\n view.addEventListener('blur', cancel)\n return () => {\n document.removeEventListener('selectionchange', updateSelection)\n document.removeEventListener('pointerdown', pointerDown, true)\n document.removeEventListener('pointerup', pointerUp)\n document.removeEventListener('pointercancel', cancel)\n document.removeEventListener('keydown', keyDown)\n document.removeEventListener('keyup', keyUp)\n document.removeEventListener('scroll', schedulePlacement, true)\n root.removeEventListener('contextmenu', contextMenu)\n view.removeEventListener('resize', schedulePlacement)\n view.removeEventListener('blur', cancel)\n if (frame !== undefined) view.cancelAnimationFrame(frame)\n }\n }, [dismiss, place, rootRef, surfaceRef, dispatchInteraction])\n useEffect(() => {\n const root = rootRef.current\n const surface = surfaceRef.current\n if (active === null || root === null || surface === null) return\n const view = root.ownerDocument.defaultView\n /* v8 ignore if -- Mounted browser content always has an owner window. */\n if (view === null) return\n let frame: number | undefined\n const schedule = (): void => {\n if (frame !== undefined) return\n frame = view.requestAnimationFrame(() => { frame = undefined; place() })\n }\n const resize = new ResizeObserver(schedule)\n resize.observe(root)\n resize.observe(surface)\n const composer = composerSeat(root)\n if (composer !== null) resize.observe(composer)\n const mutations = new MutationObserver((records) => {\n if (records.some(record => !surface.contains(record.target))) schedule()\n })\n mutations.observe(root, { childList: true, subtree: true, characterData: true, attributes: true })\n return () => {\n resize.disconnect()\n mutations.disconnect()\n if (frame !== undefined) view.cancelAnimationFrame(frame)\n }\n }, [active, place, rootRef, surfaceRef])\n return { active, dismiss, readText, clearSelection }\n}\n","/** Turn jumps and history-prepend anchoring, independent of DOM measurement. */\nimport { useLayoutEffect, useState } from 'react'\nimport type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { SessionSeq } from '@deepseek-ai/dsh-session/types'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { TurnRailItem } from './turn-rail-items.ts'\nimport type { ChatReading, ReadingSample } from './use-chat-reading.ts'\nimport type { ChatViewport } from './use-chat-viewport.ts'\n\n/** History availability and loading operations for the committed Chat window. */\nexport interface ChatNavigationInput extends Pick<ChatViewSlotProps, 'loadOlder' | 'loadThrough' | 'consumeOlder'> {\n readonly firstSeq: ChatNode['anchorSeq'] | null\n readonly hasMore: boolean\n readonly loadingOlder: boolean\n readonly historyLoadStatus: SessionSnapshot['historyLoadStatus']\n readonly isOpen: boolean\n}\n\ninterface TurnJump {\n readonly turn: number\n readonly seq: SessionSeq\n phase: 'loading' | 'settled'\n landing: 'pending' | 'landed' | 'interrupted'\n repageHead: ChatNavigationInput['firstSeq']\n}\n\ntype HistoryIntent = 'none' | 'auto' | 'manual'\n\n/** Owns one replaceable turn jump and the anchor retained while history loads. */\nexport class ChatNavigation {\n private jump: TurnJump | null = null\n private settleFrame: number | null = null\n private historyFrame: number | null = null\n private historyIntent: HistoryIntent = 'none'\n private historyRequested = false\n\n constructor(\n private readonly viewport: ChatViewport,\n private readonly reading: ChatReading,\n private input: ChatNavigationInput,\n private readonly onBusyTurn: (turn: number | null) => void,\n private readonly onHistoryIntent: (intent: HistoryIntent) => void = () => {},\n ) {}\n\n /**\n * Adopt committed history availability without starting a request.\n * @param input - history state from the latest committed render.\n */\n setInput(input: ChatNavigationInput): void {\n this.input = input\n this.historyRequested = false\n if (!input.isOpen || input.historyLoadStatus === 'error' || !input.hasMore) this.setHistoryIntent('none')\n }\n\n /** Cancel navigation when opening a Chat view. */\n reset(): void {\n this.cancel()\n }\n\n /** Cancel local callbacks; late history completions cannot revive a task. */\n dispose(): void {\n this.clearTask()\n if (this.historyFrame !== null) cancelAnimationFrame(this.historyFrame)\n this.historyFrame = null\n }\n\n /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */\n cancel(): void {\n this.setHistoryIntent('none')\n this.clearTask()\n this.onBusyTurn(null)\n }\n\n /** Release a jump after reader input without cancelling an accepted history click. */\n readerInteracted(): void {\n this.clearTask()\n this.onBusyTurn(null)\n }\n\n private clearTask(): void {\n this.cancelFrame()\n this.jump = null\n this.viewport.stopPreserving()\n this.viewport.cancelHistoryPrepend()\n }\n\n /**\n * Replace the current jump with an explicit turn selection.\n * @param item - loaded anchor or unloaded turn to fetch before landing.\n */\n readonly navigateToTurn = (item: TurnRailItem): void => {\n if (item.anchor.kind === 'loaded') {\n this.cancel()\n const landing = this.viewport.scrollToTurn(item.turn)\n if (landing === null) return\n this.reading.acceptNavigation(landing)\n if (this.input.loadingOlder) this.viewport.beginPreserving(landing.position)\n return\n }\n this.cancel()\n this.viewport.beginPreserving()\n this.reading.pauseFollowing()\n const jump: TurnJump = {\n turn: item.turn,\n seq: item.anchor.seq,\n phase: 'loading',\n landing: 'pending',\n repageHead: null,\n }\n this.jump = jump\n this.onBusyTurn(jump.turn)\n this.request(jump)\n }\n\n /** Request and consume one page, retaining the click until success, exhaustion, or failure. */\n readonly loadEarlier = (): void => {\n this.cancel()\n this.setHistoryIntent('manual')\n this.reading.pauseFollowing()\n if (this.input.historyLoadStatus === 'error') {\n this.historyRequested = true\n this.input.loadOlder()\n } else this.requestHistoryCheck()\n }\n\n private setHistoryIntent(intent: HistoryIntent): void {\n if (intent === this.historyIntent) return\n this.historyIntent = intent\n this.onHistoryIntent(intent)\n }\n\n /** Coalesce event-driven checks; waiting never schedules its own next frame. */\n requestHistoryCheck(): void {\n if (!this.input.isOpen || this.input.historyLoadStatus === 'error') return\n if (this.historyIntent === 'none' && (this.input.historyLoadStatus !== 'idle'\n || !this.input.hasMore || this.reading.followingTail)) return\n if (this.historyFrame !== null || typeof requestAnimationFrame !== 'function') return\n this.historyFrame = requestAnimationFrame(() => {\n this.historyFrame = null\n this.checkHistory()\n })\n }\n\n private checkHistory(): void {\n const input = this.input\n if (!input.isOpen || this.jump !== null || this.historyRequested || input.loadingOlder) return\n if (input.historyLoadStatus === 'error') return\n if (input.historyLoadStatus === 'pendingConsumption') {\n if (this.historyIntent === 'none') return\n if (this.reading.followingTail && this.historyIntent === 'auto') {\n this.setHistoryIntent('none')\n return\n }\n if (this.historyIntent === 'manual') {\n this.viewport.beginManualPaging()\n this.reading.pauseFollowing()\n this.consumeHistory('preserve')\n return\n }\n const mode = this.viewport.historyConsumption()\n switch (mode) {\n case 'touch':\n case 'inner-scroll':\n return\n case 'motion':\n case 'pointer':\n case 'unavailable':\n this.setHistoryIntent('none')\n return\n case 'prepend':\n if (!this.viewport.beginHistoryPrepend() && input.firstSeq !== null) {\n this.setHistoryIntent('none')\n return\n }\n break\n case 'preserve':\n case 'native':\n break\n }\n if (mode === 'preserve') {\n this.viewport.beginPreserving()\n if (!this.viewport.preserving) this.viewport.beginPaging()\n if (!this.viewport.preserving && input.firstSeq !== null) {\n this.setHistoryIntent('none')\n return\n }\n this.reading.pauseFollowing()\n }\n this.consumeHistory(mode)\n return\n }\n if (!input.hasMore || this.historyIntent !== 'manual' && (this.reading.followingTail\n || !this.viewport.confirmHistoryStart())) return\n if (this.historyIntent === 'none') this.setHistoryIntent('auto')\n this.historyRequested = true\n input.loadOlder()\n }\n\n private consumeHistory(mode: 'native' | 'preserve' | 'prepend'): void {\n this.historyRequested = true\n if (this.input.consumeOlder()) this.setHistoryIntent('none')\n else {\n this.historyRequested = false\n if (mode === 'preserve') this.viewport.stopPreserving()\n if (mode === 'prepend') this.viewport.cancelHistoryPrepend()\n }\n }\n\n /**\n * Preserve reader ownership across pending history work.\n * @param sample - settled reader movement that can update or interrupt an anchor.\n */\n readerSampled(sample: ReadingSample): void {\n if (sample.movedByReader && this.jump?.landing === 'landed') this.jump.landing = 'interrupted'\n if (sample.followingTail || sample.movedByReader) this.viewport.stopPreserving()\n }\n\n /**\n * Preserve one paging anchor after a commit or a later size change, regardless of head identity.\n * @returns whether the retained anchor handled the layout change.\n */\n contentCommitted(): boolean {\n if (!this.viewport.preserving || this.reading.pending) return false\n if (this.landJump(false)) return true\n const landing = this.viewport.preserve()\n if (landing === null) return false\n this.reading.preservePosition(landing)\n return true\n }\n\n /** Land, retry, or complete the current jump against the committed window. */\n reconcile(): void {\n const jump = this.jump\n if (jump === null || this.reading.pending) return\n if (jump.phase === 'loading') {\n if (jump.landing === 'pending') this.landJump(false)\n return\n }\n if (this.input.loadingOlder) return\n if (this.landJump(true)) return\n const uncovered = this.input.firstSeq === null || this.input.firstSeq > jump.seq\n if (uncovered && this.input.hasMore && jump.repageHead !== this.input.firstSeq) {\n jump.repageHead = this.input.firstSeq\n this.viewport.beginPreserving()\n this.request(jump)\n return\n }\n const fallback = this.viewport.scrollToTurnAtOrAfter(jump.turn)\n this.cancel()\n if (fallback !== null) this.reading.acceptNavigation(fallback)\n }\n\n private landJump(settle: boolean): boolean {\n const jump = this.jump\n if (jump === null) return false\n if (jump.landing === 'interrupted') {\n if (settle) { this.cancel(); return true }\n return false\n }\n const landing = this.viewport.scrollToTurn(jump.turn)\n if (landing === null) return false\n this.reading.acceptNavigation(landing)\n if (settle) this.cancel()\n else {\n this.viewport.beginPreserving(landing.position)\n jump.landing = 'landed'\n }\n return true\n }\n\n private request(jump: TurnJump): void {\n jump.phase = 'loading'\n const settled = (): void => {\n if (this.jump !== jump) return\n jump.phase = 'settled'\n this.cancelFrame()\n if (typeof requestAnimationFrame !== 'function') this.reconcile()\n else this.settleFrame = requestAnimationFrame(() => {\n this.settleFrame = null\n if (this.jump === jump) this.reconcile()\n })\n }\n void this.input.loadThrough(jump.seq).then(settled, settled)\n }\n\n private cancelFrame(): void {\n if (this.settleFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.settleFrame)\n this.settleFrame = null\n }\n}\n\n/**\n * Retain one navigation owner for the component's lifetime.\n * @param viewport - turn-aware DOM operations.\n * @param reading - reading and follow policy receiving navigation landings.\n * @param input - committed history state and load operations.\n * @returns the navigation owner and its visible busy turn.\n */\nexport function useChatNavigation(\n viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput,\n): { navigation: ChatNavigation; busyTurn: number | null; historyPending: boolean; historyProcessing: boolean } {\n const [busyTurn, setBusyTurn] = useState<number | null>(null)\n const [historyIntent, setHistoryIntent] = useState<HistoryIntent>('none')\n const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn, setHistoryIntent))\n useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input])\n useLayoutEffect(() => () => { navigation.dispose() }, [navigation])\n return { navigation, busyTurn, historyPending: historyIntent === 'manual', historyProcessing: historyIntent !== 'none' }\n}\n","/** Independent bottom-follow intent and native scrolling, without paging or DOM observers. */\nimport { useState } from 'react'\n\n/** Scroll position, caller-supplied floor, and viewport height; raw measurements use the physical floor. */\nexport interface ViewportMetrics {\n readonly top: number\n readonly floor: number\n readonly height: number\n}\n\n/**\n * Read one scrollport without measuring its children.\n * @param element - scrolling element.\n * @returns current position and range.\n */\nexport function scrollMetrics(element: HTMLElement): ViewportMetrics {\n const height = element.clientHeight\n return { top: element.scrollTop, height, floor: Math.max(0, element.scrollHeight - height) }\n}\n\n/** One scrollport's follow intent; native animation progress does not count as reader movement. */\nexport class ScrollFollow {\n private static readonly owners = new WeakMap<HTMLElement, ScrollFollow>()\n private target: number | null = null\n private sampledTop: number | undefined\n\n /**\n * @param following - initial follow intent.\n * @param threshold - accepted distance from the floor, in pixels.\n */\n constructor(private following: boolean, private readonly threshold: number) {}\n\n /**\n * Find the mounted controller for reading-position compensation.\n * @param element - scrollport with an optional follow owner.\n * @returns its controller, when bound.\n */\n static forElement(element: HTMLElement): ScrollFollow | undefined { return this.owners.get(element) }\n\n /**\n * Share this controller with reading-position compensation for the same scrollport.\n * @param element - owned scrollport.\n * @returns release the association on unmount or close.\n */\n bind(element: HTMLElement): () => void {\n ScrollFollow.owners.set(element, this)\n return () => { if (ScrollFollow.owners.get(element) === this) ScrollFollow.owners.delete(element) }\n }\n\n /**\n * Expose follow intent independently of the current offset.\n * @returns whether content growth should follow the floor.\n */\n get active(): boolean { return this.following }\n\n /**\n * Expose outstanding native motion before accepting reader input.\n * @returns whether a native follow animation has an outstanding target.\n */\n get animating(): boolean { return this.target !== null }\n\n /**\n * Classify bottom arrivals using this scrollport's own tolerance.\n * @param metrics - current scroll geometry.\n * @returns whether the position is within the follow threshold.\n */\n nearBottom(metrics: ViewportMetrics): boolean { return Math.abs(metrics.floor - metrics.top) <= this.threshold }\n\n /**\n * Commit caller-owned follow decisions without moving the scrollport.\n * @param active - externally committed follow intent.\n */\n setFollowing(active: boolean): void {\n this.following = active\n if (!active) this.target = null\n }\n\n /** Adopt the next visible layout as a fresh reader position. */\n reset(): void {\n this.setFollowing(false)\n this.sampledTop = undefined\n }\n\n /**\n * Adopt delivered scrolling while retaining intent during native animation.\n * @param metrics - current geometry.\n * @param movedByReader - caller attribution; omitted callers compare the last sampled position.\n * @returns updated follow intent.\n */\n sample(metrics: ViewportMetrics, movedByReader = this.sampledTop === undefined\n || Math.abs(metrics.top - this.sampledTop) > 0.5): boolean {\n this.sampledTop = metrics.top\n if (!this.animating && movedByReader) this.following = this.nearBottom(metrics)\n return this.active\n }\n\n /**\n * Settle native scrolling; an off-target stop releases follow intent.\n * @param metrics - actual geometry delivered at scrollend.\n * @returns follow intent after completing or interrupting native motion.\n */\n settle(metrics: ViewportMetrics): boolean {\n const target = this.target\n this.target = null\n return this.sample(metrics, target === null ? undefined\n : Math.abs(metrics.top - Math.min(target, metrics.floor)) > this.threshold)\n }\n\n /**\n * Position immediately and adopt the resulting follow intent.\n * @param element - scrolling element.\n * @param metrics - geometry before positioning.\n * @param top - requested offset, clamped to the measured range.\n * @returns geometry after positioning.\n */\n jump(element: HTMLElement, metrics: ViewportMetrics, top: number): ViewportMetrics {\n const animated = this.animating\n this.target = null\n const target = Math.max(0, Math.min(metrics.floor, top))\n if (animated) element.scrollTo({ top: target, behavior: 'instant' })\n else if (target !== metrics.top) element.scrollTop = target\n const landed = { ...metrics, top: element.scrollTop }\n this.sampledTop = landed.top\n this.following = this.nearBottom(landed)\n return landed\n }\n\n /**\n * Follow the measured floor, respecting reduced motion for smooth requests.\n * Smooth requests preserve an outstanding target; immediate follow updates\n * retarget active motion when content changes the floor.\n * Within-tolerance positioning is immediate while no animation is outstanding.\n * @param element - scrolling element.\n * @param metrics - current geometry.\n * @param behavior - native animation for growth, or immediate positioning unless motion is already active.\n * @returns current geometry; smooth requests retain their starting position until native scroll delivery.\n */\n toBottom(element: HTMLElement, metrics: ViewportMetrics, behavior: 'instant' | 'smooth'): ViewportMetrics {\n this.following = true\n if (metrics.top === metrics.floor) return this.jump(element, metrics, metrics.floor)\n if (behavior === 'instant' && this.animating) {\n // Content grew under an outstanding animation: retarget it instead of cutting to the floor.\n if (this.target !== metrics.floor) {\n this.target = metrics.floor\n element.scrollTo({ top: metrics.floor, behavior: 'smooth' })\n }\n return metrics\n }\n if (behavior === 'instant' || (!this.animating && this.nearBottom(metrics))) return this.jump(element, metrics, metrics.floor)\n if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) {\n return this.jump(element, metrics, metrics.floor)\n }\n if (this.target === null) {\n this.target = metrics.floor\n element.scrollTo({ top: metrics.floor, behavior: 'smooth' })\n }\n return metrics\n }\n\n /**\n * Cancel native motion before a reader gesture; only subsequent actual movement changes follow intent.\n * @param element - scrolling element.\n * @param metrics - position at interruption.\n */\n interrupt(element: HTMLElement, metrics: ViewportMetrics): void {\n if (!this.animating) return\n this.target = null\n this.sampledTop = metrics.top\n element.scrollTo({ top: metrics.top, behavior: 'instant' })\n }\n}\n\n/**\n * Retain one independent follow controller without React updates for scroll samples.\n * @param initial - initial follow intent.\n * @param threshold - accepted distance from the floor, in pixels.\n * @returns the stable controller shared by the caller's scroll and resize handlers.\n */\nexport function useScrollFollow(initial: boolean, threshold: number): ScrollFollow {\n const [follow] = useState(() => new ScrollFollow(initial, threshold))\n return follow\n}\n","/** Follow-tail ownership, saved-position restoration, and sampled reader movement. */\nimport { useLayoutEffect, useState } from 'react'\nimport type { ChatScrollPosition, ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ChatViewport, ViewportLanding, ViewportScroll } from './use-chat-viewport.ts'\nimport { useScrollFollow, type ScrollFollow } from './use-scroll-follow.ts'\n\nconst FOLLOW_THRESHOLD = 24\nconst SCROLL_SAMPLE_INTERVAL_MS = 500\n\n/** Reading facts that affect Chat chrome and initial rail placement. */\nexport interface ChatReadingState {\n readonly initialized: boolean\n readonly followingTail: boolean\n readonly activeTurn: number | null\n}\n\n/** Settled reader position delivered to history-navigation policy. */\nexport interface ReadingSample {\n readonly position: ChatScrollPosition | null\n readonly movedByReader: boolean\n readonly followingTail: boolean\n}\n\ntype PositionStore = ChatViewSlotProps['chatScroll']\n\n/** Owns reading policy and its cancellable sampling work, without DOM access. */\nexport class ChatReading {\n private sampleTimer: number | null = null\n private probeFrame: number | null = null\n private sampled: ((sample: ReadingSample) => void) | null = null\n\n constructor(\n private readonly viewport: ChatViewport,\n private store: PositionStore,\n private state: ChatReadingState,\n private readonly onChange: (state: ChatReadingState) => void,\n private readonly follow: ScrollFollow,\n ) {}\n\n /**\n * Expose pending reader ownership to navigation and resize handlers.\n * @returns whether reader input still awaits interval or scrollend sampling.\n */\n get pending(): boolean { return this.sampleTimer !== null }\n /**\n * Expose the active follow policy.\n * @returns whether content growth retains bottom-follow ownership.\n */\n get followingTail(): boolean { return this.state.followingTail }\n\n /**\n * Adopt the committed Session's scroll memory.\n * @param store - scroll memory for the current Session.\n */\n setStore(store: PositionStore): void { this.store = store }\n\n /**\n * Connect history policy to settled reading observations.\n * @param sampled - receives settled reader positions.\n * @returns a disposer that disconnects only this listener.\n */\n connect(sampled: (sample: ReadingSample) => void): () => void {\n this.sampled = sampled\n return () => { if (this.sampled === sampled) this.sampled = null }\n }\n\n /** Cancel timers and animation frames and detach the sample listener. */\n dispose(): void {\n this.cancelPending()\n this.sampled = null\n }\n\n /** Release bottom follow and pending sampling for an explicit navigation. */\n pauseFollowing(): void {\n this.cancelPending()\n this.publish({ ...this.state, followingTail: false })\n }\n\n /**\n * Land at the current floor and clear saved reader position.\n * @param behavior - immediate positioning, or one native animation when the reader's own input moved the tail.\n */\n followTail(behavior: 'instant' | 'smooth' = 'instant'): void {\n const landing = this.viewport.scrollToBottom(this.follow, behavior)\n if (landing === null) return\n this.cancelPending()\n this.commit(landing, true, this.viewport.latestTurn)\n }\n\n /**\n * Follow the tail on the active fold's animation clock.\n * @param input - whether the reader's own input requests the landing rather than a content change.\n * @returns whether a fold batch owns the tail movement instead of a separate scroll animation.\n */\n followInputFold(input: boolean): boolean {\n this.cancelPending()\n return this.viewport.followInputFold(this.follow, input)\n }\n\n /**\n * Let fold batches read follow intent and commit their tail landings.\n * @returns a disposer that disconnects this reading policy from the viewport.\n */\n bindFolds(): () => void {\n return this.viewport.bindReader({\n follow: this.follow,\n landedAtTail: (landing) => {\n this.cancelPending()\n this.commit(landing, true, this.viewport.latestTurn)\n },\n pending: () => this.pending,\n })\n }\n\n /** Stop a native follow animation where it is; the next sampled position decides follow intent. */\n interruptFollow(): void {\n this.viewport.interruptFollow(this.follow)\n }\n\n /** Restore the Session's semantic position, or follow the tail when none is saved. */\n restore(): void {\n const saved = this.store.read()\n if (saved === null) { this.followTail(); return }\n const landing = this.viewport.restore(saved)\n if (landing === null) return\n this.cancelPending()\n const following = this.follow.nearBottom(landing.metrics)\n this.commit(landing, following, following ? this.viewport.latestTurn : this.state.activeTurn, following)\n if (!this.state.followingTail && landing.position === null) {\n const position = this.viewport.capturePosition()\n if (position !== null) this.store.save(position)\n }\n this.refreshActiveTurn()\n }\n\n /**\n * Adopt a known landing without rediscovering its anchor.\n * @param landing - measured navigation result that replaces pending reader input.\n */\n acceptNavigation(landing: ViewportLanding): void {\n this.cancelPending()\n const following = this.follow.nearBottom(landing.metrics)\n this.commit(landing, following, landing.turn ?? (following ? this.viewport.latestTurn : this.state.activeTurn))\n }\n\n /**\n * Retain reading policy while history changes the anchor's geometry.\n * @param landing - compensated position that retains the current reading policy.\n */\n preservePosition(landing: ViewportLanding): void {\n this.cancelPending()\n this.commit(landing, this.state.followingTail, this.state.activeTurn)\n }\n\n /**\n * Handle pinned layout movement and reader arrivals at the floor immediately.\n * @param scroll - attributed scroll delivery; other reader movement remains pending until sampled.\n */\n readonly onScroll = (scroll: ViewportScroll): void => {\n // Native follow animation progress is not reader movement; scrollend settles it.\n if (this.follow.animating) return\n if ((!scroll.movedByReader && this.state.followingTail)\n || (scroll.movedByReader && Math.abs(scroll.metrics.top - scroll.metrics.floor) < 1)) {\n this.followTail()\n this.sampled?.({ position: null, movedByReader: scroll.movedByReader, followingTail: true })\n return\n }\n this.sampleTimer ??= window.setTimeout(this.flushSample, SCROLL_SAMPLE_INTERVAL_MS)\n }\n\n /**\n * Settle pending reader movement; only the outer scroller can finish its native follow animation.\n * @param outer - whether the event belongs to the outer scroller rather than a process body.\n */\n readonly onScrollEnd = (outer = true): void => {\n if (this.follow.animating) {\n if (!outer) return\n const scroll = this.viewport.readScroll()\n if (scroll === null) return\n if (this.follow.settle(scroll.metrics)) {\n this.followTail()\n return\n }\n this.viewport.acknowledge(scroll.metrics)\n this.publish({ ...this.state, followingTail: false })\n this.refreshActiveTurn()\n return\n }\n this.flushSample()\n }\n\n /** Reconcile a layout change without overriding unsampled reader input. */\n onResize(): void {\n if (this.pending) return\n if (this.state.followingTail) this.followTail()\n else this.refreshActiveTurn()\n }\n\n /** Resolve the active turn from tail ownership or a coalesced reading-line probe. */\n refreshActiveTurn(): void {\n if (this.pending) return\n if (this.state.followingTail) {\n this.publish({ ...this.state, initialized: true, activeTurn: this.viewport.latestTurn })\n return\n }\n if (this.probeFrame !== null) return\n if (typeof requestAnimationFrame !== 'function') this.probe()\n else this.probeFrame = requestAnimationFrame(this.probe)\n }\n\n private commit(\n landing: ViewportLanding, followingTail: boolean, activeTurn: number | null, initialized = true,\n ): void {\n if (followingTail) this.store.save(null)\n else if (landing.position !== null) this.store.save(landing.position)\n this.publish({ initialized, followingTail, activeTurn })\n }\n\n private publish(state: ChatReadingState): void {\n this.follow.setFollowing(state.followingTail)\n if (state.initialized === this.state.initialized && state.followingTail === this.state.followingTail\n && state.activeTurn === this.state.activeTurn) return\n this.state = state\n this.onChange(state)\n }\n\n private cancelPending(): void {\n if (this.sampleTimer !== null) window.clearTimeout(this.sampleTimer)\n if (this.probeFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.probeFrame)\n this.sampleTimer = null\n this.probeFrame = null\n }\n\n private readonly probe = (): void => {\n this.probeFrame = null\n if (this.pending) return\n const scroll = this.viewport.readScroll()\n if (scroll === null) return\n const activeTurn = this.follow.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)\n this.publish({ ...this.state, initialized: true, activeTurn })\n }\n\n private readonly flushSample = (): void => {\n if (!this.pending) return\n this.cancelPending()\n const scroll = this.viewport.readScroll()\n if (scroll === null) return\n const followingTail = this.follow.sample(scroll.metrics, scroll.movedByReader)\n let position: ChatScrollPosition | null = null\n if (!scroll.movedByReader && followingTail) this.followTail()\n else {\n position = followingTail ? null : this.viewport.capturePosition()\n this.viewport.acknowledge(scroll.metrics)\n if (followingTail || position !== null) this.store.save(position)\n const activeTurn = this.follow.nearBottom(scroll.metrics) ? this.viewport.latestTurn : this.viewport.readVisibleTurn(scroll.metrics)\n this.publish({ initialized: true, followingTail, activeTurn })\n }\n this.sampled?.({ position, movedByReader: scroll.movedByReader, followingTail })\n }\n}\n\n/**\n * Retain reading policy and expose only changes in visible reading state.\n * @param viewport - turn-aware DOM operations.\n * @param store - Session-owned semantic scroll memory.\n * @param initialTurn - latest loaded turn before the first landing.\n * @returns the reading owner and its React-visible state.\n */\nexport function useChatReading(\n viewport: ChatViewport, store: PositionStore, initialTurn: number | null,\n): { reading: ChatReading; state: ChatReadingState } {\n const [state, setState] = useState<ChatReadingState>(() => ({\n initialized: false,\n followingTail: store.read() === null,\n activeTurn: initialTurn,\n }))\n const follow = useScrollFollow(state.followingTail, FOLLOW_THRESHOLD + 1)\n const [reading] = useState(() => new ChatReading(viewport, store, state, setState, follow))\n useLayoutEffect(() => { reading.setStore(store) }, [reading, store])\n useLayoutEffect(() => reading.bindFolds(), [reading])\n useLayoutEffect(() => () => { reading.dispose() }, [reading])\n return { reading, state }\n}\n","import { useEffect, useLayoutEffect, useRef, type RefObject } from 'react'\n\n/**\n * Optional visibility operation; its caller owns cancellation and eventually commits the attribute.\n * @param element - stable subtree root.\n * @param hidden - desired hidden state.\n * @param commit - apply the final visibility before reporting the operation complete.\n */\nexport type HiddenTransition = (element: HTMLElement, hidden: boolean, commit: () => void) => void\n\n/**\n * Apply searchable hidden state without unmounting a stable subtree.\n * @param hidden - whether the subtree is currently hidden.\n * @param reveal - callback for browser find's beforematch reveal.\n * @param transition - optional caller-owned visibility operation; otherwise apply synchronously.\n * @returns ref for the stable subtree root.\n */\nexport function useSearchableHidden(\n hidden: boolean,\n reveal: () => void,\n transition?: HiddenTransition,\n): RefObject<HTMLDivElement> {\n const ref = useRef<HTMLDivElement>(null)\n useLayoutEffect(() => {\n const element = ref.current\n if (element === null) return\n if (hidden && element.contains(element.ownerDocument.activeElement)) {\n reveal()\n return\n }\n const commit = (): void => {\n if (hidden) element.setAttribute('hidden', 'until-found')\n else element.removeAttribute('hidden')\n }\n if (transition === undefined) commit()\n else transition(element, hidden, commit)\n }, [hidden, reveal, transition])\n useEffect(() => {\n const element = ref.current\n if (element === null) return\n element.addEventListener('beforematch', reveal)\n return () => { element.removeEventListener('beforematch', reveal) }\n }, [reveal])\n return ref\n}\n","/**\n * Fold transitions owned by one Chat viewport. Every batch containing a closing row moves its boxes and\n * the scrollport on one frame clock; a batch that only reveals rows, or a viewport without a reading\n * policy, uses CSS transitions. Motion is opt-in under `[data-chat-motion]`, respects reduced motion,\n * and clears temporary styles.\n */\nimport { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'\nimport { useSearchableHidden, type HiddenTransition } from './searchable-hidden.ts'\n\nconst FADE_OUT_MS = 70\n/** The box starts closing while the fade finishes; by then the row is nearly transparent. */\nconst CLOSE_DELAY_MS = 50\nconst CLOSE_MS = 110\nconst SETTLE_SLACK_MS = 80\nconst MOTION_SCOPE = '[data-chat-motion]'\nconst EASING = 'cubic-bezier(0.4, 0, 0.2, 1)'\n\n/** Row-local operations supplied by the containing viewport. */\nexport interface FlowMotionRows {\n /** @param element - visible row. @param done - commits hidden state before idle callbacks run. */\n collapse(element: HTMLElement, done: () => void): void\n /** @param element - newly visible row to grow to its natural size. */\n reveal(element: HTMLElement): void\n /** @param element - row whose active transition should be cancelled without hiding it. */\n cancelMotion(element: HTMLElement): void\n /**\n * Hide a row at once, outside a motion scope; the owning viewport measures the layout first.\n * @param element - visible row.\n * @param commit - applies the hidden state.\n */\n hideNow?(element: HTMLElement, commit: () => void): void\n}\n\n/** Geometry captured before one fold batch changes its boxes. */\nexport interface InputFoldBox {\n readonly element: HTMLElement\n readonly height: number\n readonly marginTop: number\n readonly closing: boolean\n}\n\n/** The viewport moves on the same progress that changes the folded boxes. */\nexport interface InputFoldDriver {\n /**\n * Capture geometry and choose the landing before the frame clock changes the boxes.\n * @param boxes - non-nested boxes whose layout changes on this clock.\n * @returns closing boxes that scroll with the content and stay opaque; the rest fade in place. The driver\n * may add boxes while the batch runs, when a newer tail request takes it over.\n */\n begin(boxes: readonly InputFoldBox[]): ReadonlySet<HTMLElement>\n /**\n * Reserve scroll range before box writes.\n * @param progress - shared eased progress from zero to one.\n * @param cancelled - a reading gesture stopped a tail landing's automatic target; a landing that keeps\n * the reader's content still continues and includes the reader's own movement.\n */\n prepare(progress: number, cancelled: boolean): void\n /**\n * Apply viewport geometry after box writes.\n * @param progress - shared eased progress from zero to one.\n * @param cancelled - a reading gesture stopped a tail landing's automatic target.\n * @returns actual scrollTop displacement from the batch start, for closing-content visual compensation.\n */\n frame(progress: number, cancelled: boolean): number\n /**\n * Install the final geometry after the last frame or cancellation.\n * @param cancelled - a reading gesture stopped the automatic target, every closing row reopened, or the\n * viewport detached; the driver commits no obsolete landing.\n */\n finish(cancelled: boolean): void\n}\n\n/** Animation lifetime and fold coordination for one viewport. */\nexport interface FlowMotion extends FlowMotionRows {\n /** @returns whether owned transitions or a scheduled, running, or settling batch remain active. */\n active(): boolean\n /** @returns whether a row owned by this viewport is closing. */\n foldActive(): boolean\n /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */\n onFoldIdle(listener: () => void): () => void\n /** Stop the running batch's automatic target while letting its boxes finish. */\n cancelInput(): void\n /** Restore the running batch's automatic target after a newer request takes it over. */\n resumeInput(): void\n /** @returns whether a fold batch runs, or one is scheduled for this commit's closing rows. */\n inputActive(): boolean\n /** Cancel owned animations and pending work when the viewport detaches. */\n clear(): void\n}\n\n/**\n * Decide whether a row may animate: inside a live scope and not under reduced motion.\n * @param element - row about to be hidden.\n * @returns whether the fade-then-close transition applies.\n */\nexport function motionEnabled(element: HTMLElement): boolean {\n if (element.closest(MOTION_SCOPE) === null) return false\n return typeof matchMedia !== 'function' || !matchMedia('(prefers-reduced-motion: reduce)').matches\n}\n\n/**\n * Whether a row is already hidden or on its way there.\n * @param element - row under Turn-level visibility control.\n * @returns hidden attribute present or a collapse transition outstanding.\n */\nexport function hiddenOrCollapsing(element: HTMLElement): boolean {\n return element.hasAttribute('hidden') || element.dataset.chatMotion === 'collapse'\n}\n\n/**\n * Opacity of a revealing box at batch progress, continuing from the share its own transition reached.\n * @param box - revealing box.\n * @param progress - shared eased progress from zero to one.\n * @returns opacity from zero to one.\n */\nfunction revealedShare(box: OwnedBox, progress: number): number {\n const start = box.height === 0 ? 0 : box.fromHeight / box.height\n return start + (1 - start) * progress\n}\n\n/** A box this viewport owns until it finishes or is cancelled. */\ninterface OwnedBox {\n readonly element: HTMLElement\n /**\n * Full size: a closing box shrinks from it, a revealing box grows to it. A batch re-measures a closing\n * box's current size when it takes the box over.\n */\n height: number\n marginTop: number\n /** Size a revealing box had already reached on its own transition when a batch took it over. */\n fromHeight: number\n fromMarginTop: number\n readonly closing: boolean\n /** The box changed while a batch ran; it waits without a CSS transition until the next batch. */\n held: boolean\n /** Start a held revealing box's own transition when no batch will drive it. */\n release(): void\n /** Stop the box's own transition and fallback timer before a batch drives it. */\n take(): void\n finish(): void\n}\n\n/**\n * Create animation coordination without cross-viewport broadcasts.\n * @param driver - the viewport's driver for the next batch; null while detached.\n * @param foldingChanged - disable or restore this viewport's native scroll anchoring.\n * @param beforeInstantHide - measures the layout before a row hides at once outside a motion scope.\n * @returns stable callbacks and cleanup for this viewport's animations.\n */\nexport function createFlowMotion(\n driver: () => InputFoldDriver | null, foldingChanged: (active: boolean) => void,\n beforeInstantHide?: (element: HTMLElement) => void,\n): FlowMotion {\n const running = new Map<HTMLElement, () => void>()\n let folding = 0\n const foldIdleListeners = new Set<() => void>()\n let batchScheduled = false\n const boxes = new Map<HTMLElement, OwnedBox>()\n let frameRequest: number | null = null\n let batch = false\n let cancelled = false\n let clearEpoch = 0\n let batchCleanup: (() => void) | null = null\n let cancelEmptyBatch: (() => void) | null = null\n /** The batch is committing hidden rows and its final geometry; idle listeners wait until both land. */\n let settling = false\n let anchoringDisabled = false\n\n function cancelInput(): void {\n if (batch) cancelled = true\n }\n\n function resumeInput(): void {\n if (batch) cancelled = false\n }\n\n /** Rows inside a closing ancestor change with it and never join a batch on their own. */\n function batchMember(box: InputFoldBox): boolean {\n return box.element.parentElement?.closest('[data-chat-motion=\"collapse\"]') === null\n }\n\n /** @returns whether a batch started; without a closing member the caller settles held rows itself. */\n function runBatch(current: InputFoldDriver): boolean {\n // Every member continues from the size it has now, so the driver's measured layout and its change\n // amounts describe the same boxes: a closing box may have moved on its own transition, and a revealing\n // box may have grown part of the way on its own transition.\n for (const box of [...boxes.values()]) {\n if (!batchMember(box)) continue\n // A row that finished closing is `hidden=\"until-found\"`, which skips its contents without removing\n // their boxes: a box under it still reports its own size but contributes nothing to the flow.\n if (box.element.parentElement?.closest('[hidden]') != null) {\n box.finish()\n continue\n }\n const height = box.element.offsetHeight\n const marginTop = Number.parseFloat(getComputedStyle(box.element).marginTop) || 0\n if (!box.closing) {\n box.fromHeight = Math.min(height, box.height)\n box.fromMarginTop = Math.min(marginTop, box.marginTop)\n continue\n }\n box.height = height\n box.marginTop = marginTop\n if (height === 0 && marginTop === 0) box.finish()\n }\n const owned = [...boxes.values()]\n const members = owned.filter(batchMember)\n .sort((left, right) => left.element.compareDocumentPosition(right.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)\n if (!members.some(box => box.closing)) return false\n batch = true\n cancelled = false\n const travelling = current.begin(members.map(box => box.closing ? box : {\n element: box.element,\n height: box.height - box.fromHeight,\n marginTop: box.marginTop - box.fromMarginTop,\n closing: false,\n }))\n batchCleanup = () => { current.finish(true) }\n for (const box of owned) box.take()\n for (const box of members) {\n box.element.style.transition = 'none'\n box.element.style.height = `${box.closing ? box.height : box.fromHeight}px`\n box.element.style.marginTop = `${box.closing ? box.marginTop : box.fromMarginTop}px`\n box.element.style.opacity = box.closing ? '1' : String(revealedShare(box, 0))\n }\n const memberSet = new Set(members)\n const settledTravel = new Set<HTMLElement>()\n // A travelling box clips its content as it shrinks, so nested closing rows keep their size until it ends.\n const freezeTravelling = (): void => {\n for (const element of travelling) {\n if (settledTravel.has(element)) continue\n settledTravel.add(element)\n element.style.translate = ''\n for (const box of owned) {\n if (memberSet.has(box) || !element.contains(box.element)) continue\n box.element.style.transition = 'none'\n box.element.style.height = `${box.height}px`\n box.element.style.marginTop = `${box.marginTop}px`\n box.element.style.opacity = '1'\n }\n }\n }\n freezeTravelling()\n const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n let started: number | undefined\n let displacement = 0\n const settle = (finishCancelled: boolean): void => {\n batch = false\n batchCleanup = null\n cancelEmptyBatch = null\n settling = true\n try {\n for (const box of owned) if (boxes.get(box.element) === box) box.finish()\n current.finish(finishCancelled)\n } finally {\n settling = false\n }\n if (folding === 0) notifyIdle()\n // Rows that changed while this batch ran wait in place; the next flush drives or releases them.\n if ([...boxes.values()].some(box => box.held)) flushBatch()\n }\n cancelEmptyBatch = () => {\n if (members.some(box => box.closing && boxes.get(box.element) === box)) return\n if (frameRequest !== null) cancelAnimationFrame(frameRequest)\n frameRequest = null\n settle(true)\n }\n const tick = (now: number): void => {\n frameRequest = null\n started ??= now\n const elapsed = reduced ? CLOSE_DELAY_MS + CLOSE_MS : now - started\n const linear = Math.min(1, Math.max(0, (elapsed - CLOSE_DELAY_MS) / CLOSE_MS))\n const progress = linear * linear * (3 - 2 * linear)\n current.prepare(progress, cancelled)\n freezeTravelling()\n for (const box of members) {\n if (boxes.get(box.element) !== box) continue\n if (box.closing) {\n box.element.style.height = `${box.height * (1 - progress)}px`\n box.element.style.marginTop = `${box.marginTop * (1 - progress)}px`\n box.element.style.opacity = travelling.has(box.element) ? '1' : String(Math.max(0, 1 - elapsed / FADE_OUT_MS))\n } else {\n box.element.style.height = `${box.fromHeight + (box.height - box.fromHeight) * progress}px`\n box.element.style.marginTop = `${box.fromMarginTop + (box.marginTop - box.fromMarginTop) * progress}px`\n box.element.style.opacity = String(revealedShare(box, progress))\n }\n }\n displacement = current.frame(progress, cancelled)\n let removedBefore = 0\n for (const box of members) {\n if (boxes.get(box.element) !== box) continue\n if (box.closing) {\n // Transforming the closing box changes its pixels, not its flow contribution.\n if (!travelling.has(box.element)) box.element.style.translate = `0 ${displacement + removedBefore}px`\n removedBefore += (box.height + box.marginTop) * progress\n } else removedBefore -= (box.height - box.fromHeight + box.marginTop - box.fromMarginTop) * progress\n }\n if (linear < 1) {\n frameRequest = requestAnimationFrame(tick)\n return\n }\n settle(cancelled)\n }\n if (reduced) tick(0)\n else frameRequest = requestAnimationFrame(tick)\n return true\n }\n\n function foldActive(): boolean { return folding > 0 }\n\n function onFoldIdle(listener: () => void): () => void {\n if (folding === 0) listener()\n else foldIdleListeners.add(listener)\n return () => { foldIdleListeners.delete(listener) }\n }\n\n function flushBatch(): void {\n batchScheduled = false\n // Rows that change during a batch are held until it settles, which flushes again.\n if (batch) return\n const current = [...boxes.values()].some(box => box.closing) ? driver() : null\n if (current !== null && runBatch(current)) return\n const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches\n // Without a batch, a held closing row finishes at once and a held revealing row starts its own transition.\n for (const box of [...boxes.values()]) {\n if (reduced || (box.held && box.closing)) box.finish()\n else if (box.held) box.release()\n }\n }\n\n function scheduleBatch(): void {\n if (batchScheduled) return\n batchScheduled = true\n // After the whole commit's collapses and reveals have started, before any box changes size.\n const epoch = clearEpoch\n queueMicrotask(() => { if (epoch === clearEpoch) flushBatch() })\n }\n\n function foldStarted(): void {\n folding += 1\n if (folding !== 1 || anchoringDisabled) return\n anchoringDisabled = true\n foldingChanged(true)\n }\n\n function foldEnded(): void {\n folding = Math.max(0, folding - 1)\n if (folding === 0 && !settling) notifyIdle()\n }\n\n function notifyIdle(): void {\n if (anchoringDisabled) {\n anchoringDisabled = false\n foldingChanged(false)\n }\n const listeners = [...foldIdleListeners]\n foldIdleListeners.clear()\n for (const listener of listeners) listener()\n }\n\n function clearMotion(\n element: HTMLElement,\n onEnd: (event: TransitionEvent) => void,\n timer: ReturnType<typeof setTimeout> | undefined,\n ): void {\n element.removeEventListener('transitionend', onEnd)\n clearTimeout(timer)\n running.delete(element)\n boxes.delete(element)\n const { style } = element\n style.height = ''\n style.marginTop = ''\n style.opacity = ''\n style.overflow = ''\n style.transition = ''\n style.translate = ''\n delete element.dataset.chatMotion\n }\n\n function cancelMotion(element: HTMLElement): void {\n running.get(element)?.()\n cancelEmptyBatch?.()\n }\n\n function collapse(element: HTMLElement, done: () => void): void {\n cancelMotion(element)\n const height = element.offsetHeight\n const marginTop = Number.parseFloat(getComputedStyle(element).marginTop) || 0\n if (height === 0 && marginTop === 0) {\n done()\n return\n }\n const { style } = element\n // A running batch owns the scrollport; a row closing now keeps its size until the next batch drives it.\n const held = batch\n element.dataset.chatMotion = 'collapse'\n foldStarted()\n scheduleBatch()\n style.transition = 'none'\n style.overflow = 'hidden'\n style.height = `${height}px`\n style.marginTop = `${marginTop}px`\n if (!held) {\n void element.offsetHeight\n style.transition = `opacity ${FADE_OUT_MS}ms ${EASING}, `\n + `height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`\n style.opacity = '0'\n style.height = '0px'\n style.marginTop = '0px'\n }\n\n // The hidden state must land before fold-idle listeners measure the flow.\n const finish = (): void => {\n if (running.get(element) !== cancel) return\n clearMotion(element, onEnd, timer)\n done()\n foldEnded()\n }\n const onEnd = (event: TransitionEvent): void => {\n if (event.target === element && event.propertyName === 'height') finish()\n }\n const timer = held ? undefined : setTimeout(finish, CLOSE_DELAY_MS + CLOSE_MS + SETTLE_SLACK_MS)\n const cancel = (): void => {\n clearMotion(element, onEnd, timer)\n foldEnded()\n }\n if (!held) element.addEventListener('transitionend', onEnd)\n running.set(element, cancel)\n boxes.set(element, { element, height, marginTop, fromHeight: height, fromMarginTop: marginTop, closing: true, held, finish,\n release: () => {},\n take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } })\n }\n\n function reveal(element: HTMLElement): void {\n cancelMotion(element)\n const height = element.offsetHeight\n if (height === 0) return\n const marginTop = Number.parseFloat(getComputedStyle(element).marginTop) || 0\n scheduleBatch()\n const { style } = element\n element.dataset.chatMotion = 'reveal'\n style.transition = 'none'\n style.overflow = 'hidden'\n style.opacity = '0'\n style.height = '0px'\n style.marginTop = '0px'\n const finish = (): void => {\n if (running.get(element) !== finish) return\n clearMotion(element, onEnd, timer)\n }\n const onEnd = (event: TransitionEvent): void => {\n if (event.target === element && event.propertyName === 'height') finish()\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n const startTransition = (): void => {\n void element.offsetHeight\n style.transition = `height ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, margin-top ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms, `\n + `opacity ${CLOSE_MS}ms ${EASING} ${CLOSE_DELAY_MS}ms`\n style.height = `${height}px`\n style.marginTop = `${marginTop}px`\n style.opacity = '1'\n timer = setTimeout(finish, CLOSE_DELAY_MS + CLOSE_MS + SETTLE_SLACK_MS)\n element.addEventListener('transitionend', onEnd)\n }\n // A running batch owns the scrollport; a row revealed now waits at zero size until the next flush.\n const held = batch\n if (!held) startTransition()\n running.set(element, finish)\n const box: OwnedBox = { element, height, marginTop, fromHeight: 0, fromMarginTop: 0, closing: false, held, finish,\n release: () => {\n box.held = false\n startTransition()\n },\n take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } }\n boxes.set(element, box)\n }\n\n function clear(): void {\n clearEpoch++\n batchScheduled = false\n batch = false\n cancelled = false\n if (frameRequest !== null) cancelAnimationFrame(frameRequest)\n frameRequest = null\n batchCleanup?.()\n batchCleanup = null\n cancelEmptyBatch = null\n foldIdleListeners.clear()\n for (const cancel of [...running.values()]) cancel()\n }\n\n function hideNow(element: HTMLElement, commit: () => void): void {\n beforeInstantHide?.(element)\n commit()\n }\n\n return {\n collapse, reveal, cancelMotion, foldActive, onFoldIdle, cancelInput, resumeInput, clear, hideNow,\n active: () => running.size > 0 || batchScheduled || batch || settling,\n inputActive: () => batch || (batchScheduled && [...boxes.values()].some(box => box.closing && batchMember(box))),\n }\n}\n\nfunction useFlowTransition(motion: FlowMotionRows | undefined, grow: boolean): HiddenTransition | undefined {\n const current = useRef<HTMLElement | null>(null)\n useLayoutEffect(() => () => {\n if (current.current !== null) motion?.cancelMotion(current.current)\n current.current = null\n }, [motion])\n const transition = useCallback<HiddenTransition>((element, hidden, commit) => {\n const mounted = current.current === element\n const animate = mounted && motionEnabled(element)\n current.current = element\n if (hidden) {\n if (hiddenOrCollapsing(element)) return\n if (mounted && element.closest(MOTION_SCOPE) !== null && motion !== undefined) motion.collapse(element, commit)\n else if (mounted && motion?.hideNow !== undefined) motion.hideNow(element, commit)\n else commit()\n return\n }\n motion?.cancelMotion(element)\n const wasHidden = element.hasAttribute('hidden')\n commit()\n if (wasHidden && animate && grow) motion?.reveal(element)\n }, [motion, grow])\n return motion === undefined ? undefined : transition\n}\n\n/**\n * Apply searchable hiding with the containing Chat viewport's optional fold animation.\n * @param hidden - desired visibility.\n * @param reveal - browser-find and focus-protection callback.\n * @param motion - owning viewport's row callbacks; undefined applies visibility synchronously.\n * @returns the stable subtree ref.\n */\nexport function useFlowHidden(hidden: boolean, reveal: () => void, motion: FlowMotionRows | undefined): RefObject<HTMLDivElement> {\n return useSearchableHidden(hidden, reveal, useFlowTransition(motion, false))\n}\n\n/**\n * Toggle a plain hidden attribute on the fold clock, growing newly revealed headers.\n * @param ref - element whose visibility follows hidden.\n * @param hidden - desired hidden state.\n * @param motion - containing viewport's row callbacks.\n */\nexport function useMotionHidden(ref: RefObject<HTMLElement | null>, hidden: boolean, motion: FlowMotionRows): void {\n const transition = useFlowTransition(motion, true)\n useLayoutEffect(() => {\n const element = ref.current\n if (element === null) return\n transition?.(element, hidden, () => {\n if (hidden) element.setAttribute('hidden', '')\n else element.removeAttribute('hidden')\n })\n }, [ref, hidden, transition])\n}\n","/** Turn-aware DOM scrolling and geometry, without history-loading or follow policy. */\nimport { useLayoutEffect, useRef, useState, type RefObject } from 'react'\nimport type { ChatScrollPosition } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { createFlowMotion, type InputFoldBox, type InputFoldDriver } from './flow-motion.ts'\nimport { scrollMetrics, ScrollFollow, type ViewportMetrics } from './use-scroll-follow.ts'\nexport type { ViewportMetrics } from './use-scroll-follow.ts'\n\n/** Scroll geometry attributed against the last acknowledged position. */\nexport interface ViewportScroll {\n readonly metrics: ViewportMetrics\n readonly movedByReader: boolean\n}\n\n/** Actual clamped scroll result, including any known semantic anchor and turn. */\nexport interface ViewportLanding {\n readonly metrics: ViewportMetrics\n readonly position: ChatScrollPosition | null\n readonly turn: number | null\n}\n\ninterface ViewportEvents {\n scroll: (event: ViewportScroll) => void\n scrollEnd: (outer: boolean) => void\n resize: () => void\n interact: () => void\n /** Any reading gesture, before paging ownership is consulted. */\n intent?: () => void\n /** Recheck a prepared history page after an input or transition settles. */\n history?: () => void\n}\n\ninterface ViewportElements {\n readonly list: HTMLElement\n readonly column: HTMLElement\n readonly scroller: HTMLElement\n readonly composer: HTMLElement | null\n /** Room below closing rows, retained until scrolling or content growth makes it unnecessary. */\n readonly spacer: HTMLElement | null\n}\n\n/** Reading policy that fold batches consult and report tail landings to. */\nexport interface FoldReader {\n /** Follow intent at batch start selects the tail landing; tail landings commit it. */\n readonly follow: ScrollFollow\n /** @param landing - the actual geometry after a batch landed at the tail. */\n readonly landedAtTail: (landing: ViewportLanding) => void\n /** @returns whether reader movement awaits sampling; until then follow intent is undecided. */\n readonly pending: () => boolean\n}\n\n/** A top-level row a closing shrink may keep still, measured before the rows close. */\ninterface ShrinkAnchor {\n readonly element: HTMLElement\n /** Distance from the row's top to the end of the content last painted. */\n readonly fromEnd: number\n}\n\n/** Layout measured at the first instant hide of a commit; only the size observation of that frame uses it. */\ninterface ClosingLayout {\n /** The first visible row, then the rows above it within one scrollport. */\n readonly rows: readonly ShrinkAnchor[]\n /** Content height without fold room when the rows were measured. */\n readonly content: number\n}\n\ninterface PagingPosition {\n readonly row: HTMLElement\n readonly position: ChatScrollPosition\n readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null\n}\n\nconst READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const\nconst SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '])\n\n/** Owns one Chat scrollport's DOM operations, event listeners, and size observer. */\nexport class ChatViewport {\n private elements: ViewportElements | null = null\n private observer: ResizeObserver | null = null\n private events: ViewportEvents | null = null\n private turns: ReturnType<ChatSnapshot['navigation']['items']> = []\n private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null }\n private paging: PagingPosition | null = null\n private historyPrepend: PagingPosition | null = null\n private reader: FoldReader | null = null\n private historyEdge: HTMLElement | null = null\n private historyHeight = 0\n private historyScrolling = new Set<EventTarget>()\n private historyPointer = false\n private historyTouch = false\n /** Rows measured before an instant close; see {@link ChatViewport.keepAboveClosing}. */\n private closing: ClosingLayout | null = null\n /** Discards a closing measurement that no size observation consumed by the end of its frame. */\n private closingFrame: number | null = null\n /** Content height without fold room at the latest size observation: the content that frame painted. */\n private settledContent = 0\n /** The pending or running fold batch lands at the tail. */\n private tailRequested = false\n /** The tail request came from the reader's own input rather than from a content change. */\n private tailInput = false\n /** Switches the running batch to a tail landing; null while no batch runs. */\n private retarget: (() => void) | null = null\n /** Transition state and row callbacks owned by this viewport's attachment. */\n readonly motion = createFlowMotion(\n () => this.foldDriver(),\n (active) => {\n if (this.elements !== null) this.elements.scroller.style.overflowAnchor = active ? 'none' : ''\n },\n (element) => { this.measureClosing(element) },\n )\n\n /**\n * Bind to the containing scrollport and observe content and viewport sizes.\n * @param list - Chat root inside an optional shared conversation scrollport.\n * @param column - ordered outer Node/Group boxes; its size changes invalidate cached landings.\n */\n attach(list: HTMLElement, column: HTMLElement): void {\n this.detach()\n const scroller = list.closest<HTMLElement>('[data-conversation-scroll]') ?? list\n const composer = scroller.querySelector<HTMLElement>('[data-composer-seat]')\n const spacer = list.querySelector<HTMLElement>('[data-chat-turn-spacer]')\n const elements = { list, column, scroller, composer, spacer }\n this.elements = elements\n if (spacer !== null) spacer.style.height = ''\n scroller.addEventListener('scroll', this.onHistoryScroll, { passive: true, capture: true })\n scroller.addEventListener('pointerdown', this.onHistoryPointerDown, { passive: true, capture: true })\n scroller.addEventListener('touchstart', this.onHistoryTouch, { passive: true, capture: true })\n for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) {\n scroller.ownerDocument.addEventListener(type, this.onHistoryRelease, true)\n }\n scroller.addEventListener('scroll', this.onScroll, { passive: true })\n scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true })\n for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true })\n if (typeof ResizeObserver !== 'undefined') {\n this.observer = new ResizeObserver((entries) => {\n if (this.elements !== elements) return\n // Read while layout is still clean, before this callback writes room or scroll positions. Those writes\n // leave the content height unchanged, so it is also the content this frame paints.\n if (entries.some(entry => entry.target === elements.scroller)) this.historyHeight = elements.scroller.clientHeight\n this.settledContent = elements.scroller.scrollHeight - this.spacerHeight()\n this.keepAboveClosing()\n this.reclaimBelow()\n this.invalidate()\n this.pruneHistoryScrolling()\n this.events?.resize()\n })\n this.observer.observe(column)\n this.observer.observe(scroller)\n if (composer !== null) this.observer.observe(composer)\n }\n }\n\n /** Disconnect DOM resources and clear observations for the detached view. */\n detach(): void {\n this.historyPrepend = null\n this.stopPreserving()\n this.motion.clear()\n if (this.elements !== null) this.elements.scroller.style.overflowAnchor = ''\n this.dropClosing()\n const scroller = this.elements?.scroller\n scroller?.removeEventListener('scroll', this.onHistoryScroll, true)\n scroller?.removeEventListener('pointerdown', this.onHistoryPointerDown, true)\n scroller?.removeEventListener('touchstart', this.onHistoryTouch, true)\n for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) {\n scroller?.ownerDocument.removeEventListener(type, this.onHistoryRelease, true)\n }\n this.historyHeight = 0\n this.historyScrolling.clear()\n this.historyPointer = false\n this.historyTouch = false\n this.elements?.scroller.removeEventListener('scroll', this.onScroll)\n this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true)\n for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true)\n this.observer?.disconnect()\n this.observer = null\n this.elements = null\n this.events = null\n this.tailRequested = false\n this.tailInput = false\n this.retarget = null\n this.turns = []\n this.observation = { top: 0, landing: null }\n }\n\n /**\n * Connect business policy without changing DOM listener ownership.\n * @param events - business handlers for scroll and layout changes.\n * @returns a disposer that disconnects only these handlers.\n */\n connect(events: ViewportEvents): () => void {\n this.events = events\n return () => { if (this.events === events) this.events = null }\n }\n\n /**\n * Adopt the loaded turn anchors without querying the DOM.\n * @param turns - ordered loaded turns from the committed Chat snapshot.\n */\n updateTurns(turns: ReturnType<ChatSnapshot['navigation']['items']>): void {\n this.turns = turns\n }\n\n /**\n * Resolve the tail from the committed turn index.\n * @returns the latest loaded turn, or null for an empty window.\n */\n get latestTurn(): number | null {\n return this.turns.at(-1)?.turn ?? null\n }\n\n /** Discard geometry-dependent landing knowledge while retaining scroll attribution. */\n invalidate(): void {\n this.observation.landing = null\n }\n\n private spacerHeight(): number {\n const spacer = this.elements?.spacer\n return spacer == null ? 0 : Number.parseFloat(spacer.style.height) || 0\n }\n\n private setSpacer(height: number): void {\n const spacer = this.elements?.spacer\n if (spacer == null) return\n const next = height <= 0 ? '' : `${Math.ceil(height)}px`\n if (spacer.style.height !== next) spacer.style.height = next\n }\n\n /**\n * Connect the reading policy that fold batches consult.\n * @param reader - follow intent and the tail-landing commit.\n * @returns a disposer that disconnects only this reader.\n */\n bindReader(reader: FoldReader): () => void {\n this.reader = reader\n return () => { if (this.reader === reader) this.reader = null }\n }\n\n /**\n * Land the pending or running fold batch at the tail instead of starting a separate scroll.\n * @param follow - follow controller whose native animation yields to the batch.\n * @param input - whether the reader's own input requests the landing; a content change, such as a Turn\n * ending, requests it in place of the immediate follow.\n * @returns whether a fold owns the tail movement.\n */\n followInputFold(follow: ScrollFollow, input: boolean): boolean {\n // Rows still closing on CSS transitions after a batch have no batch to consume the request.\n if (this.elements === null || this.reader === null || !this.motion.inputActive()) return false\n this.interruptFollow(follow)\n this.tailRequested = true\n this.tailInput ||= input\n this.retarget?.()\n return true\n }\n\n /**\n * Drive one fold batch on its frame clock. A tail landing ends at the floor, never above the reader's\n * compensated position; a reader landing keeps the visible content still. Both install only the room\n * the landing lacks.\n * @returns the batch driver, or null while detached or without a reading policy.\n */\n private foldDriver(): InputFoldDriver | null {\n const elements = this.elements\n const reader = this.reader\n if (elements === null || reader === null) return null\n const { follow } = reader\n let tail = false\n let start = 0\n let base = 0\n let target = 0\n let removed = 0\n let growth = 0\n let initialHeight = 0\n let finalRoom = 0\n let previousColumnHeight = 0\n let previousProgress = 0\n let segmentProgress = 0\n let segmentTop = 0\n let written = 0\n const closing: InputFoldBox[] = []\n const travelling = new Set<HTMLElement>()\n // A visible row outside the batch measures spacing that snaps when the batch starts and ends.\n let reference: HTMLElement | null = null\n let referenceTop = 0\n let viewportTop = 0\n const screenTop = (element: HTMLElement): number => element.getBoundingClientRect().top - viewportTop\n const aim = (): void => {\n const finalHeight = initialHeight - removed + growth\n const height = elements.scroller.clientHeight\n target = tail ? Math.max(base, finalHeight - height, 0) : base\n finalRoom = target === 0 ? 0 : Math.max(0, target + height - finalHeight)\n }\n const restart = (): void => {\n segmentTop = elements.scroller.scrollTop\n segmentProgress = previousProgress\n }\n const automatic = (cancelled: boolean): boolean => !(cancelled && tail)\n const position = (progress: number, cancelled: boolean): number => {\n if (!automatic(cancelled)) return elements.scroller.scrollTop\n const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress)\n return segmentTop + (target - segmentTop) * remaining\n }\n const room = (top: number, progress: number, cancelled: boolean): number => Math.max(\n automatic(cancelled) ? finalRoom : 0,\n top + elements.scroller.clientHeight - (initialHeight + (growth - removed) * progress),\n )\n return {\n begin: (boxes) => {\n // Own input lands at the tail; otherwise an unsampled reading movement outranks follow intent.\n tail = this.tailRequested || (follow.active && !reader.pending())\n const input = this.tailInput\n this.tailRequested = false\n this.tailInput = false\n viewportTop = elements.scroller.getBoundingClientRect().top\n start = elements.scroller.scrollTop\n const originalRoom = this.spacerHeight()\n initialHeight = Math.max(elements.column.offsetHeight, elements.scroller.scrollHeight - originalRoom)\n if (tail && !input) {\n // The batch replaces the immediate follow of a reader pinned to the tail, following content that\n // overflows with no fold room: content that grew outside the batch since that paint, such as a Turn's\n // duration control, is taken before the first frame as following takes streaming growth, so the\n // batch only animates its own rows.\n const pinned = originalRoom === 0 && this.settledContent > elements.scroller.clientHeight\n && follow.active && !reader.pending() && !follow.animating\n const external = elements.scroller.scrollHeight - originalRoom - this.settledContent\n if (external > 0.5 && pinned) {\n elements.scroller.scrollTop = start + external\n start = elements.scroller.scrollTop\n this.observation = { top: start, landing: null }\n }\n }\n let above = 0\n const below: HTMLElement[] = []\n for (const box of boxes) {\n const amount = box.height + box.marginTop\n const top = box.element.getBoundingClientRect().top - box.marginTop\n if (box.closing) {\n removed += amount\n above += Math.max(0, Math.min(amount, viewportTop - top))\n if (top >= viewportTop) below.push(box.element)\n closing.push(box)\n } else {\n growth += amount\n if (top < viewportTop) above -= amount\n }\n }\n if (!tail) reference = this.readingReference()\n const referenceBefore = reference === null ? 0 : screenTop(reference)\n elements.column.dataset.inputFold = ''\n if (reference !== null) {\n referenceTop = screenTop(reference)\n above -= referenceTop - referenceBefore\n }\n base = Math.max(0, start - above)\n segmentTop = start\n written = start\n previousColumnHeight = elements.column.offsetHeight\n aim()\n // This reserve only prevents an intermediate clamp; the final frame installs the exact deficit.\n this.setSpacer(Math.max(originalRoom, finalRoom, removed))\n if (tail) follow.setFollowing(true)\n // A newer tail request also takes over a batch whose target a reading gesture cancelled.\n this.retarget = () => {\n tail = true\n follow.setFollowing(true)\n this.motion.resumeInput()\n aim()\n restart()\n if (target <= segmentTop) return\n for (const box of closing) {\n // A box fading in place carries a visual translate; its layout position excludes it.\n const shift = Number.parseFloat(box.element.style.translate.split(' ')[1] ?? '') || 0\n if (box.element.getBoundingClientRect().top - shift - box.marginTop >= viewportTop) travelling.add(box.element)\n }\n }\n // Scrolling forward past closing rows shows them shrinking; faded rows would leave their space empty.\n if (tail && target > start) for (const element of below) travelling.add(element)\n return travelling\n },\n prepare: (progress, cancelled) => {\n if (this.elements !== elements) return\n if (!tail) {\n // Reader scrolling between frames moves the reading position the batch keeps still.\n const drift = elements.scroller.scrollTop - written\n if (Math.abs(drift) > 0.5) {\n base = Math.max(0, base + drift)\n segmentTop += drift\n // The reference moves on screen with the reader's scroll; only layout changes are corrected.\n referenceTop -= drift\n aim()\n }\n }\n const added = elements.column.offsetHeight - previousColumnHeight\n if (added !== 0) {\n initialHeight += added\n aim()\n restart()\n }\n const top = position(progress, cancelled)\n // Growing the room before shrinking boxes avoids a native clamp between writes.\n this.setSpacer(Math.max(this.spacerHeight(), room(top, progress, cancelled)))\n },\n frame: (progress, cancelled) => {\n if (this.elements !== elements) return 0\n const top = position(progress, cancelled)\n elements.scroller.scrollTop = top\n this.setSpacer(room(top, progress, cancelled))\n written = elements.scroller.scrollTop\n // Earlier frames keep the reference still; only its final position is compared at finish.\n if (reference !== null && progress === 1) referenceTop = screenTop(reference)\n if (automatic(cancelled)) this.observation = { top: written, landing: null }\n previousColumnHeight = elements.column.offsetHeight\n previousProgress = progress\n return written - start\n },\n finish: (cancelled) => {\n this.retarget = null\n this.tailRequested = false\n this.tailInput = false\n if (this.elements !== elements) return\n // Commit the final sibling margins while their fold transition override still applies.\n void elements.column.offsetHeight\n delete elements.column.dataset.inputFold\n if (!tail || cancelled) {\n if (!tail && reference?.isConnected === true && reference.closest('[hidden]') === null) {\n // Committing the hidden rows settles their neighbours' spacing; keep the reference still.\n const shift = screenTop(reference) - referenceTop\n if (Math.abs(shift) > 0.5) {\n const top = elements.scroller.scrollTop + shift\n const content = elements.scroller.scrollHeight - this.spacerHeight()\n this.setSpacer(Math.max(this.spacerHeight(), top + elements.scroller.clientHeight - content))\n elements.scroller.scrollTop = top\n }\n }\n const metrics = scrollMetrics(elements.scroller)\n const height = elements.scroller.scrollHeight - this.spacerHeight()\n this.setSpacer(metrics.top === 0 ? 0 : Math.max(0, metrics.top + metrics.height - height))\n if (tail) this.invalidate()\n else this.observation = { top: elements.scroller.scrollTop, landing: null }\n return\n }\n // The estimate can differ from the committed layout, for example settled sibling spacing.\n // Land on the actual content: never above the target, and at the real floor when content reaches past it.\n const content = elements.scroller.scrollHeight - this.spacerHeight()\n const clientHeight = elements.scroller.clientHeight\n const top = Math.max(target, content - clientHeight, 0)\n this.setSpacer(top === 0 ? 0 : Math.max(0, top + clientHeight - content))\n elements.scroller.scrollTop = top\n const metrics = scrollMetrics(elements.scroller)\n const landing = { metrics, position: null, turn: this.latestTurn }\n this.observation = { top: metrics.top, landing }\n reader.landedAtTail(landing)\n },\n }\n }\n\n /**\n * Find the first visible top-level row at or below the scrollport top that holds no batch box.\n * Binary search over the ordered top-level rows reads O(log n) boxes.\n * @returns the reference row, or null when every visible row folds.\n */\n private readingReference(): HTMLElement | null {\n const elements = this.elements\n if (elements === null) return null\n const viewport = elements.scroller.getBoundingClientRect()\n // Slot anchors use display:contents: their children are the top-level rows.\n const rows = (elements.column.querySelector(':scope > [data-slot=\"conversation.chat.flow\"]') ?? elements.column).children\n let low = 0\n let high = rows.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if ((rows[middle] as Element).getBoundingClientRect().bottom > viewport.top) high = middle\n else low = middle + 1\n }\n for (let index = low; index < rows.length; index++) {\n const row = rows[index] as HTMLElement\n if (row.hasAttribute('hidden')) continue\n const rect = row.getBoundingClientRect()\n if (rect.top >= viewport.bottom) return null\n if (rect.height === 0 || rect.bottom <= viewport.top) continue\n if (row.hasAttribute('data-chat-motion') || row.querySelector('[data-chat-motion]') !== null) continue\n return row\n }\n return null\n }\n\n /**\n * Measure, before the first row of a commit closes at once, the rows a following reader's shrink keeps\n * still: the first row visible in the last painted layout, the rows after it that were on screen, and the\n * rows above it within one scrollport.\n * Rows above the closing rows keep their painted screen positions, which the commit did not move; the same\n * commit can add rows between them and the closing rows, as a Turn's duration control does, so rows from\n * the closing rows on are placed against the current end. Reads happen only when rows close, never on the\n * following path's size observations. A measurement the same frame's size observation does not use is\n * discarded after that frame.\n * @param element - the first row of this commit to close.\n */\n private measureClosing(element: HTMLElement): void {\n const elements = this.elements\n const reader = this.reader\n if (elements === null || reader === null || this.closing !== null || !element.isConnected) return\n if (!reader.follow.active || reader.follow.animating || reader.pending()) return\n if (this.paging !== null || this.motion.foldActive() || this.motion.inputActive()) return\n const scroller = elements.scroller\n const scrollHeight = scroller.scrollHeight\n const height = scroller.clientHeight\n // The commit has not moved the scroll position, so it is the painted one, within the follow threshold too.\n const painted = scroller.scrollTop + height\n const origin = scroller.getBoundingClientRect().top - scroller.scrollTop\n const rows = (elements.column.querySelector(':scope > [data-slot=\"conversation.chat.flow\"]') ?? elements.column).children\n // End is the content end each row is placed against: painted for rows above the closing rows.\n const end = (row: Element): number => row !== element && !row.contains(element)\n && (element.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING) !== 0 ? painted : scrollHeight\n const screen = (row: Element, offset: number): number => offset - origin - (end(row) - height)\n let low = 0\n let high = rows.length\n while (low < high) {\n const middle = (low + high) >>> 1\n const row = rows[middle] as Element\n if (screen(row, row.getBoundingClientRect().bottom) > 0) high = middle\n else low = middle + 1\n }\n let first = -1\n for (let index = low; index < rows.length && first < 0; index++) {\n const row = rows[index] as HTMLElement\n const rect = row.getBoundingClientRect()\n if (screen(row, rect.top) >= height) break\n if (rect.height > 0 && !row.hasAttribute('hidden')) first = index\n }\n if (first < 0) return\n const anchors: ShrinkAnchor[] = []\n const add = (row: HTMLElement, rect: DOMRect): void => {\n if (rect.height > 0 && !row.hasAttribute('hidden')) anchors.push({ element: row, fromEnd: end(row) - (rect.top - origin) })\n }\n add(rows[first] as HTMLElement, (rows[first] as HTMLElement).getBoundingClientRect())\n // When the first visible row closes, the reader's eyes are on the rows that follow it on screen.\n for (let index = first + 1; index < rows.length; index++) {\n const row = rows[index] as HTMLElement\n const rect = row.getBoundingClientRect()\n if (screen(row, rect.top) >= height) break\n add(row, rect)\n }\n for (let index = first - 1; index >= 0; index--) {\n const row = rows[index] as HTMLElement\n const rect = row.getBoundingClientRect()\n if (screen(row, rect.bottom) <= -height) break\n add(row, rect)\n }\n this.closing = { rows: anchors, content: scrollHeight - this.spacerHeight() }\n if (typeof requestAnimationFrame === 'function') {\n // This frame's size observation runs before the second callback; nothing later may use the measurement.\n this.closingFrame = requestAnimationFrame(() => {\n this.closingFrame = requestAnimationFrame(() => {\n this.closingFrame = null\n this.closing = null\n })\n })\n }\n }\n\n private dropClosing(): void {\n this.closing = null\n if (this.closingFrame !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.closingFrame)\n this.closingFrame = null\n }\n\n /**\n * Keep a following reader's content still after rows closed at once, for example work details at Turn\n * completion: the first visible row keeps its screen position, or, when it closed, the first surviving row\n * that followed it on screen, else the nearest surviving row above it. Room below fills the gap, at most half\n * the scrollport; beyond that the content end stops at the scrollport's middle. Called from the size\n * observation, after layout and before paint; only the observation of the frame that closed the rows uses\n * the measurement, and only while the reader still follows the tail with no fold batch, native animation,\n * unsampled movement, or paging writing positions.\n */\n private keepAboveClosing(): void {\n const closing = this.closing\n const elements = this.elements\n const reader = this.reader\n if (closing === null) return\n this.dropClosing()\n if (elements === null || reader === null || !reader.follow.active || reader.follow.animating || reader.pending()) return\n if (this.paging !== null || this.motion.foldActive() || this.motion.inputActive()) return\n const scroller = elements.scroller\n const content = scroller.scrollHeight - this.spacerHeight()\n // Growth in the same commit can outweigh the closed rows; nothing then shrank to compensate.\n if (content >= closing.content - 0.5) return\n const height = scroller.clientHeight\n const origin = scroller.getBoundingClientRect().top - scroller.scrollTop\n const cap = height / 2\n let top = content + cap - height\n for (const row of closing.rows) {\n if (!row.element.isConnected || row.element.closest('[hidden]') !== null) continue\n const rect = row.element.getBoundingClientRect()\n if (rect.height === 0) continue\n top = rect.top - origin - (height - row.fromEnd)\n break\n }\n if (top + height - content > cap) top = content + cap - height\n top = Math.max(0, top)\n this.setSpacer(top === 0 ? 0 : Math.max(0, top + height - content))\n if (scroller.scrollTop !== top) scroller.scrollTop = top\n const metrics = scrollMetrics(scroller)\n this.observation = { top: metrics.top, landing: { metrics, position: null, turn: this.latestTurn } }\n }\n\n /** Clear fold reservations after a display-mode change, allowing the scroll range to shrink. */\n resetBelow(): void {\n this.dropClosing()\n this.setSpacer(0)\n this.invalidate()\n }\n\n /**\n * Give reserved room back after acknowledged scrolling or content growth without clamping the reader.\n * Holds still during folds and unsampled movement; following includes the room that remains.\n */\n reclaimBelow(): void {\n const elements = this.elements\n if (elements === null || elements.spacer === null) return\n const current = this.spacerHeight()\n if (current === 0 || this.motion.foldActive()) return\n const scroll = this.readScroll()\n // Trimming the range before sampling could misclassify a reader's move as a layout clamp.\n if (scroll === null || scroll.movedByReader) return\n const floorWithoutSpacer = scroll.metrics.floor - current\n this.setSpacer(Math.min(current, Math.max(0, scroll.metrics.top - floorWithoutSpacer)))\n }\n\n /**\n * Stop an outstanding native follow animation at its current position before a reading gesture.\n * @param follow - follow controller bound to this scrollport.\n */\n interruptFollow(follow: ScrollFollow): void {\n if (!follow.animating) return\n const metrics = this.metrics()\n if (metrics === null || this.elements === null) return\n follow.interrupt(this.elements.scroller, metrics)\n this.observation = { top: metrics.top, landing: null }\n }\n\n /**\n * Accept a sampled reader position without retaining a known landing.\n * @param metrics - settled reader position used as the next attribution baseline.\n */\n acknowledge(metrics: ViewportMetrics): void {\n this.observation = { top: metrics.top, landing: null }\n this.reclaimBelow()\n }\n\n /**\n * Compare the current scroll geometry with the last acknowledged position.\n * @returns current metrics and movement attribution, or null while detached.\n */\n readScroll(): ViewportScroll | null {\n const metrics = this.metrics()\n if (metrics === null) return null\n return {\n metrics,\n movedByReader: Math.abs(metrics.top - Math.min(this.observation.top, metrics.floor)) > 0.5,\n }\n }\n\n private metrics(): ViewportMetrics | null {\n const scroller = this.elements?.scroller\n if (scroller === undefined) return null\n return scrollMetrics(scroller)\n }\n\n private anchor(key: string, identity: 'position' | 'node' = 'position'): HTMLElement | null {\n if (this.elements === null) return null\n // Reading anchors name exact parts; Turn navigation names the original Node.\n let nodePart: HTMLElement | null = null\n for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-anchor-key]:not([hidden]):not([hidden] *)')) {\n if (row.dataset.chatAnchorKey === key || (identity === 'node' && row.dataset.chatNodeKey === key)) return row\n if (nodePart === null && row.dataset.chatNodeKey === key) nodePart = row\n }\n return nodePart\n }\n\n /**\n * Capture visible transcript content, excluding Turn controls that relocate when history expands.\n * @returns a visible semantic anchor, or null when no anchor can be resolved.\n */\n capturePosition(): ChatScrollPosition | null {\n const elements = this.elements\n if (elements === null) return null\n const { list, scroller, composer } = elements\n const viewport = scroller.getBoundingClientRect()\n const bottom = composer?.getBoundingClientRect().top ?? viewport.bottom\n let anchor: HTMLElement | null = null\n if (typeof document.elementsFromPoint === 'function' && bottom > viewport.top) {\n const content = list.getBoundingClientRect()\n const left = Math.max(viewport.left, content.left)\n const right = Math.min(viewport.right, content.right)\n for (const element of document.elementsFromPoint(left + Math.max(0, right - left) / 2, viewport.top + 1)) {\n const row = element instanceof HTMLElement ? element.closest<HTMLElement>('[data-chat-anchor-key]') : null\n if (row !== null && row.dataset.chatFlowKind !== 'turn-process' && list.contains(row)) {\n // An open group's header stays put while older members enter above its body content.\n anchor = row.dataset.chatGroupKey === undefined ? row\n : row.querySelector<HTMLElement>('[data-step-process-content] > [data-chat-anchor-key]:not(:empty):not([hidden]):not([hidden] *)') ?? row\n break\n }\n }\n }\n if (anchor === null) {\n const rows = list.querySelectorAll<HTMLElement>(\n '[data-chat-flow-key]:not([data-chat-group-key]):not([data-chat-flow-kind=\"turn-process\"])'\n + ':not(:empty):not([hidden]):not([hidden] *)',\n )\n let low = 0\n let high = rows.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if (rows.item(middle).getBoundingClientRect().bottom > viewport.top) high = middle\n else low = middle + 1\n }\n const row = rows[low]\n anchor = row !== undefined && row.getBoundingClientRect().top < bottom ? row : rows[0] ?? null\n }\n const key = anchor?.dataset.chatAnchorKey\n return anchor === null || key === undefined ? null : {\n anchorKey: key,\n anchorTop: anchor.getBoundingClientRect().top - viewport.top,\n scrollTop: scroller.scrollTop,\n }\n }\n\n /**\n * Approximate the active Turn by binary-searching outer Node/Group boxes.\n * Gaps retain the last visited Turn candidate, not necessarily the immediate predecessor.\n * A known landing bypasses measurement while its position is unchanged.\n * @param metrics - reusable scroll metrics; omitted callers request a fresh read.\n * @returns the Turn near the reading line, or null while detached or empty.\n */\n readVisibleTurn(metrics = this.metrics()): number | null {\n const knownTurn = this.observation.landing?.turn\n if (knownTurn != null && metrics?.top === this.observation.top) return knownTurn\n const elements = this.elements\n const first = this.turns[0]\n if (elements === null || metrics === null || first === undefined) return null\n const line = elements.scroller.getBoundingClientRect().top + Math.min(96, metrics.height * 0.2)\n // Slot anchors use display:contents: measure their rows, not the anchor's empty box.\n const rows = (elements.column.querySelector(':scope > [data-slot=\"conversation.chat.flow\"]') ?? elements.column).children\n let low = 0\n let high = rows.length\n let reading = first.turn\n while (low < high) {\n const middle = (low + high) >>> 1\n const row = rows[middle] as Element\n if (row.getBoundingClientRect().top > line) high = middle\n else {\n const value = row.getAttribute('data-chat-turn')\n const turn = value === null ? NaN : Number(value)\n if (Number.isSafeInteger(turn)) reading = turn\n low = middle + 1\n }\n }\n return reading\n }\n\n /**\n * Align a known loaded turn and return its actual clamped position.\n * A split Node anchor selects its first visible part.\n * @param turn - loaded turn to align below the scrollport's top edge.\n * @returns the actual landing, or null when its anchor is unavailable.\n */\n scrollToTurn(turn: number): ViewportLanding | null {\n const item = this.turns.find(candidate => candidate.turn === turn)\n if (item === undefined) return null\n const row = this.anchor(item.anchorKey, 'node')\n return row === null ? null : this.align(row, 24, turn)\n }\n\n /**\n * Align the nearest available fallback for an unavailable turn anchor.\n * @param turn - minimum turn number for a mounted fallback row.\n * @returns the fallback landing, or null when no eligible row exists.\n */\n scrollToTurnAtOrAfter(turn: number): ViewportLanding | null {\n if (this.elements === null) return null\n for (const row of this.elements.list.querySelectorAll<HTMLElement>('[data-chat-turn]:not([hidden]):not([hidden] *)')) {\n const candidate = Number(row.dataset.chatTurn)\n if (Number.isSafeInteger(candidate) && candidate >= turn) return this.align(row, 24, candidate)\n }\n return null\n }\n\n /**\n * Restore a semantic anchor with a raw-position fallback.\n * @param position - semantic scroll memory; raw top is used only if its row is absent.\n * @returns the actual landing, or null while detached.\n */\n restore(position: ChatScrollPosition): ViewportLanding | null {\n const row = this.anchor(position.anchorKey)\n if (row !== null) return this.align(row, position.anchorTop, null)\n const metrics = this.metrics()\n return metrics === null ? null : this.write(position.scrollTop, metrics, null)\n }\n\n /** Capture a manual paging anchor without consulting automatic-consumption blockers. */\n beginManualPaging(): void {\n if (this.elements === null) return\n if (this.elements.scroller.scrollTop <= 0.5) this.beginPaging()\n else {\n this.beginPreserving()\n if (!this.preserving) this.beginPaging()\n }\n }\n\n /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */\n beginPaging(): void {\n this.stopPreserving()\n const row = this.pagingAnchor()\n if (row !== null) this.retain(row)\n }\n\n private pagingAnchor(): HTMLElement | null {\n return this.elements?.list.querySelector<HTMLElement>(\n '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)',\n ) ?? null\n }\n\n /**\n * Retain one old row and its inner/outer offsets for paging and later content growth.\n * @param position - an explicit landing to retain; omitted callers capture the current reading position.\n */\n beginPreserving(position: ChatScrollPosition | null = this.capturePosition()): void {\n this.stopPreserving()\n if (position === null) return\n const row = this.anchor(position.anchorKey)\n if (row === null) return\n this.retain(row, position)\n }\n\n private measurePaging(row: HTMLElement, position?: ChatScrollPosition, previousGroup?: PagingPosition['group']): PagingPosition | null {\n const elements = this.elements\n const key = row.dataset.chatAnchorKey\n if (elements === null || key === undefined) return null\n const top = row.getBoundingClientRect().top\n const body = row.closest<HTMLElement>('[data-step-process-body]')\n const content = body?.querySelector<HTMLElement>('[data-step-process-content]')\n const group = body === null || content == null ? null\n : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top }\n return {\n row, group,\n position: position ?? {\n anchorKey: key,\n anchorTop: top - elements.scroller.getBoundingClientRect().top,\n scrollTop: elements.scroller.scrollTop,\n },\n }\n }\n\n private retain(row: HTMLElement, position?: ChatScrollPosition): PagingPosition | null {\n const paging = this.measurePaging(row, position)\n if (paging === null) return null\n this.retainPaging(paging)\n return paging\n }\n\n private retainPaging(paging: PagingPosition): void {\n this.stopPreserving()\n this.paging = paging\n if (paging.group !== null) this.observer?.observe(paging.group.content)\n }\n\n /** Release paging ownership and its content-size observation. */\n stopPreserving(): void {\n const group = this.paging?.group\n if (group != null) this.observer?.unobserve(group.content)\n this.paging = null\n }\n\n /**\n * Expose retained paging ownership to navigation and resize policy.\n * @returns whether a paging row is retained for subsequent layout changes.\n */\n get preserving(): boolean { return this.paging !== null }\n\n /**\n * Compensate inner scrolling first, then the outer scrollport, within their actual scroll ranges.\n * An inner write pauses its bound follow controller so the reading anchor takes priority.\n * @returns the actual landing, or null when no visible retained row remains.\n */\n preserve(): ViewportLanding | null {\n const paging = this.resolvePaging(this.paging)\n if (paging === null) {\n this.stopPreserving()\n return null\n }\n if (paging !== this.paging) this.retainPaging(paging)\n return this.applyPaging(paging)\n }\n\n private resolvePaging(paging: PagingPosition | null): PagingPosition | null {\n const elements = this.elements\n if (paging === null || elements === null) return null\n if (!elements.list.contains(paging.row)) {\n // Segmentation can remount the same semantic row under another group.\n const replacement = this.anchor(paging.position.anchorKey)\n if (replacement === null) return null\n paging = this.measurePaging(replacement, paging.position, paging.group)\n if (paging === null) return null\n }\n return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging\n }\n\n /** Restore the captured screen position; native anchoring already applied to this change needs no further correction. */\n private applyPaging(paging: PagingPosition): ViewportLanding | null {\n const elements = this.elements\n if (elements === null) return null\n const { row, group, position } = paging\n if (group !== null && group.body.contains(row)) {\n const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top\n const metrics = scrollMetrics(group.body)\n const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top))\n if (metrics.top !== target) {\n const follow = ScrollFollow.forElement(group.body)\n if (follow === undefined) group.body.scrollTop = target\n else {\n follow.jump(group.body, metrics, target)\n follow.setFollowing(false)\n }\n }\n }\n const metrics = this.metrics()\n if (metrics === null) return null\n const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top\n const target = metrics.top + top - position.anchorTop\n return this.write(target, metrics, null, { key: position.anchorKey, top })\n }\n\n /**\n * Align with the physical floor, including fold room that newer content has not yet filled.\n * @param follow - independent follow intent and scrolling controller.\n * @param behavior - immediate positioning, or one native animation for a reader-caused tail change.\n * @returns the actual floor landing, or null while detached. A smooth landing reports the starting\n * position; native scroll delivery moves it.\n */\n scrollToBottom(follow: ScrollFollow, behavior: 'instant' | 'smooth' = 'instant'): ViewportLanding | null {\n const metrics = this.metrics()\n if (metrics === null || this.elements === null) return null\n this.observation = { top: metrics.top, landing: null }\n this.reclaimBelow()\n const landing: ViewportLanding = {\n metrics: follow.toBottom(this.elements.scroller, scrollMetrics(this.elements.scroller), behavior),\n position: null,\n turn: this.latestTurn,\n }\n this.observation = { top: landing.metrics.top, landing }\n return landing\n }\n\n private align(row: HTMLElement, offset: number, turn: number | null): ViewportLanding | null {\n const metrics = this.metrics()\n if (metrics === null || this.elements === null) return null\n const top = row.getBoundingClientRect().top - this.elements.scroller.getBoundingClientRect().top\n return this.write(metrics.top + top - offset, metrics, turn, { key: row.dataset.chatAnchorKey, top })\n }\n\n private write(\n target: number, metrics: ViewportMetrics, turn: number | null,\n anchor?: { key: string | undefined; top: number },\n ): ViewportLanding | null {\n if (this.elements === null) return null\n const top = Math.max(0, Math.min(metrics.floor, target))\n if (top !== metrics.top) this.elements.scroller.scrollTop = top\n const actual = this.elements.scroller.scrollTop\n const landing: ViewportLanding = {\n metrics: { ...metrics, top: actual },\n turn,\n position: anchor?.key === undefined ? null : {\n anchorKey: anchor.key,\n anchorTop: anchor.top - (actual - metrics.top),\n scrollTop: actual,\n },\n }\n this.observation = { top: actual, landing }\n return landing\n }\n\n /**\n * Track the history control for request-distance checks.\n * @param element - stable history control, or null when its view unmounts.\n */\n readonly setHistoryEdge = (element: HTMLDivElement | null): void => {\n this.historyEdge = element\n }\n\n private pruneHistoryScrolling(): void {\n for (const target of this.historyScrolling) {\n if (!(target instanceof HTMLElement) || this.elements?.scroller.contains(target) !== true) {\n this.historyScrolling.delete(target)\n }\n }\n }\n\n /**\n * Confirm the actual history distance immediately before an automatic request.\n * @returns whether the control is within two viewport heights.\n */\n confirmHistoryStart(): boolean {\n const scroller = this.elements?.scroller\n if (scroller === undefined || this.historyEdge === null || this.historyHeight <= 0) return false\n const distance = scroller.getBoundingClientRect().top - this.historyEdge.getBoundingClientRect().bottom\n return distance <= this.historyHeight * 2\n }\n\n /**\n * Expose held input to history status copy.\n * @returns whether a touch or pointer remains down.\n */\n get historyInputHeld(): boolean { return this.historyTouch || this.historyPointer }\n\n /**\n * Select consumption behavior from current input and motion state.\n * @returns the blocker or positioning path for a prepared page.\n */\n historyConsumption(): 'motion' | 'touch' | 'pointer' | 'inner-scroll' | 'unavailable' | 'native' | 'preserve' | 'prepend' {\n const elements = this.elements\n if (elements === null) return 'unavailable'\n if (this.historyTouch) return 'touch'\n if (this.historyScrolling.size > 0\n && (this.historyScrolling.size !== 1 || !this.historyScrolling.has(elements.scroller))) return 'inner-scroll'\n if (this.motion.active() || this.reader?.follow.animating) return 'motion'\n if (this.historyPointer) return 'pointer'\n if (this.historyScrolling.size === 0) return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'preserve'\n if (this.preserving || typeof CSS === 'undefined' || !CSS.supports('overflow-anchor', 'auto')) return 'unavailable'\n return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'native'\n }\n\n /**\n * Capture one top-edge prepend anchor without acquiring continuous scroll ownership.\n * @returns whether an old paging row was captured.\n */\n beginHistoryPrepend(): boolean {\n const row = this.pagingAnchor()\n this.historyPrepend = row === null ? null : this.measurePaging(row)\n return this.historyPrepend !== null\n }\n\n /** Clear an unapplied one-shot correction when its page was not consumed. */\n cancelHistoryPrepend(): void { this.historyPrepend = null }\n\n /**\n * Correct a committed prepend once, then release positioning ownership.\n * @returns the compensated landing for reading memory, or null when no anchor remains.\n */\n finishHistoryPrepend(): ViewportLanding | null {\n const pending = this.historyPrepend\n this.historyPrepend = null\n const paging = this.resolvePaging(pending)\n return paging === null ? null : this.applyPaging(paging)\n }\n\n private readonly onHistoryScroll = (event: Event): void => {\n if (event.target === this.elements?.scroller || event.target instanceof HTMLElement\n && event.target.hasAttribute('data-step-process-body')) {\n this.historyScrolling.add(event.target)\n }\n }\n\n private readonly onHistoryPointerDown = (): void => {\n this.historyPointer = true\n this.events?.history?.()\n }\n private readonly onHistoryTouch = (): void => {\n this.historyTouch = true\n this.events?.history?.()\n }\n private readonly onHistoryRelease = (event: Event): void => {\n if (event.type === 'pointerup' || event.type === 'pointercancel') this.historyPointer = false\n if (event.type === 'touchend' || event.type === 'touchcancel') {\n this.historyTouch = typeof TouchEvent !== 'undefined' && event instanceof TouchEvent && event.touches.length > 0\n }\n this.events?.history?.()\n }\n\n private readonly onScroll = (event: Event): void => {\n if (this.elements === null || event.target !== this.elements.scroller) return\n if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return\n this.invalidate()\n if (this.paging !== null) {\n this.events?.resize()\n return\n }\n const scroll = this.readScroll()\n if (scroll !== null) this.events?.scroll(scroll)\n }\n\n private readonly onScrollEnd = (event: Event): void => {\n if (event.target !== null) this.historyScrolling.delete(event.target)\n this.events?.history?.()\n if (event.target === this.elements?.scroller) {\n this.events?.scrollEnd(true)\n this.reclaimBelow()\n } else if (event.target instanceof HTMLElement && event.target.hasAttribute('data-step-process-body')) this.events?.scrollEnd(false)\n }\n\n private readonly onIntent = (event: Event): void => {\n if (event.type === 'keydown' || event.type === 'pointerdown') {\n if (event.target instanceof Element && event.target.closest('[data-composer-seat]') !== null) return\n if (event.type === 'keydown' && (!(event instanceof KeyboardEvent) || !SCROLL_KEYS.has(event.key))) return\n }\n this.events?.intent?.()\n if (this.paging === null) return\n this.stopPreserving()\n this.events?.interact()\n }\n}\n\n/**\n * Bind viewport resource ownership to the component's layout lifetime.\n * @returns one viewport owner and the element refs attached for this mount.\n */\nexport function useChatViewport(): {\n viewport: ChatViewport\n listRef: RefObject<HTMLDivElement>\n columnRef: RefObject<HTMLDivElement>\n} {\n const listRef = useRef<HTMLDivElement | null>(null)\n const columnRef = useRef<HTMLDivElement | null>(null)\n const [viewport] = useState(() => new ChatViewport())\n useLayoutEffect(() => {\n if (listRef.current === null || columnRef.current === null) return\n viewport.attach(listRef.current, columnRef.current)\n return () => { viewport.detach() }\n }, [viewport])\n return { viewport, listRef, columnRef }\n}\n","/** Composes viewport operations, reading policy, and history navigation for Chat. */\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'\nimport type { TranscriptViewMode } from '../../chat-settings.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { useChatNavigation, type ChatNavigation, type ChatNavigationInput } from './use-chat-navigation.ts'\nimport { useChatReading, type ChatReadingState } from './use-chat-reading.ts'\nimport { useChatViewport } from './use-chat-viewport.ts'\nimport type { FlowMotionRows } from './flow-motion.ts'\n\n/** Committed content and Session operations used to reconcile scroll ownership. */\nexport interface ChatScrollInput extends ChatNavigationInput {\n readonly chatScroll: ChatViewSlotProps['chatScroll']\n readonly order: readonly string[]\n readonly lastKey: string | null\n readonly lastIsUser: boolean\n readonly steeringId: string | null\n readonly submissionId: string | null\n /** The latest visible submission steers the running Turn instead of opening a new one. */\n readonly submissionSteers: boolean\n readonly running: boolean\n /** Enable the browser-local delayed-fold experiment and its input reveal animation. */\n readonly deferCompletedTurns: boolean\n /** A changed work-details preference resets fold reservations after the layout settles. */\n readonly transcriptView: TranscriptViewMode\n readonly loadedTurns: ReturnType<ChatSnapshot['navigation']['items']>\n}\n\ninterface ChatScrollState extends ChatReadingState {\n readonly listRef: RefObject<HTMLDivElement>\n readonly columnRef: RefObject<HTMLDivElement>\n readonly busyTurn: number | null\n readonly navigateToTurn: ChatNavigation['navigateToTurn']\n readonly loadEarlier: ChatNavigation['loadEarlier']\n readonly historyInputHeld: boolean\n readonly historyProcessing: boolean\n readonly historyPending: boolean\n readonly historyEdgeRef: (element: HTMLDivElement | null) => void\n readonly returnToBottom: () => void\n readonly motion: FlowMotionRows\n}\n\n/**\n * Coordinate scroll policy after Chat content commits. Initial history must be available\n * before automatic scroll or resize handling can initialize reading state and fold motion.\n * New submitted input supersedes pending reader sampling.\n * @param input - current Chat content, scroll memory, and history operations.\n * @returns element refs, visible reading state, and navigation callbacks.\n */\nexport function useChatScroll(input: ChatScrollInput): ChatScrollState {\n const {\n isOpen, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running,\n deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, historyLoadStatus,\n loadOlder, consumeOlder, loadThrough, transcriptView,\n } = input\n const { viewport, listRef, columnRef } = useChatViewport()\n const [historyInputHeld, setHistoryInputHeld] = useState(false)\n const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null)\n const navigationInput = useMemo(() => ({\n firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough,\n }), [firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough])\n const { navigation, busyTurn, historyPending, historyProcessing } = useChatNavigation(viewport, reading, navigationInput)\n const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({\n input, applied: null, opened: false,\n })\n // A fold batch owns layout and scrolling until it lands: at the tail for own input or a following\n // reader, otherwise with the reader's content still. Growth consumes any room the landing installed.\n const cancelPendingFollow = useCallback(() => { viewport.motion.cancelInput() }, [viewport])\n\n const processContent = useCallback(() => {\n const current = content.current.input\n if (!current.isOpen && !content.current.opened) return\n const previous = content.current.applied\n const steeringInput = current.steeringId !== null && current.steeringId !== previous?.steeringId\n && current.steeringId !== previous?.submissionId\n const submissionInput = current.submissionId !== null && current.submissionId !== previous?.submissionId\n && current.submissionId !== previous?.steeringId\n const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey) || steeringInput || submissionInput\n if (reading.pending && !ownInput) return\n content.current.applied = current\n if (current.isOpen && !content.current.opened) {\n content.current.opened = true\n navigation.reset()\n reading.restore()\n return\n }\n if (ownInput) {\n navigation.cancel()\n if (current.deferCompletedTurns && reading.followInputFold(true)) return\n // Steering lands at once: the running Turn keeps streaming above its echo, and that growth would push\n // the echo down under a native animation.\n const steering = steeringInput || (submissionInput && current.submissionSteers)\n reading.followTail(current.deferCompletedTurns && !steering ? 'smooth' : 'instant')\n return\n }\n if (navigation.contentCommitted()) {\n navigation.reconcile()\n return\n }\n const tipChanged = previous === null || current.isOpen !== previous.isOpen\n || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey\n || current.order.length !== previous.order.length || current.running !== previous.running\n || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId\n if (tipChanged && reading.followingTail) {\n navigation.cancel()\n if (current.deferCompletedTurns && reading.followInputFold(false)) return\n reading.followTail()\n } else navigation.reconcile()\n }, [reading, navigation])\n\n useLayoutEffect(() => {\n const disconnectViewport = viewport.connect({\n scroll: (event) => {\n if (!content.current.opened) return\n if (!event.movedByReader && viewport.motion.foldActive()) return\n reading.onScroll(event)\n },\n scrollEnd: (outer) => {\n reading.onScrollEnd(outer)\n navigation.requestHistoryCheck()\n },\n interact: () => { navigation.readerInteracted() },\n history: () => {\n setHistoryInputHeld(viewport.historyInputHeld)\n if (content.current.opened) navigation.requestHistoryCheck()\n },\n intent: () => { cancelPendingFollow(); reading.interruptFollow() },\n resize: () => {\n if (!content.current.opened) return\n navigation.requestHistoryCheck()\n if (navigation.contentCommitted()) {\n navigation.reconcile()\n return\n }\n if (!content.current.input.deferCompletedTurns || !viewport.motion.foldActive()) reading.onResize()\n navigation.reconcile()\n },\n })\n const disconnectReading = reading.connect((sample) => {\n navigation.readerSampled(sample)\n processContent()\n navigation.requestHistoryCheck()\n })\n return () => {\n disconnectViewport()\n disconnectReading()\n content.current.opened = false\n content.current.applied = null\n }\n }, [viewport, reading, navigation, processContent, cancelPendingFollow])\n\n useLayoutEffect(() => {\n const previous = content.current.input\n content.current.input = {\n order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns,\n chatScroll, deferCompletedTurns, transcriptView, ...navigationInput,\n }\n if (!deferCompletedTurns) {\n cancelPendingFollow()\n reading.interruptFollow()\n }\n viewport.updateTurns(loadedTurns)\n const layoutChanged = previous.order !== order || previous.isOpen !== isOpen\n const historyConsumed = previous.historyLoadStatus === 'pendingConsumption' && historyLoadStatus === 'idle'\n if (!isOpen || historyLoadStatus === 'error') viewport.cancelHistoryPrepend()\n else if (layoutChanged || historyConsumed) {\n const landing = viewport.finishHistoryPrepend()\n if (landing !== null) reading.preservePosition(landing)\n }\n if (layoutChanged) viewport.invalidate()\n viewport.reclaimBelow()\n processContent()\n if (layoutChanged && content.current.opened) reading.refreshActiveTurn()\n if (content.current.opened) navigation.requestHistoryCheck()\n }, [\n viewport, reading, processContent, navigationInput, isOpen, order, lastKey, lastIsUser,\n steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView,\n cancelPendingFollow,\n ])\n\n const previousView = useRef(transcriptView)\n useLayoutEffect(() => {\n if (previousView.current === transcriptView) return\n previousView.current = transcriptView\n cancelPendingFollow()\n reading.interruptFollow()\n return viewport.motion.onFoldIdle(() => {\n viewport.resetBelow()\n if (content.current.opened) reading.onResize()\n })\n }, [transcriptView, viewport, reading, cancelPendingFollow])\n\n const returnToBottom = useCallback(() => {\n cancelPendingFollow()\n navigation.cancel()\n reading.followTail()\n }, [navigation, reading, cancelPendingFollow])\n\n return {\n listRef, columnRef, ...state, busyTurn, motion: viewport.motion,\n navigateToTurn: navigation.navigateToTurn,\n loadEarlier: navigation.loadEarlier,\n historyPending,\n historyProcessing,\n historyInputHeld,\n historyEdgeRef: viewport.setHistoryEdge,\n returnToBottom,\n }\n}\n","// An enclosing `[data-conversation-scroll]` owns scrolling when present;\n// otherwise this view owns it. Each row subscribes to one stable node key.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type {\n NodeKey, RenderEntry,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { InboxState } from '@deepseek-ai/dsh-agent/types'\nimport type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client'\nimport {\n Button, FenceCodeBlock, IconChevronDownOutlineRegular, MarkdownDelegateProvider, Modal,\n type MarkdownDelegateFenceInfo, type MarkdownMenuTarget,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport { isAtOrOutside } from '../contract/group-tree.ts'\nimport type { ChatFlowHookContext, ChatViewSlotProps, OpenFileOptions } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport { TurnNavigator } from './TurnNavigator.tsx'\nimport { mergeTurnRailItems } from './turn-rail-items.ts'\nimport { useTextInteraction } from './text-interaction.ts'\nimport { useChatScroll } from './use-chat-scroll.ts'\nimport { fileMediaUrl, resolveWorkspacePath, sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path'\nimport css from './ChatView.module.css'\n\n/** Host/OS refusal text for the file-open dialog; empty throws keep a locale fallback. */\nfunction openFailureMessage(error: unknown, fallback: string): string {\n const message = error instanceof Error ? error.message : String(error)\n return message === '' ? fallback : message\n}\n\n/**\n * Durable input identities suppress matching echoes in the same render.\n * The last input's Turn also distinguishes an empty opening control from\n * one whose human input or trigger notice is already present.\n */\nfunction observedInputs(\n order: readonly string[],\n nodes: ChatSnapshot['nodes'],\n): { readonly rpcIds: ReadonlySet<string>; readonly lastInputTurn: number | undefined } {\n const observed = new Set<string>()\n let lastInputTurn: number | undefined\n for (const key of order) {\n const node = nodes.get(key)\n if (node === undefined || !isAtOrOutside(node, 'input')) continue\n if (node.location.kind === 'turn' || node.location.kind === 'step') lastInputTurn = node.location.turn.turn\n const data: unknown = node.data\n const source = typeof data === 'object' && data !== null && 'source' in data ? data.source : undefined\n if (typeof source === 'object' && source !== null && 'kind' in source && source.kind === 'user'\n && 'rpcId' in source && typeof source.rpcId === 'string') observed.add(source.rpcId)\n }\n return { rpcIds: observed, lastInputTurn }\n}\n\ntype PendingInput = PendingSubmission | InboxState['next-step'][number]\n\n/** How long fold transitions stay enabled after a Turn stops running. */\nconst MOTION_TAIL_MS = 800\n\n/**\n * The chat view slot entry: pure component over the composed props; each\n * ordered business Node crosses the keyed renderer seat.\n */\nexport function ChatView({\n useSession, useChat, useConversation, useSessions, renderSlot,\n sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu,\n loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt,\n usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag,\n}: ChatViewSlotProps) {\n const { getTriggerProps } = useContextMenu()\n const getMarkdownTriggerProps = useCallback((target: MarkdownMenuTarget) => getTriggerProps(() => {\n switch (target.kind) {\n case 'file': return { kind: 'file', value: { sessionId, path: resolveFilePath(target.path),\n ...(target.line === undefined ? {} : { line: target.line }) } }\n case 'url': return { kind: 'url', value: { sessionId, url: target.url } }\n case 'image': return { kind: 'image', value: { sessionId, url: target.url,\n ...(target.name === undefined ? {} : { name: target.name }),\n ...(target.mediaType === undefined ? {} : { mediaType: target.mediaType }),\n ...(target.path === undefined ? {} : { path: resolveFilePath(target.path) }) } }\n }\n }), [getTriggerProps, resolveFilePath, sessionId])\n const order = useChat(s => s.order)\n const groupedEntries = useConversation(snapshot => snapshot.views.grouped('chat')?.entries)\n const entries = useMemo<readonly RenderEntry[]>(() => groupedEntries\n ?? order.map(key => ({ kind: 'node', key: key as NodeKey })), [groupedEntries, order])\n const nodeStore = useChat(s => s.nodes)\n const deferCompletedTurns = usePresentation(policy => policy.collapseTiming === 'next-input')\n const transcriptView = usePresentation(policy => policy.mode)\n // The rail's items are accumulated in the Chat snapshot, so this selector is\n // both the data and its change signal: the array identity moves only when a\n // Turn enters, leaves, or changes its preview.\n const turnNavigationItems = useChat(s => s.navigation.items())\n // Host-computed whole-log outline; the merge is view-layer only (the\n // conversation snapshot never carries projection values).\n const turnOutline = useProjection('turnOutline')\n const railItems = useMemo(\n () => mergeTurnRailItems(turnNavigationItems, turnOutline),\n [turnNavigationItems, turnOutline],\n )\n const inbox = useProjection('inbox') as InboxState | undefined\n // Workspace root off the session list row: path summaries display relative to it.\n const cwd = useSessions(s => s.byId[sessionId]?.cwd)\n const fileImages = useMemo(() => ({\n fileDrag,\n resolve: (path: string) => fileMediaUrl(document.baseURI, resolveWorkspacePath(cwd, path)),\n resourceAddress: (path: string) => sessionFileAddress(sessionId, resolveWorkspacePath(cwd, path)),\n labels: {\n open: t('image.open'), loading: t('image.loading'), failed: t('image.failed'),\n dialog: t('image.dialog'), close: t('image.close'),\n },\n }), [cwd, t, fileDrag, sessionId])\n const codeLabels = useMemo(() => markdownLabels(t).code, [t])\n // Every fence in the flow dispatches by language; the content is the plain\n // code block, so a language without a layer renders as code without diff rows.\n const renderCode = useCallback((fence: MarkdownDelegateFenceInfo) => renderSlot('conversation.chat.markdown.fence', fence, {\n entryKey: fence.lang,\n children: (\n <FenceCodeBlock lang={fence.lang} code={fence.code} streaming={fence.streaming} labels={codeLabels} diff={false} />\n ),\n }), [renderSlot, codeLabels])\n const running = useSession(s => s.running)\n // Fold transitions run while a Turn is live, while an input is pending, and briefly after settling.\n const [motionTail, setMotionTail] = useState(false)\n useEffect(() => {\n if (!deferCompletedTurns) {\n setMotionTail(false)\n return\n }\n if (running) {\n setMotionTail(true)\n return\n }\n const timer = setTimeout(() => { setMotionTail(false) }, MOTION_TAIL_MS)\n return () => { clearTimeout(timer) }\n }, [running, deferCompletedTurns])\n const openState = useSession(s => s.openState)\n const openError = useSession(s => s.openError)\n const hasMore = useSession(s => s.hasMore)\n const loadingOlder = useSession(s => s.loadingOlder)\n const historyLoadStatus = useSession(s => s.historyLoadStatus)\n const historyWasPartial = useSession(s => s.historyWasPartial)\n const [fileOpenError, setFileOpenError] = useState<{ path: string; message: string } | null>(null)\n const [fileOpenBusy, setFileOpenBusy] = useState(false)\n // Close/retry must ignore a settlement that started before the latest\n // gesture; otherwise a cancelled in-flight refusal reopens the dialog.\n const fileOpenRequest = useRef(0)\n\n const requestOpenFile = useCallback((path: string, options?: OpenFileOptions) => {\n const id = ++fileOpenRequest.current\n setFileOpenBusy(true)\n void (options === undefined ? openFile(path) : openFile(path, options)).then(\n () => {\n if (id !== fileOpenRequest.current) return\n setFileOpenError(null)\n setFileOpenBusy(false)\n },\n (error: unknown) => {\n if (id !== fileOpenRequest.current) return\n setFileOpenError({\n path,\n message: openFailureMessage(\n error,\n t('fileOpen.unknown'),\n ),\n })\n setFileOpenBusy(false)\n },\n )\n }, [openFile, t])\n\n const closeFileOpenError = useCallback(() => {\n fileOpenRequest.current += 1\n setFileOpenError(null)\n setFileOpenBusy(false)\n }, [])\n\n const inboxSteering = useMemo(\n () => inbox?.['next-step'].filter(message => message.source.kind === 'user') ?? [],\n [inbox],\n )\n const pendingSubmissions = useSession(s => s.pendingSubmissions)\n // Submission echoes still awaiting their durable counterpart. `order` is the\n // recompute trigger: durable user material always arrives as an append, and\n // every append replaces the order array.\n const [visibleSubmissions, lastInputTurn] = useMemo(() => {\n if (pendingSubmissions.length === 0) return [pendingSubmissions, undefined] as const\n const observed = observedInputs(order, nodeStore)\n return [pendingSubmissions.filter(submission => (\n submission.placement !== 'queued' && !observed.rpcIds.has(submission.requestId)\n )), observed.lastInputTurn] as const\n }, [pendingSubmissions, order, nodeStore])\n const pendingInputs = useMemo(() => {\n const local = new Map(visibleSubmissions.map(submission => [submission.requestId, submission]))\n // Admitted local identities outlive their bubbles until the Inbox claim watermark.\n const localIds = new Set(pendingSubmissions.filter(submission => submission.placement !== 'queued')\n .map(submission => submission.requestId))\n const pending = inboxSteering.flatMap<PendingInput>((item) => {\n const source = item.source\n if (source.kind !== 'user' || !('rpcId' in source)) return [item]\n const submission = local.get(source.rpcId)\n if (submission === undefined) return localIds.has(source.rpcId) ? [] : [item]\n local.delete(source.rpcId)\n return [submission]\n })\n return [...pending, ...local.values()]\n }, [inboxSteering, pendingSubmissions, visibleSubmissions])\n const deferCollapse = deferCompletedTurns\n && !pendingInputs.some(item => 'requestId' in item && item.placement === 'transcript')\n\n const firstKey = order[0]\n const firstSeq = firstKey === undefined ? null : nodeStore.get(firstKey)?.anchorSeq ?? null\n const lastKey = order.at(-1) ?? null\n const latestSteering = pendingInputs.findLast(item => 'source' in item)\n const steeringId = latestSteering?.source.kind === 'user' && 'rpcId' in latestSteering.source\n ? latestSteering.source.rpcId : latestSteering?.id ?? null\n const scroll = useChatScroll({\n isOpen: openState === 'open',\n order, firstSeq, lastKey, running, loadingOlder, historyLoadStatus, hasMore, chatScroll,\n loadOlder, consumeOlder, loadThrough, deferCompletedTurns,\n lastIsUser: lastKey !== null && nodeStore.get(lastKey)?.kind === 'user',\n steeringId,\n submissionId: visibleSubmissions.at(-1)?.requestId ?? null,\n submissionSteers: visibleSubmissions.at(-1)?.placement === 'steering',\n loadedTurns: turnNavigationItems,\n transcriptView,\n })\n const interactionSurfaceRef = useRef<HTMLDivElement>(null)\n const interactionIds = useInteractionIds(ids => ids)\n const textInteraction = useTextInteraction(scroll.columnRef, interactionSurfaceRef, dispatchInteraction, interactionIds)\n const flowContext = useMemo<ChatFlowHookContext>(() => ({ motion: scroll.motion }), [scroll.motion])\n\n return (\n <div className={css.frame}>\n {scroll.initialized && (\n <TurnNavigator\n items={railItems}\n activeTurn={scroll.activeTurn}\n busyTurn={scroll.busyTurn}\n onNavigate={scroll.navigateToTurn}\n t={t}\n />\n )}\n <div className={css.root} data-chat-following-tail={scroll.followingTail ? '' : undefined}>\n <div ref={scroll.listRef} className={css.scroll}>\n <div ref={scroll.columnRef} className={css.column} data-chat-flow=\"\"\n data-chat-motion={deferCompletedTurns && scroll.initialized\n && (running || motionTail || pendingInputs.length > 0) ? '' : undefined}>\n {openState === 'loading' && <div className={css.hint}>{t('chat.loadingHistory')}</div>}\n {openState === 'error' && openError !== null && (\n <div className={css.openError}>\n {t('chat.loadError', { message: openError.message, code: openError.code })}\n </div>\n )}\n {(hasMore || historyWasPartial) && (\n <div className={css.older} ref={scroll.historyEdgeRef} data-chat-history={historyLoadStatus}>\n <button type=\"button\" disabled={!hasMore}\n onClick={scroll.loadEarlier}>\n {([\n ['more', t('chat.loadOlder')],\n ['loading', t('chat.loadingOlder')],\n ['processing', t('chat.processingOlder')],\n ['error', t('chat.retryOlder')],\n ['start', t('chat.historyStart')],\n ] as const).map(([state, label]) => {\n const current = !hasMore ? 'start' : loadingOlder ? 'loading'\n : historyLoadStatus === 'error' ? 'error'\n : scroll.historyInputHeld ? 'more'\n : scroll.historyProcessing ? 'processing' : 'more'\n return <span key={state} aria-hidden={state !== current}\n className={state === current ? undefined : css.historyHidden}>{label}</span>\n })}\n </button>\n </div>\n )}\n <MarkdownDelegateProvider\n getTriggerProps={getMarkdownTriggerProps}\n openFile={requestOpenFile}\n openExternalLink={openExternalLink}\n fileImages={fileImages}\n renderCode={renderCode}\n >\n {renderSlot('conversation.chat.flow', {\n entries, pendingInputs, lastInputTurn, deferCollapse,\n cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage,\n }, { hookContext: flowContext })}\n </MarkdownDelegateProvider>\n <div ref={interactionSurfaceRef} className={css.textInteraction} data-text-interaction-surface=\"\"\n aria-hidden={textInteraction.active === null}>\n {textInteraction.active !== null && renderSlot('conversation.chat.text-interaction', {\n trigger: textInteraction.active.trigger, readText: textInteraction.readText,\n dismiss: textInteraction.dismiss, clearSelection: textInteraction.clearSelection,\n }, { entryKey: textInteraction.active.id })}\n </div>\n {/* No pending placeholders: questions (ui-user-questions) and approvals\n (ApprovalPanel) both take over the composer, so a flow card would\n double-render the same wait. */}\n </div>\n {/* Fold room is reclaimed by viewport scroll, content-growth, and display-mode policies. */}\n <div className={css.turnSpacer} data-chat-turn-spacer aria-hidden=\"true\" />\n </div>\n </div>\n {!scroll.followingTail && (\n <div className={css.toBottomSlot}>\n <button\n type=\"button\"\n className={css.toBottom}\n aria-label={t('chat.toBottom')}\n onClick={scroll.returnToBottom}\n >\n <IconChevronDownOutlineRegular />\n </button>\n </div>\n )}\n {fileOpenError !== null && (\n <FileOpenErrorDialog\n message={fileOpenError.message}\n busy={fileOpenBusy}\n onClose={closeFileOpenError}\n onRetry={() => { requestOpenFile(fileOpenError.path) }}\n t={t}\n />\n )}\n </div>\n )\n}\n\n/** In-page Host open-path refusal: the wire reason plus a retry of the same path. */\nfunction FileOpenErrorDialog({\n message, busy, onClose, onRetry, t,\n}: {\n message: string\n busy: boolean\n onClose: () => void\n onRetry: () => void\n t: ChatViewSlotProps['t']\n}) {\n return (\n <Modal\n open\n onClose={onClose}\n closeLabel={t('close')}\n title={t('fileOpen.title')}\n description={message}\n footer={(\n <>\n <Button variant=\"outline\" className={css.modalAction} onClick={onClose}>{t('cancel')}</Button>\n <Button variant=\"primary\" className={css.modalAction} disabled={busy} onClick={onRetry}>{t('retry')}</Button>\n </>\n )}\n />\n )\n}\n","//#region lib/types/partial-json.js\n/**\n* Lazily scanned view of one JSON object's top-level fields, built from text\n* that may still be streaming or from an already parsed object. Nothing is\n* scanned until a reader asks; the view remembers every question it answered\n* and reports changed answers when the owner refreshes for publication.\n* Used for model tool-call arguments: a row reads the fields it\n* cares about at whatever granularity it displays, at every stage of the call.\n* @module @deepseek-ai/dsh-util-values/src/partial-json\n*/\nconst SIMPLE_ESCAPES = {\n\t\"\\\"\": \"\\\"\",\n\t\"\\\\\": \"\\\\\",\n\t\"/\": \"/\",\n\tb: \"\\b\",\n\tf: \"\\f\",\n\tn: \"\\n\",\n\tr: \"\\r\",\n\tt: \"\t\"\n};\nconst CONTENT_ESCAPE = /[\\\\\\u0000-\\u001f]/u;\nfunction isWhitespace(c) {\n\treturn c === \" \" || c === \"\\n\" || c === \"\\r\" || c === \"\t\";\n}\nfunction isHex(c) {\n\treturn c >= \"0\" && c <= \"9\" || c >= \"a\" && c <= \"f\" || c >= \"A\" && c <= \"F\";\n}\n/**\n* The view. A streaming instance grows through {@link PartialArguments.append};\n* {@link PartialArguments.fromText} and {@link PartialArguments.fromObject} build\n* sealed instances over a finished call. Every reader is total: an absent or\n* differently typed field answers `undefined` (or `false`), never throws.\n*/\nvar PartialArguments = class PartialArguments {\n\t/** The view of a call with no arguments available. */\n\tstatic EMPTY = PartialArguments.fromObject({});\n\t/**\n\t* View finished argument text without scanning it until a reader asks.\n\t* @param text - the complete argument JSON text.\n\t* @returns a sealed view.\n\t*/\n\tstatic fromText(text) {\n\t\tconst view = new PartialArguments();\n\t\tview.append(text);\n\t\tview.sealed = true;\n\t\treturn view;\n\t}\n\t/**\n\t* View an already parsed argument payload, such as a PTC dispatch object.\n\t* @param value - the parsed argument value.\n\t* @returns a sealed view; a non-object payload has no fields.\n\t*/\n\tstatic fromObject(value) {\n\t\tconst view = new PartialArguments();\n\t\tview.object = typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : {};\n\t\tview.sealed = true;\n\t\treturn view;\n\t}\n\t/**\n\t* The source: text so far or a parsed object, plus whether it can still grow.\n\t* These are the only enumerable fields, so two views over the same source\n\t* compare equal structurally however far each has been read.\n\t*/\n\tchunks = [];\n\tobject;\n\tsealed = false;\n\t#ends = [];\n\t#size = 0;\n\t#consumed = 0;\n\t#mode = \"root\";\n\t#escape = false;\n\t#keyStart = 0;\n\t#keyEscaped = false;\n\t#key = \"\";\n\t#current = null;\n\t#nestedEnds = [];\n\t#nestedInString = false;\n\t#invalidAt;\n\t#invalidValue = false;\n\t#entries = /* @__PURE__ */ new Map();\n\t#order = [];\n\t#reads = /* @__PURE__ */ new Map();\n\t/** Whether this view rejects further appends; does not scan text or register reads. */\n\tget isSealed() {\n\t\treturn this.sealed;\n\t}\n\t/** Whether indexing or a content read found invalid JSON; unread value contents are not validated. */\n\tget invalid() {\n\t\tthis.scan();\n\t\treturn this.#mode === \"invalid\" || this.#invalidValue;\n\t}\n\t/**\n\t* Retain streamed argument text without scanning or comparing observed answers.\n\t* @param fragment - the text following every fragment appended before.\n\t*/\n\tappend(fragment) {\n\t\tif (this.sealed) throw new Error(\"PartialArguments: cannot append to a sealed view\");\n\t\tif (fragment.length === 0) return;\n\t\tthis.chunks.push(fragment);\n\t\tthis.#size += fragment.length;\n\t\tthis.#ends.push(this.#size);\n\t}\n\t/**\n\t* Reconcile a streamed prefix with authoritative complete text without joining the fragments.\n\t* @param text - the final argument text, which replaces missing or conflicting deltas.\n\t* @returns this view sealed with its caches retained when every character matches; otherwise a new sealed view.\n\t*/\n\tsettle(text) {\n\t\tif (this.object !== void 0 || text.length !== this.#size) return PartialArguments.fromText(text);\n\t\tlet offset = 0;\n\t\tfor (const chunk of this.chunks) {\n\t\t\tif (!text.startsWith(chunk, offset)) return PartialArguments.fromText(text);\n\t\t\toffset += chunk.length;\n\t\t}\n\t\tthis.chunks = text.length === 0 ? [] : [text];\n\t\tthis.#ends = text.length === 0 ? [] : [text.length];\n\t\tthis.sealed = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Compare observed answers and advance their publication baseline. Unread views remain unscanned.\n\t* @returns whether any observed answer changed since its first read or the preceding refresh.\n\t*/\n\trefresh() {\n\t\tif (this.#reads.size === 0) return false;\n\t\tthis.scan();\n\t\tlet changed = false;\n\t\tlet completions = false;\n\t\tfor (const read of this.#reads.values()) {\n\t\t\tif (read.completion) {\n\t\t\t\tcompletions = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = this.refreshRead(read) || changed;\n\t\t}\n\t\tif (completions) {\n\t\t\tfor (const read of this.#reads.values()) if (read.completion) changed = this.refreshRead(read) || changed;\n\t\t}\n\t\tif (this.sealed) this.#reads.clear();\n\t\treturn changed;\n\t}\n\trefreshRead(read) {\n\t\tconst now = read.answer();\n\t\tif (Object.is(now, read.last)) return false;\n\t\tread.last = now;\n\t\treturn true;\n\t}\n\t/**\n\t* Check whether no further fields can arrive.\n\t* @returns whether the outer object closed, indexing failed, or the view is sealed; unread values are not validated.\n\t*/\n\tclosed() {\n\t\treturn this.remember(\"closed\", \"\", () => this.closedNow());\n\t}\n\t/**\n\t* List discovered fields in first-appearance order.\n\t* @returns top-level keys seen so far, in first-appearance order.\n\t*/\n\tkeys() {\n\t\treturn this.remember(\"keys\", \"\", () => this.keysNow(), (keys) => keys.length);\n\t}\n\t/**\n\t* Check whether a top-level field has appeared.\n\t* @param key - argument name.\n\t* @returns whether the field has appeared (a string opened or another value began).\n\t*/\n\thas(key) {\n\t\treturn this.remember(\"has\", key, () => this.hasNow(key));\n\t}\n\t/**\n\t* Check whether a field's closing delimiter has arrived, without validating its contents.\n\t* @param key - argument name.\n\t* @returns whether its delimiter arrived and no content reader has reported an error for this value.\n\t*/\n\tcomplete(key) {\n\t\treturn this.remember(\"complete\", key, () => this.completeNow(key));\n\t}\n\t/**\n\t* Read string length without materializing its text.\n\t* @param key - argument name.\n\t* @param options - change granularity for a streaming string.\n\t* @returns decoded UTF-16 length of the string field so far; undefined when absent or not a string.\n\t*/\n\tstringLength(key, options) {\n\t\tconst step = Math.max(1, Math.floor(options?.step ?? 1));\n\t\tconst offset = options?.offset ?? 0;\n\t\treturn this.remember(`length:${step}:${offset}`, key, () => this.lengthNow(key), (length) => length === void 0 ? void 0 : Math.ceil((length + offset) / step));\n\t}\n\t/**\n\t* Check a string against a decoded UTF-16 length limit without materializing it.\n\t* @param key - argument name.\n\t* @param maxLength - decoded UTF-16 limit, floored to at least zero.\n\t* @returns whether the string is longer than the limit; false when absent or not a string.\n\t*/\n\tstringExceeds(key, maxLength) {\n\t\tconst limit = Math.max(0, Math.floor(maxLength));\n\t\treturn this.remember(`exceeds:${limit}`, key, () => (this.lengthNow(key, limit + 1) ?? 0) > limit);\n\t}\n\t/**\n\t* Read a decoded string, including a streaming prefix.\n\t* @param key - argument name.\n\t* @returns the string field's decoded text so far; undefined when absent or not a string.\n\t*/\n\ttext(key) {\n\t\treturn this.remember(\"text\", key, () => this.textNow(key));\n\t}\n\t/**\n\t* Read at most the first decoded UTF-16 units of a string.\n\t* @param key - argument name.\n\t* @param maxLength - maximum decoded UTF-16 length, floored to at least one.\n\t* @returns the bounded string prefix; undefined when absent or not a string.\n\t*/\n\ttextPrefix(key, maxLength) {\n\t\tconst limit = Math.max(1, Math.floor(maxLength));\n\t\treturn this.remember(`prefix:${limit}`, key, () => this.textPrefixNow(key, limit));\n\t}\n\t/**\n\t* Read a completed non-string argument.\n\t* @param key - argument name.\n\t* @returns the parsed non-string value once it closed; undefined while open, absent, or a string.\n\t*/\n\tvalue(key) {\n\t\treturn this.remember(\"value\", key, () => this.valueNow(key));\n\t}\n\t/** Answer a question and, on a streaming view, remember it for change detection. */\n\tremember(kind, key, read, comparison) {\n\t\tthis.scan();\n\t\tconst result = read();\n\t\tif (!this.sealed) {\n\t\t\tconst id = `${kind}/${key}`;\n\t\t\tif (!this.#reads.has(id)) this.#reads.set(id, {\n\t\t\t\tcompletion: kind === \"complete\",\n\t\t\t\tanswer: comparison === void 0 ? read : () => comparison(read()),\n\t\t\t\tlast: comparison === void 0 ? result : comparison(result)\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t}\n\tclosedNow() {\n\t\treturn this.sealed || this.#mode === \"closed\" || this.#mode === \"invalid\";\n\t}\n\tkeysNow() {\n\t\treturn this.object === void 0 ? this.#order : Object.keys(this.object);\n\t}\n\thasNow(key) {\n\t\treturn this.object === void 0 ? this.#entries.has(key) : Object.hasOwn(this.object, key);\n\t}\n\tcompleteNow(key) {\n\t\tif (this.object !== void 0) return Object.hasOwn(this.object, key);\n\t\tconst entry = this.#entries.get(key);\n\t\treturn entry !== void 0 && entry.end >= 0 && (entry.kind === \"string\" ? entry.invalidAt === void 0 : !entry.invalid);\n\t}\n\tlengthNow(key, limit = Number.POSITIVE_INFINITY) {\n\t\tif (this.object !== void 0) {\n\t\t\tconst field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;\n\t\t\treturn typeof field === \"string\" ? field.length : void 0;\n\t\t}\n\t\tconst entry = this.#entries.get(key);\n\t\tif (entry?.kind !== \"string\") return void 0;\n\t\tif (entry.text !== void 0 && entry.text.at === entry.end) return entry.text.length;\n\t\tconst read = entry.length ??= {\n\t\t\tat: entry.start,\n\t\t\tlength: 0,\n\t\t\ttext: \"\"\n\t\t};\n\t\tthis.readString(entry, read, limit, false);\n\t\treturn read.length;\n\t}\n\ttextNow(key) {\n\t\tif (this.object !== void 0) {\n\t\t\tconst field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;\n\t\t\treturn typeof field === \"string\" ? field : void 0;\n\t\t}\n\t\tconst entry = this.#entries.get(key);\n\t\tif (entry?.kind !== \"string\") return void 0;\n\t\tif (entry.text === void 0 && entry.end >= 0 && entry.needsDecoding && entry.invalidAt === void 0) {\n\t\t\tlet text;\n\t\t\ttry {\n\t\t\t\ttext = JSON.parse(`\"${this.slice(entry.start, entry.end)}\"`);\n\t\t\t} catch (_error) {}\n\t\t\tif (text !== void 0) entry.text = {\n\t\t\t\tat: entry.end,\n\t\t\t\tlength: text.length,\n\t\t\t\ttext\n\t\t\t};\n\t\t}\n\t\tconst read = entry.text ??= {\n\t\t\tat: entry.start,\n\t\t\tlength: 0,\n\t\t\ttext: \"\"\n\t\t};\n\t\tthis.readString(entry, read, Number.POSITIVE_INFINITY, true);\n\t\treturn read.text;\n\t}\n\ttextPrefixNow(key, maxLength) {\n\t\tif (this.object !== void 0) {\n\t\t\tconst field = Object.hasOwn(this.object, key) ? this.object[key] : void 0;\n\t\t\treturn typeof field === \"string\" ? field.slice(0, maxLength) : void 0;\n\t\t}\n\t\tconst entry = this.#entries.get(key);\n\t\tif (entry?.kind !== \"string\") return void 0;\n\t\tconst prefixes = entry.prefixes ??= /* @__PURE__ */ new Map();\n\t\tlet read = prefixes.get(maxLength);\n\t\tif (read === void 0) {\n\t\t\tread = {\n\t\t\t\tat: entry.start,\n\t\t\t\tlength: 0,\n\t\t\t\ttext: \"\"\n\t\t\t};\n\t\t\tprefixes.set(maxLength, read);\n\t\t}\n\t\tthis.readString(entry, read, maxLength, true);\n\t\treturn read.text;\n\t}\n\tvalueNow(key) {\n\t\tif (this.object !== void 0) {\n\t\t\tif (!Object.hasOwn(this.object, key)) return void 0;\n\t\t\tconst field = this.object[key];\n\t\t\treturn typeof field === \"string\" ? void 0 : field;\n\t\t}\n\t\tconst entry = this.#entries.get(key);\n\t\tif (entry?.kind !== \"value\" || entry.end < 0 || entry.invalid) return void 0;\n\t\tif (entry.parsed === void 0) try {\n\t\t\tentry.parsed = JSON.parse(this.slice(entry.start, entry.end));\n\t\t} catch (_error) {\n\t\t\tentry.invalid = true;\n\t\t\tthis.#invalidValue = true;\n\t\t}\n\t\treturn entry.parsed;\n\t}\n\tchunkAt(at) {\n\t\tlet low = 0;\n\t\tlet high = this.#ends.length;\n\t\twhile (low < high) {\n\t\t\tconst mid = low + high >>> 1;\n\t\t\tif (this.#ends[mid] <= at) low = mid + 1;\n\t\t\telse high = mid;\n\t\t}\n\t\treturn low;\n\t}\n\t/** Materialize only a requested range, never the cumulative source. */\n\tslice(start, end) {\n\t\tif (start >= end) return \"\";\n\t\tconst first = this.chunkAt(start);\n\t\tconst last = this.chunkAt(end - 1);\n\t\tconst base = first === 0 ? 0 : this.#ends[first - 1];\n\t\tif (first === last) return this.chunks[first].slice(start - base, end - base);\n\t\tconst parts = [this.chunks[first].slice(start - base)];\n\t\tfor (let i = first + 1; i < last; i++) parts.push(this.chunks[i]);\n\t\tparts.push(this.chunks[last].slice(0, end - this.#ends[last - 1]));\n\t\treturn parts.join(\"\");\n\t}\n\treadString(entry, read, limit, materialize) {\n\t\tconst end = Math.min(entry.end < 0 ? this.#consumed : entry.end, entry.invalidAt ?? Number.POSITIVE_INFINITY, this.#invalidAt ?? Number.POSITIVE_INFINITY);\n\t\tif (!entry.needsDecoding) {\n\t\t\tconst length = Math.min(end - read.at, limit - read.length);\n\t\t\tif (length <= 0) return;\n\t\t\tif (materialize) read.text += this.slice(read.at, read.at + length);\n\t\t\tread.at += length;\n\t\t\tread.length += length;\n\t\t\treturn;\n\t\t}\n\t\tlet chunkIndex = this.chunkAt(read.at);\n\t\twhile (read.at < end && read.length < limit) {\n\t\t\tconst base = chunkIndex === 0 ? 0 : this.#ends[chunkIndex - 1];\n\t\t\tconst chunk = this.chunks[chunkIndex];\n\t\t\tconst remaining = chunk.slice(read.at - base, Math.min(chunk.length, end - base));\n\t\t\tconst boundary = remaining.search(CONTENT_ESCAPE);\n\t\t\tconst length = Math.min(boundary < 0 ? remaining.length : boundary, limit - read.length);\n\t\t\tif (length > 0) {\n\t\t\t\tif (materialize) read.text += remaining.slice(0, length);\n\t\t\t\tread.at += length;\n\t\t\t\tread.length += length;\n\t\t\t\tif (read.at === base + chunk.length) chunkIndex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst type = remaining.length > 1 ? remaining[1] : read.at + 1 < end ? this.chunks[chunkIndex + 1][0] : void 0;\n\t\t\tlet decoded;\n\t\t\tlet width = 2;\n\t\t\tif (remaining[0] === \"\\\\\" && type === void 0 && entry.end < 0) return;\n\t\t\tif (remaining[0] === \"\\\\\" && type === \"u\") {\n\t\t\t\tconst hex = this.slice(read.at + 2, Math.min(end, read.at + 6));\n\t\t\t\tlet valid = true;\n\t\t\t\tfor (let i = 0; i < hex.length; i++) if (!isHex(hex[i])) valid = false;\n\t\t\t\tif (valid) {\n\t\t\t\t\tif (hex.length < 4 && entry.end < 0) return;\n\t\t\t\t\tif (hex.length === 4) decoded = String.fromCharCode(Number.parseInt(hex, 16));\n\t\t\t\t}\n\t\t\t\twidth = 6;\n\t\t\t} else if (remaining[0] === \"\\\\\" && type !== void 0) decoded = SIMPLE_ESCAPES[type];\n\t\t\tif (decoded === void 0) {\n\t\t\t\tentry.invalidAt = read.at;\n\t\t\t\tthis.#invalidValue = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (materialize) read.text += decoded;\n\t\t\tread.length++;\n\t\t\tread.at += width;\n\t\t\twhile (chunkIndex < this.chunks.length && read.at >= this.#ends[chunkIndex]) chunkIndex++;\n\t\t}\n\t}\n\t/** Locate new field ranges without decoding or parsing their contents. */\n\tscan() {\n\t\tif (this.object !== void 0 || this.#consumed === this.#size) return;\n\t\tfor (let i = this.chunkAt(this.#consumed); i < this.chunks.length && this.#invalidAt === void 0; i++) {\n\t\t\tconst pending = this.chunks[i];\n\t\t\tconst base = i === 0 ? 0 : this.#ends[i - 1];\n\t\t\tfor (let index = this.#consumed - base; index < pending.length && this.#mode !== \"invalid\"; index++) {\n\t\t\t\tif (this.#mode === \"string\" || this.#mode === \"nested\" && this.#nestedInString) {\n\t\t\t\t\tconst end = this.stringBoundary(pending, index);\n\t\t\t\t\tthis.#consumed += end - index;\n\t\t\t\t\tindex = end;\n\t\t\t\t\tif (index === pending.length) break;\n\t\t\t\t}\n\t\t\t\tthis.step(pending[index], this.#consumed);\n\t\t\t\tthis.#consumed++;\n\t\t\t}\n\t\t}\n\t}\n\t/** Only raw quotes and their preceding backslash runs can terminate a string. */\n\tstringBoundary(fragment, start) {\n\t\tlet at = start;\n\t\twhile (true) {\n\t\t\tconst quote = fragment.indexOf(\"\\\"\", at);\n\t\t\tconst end = quote < 0 ? fragment.length : quote;\n\t\t\tif (this.#mode === \"string\") {\n\t\t\t\tconst entry = this.#current;\n\t\t\t\tif (!entry.needsDecoding && CONTENT_ESCAPE.test(fragment.slice(at, end))) entry.needsDecoding = true;\n\t\t\t}\n\t\t\tlet slashStart = end;\n\t\t\twhile (slashStart > at && fragment[slashStart - 1] === \"\\\\\") slashStart--;\n\t\t\tconst escaped = (end - slashStart) % 2 === 1 !== (slashStart === at && this.#escape);\n\t\t\tthis.#escape = quote < 0 && escaped;\n\t\t\tif (quote < 0 || !escaped) return end;\n\t\t\tat = quote + 1;\n\t\t}\n\t}\n\tstep(c, at) {\n\t\tswitch (this.#mode) {\n\t\t\tcase \"root\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tif (c === \"{\") {\n\t\t\t\t\tthis.#mode = \"key-or-end\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\tcase \"key-or-end\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tif (c === \"}\") {\n\t\t\t\t\tthis.#mode = \"closed\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (c === \"\\\"\") {\n\t\t\t\t\tthis.beginKey(at);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\tcase \"key-only\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tif (c === \"\\\"\") {\n\t\t\t\t\tthis.beginKey(at);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\tcase \"key\":\n\t\t\t\tthis.stepKey(c, at);\n\t\t\t\treturn;\n\t\t\tcase \"colon\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tif (c === \":\") {\n\t\t\t\t\tthis.#mode = \"value\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\tcase \"value\":\n\t\t\t\tthis.beginValue(c, at);\n\t\t\t\treturn;\n\t\t\tcase \"string\": {\n\t\t\t\tconst entry = this.#current;\n\t\t\t\tentry.end = at;\n\t\t\t\tthis.#current = null;\n\t\t\t\tthis.#mode = \"comma-or-end\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"scalar\":\n\t\t\t\tthis.stepScalar(c, at);\n\t\t\t\treturn;\n\t\t\tcase \"nested\":\n\t\t\t\tthis.stepNested(c, at);\n\t\t\t\treturn;\n\t\t\tcase \"comma-or-end\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tif (c === \",\") {\n\t\t\t\t\tthis.#mode = \"key-only\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (c === \"}\") {\n\t\t\t\t\tthis.#mode = \"closed\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\tcase \"closed\":\n\t\t\t\tif (isWhitespace(c)) return;\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\t/* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */\n\t\t\tcase \"invalid\": return;\n\t\t\t/* v8 ignore next 2 -- Every scanner mode has a handler above. */\n\t\t\tdefault: assertNever(this.#mode);\n\t\t}\n\t}\n\tfail() {\n\t\tthis.#invalidAt = this.#consumed;\n\t\tthis.#mode = \"invalid\";\n\t\tthis.#current = null;\n\t}\n\tbeginKey(at) {\n\t\tthis.#mode = \"key\";\n\t\tthis.#keyStart = at + 1;\n\t\tthis.#keyEscaped = false;\n\t\tthis.#escape = false;\n\t}\n\tstepKey(c, at) {\n\t\tif (c < \" \") {\n\t\t\tthis.fail();\n\t\t\treturn;\n\t\t}\n\t\tif (this.#escape) {\n\t\t\tthis.#escape = false;\n\t\t\treturn;\n\t\t}\n\t\tif (c === \"\\\\\") {\n\t\t\tthis.#escape = true;\n\t\t\tthis.#keyEscaped = true;\n\t\t\treturn;\n\t\t}\n\t\tif (c !== \"\\\"\") return;\n\t\tconst raw = this.slice(this.#keyStart, at);\n\t\tif (this.#keyEscaped) try {\n\t\t\tthis.#key = JSON.parse(`\"${raw}\"`);\n\t\t} catch (_error) {\n\t\t\tthis.fail();\n\t\t\treturn;\n\t\t}\n\t\telse this.#key = raw;\n\t\tthis.#mode = \"colon\";\n\t}\n\topen(entry) {\n\t\tif (!this.#entries.has(this.#key)) this.#order.push(this.#key);\n\t\tthis.#entries.set(this.#key, entry);\n\t\tthis.#current = entry;\n\t}\n\tbeginValue(c, at) {\n\t\tif (isWhitespace(c)) return;\n\t\tif (c === \"\\\"\") {\n\t\t\tthis.open({\n\t\t\t\tkind: \"string\",\n\t\t\t\tstart: at + 1,\n\t\t\t\tend: -1,\n\t\t\t\tneedsDecoding: false,\n\t\t\t\tinvalidAt: void 0,\n\t\t\t\tlength: void 0,\n\t\t\t\ttext: void 0,\n\t\t\t\tprefixes: void 0\n\t\t\t});\n\t\t\tthis.#escape = false;\n\t\t\tthis.#mode = \"string\";\n\t\t\treturn;\n\t\t}\n\t\tif (c === \"}\" || c === \",\" || c === \":\" || c === \"]\") {\n\t\t\tthis.fail();\n\t\t\treturn;\n\t\t}\n\t\tthis.open({\n\t\t\tkind: \"value\",\n\t\t\tstart: at,\n\t\t\tend: -1,\n\t\t\tparsed: void 0,\n\t\t\tinvalid: false\n\t\t});\n\t\tif (c === \"{\" || c === \"[\") {\n\t\t\tthis.#mode = \"nested\";\n\t\t\tthis.#nestedEnds = [c === \"{\" ? \"}\" : \"]\"];\n\t\t\tthis.#nestedInString = false;\n\t\t\tthis.#escape = false;\n\t\t\treturn;\n\t\t}\n\t\tthis.#mode = \"scalar\";\n\t}\n\tstepScalar(c, at) {\n\t\tif (c !== \",\" && c !== \"}\" && !isWhitespace(c)) return;\n\t\tthis.closeValue(at);\n\t\tthis.#mode = c === \",\" ? \"key-only\" : c === \"}\" ? \"closed\" : \"comma-or-end\";\n\t}\n\tstepNested(c, at) {\n\t\tif (this.#nestedInString) {\n\t\t\tthis.#nestedInString = false;\n\t\t\treturn;\n\t\t}\n\t\tif (c === \"\\\"\") {\n\t\t\tthis.#nestedInString = true;\n\t\t\treturn;\n\t\t}\n\t\tif (c === \"{\" || c === \"[\") {\n\t\t\tthis.#nestedEnds.push(c === \"{\" ? \"}\" : \"]\");\n\t\t\treturn;\n\t\t}\n\t\tif (c === \"}\" || c === \"]\") {\n\t\t\tif (this.#nestedEnds.pop() !== c) {\n\t\t\t\tthis.fail();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#nestedEnds.length === 0) {\n\t\t\t\tthis.closeValue(at + 1);\n\t\t\t\tthis.#mode = \"comma-or-end\";\n\t\t\t}\n\t\t}\n\t}\n\tcloseValue(end) {\n\t\tconst entry = this.#current;\n\t\tentry.end = end;\n\t\tthis.#current = null;\n\t}\n};\n//#endregion\n//#region lib/types/index.js\n/** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */\n/**\n* Mark an unreachable closed-union branch.\n* @param value - impossible value; an unhandled typed variant fails at the call site.\n* @param context - optional switch-site label included in the failure message.\n* @returns never; a runtime value that escaped its type always throws.\n*/\nfunction assertNever(value, context) {\n\tconst rendered = JSON.stringify(value) ?? String(value);\n\tthrow new Error(`unreachable variant${context ? ` in ${context}` : \"\"}: ${rendered}`);\n}\n/** Whether a realm-owned intrinsic prototype has a native constructor matching this engine's representation. */\nfunction hasIntrinsicConstructor(prototype, name) {\n\tconst constructor = Object.getOwnPropertyDescriptor(prototype, \"constructor\")?.value;\n\tif (typeof constructor !== \"function\") return false;\n\ttry {\n\t\treturn constructor.name === name && constructor.prototype === prototype && Function.prototype.toString.call(constructor) === Function.prototype.toString.call(name === \"Array\" ? Array : Object);\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Whether a candidate is one realm's intrinsic `Object.prototype`. */\nfunction isIntrinsicObjectPrototype(value) {\n\treturn Object.getPrototypeOf(value) === null && hasIntrinsicConstructor(value, \"Object\");\n}\n/** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */\nfunction hasPlainArrayPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\tif (!Array.isArray(prototype) || !hasIntrinsicConstructor(prototype, \"Array\")) return false;\n\tconst objectPrototype = Object.getPrototypeOf(prototype);\n\treturn typeof objectPrototype === \"object\" && objectPrototype !== null && isIntrinsicObjectPrototype(objectPrototype);\n}\n/** Whether an object is a plain or null-prototype record from any JavaScript realm. */\nfunction hasPlainObjectPrototype(value) {\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || typeof prototype === \"object\" && isIntrinsicObjectPrototype(prototype);\n}\n/** Return every JSON-visible object key, or reject own data JSON would discard. */\nfunction enumerableStringKeys(value) {\n\tconst keys = Reflect.ownKeys(value);\n\tif (keys.some((key) => typeof key !== \"string\" || !Object.prototype.propertyIsEnumerable.call(value, key))) return void 0;\n\treturn keys;\n}\n/** Validate lossless JSON iteratively, optionally materializing a detached snapshot. */\nfunction walkJsonValue(value, detach) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tlet root;\n\tlet parent;\n\tconst assign = (item) => {\n\t\tif (parent === void 0) {\n\t\t\tif (detach) root = item;\n\t\t} else if (parent.kind === \"array\") {\n\t\t\tif (parent.target !== void 0) parent.target[parent.key] = item;\n\t\t} else if (parent.target !== void 0) Object.defineProperty(parent.target, parent.key, {\n\t\t\tvalue: item,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\t};\n\tconst frames = [];\n\tlet current = value;\n\tfor (;;) {\n\t\tif (current === null) assign(null);\n\t\telse if (typeof current === \"boolean\" || typeof current === \"string\") assign(current);\n\t\telse if (typeof current === \"number\") {\n\t\t\tif (!Number.isFinite(current) || Object.is(current, -0)) return void 0;\n\t\t\tassign(current);\n\t\t} else {\n\t\t\tif (typeof current !== \"object\") return void 0;\n\t\t\tif (ancestors.has(current)) return void 0;\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (!hasPlainArrayPrototype(current)) return void 0;\n\t\t\t\tconst length = current.length;\n\t\t\t\tif (Reflect.ownKeys(current).length !== length + 1) return void 0;\n\t\t\t\tconst target = detach ? [] : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tlet indices;\n\t\t\t\tif (!Number.isInteger(length)) {\n\t\t\t\t\tindices = [];\n\t\t\t\t\tfor (let index = length - 1; index >= 0; index--) indices.push(index);\n\t\t\t\t}\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"array\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tlength: indices?.length ?? length,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: 0,\n\t\t\t\t\tindices,\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (!hasPlainObjectPrototype(current)) return void 0;\n\t\t\t\tconst keys = enumerableStringKeys(current);\n\t\t\t\tif (keys === void 0) return void 0;\n\t\t\t\tconst target = detach ? {} : void 0;\n\t\t\t\tif (target !== void 0) assign(target);\n\t\t\t\tframes.push({\n\t\t\t\t\tkind: \"object\",\n\t\t\t\t\tsource: current,\n\t\t\t\t\tkeys,\n\t\t\t\t\tindex: 0,\n\t\t\t\t\tkey: \"\",\n\t\t\t\t\ttarget\n\t\t\t\t});\n\t\t\t}\n\t\t\tancestors.add(current);\n\t\t}\n\t\tfor (;;) {\n\t\t\tconst frame = frames.at(-1);\n\t\t\tif (frame === void 0) return detach ? root : true;\n\t\t\tconst length = frame.kind === \"array\" ? frame.length : frame.keys.length;\n\t\t\tif (frame.index >= length) {\n\t\t\t\tancestors.delete(frame.source);\n\t\t\t\tframes.pop();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst index = frame.index++;\n\t\t\tparent = frame;\n\t\t\tif (frame.kind === \"array\") {\n\t\t\t\tconst key = frame.indices === void 0 ? index : frame.indices[frame.indices.length - index - 1];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured index count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tif (!Object.prototype.hasOwnProperty.call(frame.source, key)) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t} else {\n\t\t\t\tconst key = frame.keys[index];\n\t\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\t\tif (key === void 0) return void 0;\n\t\t\t\tframe.key = key;\n\t\t\t\tcurrent = frame.source[key];\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n/**\n* Validate and detach lossless JSON in one read per property.\n* @param value - candidate value to validate and detach.\n* @returns the detached snapshot, or `undefined` when the value is not losslessly JSON-serializable.\n*/\nfunction snapshotJsonValue(value) {\n\treturn walkJsonValue(value, true);\n}\n/**\n* Test the same lossless JSON rules as {@link snapshotJsonValue} without detaching the value.\n* @param value - candidate value to test.\n* @returns whether the value survives a JSON round trip without loss.\n*/\nfunction isJsonValue(value) {\n\treturn walkJsonValue(value, false) === true;\n}\n/**\n* Compare JSON-compatible values structurally.\n* @param a - one JSON-compatible value.\n* @param b - the other JSON-compatible value.\n* @returns whether both values contain the same JSON data.\n*/\nfunction deepEqualJson(a, b) {\n\tif (a === b) return true;\n\tif (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n\tif (Array.isArray(a) || Array.isArray(b)) {\n\t\tif (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n\t\treturn a.every((entry, index) => deepEqualJson(entry, b[index]));\n\t}\n\tconst left = a;\n\tconst right = b;\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => key in right && deepEqualJson(left[key], right[key]));\n}\n/**\n* Deep-freeze an object graph in place while leaving live AbortSignal objects mutable.\n* @param value - value to freeze.\n* @returns the same value after every reachable enumerable child is frozen.\n*/\nfunction deepFreeze(value) {\n\tconst seen = /* @__PURE__ */ new WeakSet();\n\tconst pending = [{\n\t\tkind: \"visit\",\n\t\tnode: value\n\t}];\n\twhile (pending.length > 0) {\n\t\tconst task = pending.pop();\n\t\t/* v8 ignore next -- the loop condition guarantees one pending task. */\n\t\tif (task === void 0) continue;\n\t\tif (task.kind === \"property\") {\n\t\t\tpending.push({\n\t\t\t\tkind: \"visit\",\n\t\t\t\tnode: task.source[task.key]\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tconst node = task.node;\n\t\tif (node === null || typeof node !== \"object\") continue;\n\t\tif (node instanceof AbortSignal) continue;\n\t\tif (seen.has(node)) continue;\n\t\tseen.add(node);\n\t\tObject.freeze(node);\n\t\tconst keys = Object.keys(node);\n\t\tfor (let index = keys.length - 1; index >= 0; index--) {\n\t\t\tconst key = keys[index];\n\t\t\t/* v8 ignore next -- the loop is bounded by the captured key count. */\n\t\t\tif (key === void 0) continue;\n\t\t\tpending.push({\n\t\t\t\tkind: \"property\",\n\t\t\t\tsource: node,\n\t\t\t\tkey\n\t\t\t});\n\t\t}\n\t}\n\treturn value;\n}\n/**\n* Weak-key lookup with a strongly retained iterable set of associated values.\n*\n* Each value must belong to only one key. The container performs no automatic\n* cleanup; owners delete associations or clear the container at lifecycle end.\n*/\nvar WeakMapWithValues = class {\n\tkeys = /* @__PURE__ */ new WeakMap();\n\tvalueSet = /* @__PURE__ */ new Set();\n\t/** Live strongly retained values in insertion order. */\n\tvalues = this.valueSet;\n\t/**\n\t* Read the value associated with a key.\n\t* @param key - weakly held lookup key.\n\t* @returns the associated value, or absence.\n\t*/\n\tget(key) {\n\t\treturn this.keys.get(key);\n\t}\n\t/**\n\t* Test whether a key has an association.\n\t* @param key - weakly held lookup key.\n\t* @returns whether the key is present.\n\t*/\n\thas(key) {\n\t\treturn this.keys.has(key);\n\t}\n\t/**\n\t* Associate one key with one caller-unique value.\n\t* @param key - weakly held lookup key.\n\t* @param value - strongly retained value that belongs to no other key.\n\t* @returns this container.\n\t*/\n\tset(key, value) {\n\t\tif (this.keys.has(key)) {\n\t\t\tconst previous = this.keys.get(key);\n\t\t\tif (previous === value) return this;\n\t\t\tthis.valueSet.delete(previous);\n\t\t}\n\t\tthis.keys.set(key, value);\n\t\tthis.valueSet.add(value);\n\t\treturn this;\n\t}\n\t/**\n\t* Remove one association and its strongly retained value.\n\t* @param key - weakly held lookup key.\n\t* @returns whether an association was removed.\n\t*/\n\tdelete(key) {\n\t\tif (!this.keys.has(key)) return false;\n\t\tconst value = this.keys.get(key);\n\t\tconst deleted = this.keys.delete(key);\n\t\tthis.valueSet.delete(value);\n\t\treturn deleted;\n\t}\n\t/** Remove every association and strongly retained value. */\n\tclear() {\n\t\tthis.keys = /* @__PURE__ */ new WeakMap();\n\t\tthis.valueSet.clear();\n\t}\n};\n//#endregion\nexport { PartialArguments, WeakMapWithValues, assertNever, deepEqualJson, deepFreeze, isJsonValue, snapshotJsonValue };\n","import type { AssistantBlock } from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/**\n * Test whether Assistant blocks contain a user-facing reply rather than only\n * reasoning or Tool-call protocol material.\n * @param blocks - Assistant content blocks.\n * @returns whether the blocks contain visible reply content.\n */\nexport function hasAssistantReplyContent(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some((block) => {\n if (block.kind === 'reasoning' || block.kind === 'tool-call') return false\n if (block.kind === 'text') return block.text.trim() !== ''\n return true\n })\n}\n","import type { ChatNode } from './chat-nodes.ts'\n\n/** Current process range and finalized answer boundary derived from one Turn. */\nexport interface TurnProcessSpec {\n readonly turn: number\n /** Stable control-node anchor source, including currently ineligible evidence. */\n readonly controlAnchorSeq: number\n readonly processStartSeq: number\n readonly answerAnchorSeq: number | null\n readonly answerStep: number | null\n readonly inlineReasoning: boolean\n /** Reply-bearing durable Assistant messages before the final answer. */\n readonly messageCount: number\n /** Durable non-subagent Tool calls recorded by this Turn. */\n readonly toolCallCount: number\n /** Tool calls whose configured name identifies a subagent delegation. */\n readonly subagentCount: number\n}\n\n/**\n * Compare immutable Turn-process specifications by their published fields.\n * @param left - previous specification.\n * @param right - next specification.\n * @returns whether both values describe the same process presentation.\n */\nexport function sameTurnProcessSpec(left: TurnProcessSpec, right: TurnProcessSpec): boolean {\n return left.turn === right.turn\n && left.controlAnchorSeq === right.controlAnchorSeq\n && left.processStartSeq === right.processStartSeq\n && left.answerAnchorSeq === right.answerAnchorSeq\n && left.answerStep === right.answerStep\n && left.inlineReasoning === right.inlineReasoning\n && left.messageCount === right.messageCount\n && left.toolCallCount === right.toolCallCount\n && left.subagentCount === right.subagentCount\n}\n\n/**\n * Recognize the shipped subagent delegation name and its configured variants.\n * Control tools use distinct names such as `send_message` and `list_agents`.\n * @param name - durable Tool-call name.\n * @returns whether the call creates or forks a subagent.\n */\nexport function isSubagentDelegationTool(name: string): boolean {\n return name === 'subagent' || name.startsWith('subagent_')\n}\n\n/**\n * Keep live, stopped, and failed Turns open.\n * @param node - Node carrying the owning Turn.\n * @returns whether whole-Turn collapse is unavailable.\n */\nexport function turnProcessAlwaysOpen(node: ChatNode | undefined): boolean {\n const location = node?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return false\n const reason = location.turn.end?.data.reason.kind\n return location.turn.status === 'open' || reason === 'aborted' || reason === 'interrupted' || reason === 'error'\n}\n","/** Per-Session Chat view store. */\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'\nimport type { ChatStoreState, TurnProcessViewEntry } from './contract/store.ts'\nimport type { TurnProcessSpec } from './contract/turn-process.ts'\n\ntype ChatActions = {\n setTurnProcessOpen: (\n draft: ChatStoreState,\n turn: number,\n answerStep: number,\n open: boolean,\n ) => void\n}\n\n/**\n * Resolve the manual disclosure choice for one Turn.\n * @param state - Chat store snapshot.\n * @param turn - owning Turn.\n * @returns the Turn's stored entry, when present.\n */\nexport function storedTurnProcessEntry(\n state: Readonly<ChatStoreState>,\n turn: number,\n): Readonly<TurnProcessViewEntry> | undefined {\n return state.turnProcesses.find(entry => entry.turn === turn)\n}\n\n/**\n * Whether a foldable Turn's process is open: the reader's choice for the current answer generation\n * wins; otherwise the latest completed Turn stays open until the next input, and older Turns fold.\n * @param state - Chat store snapshot.\n * @param spec - the Turn's process specification.\n * @param defaultOpen - whether this Turn is exempt from automatic folding.\n * @returns the effective open state.\n */\nexport function turnProcessOpen(\n state: Readonly<ChatStoreState>,\n spec: Pick<TurnProcessSpec, 'turn' | 'answerStep'>,\n defaultOpen: boolean,\n): boolean {\n const stored = storedTurnProcessEntry(state, spec.turn)\n if (stored === undefined || stored.answerStep !== (spec.answerStep ?? 0)) return defaultOpen\n return stored.collapsed !== true\n}\n\n/**\n * Create the Chat view store handle.\n * @returns a handle instantiated once per rendered Session scope.\n */\nexport function createChatStore(): EngineStoreHandle<ChatStoreState, ChatActions> {\n return defineStore({\n init: (): ChatStoreState => ({ turnProcesses: [] }),\n actions: {\n setTurnProcessOpen: (draft, turn, answerStep, open) => {\n const index = draft.turnProcesses.findIndex(entry => entry.turn === turn)\n const next = (open ? { turn, answerStep } : { turn, answerStep, collapsed: true }) satisfies TurnProcessViewEntry\n if (index < 0) draft.turnProcesses.push(next)\n else draft.turnProcesses[index] = next\n },\n },\n })\n}\n","import { memo, useCallback, useEffect, useMemo, useState } from 'react'\nimport { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConversationLocationDataStore, ConversationTurnDataMap } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatNodeHookContext, ChatNodeOwnerProps, ChatFlowSlotProps, UsePresentation } from '../contract/slots.ts'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatNodeStore } from '../contract/snapshot.ts'\nimport { isAtOrOutside } from '../contract/group-tree.ts'\nimport { turnProcessAlwaysOpen } from '../contract/turn-process.ts'\nimport { turnProcessOpen } from '../stores.ts'\nimport { hiddenOrCollapsing } from './flow-motion.ts'\nimport css from './ChatView.module.css'\n\ninterface ChatNodeSeatProps extends ChatNodeOwnerProps {\n readonly nodeKey: string\n /** A replaced Builder must rebind keyed hooks even when references and keys survive. */\n readonly nodeStore: ChatNodeStore\n readonly useChatNode: ChatFlowSlotProps['useChatNode']\n readonly useChatNodeProcess: ChatFlowSlotProps['useChatNodeProcess']\n readonly usePresentation: UsePresentation\n readonly useStore: ChatFlowSlotProps['useStore']\n readonly actions: ChatFlowSlotProps['actions']\n readonly renderSlot: ChatFlowSlotProps['renderSlot']\n readonly t: ChatFlowSlotProps['t']\n readonly useChatNodeBottom: ChatFlowSlotProps['useChatNodeBottom']\n readonly deferCollapse: boolean\n readonly useGroupAction: ChatFlowSlotProps['useGroupAction']\n}\n\ntype RoutedChatNodeOwner = {\n [Kind in ChatNode['kind']]: ChatNodeOwnerProps & { readonly node: ChatNode<Kind> }\n}[ChatNode['kind']]\n\nfunction turnDataOf(node: ChatNode | undefined): ConversationLocationDataStore<ConversationTurnDataMap> | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.data : undefined\n}\n\nfunction turnOf(node: ChatNode | undefined): number | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.turn : undefined\n}\n\n/**\n * Subscribe, apply Turn-process visibility, and dispatch one stable Context key.\n * Policy reads select this seat's own conclusion, so a mode change re-renders\n * only seats whose visibility actually changes.\n */\nexport const ChatNodeSeat = memo(function ChatNodeSeat({\n nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation,\n cwd, openFile, inspectCall, forkAt,\n loadImage, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction,\n}: ChatNodeSeatProps) {\n const bottom = useChatNodeBottom(nodeKey)\n const node = useChatNode(nodeKey)\n const routedNode = node as ChatNode | undefined\n const turn = turnOf(routedNode)\n const processPresentation = useChatNodeProcess(nodeKey)\n const processSpec = processPresentation?.spec\n const storedOpen = useStore(state => processSpec !== undefined\n && turnProcessOpen(state, processSpec, bottom === true && deferCollapse))\n const liveProcess = processPresentation !== undefined && !processPresentation.turnClosed\n const interleavedInput = processPresentation?.hasInterleavedInput === true\n const alwaysOpen = liveProcess || interleavedInput || turnProcessAlwaysOpen(routedNode)\n const processOpen = alwaysOpen || storedOpen\n const setOpen = useCallback((open: boolean) => {\n if (processSpec !== undefined && !alwaysOpen) {\n actions.setTurnProcessOpen(processSpec.turn, processSpec.answerStep ?? 0, open)\n }\n }, [actions, processSpec, alwaysOpen])\n const foldCompleted = usePresentation(policy => policy.foldCompletedTurns)\n const keepReplies = usePresentation(policy => policy.foldedReplies === 'all')\n // A loaded end makes a partial historical Turn eligible without its start.\n const processWindowReady = processSpec !== undefined\n && processPresentation !== undefined\n && foldCompleted\n && processPresentation.turn === processSpec.turn\n && (processPresentation.turnStarted || processPresentation.turnClosed)\n // With every reply kept, an Assistant reply stays outside whole-Turn folding; its reasoning remains process content.\n const replyRow = keepReplies\n && routedNode?.kind === 'assistant-step'\n && groupPart !== 'reasoning'\n && hasAssistantReplyContent(routedNode.data.blocks)\n const processMember = routedNode !== undefined\n && processWindowReady\n && !replyRow\n && !isAtOrOutside(routedNode, 'turn')\n && routedNode.anchorSeq >= processSpec.processStartSeq\n && (liveProcess || processSpec.answerAnchorSeq === null || routedNode.anchorSeq < processSpec.answerAnchorSeq\n || (groupPart === 'reasoning' && routedNode.kind === 'assistant-step' && routedNode.data.step === processSpec.answerStep))\n const processAnswer = routedNode !== undefined\n && processWindowReady\n && !liveProcess\n && groupPart !== 'reasoning'\n && routedNode.kind === 'assistant-step'\n && routedNode.data.step === processSpec.answerStep\n const ownsDisclosure = routedNode?.kind === 'turn-process' || processAnswer || replyRow\n const foldable = processWindowReady\n && (liveProcess || processMember || ownsDisclosure)\n const turnProcess = useMemo(() => processSpec === undefined\n ? undefined\n : {\n spec: processSpec,\n foldable,\n hasContent: !interleavedInput && (processSpec.inlineReasoning || (keepReplies\n ? processPresentation?.hasNonReplyProcess === true\n : processPresentation?.hasExternalProcess === true)),\n open: processOpen,\n setOpen,\n }, [\n foldable, interleavedInput, keepReplies, processOpen, processSpec,\n processPresentation?.hasExternalProcess, processPresentation?.hasNonReplyProcess, setOpen,\n ])\n const controllerInactive = routedNode?.kind === 'turn-process'\n && foldCompleted && !foldable\n const processHidden = controllerInactive || (foldable && processMember && !processOpen)\n const revealProcess = useCallback(() => {\n if (processMember) setOpen(true)\n }, [processMember, setOpen])\n const wrapperRef = useGroupAction(processHidden, revealProcess)\n const [disclosureReset] = useState(() => createSnapshotStore(0))\n const turnData = turnDataOf(routedNode)\n const hookContext = useMemo<ChatNodeHookContext>(\n () => ({ turnData, disclosureReset, useGroupAction }), [turnData, disclosureReset, useGroupAction],\n )\n useEffect(() => {\n if (processMember && processHidden && wrapperRef.current !== null && hiddenOrCollapsing(wrapperRef.current)) {\n disclosureReset.set(disclosureReset.getSnapshot() + 1)\n }\n }, [processMember, processHidden, wrapperRef, disclosureReset])\n const owner = useMemo<ChatNodeOwnerProps | null>(() => node === undefined\n ? null\n : {\n ...groupPart === undefined ? {} : { groupPart },\n cwd,\n openFile,\n inspectCall,\n forkAt,\n loadImage,\n turnProcess,\n }, [\n node, groupPart, cwd, openFile, inspectCall, forkAt,\n loadImage, turnProcess,\n ])\n if (routedNode === undefined || owner === null) return null\n // Runtime dispatch owns the correlation: every Node's discriminant is the\n // keyed-slot entry passed alongside that same Node. TypeScript does not\n // distribute an object containing a union into a union of objects itself.\n const routedOwner = { ...owner, node: routedNode } as RoutedChatNodeOwner\n const flowKey = groupPart === undefined || groupPart === 'response' ? routedNode.key : JSON.stringify([routedNode.key, groupPart])\n return (\n <div\n ref={wrapperRef}\n className={css.flowItem}\n data-chat-anchor-key={flowKey}\n data-chat-flow-key={flowKey}\n data-chat-paging-anchor={routedNode.kind !== 'turn-process' || undefined}\n data-chat-node-key={routedNode.key}\n data-chat-group-part={groupPart}\n data-chat-flow-kind={routedNode.kind}\n data-chat-turn={turn}\n data-turn-process-member={processMember || undefined}\n data-turn-process-hidden={processHidden || undefined}\n >\n {renderSlot('conversation.chat.node', routedOwner, {\n entryKey: routedNode.kind,\n hookContext,\n fallback: (\n <JsonBlock\n label={t('message.unknownSurface', { type: routedNode.kind })}\n payload={routedNode.data}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n ),\n })}\n </div>\n )\n})\n","/** Stable React identities for the two grouping reference kinds. */\nimport type { RenderEntry } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { assertNever } from '@deepseek-ai/dsh-util-values'\n\n/**\n * Identify a rendering position independently of presentation mode.\n * @param entry - mode-independent rendering reference.\n * @returns its collision-free React key.\n */\nexport function chatRenderKey(entry: RenderEntry): string {\n switch (entry.kind) {\n case 'node': return JSON.stringify(['node', entry.key, entry.groupPart ?? null])\n case 'group': return JSON.stringify(['group', entry.key])\n default: return assertNever(entry)\n }\n}\n","/** Localized titles for projected step-process activity. */\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ProcessActivitySummary } from '../contract/process-groups.ts'\n\n/**\n * Compose a closed group's localized title from its top three categories without counts.\n * @param summary - ranked work and phase evidence for this range.\n * @param t - Chat namespace translator.\n * @returns the secondary disclosure title.\n */\nexport function processTitle(\n summary: ProcessActivitySummary,\n t: ChatViewSlotProps['t'],\n): string {\n const labels = summary.counts.slice(0, 3).map(({ kind }) => t(`message.stepProcess.done.${kind}`))\n const first = labels[0]\n if (first === undefined) return t('message.stepProcess.done.thinking')\n const continuation = (label: string): string => label.charAt(0).toLowerCase() + label.slice(1)\n const second = labels[1]\n if (second === undefined) return first\n if (labels.length === 2) {\n const prefix = t('message.stepProcess.sharedPrefix')\n const shared = prefix !== '' && first.startsWith(prefix) && second.startsWith(prefix)\n return t('message.stepProcess.joinTwo', { first, second: continuation(shared ? second.slice(prefix.length) : second) })\n }\n const title = [first, ...labels.slice(1).map(continuation)].join(t('message.stepProcess.comma'))\n return summary.counts.length > 3 ? t('message.stepProcess.more', { title }) : title\n}\n","/** Bind independent disclosure state to a Chat seat's reset source. */\nimport { useCallback, useState, useSyncExternalStore } from 'react'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { UseDisclosure } from '../contract/slots.ts'\n\n/**\n * Own one initially collapsed disclosure without an external subscription.\n * @param version - reset generation; unchanged generations retain local open state.\n * @returns the open state, an explicit setter, and a toggle action.\n */\nexport function useDisclosure(version = 0): ReturnType<UseDisclosure> {\n const [expandedVersion, setExpandedVersion] = useState<number | null>(null)\n const expanded = expandedVersion === version\n const setExpanded = useCallback((open: boolean) => {\n setExpandedVersion(open ? version : null)\n }, [version])\n const toggle = useCallback(() => {\n setExpandedVersion(previous => previous === version ? null : version)\n }, [version])\n return { expanded, setExpanded, toggle }\n}\n\n/**\n * Bind a Hook without subscribing until a component calls it.\n * @param reset - stable source whose version advances when the seat is hidden by its Turn.\n * @returns a Hook with independent open state for each invocation.\n */\nexport function bindDisclosure(reset: ObservableSnapshot<number>): UseDisclosure {\n const subscribe = (listener: () => void) => reset.subscribe(listener)\n const getSnapshot = () => reset.getSnapshot()\n return function useBoundDisclosure() {\n const version = useSyncExternalStore(subscribe, getSnapshot)\n return useDisclosure(version)\n }\n}\n","/** Capped process-group scrolling and fades over the shared follow controller. */\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState, type DOMAttributes, type KeyboardEvent, type RefObject } from 'react'\nimport { scrollMetrics, useScrollFollow } from './use-scroll-follow.ts'\n\ninterface ScrollEdges { readonly canScrollUp: boolean; readonly canScrollDown: boolean }\nconst AT_REST: ScrollEdges = { canScrollUp: false, canScrollDown: false }\nconst SCROLL_KEYS = new Set(['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '])\n\n/**\n * Observe one group's body and content without coupling its follow intent to the outer transcript.\n * Wheel, touchstart, any pointerdown, and unprevented scroll keys interrupt active animations,\n * including events from editable controls; subsequent position sampling determines follow intent.\n * @param bodyRef - capped scrolling body.\n * @param contentRef - uncapped content whose size reports growth.\n * @param open - local disclosure state.\n * @param grouped - whether the display mode retains the group's height cap.\n * @returns edge fades, DOM event bindings, and one-shot positioning for manual opening.\n */\nexport function useProcessScroll(\n bodyRef: RefObject<HTMLDivElement>, contentRef: RefObject<HTMLDivElement>, open: boolean, grouped: boolean,\n): {\n edges: ScrollEdges\n events: Pick<DOMAttributes<HTMLDivElement>, 'onScroll' | 'onWheel' | 'onTouchStart' | 'onPointerDown' | 'onKeyDown'>\n initialize: (position: 'top' | 'bottom') => void\n} {\n const follow = useScrollFollow(false, 1)\n const initialPosition = useRef<'top' | 'bottom' | null>(null)\n const [edges, setEdges] = useState<ScrollEdges>(AT_REST)\n const initialize = useCallback((position: 'top' | 'bottom') => { initialPosition.current = position }, [])\n const sync = useCallback((cause: 'resize' | 'scroll' | 'scrollend') => {\n const body = bodyRef.current\n let next = AT_REST\n if (body !== null && body.closest('[hidden], [data-group-expanded-mode]') === null) {\n let metrics = scrollMetrics(body)\n const initial = cause === 'resize' ? initialPosition.current : null\n if (initial !== null) {\n metrics = follow.jump(body, metrics, initial === 'bottom' ? metrics.floor : 0)\n if (initial === 'top') follow.setFollowing(false)\n initialPosition.current = null\n } else {\n const wasAnimating = follow.animating\n if (cause === 'scrollend') follow.settle(metrics)\n else follow.sample(metrics)\n if (follow.active && (cause === 'resize' || (cause === 'scrollend' && wasAnimating))) {\n metrics = follow.toBottom(body, metrics, 'smooth')\n }\n }\n next = { canScrollUp: metrics.top > 1, canScrollDown: metrics.top < metrics.floor - 1 }\n } else follow.reset()\n setEdges(previous => previous.canScrollUp === next.canScrollUp && previous.canScrollDown === next.canScrollDown\n ? previous : next)\n }, [bodyRef, follow])\n const interrupt = useCallback(() => {\n const body = bodyRef.current\n if (body !== null && follow.animating) follow.interrupt(body, scrollMetrics(body))\n }, [bodyRef, follow])\n const events = useMemo(() => ({\n onScroll: () => { sync('scroll') },\n onWheel: interrupt,\n onTouchStart: interrupt,\n onPointerDown: interrupt,\n onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => {\n if (!event.defaultPrevented && SCROLL_KEYS.has(event.key)) interrupt()\n },\n }), [interrupt, sync])\n\n useLayoutEffect(() => {\n interrupt()\n follow.reset()\n if (!grouped || !open) initialPosition.current = null\n }, [follow, grouped, interrupt, open])\n useLayoutEffect(() => {\n const body = bodyRef.current\n if (body === null || !open || typeof ResizeObserver === 'undefined') return\n const unbind = follow.bind(body)\n const observer = new ResizeObserver(() => { sync('resize') })\n const onScrollEnd = (event: Event): void => { if (event.target === body) sync('scrollend') }\n body.addEventListener('scrollend', onScrollEnd)\n observer.observe(body)\n if (contentRef.current !== null) observer.observe(contentRef.current)\n return () => {\n unbind()\n observer.disconnect()\n body.removeEventListener('scrollend', onScrollEnd)\n }\n }, [bodyRef, contentRef, follow, open, sync])\n return { edges, events, initialize }\n}\n","/** Stable process container; display policy changes visibility, never member parents. */\nimport { memo, useCallback, useEffect, useId, useRef, useState, type ComponentProps, type ReactNode } from 'react'\nimport {\n IconAgentPresetOutlineRegular, IconApiOutlineRegular, IconBrowseOutlineRegular, IconChevronDownOutlineRegular,\n IconChevronUpOutlineRegular, IconCodeOutlineRegular, IconContextInjectionOutlineRegular, IconEditOutlineRegular,\n IconGlobeOutlineRegular, IconPlanOutlineRegular, IconQuestionOutlineRegular, IconSearchOutlineRegular, IconSparkleRegular,\n IconThinkOutlineRegular, TextShimmer,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { GroupKey, NodeReference } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ProcessActivity, RunningProcessActivity } from '../contract/process-groups.ts'\nimport type { ChatStoreState } from '../contract/store.ts'\nimport type { ChatFlowSlotProps } from '../contract/slots.ts'\nimport { turnProcessOpen } from '../stores.ts'\nimport { ChatNodeSeat } from './ChatNodeSeat.tsx'\nimport { hiddenOrCollapsing } from './flow-motion.ts'\nimport { chatRenderKey } from './render-entry.ts'\nimport { processTitle } from './step-process.ts'\nimport { useDisclosure } from './use-disclosure.ts'\nimport { useProcessScroll } from './use-process-scroll.ts'\nimport css from './ChatGroupSeat.module.css'\n\ntype SeatProps = Omit<ComponentProps<typeof ChatNodeSeat>, 'nodeKey' | 'groupPart'>\ntype ChatGroupSeatProps = SeatProps & {\n readonly groupKey: GroupKey\n readonly useChatGroup: ChatFlowSlotProps['useChatGroup']\n readonly useGroupHeaderAction: ChatFlowSlotProps['useGroupHeaderAction']\n}\nconst PROCESS_TITLE_MINIMUM_MS = 150\n\ntype ProcessTitleActivity = ProcessActivity | 'thinking'\n\ninterface LiveProcessTitle {\n readonly activity: RunningProcessActivity | 'thinking'\n readonly detail: string\n readonly preparing: boolean\n}\n\nconst PROCESS_ICONS: Record<ProcessTitleActivity, ReactNode> = {\n thinking: <IconThinkOutlineRegular />,\n read: <IconBrowseOutlineRegular size={14} />,\n readImage: <IconBrowseOutlineRegular size={14} />,\n search: <IconSearchOutlineRegular size={14} />,\n edit: <IconEditOutlineRegular size={14} />,\n write: <IconEditOutlineRegular size={14} />,\n commands: <IconApiOutlineRegular />,\n code: <IconCodeOutlineRegular size={14} />,\n webSearch: <IconGlobeOutlineRegular />,\n webFetch: <IconBrowseOutlineRegular size={14} />,\n subagents: <IconAgentPresetOutlineRegular size={14} />,\n plan: <IconPlanOutlineRegular />,\n questions: <IconQuestionOutlineRegular />,\n tools: <IconSparkleRegular size={14} />,\n context: <IconContextInjectionOutlineRegular size={14} />,\n}\n\nfunction sameLiveProcessTitle(left: LiveProcessTitle, right: LiveProcessTitle): boolean {\n return left.activity === right.activity && left.detail === right.detail && left.preparing === right.preparing\n}\n\nfunction useStableLiveProcessTitle(desired: LiveProcessTitle, active: boolean): LiveProcessTitle {\n const [displayed, setDisplayed] = useState(desired)\n const displayedRef = useRef(displayed)\n const desiredRef = useRef(desired)\n const displayedAtRef = useRef(Date.now())\n useEffect(() => {\n desiredRef.current = desired\n if (!active || sameLiveProcessTitle(displayedRef.current, desired)) return\n const remaining = PROCESS_TITLE_MINIMUM_MS - (Date.now() - displayedAtRef.current)\n const commit = (): void => {\n const next = desiredRef.current\n displayedRef.current = next\n displayedAtRef.current = Date.now()\n setDisplayed(next)\n }\n if (remaining <= 0) {\n commit()\n return\n }\n const timer = setTimeout(commit, remaining)\n return () => { clearTimeout(timer) }\n }, [active, desired.activity, desired.detail, desired.preparing])\n return active ? displayed : desired\n}\n\n\nconst GroupMembers = memo(function GroupMembers({ members, ...props }: SeatProps & {\n readonly members: readonly NodeReference[]\n}) {\n return members.map(member => <ChatNodeSeat {...props} key={chatRenderKey(member)} nodeKey={member.key}\n {...member.groupPart === undefined ? {} : { groupPart: member.groupPart }} />)\n})\n\nconst ProcessGroupHeader = memo(function ProcessGroupHeader({ groupKey, useChatGroup, usePresentation, t, open, bodyId, toggle }: {\n readonly groupKey: GroupKey\n readonly useChatGroup: ChatFlowSlotProps['useChatGroup']\n readonly usePresentation: ChatFlowSlotProps['usePresentation']\n readonly t: ChatFlowSlotProps['t']\n readonly open: boolean\n readonly bodyId: string\n readonly toggle: () => void\n}) {\n const data = useChatGroup(groupKey, group => group?.data)\n const detailed = usePresentation(policy => data?.closed === false && policy.liveProcessDetail)\n const live = useStableLiveProcessTitle({\n activity: data?.summary.running ?? 'thinking',\n detail: data?.summary.runningDetail ?? '',\n preparing: data?.summary.preparing === true,\n }, data !== undefined && !data.closed)\n if (data === undefined) return null\n const label = data.closed ? processTitle(data.summary, t)\n : live.preparing ? t(`message.stepProcess.prepare.${live.activity === 'thinking' ? 'tools' : live.activity}`)\n : t(`message.stepProcess.${live.activity}`)\n const detail = detailed && !data.closed ? live.detail : ''\n const title = detail === '' ? label : `${label}${t('message.turnProcess.separator')}${detail}`\n const activity = data.closed ? data.summary.counts[0]?.kind ?? 'thinking' : live.activity\n return (\n <button type=\"button\" className={css.title} aria-expanded={open} aria-controls={bodyId}\n data-process-activity={activity} onClick={(event) => { event.currentTarget.focus(); toggle() }}>\n <span className={css.leading} aria-hidden=\"true\">\n <span className={css.activityIcon} data-step-process-icon>{PROCESS_ICONS[activity]}</span>\n <span className={css.chevron} data-step-process-chevron>\n {open ? <IconChevronUpOutlineRegular /> : <IconChevronDownOutlineRegular />}\n </span>\n </span>\n <TextShimmer active={!data.closed}>\n <TextShimmer className={css.label}>{title}</TextShimmer>\n </TextShimmer>\n </button>\n )\n})\n\n/** Render a process group with local disclosure and the existing outer-Turn visibility. */\nexport const ChatGroupSeat = memo(function ChatGroupSeat({ groupKey, useChatGroup, useGroupHeaderAction, ...props }: ChatGroupSeatProps) {\n const members = useChatGroup(groupKey, group => group?.members)\n const turn = useChatGroup(groupKey, group => group?.data.turn)\n const closed = useChatGroup(groupKey, group => group?.data.closed)\n const foldCompleted = props.usePresentation(policy => policy.foldCompletedTurns)\n const { expanded: open, setExpanded: setOpen } = useDisclosure()\n const firstKey = members?.[0]?.key ?? ''\n const bottom = props.useChatNodeBottom(firstKey)\n const deferCollapse = bottom === true && props.deferCollapse\n const presentation = props.useChatNodeProcess(firstKey)\n const turnLocation = props.useChatNode(firstKey, (node) => {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n })\n // Detailed keeps the latest completed Turn flat, like a running one, until the next input.\n const grouped = props.usePresentation(policy => policy.stepGrouping === 'collapsed'\n || (policy.stepGrouping === 'history' && turnLocation?.status !== 'open' && !deferCollapse))\n const reason = turnLocation?.end?.data.reason.kind\n const alwaysOpen = presentation?.turnClosed === false || presentation?.hasInterleavedInput === true\n || reason === 'aborted' || reason === 'interrupted' || reason === 'error'\n const spec = presentation?.spec\n const selectOpen = useCallback((state: Readonly<ChatStoreState>) => spec !== undefined\n && turnProcessOpen(state, spec, deferCollapse), [spec, deferCollapse])\n const storedOpen = props.useStore(selectOpen)\n const outerHidden = foldCompleted && presentation?.turnClosed === true && spec !== undefined\n && !alwaysOpen && !storedOpen\n const revealOuter = useCallback(() => {\n if (spec !== undefined && !alwaysOpen) props.actions.setTurnProcessOpen(spec.turn, spec.answerStep ?? 0, true)\n }, [props.actions, spec, alwaysOpen])\n const rootRef = props.useGroupAction(outerHidden, revealOuter)\n // The header appears when a flat latest Turn becomes historical; it grows on the fold clock while the\n // body closes. A group whose whole Turn is folding never shows one in the frame it starts closing.\n const headerRef = useRef<HTMLDivElement>(null)\n const deferCompletedTurns = props.usePresentation(policy => policy.collapseTiming === 'next-input')\n useGroupHeaderAction(headerRef, !grouped || (deferCompletedTurns && outerHidden))\n useEffect(() => {\n if (outerHidden && rootRef.current !== null && hiddenOrCollapsing(rootRef.current)) setOpen(false)\n }, [outerHidden, rootRef, setOpen])\n const reveal = useCallback(() => { setOpen(true) }, [setOpen])\n const bodyRef = props.useGroupAction(grouped && !open, reveal)\n const contentRef = useRef<HTMLDivElement>(null)\n const bodyId = useId()\n const { edges, events, initialize } = useProcessScroll(bodyRef, contentRef, open, grouped)\n const toggle = useCallback(() => {\n if (!open) initialize(closed === false ? 'bottom' : 'top')\n setOpen(!open)\n }, [closed, initialize, open, setOpen])\n // With next-input timing the height cap applies only to a group the reader opened. A closing body keeps\n // the cap it was last shown with, so the transition starts from what is on screen: a reader-opened group\n // closes from its cap, and a flat latest Turn becoming historical closes from its flat height.\n const shownCap = !grouped ? false : open ? true : undefined\n const [closingCap, setClosingCap] = useState(shownCap ?? true)\n if (shownCap !== undefined && shownCap !== closingCap) setClosingCap(shownCap)\n if (members === undefined) return null\n const capped = grouped && (!deferCompletedTurns || (shownCap ?? closingCap))\n const classes = [css.body, !capped ? css.expandedBody : '',\n capped && edges.canScrollUp ? css.fadeTop : '', capped && edges.canScrollDown ? css.fadeBottom : '']\n return (\n <div ref={rootRef} className={css.root} data-chat-group-key={groupKey}\n data-chat-flow-key={groupKey} data-chat-anchor-key={`group:${groupKey}`} data-chat-turn={turn}\n data-chat-paging-anchor={grouped && !open || undefined}\n data-step-process data-group-expanded-mode={!grouped || undefined}>\n <div ref={headerRef}>\n <ProcessGroupHeader groupKey={groupKey} useChatGroup={useChatGroup}\n usePresentation={props.usePresentation} t={props.t} open={open} bodyId={bodyId} toggle={toggle} />\n </div>\n <div ref={bodyRef} id={bodyId} className={classes.join(' ')} data-step-process-body\n data-scroll-up={edges.canScrollUp || undefined} data-scroll-down={edges.canScrollDown || undefined}\n {...events}>\n <div ref={contentRef} className={css.content} data-step-process-content data-chat-flow=\"\">\n <GroupMembers {...props} members={members} />\n </div>\n </div>\n </div>\n )\n})\n","// A compaction marker does not replace shadowed transcript rows. It is\n// expandable only when the current window includes its cited summary.\n\nimport { memo, useMemo, useState } from 'react'\nimport {\n IconApiOutlineRegular,\n IconChevronDownOutlineRegular,\n IconChevronRightOutlineRegular,\n MarkdownText,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport type { CompactionSummaryNode } from '../contract/snapshot.ts'\nimport css from './MessageItem.module.css'\n\ninterface CompactionItemProps {\n node: CompactionSummaryNode\n /** Optional command title for a manual compaction folded into this marker. */\n title?: string\n /** Command settlement text used when structured compaction counts are unavailable. */\n fallbackSummary?: string | null\n /** The owning view's locale seat. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Renders the model-history compaction marker.\n * @param props - the marker node off the snapshot cache.\n * @returns the marker row, with the summary disclosure when one is available.\n */\nexport const CompactionItem = memo(function CompactionItem({\n node,\n title,\n fallbackSummary,\n t,\n}: CompactionItemProps) {\n const [expanded, setExpanded] = useState(false)\n const labels = useMemo(() => markdownLabels(t), [t])\n const expandable = node.summary !== null\n const open = expandable && expanded\n const summary = node.shadowedItemCount !== null && node.shadowedTokenCount !== null\n ? t('message.compaction.completed', {\n items: node.shadowedItemCount,\n tokens: node.shadowedTokenCount,\n })\n : fallbackSummary\n ?? (expandable ? t('message.compaction.expand') : t('message.compaction.unavailable'))\n return (\n <div className={css.compactionRow}>\n <button\n type=\"button\"\n className={css.compactionButton}\n disabled={!expandable}\n aria-expanded={expandable ? open : undefined}\n onClick={() => { setExpanded(value => !value) }}\n >\n <span className={css.compactionLeading} aria-hidden>\n <span className={css.compactionContextIcon} data-compaction-icon=\"context\">\n <IconApiOutlineRegular />\n </span>\n <span\n className={css.compactionDisclosureIcon}\n data-compaction-disclosure={open ? 'expanded' : 'collapsed'}\n >\n {open ? <IconChevronDownOutlineRegular /> : <IconChevronRightOutlineRegular />}\n </span>\n </span>\n <span className={css.compactionTitle}>{title ?? t('message.compaction')}</span>\n <span className={css.compactionSep} aria-hidden />\n <span className={css.compactionSummary}>{summary}</span>\n </button>\n {open && node.summary !== null\n && <div className={css.compactionBody}><MarkdownText text={node.summary} labels={labels} /></div>}\n </div>\n )\n})\n","// Expanded bodies for the context disclosure, one per durable context form.\n// The producer declares the form; this module only chooses a presentation for\n// it. Every form falls back to OpaqueBody, which is the documented default for\n// an absent, unknown, or malformed form — a resumed or foreign log must render\n// even when this UI version has never seen its producer.\n\nimport type { ReactNode } from 'react'\nimport { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport type { KnownContextForm } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport css from './ContextBody.module.css'\n\n/** Model-facing text stays bounded at the disclosure, not at the producer. */\nconst MAX_CHARS = 20_000\n\n/** Rows a list body materializes before summarizing the remainder. */\nconst MAX_ENTRIES = 200\n\ntype Translate = ChatViewSlotProps['t']\n\n/** One durable source narrowed to the readable-record shape; null for anything else. */\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\n/** One run of the model-facing content: adjacent text, or one unknown block. */\ntype ContentRun = { text: string } | { block: unknown }\n\n/**\n * The content blocks as runs, IN THE ORDER the model received them.\n *\n * Adjacent text blocks join with no separator, matching how provider adapters\n * flatten them — inserting a line break would show the reader a line the model\n * never saw. An unknown block breaks the run and keeps its own fallback rather\n * than being hoisted past the text around it or vanishing; the block union is\n * merge-extensible, so a foreign log may interleave shapes this build does not\n * know.\n */\nfunction contentRuns(content: ContextMessageNode['content']): ContentRun[] {\n const runs: ContentRun[] = []\n for (const block of content) {\n if (block.type !== 'text') {\n runs.push({ block })\n continue\n }\n const last = runs[runs.length - 1]\n if (last !== undefined && 'text' in last) last.text += block.text\n else runs.push({ text: block.text })\n }\n return runs\n}\n\n/** Only the blocks this UI version does not know, for bodies that replace the text. */\nfunction unknownBlocks(content: ContextMessageNode['content']): unknown[] {\n return contentRuns(content).flatMap(run => 'block' in run ? [run.block] : [])\n}\n\n/** The model-facing text, truncated to the display bound. */\nfunction boundedText(text: string, t: Translate): string {\n return text.length > MAX_CHARS\n ? `${text.slice(0, MAX_CHARS)}\\n${t('json.truncated', { total: text.length })}`\n : text\n}\n\n/**\n * One source field rendered as a value row; nested shapes stay compact JSON.\n * Bounded on its own, because source fields are as unbounded as the text: an unknown\n * producer may record an arbitrarily large string or array.\n */\nfunction fieldValue(value: unknown, t: Translate): string {\n const text = typeof value === 'string'\n ? value\n : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value)\n return boundedText(text, t)\n}\n\n/**\n * Source fields as a key/value list. `kind` is always omitted because the\n * row header already names the producer. `form` is omitted only when a\n * dedicated body rendered for it — then the presentation the reader is looking\n * at IS that value. On the opaque fallback the declaration is kept, because\n * that is the one place a form this version cannot present would otherwise\n * disappear from the UI entirely.\n */\nfunction SourceFields({ source, formRendered, t }: {\n source: unknown\n formRendered: boolean\n t: Translate\n}): ReactNode {\n const record = asRecord(source)\n if (record === null) return null\n const hidden = formRendered ? ['kind', 'form'] : ['kind']\n const rows = Object.entries(record).filter(([key]) => !hidden.includes(key))\n if (rows.length === 0) return null\n return (\n <dl className={css.fields} data-context-fields>\n {rows.map(([key, value]) => (\n <div key={key} className={css.field}>\n <dt className={css.fieldKey}>{key}</dt>\n <dd className={css.fieldValue}>{fieldValue(value, t)}</dd>\n </div>\n ))}\n </dl>\n )\n}\n\n/**\n * Content blocks this UI version does not know, kept visible rather than\n * dropped: the block union is merge-extensible, so a newer or foreign log may\n * carry a shape this build has no presentation for.\n * @param props - The unrecognized blocks and the locale seat.\n * @returns One generic JSON block per unknown entry.\n */\nfunction UnknownBlocks({ blocks, t }: { blocks: readonly unknown[]; t: Translate }): ReactNode {\n return (\n <>\n {blocks.map((block, index) => (\n <JsonBlock\n key={index}\n label={t('message.unknownBlock')}\n payload={block}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n ))}\n </>\n )\n}\n\n/**\n * The model-facing content of one context, shared by every form that shows it:\n * the text with its real line breaks, then any block this UI version does not\n * know, which keeps its own fallback rather than vanishing.\n * @param props - Durable content and the locale seat.\n * @returns The content blocks as the model received them.\n */\nfunction ModelFacingContent({ content, t }: {\n content: ContextMessageNode['content']\n t: Translate\n}): ReactNode {\n return (\n <>\n {contentRuns(content).map((run, index) => ('text' in run\n ? run.text !== '' && (\n <pre key={index} className={css.text} data-context-text>{boundedText(run.text, t)}</pre>\n )\n : (\n <JsonBlock\n key={index}\n label={t('message.unknownBlock')}\n payload={run.block}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n )))}\n </>\n )\n}\n\n/**\n * Default presentation: the model-facing text as text, with its real line\n * breaks, and the remaining source fields beneath it. This is what every form\n * this UI version does not recognize renders as.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The opaque context body.\n */\nexport function OpaqueBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n return (\n <>\n <ModelFacingContent content={content} t={t} />\n <SourceFields source={source} formRendered={false} t={t} />\n </>\n )\n}\n\n/** One reconciled instruction file, as the durable source records it. */\ninterface InstructionChange {\n action: 'set' | 'replace' | 'remove'\n path: string\n digest?: string\n}\n\n/**\n * Instruction changes read off the source, or null when the record is not a\n * usable instruction list.\n *\n * The read is all-or-nothing: silently dropping one unreadable entry would show\n * a confident, incomplete file list for a log this version cannot fully read.\n * Paths are deduplicated in first-seen order, matching how the header label is\n * derived from the same array.\n */\nfunction instructionChanges(source: unknown): InstructionChange[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['changes']\n if (!Array.isArray(list)) return null\n const changes: InstructionChange[] = []\n const seen = new Set<string>()\n for (const entry of list as readonly unknown[]) {\n const change = asRecord(entry)\n if (change === null) return null\n const path = change['path']\n if (typeof path !== 'string' || path === '') return null\n const action = change['action']\n // The action decides which word the row shows, so an unrecognized one is\n // not a readable change — it would be presented as loaded or updated.\n if (action !== 'set' && action !== 'replace' && action !== 'remove') return null\n const digest = change['digest']\n if (seen.has(path)) continue\n seen.add(path)\n changes.push({ action, path, ...typeof digest === 'string' ? { digest } : {} })\n }\n return changes.length === 0 ? null : changes\n}\n\n/**\n * Locale key for one reconciled file. The baseline loads a file; a later delta\n * distinguishes a newly reconciled path from a rewritten one, which `set` and\n * `replace` already separate at the producer.\n * @param action - the durable change action.\n * @param baseline - whether this context is the startup/resume baseline.\n * @returns the key naming what happened to that file.\n */\nfunction instructionAction(\n action: InstructionChange['action'],\n baseline: boolean,\n): 'message.context.instructions.removed' | 'message.context.instructions.loaded'\n | 'message.context.instructions.added' | 'message.context.instructions.updated' {\n if (action === 'remove') return 'message.context.instructions.removed'\n if (baseline) return 'message.context.instructions.loaded'\n return action === 'set' ? 'message.context.instructions.added' : 'message.context.instructions.updated'\n}\n\n/**\n * `instructions` form: the files this context reconciled, then their text.\n *\n * The text keeps its `<system-reminder>` framing verbatim — the framing is part\n * of what the model read, so hiding it would misreport the request.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The instructions context body, or the opaque body when the change\n * list is unreadable.\n */\nexport function InstructionsBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const changes = instructionChanges(source)\n if (changes === null) return <OpaqueBody content={content} source={source} t={t} />\n const baseline = asRecord(source)?.['baseline'] === true\n return (\n <>\n <ul className={css.files} data-context-files>\n {changes.map(change => (\n <li key={change.path} className={css.file} title={change.digest}>\n <span className={css.filePath}>{change.path}</span>\n <span className={css.fileAction}>\n {t(instructionAction(change.action, baseline))}\n </span>\n </li>\n ))}\n </ul>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** One catalog entry, as the durable source records it. */\ninterface CatalogEntry {\n name: string\n description: string\n}\n\n/**\n * Catalog entries read off the source, or null when the record is not a usable\n * catalog. All-or-nothing for the same reason as the instruction list: this body\n * replaces the model-facing text, so a partial list would hide the only complete\n * account of what the model read.\n */\nfunction catalogEntries(source: unknown): CatalogEntry[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['entries']\n if (!Array.isArray(list)) return null\n const entries: CatalogEntry[] = []\n for (const item of list as readonly unknown[]) {\n const entry = asRecord(item)\n if (entry === null) return null\n const name = entry['name']\n const description = entry['description']\n if (typeof name !== 'string' || name === '' || typeof description !== 'string') return null\n entries.push({ name, description })\n }\n // An empty list is a real catalog: a replacement with no entries retires\n // every earlier name. Only an unreadable shape falls back.\n return entries\n}\n\n/**\n * `catalog` form: the published entries as a list, read from the source rather\n * than re-parsed out of the model-facing prose.\n *\n * A catalog whose source carries no usable entries falls through to the opaque\n * body, so an older or hand-edited log still shows its text.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The catalog context body, or the opaque body when the entry list is\n * unreadable.\n */\nexport function CatalogBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const entries = catalogEntries(source)\n if (entries === null) return <OpaqueBody content={content} source={source} t={t} />\n const update = asRecord(source)?.['update'] === true\n // Entry count is unbounded (a provider may publish any number of skills), and\n // the scrollport bounds height, not node count — so the list bounds itself.\n const shown = entries.slice(0, MAX_ENTRIES)\n const rest = unknownBlocks(content)\n return (\n <>\n {update && <p className={css.catalogNotice} data-context-catalog-update>{t('message.context.catalog.replaced')}</p>}\n <ul className={css.entries} data-context-entries>\n {shown.map((entry, index) => (\n // Index key: a hand-edited or foreign log may repeat a name, and a\n // duplicate React key would drop a row the model did see.\n <li key={index} className={css.entry}>\n <code className={css.entryName}>{entry.name}</code>\n <span className={css.entryDescription}>{entry.description}</span>\n </li>\n ))}\n </ul>\n {shown.length < entries.length && (\n <p className={css.catalogNotice} data-context-entries-truncated>\n {t('message.context.catalog.more', { count: entries.length - shown.length })}\n </p>\n )}\n {/* The block union is merge-extensible: a catalog message carrying an\n unknown block still shows it rather than dropping model-visible content. */}\n <UnknownBlocks blocks={rest} t={t} />\n </>\n )\n}\n\n/** One named contribution to a runtime snapshot, as the durable source records it. */\ninterface SnapshotSection {\n name: string\n text: string\n}\n\n/** Snapshot sections read off the source, or null when the record is unusable. */\nfunction snapshotSections(source: unknown): SnapshotSection[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['sections']\n if (!Array.isArray(list)) return null\n const sections: SnapshotSection[] = []\n for (const item of list as readonly unknown[]) {\n const section = asRecord(item)\n if (section === null) return null\n const name = section['name']\n const text = section['text']\n if (typeof name !== 'string' || name === '' || typeof text !== 'string') return null\n sections.push({ name, text })\n }\n return sections.length === 0 ? null : sections\n}\n\n/**\n * `snapshot` form: the named contributions this snapshot assembled, in order.\n *\n * The sections are the same bytes the model read, split at the boundaries the\n * producer assembled them on, so a reader sees which subsystem contributed\n * which state instead of one undifferentiated wall.\n *\n * One sentence of the model-facing text is NOT in any section: the producer's\n * framing line declaring that this snapshot supersedes earlier ones. Unlike the\n * `<system-reminder>` wrapper an instruction context carries — which wraps\n * content and cannot be separated from it — that line states the form's own\n * semantics, so the body states them as a caption instead of reprinting the\n * joined prose beside the sections it was split from.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The snapshot context body, or the opaque body when unreadable.\n */\nexport function SnapshotBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sections = snapshotSections(source)\n /* v8 ignore next -- contextBody reads the sections before choosing this body. */\n if (sections === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <p className={css.catalogNotice} data-context-snapshot-supersedes>\n {t('message.context.snapshot.supersedes')}\n </p>\n <dl className={css.sections} data-context-sections>\n {sections.map((section, index) => (\n <div key={index} className={css.section}>\n <dt className={css.sectionName}>{section.name}</dt>\n <dd className={css.sectionText}>{boundedText(section.text, t)}</dd>\n </div>\n ))}\n </dl>\n </>\n )\n}\n\n/**\n * `notice` form: what just happened, with the model-facing text beneath it.\n *\n * The one-line account also rides the collapsed row ({@link contextBody}), so a\n * notice is usually readable without expanding at all.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The notice context body.\n */\nexport function NoticeBody({ content, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n return <ModelFacingContent content={content} t={t} />\n}\n\n/**\n * `relay` form: which agent sent this, then what it said.\n *\n * The sender is an opaque session id; it is shown as a field rather than a\n * label, because this client cannot resolve it to a title.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The relay context body.\n */\nexport function RelayBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sender = relaySender(source)\n /* v8 ignore next -- contextBody resolves the sender before choosing this body. */\n if (sender === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <p className={css.relaySender} data-context-relay-sender>\n {t('message.context.relay.from', { session: sender })}\n </p>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** The sending agent's session id, or null when the record does not name one. */\nfunction relaySender(source: unknown): string | null {\n const sender = asRecord(source)?.['senderSessionId']\n return typeof sender === 'string' && sender !== '' ? sender : null\n}\n\n/** One recalled session, as the durable source records it. */\ninterface RecalledSession {\n label: string\n retained: number\n omitted: number\n truncated: boolean\n}\n\n/** Recalled sessions read off the source, or null when the record is unusable. */\nfunction recalledSessions(source: unknown): RecalledSession[] | null {\n const record = asRecord(source)\n const list = record === null ? undefined : record['references']\n if (!Array.isArray(list)) return null\n const sessions: RecalledSession[] = []\n for (const item of list as readonly unknown[]) {\n const reference = asRecord(item)\n if (reference === null) return null\n const label = reference['label']\n const retained = reference['retainedMessages']\n const omitted = reference['omittedMessages']\n const truncated = reference['truncated']\n // Completeness is the fact this card exists to report, so a reference that\n // cannot state it is not a readable recall — showing the label alone would\n // present a confident card over unknown loss.\n if (typeof label !== 'string' || label === ''\n || typeof retained !== 'number' || typeof omitted !== 'number'\n || typeof truncated !== 'boolean') return null\n sessions.push({ label, retained, omitted, truncated })\n }\n return sessions.length === 0 ? null : sessions\n}\n\n/**\n * `recall` form: which sessions this material came from and how much of each\n * survived the read, then the material itself.\n *\n * Completeness is the fact a reader needs first: recalled context is bounded on\n * the way in, so a card that hid the omitted count would overstate what the\n * model received.\n * @param props - Durable content, its source, and the locale seat.\n * @returns The recall context body, or the opaque body when unreadable.\n */\nexport function RecallBody({ content, source, t }: {\n content: ContextMessageNode['content']\n source: unknown\n t: Translate\n}): ReactNode {\n const sessions = recalledSessions(source)\n if (sessions === null) return <OpaqueBody content={content} source={source} t={t} />\n return (\n <>\n <ul className={css.recalls} data-context-recalls>\n {sessions.map((session, index) => (\n <li key={index} className={css.recall}>\n <span className={css.recallLabel}>{session.label}</span>\n <span className={css.recallCounts}>\n {t('message.context.recall.counts', {\n retained: session.retained,\n omitted: session.omitted,\n })}\n </span>\n {session.truncated && (\n <span className={css.recallCounts}>{t('message.context.recall.truncated')}</span>\n )}\n </li>\n ))}\n </ul>\n <ModelFacingContent content={content} t={t} />\n </>\n )\n}\n\n/** The one-line account a `notice` puts on its collapsed row, when it records one. */\nfunction noticeSummary(source: unknown): string | null {\n const summary = asRecord(source)?.['summary']\n return typeof summary === 'string' && summary !== '' ? summary : null\n}\n\n/**\n * Choose the body for one context node.\n *\n * Returns the form the body actually rendered as, which is not always the\n * declared one: a declared form whose fields are unreadable falls back to\n * opaque, and the caller labels the row with what it really shows.\n * `summary` is the collapsed row's one-line account, which only a `notice`\n * records: its whole point is being readable without expanding.\n * @param form - the producer-declared form projected onto the node.\n * @param props - durable content, its source, and the locale seat.\n * @returns the rendered form (null for opaque), its collapsed summary, and its body.\n */\nexport function contextBody(\n form: ContextMessageNode['form'],\n props: { content: ContextMessageNode['content']; source: unknown; t: Translate },\n): { rendered: KnownContextForm | null; summary: string | null; body: ReactNode } {\n const opaque = { rendered: null, summary: null, body: <OpaqueBody {...props} /> }\n switch (form) {\n case 'instructions':\n return instructionChanges(props.source) === null\n ? opaque\n : { rendered: 'instructions', summary: null, body: <InstructionsBody {...props} /> }\n case 'catalog':\n return catalogEntries(props.source) === null\n ? opaque\n : { rendered: 'catalog', summary: null, body: <CatalogBody {...props} /> }\n case 'snapshot':\n return snapshotSections(props.source) === null\n ? opaque\n : { rendered: 'snapshot', summary: null, body: <SnapshotBody {...props} /> }\n case 'notice': {\n const summary = noticeSummary(props.source)\n return summary === null\n ? opaque\n : { rendered: 'notice', summary, body: <NoticeBody {...props} /> }\n }\n case 'relay':\n return relaySender(props.source) === null\n ? opaque\n : { rendered: 'relay', summary: null, body: <RelayBody {...props} /> }\n case 'recall':\n return recalledSessions(props.source) === null\n ? opaque\n : { rendered: 'recall', summary: null, body: <RecallBody {...props} /> }\n case null:\n return opaque\n /* v8 ignore next 4 -- closed-union backstop; the compiler rejects a new\n KnownContextForm here rather than letting it degrade to opaque silently. */\n default: {\n const unreachable: never = form\n throw new Error(`unreachable context form: ${String(unreachable)}`)\n }\n }\n}\n","import { useState } from 'react'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconBrowseOutlineRegular, IconContextInjectionOutlineRegular, ReferenceIconRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport { contextBody } from './ContextBody.tsx'\nimport css from './ContextInjectionRow.module.css'\n\n/** Props for the logged non-user message presentation. */\nexport interface ContextInjectionRowProps {\n content: ContextMessageNode['content']\n source: ContextMessageNode['source']\n /** Role and producer name projected from the durable source. */\n producer: ContextMessageNode['producer']\n /** Producer-declared information form; null renders the opaque body. */\n form: ContextMessageNode['form']\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Render logged context with the Tool calls disclosure chrome from Figma.\n *\n * The header names the role the context plays and, beside it, the producer the\n * durable source identifies, so a reader can tell an injected skill catalog\n * from a workspace instruction file or a recalled session without expanding.\n * The expanded body follows the producer-declared form; an absent or unknown\n * form renders the opaque body.\n * @param props - Durable content, its projected producer role/name and form, and the locale seat.\n * @returns A collapsed context row with a bounded, form-specific body.\n */\nexport function ContextInjectionRow({ content, source, producer, form, t }: ContextInjectionRowProps) {\n const [open, setOpen] = useState(false)\n // Resolved rather than declared: a form whose fields are unreadable renders\n // the opaque body, and the marker must say what the row actually shows.\n const { rendered, summary, body } = contextBody(form, { content, source, t })\n\n const toolBlocks = content.length > 0\n && content.every(block => block.type === 'tool-addition' || block.type === 'tool-removal')\n ? content : undefined\n const added = toolBlocks?.flatMap(block => block.type === 'tool-addition' ? [block.toolName] : []) ?? []\n const removed = toolBlocks?.flatMap(block => block.type === 'tool-removal' ? [block.toolName] : []) ?? []\n const single = toolBlocks?.length === 1 ? toolBlocks[0] : undefined\n const toolSummary = toolBlocks === undefined || single !== undefined ? null\n : added.length > 0 && removed.length > 0\n ? t('message.toolsChanged', { added: added.length, removed: removed.length })\n : added.length > 0\n ? t('message.toolsAddedCount', { count: added.length })\n : t('message.toolsRemovedCount', { count: removed.length })\n\n return (\n <DisclosureRow\n className={css.root}\n icon={toolBlocks !== undefined ? <IconBrowseOutlineRegular size={14} /> : producer.role === 'recall'\n ? <span data-context-recall-icon><ReferenceIconRegular kind=\"session\" /></span>\n : <IconContextInjectionOutlineRegular size={14} />}\n chevronClassName={css.chevron}\n title={single !== undefined ? t(single.type === 'tool-addition' ? 'message.toolAdded' : 'message.toolRemoved', { name: single.toolName }) : t(toolBlocks !== undefined ? 'message.toolsUpdated' : producer.role === 'recall' ? 'message.contextRecall' : 'message.contextInjection')}\n collapsedContent={toolSummary !== null ? (\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.summary}>{toolSummary}</span>\n </>\n ) : toolBlocks !== undefined || producer.label === null ? undefined : (\n /* ToolRow's separator shape: an aria-hidden dot, so the accessible name\n stays the two readable parts and the two disclosure rows expose one\n name shape. A source that names no producer drops the dot with it. */\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.source} data-context-source>{producer.label}</span>\n {summary !== null && (\n <>\n <span className={css.sep} aria-hidden />\n <span className={css.summary} data-context-summary>{summary}</span>\n </>\n )}\n </>\n )}\n keepContentWhenOpen\n open={open && single === undefined}\n expandable={single === undefined}\n expandOnRowClick\n onToggle={() => { setOpen(value => !value) }}\n >\n <div className={css.body} data-context-injection-body data-context-form={rendered ?? undefined}>\n {toolBlocks === undefined ? body : (\n <div className={css.toolChanges}>\n {added.length > 0 && <div>{t('message.toolsAdded', { names: added.join(', ') })}</div>}\n {removed.length > 0 && <div>{t('message.toolsRemoved', { names: removed.join(', ') })}</div>}\n </div>\n )}\n </div>\n </DisclosureRow>\n )\n}\n","// Shared time-label helpers for user/assistant IconActions rows.\n\nimport type { Translate } from '@deepseek-ai/dsh-client-ui-slots'\n\n/** The date-template share of the conversation dictionary the clock consumes. */\nexport type ClockTranslate = Translate<'clock.md' | 'clock.ymd'>\n\n/** The elapsed-duration share of the conversation dictionary. */\nexport type RunDurationTranslate =\n Translate<'duration.secondUnit' | 'duration.minuteUnit' | 'duration.hourUnit'>\n\n/** Refresh interval for whole-second live run clocks. */\nexport const LIVE_RUN_CLOCK_INTERVAL_MS = 1000\n\nfunction pad2(n: number): string {\n return String(n).padStart(2, '0')\n}\n\n/**\n * Local calendar-day epoch (ms at local midnight) for an instant.\n * @param ms - Unix epoch ms.\n * @returns Midnight of that local calendar day.\n */\nexport function startOfLocalDay(ms: number): number {\n const d = new Date(ms)\n d.setHours(0, 0, 0, 0)\n return d.getTime()\n}\n\n/**\n * Delay until the next local midnight after `ms` (at least 1ms).\n * @param ms - Unix epoch ms.\n * @returns Milliseconds until the following local midnight.\n */\nexport function msUntilNextLocalMidnight(ms: number): number {\n const next = new Date(ms)\n next.setHours(24, 0, 0, 0)\n return Math.max(next.getTime() - ms, 1)\n}\n\n/** One numeric value or localized unit in an elapsed-time label. */\nexport interface RunDurationPart {\n readonly text: string\n readonly numeric: boolean\n}\n\n/**\n * Build elapsed-time fragments for both live and completed Turn labels.\n * @param ms - elapsed milliseconds; negatives clamp to zero and fractions floor.\n * @param t - translate seat supplying units and their trailing spacing.\n * @returns numbers and localized units in display order, without leading zeros;\n * minutes start at 60 seconds and hours at 60 minutes.\n */\nexport function formatRunDuration(ms: number, t: RunDurationTranslate): RunDurationPart[] {\n const total = Math.max(0, Math.floor(ms / 1000))\n const hours = Math.floor(total / 3600)\n const minutes = Math.floor(total / 60) % 60\n const seconds = total % 60\n const parts: RunDurationPart[] = []\n if (hours > 0) parts.push({ text: String(hours), numeric: true }, { text: t('duration.hourUnit'), numeric: false })\n if (total >= 60) parts.push({ text: String(minutes), numeric: true }, { text: t('duration.minuteUnit'), numeric: false })\n parts.push({ text: String(seconds), numeric: true }, { text: t('duration.secondUnit'), numeric: false })\n return parts\n}\n\n/**\n * Decode-throughput figure: whole tokens from ten up, one decimal below.\n * @param tps - Tokens per second.\n * @returns Display number without unit.\n */\nexport function formatTokensPerSecond(tps: number): string {\n const clamped = Math.max(0, tps)\n return clamped >= 10 ? String(Math.round(clamped)) : String(Math.round(clamped * 10) / 10)\n}\n\n/**\n * Compact local timestamp for message IconActions. Same calendar day →\n * `HH:mm`; earlier this year → the `clock.md` date template + clock; other\n * years → the `clock.ymd` template + clock. Pure: the date templates arrive\n * through the caller's locale seat.\n * @param time - Unix epoch ms from the source session event.\n * @param t - translate seat supplying the `clock.md` / `clock.ymd` templates.\n * @param now - Reference instant for the day/year cut (defaults to wall clock).\n * @returns Date-aware clock string (24-hour, zero-padded time).\n */\nexport function formatMessageClock(time: number, t: ClockTranslate, now: number = Date.now()): string {\n const d = new Date(time)\n const n = new Date(now)\n const clock = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`\n if (\n d.getFullYear() === n.getFullYear()\n && d.getMonth() === n.getMonth()\n && d.getDate() === n.getDate()\n ) {\n return clock\n }\n const params = { y: d.getFullYear(), m: d.getMonth() + 1, d: d.getDate() }\n const md = d.getFullYear() === n.getFullYear() ? t('clock.md', params) : t('clock.ymd', params)\n return `${md} ${clock}`\n}\n","// Component-local calendar-day tick: memoized message rows keep stable props\n// across midnight, so the IconActions clock needs a local day seat that\n// re-fires at the next local midnight without reaching for framework hooks.\n\nimport { useEffect, useState } from 'react'\nimport { msUntilNextLocalMidnight, startOfLocalDay } from './message-chrome.ts'\n\n/**\n * Local calendar-day epoch that advances at each local midnight.\n * @returns Midnight ms for the current local day; updates after the boundary.\n */\nexport function useCalendarDay(): number {\n const [day, setDay] = useState(() => startOfLocalDay(Date.now()))\n useEffect(() => {\n let timer: ReturnType<typeof setTimeout>\n const arm = (): void => {\n const now = Date.now()\n setDay(startOfLocalDay(now))\n timer = setTimeout(arm, msUntilNextLocalMidnight(now))\n }\n timer = setTimeout(arm, msUntilNextLocalMidnight(Date.now()))\n return () => { clearTimeout(timer) }\n }, [])\n return day\n}\n","// Shared IconActions chrome for user and assistant messages: copy\n// live, optional branch wiring, and an optional date-aware clock.\n\nimport { useId, type ReactNode } from 'react'\nimport {\n IconBranchOutlineRegular, IconCheckOutlineRegular, IconCopyOutlineRegular, Tooltip, useClipboardCopy,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatMessageClock } from './message-chrome.ts'\nimport { useCalendarDay } from './use-calendar-day.ts'\nimport css from './MessageIconActions.module.css'\n\nexport interface MessageIconActionsProps {\n /** Plain text the copy action writes. */\n text: string\n /** Unix epoch ms for the clock label; omitted for transient messages. */\n time?: number | undefined\n /** Clock before icons (user) or after (assistant). */\n clock: 'start' | 'end'\n /** Fork the session at this message; omission hides the branch action. */\n onBranch?: (() => void) | undefined\n /** The message is not a completed transcript tail, so branch stays visible but unavailable. */\n branchUnavailable?: boolean | undefined\n /** Parent layout class composed onto the actions row. */\n className?: string | undefined\n /**\n * Slot-rendered actions owned by independent plugins, placed between the\n * built-in copy and branch controls.\n */\n extraActions?: ReactNode\n /**\n * Icon-row Turn-usage trigger (the TurnUsagePanel pill), seated after the\n * branch control at the end of the icon cluster.\n */\n usageAction?: ReactNode\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Copy / branch (/ clock) IconActions row shared by user and assistant chrome.\n * @param props - Copy text, event time, clock side, branch callback, className.\n * @returns The actions row element.\n */\nexport function MessageIconActions({\n text, time, clock, onBranch, branchUnavailable = false, className,\n extraActions, usageAction, t,\n}: MessageIconActionsProps) {\n const day = useCalendarDay()\n const reasonId = useId()\n const { copied, onCopy } = useClipboardCopy(text)\n const clockEl = time === undefined ? null : (\n <span className={clock === 'start' ? css.timeStart : css.timeEnd}>\n {formatMessageClock(time, t, day)}\n </span>\n )\n return (\n <div className={className === undefined ? css.actions : `${css.actions} ${className}`} data-clock={clock}>\n {clock === 'start' ? clockEl : null}\n <Tooltip label={copied ? t('copied') : t('copy')} side=\"bottom\">\n <button type=\"button\" className={css.action} aria-label={copied ? t('copied') : t('copy')} onClick={onCopy}>\n {copied ? <IconCheckOutlineRegular /> : <IconCopyOutlineRegular />}\n </button>\n </Tooltip>\n {extraActions}\n {onBranch !== undefined && (\n <Tooltip label={branchUnavailable ? t('message.branchUnavailable') : t('message.branch')} side=\"bottom\" openOnClick={branchUnavailable}>\n {/* Native disabled buttons do not deliver the hover/focus events Tooltip needs. */}\n <button\n type=\"button\"\n className={css.action}\n aria-label={t('message.branch')}\n aria-disabled={branchUnavailable || undefined}\n aria-describedby={branchUnavailable ? reasonId : undefined}\n data-unavailable={branchUnavailable || undefined}\n onClick={branchUnavailable ? undefined : onBranch}\n >\n <IconBranchOutlineRegular />\n </button>\n </Tooltip>\n )}\n {onBranch !== undefined && branchUnavailable && (\n <span id={reasonId} className={css.visuallyHidden}>{t('message.branchUnavailable')}</span>\n )}\n {clock === 'end'\n ? <span className={css.endInfo}>{usageAction}{clockEl}</span>\n : usageAction}\n </div>\n )\n}\n","import { memo, useEffect, useMemo, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { UserTextFacts } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { JsonBlock, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type {\n ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps, UserContentAttachment, UserContentData, UserContentInput,\n} from '../contract/slots.ts'\nimport type { ModelRetryNode, TurnErrorNode, UserMessageNode } from '../contract/snapshot.ts'\nimport { CompactionItem } from './CompactionItem.tsx'\nimport { ContextInjectionRow } from './ContextInjectionRow.tsx'\nimport { MessageIconActions } from './MessageIconActions.tsx'\nimport css from './MessageItem.module.css'\n\nconst EMPTY_TEXT_FACTS: Readonly<Partial<UserTextFacts>> = {}\n\ntype UserImage = Extract<UserMessageNode['content'][number], { type: 'image' }>\ntype UserFile = Extract<UserMessageNode['content'][number], { type: 'file' }>\nfunction contentParts(content: readonly unknown[]): {\n text: string\n attachments: UserContentAttachment[]\n rest: unknown[]\n} {\n const texts: string[] = []\n const attachments: UserContentAttachment[] = []\n const rest: unknown[] = []\n for (const block of content) {\n const b = block as { type?: string; text?: string; attachment?: unknown }\n if (b.type === 'text' && typeof b.text === 'string') texts.push(b.text)\n else if (b.type === 'image' && b.attachment !== undefined) {\n attachments.push({ type: 'image', image: { attachment: (b as UserImage).attachment } })\n }\n else if (b.type === 'file' && b.attachment !== undefined) {\n attachments.push({ type: 'file', file: (b as UserFile).attachment })\n }\n else rest.push(block)\n }\n return { text: texts.join(''), attachments, rest }\n}\n\nfunction retrySeconds(milliseconds: number): number {\n return Math.max(1, Math.ceil(milliseconds / 1_000))\n}\n\ninterface RetryCountdown {\n deadline: number\n seconds: number\n}\n\nfunction failureMessage(\n message: string,\n code: unknown,\n t: ChatViewSlotProps['t'],\n): string {\n if (code === 'ACCOUNT_SIGNED_OUT') return t('message.failure.accountSignedOut')\n if (code === 'INTERRUPTED') return t('message.failure.interrupted')\n if (code === 'ACCOUNT_SIGN_IN_REQUIRED') return t('message.failure.accountSignInRequired')\n if (code === 'QUOTA' || code === 'ACCOUNT_QUOTA') return t('message.failure.quota')\n return code === 'AUTH' ? t('message.failure.auth') : message\n}\n\nfunction ModelRetryItem({ node, active, t }: {\n node: ModelRetryNode\n active: boolean\n t: ChatViewSlotProps['t']\n}) {\n // Anchor the host-scheduled delay to this browser's first render of the\n // retry node. Host event time and Date.now() may belong to different clocks.\n const deadline = useMemo(() => Date.now() + node.delayMs, [node.delayMs, node.seq])\n const scheduledSeconds = retrySeconds(node.delayMs)\n const maximum = node.mode === 'normal' ? node.maxRetries : '∞'\n const [countdown, setCountdown] = useState<RetryCountdown>(() => ({\n deadline,\n seconds: retrySeconds(deadline - Date.now()),\n }))\n const remainingSeconds = countdown.deadline === deadline\n ? countdown.seconds\n : retrySeconds(deadline - Date.now())\n\n useEffect(() => {\n if (!active) return\n const updateCountdown = (): number => {\n const next = retrySeconds(deadline - Date.now())\n setCountdown(current => (\n current.deadline === deadline && current.seconds === next\n ? current\n : { deadline, seconds: next }\n ))\n return next\n }\n if (updateCountdown() === 1) return\n const timer = window.setInterval(() => {\n if (updateCountdown() === 1) window.clearInterval(timer)\n }, 250)\n return () => { window.clearInterval(timer) }\n }, [active, deadline])\n\n const label = active\n ? t('message.retry.active')\n : node.retryState === 'cancelled'\n ? t('message.retry.cancelled')\n : node.retryState === 'started'\n ? t('message.retry.started')\n : t('message.retry.scheduled')\n const seconds = active ? remainingSeconds : scheduledSeconds\n\n return (\n <details className={css.retryRow} data-active={active || undefined}>\n <summary className={css.retrySummary}>\n <span className={css.retryText} role=\"status\">\n <TextShimmer active={active}>\n {t('message.retry.status', { label, retry: node.retry, maximum, seconds })}\n </TextShimmer>\n </span>\n </summary>\n <div className={css.retryDetails}>\n <div>\n <span className={css.retryDetailLabel}>{t('message.retry.delay')}</span>\n {t('duration.milliseconds', { milliseconds: Math.round(node.delayMs) })}\n </div>\n <div>\n <span className={css.retryDetailLabel}>{t('message.retry.failure')}</span>\n {failureMessage(node.failure.message, node.failure.code, t)}\n </div>\n </div>\n </details>\n )\n}\n\n/** Persistent, turn-positioned feedback for a terminal failure. */\nfunction TurnErrorItem({ node, t }: {\n node: TurnErrorNode\n t: ChatViewSlotProps['t']\n}) {\n return (\n <div className={css.turnErrorRow} role=\"status\">\n <StateDot state=\"error\" className={css.turnErrorDot} />\n <div className={css.turnErrorCopy}>\n <span className={css.turnErrorTitle}>{node.code === 'ACCOUNT_SIGNED_OUT' || node.code === 'INTERRUPTED' ? t('message.taskStopped') : t('message.turnError')}</span>\n <span className={css.turnErrorMessage}>{failureMessage(node.message, node.code, t)}</span>\n </div>\n {node.code !== undefined && node.code !== 'INTERRUPTED' && <code className={css.turnErrorCode}>{node.code}</code>}\n </div>\n )\n}\n\n/** Persistent, turn-positioned notice for a turn ended at the output-token cap. */\nfunction TurnMaxTokensItem({ t }: {\n t: ChatViewSlotProps['t']\n}) {\n return (\n <div className={css.turnErrorRow} role=\"status\">\n <StateDot state=\"warning\" className={css.turnErrorDot} />\n <div className={css.turnErrorCopy}>\n <span className={css.maxTokensTitle}>{t('message.maxTokens')}</span>\n <span className={css.turnErrorMessage}>{t('message.maxTokens.hint')}</span>\n </div>\n </div>\n )\n}\n\n/**\n * A row the message-source seat decorates. A durable Chat node satisfies it;\n * pending and local-echo rows pass a source-less stand-in.\n */\ninterface DecoratedRow {\n readonly kind: 'user' | 'steering'\n readonly data: { readonly source: unknown }\n}\n\n/** Pending and local-echo rows carry no durable source for the seat to elect. */\nconst UNDECORATED_ROW: DecoratedRow = { kind: 'user', data: { source: null } }\n\n/** Occupant used by rows that do not own the message-source seat. */\nconst NO_MESSAGE_SOURCE: PropsRenderSlots<'conversation.chat.user.before'>['renderSlotChain'] = () => null\n\n/** Right-aligned bubble shared by user and steering rows. */\nfunction UserStyleBubble({\n node, renderSlotChain, content, loadImage, renderFactorySlot, actions,\n pending = false, echo = false, batchStart = false,\n referenceLabels, skillNames, previewAttachments, facts: inputFacts = EMPTY_TEXT_FACTS, interactive = false,\n}: {\n content: readonly unknown[]\n renderFactorySlot: PropsRenderFactories['renderFactorySlot']\n /** Optional IconActions (or similar) below the bubble; receives the joined text. */\n actions?: (text: string) => ReactNode\n /** Row whose durable source the message-source seat elects above this bubble. */\n node: DecoratedRow\n /** Seat renderer; rows that do not own the seat pass {@link NO_MESSAGE_SOURCE}. */\n renderSlotChain: PropsRenderSlots<'conversation.chat.user.before'>['renderSlotChain']\n /** Whether this is the Host-authoritative pre-admission steering projection. */\n pending?: boolean\n /** Whether this is a local submission echo (invisible marker; the echo renders exactly like its durable replacement). */\n echo?: boolean\n /** Whether this admitted steering row starts its claim's batch and keeps the Turn tail slot above it. */\n batchStart?: boolean\n /** Exact session mention labels associated by the adjacent recall node. */\n referenceLabels?: readonly string[]\n /** Skill names the step's `skill-invocation` injections loaded for this message. */\n skillNames?: readonly string[]\n /** Local submission-echo attachments replacing the content-derived attachment sequence. */\n previewAttachments?: readonly UserContentAttachment[]\n /** Inputs used by text transforms, separate from row and rendering props. */\n facts?: Readonly<Partial<UserTextFacts>>\n} & Pick<ChatNodeOwnerProps, 'loadImage'> & Pick<UserContentInput, 'interactive'>): ReactNode {\n const parts = useMemo(() => contentParts(content), [content])\n const prepared = useMemo<UserContentData>(() => ({\n text: parts.text,\n attachments: previewAttachments ?? parts.attachments,\n extraBlocks: parts.rest,\n ...(referenceLabels === undefined ? {} : { referenceLabels }),\n }), [parts, previewAttachments, referenceLabels])\n const facts = useMemo<Readonly<Partial<UserTextFacts>>>(() => ({\n ...inputFacts,\n ...(referenceLabels === undefined ? {} : { sessionLabels: referenceLabels }),\n ...(skillNames === undefined ? {} : { skillNames }),\n }), [inputFacts, referenceLabels, skillNames])\n return (\n <div\n className={css.userRow}\n data-pending-steering={pending || undefined}\n data-submission-echo={echo || undefined}\n data-chat-steering-batch={batchStart ? 'start' : undefined}\n >\n {renderSlotChain('conversation.chat.user.before', { source: node.data.source, kind: node.kind }, { fallback: null })}\n {renderFactorySlot('conversation.chat.user.content', {\n content: prepared,\n loadImage,\n facts,\n interactive,\n })}\n {actions?.(prepared.text)}\n </div>\n )\n}\n\n/**\n * Render one Host-authoritative pending steering item with the same visual\n * language as its eventual durable transcript node.\n * @param props - pending content, authorized image loader, and Factory/locale seats.\n * @returns the pending steering bubble.\n */\nexport function PendingSteeringBubble({ content, loadImage, renderFactorySlot, t }: {\n content: readonly unknown[]\n renderFactorySlot: PropsRenderFactories['renderFactorySlot']\n t: ChatViewSlotProps['t']\n} & Pick<ChatNodeOwnerProps, 'loadImage'>): ReactNode {\n return (\n <UserStyleBubble\n node={UNDECORATED_ROW}\n renderSlotChain={NO_MESSAGE_SOURCE}\n content={content}\n renderFactorySlot={renderFactorySlot}\n loadImage={loadImage}\n pending\n actions={text => (\n <MessageIconActions\n text={text}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n}\n\n/**\n * Render one local transcript or steering submission echo with the same\n * visual language and surface marker as the Host occurrence that replaces\n * it: draft text plus object-URL previews, visible from the submit click\n * until the durable `user/message` or steering occurrence renders.\n * @param props - the pending submission, authorized image loader, and render seats.\n * @returns the echoed user bubble.\n */\nexport function PendingSubmissionBubble({ submission, loadImage, renderFactorySlot, t }: {\n submission: PendingSubmission\n renderFactorySlot: PropsRenderFactories['renderFactorySlot']\n t: ChatViewSlotProps['t']\n} & Pick<ChatNodeOwnerProps, 'loadImage'>): ReactNode {\n const content = useMemo(\n () => (submission.text === '' ? [] : [{ type: 'text', text: submission.text }]),\n [submission.text],\n )\n const previewAttachments = useMemo<readonly UserContentAttachment[]>(\n () => submission.attachments.map(attachment => attachment.type === 'image'\n ? {\n type: 'image',\n image: {\n preview: {\n url: attachment.value.previewUrl,\n ...(attachment.value.name === undefined ? {} : { name: attachment.value.name }),\n ...(attachment.value.width === undefined ? {} : { width: attachment.value.width }),\n ...(attachment.value.height === undefined ? {} : { height: attachment.value.height }),\n },\n },\n }\n : { type: 'file', file: attachment.value }),\n [submission.attachments],\n )\n return (\n <UserStyleBubble\n node={UNDECORATED_ROW}\n renderSlotChain={NO_MESSAGE_SOURCE}\n content={content}\n previewAttachments={previewAttachments}\n renderFactorySlot={renderFactorySlot}\n loadImage={loadImage}\n pending={submission.placement === 'steering'}\n echo\n actions={text => (\n <MessageIconActions\n text={text}\n time={submission.time}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n}\n\n/**\n * Official user and admitted-steering keyed Chat renderer.\n *\n * Renders the durable-message chain seat directly above the bubble. The seat is\n * declared by the `user` registration alone, so a steering row renders the same\n * bubble without asking for it.\n */\nexport const UserMessageNodeView = memo(function UserMessageNodeView({\n node, renderFactorySlot, loadImage, renderSlotChain, t,\n}: ChatNodeViewProps<'user' | 'steering'> & {\n /** Bound by the `user` keyed registration, the only entry that declares the seat. */\n renderSlotChain: PropsRenderSlots<'conversation.chat.user.before'>['renderSlotChain']\n}) {\n const data = node.data\n return (\n <UserStyleBubble\n node={node}\n renderSlotChain={renderSlotChain}\n content={data.content}\n interactive\n renderFactorySlot={renderFactorySlot}\n loadImage={loadImage}\n batchStart={node.kind === 'steering' && node.data.batchStart === true}\n {...data.referenceLabels === undefined ? {} : { referenceLabels: data.referenceLabels }}\n {...data.skillNames === undefined ? {} : { skillNames: data.skillNames }}\n actions={text => (\n <MessageIconActions\n text={text}\n time={data.time}\n clock=\"start\"\n className={css.actions}\n t={t}\n />\n )}\n />\n )\n})\n\n/** Injected-context keyed Chat renderer. */\nexport const ContextMessageNodeView = memo(function ContextMessageNodeView({ node, t }: ChatNodeViewProps<'context'>) {\n const data = node.data\n return (\n <ContextInjectionRow\n content={data.content}\n source={data.source}\n producer={data.producer}\n form={data.form}\n t={t}\n />\n )\n})\n\n/** Automatic compaction keyed Chat renderer. */\nexport const CompactionNodeView = memo(function CompactionNodeView({ node, t }: ChatNodeViewProps<'compaction'>) {\n return <CompactionItem node={node.data} t={t} />\n})\n\n/** Correlated retry-chain keyed Chat renderer. */\nexport const RetryNodeView = memo(function RetryNodeView({ node, t }: ChatNodeViewProps<'model-retry'>) {\n const data = node.data\n return <ModelRetryItem node={data.current} active={data.current.retryState === 'scheduled'} t={t} />\n})\n\n/** Terminal turn-error keyed Chat renderer. */\nexport const TurnErrorNodeView = memo(function TurnErrorNodeView({ node, t }: ChatNodeViewProps<'turn-error'>) {\n return <TurnErrorItem node={node.data} t={t} />\n})\n\n/** Max-tokens turn-end notice keyed Chat renderer. */\nexport const TurnMaxTokensNodeView = memo(function TurnMaxTokensNodeView({ t }: ChatNodeViewProps<'turn-max-tokens'>) {\n return <TurnMaxTokensItem t={t} />\n})\n\n/** Explicit unknown-surface keyed Chat renderer. */\nexport const UnknownNodeView = memo(function UnknownNodeView({ node, t }: ChatNodeViewProps<'unknown'>) {\n const data = node.data\n return (\n <div className={css.contextRow}>\n <JsonBlock\n label={t('message.unknownSurface', { type: data.type })}\n payload={data.data}\n truncatedLabel={total => t('json.truncated', { total })}\n />\n </div>\n )\n})\n","/** Animated whale mask and static SVG fallback for the running Chat status. */\nimport css from './ChatView.module.css'\n\nconst 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'\n\n/**\n * Render the decorative running icon; the APNG asset owns its animation timing.\n * @returns mask and static SVG selected by browser capabilities and accessibility preferences.\n */\nexport function RunningWhaleTail() {\n return (\n <span className={css.runningIcon} aria-hidden=\"true\">\n <span className={css.runningWhaleAnimated} />\n <svg className={css.runningWhaleStill} width=\"100%\" height=\"100%\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path d={REST_PATH} stroke=\"currentColor\" strokeWidth={1} />\n </svg>\n </span>\n )\n}\n","/** Running Turn clock isolated from the transcript's render cycle. */\nimport { memo, useEffect, useState } from 'react'\nimport { TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatRunDuration, LIVE_RUN_CLOCK_INTERVAL_MS } from './message-chrome.ts'\nimport { RunningWhaleTail } from './RunningWhaleTail.tsx'\nimport a11yCss from './accessibility.module.css'\nimport css from './ChatView.module.css'\n\ninterface RunningStatusProps {\n readonly startTime: number | undefined\n /** Freeze the shown duration while the Client cannot observe the Session. */\n readonly paused: boolean\n /** Keep the slot without showing or announcing the status: the Session stopped before its Turn closed. */\n readonly holding?: boolean\n readonly t: ChatViewSlotProps['t']\n}\n\n/**\n * Show live elapsed time after the current Turn's content without announcing ticks.\n * @param props - Current Turn start time, pause state, and localized copy.\n * @returns the blue running indicator; mount while the Session is running, or holding its slot hidden until the\n * Turn's actions row replaces it.\n */\nexport const RunningStatus = memo(function RunningStatus({ startTime, paused, holding = false, t }: RunningStatusProps) {\n const [now, setNow] = useState(Date.now)\n useEffect(() => {\n if (startTime === undefined || paused || holding) return\n setNow(Date.now())\n const timer = setInterval(() => { setNow(Date.now()) }, LIVE_RUN_CLOCK_INTERVAL_MS)\n return () => { clearInterval(timer) }\n }, [startTime, paused, holding])\n const label = startTime === undefined ? t('chat.deepDiving') : t('chat.deepDivingFor', {\n duration: formatRunDuration(Math.max(1000, now - startTime), t).map(part => part.text).join(''),\n })\n return (\n <div className={css.running} data-chat-running data-holding={holding ? '' : undefined} aria-hidden={holding || undefined}>\n {holding ? null : (\n <span className={a11yCss.visuallyHidden} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">{t('chat.deepDiving')}</span>\n )}\n <span className={css.runningDivider} aria-hidden=\"true\" />\n <span className={css.runningContent}>\n <RunningWhaleTail />\n <TextShimmer active={!holding} className={css.runningText}>{label}</TextShimmer>\n </span>\n </div>\n )\n})\n","/** Ordered Chat rows, local echoes, and running status share the flow slot's parent. */\nimport { memo, type ReactElement } from 'react'\nimport type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client'\nimport { assertNever } from '@deepseek-ai/dsh-util-values'\nimport type { ChatFlowSlotProps } from '../contract/slots.ts'\nimport { ChatNodeSeat } from './ChatNodeSeat.tsx'\nimport { ChatGroupSeat } from './ChatGroupSeat.tsx'\nimport { PendingSteeringBubble, PendingSubmissionBubble } from './MessageItem.tsx'\nimport { chatRenderKey } from './render-entry.ts'\nimport { RunningStatus } from './RunningStatus.tsx'\n\n/** A local submission echo, or a Host-pending steering item without a local submission. */\ntype PendingInput = ChatFlowSlotProps['pendingInputs'][number]\n\n/** Whether the echo is a local submission rather than a Host-pending steering item. */\nfunction isLocalSubmission(item: PendingInput): item is PendingSubmission {\n return 'requestId' in item\n}\n\n/** Whether the echo is a local submission that opens a new Turn. */\nfunction isTranscriptEcho(item: PendingInput): boolean {\n return isLocalSubmission(item) && item.placement === 'transcript'\n}\n\n/** Render the flow without adding a DOM parent or changing keyed row positions. */\nexport const ChatFlow = memo(function ChatFlow({\n entries, pendingInputs, lastInputTurn, deferCollapse,\n useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, useConnectionState,\n useStore, actions, renderSlot, renderFactorySlot, t, useGroupAction, useGroupHeaderAction,\n cwd, openFile, inspectCall, forkAt, loadImage,\n}: ChatFlowSlotProps) {\n const nodeStore = useChat(snapshot => snapshot.nodes)\n const running = useSession(snapshot => snapshot.running)\n const disconnected = useConnectionState(state => state === 'disconnected' || state === 'connecting')\n const latestTurnAnchor = useChat(snapshot => snapshot.navigation.items().at(-1)?.anchorKey)\n const runningStartTime = useChatNode(latestTurnAnchor ?? '', (node) => {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step'\n ? location.turn.status === 'open' ? location.turn.start?.time : undefined\n : undefined\n })\n const latestTurnOpen = useChatNode(latestTurnAnchor ?? '', (node) => {\n const location = node?.location\n return (location?.kind === 'turn' || location?.kind === 'step') && location.turn.status === 'open'\n })\n const holding = !running && latestTurnOpen\n const seatProps = {\n nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation,\n useStore, actions, renderSlot, t, useGroupAction, deferCollapse,\n cwd, openFile, inspectCall, forkAt, loadImage,\n }\n const rows = entries.map((entry) => {\n switch (entry.kind) {\n case 'node':\n return <ChatNodeSeat {...seatProps} key={chatRenderKey(entry)} nodeKey={entry.key}\n {...entry.groupPart === undefined ? {} : { groupPart: entry.groupPart }} />\n case 'group':\n return <ChatGroupSeat {...seatProps} key={chatRenderKey(entry)} groupKey={entry.key}\n useChatGroup={useChatGroup} useGroupHeaderAction={useGroupHeaderAction} />\n default:\n return assertNever(entry)\n }\n })\n // Transcript echoes open the running Turn and precede the status; steering\n // and Inbox echoes follow it, so the status stays on the running Turn's tail.\n // The first transcript echo opens the next Turn, whose first claim takes the\n // steering already pending ahead of it before that prompt; those echoes lead\n // the same Turn in claim order.\n const firstTranscript = pendingInputs.findIndex(isTranscriptEcho)\n const leadingRows: ReactElement[] = []\n const openingRows: ReactElement[] = []\n const pendingRows: ReactElement[] = []\n for (const [index, item] of pendingInputs.entries()) {\n const row = isLocalSubmission(item)\n ? <PendingSubmissionBubble key={item.requestId} submission={item}\n loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} />\n : <PendingSteeringBubble key={item.id} content={item.content}\n loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} />\n if (index <= firstTranscript) leadingRows.push(row)\n else if (isTranscriptEcho(item)) openingRows.push(row)\n else pendingRows.push(row)\n }\n const tail = entries.at(-1)\n const node = tail?.kind === 'node' ? nodeStore.get(tail.key) : undefined\n // An empty opening control follows the echoes that lead its Turn.\n // All rows share this keyed list so inserting the control keeps the echoes mounted.\n if (node?.kind === 'turn-process' && node.location.kind === 'turn'\n && node.location.turn.status === 'open' && node.location.turn.turn !== lastInputTurn) {\n rows.splice(rows.length - 1, 0, ...leadingRows.splice(0))\n }\n // Rows enter before the keyed status and echoes after it, so React never moves its DOM node. The\n // running bit and the Turn's end arrive separately: after the bit clears, an open latest Turn keeps\n // the status slot (hidden) until its actions row takes the slot in the same commit.\n return [\n ...rows, ...leadingRows, ...openingRows,\n ...running || holding ? [<RunningStatus key=\"running\" startTime={runningStartTime} paused={disconnected}\n holding={holding} t={t} />] : [],\n ...pendingRows,\n ]\n})\n","/** Chat-owned locale namespace and dictionaries. */\n\n/** Namespace for Chat target, node, statistics, and details copy. */\nexport const NS = 'chat'\n\n/** Simplified Chinese dictionary and key-set source of truth. */\nexport const zh = {\n 'message.stepProcess.thinking': '正在分析请求',\n 'message.stepProcess.read': '正在读取文件',\n 'message.stepProcess.readImage': '正在读取图片',\n 'message.stepProcess.write': '正在写入文件',\n 'message.stepProcess.search': '正在搜索代码',\n 'message.stepProcess.edit': '正在编辑文件',\n 'message.stepProcess.commands': '正在运行命令',\n 'message.stepProcess.code': '正在运行代码',\n 'message.stepProcess.webSearch': '正在搜索网页',\n 'message.stepProcess.webFetch': '正在访问网页',\n 'message.stepProcess.subagents': '正在协调子智能体',\n 'message.stepProcess.plan': '正在更新计划',\n 'message.stepProcess.questions': '等待你的操作',\n 'message.stepProcess.tools': '正在调用工具',\n 'message.stepProcess.prepare.read': '准备读取文件',\n 'message.stepProcess.prepare.readImage': '准备读取图片',\n 'message.stepProcess.prepare.write': '准备写入文件',\n 'message.stepProcess.prepare.search': '准备搜索代码',\n 'message.stepProcess.prepare.edit': '准备编辑文件',\n 'message.stepProcess.prepare.commands': '准备运行命令',\n 'message.stepProcess.prepare.code': '准备运行代码',\n 'message.stepProcess.prepare.webSearch': '准备搜索网页',\n 'message.stepProcess.prepare.webFetch': '准备访问网页',\n 'message.stepProcess.prepare.subagents': '准备协调子智能体',\n 'message.stepProcess.prepare.plan': '准备更新计划',\n 'message.stepProcess.prepare.questions': '准备提问',\n 'message.stepProcess.prepare.tools': '准备调用工具',\n 'message.stepProcess.done.thinking': '已完成分析',\n 'message.stepProcess.done.read': '已读取文件',\n 'message.stepProcess.done.readImage': '已读取图片',\n 'message.stepProcess.done.write': '已写入文件',\n 'message.stepProcess.done.search': '已搜索代码',\n 'message.stepProcess.done.edit': '修改了文件',\n 'message.stepProcess.done.commands': '执行了命令',\n 'message.stepProcess.done.code': '运行了代码',\n 'message.stepProcess.done.webSearch': '已搜索网页',\n 'message.stepProcess.done.webFetch': '已访问网页',\n 'message.stepProcess.done.subagents': '已协调子智能体',\n 'message.stepProcess.done.plan': '更新了计划',\n 'message.stepProcess.done.questions': '向用户提出了问题',\n 'message.stepProcess.done.tools': '已调用工具',\n 'message.stepProcess.done.context': '已注入上下文',\n 'message.stepProcess.joinTwo': '{first}并{second}',\n 'message.stepProcess.comma': ',',\n 'message.stepProcess.sharedPrefix': '已',\n 'message.stepProcess.more': '{title}等',\n 'message.trigger.request': '收到执行请求',\n 'message.trigger.goal': '继续执行目标',\n 'message.trigger.agent': '收到任务消息',\n 'message.trigger.team': '收到团队消息',\n 'message.trigger.subagent': '子任务状态更新',\n 'message.trigger.subagent.completed': '子智能体已完成任务',\n 'message.trigger.subagent.aborted': '子智能体任务已停止',\n 'message.trigger.subagent.error': '子智能体执行失败',\n 'message.trigger.subagent.maxTokens': '子智能体已达 token 上限',\n 'message.trigger.subagent.refusal': '子智能体拒绝执行',\n 'message.trigger.subagent.unknown': '子智能体异常结束',\n 'message.trigger.github': '收到 GitHub 事件',\n 'message.trigger.webhook': '收到外部事件',\n 'message.trigger.schedule': '自动化任务',\n 'message.trigger.job': '后台任务状态更新',\n 'message.trigger.plugin': '插件状态更新',\n 'message.trigger.explanation': '这条通知触发了本轮回复。',\n 'message.turnProcess.worked': '已完成',\n 'message.turnProcess.took': '已完成,用时 ',\n 'message.turnProcess.failed': '处理失败',\n 'view.chat': '对话',\n 'image.open': '查看大图',\n 'image.loading': '加载图片…',\n 'image.failed': '图片无法预览',\n 'image.dialog': '图片预览',\n 'image.close': '关闭图片预览',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}秒',\n 'duration.compactMinutes': '{minutes}分{seconds}秒',\n 'duration.milliseconds': '{milliseconds}毫秒',\n 'stats.counts': '{turns} 轮 {steps} 步',\n 'stats.cacheHit': '缓存命中 {percent}%',\n 'stats.dialog.title': '会话统计',\n 'stats.dialog.usageTitle': 'Token 用量',\n 'stats.dialog.llmTime': '模型用时',\n 'stats.dialog.toolTime': '工具调用用时',\n 'stats.dialog.ttft': '首 token 平均(TTFT)',\n 'stats.dialog.speed': '输出速度(TPS)',\n 'chat.loadingHistory': '载入历史…',\n 'chat.loadError': '历史加载失败:{message}({code})',\n 'chat.loadOlder': '加载更早',\n 'chat.loadingOlder': '正在加载',\n 'chat.processingOlder': '正在处理',\n 'chat.retryOlder': '重新加载',\n 'chat.historyStart': '已到会话开头',\n 'chat.toBottom': '回到底部',\n 'chat.deepDiving': '深度求索中',\n 'chat.deepDivingFor': '深度求索中,用时 {duration} ···',\n 'chat.turnNavigation.label': '轮次导航',\n 'chat.turnNavigation.jump': '跳转到第 {turn} 轮',\n 'chat.turnNavigation.jumpLoad': '加载并跳转到第 {turn} 轮',\n 'chat.turnNavigation.turn': '第 {turn} 轮',\n 'settings.performance.title': '性能与用量',\n 'settings.performance.description': '选择性能与用量信息展示的详细程度',\n 'settings.performance.compact': '简洁',\n 'settings.performance.detailed': '详细',\n 'settings.links.title': '网页链接默认打开方式',\n 'settings.links.description': '对话中网页链接的打开位置',\n 'settings.links.sidebar': '应用内侧边栏',\n 'settings.links.newTab': '默认浏览器',\n 'settings.transcript.title': '工作步骤展示',\n 'settings.transcript.description': '选择希望看到多少工具调用细节',\n 'settings.collapse.title': '工作步骤收起时机',\n 'settings.collapse.description': '选择何时自动收起工作步骤',\n 'settings.collapse.completion': '回答结束后',\n 'settings.collapse.nextInput': '下次有新消息时',\n 'settings.foldedReplies.title': '收起后显示的回复',\n 'settings.foldedReplies.description': '工作步骤收起后,保留哪些助手回复',\n 'settings.foldedReplies.all': '全部回复',\n 'settings.foldedReplies.final': '仅最终回答',\n 'settings.transcript.compact': '简洁',\n 'settings.transcript.standard': '标准',\n 'settings.transcript.detailed': '详细',\n 'settings.transcript.verbose': '完全展开',\n 'fileOpen.title': '无法打开文件',\n 'fileOpen.unknown': '无法打开此文件',\n 'message.extraBlock': '附加内容块',\n 'message.systemPrompt': '系统提示词',\n 'message.systemPromptUpdate': '系统提示词更新',\n 'message.toolAdded': '已添加工具:{name}',\n 'message.toolRemoved': '已移除工具:{name}',\n 'message.toolsAdded': '新增:{names}',\n 'message.toolsAddedCount': '新增 {count} 个',\n 'message.toolsChanged': '新增 {added} 个,移除 {removed} 个',\n 'message.toolsRemoved': '移除:{names}',\n 'message.toolsRemovedCount': '移除 {count} 个',\n 'message.toolsUpdated': '工具已更新',\n 'message.contextInjection': '上下文注入',\n 'message.contextRecall': '跨会话召回',\n 'message.referenceSummary': '引用会话 · {labels}',\n 'message.referenceSeparator': '、',\n 'message.context.instructions.loaded': '已载入',\n 'message.context.instructions.added': '已新增',\n 'message.context.instructions.updated': '已更新',\n 'message.context.instructions.removed': '已移除',\n 'message.context.catalog.replaced': '替换目录',\n 'message.context.catalog.more': '…还有 {count} 条',\n 'message.context.snapshot.supersedes': '取代先前的快照',\n 'message.context.relay.from': '来自会话 {session}',\n 'message.context.recall.counts': '保留 {retained} 条 · 省略 {omitted} 条',\n 'message.context.recall.truncated': '已截断',\n 'message.compaction': '上下文已压缩',\n 'message.compaction.running': '正在压缩…',\n 'message.compaction.completed': '已压缩 {items} 条历史记录(约 {tokens} tokens)',\n 'message.compaction.expand': '点击查看压缩摘要',\n 'message.compaction.unavailable': '压缩摘要不可用',\n 'message.compaction.commandTitle': 'compact',\n 'message.think': '思考',\n 'message.unknownSurface': '未知 surface 事件:{type}',\n 'message.unknownBlock': '未知内容块',\n 'message.turnProcess.toolCalls.one': '{count} 次工具调用',\n 'message.turnProcess.toolCalls.other': '{count} 次工具调用',\n 'message.turnProcess.messages.one': '{count} 条消息',\n 'message.turnProcess.messages.other': '{count} 条消息',\n 'message.turnProcess.subagents.one': '{count} 个 subagent',\n 'message.turnProcess.subagents.other': '{count} 个 subagent',\n 'message.turnProcess.thoughtForAWhile': '已思考',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': '已停止',\n 'message.branch': '在新对话中分支',\n 'message.branchUnavailable': '仅可从已完成轮次的最后一条消息分支',\n 'message.retry.active': '正在重试模型请求',\n 'message.retry.cancelled': '模型请求重试已取消',\n 'message.retry.started': '已重试模型请求',\n 'message.continuation.requested': '已请求继续生成',\n 'message.retry.scheduled': '等待重试模型请求',\n 'message.retry.status': '{label}({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': '重试延迟:',\n 'message.retry.failure': '失败原因:',\n 'message.failure.auth': 'API 密钥无效',\n 'message.taskStopped': '任务已停止',\n 'message.failure.accountSignedOut': '任务已因退出 DeepSeek 登录而停止。',\n 'message.failure.interrupted': 'DSH 进程在本轮完成前退出(例如被强制结束、崩溃或关闭超时),重新启动后本轮已中止。未完成的工具调用结果未知。',\n 'message.failure.accountSignInRequired': '请先登录 DeepSeek,并确认请求地址支持账号认证。',\n 'message.failure.quota': '当前请求的额度已用尽',\n 'message.turnError': '本轮运行失败',\n 'message.maxTokens': '已达到输出 token 上限',\n 'message.maxTokens.hint': '回答被截断,已有输出保留在对话中。发送“继续”可让模型接着输出。',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': '本轮用量',\n 'message.turnUsage.consumed': '用量 {total}',\n 'message.turnUsage.model': '提供方 / 模型',\n 'message.turnUsage.cacheHit': '缓存命中',\n 'message.turnUsage.input': '未缓存输入',\n 'message.turnUsage.cacheRead': '缓存读取',\n 'message.turnUsage.cacheWrite': '缓存写入',\n 'message.turnUsage.output': '输出',\n 'message.turnUsage.reasoning': '(其中推理 {tokens})',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': '秒',\n 'duration.minuteUnit': '分',\n 'duration.hourUnit': '小时',\n 'command.running': '执行中…',\n 'command.failed': '指令失败',\n 'command.done': '已完成',\n 'command.title': '指令',\n 'row.running': '运行中',\n 'row.failed': '失败',\n 'json.truncated': '… 已截断,共 {total} 字符',\n 'clock.md': '{m}月{d}日',\n 'clock.ymd': '{y}年{m}月{d}日',\n} satisfies Record<string, string>\n\n/** Chat dictionary key union. */\nexport type ChatKey = keyof typeof zh\n\n/** English dictionary, checked against the Chinese key set. */\nexport const en = {\n 'message.stepProcess.thinking': 'Analyzing the request',\n 'message.stepProcess.read': 'Reading files',\n 'message.stepProcess.readImage': 'Reading images',\n 'message.stepProcess.write': 'Writing files',\n 'message.stepProcess.search': 'Searching code',\n 'message.stepProcess.edit': 'Editing files',\n 'message.stepProcess.commands': 'Running commands',\n 'message.stepProcess.code': 'Running code',\n 'message.stepProcess.webSearch': 'Searching the web',\n 'message.stepProcess.webFetch': 'Visiting web pages',\n 'message.stepProcess.subagents': 'Coordinating subagents',\n 'message.stepProcess.plan': 'Updating the plan',\n 'message.stepProcess.questions': 'Waiting for your action',\n 'message.stepProcess.tools': 'Calling tools',\n 'message.stepProcess.prepare.read': 'Preparing to read files',\n 'message.stepProcess.prepare.readImage': 'Preparing to read images',\n 'message.stepProcess.prepare.write': 'Preparing to write files',\n 'message.stepProcess.prepare.search': 'Preparing to search code',\n 'message.stepProcess.prepare.edit': 'Preparing to edit files',\n 'message.stepProcess.prepare.commands': 'Preparing to run commands',\n 'message.stepProcess.prepare.code': 'Preparing to run code',\n 'message.stepProcess.prepare.webSearch': 'Preparing to search the web',\n 'message.stepProcess.prepare.webFetch': 'Preparing to visit web pages',\n 'message.stepProcess.prepare.subagents': 'Preparing to coordinate subagents',\n 'message.stepProcess.prepare.plan': 'Preparing to update the plan',\n 'message.stepProcess.prepare.questions': 'Preparing questions',\n 'message.stepProcess.prepare.tools': 'Preparing tool calls',\n 'message.stepProcess.done.thinking': 'Analysis completed',\n 'message.stepProcess.done.read': 'Read files',\n 'message.stepProcess.done.readImage': 'Read images',\n 'message.stepProcess.done.write': 'Wrote files',\n 'message.stepProcess.done.search': 'Searched code',\n 'message.stepProcess.done.edit': 'Edited files',\n 'message.stepProcess.done.commands': 'Ran commands',\n 'message.stepProcess.done.code': 'Ran code',\n 'message.stepProcess.done.webSearch': 'Searched the web',\n 'message.stepProcess.done.webFetch': 'Visited web pages',\n 'message.stepProcess.done.subagents': 'Coordinated subagents',\n 'message.stepProcess.done.plan': 'Updated the plan',\n 'message.stepProcess.done.questions': 'Asked questions',\n 'message.stepProcess.done.tools': 'Called tools',\n 'message.stepProcess.done.context': 'Injected context',\n 'message.stepProcess.joinTwo': '{first} and {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}, etc.',\n 'message.trigger.request': 'Execution requested',\n 'message.trigger.goal': 'Continuing goal',\n 'message.trigger.agent': 'Task message received',\n 'message.trigger.team': 'Team message received',\n 'message.trigger.subagent': 'Subtask status updated',\n 'message.trigger.subagent.completed': 'Subagent run completed',\n 'message.trigger.subagent.aborted': 'Subagent run stopped',\n 'message.trigger.subagent.error': 'Subagent run failed',\n 'message.trigger.subagent.maxTokens': 'Subagent reached the token limit',\n 'message.trigger.subagent.refusal': 'Subagent declined the task',\n 'message.trigger.subagent.unknown': 'Subagent run ended unexpectedly',\n 'message.trigger.github': 'GitHub event received',\n 'message.trigger.webhook': 'External event received',\n 'message.trigger.schedule': 'Automation task',\n 'message.trigger.job': 'Background task updated',\n 'message.trigger.plugin': 'Plugin status updated',\n 'message.trigger.explanation': 'This notification triggered this response.',\n 'message.turnProcess.worked': 'Completed',\n 'message.turnProcess.took': 'Completed in ',\n 'message.turnProcess.failed': 'Failed',\n 'view.chat': 'Chat',\n 'image.open': 'View full image',\n 'image.loading': 'Loading image…',\n 'image.failed': 'Image preview unavailable',\n 'image.dialog': 'Image preview',\n 'image.close': 'Close image preview',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} turns {steps} steps',\n 'stats.cacheHit': 'Cache hit {percent}%',\n 'stats.dialog.title': 'Session statistics',\n 'stats.dialog.usageTitle': 'Token usage',\n 'stats.dialog.llmTime': 'LLM time',\n 'stats.dialog.toolTime': 'Tool time',\n 'stats.dialog.ttft': 'Avg time to first token (TTFT)',\n 'stats.dialog.speed': 'Tokens per second (TPS)',\n 'chat.loadingHistory': 'Loading history…',\n 'chat.loadError': 'Failed to load history: {message} ({code})',\n 'chat.loadOlder': 'Load earlier',\n 'chat.loadingOlder': 'Loading earlier',\n 'chat.processingOlder': 'Processing',\n 'chat.retryOlder': 'Retry loading',\n 'chat.historyStart': 'Start of conversation',\n 'chat.toBottom': 'Back to bottom',\n 'chat.deepDiving': 'Deep diving',\n 'chat.deepDivingFor': 'Deep diving for {duration} ···',\n 'chat.turnNavigation.label': 'Turn navigation',\n 'chat.turnNavigation.jump': 'Jump to turn {turn}',\n 'chat.turnNavigation.jumpLoad': 'Load and jump to turn {turn}',\n 'chat.turnNavigation.turn': 'Turn {turn}',\n 'settings.performance.title': 'Performance & usage',\n 'settings.performance.description': 'Choose how much performance and usage information to show',\n 'settings.performance.compact': 'Compact',\n 'settings.performance.detailed': 'Detailed',\n 'settings.links.title': 'Open chat links in',\n 'settings.links.description': 'Choose where to open web links',\n 'settings.links.sidebar': 'In-App Sidebar',\n 'settings.links.newTab': 'Default Browser',\n 'settings.transcript.title': 'Work details',\n 'settings.transcript.description': 'Choose how much detail to show for tool calls',\n 'settings.collapse.title': 'When to Collapse Work Details',\n 'settings.collapse.description': 'Choose when to automatically collapse work details',\n 'settings.collapse.completion': 'On completion',\n 'settings.collapse.nextInput': 'On next message',\n 'settings.foldedReplies.title': 'Replies After Collapse',\n 'settings.foldedReplies.description': 'Choose which assistant replies stay visible when work details collapse',\n 'settings.foldedReplies.all': 'All replies',\n 'settings.foldedReplies.final': 'Final answer only',\n 'settings.transcript.compact': 'Compact',\n 'settings.transcript.standard': 'Standard',\n 'settings.transcript.detailed': 'Detailed',\n 'settings.transcript.verbose': 'Verbose',\n 'fileOpen.title': 'Couldn’t open file',\n 'fileOpen.unknown': 'Couldn’t open this file',\n 'message.extraBlock': 'Extra content block',\n 'message.systemPrompt': 'System prompt',\n 'message.systemPromptUpdate': 'System prompt update',\n 'message.toolAdded': 'Tool added: {name}',\n 'message.toolRemoved': 'Tool removed: {name}',\n 'message.toolsAdded': 'Added: {names}',\n 'message.toolsAddedCount': '{count} added',\n 'message.toolsChanged': '{added} added, {removed} removed',\n 'message.toolsRemoved': 'Removed: {names}',\n 'message.toolsRemovedCount': '{count} removed',\n 'message.toolsUpdated': 'Tools updated',\n 'message.contextInjection': 'Context injection',\n 'message.contextRecall': 'Session recall',\n 'message.referenceSummary': 'Referenced session · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'loaded',\n 'message.context.instructions.added': 'added',\n 'message.context.instructions.updated': 'updated',\n 'message.context.instructions.removed': 'removed',\n 'message.context.catalog.replaced': 'Replacement catalog',\n 'message.context.catalog.more': '… {count} more',\n 'message.context.snapshot.supersedes': 'Supersedes earlier snapshots',\n 'message.context.relay.from': 'From session {session}',\n 'message.context.recall.counts': '{retained} kept · {omitted} omitted',\n 'message.context.recall.truncated': 'truncated',\n 'message.compaction': 'Context compacted',\n 'message.compaction.running': 'Compacting context…',\n 'message.compaction.completed': 'Compacted {items} history items (~{tokens} tokens)',\n 'message.compaction.expand': 'View compaction summary',\n 'message.compaction.unavailable': 'Compaction summary unavailable',\n 'message.compaction.commandTitle': 'compact',\n 'message.think': 'Think',\n 'message.unknownSurface': 'Unknown surface event: {type}',\n 'message.unknownBlock': 'Unknown content block',\n 'message.turnProcess.toolCalls.one': '{count} tool call',\n 'message.turnProcess.toolCalls.other': '{count} tool calls',\n 'message.turnProcess.messages.one': '{count} message',\n 'message.turnProcess.messages.other': '{count} messages',\n 'message.turnProcess.subagents.one': '{count} subagent',\n 'message.turnProcess.subagents.other': '{count} subagents',\n 'message.turnProcess.thoughtForAWhile': 'Thought for a while',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Stopped',\n 'message.branch': 'Branch into a new conversation',\n 'message.branchUnavailable': 'Available only on the last message of a completed turn',\n 'message.retry.active': 'Retrying model request',\n 'message.retry.cancelled': 'Model request retry cancelled',\n 'message.retry.started': 'Retried model request',\n 'message.continuation.requested': 'Requested to continue generation',\n 'message.retry.scheduled': 'Waiting to retry model request',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': 'Retry delay: ',\n 'message.retry.failure': 'Failure reason: ',\n 'message.failure.auth': 'API key is invalid',\n 'message.taskStopped': 'Task stopped',\n 'message.failure.accountSignedOut': 'Stopped because you signed out of DeepSeek.',\n '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.',\n 'message.failure.accountSignInRequired': 'Sign in to DeepSeek and ensure the request destination supports account authentication.',\n 'message.failure.quota': 'Request quota exhausted.',\n 'message.turnError': 'This turn failed',\n 'message.maxTokens': 'Output token limit reached',\n 'message.maxTokens.hint': 'The reply was cut off; earlier output is preserved in the conversation. Send \"continue\" to let the model resume.',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'Turn usage',\n 'message.turnUsage.consumed': 'Usage {total}',\n 'message.turnUsage.model': 'Provider / model',\n 'message.turnUsage.cacheHit': 'Cache hit',\n 'message.turnUsage.input': 'Uncached input',\n 'message.turnUsage.cacheRead': 'Cached input',\n 'message.turnUsage.cacheWrite': 'Cache write',\n 'message.turnUsage.output': 'Output',\n 'message.turnUsage.reasoning': ' ({tokens} reasoning)',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Running…',\n 'command.failed': 'Command failed',\n 'command.done': 'Completed',\n 'command.title': 'Command',\n 'row.running': 'Running',\n 'row.failed': 'Failed',\n 'json.truncated': '… truncated, {total} characters total',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<ChatKey, string>\n\n/** Japanese copy, checked against the English keys. */\nexport const ja = {\n 'message.stepProcess.thinking': 'リクエストを分析中',\n 'message.stepProcess.read': 'ファイルを読み取り中',\n 'message.stepProcess.readImage': '画像を読み取り中',\n 'message.stepProcess.write': 'ファイルを書き込み中',\n 'message.stepProcess.search': 'コードを検索中',\n 'message.stepProcess.edit': 'ファイルを編集中',\n 'message.stepProcess.commands': 'コマンドを実行中',\n 'message.stepProcess.code': 'コードを実行中',\n 'message.stepProcess.webSearch': 'ウェブを検索中',\n 'message.stepProcess.webFetch': 'ウェブページを閲覧中',\n 'message.stepProcess.subagents': 'サブエージェントを調整中',\n 'message.stepProcess.plan': '計画を更新中',\n 'message.stepProcess.questions': '操作を待機中',\n 'message.stepProcess.tools': 'ツールを呼び出し中',\n 'message.stepProcess.prepare.read': 'ファイル読み取りの準備中',\n 'message.stepProcess.prepare.readImage': '画像読み取りの準備中',\n 'message.stepProcess.prepare.write': 'ファイル書き込みの準備中',\n 'message.stepProcess.prepare.search': 'コード検索の準備中',\n 'message.stepProcess.prepare.edit': 'ファイル編集の準備中',\n 'message.stepProcess.prepare.commands': 'コマンド実行の準備中',\n 'message.stepProcess.prepare.code': 'コード実行の準備中',\n 'message.stepProcess.prepare.webSearch': 'ウェブ検索の準備中',\n 'message.stepProcess.prepare.webFetch': 'ウェブページ閲覧の準備中',\n 'message.stepProcess.prepare.subagents': 'サブエージェント調整の準備中',\n 'message.stepProcess.prepare.plan': '計画更新の準備中',\n 'message.stepProcess.prepare.questions': '質問の準備中',\n 'message.stepProcess.prepare.tools': 'ツール呼び出しの準備中',\n 'message.stepProcess.done.thinking': '分析完了',\n 'message.stepProcess.done.read': 'ファイルを読み取りました',\n 'message.stepProcess.done.readImage': '画像を読み取りました',\n 'message.stepProcess.done.write': 'ファイルを書き込みました',\n 'message.stepProcess.done.search': 'コードを検索しました',\n 'message.stepProcess.done.edit': 'ファイルを編集しました',\n 'message.stepProcess.done.commands': 'コマンドを実行しました',\n 'message.stepProcess.done.code': 'コードを実行しました',\n 'message.stepProcess.done.webSearch': 'ウェブを検索しました',\n 'message.stepProcess.done.webFetch': 'ウェブページを閲覧しました',\n 'message.stepProcess.done.subagents': 'サブエージェントを調整しました',\n 'message.stepProcess.done.plan': '計画を更新しました',\n 'message.stepProcess.done.questions': '質問しました',\n 'message.stepProcess.done.tools': 'ツールを呼び出しました',\n 'message.stepProcess.done.context': 'コンテキストを注入しました',\n 'message.stepProcess.joinTwo': '{first}と{second}',\n 'message.stepProcess.comma': '、',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}など',\n 'message.trigger.request': '実行が要求されました',\n 'message.trigger.goal': '目標を継続中',\n 'message.trigger.agent': 'タスクメッセージを受信しました',\n 'message.trigger.team': 'チームメッセージを受信しました',\n 'message.trigger.subagent': 'サブタスクの状態が更新されました',\n 'message.trigger.subagent.completed': 'サブエージェントの実行が完了しました',\n 'message.trigger.subagent.aborted': 'サブエージェントの実行が停止しました',\n 'message.trigger.subagent.error': 'サブエージェントの実行が失敗しました',\n 'message.trigger.subagent.maxTokens': 'サブエージェントがトークンの上限に達しました',\n 'message.trigger.subagent.refusal': 'サブエージェントがタスクを拒否しました',\n 'message.trigger.subagent.unknown': 'サブエージェントの実行が予期せず終了しました',\n 'message.trigger.github': 'GitHubイベントを受信しました',\n 'message.trigger.webhook': '外部イベントを受信しました',\n 'message.trigger.schedule': '自動化タスク',\n 'message.trigger.job': 'バックグラウンドタスクが更新されました',\n 'message.trigger.plugin': 'プラグインの状態が更新されました',\n 'message.trigger.explanation': 'この通知がこの応答のトリガーとなりました。',\n 'message.turnProcess.worked': '完了',\n 'message.turnProcess.took': '完了まで ',\n 'message.turnProcess.failed': '失敗',\n 'view.chat': 'チャット',\n 'image.open': '画像を全画面表示',\n 'image.loading': '画像を読み込み中…',\n 'image.failed': '画像プレビューを利用できません',\n 'image.dialog': '画像プレビュー',\n 'image.close': '画像プレビューを閉じる',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}秒',\n 'duration.compactMinutes': '{minutes}分{seconds}秒',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns}ターン {steps}ステップ',\n 'stats.cacheHit': 'キャッシュヒット {percent}%',\n 'stats.dialog.title': 'セッション統計',\n 'stats.dialog.usageTitle': 'トークン使用量',\n 'stats.dialog.llmTime': 'LLM時間',\n 'stats.dialog.toolTime': 'ツール時間',\n 'stats.dialog.ttft': '平均初回トークン時間(TTFT)',\n 'stats.dialog.speed': '毎秒トークン数(TPS)',\n 'chat.loadingHistory': '履歴を読み込み中…',\n 'chat.loadError': '履歴の読み込みに失敗しました: {message}({code})',\n 'chat.loadOlder': '以前を読み込む',\n 'chat.loadingOlder': '読み込み中',\n 'chat.processingOlder': '処理中',\n 'chat.retryOlder': '再読み込み',\n 'chat.historyStart': '会話の先頭です',\n 'chat.toBottom': '最下部へ戻る',\n 'chat.deepDiving': '深掘り中',\n 'chat.deepDivingFor': '{duration} の間深く分析中 ···',\n 'chat.turnNavigation.label': 'ターン移動',\n 'chat.turnNavigation.jump': 'ターン {turn} へ移動',\n 'chat.turnNavigation.jumpLoad': '読み込んでターン {turn} へ移動',\n 'chat.turnNavigation.turn': 'ターン {turn}',\n 'settings.performance.title': 'パフォーマンスと使用状況',\n 'settings.performance.description': 'パフォーマンスと使用状況の表示量を選択',\n 'settings.performance.compact': 'コンパクト',\n 'settings.performance.detailed': '詳細',\n 'settings.links.title': 'チャットリンクを開く場所',\n 'settings.links.description': 'Web リンクを開く場所を選択',\n 'settings.links.sidebar': 'アプリ内サイドバー',\n 'settings.links.newTab': '既定のブラウザー',\n 'settings.transcript.title': '作業の詳細',\n 'settings.transcript.description': 'ツール呼び出しの表示詳細度を選択',\n 'settings.collapse.title': '作業詳細を折りたたむタイミング',\n 'settings.collapse.description': '作業詳細を自動で折りたたむタイミングを選択',\n 'settings.collapse.completion': '完了時',\n 'settings.collapse.nextInput': '次のメッセージ送信時',\n 'settings.foldedReplies.title': '折りたたみ後の返信',\n 'settings.foldedReplies.description': '作業詳細の折りたたみ時に表示するアシスタントの返信を選択',\n 'settings.foldedReplies.all': 'すべての返信',\n 'settings.foldedReplies.final': '最終回答のみ',\n 'settings.transcript.compact': 'コンパクト',\n 'settings.transcript.standard': '標準',\n 'settings.transcript.detailed': '詳細',\n 'settings.transcript.verbose': '冗長',\n 'fileOpen.title': 'ファイルを開けませんでした',\n 'fileOpen.unknown': 'このファイルを開けませんでした',\n 'message.extraBlock': '追加のコンテンツブロック',\n 'message.systemPrompt': 'システムプロンプト',\n 'message.systemPromptUpdate': 'システムプロンプトの更新',\n 'message.toolAdded': 'ツールを追加: {name}',\n 'message.toolRemoved': 'ツールを削除: {name}',\n 'message.toolsAdded': '追加: {names}',\n 'message.toolsAddedCount': '{count} 件追加',\n 'message.toolsChanged': '{added} 件追加、{removed} 件削除',\n 'message.toolsRemoved': '削除: {names}',\n 'message.toolsRemovedCount': '{count} 件削除',\n 'message.toolsUpdated': 'ツールを更新しました',\n 'message.contextInjection': 'コンテキスト注入',\n 'message.contextRecall': 'セッションの呼び出し',\n 'message.referenceSummary': '参照セッション · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': '読み込み済み',\n 'message.context.instructions.added': '追加済み',\n 'message.context.instructions.updated': '更新済み',\n 'message.context.instructions.removed': '削除済み',\n 'message.context.catalog.replaced': '置換カタログ',\n 'message.context.catalog.more': '… 他 {count} 件',\n 'message.context.snapshot.supersedes': '以前のスナップショットを置き換えます',\n 'message.context.relay.from': 'セッション {session} から',\n 'message.context.recall.counts': '{retained} 件保持 · {omitted} 件除外',\n 'message.context.recall.truncated': '切り詰め済み',\n 'message.compaction': 'コンテキストを圧縮しました',\n 'message.compaction.running': 'コンテキストを圧縮中…',\n 'message.compaction.completed': '履歴 {items} 件を圧縮しました(約 {tokens} トークン)',\n 'message.compaction.expand': '圧縮の要約を表示',\n 'message.compaction.unavailable': '圧縮の要約は利用できません',\n 'message.compaction.commandTitle': 'compact',\n 'message.think': '思考',\n 'message.unknownSurface': '不明なサーフェスイベント: {type}',\n 'message.unknownBlock': '不明なコンテンツブロック',\n 'message.turnProcess.toolCalls.one': 'ツール呼び出し {count} 件',\n 'message.turnProcess.toolCalls.other': 'ツール呼び出し {count} 件',\n 'message.turnProcess.messages.one': 'メッセージ {count} 件',\n 'message.turnProcess.messages.other': 'メッセージ {count} 件',\n 'message.turnProcess.subagents.one': 'サブエージェント {count} 件',\n 'message.turnProcess.subagents.other': 'サブエージェント {count} 件',\n 'message.turnProcess.thoughtForAWhile': 'しばらく思考しました',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': '停止しました',\n 'message.branch': '新しい会話に分岐',\n 'message.branchUnavailable': '完了したターンの最後のメッセージでのみ利用できます',\n 'message.retry.active': 'モデルリクエストを再試行中',\n 'message.retry.cancelled': 'モデルリクエストの再試行をキャンセルしました',\n 'message.retry.started': 'モデルリクエストを再試行しました',\n 'message.continuation.requested': '生成の続行をリクエストしました',\n 'message.retry.scheduled': 'モデルリクエストの再試行待ちです',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}秒',\n 'message.retry.delay': '再試行までの待機時間: ',\n 'message.retry.failure': '失敗理由: ',\n 'message.failure.auth': 'APIキーが無効です',\n 'message.taskStopped': 'タスクを停止しました',\n 'message.failure.accountSignedOut': 'DeepSeekからログアウトしたため停止しました。',\n 'message.failure.interrupted': 'このターンが完了する前にDSHプロセスが終了したため(強制終了、クラッシュ、シャットダウン中のタイムアウトなど)、DSHの再起動時にターンは閉じられました。未完了のツール呼び出しの結果は不明です。',\n 'message.failure.accountSignInRequired': 'DeepSeekにログインし、リクエスト先がアカウント認証に対応していることを確認してください。',\n 'message.failure.quota': 'リクエストのクォータを使い切りました。',\n 'message.turnError': 'このターンは失敗しました',\n 'message.maxTokens': '出力トークンの上限に達しました',\n 'message.maxTokens.hint': '応答が途中で打ち切られました。それまでの出力は会話に保持されています。「続けて」と送信するとモデルが再開します。',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'ターンの使用量',\n 'message.turnUsage.consumed': '使用量 {total}',\n 'message.turnUsage.model': 'プロバイダー / モデル',\n 'message.turnUsage.cacheHit': 'キャッシュヒット',\n 'message.turnUsage.input': '未キャッシュの入力',\n 'message.turnUsage.cacheRead': 'キャッシュ済み入力',\n 'message.turnUsage.cacheWrite': 'キャッシュ書き込み',\n 'message.turnUsage.output': '出力',\n 'message.turnUsage.reasoning': ' (推論 {tokens})',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': '秒',\n 'duration.minuteUnit': '分 ',\n 'duration.hourUnit': '時間 ',\n 'command.running': '実行中…',\n 'command.failed': 'コマンドが失敗しました',\n 'command.done': '完了',\n 'command.title': 'コマンド',\n 'row.running': '実行中',\n 'row.failed': '失敗',\n 'json.truncated': '… 省略表示、全{total}文字',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n\n/** Spanish dictionary, checked against the English keys. */\nexport const es = {\n 'message.stepProcess.thinking': 'Analizando la solicitud',\n 'message.stepProcess.read': 'Leyendo archivos',\n 'message.stepProcess.readImage': 'Leyendo imágenes',\n 'message.stepProcess.write': 'Escribir archivos',\n 'message.stepProcess.search': 'código de búsqueda',\n 'message.stepProcess.edit': 'Editar archivos',\n 'message.stepProcess.commands': 'Ejecutar comandos',\n 'message.stepProcess.code': 'Código en ejecución',\n 'message.stepProcess.webSearch': 'buscando en la web',\n 'message.stepProcess.webFetch': 'Visitar páginas web',\n 'message.stepProcess.subagents': 'Subagentes coordinadores',\n 'message.stepProcess.plan': 'Actualizando el plan',\n 'message.stepProcess.questions': 'Esperando tu acción',\n 'message.stepProcess.tools': 'herramientas de llamada',\n 'message.stepProcess.prepare.read': 'Preparándose para leer archivos',\n 'message.stepProcess.prepare.readImage': 'Preparándose para leer imágenes',\n 'message.stepProcess.prepare.write': 'Preparándose para escribir archivos',\n 'message.stepProcess.prepare.search': 'Preparándose para buscar el código',\n 'message.stepProcess.prepare.edit': 'Preparándose para editar archivos',\n 'message.stepProcess.prepare.commands': 'Preparándose para ejecutar comandos',\n 'message.stepProcess.prepare.code': 'Preparándose para ejecutar código',\n 'message.stepProcess.prepare.webSearch': 'Preparándose para buscar en la web',\n 'message.stepProcess.prepare.webFetch': 'Preparándose para visitar páginas web',\n 'message.stepProcess.prepare.subagents': 'Preparándose para coordinar subagentes',\n 'message.stepProcess.prepare.plan': 'Preparándose para actualizar el plan',\n 'message.stepProcess.prepare.questions': 'Preparando preguntas',\n 'message.stepProcess.prepare.tools': 'Preparando llamadas a herramientas',\n 'message.stepProcess.done.thinking': 'Análisis completado',\n 'message.stepProcess.done.read': 'leer archivos',\n 'message.stepProcess.done.readImage': 'Leer imágenes',\n 'message.stepProcess.done.write': 'Escribió archivos',\n 'message.stepProcess.done.search': 'código buscado',\n 'message.stepProcess.done.edit': 'Archivos editados',\n 'message.stepProcess.done.commands': 'Comandos ejecutados',\n 'message.stepProcess.done.code': 'código ejecutado',\n 'message.stepProcess.done.webSearch': 'Busqué en la web',\n 'message.stepProcess.done.webFetch': 'Paginas web visitadas',\n 'message.stepProcess.done.subagents': 'Subagentes coordinados',\n 'message.stepProcess.done.plan': 'Actualizado el plan',\n 'message.stepProcess.done.questions': 'preguntas hechas',\n 'message.stepProcess.done.tools': 'herramientas llamadas',\n 'message.stepProcess.done.context': 'Contexto inyectado',\n 'message.stepProcess.joinTwo': '{first} y {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}, etc.',\n 'message.trigger.request': 'Ejecución solicitada',\n 'message.trigger.goal': 'Objetivo continuo',\n 'message.trigger.agent': 'Mensaje de tarea recibido',\n 'message.trigger.team': 'Mensaje del equipo recibido',\n 'message.trigger.subagent': 'Estado de subtarea actualizado',\n 'message.trigger.subagent.completed': 'Ejecución del subagente completada',\n 'message.trigger.subagent.aborted': 'Ejecución del subagente detenida',\n 'message.trigger.subagent.error': 'La ejecución del subagente falló',\n 'message.trigger.subagent.maxTokens': 'El subagente alcanzó el límite de tokens',\n 'message.trigger.subagent.refusal': 'El subagente rechazó la tarea',\n 'message.trigger.subagent.unknown': 'La ejecución del subagente terminó de forma inesperada',\n 'message.trigger.github': 'Evento GitHub recibido',\n 'message.trigger.webhook': 'Evento externo recibido',\n 'message.trigger.schedule': 'Tarea de automatización',\n 'message.trigger.job': 'Tarea en segundo plano actualizada',\n 'message.trigger.plugin': 'Estado del complemento actualizado',\n 'message.trigger.explanation': 'Esta notificación desencadenó esta respuesta.',\n 'message.turnProcess.worked': 'Completado',\n 'message.turnProcess.took': 'Completado en ',\n 'message.turnProcess.failed': 'Fallido',\n 'view.chat': 'Chat',\n 'image.open': 'Ver imagen completa',\n 'image.loading': 'Cargando imagen…',\n 'image.failed': 'Vista previa de la imagen no disponible',\n 'image.dialog': 'Vista previa de la imagen',\n 'image.close': 'Cerrar vista previa de la imagen',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} turnos, {steps} pasos',\n 'stats.cacheHit': 'Aciertos de caché: {percent}%',\n 'stats.dialog.title': 'Estadísticas de sesión',\n 'stats.dialog.usageTitle': 'Uso de tokens',\n 'stats.dialog.llmTime': 'tiempo de maestría',\n 'stats.dialog.toolTime': 'tiempo de herramienta',\n 'stats.dialog.ttft': 'Tiempo promedio hasta el primer token (TTFT)',\n 'stats.dialog.speed': 'Fichas por segundo (TPS)',\n 'chat.loadingHistory': 'Cargando historial…',\n 'chat.loadError': 'No se pudo cargar el historial: {message} ({code})',\n 'chat.loadOlder': 'Cargar antes',\n 'chat.loadingOlder': 'Cargando anteriores',\n 'chat.processingOlder': 'Procesando',\n 'chat.retryOlder': 'Reintentar carga',\n 'chat.historyStart': 'Inicio de la conversación',\n 'chat.toBottom': 'Volver al fondo',\n 'chat.deepDiving': 'Razonamiento profundo',\n 'chat.deepDivingFor': 'Razonando a fondo durante {duration} ···',\n 'chat.turnNavigation.label': 'Navegación por turnos',\n 'chat.turnNavigation.jump': 'Ir al turno {turn}',\n 'chat.turnNavigation.jumpLoad': 'Cargar e ir al turno {turn}',\n 'chat.turnNavigation.turn': 'Turno {turn}',\n 'settings.performance.title': 'Rendimiento y uso',\n 'settings.performance.description': 'Elija cuánta información de rendimiento y uso desea mostrar',\n 'settings.performance.compact': 'Compacto',\n 'settings.performance.detailed': 'Detallado',\n 'settings.links.title': 'Abrir enlaces de chat en',\n 'settings.links.description': 'Elija dónde abrir enlaces web',\n 'settings.links.sidebar': 'Barra lateral en la aplicación',\n 'settings.links.newTab': 'Navegador predeterminado',\n 'settings.transcript.title': 'Detalles del trabajo',\n 'settings.transcript.description': 'Elija cuántos detalles mostrar para las llamadas de herramientas',\n 'settings.collapse.title': 'Cuándo contraer los detalles del trabajo',\n 'settings.collapse.description': 'Elija cuándo contraer automáticamente los detalles del trabajo',\n 'settings.collapse.completion': 'Al finalizar',\n 'settings.collapse.nextInput': 'En el siguiente mensaje',\n 'settings.foldedReplies.title': 'Respuestas después del plegado',\n 'settings.foldedReplies.description': 'Elija qué respuestas del asistente permanecen visibles cuando los detalles del trabajo colapsan',\n 'settings.foldedReplies.all': 'Todas las respuestas',\n 'settings.foldedReplies.final': 'Solo respuesta final',\n 'settings.transcript.compact': 'Compacto',\n 'settings.transcript.standard': 'Estándar',\n 'settings.transcript.detailed': 'Detallado',\n 'settings.transcript.verbose': 'Detallado',\n 'fileOpen.title': 'No se pudo abrir el archivo',\n 'fileOpen.unknown': 'No se pudo abrir este archivo',\n 'message.extraBlock': 'Bloque de contenido adicional',\n 'message.systemPrompt': 'Aviso del sistema',\n 'message.systemPromptUpdate': 'Actualización del mensaje del sistema',\n 'message.toolAdded': 'Herramienta agregada: {name}',\n 'message.toolRemoved': 'Herramienta eliminada: {name}',\n 'message.toolsAdded': 'Añadido: {names}',\n 'message.toolsAddedCount': '{count} añadido',\n 'message.toolsChanged': '{added} agregado, {removed} eliminado',\n 'message.toolsRemoved': 'Eliminado: {names}',\n 'message.toolsRemovedCount': '{count} eliminado',\n 'message.toolsUpdated': 'Herramientas actualizadas',\n 'message.contextInjection': 'inyección de contexto',\n 'message.contextRecall': 'Recuerdo de sesión',\n 'message.referenceSummary': 'Sesión referenciada · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'cargado',\n 'message.context.instructions.added': 'añadido',\n 'message.context.instructions.updated': 'actualizado',\n 'message.context.instructions.removed': 'eliminado',\n 'message.context.catalog.replaced': 'Catálogo de repuestos',\n 'message.context.catalog.more': '… {count} más',\n 'message.context.snapshot.supersedes': 'Reemplaza instantáneas anteriores',\n 'message.context.relay.from': 'De la sesión {session}',\n 'message.context.recall.counts': '{retained} mantenido · {omitted} omitido',\n 'message.context.recall.truncated': 'truncado',\n 'message.compaction': 'Contexto compactado',\n 'message.compaction.running': 'Contexto de compactación…',\n 'message.compaction.completed': 'Elementos del historial {items} compactados (~tokens {tokens})',\n 'message.compaction.expand': 'Ver resumen de compactación',\n 'message.compaction.unavailable': 'Resumen de compactación no disponible',\n 'message.compaction.commandTitle': 'compacto',\n 'message.think': 'pensar',\n 'message.unknownSurface': 'Evento de superficie desconocido: {type}',\n 'message.unknownBlock': 'Bloque de contenido desconocido',\n 'message.turnProcess.toolCalls.one': 'Llamada a la herramienta {count}',\n 'message.turnProcess.toolCalls.other': 'Llamadas a herramientas {count}',\n 'message.turnProcess.messages.one': 'Mensaje {count}',\n 'message.turnProcess.messages.other': 'Mensajes {count}',\n 'message.turnProcess.subagents.one': 'Subagente {count}',\n 'message.turnProcess.subagents.other': 'Subagentes {count}',\n 'message.turnProcess.thoughtForAWhile': 'Razonó durante un tiempo',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Detenido',\n 'message.branch': 'Pasar a una nueva conversación',\n 'message.branchUnavailable': 'Disponible solo en el último mensaje de un turno completado',\n 'message.retry.active': 'Reintentando solicitud de modelo',\n 'message.retry.cancelled': 'Reintento de solicitud de modelo cancelado',\n 'message.retry.started': 'Solicitud de modelo reintentada',\n 'message.continuation.requested': 'Se ha solicitado continuar la generación',\n 'message.retry.scheduled': 'Esperando para volver a intentar la solicitud de modelo',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': 'Retraso de reintento: ',\n 'message.retry.failure': 'Razón del fracaso: ',\n 'message.failure.auth': 'La clave API no es válida',\n 'message.taskStopped': 'Tarea detenida',\n 'message.failure.accountSignedOut': 'Se detuvo porque cerró sesión en DeepSeek.',\n '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.',\n '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.',\n 'message.failure.quota': 'Solicitud de cupo agotado.',\n 'message.turnError': 'Este turno falló',\n 'message.maxTokens': 'Se alcanzó el límite del token de salida',\n '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.',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'Uso del turno',\n 'message.turnUsage.consumed': 'Uso {total}',\n 'message.turnUsage.model': 'Proveedor / modelo',\n 'message.turnUsage.cacheHit': 'Aciertos de caché',\n 'message.turnUsage.input': 'Entrada sin caché',\n 'message.turnUsage.cacheRead': 'Entrada en caché',\n 'message.turnUsage.cacheWrite': 'escritura en caché',\n 'message.turnUsage.output': 'Salida',\n 'message.turnUsage.reasoning': ' (razonamiento {tokens})',\n 'message.turnUsage.count': 'Tok {count}',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Corriendo…',\n 'command.failed': 'El comando falló',\n 'command.done': 'Completado',\n 'command.title': 'Comando',\n 'row.running': 'corriendo',\n 'row.failed': 'Fallido',\n 'json.truncated': '… truncado, caracteres {total} en total',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n\n/** French dictionary, checked against the English keys. */\nexport const fr = {\n 'message.stepProcess.thinking': 'Analyser la demande',\n 'message.stepProcess.read': 'Lecture de fichiers',\n 'message.stepProcess.readImage': 'Lire des images',\n 'message.stepProcess.write': 'Écriture de fichiers',\n 'message.stepProcess.search': 'Recherche de code',\n 'message.stepProcess.edit': 'Modification de fichiers',\n 'message.stepProcess.commands': 'Exécuter des commandes',\n 'message.stepProcess.code': 'Exécution du code',\n 'message.stepProcess.webSearch': 'Recherche sur le Web',\n 'message.stepProcess.webFetch': 'Visiter des pages Web',\n 'message.stepProcess.subagents': 'Sous-agents de coordination',\n 'message.stepProcess.plan': 'Mise à jour du plan',\n 'message.stepProcess.questions': 'En attendant votre action',\n 'message.stepProcess.tools': \"Outils d'appel\",\n 'message.stepProcess.prepare.read': 'Préparation à la lecture de fichiers',\n 'message.stepProcess.prepare.readImage': 'Se préparer à lire des images',\n 'message.stepProcess.prepare.write': \"Préparation à l'écriture de fichiers\",\n 'message.stepProcess.prepare.search': 'Préparation à la recherche de code',\n 'message.stepProcess.prepare.edit': 'Préparation à la modification de fichiers',\n 'message.stepProcess.prepare.commands': \"Préparation à l'exécution de commandes\",\n 'message.stepProcess.prepare.code': \"Préparation à l'exécution du code\",\n 'message.stepProcess.prepare.webSearch': 'Se préparer à effectuer une recherche sur le Web',\n 'message.stepProcess.prepare.webFetch': 'Se préparer à visiter des pages Web',\n 'message.stepProcess.prepare.subagents': 'Se préparer à coordonner les sous-agents',\n 'message.stepProcess.prepare.plan': 'Préparation de la mise à jour du plan',\n 'message.stepProcess.prepare.questions': 'Préparation des questions',\n 'message.stepProcess.prepare.tools': \"Préparation des appels d'outils\",\n 'message.stepProcess.done.thinking': 'Analyse terminée',\n 'message.stepProcess.done.read': 'Lire des fichiers',\n 'message.stepProcess.done.readImage': 'Lire des images',\n 'message.stepProcess.done.write': 'A écrit des fichiers',\n 'message.stepProcess.done.search': 'Code recherché',\n 'message.stepProcess.done.edit': 'Fichiers modifiés',\n 'message.stepProcess.done.commands': 'Commandes exécutées',\n 'message.stepProcess.done.code': 'Code exécuté',\n 'message.stepProcess.done.webSearch': \"J'ai cherché sur le Web\",\n 'message.stepProcess.done.webFetch': 'Pages Web visitées',\n 'message.stepProcess.done.subagents': 'Sous-agents coordonnés',\n 'message.stepProcess.done.plan': 'Plan mis à jour',\n 'message.stepProcess.done.questions': 'Questions posées',\n 'message.stepProcess.done.tools': 'Outils appelés',\n 'message.stepProcess.done.context': 'Contexte injecté',\n 'message.stepProcess.joinTwo': '{first} et {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}, etc.',\n 'message.trigger.request': 'Exécution demandée',\n 'message.trigger.goal': 'Objectif continu',\n 'message.trigger.agent': 'Message de tâche reçu',\n 'message.trigger.team': \"Message d'équipe reçu\",\n 'message.trigger.subagent': 'Statut de la sous-tâche mis à jour',\n 'message.trigger.subagent.completed': 'Exécution du sous-agent terminée',\n 'message.trigger.subagent.aborted': 'Exécution du sous-agent arrêtée',\n 'message.trigger.subagent.error': 'Échec de l’exécution du sous-agent',\n 'message.trigger.subagent.maxTokens': 'Le sous-agent a atteint la limite de jetons',\n 'message.trigger.subagent.refusal': 'Le sous-agent a refusé la tâche',\n 'message.trigger.subagent.unknown': 'L’exécution du sous-agent s’est terminée de façon inattendue',\n 'message.trigger.github': 'Événement GitHub reçu',\n 'message.trigger.webhook': 'Événement externe reçu',\n 'message.trigger.schedule': \"Tâche d'automatisation\",\n 'message.trigger.job': 'Tâche en arrière-plan mise à jour',\n 'message.trigger.plugin': 'Statut du plugin mis à jour',\n 'message.trigger.explanation': 'Cette notification a déclenché cette réponse.',\n 'message.turnProcess.worked': 'Terminé',\n 'message.turnProcess.took': 'Terminé en ',\n 'message.turnProcess.failed': 'Échec',\n 'view.chat': 'Discussion',\n 'image.open': \"Voir l'image complète\",\n 'image.loading': \"Chargement de l'image…\",\n 'image.failed': \"Aperçu de l'image indisponible\",\n 'image.dialog': \"Aperçu de l'image\",\n 'image.close': \"Fermer l'aperçu de l'image\",\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} tours, {steps} étapes',\n 'stats.cacheHit': 'Taux de réussite du cache : {percent} %',\n 'stats.dialog.title': 'Statistiques de session',\n 'stats.dialog.usageTitle': 'Utilisation des jetons',\n 'stats.dialog.llmTime': 'Temps LLM',\n 'stats.dialog.toolTime': \"Temps d'outil\",\n 'stats.dialog.ttft': \"Temps moyen jusqu'au premier jeton (TTFT)\",\n 'stats.dialog.speed': 'Jetons par seconde (TPS)',\n 'chat.loadingHistory': \"Chargement de l'historique…\",\n 'chat.loadError': \"Échec du chargement de l'historique : {message} ({code})\",\n 'chat.loadOlder': 'Charger plus tôt',\n 'chat.loadingOlder': 'Chargement en cours',\n 'chat.processingOlder': 'Traitement en cours',\n 'chat.retryOlder': 'Réessayer',\n 'chat.historyStart': 'Début de la conversation',\n 'chat.toBottom': 'Retour en bas',\n 'chat.deepDiving': 'Réflexion approfondie',\n 'chat.deepDivingFor': 'Réflexion approfondie depuis {duration} ···',\n 'chat.turnNavigation.label': 'Navigation entre les tours',\n 'chat.turnNavigation.jump': 'Aller au tour {turn}',\n 'chat.turnNavigation.jumpLoad': 'Charger et aller au tour {turn}',\n 'chat.turnNavigation.turn': 'Tour {turn}',\n 'settings.performance.title': 'Performances et utilisation',\n 'settings.performance.description': \"Choisissez la quantité d'informations sur les performances et l'utilisation à afficher\",\n 'settings.performance.compact': 'Compacte',\n 'settings.performance.detailed': 'Détaillé',\n 'settings.links.title': 'Ouvrir les liens de discussion dans',\n 'settings.links.description': 'Choisissez où ouvrir les liens Web',\n 'settings.links.sidebar': \"Barre latérale dans l'application\",\n 'settings.links.newTab': 'Navigateur par défaut',\n 'settings.transcript.title': 'Détails du travail',\n 'settings.transcript.description': \"Choisissez le niveau de détails à afficher pour les appels d'outils\",\n 'settings.collapse.title': 'Quand réduire les détails du travail',\n 'settings.collapse.description': 'Choisissez quand réduire automatiquement les détails du travail',\n 'settings.collapse.completion': 'À la fin',\n 'settings.collapse.nextInput': 'Au prochain message',\n 'settings.foldedReplies.title': 'Réponses après le repli',\n 'settings.foldedReplies.description': \"Choisissez quelles réponses de l'assistant restent visibles lorsque les détails du travail sont réduits\",\n 'settings.foldedReplies.all': 'Toutes les réponses',\n 'settings.foldedReplies.final': 'Réponse finale seulement',\n 'settings.transcript.compact': 'Compacte',\n 'settings.transcript.standard': 'Norme',\n 'settings.transcript.detailed': 'Détaillé',\n 'settings.transcript.verbose': 'Verbeux',\n 'fileOpen.title': \"Impossible d'ouvrir le fichier\",\n 'fileOpen.unknown': \"Impossible d'ouvrir ce fichier\",\n 'message.extraBlock': 'Bloc de contenu supplémentaire',\n 'message.systemPrompt': 'Invite système',\n 'message.systemPromptUpdate': \"Mise à jour de l'invite du système\",\n 'message.toolAdded': 'Outil ajouté : {name}',\n 'message.toolRemoved': 'Outil supprimé : {name}',\n 'message.toolsAdded': 'Ajouté : {names}',\n 'message.toolsAddedCount': '{count} ajouté',\n 'message.toolsChanged': '{added} ajouté, {removed} supprimé',\n 'message.toolsRemoved': 'Supprimé : {names}',\n 'message.toolsRemovedCount': '{count} supprimé',\n 'message.toolsUpdated': 'Outils mis à jour',\n 'message.contextInjection': 'Injection de contexte',\n 'message.contextRecall': 'Rappel de session',\n 'message.referenceSummary': 'Séance référencée · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'chargé',\n 'message.context.instructions.added': 'ajouté',\n 'message.context.instructions.updated': 'mis à jour',\n 'message.context.instructions.removed': 'supprimé',\n 'message.context.catalog.replaced': 'Catalogue de remplacement',\n 'message.context.catalog.more': '… {count} plus',\n 'message.context.snapshot.supersedes': 'Remplace les instantanés précédents',\n 'message.context.relay.from': 'De la séance {session}',\n 'message.context.recall.counts': '{retained} conservé · {omitted} omis',\n 'message.context.recall.truncated': 'tronqué',\n 'message.compaction': 'Contexte compacté',\n 'message.compaction.running': 'Contexte de compactage…',\n 'message.compaction.completed': \"Éléments d'historique {items} compactés (~jetons {tokens})\",\n 'message.compaction.expand': 'Afficher le résumé du compactage',\n 'message.compaction.unavailable': 'Résumé du compactage indisponible',\n 'message.compaction.commandTitle': 'compacte',\n 'message.think': 'Pensez',\n 'message.unknownSurface': 'Événement de surface inconnu : {type}',\n 'message.unknownBlock': 'Bloc de contenu inconnu',\n 'message.turnProcess.toolCalls.one': \"Appel d'outil {count}\",\n 'message.turnProcess.toolCalls.other': \"Appels d'outil {count}\",\n 'message.turnProcess.messages.one': 'Message {count}',\n 'message.turnProcess.messages.other': 'Messages {count}',\n 'message.turnProcess.subagents.one': 'Sous-agent {count}',\n 'message.turnProcess.subagents.other': 'Sous-agents {count}',\n 'message.turnProcess.thoughtForAWhile': 'Réflexion pendant un moment',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Arrêté',\n 'message.branch': 'Lancez-vous dans une nouvelle conversation',\n 'message.branchUnavailable': \"Disponible uniquement sur le dernier message d'un tour terminé\",\n 'message.retry.active': 'Nouvelle tentative de demande de modèle',\n 'message.retry.cancelled': 'Nouvelle tentative de demande de modèle annulée',\n 'message.retry.started': 'Demande de modèle réessayée',\n 'message.continuation.requested': 'Suite de la génération demandée',\n 'message.retry.scheduled': 'En attente de réessayer la demande de modèle',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}',\n 'message.retry.delay': 'Délai de nouvelle tentative : ',\n 'message.retry.failure': \"Raison de l'échec : \",\n 'message.failure.auth': \"La clé API n'est pas valide\",\n 'message.taskStopped': 'Tâche arrêtée',\n 'message.failure.accountSignedOut': 'Arrêté car vous vous êtes déconnecté de DeepSeek.',\n '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.\",\n 'message.failure.accountSignInRequired': \"Connectez-vous à DeepSeek et assurez-vous que la destination de la demande prend en charge l'authentification du compte.\",\n 'message.failure.quota': 'Quota de demandes épuisé.',\n 'message.turnError': 'Ce tour a échoué',\n 'message.maxTokens': 'Limite de jetons de sortie atteinte',\n 'message.maxTokens.hint': 'La réponse fut coupée ; la sortie antérieure est conservée dans la conversation. Envoyez « continuer » pour laisser le modèle reprendre.',\n 'message.tokensPerSecond': '{tps} jetons/s',\n 'message.turnUsage.title': 'Consommation du tour',\n 'message.turnUsage.consumed': 'Utilisation {total}',\n 'message.turnUsage.model': 'Fournisseur / modèle',\n 'message.turnUsage.cacheHit': 'Taux de réussite du cache',\n 'message.turnUsage.input': 'Entrée non mise en cache',\n 'message.turnUsage.cacheRead': 'Entrée en cache',\n 'message.turnUsage.cacheWrite': 'Écriture en cache',\n 'message.turnUsage.output': 'Sortie',\n 'message.turnUsage.reasoning': ' (raisonnement {tokens})',\n 'message.turnUsage.count': 'Jeton {count}',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Courir…',\n 'command.failed': 'La commande a échoué',\n 'command.done': 'Terminé',\n 'command.title': 'Commande',\n 'row.running': 'Courir',\n 'row.failed': 'Échec',\n 'json.truncated': '… tronqué, nombre total de caractères {total}',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n\n/** German dictionary, checked against the English keys. */\nexport const de = {\n 'message.stepProcess.thinking': 'Analyse der Anfrage',\n 'message.stepProcess.read': 'Dateien lesen',\n 'message.stepProcess.readImage': 'Bilder lesen',\n 'message.stepProcess.write': 'Dateien schreiben',\n 'message.stepProcess.search': 'Code wird gesucht',\n 'message.stepProcess.edit': 'Bearbeiten von Dateien',\n 'message.stepProcess.commands': 'Befehle ausführen',\n 'message.stepProcess.code': 'Ausführen von Code',\n 'message.stepProcess.webSearch': 'Suche im Internet',\n 'message.stepProcess.webFetch': 'Besuch von Webseiten',\n 'message.stepProcess.subagents': 'Koordinierende Unteragenten',\n 'message.stepProcess.plan': 'Aktualisierung des Plans',\n 'message.stepProcess.questions': 'Ich warte auf Ihre Aktion',\n 'message.stepProcess.tools': 'Aufrufende Werkzeuge',\n 'message.stepProcess.prepare.read': 'Vorbereitung zum Lesen von Dateien',\n 'message.stepProcess.prepare.readImage': 'Vorbereitung zum Lesen von Bildern',\n 'message.stepProcess.prepare.write': 'Vorbereitung zum Schreiben von Dateien',\n 'message.stepProcess.prepare.search': 'Vorbereiten der Codesuche',\n 'message.stepProcess.prepare.edit': 'Vorbereitung zum Bearbeiten von Dateien',\n 'message.stepProcess.prepare.commands': 'Vorbereitung zum Ausführen von Befehlen',\n 'message.stepProcess.prepare.code': 'Vorbereiten, Code auszuführen',\n 'message.stepProcess.prepare.webSearch': 'Bereiten Sie sich auf die Suche im Internet vor',\n 'message.stepProcess.prepare.webFetch': 'Vorbereitung auf den Besuch von Webseiten',\n 'message.stepProcess.prepare.subagents': 'Vorbereitung zur Koordinierung von Subagenten',\n 'message.stepProcess.prepare.plan': 'Vorbereitung zur Aktualisierung des Plans',\n 'message.stepProcess.prepare.questions': 'Fragen vorbereiten',\n 'message.stepProcess.prepare.tools': 'Toolaufrufe vorbereiten',\n 'message.stepProcess.done.thinking': 'Analyse abgeschlossen',\n 'message.stepProcess.done.read': 'Dateien lesen',\n 'message.stepProcess.done.readImage': 'Bilder lesen',\n 'message.stepProcess.done.write': 'Dateien geschrieben',\n 'message.stepProcess.done.search': 'Gesuchter Code',\n 'message.stepProcess.done.edit': 'Bearbeitete Dateien',\n 'message.stepProcess.done.commands': 'Befehle ausgeführt',\n 'message.stepProcess.done.code': 'Code ausgeführt',\n 'message.stepProcess.done.webSearch': 'Habe das Internet durchsucht',\n 'message.stepProcess.done.webFetch': 'Besuchte Webseiten',\n 'message.stepProcess.done.subagents': 'Koordinierte Unteragenten',\n 'message.stepProcess.done.plan': 'Plan aktualisiert',\n 'message.stepProcess.done.questions': 'Gestellte Fragen',\n 'message.stepProcess.done.tools': 'Werkzeuge genannt',\n 'message.stepProcess.done.context': 'Kontext injiziert',\n 'message.stepProcess.joinTwo': '{first} und {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title} usw.',\n 'message.trigger.request': 'Ausführung beantragt',\n 'message.trigger.goal': 'Weiterführendes Ziel',\n 'message.trigger.agent': 'Aufgabennachricht erhalten',\n 'message.trigger.team': 'Teamnachricht erhalten',\n 'message.trigger.subagent': 'Unteraufgabenstatus aktualisiert',\n 'message.trigger.subagent.completed': 'Ausführung des Subagenten abgeschlossen',\n 'message.trigger.subagent.aborted': 'Ausführung des Subagenten gestoppt',\n 'message.trigger.subagent.error': 'Ausführung des Subagenten fehlgeschlagen',\n 'message.trigger.subagent.maxTokens': 'Subagent hat das Token-Limit erreicht',\n 'message.trigger.subagent.refusal': 'Subagent hat die Aufgabe abgelehnt',\n 'message.trigger.subagent.unknown': 'Ausführung des Subagenten unerwartet beendet',\n 'message.trigger.github': 'GitHub-Ereignis empfangen',\n 'message.trigger.webhook': 'Externes Ereignis empfangen',\n 'message.trigger.schedule': 'Automatisierungsaufgabe',\n 'message.trigger.job': 'Hintergrundaufgabe aktualisiert',\n 'message.trigger.plugin': 'Plugin-Status aktualisiert',\n 'message.trigger.explanation': 'Diese Benachrichtigung hat diese Reaktion ausgelöst.',\n 'message.turnProcess.worked': 'Abgeschlossen',\n 'message.turnProcess.took': 'Fertiggestellt in ',\n 'message.turnProcess.failed': 'Fehlgeschlagen',\n 'view.chat': 'Chat',\n 'image.open': 'Vollständiges Bild anzeigen',\n 'image.loading': 'Bild wird geladen…',\n 'image.failed': 'Bildvorschau nicht verfügbar',\n 'image.dialog': 'Bildvorschau',\n 'image.close': 'Bildvorschau schließen',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} Runden, {steps} Schritte',\n 'stats.cacheHit': 'Cache-Treffer: {percent}%',\n 'stats.dialog.title': 'Sitzungsstatistiken',\n 'stats.dialog.usageTitle': 'Token-Nutzung',\n 'stats.dialog.llmTime': 'LLM-Zeit',\n 'stats.dialog.toolTime': 'Werkzeugzeit',\n 'stats.dialog.ttft': 'Durchschnittliche Zeit bis zum ersten Token (TTFT)',\n 'stats.dialog.speed': 'Token pro Sekunde (TPS)',\n 'chat.loadingHistory': 'Verlauf wird geladen…',\n 'chat.loadError': 'Fehler beim Laden des Verlaufs: {message} ({code})',\n 'chat.loadOlder': 'Früher laden',\n 'chat.loadingOlder': 'Wird geladen',\n 'chat.processingOlder': 'Wird verarbeitet',\n 'chat.retryOlder': 'Erneut laden',\n 'chat.historyStart': 'Anfang der Unterhaltung',\n 'chat.toBottom': 'Zurück nach unten',\n 'chat.deepDiving': 'Gründliches Nachdenken',\n 'chat.deepDivingFor': 'Gründliches Nachdenken seit {duration} ···',\n 'chat.turnNavigation.label': 'Rundennavigation',\n 'chat.turnNavigation.jump': 'Zu Runde {turn} springen',\n 'chat.turnNavigation.jumpLoad': 'Runde {turn} laden und öffnen',\n 'chat.turnNavigation.turn': 'Runde {turn}',\n 'settings.performance.title': 'Leistung und Nutzung',\n 'settings.performance.description': 'Wählen Sie aus, wie viele Leistungs- und Nutzungsinformationen angezeigt werden sollen',\n 'settings.performance.compact': 'Kompakt',\n 'settings.performance.detailed': 'Ausführlich',\n 'settings.links.title': 'Öffnen Sie Chat-Links in',\n 'settings.links.description': 'Wählen Sie aus, wo Weblinks geöffnet werden sollen',\n 'settings.links.sidebar': 'In-App-Seitenleiste',\n 'settings.links.newTab': 'Standardbrowser',\n 'settings.transcript.title': 'Arbeitsdetails',\n 'settings.transcript.description': 'Wählen Sie aus, wie viele Details für Werkzeugaufrufe angezeigt werden sollen',\n 'settings.collapse.title': 'Wann Arbeitsdetails minimiert werden sollten',\n 'settings.collapse.description': 'Wählen Sie aus, wann Arbeitsdetails automatisch ausgeblendet werden sollen',\n 'settings.collapse.completion': 'Nach Fertigstellung',\n 'settings.collapse.nextInput': 'Bei der nächsten Nachricht',\n 'settings.foldedReplies.title': 'Antworten nach dem Einklappen',\n 'settings.foldedReplies.description': 'Wählen Sie aus, welche Assistentenantworten sichtbar bleiben, wenn die Arbeitsdetails ausgeblendet werden',\n 'settings.foldedReplies.all': 'Alle Antworten',\n 'settings.foldedReplies.final': 'Nur die endgültige Antwort',\n 'settings.transcript.compact': 'Kompakt',\n 'settings.transcript.standard': 'Standard',\n 'settings.transcript.detailed': 'Ausführlich',\n 'settings.transcript.verbose': 'Ausführlich',\n 'fileOpen.title': 'Datei konnte nicht geöffnet werden',\n 'fileOpen.unknown': 'Diese Datei konnte nicht geöffnet werden',\n 'message.extraBlock': 'Zusätzlicher Inhaltsblock',\n 'message.systemPrompt': 'Systemaufforderung',\n 'message.systemPromptUpdate': 'Aktualisierung der Systemaufforderung',\n 'message.toolAdded': 'Tool hinzugefügt: {name}',\n 'message.toolRemoved': 'Entferntes Werkzeug: {name}',\n 'message.toolsAdded': 'Hinzugefügt: {names}',\n 'message.toolsAddedCount': '{count} hinzugefügt',\n 'message.toolsChanged': '{added} hinzugefügt, {removed} entfernt',\n 'message.toolsRemoved': 'Entfernt: {names}',\n 'message.toolsRemovedCount': '{count} entfernt',\n 'message.toolsUpdated': 'Werkzeuge aktualisiert',\n 'message.contextInjection': 'Kontextinjektion',\n 'message.contextRecall': 'Sitzungsrückruf',\n 'message.referenceSummary': 'Referenzierte Sitzung · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'geladen',\n 'message.context.instructions.added': 'hinzugefügt',\n 'message.context.instructions.updated': 'aktualisiert',\n 'message.context.instructions.removed': 'entfernt',\n 'message.context.catalog.replaced': 'Ersatzkatalog',\n 'message.context.catalog.more': '… {count} mehr',\n 'message.context.snapshot.supersedes': 'Ersetzt frühere Schnappschüsse',\n 'message.context.relay.from': 'Aus der Sitzung {session}',\n 'message.context.recall.counts': '{retained} beibehalten · {omitted} weggelassen',\n 'message.context.recall.truncated': 'abgeschnitten',\n 'message.compaction': 'Kontext verdichtet',\n 'message.compaction.running': 'Kontext verdichten…',\n 'message.compaction.completed': 'Komprimierte {items}-Verlaufselemente (~{tokens}-Tokens)',\n 'message.compaction.expand': 'Komprimierungszusammenfassung anzeigen',\n 'message.compaction.unavailable': 'Komprimierungszusammenfassung nicht verfügbar',\n 'message.compaction.commandTitle': 'kompakt',\n 'message.think': 'Denken Sie nach',\n 'message.unknownSurface': 'Unbekanntes Oberflächenereignis: {type}',\n 'message.unknownBlock': 'Unbekannter Inhaltsblock',\n 'message.turnProcess.toolCalls.one': 'Werkzeugaufruf {count}',\n 'message.turnProcess.toolCalls.other': '{count} Toolaufrufe',\n 'message.turnProcess.messages.one': '{count}-Nachricht',\n 'message.turnProcess.messages.other': '{count}-Nachrichten',\n 'message.turnProcess.subagents.one': '{count}-Subagent',\n 'message.turnProcess.subagents.other': '{count}-Subagenten',\n 'message.turnProcess.thoughtForAWhile': 'Eine Weile nachgedacht',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Angehalten',\n 'message.branch': 'Verzweigen Sie in ein neues Gespräch',\n 'message.branchUnavailable': 'Nur verfügbar bei der letzten Nachricht einer abgeschlossenen Runde',\n 'message.retry.active': 'Modellanforderung wird erneut versucht',\n 'message.retry.cancelled': 'Wiederholungsversuch der Modellanforderung abgebrochen',\n 'message.retry.started': 'Modellanfrage erneut versucht',\n 'message.continuation.requested': 'Fortsetzung der Generierung angefordert',\n 'message.retry.scheduled': 'Warten auf erneuten Versuch der Modellanforderung',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': 'Wiederholungsverzögerung: ',\n 'message.retry.failure': 'Fehlergrund: ',\n 'message.failure.auth': 'Der API-Schlüssel ist ungültig',\n 'message.taskStopped': 'Aufgabe gestoppt',\n 'message.failure.accountSignedOut': 'Gestoppt, weil Sie sich von DeepSeek abgemeldet haben.',\n '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.',\n 'message.failure.accountSignInRequired': 'Melden Sie sich bei DeepSeek an und stellen Sie sicher, dass das Anforderungsziel die Kontoauthentifizierung unterstützt.',\n 'message.failure.quota': 'Anforderungskontingent ausgeschöpft.',\n 'message.turnError': 'Diese Runde ist fehlgeschlagen',\n 'message.maxTokens': 'Ausgabe-Token-Limit erreicht',\n 'message.maxTokens.hint': 'Die Antwort wurde abgeschnitten; Frühere Ausgaben bleiben in der Konversation erhalten. Senden Sie „Weiter“, um das Modell fortzusetzen.',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'Rundenverbrauch',\n 'message.turnUsage.consumed': 'Verwendung {total}',\n 'message.turnUsage.model': 'Anbieter / Modell',\n 'message.turnUsage.cacheHit': 'Cache-Treffer',\n 'message.turnUsage.input': 'Nicht zwischengespeicherte Eingabe',\n 'message.turnUsage.cacheRead': 'Zwischengespeicherte Eingabe',\n 'message.turnUsage.cacheWrite': 'Cache-Schreiben',\n 'message.turnUsage.output': 'Ausgabe',\n 'message.turnUsage.reasoning': ' ({tokens}-Argumentation)',\n 'message.turnUsage.count': '{count}-Token',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Laufen…',\n 'command.failed': 'Der Befehl ist fehlgeschlagen',\n 'command.done': 'Abgeschlossen',\n 'command.title': 'Befehl',\n 'row.running': 'Laufen',\n 'row.failed': 'Fehlgeschlagen',\n 'json.truncated': '… gekürzt, {total} Zeichen insgesamt',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n\n/** Russian dictionary, checked against the English keys. */\nexport const ru = {\n 'message.stepProcess.thinking': 'Анализ запроса',\n 'message.stepProcess.read': 'Чтение файлов',\n 'message.stepProcess.readImage': 'Чтение изображений',\n 'message.stepProcess.write': 'Запись файлов',\n 'message.stepProcess.search': 'Поиск кода',\n 'message.stepProcess.edit': 'Редактирование файлов',\n 'message.stepProcess.commands': 'Запуск команд',\n 'message.stepProcess.code': 'Запуск кода',\n 'message.stepProcess.webSearch': 'Поиск в Интернете',\n 'message.stepProcess.webFetch': 'Посещение веб-страниц',\n 'message.stepProcess.subagents': 'Координирующие субагенты',\n 'message.stepProcess.plan': 'Обновление плана',\n 'message.stepProcess.questions': 'Жду ваших действий',\n 'message.stepProcess.tools': 'Вызов инструментов',\n 'message.stepProcess.prepare.read': 'Подготовка к чтению файлов',\n 'message.stepProcess.prepare.readImage': 'Подготовка к чтению изображений',\n 'message.stepProcess.prepare.write': 'Подготовка к записи файлов',\n 'message.stepProcess.prepare.search': 'Подготовка к поиску кода',\n 'message.stepProcess.prepare.edit': 'Подготовка к редактированию файлов',\n 'message.stepProcess.prepare.commands': 'Подготовка к выполнению команд',\n 'message.stepProcess.prepare.code': 'Подготовка к запуску кода',\n 'message.stepProcess.prepare.webSearch': 'Подготовка к поиску в Интернете',\n 'message.stepProcess.prepare.webFetch': 'Подготовка к посещению веб-страниц',\n 'message.stepProcess.prepare.subagents': 'Подготовка к координации субагентов',\n 'message.stepProcess.prepare.plan': 'Подготовка к обновлению плана',\n 'message.stepProcess.prepare.questions': 'Подготовка вопросов',\n 'message.stepProcess.prepare.tools': 'Подготовка вызовов инструментов',\n 'message.stepProcess.done.thinking': 'Анализ завершен',\n 'message.stepProcess.done.read': 'Чтение файлов',\n 'message.stepProcess.done.readImage': 'Чтение изображений',\n 'message.stepProcess.done.write': 'Написал файлы',\n 'message.stepProcess.done.search': 'Искомый код',\n 'message.stepProcess.done.edit': 'Отредактированные файлы',\n 'message.stepProcess.done.commands': 'Выполнение команд',\n 'message.stepProcess.done.code': 'Выполненный код',\n 'message.stepProcess.done.webSearch': 'Искал в Интернете',\n 'message.stepProcess.done.webFetch': 'Посещенные веб-страницы',\n 'message.stepProcess.done.subagents': 'Координированные субагенты',\n 'message.stepProcess.done.plan': 'Обновлен план',\n 'message.stepProcess.done.questions': 'Задаваемые вопросы',\n 'message.stepProcess.done.tools': 'Вызываемые инструменты',\n 'message.stepProcess.done.context': 'Контекст внедрён',\n 'message.stepProcess.joinTwo': '{first} и {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title} и т. д.',\n 'message.trigger.request': 'Запрошено выполнение',\n 'message.trigger.goal': 'Постоянная цель',\n 'message.trigger.agent': 'Сообщение о задаче получено',\n 'message.trigger.team': 'Сообщение команды получено',\n 'message.trigger.subagent': 'Статус подзадачи обновлен',\n 'message.trigger.subagent.completed': 'Работа субагента завершена',\n 'message.trigger.subagent.aborted': 'Работа субагента остановлена',\n 'message.trigger.subagent.error': 'Работа субагента завершилась с ошибкой',\n 'message.trigger.subagent.maxTokens': 'Субагент достиг лимита токенов',\n 'message.trigger.subagent.refusal': 'Субагент отказался выполнять задачу',\n 'message.trigger.subagent.unknown': 'Работа субагента неожиданно завершилась',\n 'message.trigger.github': 'Событие GitHub получено',\n 'message.trigger.webhook': 'Получено внешнее событие',\n 'message.trigger.schedule': 'Задача автоматизации',\n 'message.trigger.job': 'Фоновая задача обновлена.',\n 'message.trigger.plugin': 'Статус плагина обновлен',\n 'message.trigger.explanation': 'Это уведомление вызвало такой ответ.',\n 'message.turnProcess.worked': 'Завершено',\n 'message.turnProcess.took': 'Завершено в ',\n 'message.turnProcess.failed': 'Не удалось',\n 'view.chat': 'Чат',\n 'image.open': 'Посмотреть полное изображение',\n 'image.loading': 'Загрузка изображения…',\n 'image.failed': 'Предварительный просмотр изображения недоступен.',\n 'image.dialog': 'Предварительный просмотр изображения',\n 'image.close': 'Закрыть предварительный просмотр изображения',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': 'Ходов: {turns}, шагов: {steps}',\n 'stats.cacheHit': 'Попадание в кэш: {percent}%',\n 'stats.dialog.title': 'Статистика сеансов',\n 'stats.dialog.usageTitle': 'Использование токена',\n 'stats.dialog.llmTime': 'время магистратуры',\n 'stats.dialog.toolTime': 'Время работы инструмента',\n 'stats.dialog.ttft': 'Среднее время до первого токена (TTFT)',\n 'stats.dialog.speed': 'Токенов в секунду (TPS)',\n 'chat.loadingHistory': 'Загрузка истории…',\n 'chat.loadError': 'Не удалось загрузить историю: {message} ({code})',\n 'chat.loadOlder': 'Загрузить раньше',\n 'chat.loadingOlder': 'Загрузка истории',\n 'chat.processingOlder': 'Обработка',\n 'chat.retryOlder': 'Повторить загрузку',\n 'chat.historyStart': 'Начало разговора',\n 'chat.toBottom': 'Вернуться к низу',\n 'chat.deepDiving': 'Глубокое размышление',\n 'chat.deepDivingFor': 'Глубокое размышление в течение {duration} ···',\n 'chat.turnNavigation.label': 'Навигация по ходам',\n 'chat.turnNavigation.jump': 'Перейти к ходу {turn}',\n 'chat.turnNavigation.jumpLoad': 'Загрузить ход {turn} и перейти к нему',\n 'chat.turnNavigation.turn': 'Ход {turn}',\n 'settings.performance.title': 'Производительность и использование',\n 'settings.performance.description': 'Выберите, какой объем информации о производительности и использовании показывать',\n 'settings.performance.compact': 'Компактный',\n 'settings.performance.detailed': 'Подробный',\n 'settings.links.title': 'Открыть ссылки на чат в',\n 'settings.links.description': 'Выберите, где открывать веб-ссылки',\n 'settings.links.sidebar': 'Боковая панель в приложении',\n 'settings.links.newTab': 'Браузер по умолчанию',\n 'settings.transcript.title': 'Детали работы',\n 'settings.transcript.description': 'Выберите, насколько подробно следует отображать вызовы инструментов.',\n 'settings.collapse.title': 'Когда сворачивать детали работы',\n 'settings.collapse.description': 'Выберите, когда автоматически сворачивать сведения о работе',\n 'settings.collapse.completion': 'По завершении',\n 'settings.collapse.nextInput': 'В следующем сообщении',\n 'settings.foldedReplies.title': 'Ответы после сворачивания',\n 'settings.foldedReplies.description': 'Выберите, какие ответы помощника останутся видимыми, когда сведения о работе будут свернуты.',\n 'settings.foldedReplies.all': 'Все ответы',\n 'settings.foldedReplies.final': 'Только окончательный ответ',\n 'settings.transcript.compact': 'Компактный',\n 'settings.transcript.standard': 'Стандартный',\n 'settings.transcript.detailed': 'Подробный',\n 'settings.transcript.verbose': 'Многословный',\n 'fileOpen.title': 'Не удалось открыть файл',\n 'fileOpen.unknown': 'Не удалось открыть этот файл',\n 'message.extraBlock': 'Дополнительный блок контента',\n 'message.systemPrompt': 'Системная подсказка',\n 'message.systemPromptUpdate': 'Обновление системного запроса',\n 'message.toolAdded': 'Добавлен инструмент: {name}.',\n 'message.toolRemoved': 'Инструмент удален: {name}.',\n 'message.toolsAdded': 'Добавлено: {names}',\n 'message.toolsAddedCount': '{count} добавлен',\n 'message.toolsChanged': '{added} добавлен, {removed} удален.',\n 'message.toolsRemoved': 'Удалено: {names}.',\n 'message.toolsRemovedCount': '{count} удален.',\n 'message.toolsUpdated': 'Инструменты обновлены',\n 'message.contextInjection': 'Внедрение контекста',\n 'message.contextRecall': 'Отзыв сеанса',\n 'message.referenceSummary': 'Ссылка на сессию · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'загружен',\n 'message.context.instructions.added': 'добавлено',\n 'message.context.instructions.updated': 'обновлено',\n 'message.context.instructions.removed': 'удалено',\n 'message.context.catalog.replaced': 'Каталог замены',\n 'message.context.catalog.more': '… {count} ещё',\n 'message.context.snapshot.supersedes': 'Заменяет предыдущие снимки',\n 'message.context.relay.from': 'Из сеанса {session}',\n 'message.context.recall.counts': '{retained} сохранен · {omitted} опущен',\n 'message.context.recall.truncated': 'усеченный',\n 'message.compaction': 'Контекст сжат',\n 'message.compaction.running': 'Сжатие контекста…',\n 'message.compaction.completed': 'Сжатые элементы истории {items} (токены ~{tokens})',\n 'message.compaction.expand': 'Посмотреть сводку по уплотнению',\n 'message.compaction.unavailable': 'Сводка по уплотнению недоступна.',\n 'message.compaction.commandTitle': 'компактный',\n 'message.think': 'Подумайте',\n 'message.unknownSurface': 'Неизвестное событие на поверхности: {type}.',\n 'message.unknownBlock': 'Неизвестный блок контента',\n 'message.turnProcess.toolCalls.one': '{count} вызов инструмента',\n 'message.turnProcess.toolCalls.other': '{count} вызовов инструментов',\n 'message.turnProcess.messages.one': 'Сообщение {count}',\n 'message.turnProcess.messages.other': 'Сообщения {count}',\n 'message.turnProcess.subagents.one': 'Субагент {count}',\n 'message.turnProcess.subagents.other': 'Субагенты {count}',\n 'message.turnProcess.thoughtForAWhile': 'Размышлял некоторое время',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Остановлено',\n 'message.branch': 'Перейти к новому разговору',\n 'message.branchUnavailable': 'Доступно только в последнем сообщении о завершенном ходу.',\n 'message.retry.active': 'Повторный запрос модели',\n 'message.retry.cancelled': 'Повтор запроса модели отменен.',\n 'message.retry.started': 'Повторный запрос модели',\n 'message.continuation.requested': 'Запрошено продолжение генерации',\n 'message.retry.scheduled': 'Ожидание повторного запроса модели',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': 'Задержка повтора: ',\n 'message.retry.failure': 'Причина неисправности: ',\n 'message.failure.auth': 'Ключ API недействителен.',\n 'message.taskStopped': 'Задача остановлена',\n 'message.failure.accountSignedOut': 'Остановлено, поскольку вы вышли из DeepSeek.',\n 'message.failure.interrupted': 'Процесс DSH завершился до завершения этого хода (например, был завершен, произошел сбой или истекло время ожидания при завершении работы), поэтому ход был закрыт при перезапуске DSH. Незавершенные вызовы инструментов имеют неизвестные результаты.',\n 'message.failure.accountSignInRequired': 'Войдите в DeepSeek и убедитесь, что пункт назначения запроса поддерживает аутентификацию учетной записи.',\n 'message.failure.quota': 'Квота запросов исчерпана.',\n 'message.turnError': 'Этот ход завершился ошибкой',\n 'message.maxTokens': 'Достигнут предел выходных токенов',\n 'message.maxTokens.hint': 'Ответ был прерван; более ранний вывод сохраняется в разговоре. Отправьте «продолжить», чтобы модель возобновила работу.',\n 'message.tokensPerSecond': '{tps} ток/с',\n 'message.turnUsage.title': 'Использование ресурсов за ход',\n 'message.turnUsage.consumed': 'Использование {total}',\n 'message.turnUsage.model': 'Поставщик/модель',\n 'message.turnUsage.cacheHit': 'Попадание в кэш',\n 'message.turnUsage.input': 'Некэшированный ввод',\n 'message.turnUsage.cacheRead': 'Кэшированный ввод',\n 'message.turnUsage.cacheWrite': 'Запись в кэш',\n 'message.turnUsage.output': 'Выход',\n 'message.turnUsage.reasoning': ' (рассуждение {tokens})',\n 'message.turnUsage.count': '{count} ток',\n 'duration.secondUnit': 'с',\n 'duration.minuteUnit': 'м ',\n 'duration.hourUnit': 'ч ',\n 'command.running': 'Бег…',\n 'command.failed': 'Команда не выполнена',\n 'command.done': 'Завершено',\n 'command.title': 'Команда',\n 'row.running': 'Бег',\n 'row.failed': 'Не удалось',\n 'json.truncated': '… усечено, всего символов {total}',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n\n/** Portuguese dictionary, checked against the English keys. */\nexport const pt = {\n 'message.stepProcess.thinking': 'Analisando a solicitação',\n 'message.stepProcess.read': 'Lendo arquivos',\n 'message.stepProcess.readImage': 'Lendo imagens',\n 'message.stepProcess.write': 'Gravando arquivos',\n 'message.stepProcess.search': 'Pesquisando código',\n 'message.stepProcess.edit': 'Editando arquivos',\n 'message.stepProcess.commands': 'Executando comandos',\n 'message.stepProcess.code': 'Executando código',\n 'message.stepProcess.webSearch': 'Pesquisando na web',\n 'message.stepProcess.webFetch': 'Visitando páginas da web',\n 'message.stepProcess.subagents': 'Coordenando subagentes',\n 'message.stepProcess.plan': 'Atualizando o plano',\n 'message.stepProcess.questions': 'Esperando por sua ação',\n 'message.stepProcess.tools': 'Ferramentas de chamada',\n 'message.stepProcess.prepare.read': 'Preparando-se para ler arquivos',\n 'message.stepProcess.prepare.readImage': 'Preparando-se para ler imagens',\n 'message.stepProcess.prepare.write': 'Preparando-se para gravar arquivos',\n 'message.stepProcess.prepare.search': 'Preparando-se para pesquisar o código',\n 'message.stepProcess.prepare.edit': 'Preparando-se para editar arquivos',\n 'message.stepProcess.prepare.commands': 'Preparando para executar comandos',\n 'message.stepProcess.prepare.code': 'Preparando-se para executar o código',\n 'message.stepProcess.prepare.webSearch': 'Preparando-se para pesquisar na web',\n 'message.stepProcess.prepare.webFetch': 'Preparando-se para visitar páginas da web',\n 'message.stepProcess.prepare.subagents': 'Preparando-se para coordenar subagentes',\n 'message.stepProcess.prepare.plan': 'Preparando-se para atualizar o plano',\n 'message.stepProcess.prepare.questions': 'Preparando perguntas',\n 'message.stepProcess.prepare.tools': 'Preparando chamadas de ferramenta',\n 'message.stepProcess.done.thinking': 'Análise concluída',\n 'message.stepProcess.done.read': 'Ler arquivos',\n 'message.stepProcess.done.readImage': 'Ler imagens',\n 'message.stepProcess.done.write': 'Escreveu arquivos',\n 'message.stepProcess.done.search': 'Código pesquisado',\n 'message.stepProcess.done.edit': 'Arquivos editados',\n 'message.stepProcess.done.commands': 'Comandos executados',\n 'message.stepProcess.done.code': 'Código executado',\n 'message.stepProcess.done.webSearch': 'Pesquisei na web',\n 'message.stepProcess.done.webFetch': 'Páginas da web visitadas',\n 'message.stepProcess.done.subagents': 'Subagentes coordenados',\n 'message.stepProcess.done.plan': 'Atualizado o plano',\n 'message.stepProcess.done.questions': 'Perguntas feitas',\n 'message.stepProcess.done.tools': 'Ferramentas chamadas',\n 'message.stepProcess.done.context': 'Contexto injetado',\n 'message.stepProcess.joinTwo': '{first} e {second}',\n 'message.stepProcess.comma': ', ',\n 'message.stepProcess.sharedPrefix': '',\n 'message.stepProcess.more': '{title}, etc.',\n 'message.trigger.request': 'Execução solicitada',\n 'message.trigger.goal': 'Objetivo contínuo',\n 'message.trigger.agent': 'Mensagem de tarefa recebida',\n 'message.trigger.team': 'Mensagem da equipe recebida',\n 'message.trigger.subagent': 'Status da subtarefa atualizado',\n 'message.trigger.subagent.completed': 'Execução do subagente concluída',\n 'message.trigger.subagent.aborted': 'Execução do subagente interrompida',\n 'message.trigger.subagent.error': 'Falha na execução do subagente',\n 'message.trigger.subagent.maxTokens': 'O subagente atingiu o limite de tokens',\n 'message.trigger.subagent.refusal': 'O subagente recusou a tarefa',\n 'message.trigger.subagent.unknown': 'A execução do subagente terminou inesperadamente',\n 'message.trigger.github': 'GitHub evento recebido',\n 'message.trigger.webhook': 'Evento externo recebido',\n 'message.trigger.schedule': 'Tarefa de automação',\n 'message.trigger.job': 'Tarefa em segundo plano atualizada',\n 'message.trigger.plugin': 'Status do plug-in atualizado',\n 'message.trigger.explanation': 'Esta notificação desencadeou esta resposta.',\n 'message.turnProcess.worked': 'Concluído',\n 'message.turnProcess.took': 'Concluído em ',\n 'message.turnProcess.failed': 'Falha',\n 'view.chat': 'Chat',\n 'image.open': 'Ver imagem completa',\n 'image.loading': 'Carregando imagem…',\n 'image.failed': 'Visualização da imagem indisponível',\n 'image.dialog': 'Visualização da imagem',\n 'image.close': 'Fechar visualização da imagem',\n 'number.groupSeparator': ',',\n 'duration.compactSeconds': '{seconds}s',\n 'duration.compactMinutes': '{minutes}m{seconds}s',\n 'duration.milliseconds': '{milliseconds}ms',\n 'stats.counts': '{turns} turnos, {steps} etapas',\n 'stats.cacheHit': 'Acertos no cache: {percent}%',\n 'stats.dialog.title': 'Estatísticas da sessão',\n 'stats.dialog.usageTitle': 'Uso de token',\n 'stats.dialog.llmTime': 'Horário do LLM',\n 'stats.dialog.toolTime': 'Tempo da ferramenta',\n 'stats.dialog.ttft': 'Tempo médio para o primeiro token (TTFT)',\n 'stats.dialog.speed': 'Tokens por segundo (TPS)',\n 'chat.loadingHistory': 'Carregando histórico…',\n 'chat.loadError': 'Falha ao carregar o histórico: {message} ({code})',\n 'chat.loadOlder': 'Carregar mais cedo',\n 'chat.loadingOlder': 'Carregando anteriores',\n 'chat.processingOlder': 'Processando',\n 'chat.retryOlder': 'Tentar novamente',\n 'chat.historyStart': 'Início da conversa',\n 'chat.toBottom': 'De volta ao fundo',\n 'chat.deepDiving': 'Raciocínio profundo',\n 'chat.deepDivingFor': 'Raciocínio profundo há {duration} ···',\n 'chat.turnNavigation.label': 'Navegação entre turnos',\n 'chat.turnNavigation.jump': 'Ir para o turno {turn}',\n 'chat.turnNavigation.jumpLoad': 'Carregar e ir para o turno {turn}',\n 'chat.turnNavigation.turn': 'Turno {turn}',\n 'settings.performance.title': 'Desempenho e uso',\n 'settings.performance.description': 'Escolha quantas informações de desempenho e uso serão exibidas',\n 'settings.performance.compact': 'Compacto',\n 'settings.performance.detailed': 'Detalhado',\n 'settings.links.title': 'Abra links de bate-papo em',\n 'settings.links.description': 'Escolha onde abrir links da web',\n 'settings.links.sidebar': 'Barra lateral no aplicativo',\n 'settings.links.newTab': 'Navegador padrão',\n 'settings.transcript.title': 'Detalhes do trabalho',\n 'settings.transcript.description': 'Escolha quantos detalhes serão exibidos nas chamadas de ferramenta',\n 'settings.collapse.title': 'Quando recolher detalhes do trabalho',\n 'settings.collapse.description': 'Escolha quando recolher automaticamente os detalhes do trabalho',\n 'settings.collapse.completion': 'Na conclusão',\n 'settings.collapse.nextInput': 'Na próxima mensagem',\n 'settings.foldedReplies.title': 'Respostas após o recolhimento',\n 'settings.foldedReplies.description': 'Escolha quais respostas do assistente permanecerão visíveis quando os detalhes do trabalho forem recolhidos',\n 'settings.foldedReplies.all': 'Todas as respostas',\n 'settings.foldedReplies.final': 'Apenas resposta final',\n 'settings.transcript.compact': 'Compacto',\n 'settings.transcript.standard': 'Padrão',\n 'settings.transcript.detailed': 'Detalhado',\n 'settings.transcript.verbose': 'Verboso',\n 'fileOpen.title': 'Não foi possível abrir o arquivo',\n 'fileOpen.unknown': 'Não foi possível abrir este arquivo',\n 'message.extraBlock': 'Bloco de conteúdo extra',\n 'message.systemPrompt': 'Alerta do sistema',\n 'message.systemPromptUpdate': 'Atualização imediata do sistema',\n 'message.toolAdded': 'Ferramenta adicionada: {name}',\n 'message.toolRemoved': 'Ferramenta removida: {name}',\n 'message.toolsAdded': 'Adicionado: {names}',\n 'message.toolsAddedCount': '{count} adicionado',\n 'message.toolsChanged': '{added} adicionado, {removed} removido',\n 'message.toolsRemoved': 'Removido: {names}',\n 'message.toolsRemovedCount': '{count} removido',\n 'message.toolsUpdated': 'Ferramentas atualizadas',\n 'message.contextInjection': 'Injeção de contexto',\n 'message.contextRecall': 'Recuperação de sessão',\n 'message.referenceSummary': 'Sessão referenciada · {labels}',\n 'message.referenceSeparator': ', ',\n 'message.context.instructions.loaded': 'carregado',\n 'message.context.instructions.added': 'adicionado',\n 'message.context.instructions.updated': 'atualizado',\n 'message.context.instructions.removed': 'removido',\n 'message.context.catalog.replaced': 'Catálogo de substituição',\n 'message.context.catalog.more': '… {count} mais',\n 'message.context.snapshot.supersedes': 'Substitui instantâneos anteriores',\n 'message.context.relay.from': 'Da sessão {session}',\n 'message.context.recall.counts': '{retained} mantido · {omitted} omitido',\n 'message.context.recall.truncated': 'truncado',\n 'message.compaction': 'Contexto compactado',\n 'message.compaction.running': 'Contexto compactado…',\n 'message.compaction.completed': '{items} itens de histórico compactados (~{tokens} tokens)',\n 'message.compaction.expand': 'Ver resumo de compactação',\n 'message.compaction.unavailable': 'Resumo de compactação indisponível',\n 'message.compaction.commandTitle': 'compacto',\n 'message.think': 'Pense',\n 'message.unknownSurface': 'Evento de superfície desconhecido: {type}',\n 'message.unknownBlock': 'Bloco de conteúdo desconhecido',\n 'message.turnProcess.toolCalls.one': '{count} chamada de ferramenta',\n 'message.turnProcess.toolCalls.other': '{count} chamadas de ferramenta',\n 'message.turnProcess.messages.one': '{count} mensagem',\n 'message.turnProcess.messages.other': '{count} mensagens',\n 'message.turnProcess.subagents.one': '{count} subagente',\n 'message.turnProcess.subagents.other': '{count} subagentes',\n 'message.turnProcess.thoughtForAWhile': 'Pensou por um tempo',\n 'message.turnProcess.separator': ' · ',\n 'message.stopped': 'Parado',\n 'message.branch': 'Ramifique para uma nova conversa',\n 'message.branchUnavailable': 'Disponível apenas na última mensagem de um turno concluído',\n 'message.retry.active': 'Tentando novamente a solicitação de modelo',\n 'message.retry.cancelled': 'Nova tentativa de solicitação de modelo cancelada',\n 'message.retry.started': 'Solicitação de modelo repetida',\n 'message.continuation.requested': 'Continuação da geração solicitada',\n 'message.retry.scheduled': 'Aguardando para tentar novamente a solicitação de modelo',\n 'message.retry.status': '{label} ({retry}/{maximum}) · {seconds}s',\n 'message.retry.delay': 'Atraso na nova tentativa: ',\n 'message.retry.failure': 'Motivo da falha: ',\n 'message.failure.auth': 'A chave API é inválida',\n 'message.taskStopped': 'Tarefa interrompida',\n 'message.failure.accountSignedOut': 'Interrompido porque você saiu de DeepSeek.',\n '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.',\n 'message.failure.accountSignInRequired': 'Faça login em DeepSeek e verifique se o destino da solicitação suporta autenticação de conta.',\n 'message.failure.quota': 'Cota de solicitação esgotada.',\n 'message.turnError': 'Este turno falhou',\n 'message.maxTokens': 'Limite de token de saída atingido',\n 'message.maxTokens.hint': 'A resposta foi cortada; a saída anterior é preservada na conversa. Envie \"continuar\" para permitir que o modelo seja retomado.',\n 'message.tokensPerSecond': '{tps} tok/s',\n 'message.turnUsage.title': 'Uso do turno',\n 'message.turnUsage.consumed': 'Uso {total}',\n 'message.turnUsage.model': 'Provedor/modelo',\n 'message.turnUsage.cacheHit': 'Acertos no cache',\n 'message.turnUsage.input': 'Entrada sem cache',\n 'message.turnUsage.cacheRead': 'Entrada em cache',\n 'message.turnUsage.cacheWrite': 'Gravação em cache',\n 'message.turnUsage.output': 'Saída',\n 'message.turnUsage.reasoning': ' ({tokens} raciocínio)',\n 'message.turnUsage.count': '{count} tok',\n 'duration.secondUnit': 's',\n 'duration.minuteUnit': 'm ',\n 'duration.hourUnit': 'h ',\n 'command.running': 'Correndo…',\n 'command.failed': 'Falha no comando',\n 'command.done': 'Concluído',\n 'command.title': 'Comando',\n 'row.running': 'Correndo',\n 'row.failed': 'Falha',\n 'json.truncated': '… truncado, {total} caracteres no total',\n 'clock.md': '{m}/{d}',\n 'clock.ymd': '{y}-{m}-{d}',\n} satisfies Record<keyof typeof en, string>\n","/** Display text preparation for model reasoning. */\n\n/**\n * Prepare complete or streaming reasoning for display.\n * @param text - original complete or streaming reasoning.\n * @returns display text, or empty text when no displayable content is available.\n */\nexport function reasoningText(text: string): string {\n if (text[0] !== '<') return text\n /* v8 ignore start -- Custom rendering behavior is outside unit coverage. */\n const opening = '<signature>'\n if (opening.startsWith(text)) return ''\n if (!text.startsWith(opening)) return text\n const closing = '</signature>'\n const end = text.indexOf(closing, opening.length)\n if (end === -1) return ''\n let start = end + closing.length\n while (start < text.length) {\n if (text[start] === '\\n') start++\n else if (text[start] === '\\r' && text[start + 1] === '\\n') start += 2\n else break\n }\n return text.slice(start)\n /* v8 ignore stop */\n}\n","/** Assistant reasoning disclosure, independent of Tool-call presentation. */\nimport { memo, useMemo } from 'react'\nimport { DisclosureRow, IconThinkOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ChatViewSlotProps, UseDisclosure, UsePresentation } from '../contract/slots.ts'\nimport { reasoningText } from '../reasoning-text.ts'\nimport a11yCss from './accessibility.module.css'\nimport css from './ReasoningRow.module.css'\n\nconst THINK_ICON = <IconThinkOutlineRegular size={14} />\n\nfunction firstLine(text: string): string {\n const newline = text.indexOf('\\n')\n return newline === -1 ? text : text.slice(0, newline)\n}\n\nfunction latestCompletedParagraphFirstLine(text: string): string {\n let summary = ''\n let paragraphStart = 0\n const separator = /\\r?\\n(?:[\\t ]*\\r?\\n)+/g\n while (true) {\n const nextParagraph = separator.exec(text)\n const paragraphEnd = nextParagraph === null ? text.length\n : nextParagraph.index + nextParagraph[0].indexOf('\\n')\n const newline = text.indexOf('\\n', paragraphStart)\n if (newline !== -1 && newline <= paragraphEnd) {\n const candidate = text.slice(paragraphStart, newline).trim()\n if (candidate !== '') summary = candidate\n }\n if (nextParagraph === null) return summary\n paragraphStart = nextParagraph.index + nextParagraph[0].length\n }\n}\n\n/**\n * Render one assistant reasoning block collapsed until the reader opens it. The\n * collapsed summary omits double-asterisk markers; expanded content renders\n * the complete Markdown with secondary typography. A streaming preview advances\n * when a paragraph's first line completes. Mode changes toggle CSS display without unmounting\n * collapsed summaries. The Body Slot receives both original and display-ready text.\n * @param props.text - complete or streaming reasoning text.\n * @param props.running - whether this block is the streaming tail.\n * @param props.usePresentation - live display-policy selector for this reasoning row.\n * @param props.useDisclosure - independent open state with enclosing-Turn resets.\n * @param props.renderSlot - framework renderer for the standard reasoning Body Slot.\n * @param props.t - conversation locale seat for the disclosure and running status.\n * @returns the reasoning disclosure.\n */\nexport const ReasoningRow = memo(function ReasoningRow({\n text: rawText, running, textInteractionSource = false, usePresentation, useDisclosure, renderSlot, t,\n}: {\n text: string\n running: boolean\n textInteractionSource?: boolean\n useDisclosure: UseDisclosure\n usePresentation: UsePresentation\n t: ChatViewSlotProps['t']\n} & Pick<PropsRenderSlots<'conversation.chat.reasoning.body'>, 'renderSlot'>) {\n const { expanded, toggle } = useDisclosure()\n const { text, hidden } = useMemo(() => {\n const text = reasoningText(rawText)\n return { text, hidden: text !== rawText && text.trim() === '' }\n }, [rawText])\n const summaryText = running ? latestCompletedParagraphFirstLine(text) : firstLine(text)\n const summary = useMemo(() => summaryText.replaceAll('**', ''), [summaryText])\n const preview = usePresentation(policy => !expanded && summary !== ''\n && (running || policy.settledReasoningPreview))\n const collapsedContent = useMemo(() => (\n <>\n <span className={css.separator} data-shimmer-decoration aria-hidden />\n <span className={css.summary} data-streaming={running || undefined}>\n <span className={css.summaryText}>\n <TextShimmer>{summary}</TextShimmer>\n </span>\n </span>\n </>\n ), [running, summary])\n const content = useMemo(() => expanded ? (\n <div className={css.thinkBody} data-text-interaction-source={textInteractionSource && !running ? '' : undefined}>\n {renderSlot('conversation.chat.reasoning.body', { rawText, text, running })}\n </div>\n ) : undefined, [expanded, renderSlot, running, rawText, text, textInteractionSource])\n\n if (hidden) return null\n\n return (\n <div\n className={css.root}\n data-variant=\"think\"\n data-state={running ? 'running' : 'ok'}\n data-expanded={expanded || undefined}\n data-preview={preview || undefined}\n >\n {running && <span className={a11yCss.visuallyHidden}>{t('row.running')}</span>}\n <DisclosureRow\n rowClassName={css.row}\n leadingClassName={css.leading}\n titleClassName={css.title}\n icon={THINK_ICON}\n title={t('message.think')}\n running={running}\n open={expanded}\n expandable\n expandOnRowClick\n onToggle={toggle}\n collapsedContent={collapsedContent}\n >\n {content}\n </DisclosureRow>\n </div>\n )\n})\n","import { Fragment, memo, useMemo } from 'react'\nimport { fileMediaUrl } from '@deepseek-ai/dsh-util-workspace-path'\nimport type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ReactNode } from 'react'\nimport { JsonBlock, MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { MarkdownFileMentions, MarkdownPathImages } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeOwnerProps, ChatViewSlotProps, UseDisclosure, UsePresentation, UseGroupAction } from '../contract/slots.ts'\nimport type { AssistantBlock } from '../contract/snapshot.ts'\nimport { markdownLabels } from '../markdown-labels.ts'\nimport { ReasoningRow } from './ReasoningRow.tsx'\nimport css from './AssistantMarkdown.module.css'\n\n/**\n * Standalone fallback for image destinations (query/fragment suffixes are ignored).\n * Chat fileImages resolves decoded file references against cwd; pathImages also\n * serves this component outside that provider and accepts legacy image URL suffixes.\n * Resolve an authored absolute image path against the document's file API.\n * @param base - canonical `document.baseURI` at render time.\n * @param value - authored Markdown destination; URL escapes are decoded once.\n * @returns an absolute Web or Desktop file-API URL, or undefined for unsupported\n * protocols and non-local paths.\n */\nexport function localPathMediaUrl(base: string, value: string): string | undefined {\n let path: string\n try { path = decodeURIComponent(value.split(/[?#]/u)[0] ?? '') }\n catch { return undefined } // Malformed URL escapes cannot identify a file.\n return fileMediaUrl(base, path)\n}\n\nexport interface AssistantMarkdownProps extends\n Pick<PropsRenderSlots<'conversation.chat.reasoning.body' | 'conversation.chat.message.images'>, 'renderSlot'>,\n Pick<ChatNodeOwnerProps, 'loadImage'> {\n /** Render only the requested business portion, preserving original block indexes. */\n groupPart?: string | undefined\n /** Stable Hook forwarded to each independently expandable reasoning block. */\n useDisclosure: UseDisclosure\n blocks: readonly AssistantBlock[]\n streaming: boolean\n /** Only finalized durable Assistant messages supply selection sources. */\n textInteractionSource?: boolean\n /** Frozen partial of an aborted turn: rendered with a stopped marker. */\n interrupted?: boolean | undefined\n /** Hide reasoning that belongs to the Turn-level process disclosure. */\n reasoningHidden?: boolean | undefined\n /** Process hiding bound by the node slot to its current viewport. */\n useGroupAction: UseGroupAction\n /** Live display policy for reasoning summaries. */\n usePresentation: UsePresentation\n /** Reveal the disclosure that hides this reasoning. */\n revealProcess?: (() => void) | undefined\n /** Resolved prose file mentions for this Assistant's closing turn. */\n mentions?: MarkdownFileMentions | undefined\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\n/** Renders non-blank reasoning blocks as independent disclosures alongside the response. */\nexport const AssistantMarkdown = memo(function AssistantMarkdown({\n blocks, streaming, textInteractionSource = false, interrupted, loadImage, groupPart, useDisclosure,\n reasoningHidden = false, usePresentation, revealProcess, mentions, renderSlot, useGroupAction, t,\n}: AssistantMarkdownProps) {\n // Stable per locale revision (t identity changes on switch): a fresh object\n // per render would rebuild MarkdownText's component table every chunk.\n const labels = useMemo(() => markdownLabels(t), [t])\n // MarkdownText memoizes its vocabulary; keep its identity stable across renders.\n const pathImages = useMemo<MarkdownPathImages>(() => {\n return { resolve: value => localPathMediaUrl(document.baseURI, value) }\n }, [])\n const last = blocks.length - 1\n // Tool-call heads render as tool rows in the chat view's grouping pass, so\n // a node that is only those heads (or empty) would paint an empty root\n // between tool groups — skip the shell unless something visible remains.\n const hasVisible = streaming\n || interrupted === true\n || blocks.some(block => block.kind !== 'tool-call')\n if (!hasVisible) return null\n const rendered: ReactNode[] = []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]\n if (block === undefined) continue\n if (groupPart === 'reasoning' && block.kind !== 'reasoning') continue\n if (groupPart === 'response' && block.kind === 'reasoning') continue\n switch (block.kind) {\n case 'text':\n rendered.push(\n <MarkdownText\n key={i}\n text={block.text}\n streaming={streaming}\n labels={labels}\n fileMentions={mentions}\n pathImages={pathImages}\n textInteractionSource={textInteractionSource}\n />,\n )\n break\n case 'reasoning':\n if (block.text.trim() === '') break\n rendered.push(\n <ProcessReasoning\n key={i}\n hidden={reasoningHidden}\n reveal={revealProcess}\n useGroupAction={useGroupAction}\n >\n <ReasoningRow text={block.text} running={streaming && i === last} usePresentation={usePresentation}\n useDisclosure={useDisclosure} renderSlot={renderSlot} textInteractionSource={textInteractionSource} t={t} />\n </ProcessReasoning>,\n )\n break\n case 'image': {\n // Consecutive image blocks share one gallery so several images tile\n // into rows instead of each opening a one-image group of its own.\n // Keyed by the group's FIRST block index: a streaming append that\n // extends the group then only grows `images` instead of remounting\n // the gallery under a shifted key.\n const start = i\n const group = [block]\n while (i + 1 < blocks.length) {\n const next = blocks[i + 1]\n if (next === undefined || next.kind !== 'image') break\n group.push(next)\n i += 1\n }\n rendered.push(\n <Fragment key={start}>\n {renderSlot('conversation.chat.message.images', {\n images: group.map(({ attachment }) => ({ attachment })), loadImage, align: 'start',\n })}\n </Fragment>,\n )\n break\n }\n // Grouped into tool rows by ChatView; hasVisible above skips an empty shell.\n case 'tool-call':\n break\n default:\n rendered.push(\n <JsonBlock\n key={i}\n label={t('message.unknownBlock')}\n payload={block.block}\n truncatedLabel={total => t('json.truncated', { total })}\n />,\n )\n }\n }\n return (\n <div className={css.root} data-streaming={streaming || undefined}>\n <div className={css.body}>\n {rendered}\n {interrupted && (groupPart === undefined || groupPart === 'response'\n || !blocks.some(block => block.kind !== 'reasoning' && block.kind !== 'tool-call'))\n && <span className={css.stopped}>{t('message.stopped')}</span>}\n </div>\n </div>\n )\n})\n\nfunction ProcessReasoning({ hidden, reveal, useGroupAction, children }: {\n hidden: boolean\n reveal?: (() => void) | undefined\n useGroupAction: UseGroupAction\n children: ReactNode\n}) {\n const ref = useGroupAction(hidden, reveal ?? NOOP)\n return <div ref={ref} data-turn-process-inline={hidden || undefined}>{children}</div>\n}\n\nconst NOOP = (): void => {}\n","import { memo, useCallback, useMemo } from 'react'\nimport type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ChatFileMentions, ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from '../contract/slots.ts'\nimport { AssistantMarkdown } from './AssistantMarkdown.tsx'\n\n/** Business readers owned by the assistant renderer's existing Slot registration. */\nexport interface AssistantNodeInjected extends PresentationInjected {\n /** Resolve against the live Session directory. @param path - Recorded path. @returns Host path. */\n resolveFilePath: (path: string) => string\n /** Resolve closing-Turn mentions with the supplied ordinary file gesture callback. */\n fileMentions: (owner: TurnTailOwnerProps, getFileTriggerProps: NonNullable<Parameters<ChatFileMentions['forClosing']>[2]>) => ReturnType<ChatFileMentions['forClosing']>\n}\n\ntype AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace<AssistantNodeInjected>\n & PropsRenderSlots<'conversation.chat.reasoning.body' | 'conversation.chat.message.images'>\n\n/** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */\nexport const AssistantNodeView = memo(function AssistantNodeView({\n node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions,\n usePresentation, renderSlot, t, sessionId, useContextMenu, resolveFilePath,\n}: AssistantNodeViewProps) {\n const { getTriggerProps } = useContextMenu()\n const getFileTriggerProps = useCallback((path: string) => getTriggerProps(() => ({\n kind: 'file', value: { sessionId, path: resolveFilePath(path) },\n })), [getTriggerProps, sessionId, resolveFilePath])\n const data = node.data\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n const tail = useTurnData('turn-tail')\n const owner = useMemo<TurnTailOwnerProps | undefined>(() => {\n if (turn?.status !== 'closed' || data.finalNode === undefined) return undefined\n if (tail?.closing?.finalNode.seq !== data.finalNode.seq) return undefined\n return { turn, seq: data.finalNode.seq, openFile }\n }, [data.finalNode, openFile, tail, turn])\n const mentions = useMemo(\n () => owner === undefined ? undefined : fileMentions(owner, getFileTriggerProps),\n [fileMentions, owner, getFileTriggerProps],\n )\n const keepReplies = usePresentation(policy => policy.foldedReplies === 'all')\n // A kept reply row stays visible while the folded Turn hides its inline reasoning.\n const reasoningHidden = turnProcess !== undefined\n && turnProcess.foldable\n && (keepReplies\n ? groupPart !== 'reasoning'\n : turnProcess.spec.answerStep === data.step && turnProcess.spec.inlineReasoning)\n && !turnProcess.open\n const revealProcess = useCallback(() => { turnProcess?.setOpen(true) }, [turnProcess])\n return (\n <AssistantMarkdown\n blocks={data.blocks}\n groupPart={groupPart}\n useDisclosure={useDisclosure}\n streaming={data.status === 'running'}\n textInteractionSource={data.status === 'settled' && data.finalNode?.messageId !== undefined}\n interrupted={data.status === 'interrupted'}\n loadImage={loadImage}\n reasoningHidden={reasoningHidden}\n useGroupAction={useGroupAction}\n usePresentation={usePresentation}\n renderSlot={renderSlot}\n revealProcess={revealProcess}\n mentions={mentions}\n t={t}\n />\n )\n})\n","import { memo, useCallback, useMemo, useState } from 'react'\nimport type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconApiOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives'\nimport a11yCss from './accessibility.module.css'\nimport css from './GenericCommandCard.module.css'\n\ntype CommandRowState = 'running' | 'ok' | 'error'\n\nconst COMMAND_ICON = <IconApiOutlineRegular size={14} />\n\n/** Node state → row state semantic (running while unsettled; outcome kind after). */\nfunction stateOf(outcome: CommandRowOwnerProps['node']['outcome']): CommandRowState {\n if (outcome === null) return 'running'\n return outcome.kind === 'error' ? 'error' : 'ok'\n}\n\n/** Card props: the owner payload plus the render site's locale seat (plain prop). */\nexport interface GenericCommandCardProps extends CommandRowOwnerProps {\n t: ChatViewSlotProps['t']\n /** Command-specific running copy; absent uses the generic command label. */\n runningSummary?: string | undefined\n}\n\n/**\n * Render a command summary and its lazily mounted multiline output.\n * @param props - command, locale, and optional running label.\n * @returns the command disclosure.\n */\nexport const GenericCommandCard = memo(function GenericCommandCard({ node, t, runningSummary }: GenericCommandCardProps) {\n const [expanded, setExpanded] = useState(false)\n const text = node.outcome?.text\n const summary = node.outcome === null\n ? runningSummary ?? t('command.running')\n : text ?? (node.outcome.kind === 'error' ? t('command.failed') : t('command.done'))\n // The summary already carries the settlement text, so the title is the bare\n // command name.\n const title = node.name ?? t('command.title')\n const state = stateOf(node.outcome)\n const running = state === 'running'\n const body = text !== undefined && text.includes('\\n') ? text : null\n const open = expanded && body !== null\n const toggle = useCallback(() => { setExpanded(value => !value) }, [])\n const collapsedContent = useMemo(() => (\n <>\n <span className={css.separator} data-shimmer-decoration aria-hidden />\n <span className={css.summary} data-error={state === 'error' || undefined}>\n <TextShimmer>{summary}</TextShimmer>\n </span>\n </>\n ), [running, state, summary])\n const content = useMemo(() => open\n ? <pre className={css.body} data-error={state === 'error' || undefined}>{body}</pre>\n : undefined, [body, open, state])\n return (\n <div className={css.root} data-variant=\"others\" data-state={state}>\n {state === 'running' && <span className={a11yCss.visuallyHidden}>{t('row.running')}</span>}\n {state === 'error' && <span className={a11yCss.visuallyHidden}>{t('row.failed')}</span>}\n <DisclosureRow\n leadingClassName={css.leading}\n titleClassName={css.title}\n icon={COMMAND_ICON}\n title={title}\n running={running}\n open={open}\n expandable={body !== null}\n expandOnRowClick\n keepContentWhenOpen\n onToggle={toggle}\n collapsedContent={collapsedContent}\n >\n {content}\n </DisclosureRow>\n </div>\n )\n})\n","// Only a structured checkpoint uses the compaction marker; all other outcomes\n// retain the command's complete settlement text.\n\nimport type { ChatViewSlotProps, CommandRowOwnerProps } from '../contract/slots.ts'\nimport { CompactionItem } from './CompactionItem.tsx'\nimport { GenericCommandCard } from './GenericCommandCard.tsx'\n\ninterface CompactionCommandCardProps extends CommandRowOwnerProps {\n t: ChatViewSlotProps['t']\n}\n\n/** Render one manual compaction lifecycle without duplicating its checkpoint marker. */\nexport function CompactionCommandCard({ node, compaction, t }: CompactionCommandCardProps) {\n if (compaction !== undefined) {\n return (\n <CompactionItem\n node={compaction}\n title={t('message.compaction.commandTitle')}\n fallbackSummary={node.outcome?.text ?? null}\n t={t}\n />\n )\n }\n if (node.outcome !== null) return <GenericCommandCard node={node} t={t} />\n return <GenericCommandCard node={node} t={t} runningSummary={t('message.compaction.running')} />\n}\n","import { memo, useMemo } from 'react'\nimport type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type {\n ChatNodeViewProps, CommandRowOwnerProps,\n} from '../contract/slots.ts'\nimport { CompactionCommandCard } from './CompactionCommandCard.tsx'\nimport { GenericCommandCard } from './GenericCommandCard.tsx'\nimport css from './ChatView.module.css'\n\ntype CommandNodeViewProps = ChatNodeViewProps<'command'> & PropsRenderSlots<'conversation.chat.commandview'>\n\n/** Ordinary command lifecycle renderer with command-name keyed specialization. */\nexport const CommandNodeView = memo(function CommandNodeView({ node, renderSlot, t }: CommandNodeViewProps) {\n const command = node.data\n const owner = useMemo<CommandRowOwnerProps>(() => ({ node: command }), [command])\n return (\n <div className={css.callRow}>\n {renderSlot('conversation.chat.commandview', owner, {\n entryKey: command.name ?? '',\n fallback: <GenericCommandCard {...owner} t={t} />,\n })}\n </div>\n )\n})\n\n/** One integrated `/compact` command and compaction transaction renderer. */\nexport const ManualCompactionNodeView = memo(function ManualCompactionNodeView({\n node, t,\n}: ChatNodeViewProps<'manual-compaction'>) {\n const data = node.data\n return (\n <div className={css.callRow}>\n <CompactionCommandCard\n node={data.command}\n {...data.compaction === null ? {} : { compaction: data.compaction }}\n t={t}\n />\n </div>\n )\n})\n","/** Official reasoning content and its default Body Slot adapter. */\nimport { memo, useMemo } from 'react'\nimport { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { FactoryComponentPropsOf, PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { markdownLabels } from '../markdown-labels.ts'\n\ntype ReasoningBodyProps = PropsRuntime<'conversation.chat.reasoning.body'> & PropsRenderFactories\n\n/**\n * Render compact reasoning with caller-supplied labels or Chat's defaults.\n * @param props - display text, streaming state, optional localized labels, and the Factory's locale seat; no Session is required.\n * @returns the standard reasoning content; supplied labels are used without merging defaults.\n */\nexport const ReasoningContent = memo(function ReasoningContent({ text, running, labels, t }: FactoryComponentPropsOf<'conversation.chat.reasoning.content'>) {\n const resolvedLabels = useMemo(() => labels ?? markdownLabels(t), [labels, t])\n return <MarkdownText text={text} streaming={running} labels={resolvedLabels} variant=\"compact\" />\n})\n\n/**\n * Render the default Body through the same Factory available to third-party wrappers.\n * @param props - display-ready reasoning and the framework's Factory renderer.\n * @returns an occurrence of the official reasoning Content Factory.\n */\nexport function DefaultReasoningBody({ text, running, renderFactorySlot }: ReasoningBodyProps) {\n return renderFactorySlot('conversation.chat.reasoning.content', { text, running })\n}\n","import { memo, useState } from 'react'\nimport type { ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts'\nimport { DisclosureRow, IconBrowseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport { OpaqueBody } from './ContextBody.tsx'\nimport css from './ContextInjectionRow.module.css'\n\n/** Props for one complete system prompt disclosure. */\nexport interface SystemPromptRowProps {\n /** Complete model-visible prompt text. */\n text: string\n /** True when the prompt replaced an earlier one from this position in the history. */\n update?: boolean\n /** The owning view's locale seat. */\n t: ChatViewSlotProps['t']\n}\n\n/**\n * Render one complete system prompt as a collapsed disclosure whose expanded\n * body is the same opaque context chrome: 141px code-block scrollport and\n * model-facing text with its real line breaks. An in-history update uses the\n * same row under its own title.\n * @param props - Complete prompt text, whether it is an update, and the locale seat.\n * @returns The system-prompt disclosure row.\n */\nexport function SystemPromptRow({ text, update = false, t }: SystemPromptRowProps) {\n const [open, setOpen] = useState(false)\n return (\n <DisclosureRow\n className={css.root}\n icon={<IconBrowseOutlineRegular size={14} />}\n chevronClassName={css.chevron}\n title={t(update ? 'message.systemPromptUpdate' : 'message.systemPrompt')}\n open={open}\n expandable\n expandOnRowClick\n onToggle={() => { setOpen(value => !value) }}\n >\n <div className={css.body} data-system-prompt-body>\n <OpaqueBody content={[{ type: 'text', text }]} source={null} t={t} />\n </div>\n </DisclosureRow>\n )\n}\n\n/** System-prompt keyed Chat renderer. */\nexport const SystemPromptNodeView = memo(function SystemPromptNodeView({\n node, t,\n}: Pick<ChatNodeViewProps<'system-prompt'>, 'node' | 't'>) {\n return <SystemPromptRow text={node.data.text} update={node.data.update === true} t={t} />\n})\n","import { memo } from 'react'\nimport { IconChevronDownOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeViewProps } from '../contract/slots.ts'\nimport { turnProcessAlwaysOpen } from '../contract/turn-process.ts'\nimport { formatRunDuration } from './message-chrome.ts'\nimport a11yCss from './accessibility.module.css'\nimport css from './TurnProcessNodeView.module.css'\n\n/** Settled Turn duration and process disclosure above its content. */\nexport const TurnProcessNodeView = memo(function TurnProcessNodeView({\n node, turnProcess, t,\n}: ChatNodeViewProps<'turn-process'>) {\n if (turnProcess === undefined) throw new Error('turn-process node requires Turn process owner state')\n const open = !turnProcess.foldable || turnProcess.open\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n if (turn?.status !== 'closed') return null\n const canCollapse = turnProcess.foldable && turnProcess.hasContent && !turnProcessAlwaysOpen(node)\n const reason = turn.end?.data.reason.kind\n const stopped = reason === 'aborted' || reason === 'interrupted'\n const elapsedMs = turn.start === undefined || turn.end === undefined ? undefined\n : Math.max(1000, turn.end.time - turn.start.time)\n const duration = elapsedMs === undefined || stopped || reason === 'error' ? undefined\n : formatRunDuration(elapsedMs, t)\n // Other end reasons retain elapsed time; only stops and failure replace it.\n const label = stopped ? t('message.stopped')\n : reason === 'error' ? t('message.turnProcess.failed')\n : duration === undefined ? t('message.turnProcess.worked')\n : t('message.turnProcess.took')\n const announcement = stopped ? t('message.stopped')\n : reason === 'error' ? t('message.turnProcess.failed')\n : t('message.turnProcess.worked')\n return (\n <>\n <span className={a11yCss.visuallyHidden} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">{announcement}</span>\n <button\n type=\"button\"\n className={css.root}\n data-open={open || undefined}\n data-turn-process={node.data.turn}\n data-turn-process-messages={node.data.messageCount}\n data-turn-process-tool-calls={node.data.toolCallCount}\n data-turn-process-subagents={node.data.subagentCount}\n disabled={!canCollapse}\n aria-expanded={turnProcess.hasContent ? open : undefined}\n onClick={(event) => {\n event.currentTarget.focus()\n turnProcess.setOpen(!open)\n }}\n >\n <span className={css.label}>\n {label}\n {duration?.map((part, index) => (\n <span key={index} className={part.numeric ? css.durationNumber : undefined}>{part.text}</span>\n ))}\n </span>\n {canCollapse && <IconChevronDownOutlineRegular className={css.chevron} />}\n </button>\n </>\n )\n})\n","import type { ChatViewSlotProps } from '../contract/slots.ts'\n\n/**\n * Compact token count: 517 / 12.2K / 517K / 1.2M.\n * @param value - non-negative token count.\n * @param t - Chat locale seat.\n * @returns locale-owned compact display string.\n */\nexport function formatTokens(value: number, t: ChatViewSlotProps['t']): string {\n const scaled = (candidate: number): string =>\n candidate >= 100 ? String(Math.round(candidate)) : String(Math.round(candidate * 10) / 10)\n if (value < 1_000) return String(value)\n if (value < 1_000_000) return t('number.thousand', { value: scaled(value / 1_000) })\n return t('number.million', { value: scaled(value / 1_000_000) })\n}\n\n/**\n * Exact integer token count with locale-owned digit grouping.\n * @param value - non-negative safe integer token count.\n * @param t - Chat locale seat.\n * @returns an unrounded display string.\n */\nexport function formatExactTokens(value: number, t: ChatViewSlotProps['t']): string {\n const digits = String(value)\n const groups: string[] = []\n for (let end = digits.length; end > 0; end -= 3) {\n groups.unshift(digits.slice(Math.max(0, end - 3), end))\n }\n return groups.join(t('number.groupSeparator'))\n}\n\n/** Round a cache-read ratio to exact percentage units, with positive ties rounded up. */\nfunction roundedPercentUnits(cacheReadTokens: number, denominator: number, decimalPlaces: 0 | 1): number {\n const unitsPerPercent = decimalPlaces === 0 ? 1 : 10\n const scale = unitsPerPercent * 100\n const doubledScale = scale * 2\n const denominatorQuotient = Math.floor(denominator / doubledScale)\n const denominatorRemainder = denominator % doubledScale\n let lower = 0\n let upper = scale\n while (lower < upper) {\n const candidate = Math.floor((lower + upper + 1) / 2)\n const factor = candidate * 2 - 1\n const threshold = factor * denominatorQuotient\n + Math.ceil(factor * denominatorRemainder / doubledScale)\n if (cacheReadTokens >= threshold) lower = candidate\n else upper = candidate - 1\n }\n return lower\n}\n\nfunction displayPercentUnits(units: number, decimalPlaces: 0 | 1): string {\n if (decimalPlaces === 0) return String(units)\n const whole = Math.floor(units / 10)\n const tenths = units % 10\n return tenths === 0 ? String(whole) : `${whole}.${tenths}`\n}\n\n/**\n * Display-ready cache-hit share without rounding a partial hit to 100%.\n * @param cacheReadTokens - exact prompt tokens served from cache.\n * @param promptTokens - exact aggregate prompt tokens.\n * @param decimalPlaces - ordinary-ratio precision; partial hits that would\n * round to 100 automatically use enough additional precision to stay honest.\n * @returns percentage text, or null when there was no prompt input.\n */\nexport function formatCacheHitPercent(\n cacheReadTokens: number,\n promptTokens: number,\n decimalPlaces: 0 | 1 = 0,\n): string | null {\n if (promptTokens === 0) return null\n const missedInputTokens = promptTokens - cacheReadTokens\n if (missedInputTokens === 0) return '100'\n\n const roundedUnits = roundedPercentUnits(cacheReadTokens, promptTokens, decimalPlaces)\n const fullHitUnits = decimalPlaces === 0 ? 100 : 1_000\n if (roundedUnits < fullHitUnits) return displayPercentUnits(roundedUnits, decimalPlaces)\n\n let distinguishingPlaces = 1\n let scaledDoubleGap = missedInputTokens * 200\n const denominatorTens = Math.floor(promptTokens / 10)\n while (scaledDoubleGap <= denominatorTens) {\n scaledDoubleGap *= 10\n distinguishingPlaces += 1\n }\n const denominatorOnes = promptTokens % 10\n let roundedLoss = 5\n for (let loss = 1; loss < 5; loss += 1) {\n const factor = loss * 2 + 1\n const threshold = factor * denominatorTens + Math.floor(factor * denominatorOnes / 10)\n if (scaledDoubleGap <= threshold) {\n roundedLoss = loss\n break\n }\n }\n return `99.${'9'.repeat(distinguishingPlaces - 1)}${10 - roundedLoss}`\n}\n","// One trigger-anchored stat dialog seat shared by the Turn-stat pills\n// (TurnUsagePanel) and the composer-dock session stats pills (StatsPills.tsx);\n// the matching dialog surface skin lives in stat-dialog.module.css.\n\nimport { useEffect, useId, useRef, useState, type MutableRefObject } from 'react'\nimport { useDismissOnOutsidePointer } from '@deepseek-ai/dsh-client-ui-primitives'\n\n/** Open state, refs, and CSS anchor identity for one stat dialog. */\nexport interface StatDialogSeat {\n open: boolean\n setOpen: (open: boolean) => void\n rootRef: MutableRefObject<HTMLSpanElement | null>\n panelRef: MutableRefObject<HTMLDivElement | null>\n anchorName: string\n}\n\n/**\n * One trigger-anchored dialog seat: open state, CSS anchor placement, outside-close.\n * @returns the seat; assign the anchor name to the trigger and the portaled panel.\n */\nexport function useStatDialog(): StatDialogSeat {\n const [open, setOpen] = useState(false)\n const rootRef = useRef<HTMLSpanElement | null>(null)\n const panelRef = useRef<HTMLDivElement | null>(null)\n\n const anchorName = `--dsh-stat-${useId().replaceAll(':', '')}`\n\n // Outside pointerdown closes through the shared primitive; the portaled\n // panel counts as inside. An outside click also closes, because keyboard\n // activation of a sibling trigger fires click without pointerdown; the\n // capture phase lets that click close this dialog before the sibling opens.\n // Escape closes.\n useDismissOnOutsidePointer(rootRef, open, setOpen, panelRef)\n useEffect(() => {\n if (!open) return\n const onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === 'Escape') setOpen(false)\n }\n const onClick = (e: MouseEvent): void => {\n if (e.target instanceof Node\n && rootRef.current?.contains(e.target) !== true\n && panelRef.current?.contains(e.target) !== true) {\n setOpen(false)\n }\n }\n document.addEventListener('keydown', onKeyDown)\n document.addEventListener('click', onClick, true)\n return () => {\n document.removeEventListener('keydown', onKeyDown)\n document.removeEventListener('click', onClick, true)\n }\n }, [open, setOpen])\n\n return { open, setOpen, rootRef, panelRef, anchorName }\n}\n","/** Completed-Turn token usage action and its accounting details dialog. */\n\nimport { createPortal } from 'react-dom'\nimport { IconDatabaseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TurnTokenUsage } from '../contract/chat-nodes.ts'\nimport type { ChatViewSlotProps } from '../contract/slots.ts'\nimport { formatCacheHitPercent, formatExactTokens, formatTokens } from './token-format.ts'\nimport { useStatDialog } from './stat-dialog.ts'\nimport css from './TurnUsagePanel.module.css'\nimport dialogCss from './stat-dialog.module.css'\n\nexport interface TurnUsagePanelProps {\n usage: TurnTokenUsage\n /** The owning view's locale seat, passed down as a plain prop. */\n t: ChatViewSlotProps['t']\n}\n\nfunction formatCompactCount(value: number, t: ChatViewSlotProps['t']): string {\n return t('message.turnUsage.count', { count: formatTokens(value, t) })\n}\n\nfunction formatExactCount(value: number, t: ChatViewSlotProps['t']): string {\n return t('message.turnUsage.count', { count: formatExactTokens(value, t) })\n}\n\n/**\n * Turn-usage IconActions pill with a click-open Turn-usage details dialog.\n * @param props - Turn usage buckets and locale seat.\n * @returns The trigger and, while open, its portaled dialog anchored above the trigger.\n */\nexport function TurnUsagePanel({ usage, t }: TurnUsagePanelProps) {\n const { open, setOpen, rootRef, panelRef, anchorName } = useStatDialog()\n\n const cacheHit = usage.cacheReadTokens === undefined\n ? null\n : formatCacheHitPercent(usage.cacheReadTokens, usage.totalTokens - usage.outputTokens, 1)\n const total = formatCompactCount(usage.totalTokens, t)\n const routes = usage.routes?.map(route => `${route.provider}/${route.model}`).join(', ') ?? ''\n\n return (\n <span ref={rootRef} style={{ anchorName }} className={css.root}>\n <button\n type=\"button\"\n className={css.trigger}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n onClick={() => { setOpen(!open) }}\n >\n <IconDatabaseOutlineRegular />\n <span className={css.label}>{t('message.turnUsage.consumed', { total })}</span>\n </button>\n {open && createPortal(\n <div\n ref={panelRef}\n className={dialogCss.panel}\n role=\"dialog\"\n aria-label={t('message.turnUsage.title')}\n style={{ positionAnchor: anchorName }}\n >\n <div className={dialogCss.title}>\n <span className={dialogCss.titleLabel}>\n <IconDatabaseOutlineRegular />\n {t('message.turnUsage.title')}\n </span>\n <span className={dialogCss.titleValue}>{formatExactCount(usage.totalTokens, t)}</span>\n </div>\n <div className={dialogCss.titleRule} aria-hidden />\n <dl className={dialogCss.details} data-turn-usage-details>\n {routes !== '' && (\n <>\n <dt>{t('message.turnUsage.model')}</dt>\n <dd className={dialogCss.route}>{routes}</dd>\n </>\n )}\n {cacheHit !== null && (\n <>\n <dt>{t('message.turnUsage.cacheHit')}</dt>\n <dd>{`${cacheHit}%`}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.input')}</dt>\n <dd>{formatExactCount(usage.uncachedInputTokens, t)}</dd>\n {usage.cacheReadTokens !== undefined && (\n <>\n <dt>{t('message.turnUsage.cacheRead')}</dt>\n <dd>{formatExactCount(usage.cacheReadTokens, t)}</dd>\n </>\n )}\n {usage.cacheWriteTokens !== undefined && (\n <>\n <dt>{t('message.turnUsage.cacheWrite')}</dt>\n <dd>{formatExactCount(usage.cacheWriteTokens, t)}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.output')}</dt>\n <dd>\n {formatExactCount(usage.outputTokens, t)}\n {usage.reasoningTokens !== undefined && (\n <span className={dialogCss.reasoning}>\n {t('message.turnUsage.reasoning', { tokens: formatExactCount(usage.reasoningTokens, t) })}\n </span>\n )}\n </dd>\n </dl>\n </div>,\n document.body,\n )}\n </span>\n )\n}\n","import type { AssistantBlock } from '../contract/snapshot.ts'\n\n/**\n * Collect visible prose from one Assistant lifecycle.\n * @param blocks - Assistant content blocks.\n * @returns concatenated text blocks.\n */\nexport function assistantText(blocks: readonly AssistantBlock[]): string {\n return blocks.flatMap(block => block.kind === 'text' ? [block.text] : []).join('')\n}\n","import { memo } from 'react'\nimport type { InjectFace, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { ChatNodeViewProps, PerformanceUsageInjected, TurnTailOwnerProps } from '../contract/slots.ts'\nimport { MessageIconActions } from './MessageIconActions.tsx'\nimport { TurnUsagePanel } from './TurnUsagePanel.tsx'\nimport { assistantText } from './turn-assistant.ts'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport css from './TurnTailNodeView.module.css'\n\ntype TurnTailNodeViewProps = ChatNodeViewProps<'turn-tail'>\n & PropsRenderSlots<'conversation.chat.turnTail' | 'conversation.chat.assistant-actions'>\n & InjectFace<PerformanceUsageInjected>\n\nfunction lastContent(snapshot: ChatSnapshot, turn: number, skipWarning: boolean): ChatNode | undefined {\n const keys = snapshot.locations.getTurn(turn)\n for (let index = keys.length - 1; index >= 0; index--) {\n const node = snapshot.nodes.get(keys[index] as string) as ChatNode | undefined\n if (node === undefined || node.kind === 'turn-tail' || node.kind === 'turn-process'\n || (skipWarning && node.kind === 'turn-max-tokens')) continue\n return node\n }\n return undefined\n}\n\n/** Turn-local actions and feature tail over the Location index, independent of Assistant placement. */\nexport const TurnTailNodeView = memo(function TurnTailNodeView({\n node, openFile, forkAt, renderSlot, t, useAccess, useChat, usePerformanceUsage,\n}: TurnTailNodeViewProps) {\n const detailed = usePerformanceUsage(mode => mode) === 'detailed'\n const forkAllowed = useAccess('session/fork')\n const data = node.data\n const hasLaterChatNode = useChat(snapshot =>\n (lastContent(snapshot, data.turn, true)?.anchorSeq ?? -1) > (data.closing?.finalNode.seq ?? data.seq))\n const endsWithResponse = useChat((snapshot) => {\n if (snapshot.timeline.turnOrder.at(-1) !== data.turn) return false\n const last = lastContent(snapshot, data.turn, false)\n const block = last?.kind === 'assistant-step' ? last.data.blocks.findLast(candidate =>\n (candidate.kind !== 'text' && candidate.kind !== 'reasoning') || candidate.text.trim() !== '') : undefined\n return block !== undefined && hasAssistantReplyContent([block])\n })\n const turn = node.location.kind === 'turn' || node.location.kind === 'step'\n ? node.location.turn\n : undefined\n if (turn === undefined) return null\n const closing = data.closing\n const owner: TurnTailOwnerProps = { turn, seq: closing?.finalNode.seq ?? data.seq, openFile }\n const tail = renderSlot('conversation.chat.turnTail', owner)\n if (closing === null) return tail === null ? null : <div className={css.root} data-turn-tail={data.turn}>{tail}</div>\n // Interruption-frozen partials carry no messageId, so they address no\n // durable message and contribute no per-message actions.\n const messageId = closing.finalNode.messageId\n const assistantActions = messageId === undefined\n ? null\n : renderSlot('conversation.chat.assistant-actions', { messageId })\n return (\n <div\n className={css.root}\n data-turn-tail={data.turn}\n data-actions-reveal={endsWithResponse ? 'always' : 'hover'}\n >\n {tail}\n <MessageIconActions\n text={assistantText(closing.blocks)}\n time={closing.time}\n clock=\"end\"\n // The branch action owns boundary resolution: it sends the real\n // turn/end seq it already has, and the Host cuts exactly there.\n onBranch={forkAllowed ? () => { forkAt(data.seq) } : undefined}\n branchUnavailable={data.branchUnavailable || hasLaterChatNode}\n className={css.actions}\n extraActions={assistantActions}\n usageAction={detailed && data.tokenUsage !== undefined\n ? <TurnUsagePanel usage={data.tokenUsage} t={t} />\n : null}\n t={t}\n />\n </div>\n )\n})\n","/** Presentation of durable non-human messages claimed to begin a Turn. */\nimport type { ContextMessageNode } from '../contract/snapshot.ts'\nimport type { ChatKey } from '../locale.ts'\n\n/** Existing primitive glyph selected for a Turn trigger's source family. */\nexport type TurnTriggerIcon = 'agent' | 'continue' | 'github' | 'goal' | 'job' | 'plugin' | 'request' | 'schedule' | 'subagent' | 'team' | 'webhook'\n\nfunction record(value: unknown): Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {}\n}\n\nfunction field(source: Record<string, unknown>, key: string): string {\n return typeof source[key] === 'string' ? source[key] : ''\n}\n\n/** Missing or malformed historical reasons stay generic; unfamiliar reasons never imply success. */\nfunction subagentTitle(reason: unknown): ChatKey {\n if (typeof reason !== 'string' || reason === '') return 'message.trigger.subagent'\n switch (reason) {\n case 'completed': return 'message.trigger.subagent.completed'\n case 'aborted': return 'message.trigger.subagent.aborted'\n case 'error': return 'message.trigger.subagent.error'\n case 'max-tokens': return 'message.trigger.subagent.maxTokens'\n case 'refusal': return 'message.trigger.subagent.refusal'\n // Backends may extend the recorded reason vocabulary.\n default: return 'message.trigger.subagent.unknown'\n }\n}\n\n/**\n * Describe a waking message using its recorded source.\n * @param node - durable context, including the original notification body.\n * @returns localized title, source-family icon, and compact presentation for continuation receipts.\n */\nexport function turnTriggerDetails(node: ContextMessageNode): {\n title: ChatKey\n icon: TurnTriggerIcon\n compact?: true\n} {\n const source = record(node.source)\n const kind = field(source, 'kind')\n let title: ChatKey = 'message.trigger.request'\n let icon: TurnTriggerIcon = 'request'\n switch (kind) {\n case 'retry':\n if (node.content.length === 0) return { title: 'message.continuation.requested', icon: 'continue', compact: true }\n break\n case 'goal': {\n title = 'message.trigger.goal'\n icon = 'goal'\n break\n }\n case 'agent-message':\n title = 'message.trigger.agent'\n icon = 'agent'\n break\n case 'team-message':\n title = 'message.trigger.team'\n icon = 'team'\n break\n case 'subagent-settled':\n title = subagentTitle(source.stopReason)\n icon = 'subagent'\n break\n case 'webhook': {\n const github = field(source, 'provider') === 'github'\n title = github ? 'message.trigger.github' : 'message.trigger.webhook'\n icon = github ? 'github' : 'webhook'\n break\n }\n case 'schedule':\n title = 'message.trigger.schedule'\n icon = 'schedule'\n break\n case 'tool-jobs':\n title = 'message.trigger.job'\n icon = 'job'\n break\n case 'cordis-host-runner':\n title = 'message.trigger.plugin'\n icon = 'plugin'\n break\n default:\n // Custom sources remain visible without attributing unrecorded identity or success.\n break\n }\n return { title, icon }\n}\n","/** Recorded Turn triggers and compact manual-continuation receipts. */\nimport { useId, useState, type ComponentType } from 'react'\nimport {\n IconAgentPresetOutlineRegular, IconClockOutlineRegular, IconBranchOutlineRegular,\n IconChevronDownOutlineRegular, IconContextInjectionOutlineRegular, IconCordisPluginOutlineRegular,\n IconGoalOutlineRegular, IconGlobeOutlineRegular, IconPaperPlaneOutlineRegular, IconQueueOutlineRegular,\n IconUsersOutlineRegular, IconPlayOutlineRegular, type IconProps,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { ChatNodeViewProps } from '../contract/slots.ts'\nimport { formatMessageClock } from './message-chrome.ts'\nimport { NoticeBody } from './ContextBody.tsx'\nimport { turnTriggerDetails, type TurnTriggerIcon } from './turn-trigger.ts'\nimport css from './TurnTriggerNodeView.module.css'\n\nconst TRIGGER_ICONS: Record<TurnTriggerIcon, ComponentType<IconProps>> = {\n continue: IconPlayOutlineRegular,\n request: IconContextInjectionOutlineRegular,\n goal: IconGoalOutlineRegular,\n agent: IconPaperPlaneOutlineRegular,\n team: IconAgentPresetOutlineRegular,\n subagent: IconUsersOutlineRegular,\n github: IconBranchOutlineRegular,\n webhook: IconGlobeOutlineRegular,\n schedule: IconClockOutlineRegular,\n job: IconQueueOutlineRegular,\n plugin: IconCordisPluginOutlineRegular,\n}\n\n/** Render recorded trigger attribution above the whole-Turn disclosure. */\nexport function TurnTriggerNodeView({ node, t }: Pick<ChatNodeViewProps<'turn-trigger'>, 'node' | 't'>) {\n const [open, setOpen] = useState(false)\n const bodyId = useId()\n const details = turnTriggerDetails(node.data)\n const TriggerIcon = TRIGGER_ICONS[details.icon]\n if (details.compact) return (\n <div className={css.continuation} data-generation-continuation>\n <span className={css.icon} aria-hidden><TriggerIcon size={14} /></span>\n <span>{t(details.title)}</span>\n </div>\n )\n const date = new Date(node.data.time)\n const time = formatMessageClock(node.data.time, t)\n return (\n <section className={css.root} data-turn-trigger>\n <button className={css.header} type=\"button\" aria-expanded={open} aria-controls={bodyId} onClick={() => { setOpen(!open) }}>\n <span className={css.icon} aria-hidden><TriggerIcon size={14} /></span>\n <span className={css.title}>{t(details.title)}</span>\n <time className={css.time} dateTime={date.toISOString()}>{time}</time>\n <IconChevronDownOutlineRegular size={12} className={open ? css.openChevron : css.chevron} />\n </button>\n {open && <div id={bodyId} className={css.body}>\n <p className={css.explanation}>{t('message.trigger.explanation')}</p>\n <div className={css.content}><NoticeBody content={node.data.content} source={node.data.source} t={t} /></div>\n </div>}\n </section>\n )\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { PerformanceUsageMode } from '../../chat-settings.ts'\nimport type { ChatPresentationPolicy } from '../presentation-policy.ts'\nimport { NS } from '../locale.ts'\nimport { AssistantNodeView, type AssistantNodeInjected } from './AssistantNodeView.tsx'\nimport { sessionFilePath } from '../file-path.ts'\nimport { CommandNodeView, ManualCompactionNodeView } from './CommandNodeView.tsx'\nimport {\n CompactionNodeView, ContextMessageNodeView, RetryNodeView, TurnErrorNodeView,\n TurnMaxTokensNodeView, UnknownNodeView, UserMessageNodeView,\n} from './MessageItem.tsx'\nimport { DefaultReasoningBody, ReasoningContent } from './ReasoningContent.tsx'\nimport { SystemPromptNodeView } from './SystemPromptRow.tsx'\nimport { TurnProcessNodeView } from './TurnProcessNodeView.tsx'\nimport { TurnTailNodeView } from './TurnTailNodeView.tsx'\nimport { TurnTriggerNodeView } from './TurnTriggerNodeView.tsx'\n\n/**\n * Register this package's business renderers behind the keyed Chat Node seat.\n * Renderers whose output depends on the work-details mode receive the policy\n * through their own registration; the seat and the other renderers do not.\n * @param ctx - owning UI Conversation context.\n * @param performanceUsage - live statistics detail preference.\n * @param presentation - live presentation policy.\n */\nexport function registerChatNodeRenderers(\n ctx: Context,\n performanceUsage: ObservableSnapshot<PerformanceUsageMode>,\n presentation: ObservableSnapshot<ChatPresentationPolicy>,\n): void {\n ctx.effect(() => ctx.slots.registerFactory({\n name: 'conversation.chat.reasoning.content',\n scope: 'root',\n locale: NS,\n }, ReasoningContent))\n ctx.slots.inject('conversation.chat.reasoning.body', () => ctx.slots.register({\n name: 'conversation.chat.reasoning.body',\n priority: 100,\n }, DefaultReasoningBody))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node', key: 'user', locale: NS,\n children: { 'conversation.chat.user.before': { kind: 'chain', scope: 'session' } },\n }, UserMessageNodeView))\n // Steering rows share the renderer without owning the message-source seat.\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node', key: 'steering', locale: NS,\n inject: () => ({ renderSlotChain: () => null }),\n }, UserMessageNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'context', locale: NS }, ContextMessageNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-trigger', locale: NS }, TurnTriggerNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'system-prompt', locale: NS }, SystemPromptNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'assistant-step',\n locale: NS,\n children: {\n 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' },\n 'conversation.chat.message.images': { kind: 'single', scope: 'session' },\n },\n inject: (sessionId): AssistantNodeInjected => ({\n hooks: { presentation },\n resolveFilePath: sessionFilePath(ctx, sessionId),\n fileMentions: (owner, getFileTriggerProps) => ctx.get('chatFileMentions')?.forClosing(owner, sessionId, getFileTriggerProps),\n }),\n }, AssistantNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'command',\n locale: NS,\n children: { 'conversation.chat.commandview': { kind: 'keyed', scope: 'session' } },\n }, CommandNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'manual-compaction', locale: NS }, ManualCompactionNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'compaction', locale: NS }, CompactionNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'model-retry', locale: NS }, RetryNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-error', locale: NS }, TurnErrorNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-max-tokens', locale: NS }, TurnMaxTokensNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'turn-process', locale: NS }, TurnProcessNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({\n name: 'conversation.chat.node',\n key: 'turn-tail',\n locale: NS,\n inject: () => ({ hooks: { performanceUsage } }),\n children: {\n 'conversation.chat.turnTail': { kind: 'list', scope: 'session' },\n 'conversation.chat.assistant-actions': { kind: 'list', scope: 'session' },\n },\n }, TurnTailNodeView))\n ctx.slots.inject('conversation.chat.node', () => ctx.slots.register(\n { name: 'conversation.chat.node', key: 'unknown', locale: NS }, UnknownNodeView))\n}\n","/** Reusable user contents inside a caller-owned message row. */\nimport { Fragment } from 'react'\nimport type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots'\nimport { fileExtension, FileTypeIcon, fileSizeText, JsonBlock, UserMessageBubble } from '@deepseek-ai/dsh-client-ui-primitives'\nimport css from './MessageItem.module.css'\n\nconst EMPTY_LABELS: readonly string[] = []\n\n/**\n * Render prepared text, ordered attachments, and references without message chrome.\n * The caller owns row identity, pending/echo state, time, and message actions.\n * @param props - prepared content, facts, authorized image loader, and framework Factory/locale seats.\n * @returns the content stack using the existing user-message layout.\n */\nexport function UserContent({ content, loadImage, facts, interactive = false, ellipsis = false, renderSlot, renderFactorySlot, t }:\nFactoryComponentPropsOf<'conversation.chat.user.content'>) {\n const { text, attachments, extraBlocks, referenceLabels = EMPTY_LABELS } = content\n const compactImages = attachments.length > 1\n const truncated = (total: number): string => t('json.truncated', { total })\n const showBubble = text !== '' || extraBlocks.length > 0\n return (\n <div className={css.userStack}>\n {attachments.length > 0 && (\n <div className={css.attachmentRow} data-message-attachments>\n {attachments.map((attachment, index) => attachment.type === 'image'\n ? (\n <Fragment key={`image:${index}`}>\n {renderSlot('conversation.chat.user.images', {\n images: [attachment.image], loadImage, align: 'end', compact: compactImages,\n })}\n </Fragment>\n )\n : (\n <span key={`file:${index}`} className={css.fileCard} title={attachment.file.name}>\n <FileTypeIcon path={attachment.file.name} className={css.fileIcon} />\n <span className={css.fileContent}>\n <span className={css.fileName}>{attachment.file.name}</span>\n <span className={css.fileMeta}>\n {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)]\n .filter(Boolean).join(' ')}\n </span>\n </span>\n </span>\n ))}\n </div>\n )}\n {showBubble && <UserMessageBubble data-message-bubble=\"\" data-text-interaction-source=\"\">\n {renderFactorySlot('conversation.user.text', { text, facts, interactive, ellipsis })}\n {extraBlocks.map((block, index) => (\n <JsonBlock key={index} label={t('message.extraBlock')} payload={block} truncatedLabel={truncated} />\n ))}\n </UserMessageBubble>}\n {referenceLabels.length > 0 && (\n <div className={css.referenceSummary}>\n {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })}\n </div>\n )}\n </div>\n )\n}\n","// Assistant timing readings used by session statistics.\n\nimport type {\n AssistantMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/** One assistant step's derivable latency facts; null marks an unrecorded part. */\nexport interface StepReading {\n /** step/start → first token delta, in ms. */\n ttftMs: number | null\n /** First token delta → final message, in ms. */\n decodeMs: number | null\n /** Provider-reported completion tokens. */\n outputTokens: number | null\n}\n\ninterface UsageLike {\n outputTokens?: number\n}\n\ntype AssistantNode = AssistantMessageNode\n\nfunction usageOutputTokens(usage: unknown): number | null {\n if (typeof usage !== 'object' || usage === null) return null\n const value = (usage as UsageLike).outputTokens\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null\n}\n\n/**\n * Read one assistant node's TTFT, decode wall time, and output tokens.\n * @param node - A settled assistant node.\n * @returns Per-part readings with `null` for unrecorded values.\n */\nexport function assistantStepReading(node: AssistantNode): StepReading {\n const timing = node.timing\n const ttftMs = timing !== undefined && timing.stepStartTime !== null && timing.firstTokenTime !== null\n ? Math.max(0, timing.firstTokenTime - timing.stepStartTime)\n : null\n const decodeMs = timing !== undefined && timing.firstTokenTime !== null\n ? Math.max(0, timing.completedTime - timing.firstTokenTime)\n : null\n return { ttftMs, decodeMs, outputTokens: usageOutputTokens(node.usage) }\n}\n","// Composer statistics pills, each its own 'conversation.composer.dock' list\n// entry (activity, usage) so a plugin can replace or add one pill by id.\n// Compact keeps speed and cache hit as plain readings; Detailed adds counts,\n// token totals, and click-open dialogs. Settled-node identity prevents\n// stream-delta updates from rerendering the pills.\n\nimport { memo, useMemo, type ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport { IconDatabaseOutlineRegular, IconGaugeOutlineRegular, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { UseProjection } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { InjectFace, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: merges the sessionStats key into SessionProjectionMap for useProjection.\nimport type {} from '@deepseek-ai/dsh-session-stats/client'\nimport type { TokenUsageProjection } from '@deepseek-ai/dsh-token-meter/client'\nimport type { ChatViewSlotProps, PerformanceUsageInjected } from '../contract/slots.ts'\nimport type { ChatSnapshot } from '../contract/snapshot.ts'\nimport { formatTokensPerSecond } from './message-chrome.ts'\nimport { assistantStepReading } from '../contract/turn-metrics.ts'\nimport { formatCacheHitPercent, formatExactTokens, formatTokens } from './token-format.ts'\nimport { useStatDialog } from './stat-dialog.ts'\nimport css from './StatsPills.module.css'\nimport dialogCss from './stat-dialog.module.css'\n\ninterface WindowStats {\n turns: number\n steps: number\n /** Summed request wall time (step/start → assistant/message); 0 when no node carries timing. */\n llmMs: number\n /** Summed tool wall time (tool/call → tool/result); 0 when no pair is in-window. */\n toolMs: number\n /** Summed first-token latency over `ttftSteps`; 0 when no step records it. */\n ttftMs: number\n /** Steps carrying a recorded TTFT. */\n ttftSteps: number\n /** Summed decode wall time over steps that also report output tokens. */\n decodeMs: number\n /** Summed output tokens over the same decode-timed steps. */\n decodeTokens: number\n}\n\n/**\n * Fold assistant and tool-result nodes into window-scoped display totals —\n * the FALLBACK for assemblies without the `sessionStats` projection.\n *\n * Every displayed figure rides that durable whole-log projection (and token\n * accounting rides `tokenUsage`) because the window is paged and compaction\n * rewrites it; this fold answers \"what is on screen\" only when no projection\n * value is served. Its field names deliberately mirror the projection's so\n * the two swap wholesale.\n * @param nodes - snapshot nodes.\n * @returns fallback counts and summed wall times.\n */\nexport function deriveStats(nodes: ChatSnapshot['legacy']['nodes']): WindowStats {\n const turns = new Set<number>()\n let steps = 0\n let llmMs = 0\n let toolMs = 0\n let ttftMs = 0\n let ttftSteps = 0\n let decodeMs = 0\n let decodeTokens = 0\n for (const node of nodes) {\n if (node.kind === 'tool-result') {\n if (node.callTime !== null) toolMs += Math.max(0, node.time - node.callTime)\n continue\n }\n if (node.kind !== 'assistant') continue\n turns.add(node.turn)\n steps += 1\n if (node.timing !== undefined && node.timing.stepStartTime !== null) {\n llmMs += Math.max(0, node.timing.completedTime - node.timing.stepStartTime)\n }\n const reading = assistantStepReading(node)\n if (reading.ttftMs !== null) {\n ttftMs += reading.ttftMs\n ttftSteps += 1\n }\n if (reading.decodeMs !== null && reading.outputTokens !== null) {\n decodeMs += reading.decodeMs\n decodeTokens += reading.outputTokens\n }\n }\n return { turns: turns.size, steps, llmMs, toolMs, ttftMs, ttftSteps, decodeMs, decodeTokens }\n}\n\n/**\n * Compact duration: 45.2s under a minute, 2m42s from there on.\n * @param ms - duration in milliseconds.\n * @returns display string.\n */\nexport function formatDuration(ms: number, t: ChatViewSlotProps['t']): string {\n const s = ms / 1_000\n if (s < 60) return t('duration.compactSeconds', { seconds: Math.round(s * 10) / 10 })\n const whole = Math.round(s)\n return t('duration.compactMinutes', {\n minutes: Math.floor(whole / 60),\n seconds: whole % 60,\n })\n}\n\n/**\n * Display-ready cache-hit share of prompt-side input over the whole durable log.\n * @param usage - the session's token-usage projection value.\n * @returns integer text when integer rounding stays below 100, otherwise the\n * minimum decimal precision that still rounds below 100; a full hit returns\n * 100, and no billed input returns null.\n */\nexport function cacheHitPercent(usage: TokenUsageProjection): string | null {\n const denominator = billedInputTokens(usage)\n return formatCacheHitPercent(usage.cacheReadTokens, denominator)\n}\n\n/**\n * Sum the three disjoint prompt-side billing buckets.\n * @param usage - the session's token-usage projection value.\n * @returns billed input tokens.\n */\nexport function billedInputTokens(usage: TokenUsageProjection): number {\n return usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens\n}\n\ntype Translate = ChatViewSlotProps['t']\n\n/** Props shared by every composer stats pill: the conversation-snapshot selector plus the projection read seat. */\nexport interface StatPillProps extends InjectFace<PerformanceUsageInjected> {\n useChat: SnapshotSelectorHook<ChatSnapshot>\n useProjection: UseProjection\n /** The owning dock's locale seat. */\n t: Translate\n}\n\n/** Dock entry id carried as `data-composer-stat` on each pill. */\ntype StatId = 'activity' | 'usage'\n\ninterface PillContent {\n stat: StatId\n icon: ReactNode\n label: ReactNode\n /** The full reading as plain text: the accessible name and the tooltip shown while the label is cut off. */\n text: string\n}\n\nfunction exactCount(value: number, t: Translate): string {\n return t('message.turnUsage.count', { count: formatExactTokens(value, t) })\n}\n\n/** One or two reading segments, visually joined by a separator glyph. */\nfunction reading(first: string, second: string | null): Pick<PillContent, 'label' | 'text'> {\n if (second === null) return { label: first, text: first }\n return {\n label: (\n <>\n {first}\n <span className={css.sep} aria-hidden>·</span>\n {second}\n </>\n ),\n text: `${first} · ${second}`,\n }\n}\n\n// Every figure rides the durable sessionStats projection, so paging and\n// compaction cannot change any of them; an assembly without the unit falls\n// back to the window-scoped fold wholesale (same field names), paid only\n// while no projection value is served.\nfunction useSessionStats(useChat: StatPillProps['useChat'], useProjection: UseProjection): WindowStats {\n const settledNodes = useChat(s => s.legacy.nodes)\n const projected = useProjection('sessionStats')\n return useMemo(() => projected ?? deriveStats(settledNodes), [projected, settledNodes])\n}\n\nfunction decodeSpeed(stats: WindowStats, t: Translate): string {\n return t('message.tokensPerSecond', {\n tps: formatTokensPerSecond(stats.decodeTokens / (stats.decodeMs / 1_000)),\n })\n}\n\n/** The full reading above a pill, only while an ellipsis cuts its label; the delay matches the dock's context meter. */\nconst FULL_READING_TOOLTIP = { side: 'top', portal: true, delayMs: 200, onlyWhenClipped: true } as const\n\n/** A static reading: used when the pill has no dialog rows or the mode is Compact. */\nfunction PlainPill({ stat, icon, label, text }: PillContent) {\n return (\n <span className={css.anchor} data-composer-stat={stat}>\n {/* No dialog carries a static reading, so a tap also pins the full text. */}\n <Tooltip label={text} {...FULL_READING_TOOLTIP} openOnClick>\n <span className={css.pill}>\n {icon}\n <span className={css.label}>{label}</span>\n </span>\n </Tooltip>\n </span>\n )\n}\n\n/**\n * A pill button opening its own portaled dialog. Each pill owns its open\n * state; useStatDialog closes it on Escape or an outside pointerdown or click,\n * so at most one dialog is open across the dock.\n */\nfunction DialogPill({ stat, icon, label, text, title, titleValue, children }: PillContent & {\n title: string\n titleValue?: string\n children: ReactNode\n}) {\n const { open, setOpen, rootRef, panelRef, anchorName } = useStatDialog()\n return (\n <span ref={rootRef} style={{ anchorName }} className={css.anchor} data-composer-stat={stat}>\n {/* The open dialog already shows every figure; a tooltip would cover it. */}\n <Tooltip label={text} {...FULL_READING_TOOLTIP} disabled={open}>\n <button\n type=\"button\"\n className={css.pill}\n aria-haspopup=\"dialog\"\n aria-expanded={open}\n aria-label={text}\n onClick={() => { setOpen(!open) }}\n >\n {icon}\n <span className={css.label}>{label}</span>\n </button>\n </Tooltip>\n {open && createPortal(\n <div\n ref={panelRef}\n className={dialogCss.panel}\n role=\"dialog\"\n aria-label={title}\n style={{ positionAnchor: anchorName }}\n >\n <div className={dialogCss.title}>\n <span className={dialogCss.titleLabel}>\n {icon}\n {title}\n </span>\n {titleValue !== undefined && <span className={dialogCss.titleValue}>{titleValue}</span>}\n </div>\n <div className={dialogCss.titleRule} aria-hidden />\n {children}\n </div>,\n document.body,\n )}\n </span>\n )\n}\n\n/**\n * Turn and step counts with whole-session speed, opening the time and speed\n * dialog; Compact keeps only the speed reading.\n */\nexport const ActivityPill = memo(function ActivityPill({ useChat, useProjection, usePerformanceUsage, t }: StatPillProps) {\n const mode = usePerformanceUsage(value => value)\n const stats = useSessionStats(useChat, useProjection)\n const speed = stats.decodeMs > 0 ? decodeSpeed(stats, t) : null\n const icon = <IconGaugeOutlineRegular />\n if (mode === 'compact') return speed === null ? null : <PlainPill stat=\"activity\" icon={icon} {...reading(speed, null)} />\n if (stats.steps === 0) return null\n const counts = t('stats.counts', { turns: stats.turns, steps: stats.steps })\n const content: PillContent = { stat: 'activity', icon, ...reading(counts, speed) }\n // A window without one timed figure has no dialog rows to show, so the pill\n // stays a plain reading instead of a button opening an empty dialog.\n if (stats.llmMs <= 0 && stats.toolMs <= 0 && stats.ttftSteps <= 0 && speed === null) return <PlainPill {...content} />\n return (\n // The counts head the dialog, so a cut-off reading stays complete once the dialog opens.\n <DialogPill {...content} title={t('stats.dialog.title')} titleValue={counts}>\n <dl className={dialogCss.details} data-session-stats-details>\n {stats.llmMs > 0 && (\n <>\n <dt>{t('stats.dialog.llmTime')}</dt>\n <dd>{formatDuration(stats.llmMs, t)}</dd>\n </>\n )}\n {stats.toolMs > 0 && (\n <>\n <dt>{t('stats.dialog.toolTime')}</dt>\n <dd>{formatDuration(stats.toolMs, t)}</dd>\n </>\n )}\n {stats.ttftSteps > 0 && (\n <>\n <dt>{t('stats.dialog.ttft')}</dt>\n <dd>{formatDuration(stats.ttftMs / stats.ttftSteps, t)}</dd>\n </>\n )}\n {speed !== null && (\n <>\n <dt>{t('stats.dialog.speed')}</dt>\n <dd>{speed}</dd>\n </>\n )}\n </dl>\n </DialogPill>\n )\n})\n\n/** Whole-log token total and cache hit; Compact keeps only the cache hit. */\nexport const UsagePill = memo(function UsagePill({ useProjection, usePerformanceUsage, t }: StatPillProps) {\n const mode = usePerformanceUsage(value => value)\n const usage = useProjection('tokenUsage')\n // Gated on actual token activity: a session whose steps all settled without\n // billing (e.g. every request failed) shows no usage pill.\n if (usage === undefined || (billedInputTokens(usage) === 0 && usage.outputTokens === 0)) return null\n const cacheHit = cacheHitPercent(usage)\n const cacheHitText = cacheHit !== null ? t('stats.cacheHit', { percent: cacheHit }) : null\n const icon = <IconDatabaseOutlineRegular />\n if (mode === 'compact') {\n return cacheHitText === null ? null : <PlainPill stat=\"usage\" icon={icon} {...reading(cacheHitText, null)} />\n }\n // Same aggregate as the Turn pill's totalTokens: every prompt-side billing bucket plus output.\n const total = billedInputTokens(usage) + usage.outputTokens\n const totalText = t('message.turnUsage.count', { count: formatTokens(total, t) })\n return (\n <DialogPill\n stat=\"usage\"\n icon={icon}\n {...reading(totalText, cacheHitText)}\n title={t('stats.dialog.usageTitle')}\n titleValue={exactCount(total, t)}\n >\n {/* jscpd:ignore-start -- the session-total bucket rows deliberately mirror\n TurnUsagePanel's per-turn dl: same skin, different data contract (the\n buckets are always present here; per-turn fields are optional). A\n session that never wrote cache drops the row, as the per-turn panel\n drops its absent fields. */}\n <dl className={dialogCss.details} data-session-stats-usage>\n {cacheHit !== null && (\n <>\n <dt>{t('message.turnUsage.cacheHit')}</dt>\n <dd>{`${cacheHit}%`}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.input')}</dt>\n <dd>{exactCount(usage.uncachedInputTokens, t)}</dd>\n <dt>{t('message.turnUsage.cacheRead')}</dt>\n <dd>{exactCount(usage.cacheReadTokens, t)}</dd>\n {usage.cacheWriteTokens !== 0 && (\n <>\n <dt>{t('message.turnUsage.cacheWrite')}</dt>\n <dd>{exactCount(usage.cacheWriteTokens, t)}</dd>\n </>\n )}\n <dt>{t('message.turnUsage.output')}</dt>\n <dd>{exactCount(usage.outputTokens, t)}</dd>\n </dl>\n {/* jscpd:ignore-end */}\n </DialogPill>\n )\n})\n","import type {\n ConversationLocation, ConversationNodeContext,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {\n ChatNode, ChatNodeDataMap, ChatNodeKind,\n} from '../contract/chat-nodes.ts'\nimport type { ChatGroupTree } from '../contract/group-tree.ts'\n\n/**\n * Relative positions in one durable event's seq neighborhood: interrupted\n * Assistant, its follow-up Nodes, then follow-ups to an ordinary final. The\n * max-tokens notice sits between a closing Assistant and the turn-tail so the\n * tail stays the turn's last node and keeps its branch action enabled.\n */\nexport const CHAT_SYNTHETIC_SEQ_OFFSETS = {\n interruptedAssistant: -0.9,\n interruptedFollowup: -0.8,\n processControl: -0.1,\n maxTokensNotice: 0.05,\n finalizedFollowup: 0.1,\n} as const\n\n/**\n * Resolve one Context's best currently loaded event Location.\n * @param context - assembled business Context.\n * @returns start or first-match Location, otherwise unresolved.\n */\nexport function contextLocation(context: ConversationNodeContext): ConversationLocation {\n return context.start?.location ?? context.matches[0]?.location ?? { kind: 'unresolved' }\n}\n\n/**\n * Read the Turn and Step a Location resolves to.\n * @param location - engine-owned Location.\n * @returns resolved coordinates; Session-level and unresolved Locations have none.\n */\nexport function locationCoordinates(location: ConversationLocation): { turn?: number; step?: number } {\n if (location.kind === 'step') return { turn: location.turn.turn, step: location.step.step }\n if (location.kind === 'turn') return { turn: location.turn.turn }\n return {}\n}\n\n/**\n * Build one final Chat target Node with the engine-owned stable key.\n * @param context - assembled business Context.\n * @param kind - Chat renderer dispatch key.\n * @param anchorSeq - sortable render position.\n * @param data - renderer-owned payload.\n * @param options - optional Location, visibility, and group-tree overrides.\n * @returns final Chat view Node.\n */\nexport function chatNode<Kind extends ChatNodeKind>(\n context: ConversationNodeContext,\n kind: Kind,\n anchorSeq: number,\n data: ChatNodeDataMap[Kind],\n options: {\n readonly location?: ConversationLocation\n readonly visibility?: 'visible' | 'hidden'\n readonly groupTree?: ChatGroupTree | undefined\n } = {},\n): ChatNode<Kind> {\n return {\n key: context.key,\n kind,\n id: context.id,\n target: 'chat',\n anchorSeq,\n location: options.location ?? contextLocation(context),\n visibility: options.visibility ?? 'visible',\n groupTree: options.groupTree,\n data,\n }\n}\n\n/**\n * Read a finite non-negative integer from a structurally narrowed payload.\n * @param value - untrusted payload field.\n * @returns valid coordinate, otherwise undefined.\n */\nexport function coordinate(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n","/** Chat-owned conversion from durable Session events to Chat view data. */\n\nimport type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm/types'\nimport type {\n AssistantBlock, ContextProducerView, KnownContextForm,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\n/* jscpd:ignore-start -- Chat and Trajectory own independent event-to-view projections. */\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null\n}\n\nfunction readString(record: Record<string, unknown>, key: string): string | null {\n const value = record[key]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction collect(source: Record<string, unknown>, member: string, field: string): string[] {\n const list = source[member]\n if (!Array.isArray(list)) return []\n const seen: string[] = []\n for (const entry of list) {\n const record = asRecord(entry)\n const value = record === null ? null : readString(record, field)\n if (value !== null && !seen.includes(value)) seen.push(value)\n }\n return seen\n}\n\nfunction joined(names: string[]): string | null {\n return names.length > 0 ? names.join(', ') : null\n}\n\n/** Forms Chat presents structurally; unknown merge-extensible values remain opaque. */\nconst KNOWN_FORMS: readonly KnownContextForm[] = [\n 'instructions', 'catalog', 'snapshot', 'notice', 'relay', 'recall',\n]\n\n/**\n * Read the target-supported presentation form from a durable message source.\n * @param source - Logged `user/message` source.\n * @returns Supported form, or null for the opaque presentation.\n */\nexport function contextForm(source: unknown): KnownContextForm | null {\n const record = asRecord(source)\n const form = record === null ? null : readString(record, 'form')\n return form !== null && (KNOWN_FORMS as readonly string[]).includes(form)\n ? form as KnownContextForm\n : null\n}\n\n/**\n * Project a durable message source to the Chat row's role and producer label.\n * @param source - Logged `user/message` source.\n * @returns Role and label rendered by Chat.\n */\nexport function contextProducer(source: unknown): ContextProducerView {\n const record = asRecord(source)\n const kind = record === null ? null : readString(record, 'kind')\n if (record === null || kind === null) return { role: 'inject', label: null }\n switch (kind) {\n case 'session-reference':\n return { role: 'recall', label: joined(collect(record, 'references', 'label')) ?? kind }\n case 'agent-instructions':\n return { role: 'inject', label: joined(collect(record, 'changes', 'path')) ?? kind }\n case 'skill-invocation':\n return { role: 'inject', label: readString(record, 'name') ?? kind }\n default:\n // MessageSourceMap is merge-extensible; keep an unknown producer\n // visible by its durable kind.\n return { role: 'inject', label: kind }\n }\n}\n\n/**\n * Read distinct labels cited by a durable cross-session recall source.\n * @param source - Logged `user/message` source.\n * @returns Labels in first-seen order.\n */\nexport function sessionRecallLabels(source: unknown): string[] {\n const record = asRecord(source)\n if (record === null || readString(record, 'kind') !== 'session-reference') return []\n return collect(record, 'references', 'label')\n}\n\n/**\n * Read the skill name a durable skill-invocation injection loaded.\n * @param source - Logged `user/message` source.\n * @returns The skill name, or null for every other source.\n */\nexport function skillInvocationName(source: unknown): string | null {\n const record = asRecord(source)\n if (record === null || readString(record, 'kind') !== 'skill-invocation') return null\n return readString(record, 'name')\n}\n\n/**\n * Classify finalized Assistant content for Chat rendering.\n * @param content - Core content blocks.\n * @returns Chat blocks in source order.\n */\nexport function toAssistantBlocks(content: readonly ContentBlock[]): AssistantBlock[] {\n return content.map(toAssistantBlock)\n}\n\n/**\n * Classify one finalized Assistant block for Chat rendering.\n * @param block - Core content block.\n * @returns Chat block.\n */\nexport function toAssistantBlock(block: ContentBlock): AssistantBlock {\n switch (block.type) {\n case 'text': return { kind: 'text', text: block.text }\n case 'reasoning': return { kind: 'reasoning', text: block.text }\n case 'image': return { kind: 'image', attachment: block.attachment }\n case 'tool-call': return { kind: 'tool-call', callId: String(block.id), name: block.name, argsRaw: block.arguments }\n default: return { kind: 'other', block }\n }\n}\n\n/**\n * Create the initial Chat block for one streamed Assistant block kind.\n * @param blockType - Wire block kind.\n * @returns Empty block ready to receive deltas.\n */\nexport function emptyAssistantBlock(blockType: string): AssistantBlock {\n switch (blockType) {\n case 'text': return { kind: 'text', text: '' }\n case 'reasoning': return { kind: 'reasoning', text: '' }\n case 'tool-call': return { kind: 'tool-call', callId: '', name: '', argsRaw: '' }\n default: return { kind: 'other', block: null }\n }\n}\n\n/** Display-safe failure fields retained by Chat projections. */\nexport interface DisplayFailure {\n readonly code?: string\n readonly message: string\n}\n\n/**\n * Convert a durable failure to locale-independent fields safe for Chat.\n * @param failure - Failure preserved by a Session event.\n * @returns Sanitized message and optional stable provider code.\n */\nexport function displayFailure(failure: unknown): DisplayFailure {\n if (failure === null || typeof failure !== 'object') return { message: String(failure) }\n const record = failure as { code?: unknown; message?: unknown }\n const code = typeof record.code === 'string' ? record.code : undefined\n // Provider AUTH messages may echo a masked or partially preserved credential.\n // Keep the raw diagnostic in the Session log, but never retain it in UI state.\n if (code === 'AUTH') return { code, message: '' }\n return {\n ...(code === undefined ? {} : { code }),\n message: typeof record.message === 'string' ? record.message : JSON.stringify(failure),\n }\n}\n\n/**\n * Whether a stream chunk carries visible model output for Chat timing.\n * @param chunk - Stream chunk to inspect.\n * @returns true for a non-empty text, reasoning, or Tool-call delta.\n */\nexport function isTokenDelta(chunk: StreamChunk): boolean {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return chunk.text !== ''\n case 'tool-call-delta':\n return chunk.argumentsDelta !== '' || chunk.name !== undefined\n default:\n return false\n }\n}\n\n/* jscpd:ignore-end */\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n AssistantBlock, AssistantMessageNode, ConversationLocation, ConversationMatch,\n ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { StreamChunk } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session/types'\nimport type { AssistantChatData } from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\nimport {\n emptyAssistantBlock, isTokenDelta, toAssistantBlock, toAssistantBlocks,\n} from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Streaming, settled, or interrupted Assistant step. */\n 'assistant-step': AssistantChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationStepDataMap {\n /** Streaming, settled, or interrupted Assistant material for this Step. */\n 'assistant-step': AssistantChatData\n }\n}\n\ninterface AssistantState {\n readonly turn: number\n readonly step: number\n readonly blocks: readonly (AssistantBlock | undefined)[]\n /** Missing indices are invisible; same-kind appends preserve already-visible blocks. */\n readonly visibleByIndex: readonly boolean[]\n readonly visibleBlocks: number\n readonly firstVisibleSeq: number | undefined\n readonly firstVisibleTime: number | undefined\n readonly firstTokenTime: number | undefined\n readonly final: ConversationMatch | undefined\n readonly usage: unknown\n}\n\nfunction initialState(turn: number, step: number): AssistantState {\n return {\n turn,\n step,\n blocks: [],\n visibleByIndex: [],\n visibleBlocks: 0,\n firstVisibleSeq: undefined,\n firstVisibleTime: undefined,\n firstTokenTime: undefined,\n final: undefined,\n usage: undefined,\n }\n}\n\nfunction compactBlocks(blocks: readonly (AssistantBlock | undefined)[]): AssistantBlock[] {\n return blocks.filter((block): block is AssistantBlock => block !== undefined)\n}\n\nfunction blockIsVisible(block: AssistantBlock | undefined): boolean {\n if (block === undefined || block.kind === 'tool-call') return false\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n}\n\nfunction hasVisibleContent(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some(blockIsVisible)\n}\n\nfunction hasInterruptionEvidence(blocks: readonly AssistantBlock[]): boolean {\n return blocks.some((block) => {\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n })\n}\n\nfunction resetForRetry(state: AssistantState): AssistantState {\n return {\n ...initialState(state.turn, state.step),\n firstTokenTime: state.firstTokenTime,\n }\n}\n\nfunction updateChunk(\n state: AssistantState,\n chunk: StreamChunk,\n seq: number,\n time: number,\n): AssistantState {\n if (chunk.type === 'tool-call-delta') {\n const previous = state.blocks[chunk.index]\n if (previous?.kind === 'tool-call' && previous.callId !== ''\n && (chunk.name === undefined || chunk.name === previous.name)\n && (state.firstTokenTime !== undefined || !isTokenDelta(chunk))) return state\n }\n const blocks = [...state.blocks]\n let changedIndex = -1\n let previousVisible = false\n let nextVisible = false\n switch (chunk.type) {\n case 'block-start':\n changedIndex = chunk.index\n previousVisible = state.visibleByIndex[chunk.index] === true\n blocks[chunk.index] = emptyAssistantBlock(chunk.blockType)\n nextVisible = blockIsVisible(blocks[chunk.index])\n break\n case 'text-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = state.visibleByIndex[chunk.index] === true\n blocks[chunk.index] = { kind: 'text', text: (previous?.kind === 'text' ? previous.text : '') + chunk.text }\n nextVisible = (previous?.kind === 'text' && previousVisible) || chunk.text.trim() !== ''\n break\n }\n case 'reasoning-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = state.visibleByIndex[chunk.index] === true\n blocks[chunk.index] = { kind: 'reasoning', text: (previous?.kind === 'reasoning' ? previous.text : '') + chunk.text }\n nextVisible = (previous?.kind === 'reasoning' && previousVisible) || chunk.text.trim() !== ''\n break\n }\n case 'tool-call-delta': {\n const previous = blocks[chunk.index]\n changedIndex = chunk.index\n previousVisible = state.visibleByIndex[chunk.index] === true\n // Tool Nodes own streamed arguments; Assistant protocol blocks retain identity until full settlement.\n blocks[chunk.index] = {\n kind: 'tool-call',\n callId: (previous?.kind === 'tool-call' ? previous.callId : '') || String(chunk.id),\n name: chunk.name ?? (previous?.kind === 'tool-call' ? previous.name : ''),\n argsRaw: previous?.kind === 'tool-call' ? previous.argsRaw : '',\n }\n break\n }\n case 'block-end':\n changedIndex = chunk.index\n previousVisible = state.visibleByIndex[chunk.index] === true\n blocks[chunk.index] = toAssistantBlock(chunk.block)\n nextVisible = blockIsVisible(blocks[chunk.index])\n break\n case 'usage':\n return { ...state, usage: chunk.usage }\n default:\n return state\n }\n const visibleBlocks = state.visibleBlocks\n - Number(previousVisible)\n + Number(nextVisible)\n let visibleByIndex = state.visibleByIndex\n if (previousVisible !== nextVisible) {\n const next = [...visibleByIndex]\n next[changedIndex] = nextVisible\n visibleByIndex = next\n }\n const firstToken = isTokenDelta(chunk)\n return {\n ...state,\n blocks,\n visibleByIndex,\n visibleBlocks,\n ...visibleBlocks > 0 && state.firstVisibleSeq === undefined\n ? { firstVisibleSeq: seq, firstVisibleTime: time }\n : {},\n ...firstToken && state.firstTokenTime === undefined\n ? { firstTokenTime: time }\n : {},\n }\n}\n\nfunction settleMessage(\n state: AssistantState,\n match: ConversationMatch,\n event: SessionEvent<'assistant/message'>,\n): AssistantState {\n const blocks = toAssistantBlocks(event.data.message.content)\n const visibleByIndex = blocks.map(blockIsVisible)\n return {\n ...state,\n blocks,\n visibleByIndex,\n visibleBlocks: visibleByIndex.reduce((count, visible) => count + Number(visible), 0),\n final: match,\n usage: event.data.usage,\n }\n}\n\nfunction closedBoundary(location: ConversationLocation): { seq: number; time: number } | undefined {\n if (location.kind === 'step' && location.step.status === 'closed' && location.step.end !== undefined) {\n return location.step.end\n }\n if ((location.kind === 'step' || location.kind === 'turn')\n && location.turn.status === 'closed' && location.turn.end !== undefined) {\n return location.turn.end\n }\n return undefined\n}\n\nfunction finalNode(\n state: AssistantState,\n context: ConversationNodeContext<AssistantState>,\n): AssistantMessageNode | undefined {\n const final = state.final\n if (final?.event.type === 'assistant/message') {\n const event = final.event\n return {\n kind: 'assistant',\n seq: event.seq,\n messageId: event.data.message.id,\n time: event.time,\n turn: state.turn,\n step: state.step,\n blocks: toAssistantBlocks(event.data.message.content),\n usage: event.data.usage,\n timing: {\n stepStartTime: context.start?.event.time ?? null,\n firstTokenTime: state.firstTokenTime ?? null,\n completedTime: event.time,\n },\n ...event.data.interrupted === true ? { interrupted: true } : {},\n }\n }\n const location = context.start?.location ?? context.matches.at(-1)?.location\n const boundary = location === undefined ? undefined : closedBoundary(location)\n if (boundary === undefined) return undefined\n const blocks = compactBlocks(state.blocks)\n if (!hasInterruptionEvidence(blocks)) return undefined\n return {\n kind: 'assistant',\n seq: boundary.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedAssistant,\n time: boundary.time,\n turn: state.turn,\n step: state.step,\n blocks,\n interrupted: true,\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<AssistantState>): AssistantState | undefined {\n let state: AssistantState | undefined\n for (const match of context.matches) {\n if (match.event.type === 'assistant/live-chunk') {\n state ??= initialState(match.event.data.turn, match.event.data.step)\n state = updateChunk(state, match.event.data.chunk, match.event.seq, match.event.time)\n continue\n }\n if (match.event.type === 'assistant/message') {\n state ??= initialState(match.event.data.turn, match.event.data.step)\n state = settleMessage(state, match, match.event)\n continue\n }\n if (match.event.type === 'llm/retry' && state !== undefined) {\n state = resetForRetry(state)\n }\n }\n return state\n}\n\ninterface AssistantProjection {\n readonly data: AssistantChatData\n readonly anchorSeq: number\n readonly visible: boolean\n readonly settled: AssistantMessageNode | undefined\n}\n\nfunction projectAssistant(context: ConversationNodeContext<AssistantState>): AssistantProjection | undefined {\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return undefined\n const settled = finalNode(state, context)\n const blocks = settled?.blocks ?? compactBlocks(state.blocks)\n const visible = settled === undefined ? state.visibleBlocks > 0 : hasVisibleContent(blocks)\n const status = settled?.interrupted === true\n ? 'interrupted'\n : settled === undefined ? 'running' : 'settled'\n const anchorSeq = (settled?.interrupted === true ? settled.seq : state.firstVisibleSeq ?? settled?.seq)\n ?? context.matches[0]?.event.seq ?? 0\n const time = settled?.time ?? state.firstVisibleTime ?? context.matches[0]?.event.time ?? 0\n return {\n anchorSeq,\n visible,\n settled,\n data: {\n status,\n turn: state.turn,\n step: state.step,\n blocks,\n time,\n ...state.usage === undefined ? {} : { usage: state.usage },\n ...settled === undefined ? {} : { finalNode: settled },\n },\n }\n}\n\nfunction publishedAssistantData(\n context: ConversationNodeContext<AssistantState>,\n): Readonly<AssistantChatData> | undefined {\n const location = context.start?.location ?? context.matches.at(-1)?.location\n return location?.kind === 'step' ? location.step.data.get('assistant-step') : undefined\n}\n\n/** Per-step Assistant lifecycle; materialized keys survive cleared stream content as hidden Nodes. */\nexport const assistantDefinition: ConversationNodeDefinition<AssistantState> = {\n kind: 'assistant-step',\n target: 'chat',\n match: (event) => {\n if (event.type === 'step/start') return { id: `${event.data.turn}:${event.data.step}`, role: 'start' }\n if (event.type === 'assistant/live-chunk'\n || (event.type === 'assistant/message' && event.surfaceOp === 'append')) {\n return { id: `${event.data.turn}:${event.data.step}`, role: 'update' }\n }\n if (event.type === 'llm/retry') {\n return { id: `${event.data.turn}:${event.data.step}`, role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'step/start') throw new Error('assistant-step start requires step/start')\n return initialState(match.event.data.turn, match.event.data.step)\n },\n update: (context, match) => {\n if (match.event.type === 'assistant/live-chunk') {\n return updateChunk(context.state, match.event.data.chunk, match.event.seq, match.event.time)\n }\n if (match.event.type === 'assistant/message') return settleMessage(context.state, match, match.event)\n if (match.event.type === 'llm/retry') {\n return resetForRetry(context.state)\n }\n return context.state\n },\n publication: (match) => {\n if (match.event.type === 'step/start') return 'none'\n if (match.event.type !== 'assistant/live-chunk') return 'immediate'\n const type = match.event.data.chunk.type\n return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame'\n },\n buildLocationData: (context, scope) => {\n if (scope !== 'step') return null\n const projected = projectAssistant(context)\n if (projected === undefined) return null\n return {\n kind: 'step',\n turn: projected.data.turn,\n step: projected.data.step,\n key: 'assistant-step',\n value: projected.data,\n }\n },\n buildViewNode: (context) => {\n const current = context.current.get('chat')\n const state = context.state ?? fallbackState(context)\n const data = publishedAssistantData(context)\n if (state === undefined || data === undefined) {\n return current == null ? null : { ...current, visibility: 'hidden' }\n }\n const settled = data.finalNode\n const visible = settled === undefined ? state.visibleBlocks > 0 : hasVisibleContent(data.blocks)\n if (settled === undefined && !visible && current == null) return null\n // A successful message retains its live anchor alongside pending Tool calls.\n const anchorSeq = (settled?.interrupted === true ? settled.seq : state.firstVisibleSeq ?? settled?.seq)\n ?? context.matches[0]?.event.seq ?? 0\n return chatNode(context, 'assistant-step', anchorSeq, data, {\n visibility: settled?.interrupted === true || visible ? 'visible' : 'hidden',\n })\n },\n}\n\n/**\n * Register the Assistant lifecycle business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerAssistantConversationNode(ctx: Context): void {\n const match = assistantDefinition.match.bind(assistantDefinition)\n ctx.uiConversation.events.register({\n ...assistantDefinition,\n match: {\n 'step/start': match,\n 'assistant/live-chunk': match,\n 'assistant/message': match,\n 'llm/retry': match,\n },\n })\n}\n","import type {\n AssistantBlock, AssistantMessageNode, CommandNode, CompactionSummaryNode,\n ConversationLocation, ConversationViewNode, ModelRetryNode, RunningToolCall,\n ToolCallBlock,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatGroupTree } from './group-tree.ts'\n\n/** Final Chat render unit produced by a Chat business Definition. */\nexport interface ChatConversationViewNode extends ConversationViewNode {\n readonly target: 'chat'\n readonly anchorSeq: number\n readonly location: ConversationLocation\n readonly visibility: 'visible' | 'hidden'\n /**\n * Group-tree position, visible or hidden; absence joins the surrounding step\n * run. An `exchange` Node's Turn and every later Turn before the next opening\n * Turn form one exchange; the latest loaded exchange starts at the last loaded\n * opening Turn, or at the first loaded Turn when none is loaded.\n */\n readonly groupTree?: ChatGroupTree | undefined\n}\n\n/** Merge-extensible payload registry keyed by final Chat renderer kind. */\nexport interface ChatNodeDataMap {}\n\n/** Renderer kinds contributed by the currently installed Chat business modules. */\nexport type ChatNodeKind = Extract<keyof ChatNodeDataMap, string>\n\n/** Final Chat Node narrowed to one registered renderer kind and payload. */\nexport type ChatNode<Kind extends ChatNodeKind = ChatNodeKind> = {\n [RegisteredKind in Kind]: ChatConversationViewNode & {\n readonly kind: RegisteredKind\n readonly data: ChatNodeDataMap[RegisteredKind]\n }\n}[Kind]\n\n/** Final Assistant row payload shared by streaming and settled states. */\nexport interface AssistantChatData {\n readonly status: 'running' | 'settled' | 'interrupted'\n readonly turn: number\n readonly step: number\n readonly blocks: readonly AssistantBlock[]\n readonly time: number\n readonly usage?: unknown\n readonly finalNode?: AssistantMessageNode\n}\n\n/** Settled or interrupted Assistant payload with its durable presentation node. */\nexport type FinalAssistantChatData = AssistantChatData & {\n readonly finalNode: AssistantMessageNode\n}\n\n/** Root Tool row payload; the root lifecycle owns all recursive subcalls. */\nexport interface ToolChatData {\n readonly root: ToolCallBlock\n}\n\n/** One manual command and its correlated compaction transaction. */\nexport interface ManualCompactionChatData {\n readonly command: CommandNode\n readonly compaction: CompactionSummaryNode | null\n}\n\n/** One durable retry chain rendered as a single row. */\nexport interface RetryChatData {\n readonly attempts: readonly ModelRetryNode[]\n readonly current: ModelRetryNode\n}\n\n/** One provider/model route that contributed a billed request attempt. */\nexport interface TurnTokenUsageRoute {\n readonly provider: string\n readonly model: string\n}\n\n/** Exact provider-reported token accounting for every attempt in one completed Turn. */\nexport interface TurnTokenUsage {\n /** Sum of uncached prompt input across all attempts. */\n readonly uncachedInputTokens: number\n readonly outputTokens: number\n /** Exact aggregate prompt plus output total across all attempts. */\n readonly totalTokens: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheReadTokens?: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheWriteTokens?: number\n /** Output subset, present only when every attempt reported it. */\n readonly reasoningTokens?: number\n /** Present only when every billed attempt has provider/model attribution. */\n readonly routes?: readonly TurnTokenUsageRoute[]\n}\n\n/** Turn-local footer row that owns actions and optional feature contributions. */\nexport interface TurnTailChatData {\n readonly turn: number\n readonly seq: number\n readonly time: number\n /** Last finalized content-bearing Assistant in this Turn. */\n readonly closing: FinalAssistantChatData | null\n /** Whether non-rendered later evidence makes the closing seq non-tail. */\n readonly branchUnavailable: boolean\n /** Exact per-Turn accounting; absent when the loaded evidence is incomplete. */\n readonly tokenUsage?: TurnTokenUsage\n}\n\n/** Turn-level process disclosure projected before the finalized answer. */\nexport interface TurnProcessChatData {\n readonly turn: number\n readonly controlAnchorSeq: number\n readonly processStartSeq: number\n readonly answerAnchorSeq: number | null\n readonly answerStep: number | null\n readonly inlineReasoning: boolean\n readonly messageCount: number\n readonly toolCallCount: number\n readonly subagentCount: number\n}\n\n/**\n * Test whether a Tool root has settled.\n * @param block - Tool root lifecycle value.\n * @returns whether the root carries its final result.\n */\nexport function isSettledTool(block: ToolCallBlock): block is Extract<ToolCallBlock, { kind: 'tool-result' }> {\n return 'kind' in block\n}\n\n/**\n * Test whether a Tool root is still running.\n * @param block - Tool root lifecycle value.\n * @returns whether the root lacks a final result.\n */\nexport function isRunningTool(block: ToolCallBlock): block is RunningToolCall {\n return !isSettledTool(block)\n}\n","/** Chat-only row visibility; durable events and trajectory inspection remain intact. */\nimport type { ChatNode } from './chat-nodes.ts'\n\n/**\n * Exclude system prompts, permission commands, and normal Team toggle receipts.\n * Failed Team toggles remain visible.\n * @param node - projected Chat node.\n * @returns whether the node contributes a visible Chat row.\n */\nexport function isVisibleChatNode(node: ChatNode): boolean {\n if (node.kind === 'command') {\n if (node.data.name === 'permission') return false\n if (node.data.name === 'team' && node.data.outcome?.kind !== 'error') {\n const selection = node.data.args?.trim()\n if (selection === 'on' || selection === 'off') return false\n }\n }\n return node.visibility === 'visible'\n && node.kind !== 'system-prompt'\n}\n","import type { ChatConversationViewNode } from '../contract/chat-nodes.ts'\nimport { isAtOrOutside, type ChatGroupTree } from '../contract/group-tree.ts'\nimport { locationCoordinates } from './common.ts'\n\nconst NO_TURNS: readonly number[] = []\n\n/**\n * Loaded Turns split into consecutive segments at the Turns holding a Node at\n * one group-tree position, visible or hidden. The latest segment starts at the\n * last such Turn, or at the first loaded Turn when none is loaded. Node changes\n * update per-Turn counts without scanning the loaded Nodes; `settle` returns at\n * once while the start holds and otherwise reads loaded Turns only from the\n * earlier of the previous and new starts.\n */\nexport class GroupTreeSegments {\n /** Opening Node count by owning Turn. */\n private readonly openings = new Map<number, number>()\n private latestOpening: number | undefined\n private latestStart: number | undefined\n\n /** @param position - group-tree position whose Nodes open a segment. */\n constructor(private readonly position: ChatGroupTree) {}\n\n /**\n * Account one Node change.\n * @param previous - replaced Node; absent for an addition.\n * @param next - replacing Node; absent for a removal.\n */\n track(previous: ChatConversationViewNode | undefined, next: ChatConversationViewNode | undefined): void {\n const before = this.openingTurn(previous)\n const after = this.openingTurn(next)\n if (before === after) return\n if (before !== undefined && this.adjust(before, -1) === 0 && before === this.latestOpening) {\n this.latestOpening = this.lastOpeningTurn()\n }\n if (after !== undefined) {\n this.adjust(after, 1)\n if (this.latestOpening === undefined || after > this.latestOpening) this.latestOpening = after\n }\n }\n\n /**\n * Test latest-segment membership as of the last `settle`.\n * @param turn - owning Turn, when resolved.\n * @returns whether the Turn belongs to the latest segment.\n */\n inLatest(turn: number | undefined): boolean {\n return turn !== undefined && this.latestStart !== undefined && turn >= this.latestStart\n }\n\n /**\n * Move the latest segment start for the currently loaded Turns.\n * @param turnOrder - loaded Turns in ascending timeline order.\n * @returns loaded Turns that entered or left the latest segment, in ascending order.\n */\n settle(turnOrder: readonly number[]): readonly number[] {\n const previous = this.latestStart\n const start = this.latestOpening ?? turnOrder[0]\n if (start === previous) return NO_TURNS\n this.latestStart = start\n const bounded = previous !== undefined && start !== undefined\n const low = bounded ? Math.min(previous, start) : Number.NEGATIVE_INFINITY\n const high = bounded ? Math.max(previous, start) : Number.POSITIVE_INFINITY\n const changed: number[] = []\n for (const turn of turnOrder.slice(turnOrder.findLastIndex(turn => turn < low) + 1)) {\n if (turn >= high) break\n changed.push(turn)\n }\n return changed\n }\n\n private openingTurn(node: ChatConversationViewNode | undefined): number | undefined {\n return node !== undefined && isAtOrOutside(node, this.position) ? locationCoordinates(node.location).turn : undefined\n }\n\n private lastOpeningTurn(): number | undefined {\n let last: number | undefined\n for (const turn of this.openings.keys()) {\n if (last === undefined || turn > last) last = turn\n }\n return last\n }\n\n /** @returns the Turn's opening count after the change; zero removes the Turn. */\n private adjust(turn: number, delta: number): number {\n const next = (this.openings.get(turn) ?? 0) + delta\n if (next > 0) this.openings.set(turn, next)\n else this.openings.delete(turn)\n return next\n }\n}\n","import { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type { ChatLocationNodeIndex, ChatNodeStore, TurnNavigationItem } from '../contract/snapshot.ts'\n\n/**\n * Preview budgets, sized to the rail card's clamps (one prompt line, up to\n * three response lines) and mirrored by the turnOutline projection so a turn\n * shows the same words before and after its events load. Anything past a\n * budget is invisible; copying whole transcripts into navigation state would\n * otherwise grow with the loaded window on every structural update.\n */\nconst PROMPT_PREVIEW_LIMIT = 50\nconst RESPONSE_PREVIEW_LIMIT = 120\n\n/** Join rendered text, collapse whitespace, and cap at `limit` with a trailing ellipsis when clipped. */\n// Deliberate mirror of the turnOutline projection's preview(): the wire\n// boundary forbids sharing code with the host package.\n/* jscpd:ignore-start */\nfunction preview(parts: Iterable<string>, limit: number): string {\n let text = ''\n let unread = false\n for (const part of parts) {\n if (text.length >= limit * 2) {\n unread = true\n break\n }\n // Per-part bound: this runs on every structural rail update, so one huge\n // text block must not be concatenated (and regex-normalized) whole for a\n // preview this short.\n const clipped = part.length > limit * 2\n const chunk = clipped ? part.slice(0, limit * 2) : part\n text += text === '' ? chunk : ` ${chunk}`\n if (clipped) {\n unread = true\n break\n }\n }\n const normalized = text.replace(/\\s+/g, ' ').trim()\n if (normalized.length > limit - 1) return `${normalized.slice(0, limit - 1).trimEnd()}…`\n return unread ? `${normalized}…` : normalized\n}\n/* jscpd:ignore-end */\n\nfunction promptText(node: ChatNode): string {\n if (node.kind !== 'user') return ''\n return preview(node.data.content.flatMap(block => block.type === 'text' ? [block.text] : []), PROMPT_PREVIEW_LIMIT)\n}\n\nfunction responseText(node: ChatNode): string {\n if (node.kind !== 'assistant-step') return ''\n return preview(\n node.data.blocks.flatMap(block => block.kind === 'text' ? [block.text] : []),\n RESPONSE_PREVIEW_LIMIT,\n )\n}\n\n/**\n * Whether two items carry the same rail state, so the reader can keep its array.\n * @param left - previously published item, when the Turn had one.\n * @param right - freshly derived item, when the Turn still has one.\n * @returns whether both sides describe the same mark.\n */\nexport function sameTurnNavigationItem(\n left: TurnNavigationItem | undefined,\n right: TurnNavigationItem | undefined,\n): boolean {\n if (left === undefined || right === undefined) return left === right\n return left.turn === right.turn && left.anchorKey === right.anchorKey\n && left.prompt === right.prompt && left.response === right.response\n}\n\n/**\n * Project one loaded Turn into its rail item.\n * @param turn - Turn number the item addresses.\n * @param locations - live Location index supplying the Turn's node keys.\n * @param nodes - live Chat node store.\n * @returns the item, or undefined when the Turn has no visible loaded node.\n */\nexport function turnNavigationItem(\n turn: number,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n): TurnNavigationItem | undefined {\n const loaded = locations.getTurn(turn)\n .map(key => nodes.get(key))\n .filter((node): node is ChatNode => node !== undefined && isVisibleChatNode(node as ChatNode))\n const user = loaded.find(node => node.kind === 'user')\n const anchor = user ?? loaded[0]\n if (anchor === undefined) return undefined\n const response = loaded.findLast(node => responseText(node) !== '')\n return {\n turn,\n anchorKey: anchor.key,\n prompt: user === undefined ? '' : promptText(user),\n response: response === undefined ? '' : responseText(response),\n }\n}\n","import { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport type {\n ChatLocationNodeIndex, ChatNodeStore, ChatTurnProcessPresentation,\n} from '../contract/snapshot.ts'\nimport { isAtOrOutside } from '../contract/group-tree.ts'\n\nfunction nodeTurn(node: ChatNode | undefined): number | undefined {\n const location = node?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn.turn : undefined\n}\n\nfunction samePresentation(\n left: ChatTurnProcessPresentation | undefined,\n right: ChatTurnProcessPresentation | undefined,\n): boolean {\n return left === right || (left !== undefined && right !== undefined\n && left.spec === right.spec\n && left.turn === right.turn\n && left.turnStarted === right.turnStarted\n && left.turnClosed === right.turnClosed\n && left.hasExternalProcess === right.hasExternalProcess\n && left.hasNonReplyProcess === right.hasNonReplyProcess\n && left.hasInterleavedInput === right.hasInterleavedInput)\n}\n\nfunction derivePresentation(\n turn: number,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n): ChatTurnProcessPresentation | undefined {\n const keys = locations.getTurn(turn)\n const control = keys\n .map(key => nodes.get(key) as ChatNode | undefined)\n .find((node): node is ChatNode<'turn-process'> => node?.kind === 'turn-process')\n if (control === undefined) return undefined\n\n const spec = control.data\n const location = control.location\n if (location.kind !== 'turn' && location.kind !== 'step') return undefined\n let openingHumanAnchor: number | undefined\n for (const key of keys) {\n const node = nodes.get(key) as ChatNode | undefined\n if (node !== undefined && isAtOrOutside(node, 'input')\n && (spec.controlAnchorSeq === location.turn.start?.seq || node.anchorSeq < spec.controlAnchorSeq)) {\n openingHumanAnchor = Math.max(openingHumanAnchor ?? node.anchorSeq, node.anchorSeq)\n }\n }\n\n let hasExternalProcess = false\n let hasNonReplyProcess = false\n let hasInterleavedInput = false\n for (const key of keys) {\n const node = nodes.get(key) as ChatNode | undefined\n if (node === undefined || !isVisibleChatNode(node) || node.kind === 'turn-process') continue\n if (isAtOrOutside(node, 'input')\n && (openingHumanAnchor === undefined || node.anchorSeq > openingHumanAnchor)) {\n hasInterleavedInput = true\n }\n if (isAtOrOutside(node, 'turn')\n || node.anchorSeq < spec.processStartSeq\n || (spec.answerAnchorSeq !== null && node.anchorSeq >= spec.answerAnchorSeq)) continue\n if (node.kind !== 'assistant-step' || spec.answerStep === null || node.data.step !== spec.answerStep) {\n hasExternalProcess = true\n // When every reply stays visible, another Step's reply folds only its reasoning.\n if (node.kind !== 'assistant-step'\n || node.data.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '')) {\n hasNonReplyProcess = true\n }\n }\n }\n return {\n turn,\n spec,\n turnStarted: location.turn.start !== undefined,\n turnClosed: location.turn.status === 'closed',\n hasExternalProcess,\n hasNonReplyProcess,\n hasInterleavedInput,\n }\n}\n\n/** Mutable projection of cross-Node process layout facts by Turn. */\nexport class ChatTurnProcessProjector {\n private presentations = new Map<number, ChatTurnProcessPresentation>()\n\n /**\n * Read the retained process presentation for a Node's Turn.\n * @param node - Current Chat Node.\n * @returns The Turn's process presentation, when present.\n */\n get(node: ChatNode | undefined): ChatTurnProcessPresentation | undefined {\n const turn = nodeTurn(node)\n return turn === undefined ? undefined : this.presentations.get(turn)\n }\n\n /**\n * Replace every projected Turn.\n * @param order - visible Chat Node order.\n * @param locations - current Chat Location index.\n * @param nodes - current Chat Node store.\n * @returns Turns whose process presentation changed.\n */\n replace(\n order: readonly string[],\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): ReadonlySet<number> {\n const turns = new Set<number>()\n for (const key of order) {\n const turn = nodeTurn(nodes.get(key) as ChatNode | undefined)\n if (turn !== undefined) turns.add(turn)\n }\n const changed = new Set<number>()\n for (const turn of new Set([...this.presentations.keys(), ...turns])) {\n if (this.set(turn, turns.has(turn) ? derivePresentation(turn, locations, nodes) : undefined)) {\n changed.add(turn)\n }\n }\n return changed\n }\n\n /**\n * Recompute selected Turns after incremental Node changes.\n * @param turns - affected Turn numbers.\n * @param locations - current Chat Location index.\n * @param nodes - current Chat Node store.\n * @returns Turns whose process presentation changed.\n */\n update(\n turns: ReadonlySet<number>,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): ReadonlySet<number> {\n const changed = new Set<number>()\n for (const turn of turns) {\n if (this.set(turn, derivePresentation(turn, locations, nodes))) changed.add(turn)\n }\n return changed\n }\n\n private set(turn: number, next: ChatTurnProcessPresentation | undefined): boolean {\n const current = this.presentations.get(turn)\n if (samePresentation(current, next)) return false\n if (next === undefined) this.presentations.delete(turn)\n else this.presentations.set(turn, next)\n return true\n }\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport { notifySubscribers, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type {\n ConversationLocation, ConversationNode, ConversationTimelineSnapshot, ConversationViewBuilder,\n ConversationViewDefinition, ConversationGroupInput, GroupNodePosition, NodeChange, NodeKey, PartialAssistant, RunningToolCall,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNode, ChatNodeDataMap, ChatNodeKind } from '../contract/chat-nodes.ts'\nimport { isRunningTool } from '../contract/chat-nodes.ts'\nimport { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport type {\n ChatLocationNodeIndex, ChatNodeProcessSource, ChatNodeSource, ChatNodeStore, ChatSnapshot,\n ChatTurnNavigationIndex, ChatTurnProcessPresentation, LegacyConversationSlice, TurnNavigationItem,\n} from '../contract/snapshot.ts'\nimport { isAtOrOutside } from '../contract/group-tree.ts'\nimport { locationCoordinates } from './common.ts'\nimport { sessionRecallLabels, skillInvocationName } from './event-projection.ts'\nimport { GroupTreeSegments } from './group-tree-segments.ts'\nimport { sameTurnNavigationItem, turnNavigationItem } from './turn-navigation.ts'\nimport { ChatTurnProcessProjector } from './turn-process-presentation.ts'\n\nconst EMPTY_KEYS: readonly string[] = []\nconst EMPTY_TURNS: readonly number[] = []\nconst EMPTY_ITEMS: readonly TurnNavigationItem[] = []\nconst EMPTY_LIST: readonly never[] = []\n\nfunction sameReferences<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction cachedSource<Key, Source>(\n sources: Map<Key, Source>,\n key: Key,\n create: () => Source,\n): Source {\n let source = sources.get(key)\n if (source === undefined) {\n source = create()\n sources.set(key, source)\n }\n return source\n}\n\n/* jscpd:ignore-start -- Chat Node sources keep publication state inside the keyed Chat store. */\nclass MutableChatSource<Value> {\n private readonly listeners = new Set<() => void>()\n private published: Value\n\n constructor(\n private readonly read: () => Value,\n private readonly label: string,\n ) {\n this.published = read()\n }\n\n readonly getSnapshot = (): Value => this.read()\n\n readonly subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener)\n return () => { this.listeners.delete(listener) }\n }\n\n publish(): void {\n const next = this.getSnapshot()\n if (this.published === next) return\n this.published = next\n notifySubscribers(this.listeners, this.label)\n }\n}\n/* jscpd:ignore-end */\n\n/** Membership is indexed on write; ordered arrays are materialized only for observed collections. */\nclass TurnKindNodes {\n private readonly nodes = new Map<string, ChatConversationViewNode>()\n private current: readonly unknown[] = EMPTY_LIST\n private dirty = false\n private observable: MutableChatSource<readonly unknown[]> | undefined\n\n source(): ObservableSnapshot<readonly unknown[]> {\n return this.observable ??= new MutableChatSource(() => this.read(), '[ui-chat] turn kind nodes')\n }\n\n set(node: ChatConversationViewNode): void {\n const previous = this.nodes.get(node.key)\n this.nodes.set(node.key, node)\n if (previous !== undefined && previous.data === node.data && previous.anchorSeq === node.anchorSeq) return\n this.dirty = true\n }\n\n delete(key: string): void {\n this.nodes.delete(key)\n this.dirty = true\n }\n\n publish(): void {\n this.observable?.publish()\n }\n\n private read(): readonly unknown[] {\n if (this.dirty) {\n this.current = [...this.nodes.values()].sort((a, b) => a.anchorSeq - b.anchorSeq).map(node => node.data)\n this.dirty = false\n }\n return this.current\n }\n}\n\nclass MutableChatNodeStore implements ChatNodeStore {\n private readonly byKey = new Map<string, ChatConversationViewNode>()\n private readonly turnProcesses = new ChatTurnProcessProjector()\n private readonly sources = new Map<string, MutableChatSource<ChatConversationViewNode | undefined>>()\n private readonly processSources = new Map<string, MutableChatSource<ChatTurnProcessPresentation | undefined>>()\n private readonly bottomSources = new Map<string, MutableChatSource<boolean>>()\n /** Bottom membership: the latest loaded exchange. */\n private readonly exchanges = new GroupTreeSegments('exchange')\n private readonly dirtyKeys = new Set<string>()\n private readonly dirtyBottomKeys = new Set<string>()\n private readonly dirtyProcessKeys = new Set<string>()\n private readonly turnKinds = new Map<number, Map<string, TurnKindNodes>>()\n private readonly dirtyTurnKinds = new Set<TurnKindNodes>()\n private valuesCache: readonly ChatConversationViewNode[] = EMPTY_LIST\n private valuesDirty = false\n\n get(key: string): ChatConversationViewNode | undefined {\n return this.byKey.get(key)\n }\n\n source(key: string): ChatNodeSource {\n return cachedSource(this.sources, key, () => new MutableChatSource(\n () => this.get(key),\n `[ui-chat] node source ${key}`,\n ))\n }\n\n bottomSource(key: string): ObservableSnapshot<boolean> {\n return cachedSource(this.bottomSources, key, () => new MutableChatSource(() => {\n const node = this.get(key) as ChatNode | undefined\n return node !== undefined && isVisibleChatNode(node)\n && this.exchanges.inLatest(locationCoordinates(node.location).turn)\n }, `[ui-chat] node bottom source ${key}`))\n }\n\n /**\n * Settle the latest exchange for the loaded Turns and mark the Nodes of\n * Turns that entered or left it.\n * @param turnOrder - loaded Turns in ascending timeline order.\n * @param locations - current Chat Location index.\n */\n settleBottom(turnOrder: readonly number[], locations: ChatLocationNodeIndex): void {\n for (const turn of this.exchanges.settle(turnOrder)) {\n for (const key of locations.getTurn(turn)) this.dirtyBottomKeys.add(key)\n }\n }\n\n turnDataSource<Kind extends ChatNodeKind>(turn: number, kind: Kind): ObservableSnapshot<readonly ChatNodeDataMap[Kind][]> {\n return this.turnKind(turn, kind).source() as ObservableSnapshot<readonly ChatNodeDataMap[Kind][]>\n }\n\n private turnKind(turn: number, kind: string): TurnKindNodes {\n const kinds = cachedSource(this.turnKinds, turn, () => new Map<string, TurnKindNodes>())\n return cachedSource(kinds, kind, () => new TurnKindNodes())\n }\n\n private updateTurnKind(previous: ChatConversationViewNode | undefined, next: ChatConversationViewNode | undefined): void {\n const before = previous === undefined ? undefined : locationCoordinates(previous.location).turn\n const after = next === undefined ? undefined : locationCoordinates(next.location).turn\n if (previous !== undefined && before !== undefined && (before !== after || previous.kind !== next?.kind)) {\n const collection = this.turnKind(before, previous.kind)\n collection.delete(previous.key)\n this.dirtyTurnKinds.add(collection)\n }\n if (next !== undefined && after !== undefined) {\n const collection = this.turnKind(after, next.kind)\n collection.set(next)\n this.dirtyTurnKinds.add(collection)\n }\n }\n\n processSource(key: string): ChatNodeProcessSource {\n return cachedSource(this.processSources, key, () => new MutableChatSource(\n () => this.process(key),\n `[ui-chat] node process source ${key}`,\n ))\n }\n\n process(key: string): ChatTurnProcessPresentation | undefined {\n return this.turnProcesses.get(this.get(key) as ChatNode | undefined)\n }\n\n values(): readonly ChatConversationViewNode[] {\n if (this.valuesDirty) {\n this.valuesCache = [...this.byKey.values()]\n this.valuesDirty = false\n }\n return this.valuesCache\n }\n\n replace(nodes: readonly ChatConversationViewNode[]): void {\n const previous = new Map(this.byKey)\n this.byKey.clear()\n for (const node of nodes) {\n this.byKey.set(node.key, node)\n if (previous.get(node.key) !== node) {\n this.updateTurnKind(previous.get(node.key), node)\n this.exchanges.track(previous.get(node.key), node)\n this.dirtyKeys.add(node.key)\n this.dirtyProcessKeys.add(node.key)\n }\n previous.delete(node.key)\n }\n for (const key of previous.keys()) {\n this.updateTurnKind(previous.get(key), undefined)\n this.exchanges.track(previous.get(key), undefined)\n this.dirtyKeys.add(key)\n this.dirtyProcessKeys.add(key)\n }\n this.valuesCache = [...this.byKey.values()]\n this.valuesDirty = false\n }\n\n upsert(nodes: readonly ChatConversationViewNode[]): void {\n let changed = false\n for (const node of nodes) {\n if (this.byKey.get(node.key) === node) continue\n this.updateTurnKind(this.byKey.get(node.key), node)\n this.exchanges.track(this.byKey.get(node.key), node)\n this.byKey.set(node.key, node)\n this.dirtyKeys.add(node.key)\n this.dirtyProcessKeys.add(node.key)\n changed = true\n }\n if (changed) this.valuesDirty = true\n }\n\n touchProcesses(turns: ReadonlySet<number>, locations: ChatLocationNodeIndex): void {\n for (const turn of turns) {\n for (const key of locations.getTurn(turn)) this.dirtyProcessKeys.add(key)\n }\n }\n\n replaceProcesses(order: readonly string[], locations: ChatLocationNodeIndex): void {\n this.touchProcesses(this.turnProcesses.replace(order, locations, this), locations)\n }\n\n updateProcesses(turns: ReadonlySet<number>, locations: ChatLocationNodeIndex): void {\n this.touchProcesses(this.turnProcesses.update(turns, locations, this), locations)\n }\n\n publish(): void {\n const dirty = [...this.dirtyKeys]\n const dirtyBottom = new Set([...this.dirtyBottomKeys, ...dirty])\n const dirtyProcesses = [...this.dirtyProcessKeys]\n const dirtyTurnKinds = [...this.dirtyTurnKinds]\n this.dirtyKeys.clear()\n this.dirtyBottomKeys.clear()\n this.dirtyProcessKeys.clear()\n this.dirtyTurnKinds.clear()\n for (const key of dirty) this.sources.get(key)?.publish()\n for (const key of dirtyBottom) this.bottomSources.get(key)?.publish()\n for (const key of dirtyProcesses) this.processSources.get(key)?.publish()\n for (const collection of dirtyTurnKinds) collection.publish()\n }\n}\n\nclass MutableChatLocationIndex implements ChatLocationNodeIndex {\n private turns = new Map<number, readonly string[]>()\n private steps = new Map<string, readonly string[]>()\n private positions = new Map<string, GroupNodePosition>()\n\n getTurn(turn: number): readonly string[] {\n return this.turns.get(turn) ?? EMPTY_KEYS\n }\n\n getStep(turn: number, step: number): readonly string[] {\n return this.steps.get(stepKey(turn, step)) ?? EMPTY_KEYS\n }\n\n getPosition(key: string): GroupNodePosition | undefined {\n return this.positions.get(key)\n }\n\n rebuild(order: readonly string[], store: ChatNodeStore): readonly number[] {\n const turns = new Map<number, string[]>()\n const steps = new Map<string, string[]>()\n const positions = new Map<string, GroupNodePosition>()\n const changedTurns = new Set<number>()\n for (const [index, key] of order.entries()) {\n const location = store.get(key)?.location\n if (location === undefined) continue\n const coordinates = locationCoordinates(location)\n const previous = this.positions.get(key)\n const position: GroupNodePosition = {\n turn: coordinates.turn,\n previous: order[index - 1] as NodeKey | undefined,\n next: order[index + 1] as NodeKey | undefined,\n }\n const unchanged = previous !== undefined && previous.turn === position.turn\n && previous.previous === position.previous && previous.next === position.next\n positions.set(key, unchanged ? previous : position)\n if (!unchanged) {\n if (previous?.turn !== undefined) changedTurns.add(previous.turn)\n if (position.turn !== undefined) changedTurns.add(position.turn)\n }\n if (coordinates.turn === undefined) continue\n const turnKeys = turns.get(coordinates.turn) ?? []\n turnKeys.push(key)\n turns.set(coordinates.turn, turnKeys)\n if (coordinates.step === undefined) continue\n const step = stepKey(coordinates.turn, coordinates.step)\n const stepKeys = steps.get(step) ?? []\n stepKeys.push(key)\n steps.set(step, stepKeys)\n }\n for (const [key, position] of this.positions) {\n if (!positions.has(key) && position.turn !== undefined) changedTurns.add(position.turn)\n }\n this.positions = positions\n this.turns = updateIndex(this.turns, turns)\n this.steps = updateIndex(this.steps, steps)\n return [...changedTurns]\n }\n\n /** Invalidate aggregate readers when member data changes without moving. */\n touch(nodes: readonly ChatConversationViewNode[]): void {\n const turns = new Set<number>()\n const steps = new Set<string>()\n for (const node of nodes) {\n const coordinates = locationCoordinates(node.location)\n if (coordinates.turn === undefined || !this.turns.get(coordinates.turn)?.includes(node.key)) continue\n turns.add(coordinates.turn)\n if (coordinates.step !== undefined) steps.add(stepKey(coordinates.turn, coordinates.step))\n }\n for (const turn of turns) {\n const keys = this.turns.get(turn)\n if (keys === undefined) continue\n this.turns.set(turn, [...keys])\n }\n for (const step of steps) {\n const keys = this.steps.get(step)\n if (keys === undefined) continue\n this.steps.set(step, [...keys])\n }\n }\n}\n\nfunction updateIndex<Key>(\n previous: ReadonlyMap<Key, readonly string[]>,\n nextMutable: ReadonlyMap<Key, string[]>,\n): Map<Key, readonly string[]> {\n const next = new Map<Key, readonly string[]>()\n const keys = new Set([...previous.keys(), ...nextMutable.keys()])\n for (const key of keys) {\n const before = previous.get(key) ?? EMPTY_KEYS\n const candidate = nextMutable.get(key) ?? EMPTY_KEYS\n const value = sameReferences(before, candidate) ? before : candidate\n if (candidate.length > 0) next.set(key, value)\n }\n return next\n}\n\n/**\n * Loaded-Turn rail projection accumulated alongside the node store: a\n * structural change re-derives the Turn set, a content-only upsert re-derives\n * only the Turns whose nodes moved, and the published array keeps its identity\n * until an item actually changes. Renderers therefore consume final Turn data\n * instead of scanning the loaded window per frame.\n */\nclass MutableTurnNavigationIndex implements ChatTurnNavigationIndex {\n private current: readonly TurnNavigationItem[] = EMPTY_ITEMS\n private byTurn = new Map<number, TurnNavigationItem>()\n\n items(): readonly TurnNavigationItem[] {\n return this.current\n }\n\n /** Re-derive the whole Turn set; runs only when the loaded structure moves. */\n rebuild(\n timeline: ConversationTimelineSnapshot,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): void {\n const next: TurnNavigationItem[] = []\n const byTurn = new Map<number, TurnNavigationItem>()\n for (const turn of timeline.turnOrder) {\n const derived = turnNavigationItem(turn, locations, nodes)\n if (derived === undefined) continue\n const previous = this.byTurn.get(turn)\n const item = previous !== undefined && sameTurnNavigationItem(previous, derived) ? previous : derived\n next.push(item)\n byTurn.set(turn, item)\n }\n this.byTurn = byTurn\n const unchanged = next.length === this.current.length\n && next.every((item, index) => item === this.current[index])\n if (!unchanged) this.current = next\n }\n\n /** Re-derive only the Turns a content-only upsert touched. */\n touch(\n turns: ReadonlySet<number>,\n locations: ChatLocationNodeIndex,\n nodes: ChatNodeStore,\n ): void {\n if (turns.size === 0) return\n const next = this.current.map((item) => {\n if (!turns.has(item.turn)) return item\n const derived = turnNavigationItem(item.turn, locations, nodes)\n if (derived === undefined || sameTurnNavigationItem(item, derived)) return item\n this.byTurn.set(item.turn, derived)\n return derived\n })\n if (next.some((item, index) => item !== this.current[index])) this.current = next\n }\n}\n\nfunction stepKey(turn: number, step: number): string {\n return `${turn}:${step}`\n}\n\nfunction locationTurnStatus(location: ConversationLocation): string | undefined {\n return location.kind === 'turn' || location.kind === 'step' ? location.turn.status : undefined\n}\n\nfunction processPresentationInputChanged(\n previous: ChatNode | undefined,\n next: ChatNode,\n structural: boolean,\n): boolean {\n if (structural || previous === undefined) return true\n if (locationTurnStatus(previous.location) !== locationTurnStatus(next.location)) return true\n if (previous.kind === 'turn-process' && next.kind === 'turn-process') {\n return previous.data !== next.data\n }\n return previous.kind === 'assistant-step'\n && next.kind === 'assistant-step'\n && previous.data.step !== next.data.step\n}\n\ninterface TurnProcessPresentation {\n readonly control?: ChatNode<'turn-process'>\n readonly openingInputAnchor?: number\n readonly earliestProcessAnchor?: number\n}\n\nfunction turnProcessPresentations(\n nodes: readonly ChatConversationViewNode[],\n): ReadonlyMap<number, TurnProcessPresentation> {\n const presentations = new Map<number, TurnProcessPresentation>()\n for (const raw of nodes) {\n const node = raw as ChatNode\n if (node.kind === 'turn-process') {\n presentations.set(node.data.turn, { ...presentations.get(node.data.turn), control: node })\n }\n }\n for (const raw of nodes) {\n const node = raw as ChatNode\n const location = node.location\n if (location.kind !== 'turn' && location.kind !== 'step') continue\n const current: TurnProcessPresentation = presentations.get(location.turn.turn) ?? {}\n const controlAnchor = current.control?.data.controlAnchorSeq\n if (isAtOrOutside(node, 'input')\n && controlAnchor !== undefined\n && (controlAnchor === location.turn.start?.seq || node.anchorSeq < controlAnchor)) {\n presentations.set(location.turn.turn, {\n ...current,\n openingInputAnchor: Math.max(current.openingInputAnchor ?? node.anchorSeq, node.anchorSeq),\n })\n continue\n }\n if (isAtOrOutside(node, 'turn')) continue\n presentations.set(location.turn.turn, {\n ...current,\n earliestProcessAnchor: Math.min(current.earliestProcessAnchor ?? node.anchorSeq, node.anchorSeq),\n })\n }\n return presentations\n}\n\ninterface PresentationPosition {\n readonly anchor: number\n readonly rank: number\n readonly originalAnchor: number\n}\n\nfunction presentationPosition(\n raw: ChatConversationViewNode,\n presentations: ReadonlyMap<number, TurnProcessPresentation>,\n): PresentationPosition {\n const node = raw as ChatNode\n const location = node.location\n if (location.kind !== 'turn' && location.kind !== 'step') {\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n }\n const presentation = presentations.get(location.turn.turn)\n if (presentation === undefined) {\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n }\n const openingInputAnchor = presentation.openingInputAnchor\n if (openingInputAnchor !== undefined\n && node.anchorSeq < openingInputAnchor\n && !isAtOrOutside(node, 'turn')) {\n return { anchor: openingInputAnchor, rank: 2, originalAnchor: node.anchorSeq }\n }\n if (presentation.control !== undefined && node.key === presentation.control.key) {\n return openingInputAnchor === undefined\n ? {\n anchor: presentation.earliestProcessAnchor ?? node.anchorSeq,\n rank: -1,\n originalAnchor: node.anchorSeq,\n }\n : { anchor: openingInputAnchor, rank: 1, originalAnchor: node.anchorSeq }\n }\n return { anchor: node.anchorSeq, rank: 0, originalAnchor: node.anchorSeq }\n}\n\n/**\n * Order visible Chat Nodes without changing existing relative order as process\n * eligibility changes. Opening input precedes process candidates, while\n * each synthetic process control sits between them.\n * @param nodes - currently materialized Chat Nodes.\n * @returns visible Nodes in presentation order.\n */\nexport function orderedVisibleChatNodes(\n nodes: readonly ChatConversationViewNode[],\n): ChatConversationViewNode[] {\n const visible = nodes.filter(node => isVisibleChatNode(node as ChatNode))\n const presentations = turnProcessPresentations(visible)\n return visible.sort((left, right) => {\n const leftPosition = presentationPosition(left, presentations)\n const rightPosition = presentationPosition(right, presentations)\n return leftPosition.anchor - rightPosition.anchor\n || leftPosition.rank - rightPosition.rank\n || leftPosition.originalAnchor - rightPosition.originalAnchor\n || left.key.localeCompare(right.key)\n })\n}\n\nfunction referenceMessageSeq(node: ChatConversationViewNode): number | undefined {\n const candidate = node as ChatNode\n return candidate.kind === 'user' || candidate.kind === 'steering'\n ? candidate.data.seq\n : undefined\n}\n\nfunction followingRecall(node: ChatConversationViewNode): {\n readonly messageSeq: number\n readonly labels: readonly string[]\n} | undefined {\n const candidate = node as ChatNode\n if (candidate.kind !== 'context') return undefined\n return {\n messageSeq: candidate.data.seq - 1,\n labels: sessionRecallLabels(candidate.data.source),\n }\n}\n\nfunction withReferenceLabels(\n node: ChatConversationViewNode,\n labels: readonly string[],\n): ChatConversationViewNode {\n const candidate = node as ChatNode\n if (candidate.kind !== 'user' && candidate.kind !== 'steering') return node\n const current = candidate.data.referenceLabels ?? EMPTY_KEYS\n const hasLabels = Object.hasOwn(candidate.data, 'referenceLabels')\n if (sameReferences(current, labels) && hasLabels === (labels.length > 0)) return node\n const data: Record<string, unknown> = { ...candidate.data }\n if (labels.length === 0) delete data.referenceLabels\n else data.referenceLabels = labels\n return { ...candidate, data }\n}\n\n/** Associates a direct message with the sourced recall event that immediately follows it. */\nclass ReferenceLabelProjector {\n private readonly messagesBySeq = new Map<number, string>()\n private readonly labelsByMessageSeq = new Map<number, readonly string[]>()\n\n replace(nodes: readonly ChatConversationViewNode[]): readonly ChatConversationViewNode[] {\n this.messagesBySeq.clear()\n this.labelsByMessageSeq.clear()\n for (const node of nodes) {\n const messageSeq = referenceMessageSeq(node)\n if (messageSeq !== undefined) this.messagesBySeq.set(messageSeq, node.key)\n const recall = followingRecall(node)\n if (recall !== undefined && recall.labels.length > 0) {\n this.labelsByMessageSeq.set(recall.messageSeq, recall.labels)\n }\n }\n return nodes.map((node) => {\n const messageSeq = referenceMessageSeq(node)\n return messageSeq === undefined\n ? node\n : withReferenceLabels(node, this.labelsByMessageSeq.get(messageSeq) ?? EMPTY_KEYS)\n })\n }\n\n apply(\n upserts: readonly ChatConversationViewNode[],\n store: ChatNodeStore,\n ): readonly ChatConversationViewNode[] {\n const byKey = new Map(upserts.map(node => [node.key, node]))\n const affected = new Set<number>()\n for (const node of upserts) {\n const messageSeq = referenceMessageSeq(node)\n if (messageSeq !== undefined) {\n this.messagesBySeq.set(messageSeq, node.key)\n affected.add(messageSeq)\n }\n const recall = followingRecall(node)\n if (recall === undefined) continue\n const current = this.labelsByMessageSeq.get(recall.messageSeq)\n if (recall.labels.length === 0) this.labelsByMessageSeq.delete(recall.messageSeq)\n else {\n this.labelsByMessageSeq.set(\n recall.messageSeq,\n current !== undefined && sameReferences(current, recall.labels) ? current : recall.labels,\n )\n }\n affected.add(recall.messageSeq)\n }\n for (const messageSeq of affected) {\n const key = this.messagesBySeq.get(messageSeq)\n if (key === undefined) continue\n const node = byKey.get(key) ?? store.get(key)\n if (node === undefined) continue\n byKey.set(key, withReferenceLabels(node, this.labelsByMessageSeq.get(messageSeq) ?? EMPTY_KEYS))\n }\n return [...byKey.values()]\n }\n}\n\nfunction withSkillNames(\n node: ChatConversationViewNode,\n names: readonly string[],\n): ChatConversationViewNode {\n const candidate = node as ChatNode\n if (candidate.kind !== 'user' && candidate.kind !== 'steering') return node\n const current = candidate.data.skillNames ?? EMPTY_KEYS\n const hasNames = Object.hasOwn(candidate.data, 'skillNames')\n if (sameReferences(current, names) && hasNames === (names.length > 0)) return node\n const data: Record<string, unknown> = { ...candidate.data }\n if (names.length === 0) delete data.skillNames\n else data.skillNames = names\n return { ...candidate, data }\n}\n\n/** What skill-name batches are made of; every other Node is transparent. */\ntype SlashEntryKind = 'message' | 'skill' | 'boundary'\n\ninterface SlashEntry {\n readonly key: string\n readonly seq: number\n readonly kind: SlashEntryKind\n /** The injected skill name of a `skill` entry. */\n readonly name: string | null\n}\n\n/**\n * Classify one Node for batching: a direct message, a `skill-invocation`\n * context, or a boundary of any other kind. A context that injects no skill\n * (workspace rules, the catalog, a recall) is transparent and yields null.\n */\nfunction slashEntryOf(node: ChatConversationViewNode): SlashEntry | null {\n const candidate = node as ChatNode\n if (candidate.kind === 'user' || candidate.kind === 'steering') {\n return { key: node.key, seq: node.anchorSeq, kind: 'message', name: null }\n }\n if (candidate.kind === 'context') {\n const name = skillInvocationName(candidate.data.source)\n return name === null ? null : { key: node.key, seq: node.anchorSeq, kind: 'skill', name }\n }\n return { key: node.key, seq: node.anchorSeq, kind: 'boundary', name: null }\n}\n\nfunction sameSlashEntry(left: SlashEntry, right: SlashEntry): boolean {\n return left.seq === right.seq && left.kind === right.kind && left.name === right.name\n}\n\n/**\n * Attaches each direct message's step-loaded skill names to its Node.\n *\n * A step's `skill-invocation` injections follow the direct messages the host\n * scanned for `/name` gestures and precede the step's first Node of any other\n * kind, so every non-message, non-context Node closes a batch. Every ended\n * Turn publishes its `turn-tail` Node on `turn/end` whatever the reason, so a\n * batch never spans Turns, and `step/start` precedes the direct message in\n * the log, so no boundary separates a message from its injections. Names\n * attach to every direct message of the batch: the bubble decorates only the\n * tokens its own text carries.\n *\n * The index holds only messages, skill injections, and boundaries, ordered by\n * `anchorSeq`. An apply re-reads just the batches around the Nodes whose\n * classification changed and never scans the store, so an assistant\n * streaming frame costs nothing here (the append hot path never scans the\n * Chat Nodes).\n */\nexport class SkillNameProjector {\n private readonly entries = new Map<string, SlashEntry>()\n /** Every indexed entry in `anchorSeq` order. */\n private sorted: SlashEntry[] = []\n\n /**\n * Rebuild the index from a whole Node set and attach names to its messages.\n * @param nodes - every materialized Chat Node, in any order.\n * @returns the same Nodes, direct messages carrying their batch's names.\n */\n replace(nodes: readonly ChatConversationViewNode[]): readonly ChatConversationViewNode[] {\n this.entries.clear()\n this.sorted = []\n for (const node of nodes) {\n const entry = slashEntryOf(node)\n if (entry === null) continue\n this.entries.set(entry.key, entry)\n this.sorted.push(entry)\n }\n this.sorted.sort((left, right) => left.seq - right.seq)\n const names = new Map<string, readonly string[]>()\n for (let index = 0; index < this.sorted.length; index++) {\n if (this.sorted[index]?.kind === 'boundary') continue\n const end = this.runEnd(index)\n this.assignRun(index, end, names)\n index = end\n }\n return nodes.map(node => withSkillNames(node, names.get(node.key) ?? EMPTY_KEYS))\n }\n\n /**\n * Fold one incremental upsert set: re-read only the batches around the\n * Nodes whose classification changed.\n * @param upserts - the changed Nodes.\n * @param store - the resident Nodes, read by key for the messages of an affected batch.\n * @returns the upserts plus any resident message whose names changed.\n */\n apply(\n upserts: readonly ChatConversationViewNode[],\n store: ChatNodeStore,\n ): readonly ChatConversationViewNode[] {\n const dirty: number[] = []\n for (const node of upserts) {\n const next = slashEntryOf(node)\n const previous = this.entries.get(node.key)\n if (previous !== undefined) {\n if (next !== null && sameSlashEntry(previous, next)) {\n // A rebuilt message Node carries Definition state only, never the\n // names a previous apply attached: re-read its batch.\n if (next.kind === 'message') dirty.push(next.seq)\n continue\n }\n this.remove(previous)\n dirty.push(previous.seq)\n }\n if (next === null) continue\n this.insert(next)\n dirty.push(next.seq)\n }\n if (dirty.length === 0) return upserts\n const names = new Map<string, readonly string[]>()\n for (const seq of dirty) this.collectAround(seq, names)\n const byKey = new Map(upserts.map(node => [node.key, node]))\n for (const [key, list] of names) {\n const node = byKey.get(key) ?? store.get(key)\n if (node === undefined) continue\n const next = withSkillNames(node, list)\n if (next !== node || byKey.has(key)) byKey.set(key, next)\n }\n return [...byKey.values()]\n }\n\n private insert(entry: SlashEntry): void {\n this.sorted.splice(this.lowerBound(entry.seq), 0, entry)\n this.entries.set(entry.key, entry)\n }\n\n private remove(entry: SlashEntry): void {\n this.sorted.splice(this.sorted.indexOf(entry), 1)\n this.entries.delete(entry.key)\n }\n\n /** First index whose seq is at least `seq`. */\n private lowerBound(seq: number): number {\n let low = 0\n let high = this.sorted.length\n while (low < high) {\n const middle = (low + high) >>> 1\n if ((this.sorted[middle]?.seq ?? Number.POSITIVE_INFINITY) < seq) low = middle + 1\n else high = middle\n }\n return low\n }\n\n /** Last index of the boundary-free run containing `index`. */\n private runEnd(index: number): number {\n let end = index\n while (end + 1 < this.sorted.length && this.sorted[end + 1]?.kind !== 'boundary') end++\n return end\n }\n\n /** First index of the boundary-free run containing `index`. */\n private runStart(index: number): number {\n let start = index\n while (start - 1 >= 0 && this.sorted[start - 1]?.kind !== 'boundary') start--\n return start\n }\n\n /** Record the names every message of the run `[start, end]` carries. */\n private assignRun(start: number, end: number, names: Map<string, readonly string[]>): void {\n const list: string[] = []\n for (let index = start; index <= end; index++) {\n const entry = this.sorted[index]\n if (entry?.kind === 'skill' && entry.name !== null && !list.includes(entry.name)) list.push(entry.name)\n }\n for (let index = start; index <= end; index++) {\n const entry = this.sorted[index]\n if (entry?.kind === 'message') names.set(entry.key, list)\n }\n }\n\n /**\n * Re-read the run(s) around one changed seq: the run holding a message or\n * skill entry, or — for a boundary, or a seq that left the index — the runs\n * on both sides of that position.\n */\n private collectAround(seq: number, names: Map<string, readonly string[]>): void {\n const at = this.lowerBound(seq)\n const here = this.sorted[at]\n if (here !== undefined && here.seq === seq && here.kind !== 'boundary') {\n this.assignRun(this.runStart(at), this.runEnd(at), names)\n return\n }\n if (at - 1 >= 0 && this.sorted[at - 1]?.kind !== 'boundary') {\n this.assignRun(this.runStart(at - 1), at - 1, names)\n }\n const right = here !== undefined && here.seq === seq ? at + 1 : at\n if (right < this.sorted.length && this.sorted[right]?.kind !== 'boundary') {\n this.assignRun(right, this.runEnd(right), names)\n }\n }\n}\n\ninterface LegacyContribution {\n readonly anchorSeq: number\n readonly nodes: readonly ConversationNode[]\n readonly partial: PartialAssistant | null\n readonly running: RunningToolCall | null\n}\n\nconst EMPTY_CONTRIBUTION: LegacyContribution = {\n anchorSeq: 0,\n nodes: EMPTY_LIST,\n partial: null,\n running: null,\n}\n\nfunction legacyContribution(raw: ChatConversationViewNode): LegacyContribution {\n const node = raw as ChatNode\n // Content-free settled Assistants remain in the finalized compatibility\n // stream so the composer stats pills keep their pre-assembly step counts;\n // hidden running attempts have no final Node to contribute.\n if (raw.visibility !== 'visible' && node.kind !== 'assistant-step') return EMPTY_CONTRIBUTION\n switch (node.kind) {\n case 'user':\n case 'steering':\n case 'context':\n case 'command':\n case 'compaction':\n case 'turn-error':\n case 'turn-max-tokens':\n case 'unknown':\n return { anchorSeq: node.anchorSeq, nodes: [node.data], partial: null, running: null }\n case 'assistant-step': {\n const data = node.data\n if (data.status === 'running') {\n if (raw.visibility !== 'visible') return EMPTY_CONTRIBUTION\n return {\n anchorSeq: node.anchorSeq,\n nodes: EMPTY_LIST,\n partial: { turn: data.turn, step: data.step, blocks: data.blocks },\n running: null,\n }\n }\n return {\n anchorSeq: node.anchorSeq,\n nodes: data.finalNode === undefined ? EMPTY_LIST : [data.finalNode],\n partial: null,\n running: null,\n }\n }\n case 'tool-call': {\n const root = node.data.root\n return isRunningTool(root)\n ? { anchorSeq: node.anchorSeq, nodes: EMPTY_LIST, partial: null, running: root }\n : { anchorSeq: node.anchorSeq, nodes: [root], partial: null, running: null }\n }\n case 'manual-compaction': {\n const data = node.data\n return {\n anchorSeq: node.anchorSeq,\n nodes: data.compaction === null ? [data.command] : [data.command, data.compaction],\n partial: null,\n running: null,\n }\n }\n case 'model-retry':\n return {\n anchorSeq: node.anchorSeq,\n nodes: node.data.attempts,\n partial: null,\n running: null,\n }\n case 'turn-tail':\n case 'system-prompt':\n // These known Chat rows intentionally make no legacy timeline contribution.\n return EMPTY_CONTRIBUTION\n default:\n return EMPTY_CONTRIBUTION\n }\n}\n\nfunction sameContribution(left: LegacyContribution | undefined, right: LegacyContribution): boolean {\n return left !== undefined\n && left.anchorSeq === right.anchorSeq\n && left.partial?.blocks === right.partial?.blocks\n && left.partial?.turn === right.partial?.turn\n && left.partial?.step === right.partial?.step\n && left.running === right.running\n && sameReferences(left.nodes, right.nodes)\n}\n\n/** Incremental compatibility projection for the composer stats pills and legacy top-level snapshot fields. */\nclass LegacySliceBuilder {\n private readonly contributions = new Map<string, LegacyContribution>()\n private readonly finalizedContributions = new Map<string, LegacyContribution>()\n private readonly runningContributions = new Map<string, LegacyContribution>()\n private readonly partialContributions = new Map<string, LegacyContribution>()\n private finalized: readonly ConversationNode[] = EMPTY_LIST\n private runningCalls: readonly RunningToolCall[] = EMPTY_LIST\n private partial: PartialAssistant | null = null\n private timeline: ConversationTimelineSnapshot | undefined\n private turnTimings: LegacyConversationSlice['turnTimings'] = new Map()\n private turnEnds: LegacyConversationSlice['turnEnds'] = new Map()\n\n replace(\n nodes: readonly ChatConversationViewNode[],\n timeline: ConversationTimelineSnapshot,\n ): LegacyConversationSlice {\n this.contributions.clear()\n this.finalizedContributions.clear()\n this.runningContributions.clear()\n this.partialContributions.clear()\n for (const node of nodes) {\n const contribution = legacyContribution(node)\n this.contributions.set(node.key, contribution)\n this.indexContribution(node.key, contribution)\n }\n this.rebuildFinalized()\n this.rebuildRunning()\n this.rebuildPartial()\n this.updateTimeline(timeline)\n return this.snapshot()\n }\n\n apply(\n upserts: readonly ChatConversationViewNode[],\n timeline: ConversationTimelineSnapshot,\n ): LegacyConversationSlice {\n let finalizedChanged = false\n let runningChanged = false\n let partialChanged = false\n for (const node of upserts) {\n const contribution = legacyContribution(node)\n const previous = this.contributions.get(node.key)\n if (sameContribution(previous, contribution)) continue\n finalizedChanged ||= finalizedContributionChanged(previous, contribution)\n runningChanged ||= runningContributionChanged(previous, contribution)\n partialChanged ||= partialContributionChanged(previous, contribution)\n this.contributions.set(node.key, contribution)\n this.indexContribution(node.key, contribution)\n }\n if (finalizedChanged) this.rebuildFinalized()\n if (runningChanged) this.rebuildRunning()\n if (partialChanged) this.rebuildPartial()\n this.updateTimeline(timeline)\n return this.snapshot()\n }\n\n private indexContribution(key: string, contribution: LegacyContribution): void {\n updateContributionIndex(this.finalizedContributions, key, contribution, contribution.nodes.length > 0)\n updateContributionIndex(this.runningContributions, key, contribution, contribution.running !== null)\n updateContributionIndex(this.partialContributions, key, contribution, contribution.partial !== null)\n }\n\n private rebuildFinalized(): void {\n const finalized = [...this.finalizedContributions.values()]\n .flatMap(value => value.nodes)\n .sort((left, right) => left.seq - right.seq)\n if (!sameReferences(this.finalized, finalized)) this.finalized = finalized\n }\n\n private rebuildRunning(): void {\n const runningCalls = [...this.runningContributions.values()]\n .sort((left, right) => left.anchorSeq - right.anchorSeq)\n .flatMap(value => value.running === null ? [] : [value.running])\n if (!sameReferences(this.runningCalls, runningCalls)) this.runningCalls = runningCalls\n }\n\n private rebuildPartial(): void {\n const partial = [...this.partialContributions.values()]\n .sort((left, right) => left.anchorSeq - right.anchorSeq)\n .findLast(value => value.partial !== null)?.partial ?? null\n if (this.partial?.blocks !== partial?.blocks\n || this.partial?.turn !== partial?.turn\n || this.partial?.step !== partial?.step) this.partial = partial\n }\n\n private updateTimeline(timeline: ConversationTimelineSnapshot): void {\n if (this.timeline === timeline) return\n this.timeline = timeline\n const turnTimings = new Map<number, { startTime: number; endTime?: number }>()\n const turnEnds = new Map<number, number>()\n for (const turn of timeline.turns.values()) {\n if (turn.start !== undefined) {\n turnTimings.set(turn.turn, {\n startTime: turn.start.time,\n ...turn.end === undefined ? {} : { endTime: turn.end.time },\n })\n }\n if (turn.end !== undefined) turnEnds.set(turn.turn, turn.end.seq)\n }\n this.turnTimings = turnTimings\n this.turnEnds = turnEnds\n }\n\n private snapshot(): LegacyConversationSlice {\n return {\n nodes: this.finalized,\n turnTimings: this.turnTimings,\n turnEnds: this.turnEnds,\n partial: this.partial,\n runningCalls: this.runningCalls,\n }\n }\n}\n\nfunction updateContributionIndex(\n index: Map<string, LegacyContribution>,\n key: string,\n contribution: LegacyContribution,\n present: boolean,\n): void {\n if (present) index.set(key, contribution)\n else index.delete(key)\n}\n\nfunction finalizedContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n const previousNodes = previous?.nodes ?? EMPTY_LIST\n return !sameReferences(previousNodes, next.nodes)\n || ((previousNodes.length > 0 || next.nodes.length > 0) && previous?.anchorSeq !== next.anchorSeq)\n}\n\nfunction runningContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n return previous?.running !== next.running\n || ((previous.running !== null || next.running !== null)\n && previous.anchorSeq !== next.anchorSeq)\n}\n\nfunction partialContributionChanged(\n previous: LegacyContribution | undefined,\n next: LegacyContribution,\n): boolean {\n return previous?.partial?.blocks !== next.partial?.blocks\n || previous?.partial?.turn !== next.partial?.turn\n || previous?.partial?.step !== next.partial?.step\n || (((previous?.partial ?? null) !== null || next.partial !== null)\n && previous?.anchorSeq !== next.anchorSeq)\n}\n\n/** Incremental keyed Chat builder registered under the `chat` target. */\nexport class ChatSnapshotBuilder implements ConversationViewBuilder<ChatConversationViewNode, ChatSnapshot> {\n private readonly store = new MutableChatNodeStore()\n private readonly locations = new MutableChatLocationIndex()\n private readonly navigation = new MutableTurnNavigationIndex()\n private readonly legacy = new LegacySliceBuilder()\n private readonly referenceLabels = new ReferenceLabelProjector()\n private readonly skillNames = new SkillNameProjector()\n private order: readonly string[] = EMPTY_KEYS\n private latestGroupInput: ConversationGroupInput<ChatConversationViewNode>\n private readonly readGroupNode = (key: NodeKey): ChatConversationViewNode | undefined => this.store.get(key)\n private readonly readGroupTurn = (turn: number): readonly NodeKey[] => this.locations.getTurn(turn) as readonly NodeKey[]\n private readonly readGroupPosition = (key: NodeKey): GroupNodePosition | undefined => this.locations.getPosition(key)\n /** Last published timeline: a Turn boundary can land without a new node. */\n private timeline: ConversationTimelineSnapshot | null = null\n readonly empty: ChatSnapshot\n\n constructor() {\n this.empty = this.snapshot({ turnOrder: EMPTY_TURNS, turns: new Map() })\n this.latestGroupInput = {\n kind: 'replace',\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: this.empty.timeline,\n }\n }\n\n replace(input: {\n readonly nodes: readonly ChatConversationViewNode[]\n readonly timeline: ConversationTimelineSnapshot\n }): ChatSnapshot {\n const nodes = this.skillNames.replace(this.referenceLabels.replace(input.nodes))\n this.store.replace(nodes)\n this.order = orderedVisibleChatNodes(nodes).map(node => node.key)\n this.locations.rebuild(this.order, this.store)\n this.store.replaceProcesses(this.order, this.locations)\n this.store.settleBottom(input.timeline.turnOrder, this.locations)\n this.navigation.rebuild(input.timeline, this.locations, this.store)\n this.timeline = input.timeline\n this.latestGroupInput = {\n kind: 'replace',\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: input.timeline,\n }\n const snapshot = this.snapshot(input.timeline, this.legacy.replace(nodes, input.timeline))\n return snapshot\n }\n\n apply(input: {\n readonly upserts: readonly ChatConversationViewNode[]\n readonly timeline: ConversationTimelineSnapshot\n readonly changedTurns?: readonly number[]\n }): ChatSnapshot {\n const upserts = this.skillNames.apply(this.referenceLabels.apply(input.upserts, this.store), this.store)\n const processTurns = new Set<number>()\n let structural = false\n const contentOnly: ChatConversationViewNode[] = []\n const changes: NodeChange<ChatConversationViewNode>[] = []\n for (const node of upserts) {\n const previous = this.store.get(node.key)\n if (previous !== node) changes.push({ previous, current: node })\n const nodeStructural = previous === undefined\n || previous.kind !== node.kind\n || previous.anchorSeq !== node.anchorSeq\n || previous.visibility !== node.visibility\n || previous.groupTree !== node.groupTree\n || locationIdentity(previous.location) !== locationIdentity(node.location)\n structural ||= nodeStructural\n if (!nodeStructural) contentOnly.push(node)\n if (processPresentationInputChanged(previous as ChatNode | undefined, node as ChatNode, nodeStructural)) {\n const previousTurn = previous === undefined ? undefined : locationCoordinates(previous.location).turn\n const nextTurn = locationCoordinates(node.location).turn\n if (previousTurn !== undefined) processTurns.add(previousTurn)\n if (nextTurn !== undefined) processTurns.add(nextTurn)\n }\n }\n this.store.upsert(upserts)\n let changedTurnOrders: readonly number[] = EMPTY_TURNS\n if (structural) {\n const next = orderedVisibleChatNodes(this.store.values()).map(node => node.key)\n this.order = sameReferences(this.order, next) ? this.order : next\n changedTurnOrders = this.locations.rebuild(this.order, this.store)\n }\n this.locations.touch(contentOnly)\n this.store.updateProcesses(processTurns, this.locations)\n this.store.settleBottom(input.timeline.turnOrder, this.locations)\n if (structural || input.timeline !== this.timeline) {\n this.navigation.rebuild(input.timeline, this.locations, this.store)\n } else {\n this.navigation.touch(turnsOf(contentOnly), this.locations, this.store)\n }\n this.timeline = input.timeline\n this.latestGroupInput = {\n kind: 'apply',\n changes,\n order: this.order as readonly NodeKey[],\n readNode: this.readGroupNode,\n readTurn: this.readGroupTurn,\n readPosition: this.readGroupPosition,\n timeline: input.timeline,\n changedTurns: input.changedTurns ?? EMPTY_TURNS,\n changedTurnOrders,\n }\n const snapshot = this.snapshot(input.timeline, this.legacy.apply(upserts, input.timeline))\n return snapshot\n }\n\n groupInput(): ConversationGroupInput<ChatConversationViewNode> {\n return this.latestGroupInput\n }\n\n publish(): void {\n this.store.publish()\n }\n\n private snapshot(\n timeline: ConversationTimelineSnapshot,\n legacy = this.legacy.replace(EMPTY_LIST, timeline),\n ): ChatSnapshot {\n return {\n order: this.order,\n nodes: this.store,\n locations: this.locations,\n navigation: this.navigation,\n timeline,\n legacy,\n }\n }\n}\n\n/** Turns owning the given nodes, for the content-only navigation update. */\nfunction turnsOf(nodes: readonly ChatConversationViewNode[]): ReadonlySet<number> {\n const turns = new Set<number>()\n for (const node of nodes) {\n const turn = locationCoordinates(node.location).turn\n if (turn !== undefined) turns.add(turn)\n }\n return turns\n}\n\nfunction locationIdentity(location: ConversationLocation): string {\n const coordinates = locationCoordinates(location)\n return `${location.kind}:${coordinates.turn ?? ''}:${coordinates.step ?? ''}`\n}\n\n/** Chat target factory contributed to the Conversation view registry. */\nexport const chatViewDefinition: ConversationViewDefinition<ChatConversationViewNode, ChatSnapshot> = {\n target: 'chat',\n create: () => new ChatSnapshotBuilder(),\n isActive: snapshot => snapshot.order.some(key => snapshot.nodes.get(key)?.kind !== 'command'),\n}\n\n/**\n * Register the incremental Chat target builder.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerChatConversationView(ctx: Context): void {\n ctx.uiConversation.views.register(chatViewDefinition)\n}\n","/**\n * Surface layer on top of the session event log: an ordered view of events\n * that produce LLM messages. The append-only log remains the source of truth.\n *\n * Browser-safe: web clients consume this subpath export, so it must stay free\n * of `node:` imports (they break the vite bundle).\n *\n * @module @deepseek-ai/dsh-session/surface\n */\n\nimport type { Message, ToolSchema } from '@deepseek-ai/dsh-llm'\nimport { SessionLogOffset, SessionSeq } from './types.ts'\nimport { KNOWN_SESSION_EVENT_TYPES, MESSAGE_PROJECTION_EVENT_TYPES } from './known-event-types.ts'\nimport type {\n SessionEvent,\n SessionEventType,\n SessionSeqCursor,\n SurfaceEvent,\n SurfaceOp,\n} from './types.ts'\n\n/** Readonly history immediately before a message-projection event. */\nexport interface SessionMessageProjectionContext {\n /** Current message-producing event sequences in model-visible order. */\n nodes: readonly SessionSeq[]\n /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */\n events: readonly SessionEvent[]\n /** Absolute sequence of the window's first event. */\n baseSeq: SessionLogOffset\n /** Previously projected messages keyed by their original event sequences. */\n messages: ReadonlyMap<SessionSeq, Message>\n}\n\n/** Pure interpretation of one plugin-owned event that changes existing message content. */\nexport interface SessionMessageProjection<T extends SessionEventType = SessionEventType> {\n /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */\n type: T\n /**\n * Validate the complete durable decision before returning any updates. Preserve\n * message identities and publish immutable copies without mutating the input.\n * @param event - candidate event, not yet applied to the supplied history.\n * @param context - history preceding this decision.\n * @returns changed current messages keyed by their original sequences.\n * @throws when the durable decision cannot be applied to this history.\n */\n project(event: SessionEvent<T>, context: SessionMessageProjectionContext): ReadonlyMap<SessionSeq, Message>\n}\n\n/** Runtime counterpart of the message-producing event union. */\nconst SURFACE_EVENT_TYPES = new Set<string>([\n 'system/message',\n 'developer/message',\n 'user/message',\n 'assistant/message',\n 'tool/result',\n])\n\n/**\n * Whether an event type can join the model-visible surface.\n * @param type - event type to test.\n * @returns true for one of the message-producing event types.\n */\nexport function isSurfaceEligibleType(type: string): boolean {\n return SURFACE_EVENT_TYPES.has(type)\n}\n\n/**\n * Narrow an event to a surface-eligible event carrying its required marker.\n * @param event - event to test.\n * @returns true when both the type and marker identify a surface event.\n */\nexport function isSurfaceEvent(event: SessionEvent): event is SurfaceEvent {\n if (!SURFACE_EVENT_TYPES.has(event.type)) return false\n const candidate: { surfaceOp?: unknown } = event\n return candidate.surfaceOp !== undefined\n}\n\n/**\n * Narrow an event to an append-origin surface event: one that entered the\n * surface at its own log position and was never itself a replacement copy.\n *\n * The model-visible surface deliberately shadows replaced ranges, so it is the\n * wrong source for a human transcript — a landed replacement would erase\n * conversation the user already saw. Append-origin events are that transcript's\n * durable source material; replacement copies stay model-only.\n * @param event - event to test.\n * @returns true when the event appended to the surface tail.\n */\nexport function isAppendSurfaceEvent(\n event: SessionEvent,\n): event is SurfaceEvent & { surfaceOp: 'append' } {\n return isSurfaceEvent(event) && event.surfaceOp === 'append'\n}\n\n/**\n * Narrow an event to a surface replacement: a node that shadowed an existing\n * surface range instead of appending to the tail. The counterpart of\n * {@link isAppendSurfaceEvent} over the two {@link SurfaceOp} variants.\n * @param event - event to test.\n * @returns true when the event replaced a surface range.\n */\nexport function isReplacementSurfaceEvent(\n event: SessionEvent,\n): event is SurfaceEvent & { surfaceOp: Extract<SurfaceOp, { op: 'replace' }> } {\n return isSurfaceEvent(event) && event.surfaceOp !== 'append'\n}\n\n/**\n * Project a single event into the LLM message it derives to, or null when it\n * produces none — a non-surface event (attempt, boundary, log-only record) or an\n * empty-content system, developer, or assistant message. A caller\n * reconstructing model input supplies the same prefix's `projectedMessages`\n * from {@link foldSurface}; without that map this function reads original\n * event content. Session instance methods apply the live projection. Messages\n * are immutable and unchanged content retains its durable identity.\n * @param event - the event to project.\n * @param projectedMessages - message projections from the same log prefix's surface fold.\n * @returns the derived message, or null when the event produces none.\n */\nexport function deriveEventMessage(\n event: SessionEvent,\n projectedMessages?: ReadonlyMap<SessionSeq, Message>,\n): Message | null {\n const projected = projectedMessages?.get(event.seq)\n if (projected !== undefined) return projected\n // Intentionally non-exhaustive: only message-producing events derive\n // history; turn/step boundaries, failed attempts, and errors are trace/replay\n // data.\n switch (event.type) {\n // Ordinary prompts and injected context retain producer-owned framing.\n // See Derived history in packages/core/session/README.md.\n case 'user/message': {\n return event.data\n }\n // Empty system and developer nodes retain their surface positions without\n // adding wire messages. An empty assistant event hosts a max-tokens step's\n // usage and must not inject a content-less turn into the provider transcript.\n case 'system/message':\n case 'developer/message':\n case 'assistant/message': {\n if (event.data.message.content.length === 0) return null\n return event.data.message\n }\n case 'tool/result': {\n return event.data.message\n }\n default:\n // A non-surface event (boundary, attempt, log-only record) projects to\n // no message. Merge-extensible union: no assertNever here.\n return null\n }\n}\n\n/** Whether a payload field is a JSON object rather than an array or scalar. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Reject noncanonical request-header fields, developer roles/content, and contradictory tool failure metadata.\n * This does not validate complete event payloads or embedded provider streams.\n * @param event - event whose locally related payload fields are inspected.\n * @param subject - event location to include in validation errors.\n * @throws when request-header fields, developer roles/content, or tool failure metadata are invalid.\n */\nexport function validateSessionEventData(\n event: Pick<SessionEvent, 'type' | 'data'>,\n subject: string,\n): void {\n const data: unknown = event.data\n if (SURFACE_EVENT_TYPES.has(event.type) && isRecord(data)) {\n const message = event.type === 'user/message' ? data : data['message']\n if (isRecord(message)) {\n if ((event.type === 'developer/message') !== (message['role'] === 'developer')) {\n throw new Error(`${subject} developer/message and developer role must occur together`)\n }\n if (message['role'] !== 'developer' && Array.isArray(message['content'])\n && message['content'].some((block: unknown) => isRecord(block)\n && (block['type'] === 'tool-addition' || block['type'] === 'tool-removal'))) {\n throw new Error(`${subject} tool-change blocks require developer role`)\n }\n if (event.type === 'developer/message' && Array.isArray(message['content'])) {\n let hasAdditions = false\n for (const block of message['content']) {\n if (!isRecord(block) || (block['type'] !== 'tool-addition' && block['type'] !== 'tool-removal')) continue\n if (typeof block['toolName'] !== 'string' || block['toolName'].length === 0) {\n throw new Error(`${subject} ${block['type']} requires a nonempty toolName`)\n }\n if (block['type'] === 'tool-addition') {\n hasAdditions = true\n if (Object.hasOwn(block, 'tool')) throw new Error(`${subject} tool-addition must omit inline tool definitions`)\n }\n }\n if (hasAdditions ? !isEventSeq(data['headerSeq']) : Object.hasOwn(data, 'headerSeq')) {\n throw new Error(`${subject} requires headerSeq exactly when tool additions are present`)\n }\n }\n }\n }\n if (event.type === 'request/header') {\n if (!isRecord(data)) throw new Error(`${subject} data must be an object`)\n const header = data['header']\n if (!isRecord(header)) throw new Error(`${subject} header must be an object`)\n if (Object.hasOwn(header, 'system')) throw new Error(`${subject} must omit header.system; use system/message`)\n if (Array.isArray(header['tools']) && header['tools'].length === 0) {\n throw new Error(`${subject} must omit empty tools`)\n }\n const defaults = header['adapterDefaults']\n if (isRecord(defaults) && Object.keys(defaults).length === 0) {\n throw new Error(`${subject} must omit empty adapterDefaults`)\n }\n } else if (event.type === 'tool/result') {\n if (!isRecord(data)) throw new Error(`${subject} data must be an object`)\n if (data['error'] === undefined) return\n const message = data['message']\n if (!isRecord(message) || message['isError'] !== true) {\n throw new Error(`${subject} error requires message.isError === true`)\n }\n }\n}\n\n/** One replacement operation observed while folding a session surface. */\nexport interface SurfaceFoldReplacement {\n /** Seq of the event that replaced the prior surface range. */\n seq: SessionSeq\n /** Declared inclusive start seq of the replaced surface range. */\n start: SessionSeq\n /** Declared inclusive end seq of the replaced surface range. */\n end: SessionSeq\n /** Actual surface entries removed by the operation, in surface order. */\n shadowedSeqs: SessionSeq[]\n}\n\n/** Complete result of replaying the surface operations in a session log. */\nexport interface SurfaceFoldResult {\n /** Current surface event sequences in model-visible order. */\n nodes: SessionSeq[]\n /** Replacement operations in event order. */\n replacements: SurfaceFoldReplacement[]\n /** Immutable projected messages, keyed by their original event sequences. */\n projectedMessages: ReadonlyMap<SessionSeq, Message>\n}\n\n/** Readonly live projection of the message-producing session events. */\nexport interface SessionSurface {\n /** Current surface event sequences in model-visible order. */\n readonly nodes: readonly SessionSeq[]\n /** Monotonic count of committed positional replacements. */\n readonly replaceGeneration: number\n /** Monotonic count of committed replacements and plugin-owned message changes. */\n readonly contentGeneration: number\n}\n\n/** Mutable state shared by complete and incremental folds. */\ninterface SurfaceFoldState {\n nodes: SessionSeq[]\n replaceGeneration: number\n contentGeneration: number\n projectedMessages: Map<SessionSeq, Message>\n projections: Set<SessionMessageProjection>\n}\n\n/** A validated replacement transition that has not mutated fold state yet. */\ninterface SurfaceReplacePlan extends SurfaceFoldReplacement {\n kind: 'replace'\n startIdx: number\n endIdx: number\n}\n\n/** One validated surface transition that has not mutated fold state yet. */\ntype SurfacePlan =\n | { kind: 'append'; seq: SessionSeq }\n | SurfaceReplacePlan\n | { kind: 'project'; projection: SessionMessageProjection; messages: ReadonlyMap<SessionSeq, Message> }\n\n/** Create an empty surface fold state. */\nfunction createFoldState(): SurfaceFoldState {\n return { nodes: [], replaceGeneration: 0, contentGeneration: 0, projectedMessages: new Map(), projections: new Set() }\n}\n\n/** Whether a runtime value is a non-negative safe event sequence. */\nfunction isEventSeq(value: unknown): value is SessionSeq {\n return typeof value === 'number'\n && Number.isSafeInteger(value)\n && value >= 0\n && !Object.is(value, -0)\n}\n\n/** Whether a runtime value is the exact positional-replacement shape. */\nfunction isReplaceOp(value: object): value is Extract<SurfaceOp, { op: 'replace' }> {\n const op = value as Record<string, unknown>\n return Object.keys(op).length === 3\n && Object.hasOwn(op, 'op')\n && Object.hasOwn(op, 'startSeq')\n && Object.hasOwn(op, 'endSeq')\n && op['op'] === 'replace'\n && isEventSeq(op['startSeq'])\n && isEventSeq(op['endSeq'])\n}\n\n/** Validate event-local surface eligibility and return its operation. */\nfunction surfaceOpOf(event: SessionEvent): SurfaceOp | undefined {\n const raw: { surfaceOp?: unknown; sourceEventSeqs?: unknown } = event\n if (!isSurfaceEligibleType(event.type)) {\n // Unknown ignorable records retain opaque metadata without affecting history.\n if (!KNOWN_SESSION_EVENT_TYPES.has(event.type) && event.ignorable === true) return\n if (raw.surfaceOp !== undefined) {\n throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry surfaceOp`)\n }\n if (raw.sourceEventSeqs !== undefined) {\n throw new Error(`session event \"${event.type}\" is not surface-eligible and cannot carry sourceEventSeqs`)\n }\n return\n }\n const op = raw.surfaceOp\n if (op === undefined) {\n throw new Error(`session event \"${event.type}\" is surface-eligible and requires a surfaceOp marker`)\n }\n if (op === 'append') return op\n if (op === null || typeof op !== 'object' || Array.isArray(op)) {\n throw new Error(`session event \"${event.type}\" carries an invalid surfaceOp`)\n }\n if (!isReplaceOp(op)) {\n throw new Error(`session event \"${event.type}\" carries an invalid replace surfaceOp`)\n }\n return op\n}\n\n/** Validate cited source-event seqs against prior log entries and the replacement range. */\nfunction assertSourceEventReferences(\n event: SessionEvent,\n shadowedSeqs: readonly SessionSeq[],\n): void {\n const raw: unknown = event.sourceEventSeqs\n if (event.type === 'assistant/message' && raw !== undefined) {\n throw new Error('assistant/message embeds its source stream and cannot carry sourceEventSeqs')\n }\n const sources = new Set<SessionSeq>()\n if (raw !== undefined) {\n if (!Array.isArray(raw)) {\n throw new Error(`sourceEventSeqs on event at seq ${event.seq} must be an array when present`)\n }\n if (raw.length === 0) {\n throw new Error('sourceEventSeqs must not be empty')\n }\n let nonEarlierSource: SessionSeq | undefined\n for (const source of raw) {\n if (!isEventSeq(source)) {\n throw new Error(`session event \"${event.type}\" sourceEventSeqs must densely contain non-negative safe integers`)\n }\n sources.add(source)\n if (nonEarlierSource === undefined && source >= event.seq) nonEarlierSource = source\n }\n if (sources.size !== raw.length) {\n throw new Error('sourceEventSeqs must not contain duplicates')\n }\n if (nonEarlierSource !== undefined) {\n throw new Error(`sourceEventSeqs must reference earlier events: ${nonEarlierSource} >= current seq ${event.seq}`)\n }\n }\n const missing = shadowedSeqs.filter(seq => !sources.has(seq))\n if (missing.length > 0) {\n throw new Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${missing.join(', ')}`)\n }\n}\n\n/** Resolve tool additions against their immutable historical request header. */\nfunction assertDeveloperHeader(\n event: SessionEvent,\n read: (seq: number) => SessionEvent | undefined,\n): void {\n if (event.type !== 'developer/message') return\n validateSessionEventData(event, `developer/message at seq ${event.seq}`)\n if (event.data.headerSeq === undefined) return\n const headerSeq = event.data.headerSeq\n const headerEvent = read(headerSeq)\n if (headerSeq >= event.seq || headerEvent?.type !== 'request/header') {\n throw new Error('developer/message headerSeq must reference an earlier request/header')\n }\n for (const block of event.data.message.content) {\n if (block.type !== 'tool-addition') continue\n const definitions = headerEvent.data.header.tools?.filter(tool => tool.name === block.toolName) ?? []\n if (definitions.length !== 1) {\n throw new Error(`developer/message tool-addition \"${block.toolName}\" must name exactly one tool in headerSeq ${headerSeq}`)\n }\n const definition = definitions[0] as ToolSchema\n if (typeof definition.description !== 'string' || !isRecord(definition.parameters)) {\n throw new Error(`developer/message tool-addition \"${block.toolName}\" requires a complete tool definition in headerSeq ${headerSeq}`)\n }\n if (Object.hasOwn(definition, 'deferLoading') && definition.deferLoading !== true) {\n throw new Error('developer/message referenced tool deferLoading must be true when present')\n }\n }\n}\n\n/**\n * Validate one event's surface metadata without checking membership in a log or surface.\n * @param event - event whose marker and source sequence values are inspected.\n * Unknown ignorable records retain opaque metadata and never change the surface.\n * @returns the validated operation, or undefined for a log-only or unknown ignorable event.\n * @throws when metadata violates event-local eligibility, marker, or source-sequence rules.\n */\nexport function validateSurfaceMetadata(event: SessionEvent): SurfaceOp | undefined {\n const op = surfaceOpOf(event)\n if (op !== undefined && op !== 'append'\n && (op.startSeq >= event.seq || op.endSeq >= event.seq)) {\n throw new Error(`surface replace at seq ${event.seq}: startSeq and endSeq must reference earlier events`)\n }\n if (op !== undefined) assertSourceEventReferences(event, [])\n return op\n}\n\n/** Locate one replacement range without mutating the current fold state. */\nfunction replacementRange(\n state: SurfaceFoldState,\n op: Extract<SurfaceOp, { op: 'replace' }>,\n): Pick<SurfaceReplacePlan, 'startIdx' | 'endIdx' | 'shadowedSeqs'> {\n const startIdx = state.nodes.indexOf(op.startSeq)\n if (startIdx === -1) {\n throw new Error(`surface replace: start seq ${op.startSeq} not found in surface`)\n }\n const endIdx = state.nodes.indexOf(op.endSeq)\n if (endIdx === -1) {\n throw new Error(`surface replace: end seq ${op.endSeq} not found in surface`)\n }\n if (startIdx > endIdx) {\n throw new Error(`surface replace: start seq ${op.startSeq} (index ${startIdx}) is after end seq ${op.endSeq} (index ${endIdx})`)\n }\n return {\n startIdx,\n endIdx,\n shadowedSeqs: state.nodes.slice(startIdx, endIdx + 1),\n }\n}\n\n/**\n * Deep structural equality over the session-event JSON value domain\n * (null/boolean/number/string, arrays, plain objects). Replaces\n * `node:util`'s isDeepStrictEqual to keep this module browser-safe.\n */\nfunction isDeepEqualJson(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false\n return a.every((item, i) => isDeepEqualJson(item, b[i]))\n }\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false\n const aKeys = Object.keys(a)\n const bRecord = b as Record<string, unknown>\n if (aKeys.length !== Object.keys(b).length) return false\n return aKeys.every(key => Object.hasOwn(b, key) && isDeepEqualJson((a as Record<string, unknown>)[key], bRecord[key]))\n}\n\n/** Restrict a tool-result replacement to one current result's content. */\nfunction assertToolResultRewrite(\n event: SessionEvent,\n shadowedSeqs: readonly SessionSeq[],\n read: (seq: number) => SessionEvent | undefined,\n): void {\n if (event.type !== 'tool/result') return\n if (shadowedSeqs.length !== 1) {\n throw new Error('tool/result surface replacement must rewrite exactly one current node')\n }\n for (const originalSeq of shadowedSeqs) {\n const original = read(originalSeq)\n if (original?.type !== 'tool/result') {\n throw new Error('tool/result surface replacement must target a current tool/result')\n }\n const originalRest = { ...original.data } as Record<string, unknown>\n const replacementRest = { ...event.data } as Record<string, unknown>\n originalRest['message'] = {\n ...original.data.message,\n content: null,\n }\n replacementRest['message'] = {\n ...event.data.message,\n content: null,\n }\n if (!isDeepEqualJson(originalRest, replacementRest)) {\n throw new Error('tool/result surface replacement may change only content')\n }\n }\n}\n\n/**\n * Protect the system prompt at surface node 0. A replacement covering node 0\n * while that node is a `system/message` must itself be a `system/message` over\n * exactly that node; later system nodes carry no protection and a compaction\n * range may shadow them.\n */\nfunction assertSystemHeadRewrite(\n event: SessionEvent,\n state: SurfaceFoldState,\n startIdx: number,\n shadowedSeqs: readonly SessionSeq[],\n read: (seq: number) => SessionEvent | undefined,\n): void {\n if (startIdx !== 0) return\n const head = read(state.nodes[0] as number)\n if (head?.type !== 'system/message') return\n if (event.type !== 'system/message' || shadowedSeqs.length !== 1) {\n throw new Error('surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node')\n }\n}\n\n/** Validate one event at its replay boundary and prepare its atomic fold transition. */\nfunction planSurfaceEvent(\n state: SurfaceFoldState,\n event: SessionEvent,\n expectedSeq: SessionSeq,\n events: readonly SessionEvent[],\n baseSeq: SessionLogOffset,\n projections: readonly SessionMessageProjection[],\n candidates?: readonly SessionEvent[],\n): SurfacePlan | undefined {\n if (event.seq !== expectedSeq) {\n throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`)\n }\n const surfaceOp = validateSurfaceMetadata(event)\n const read = (seq: number): SessionEvent | undefined => {\n const index = seq - baseSeq\n return index < events.length ? events[index] : candidates?.[index - events.length]\n }\n assertDeveloperHeader(event, read)\n const projection = projections.find(item => item.type === event.type)\n if (projection !== undefined) {\n let projectionEvents: readonly SessionEvent[] | undefined\n return { kind: 'project', projection, messages: projection.project(event, {\n nodes: state.nodes,\n get events() { return candidates === undefined ? events : (projectionEvents ??= [...events, ...candidates]) },\n baseSeq,\n messages: state.projectedMessages,\n }) }\n }\n if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) {\n throw new Error(`session event \"${event.type}\" requires a message projection; load its owning plugin or supply its projection definition`)\n }\n if (surfaceOp === undefined) return\n if (surfaceOp === 'append') {\n return { kind: 'append', seq: event.seq }\n }\n const range = replacementRange(state, surfaceOp)\n assertSourceEventReferences(event, range.shadowedSeqs)\n assertToolResultRewrite(event, range.shadowedSeqs, read)\n assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read)\n return {\n kind: 'replace',\n seq: event.seq,\n start: surfaceOp.startSeq,\n end: surfaceOp.endSeq,\n ...range,\n }\n}\n\n/** Apply one event and return replacement metadata only when one occurred. */\nfunction applySurfaceEvent(\n state: SurfaceFoldState,\n event: SessionEvent,\n expectedSeq: SessionSeq,\n events: readonly SessionEvent[],\n baseSeq: SessionLogOffset,\n projections: readonly SessionMessageProjection[],\n): SurfaceFoldReplacement | undefined {\n const plan = planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections)\n return applySurfacePlan(state, plan)\n}\n\n/** Commit one previously validated surface transition. */\nfunction applySurfacePlan(\n state: SurfaceFoldState,\n plan: SurfacePlan | undefined,\n): SurfaceFoldReplacement | undefined {\n if (plan?.kind === 'append') {\n state.nodes.push(plan.seq)\n } else if (plan?.kind === 'replace') {\n state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq)\n state.replaceGeneration += 1\n state.contentGeneration += 1\n } else if (plan?.kind === 'project') {\n for (const [seq, message] of plan.messages) state.projectedMessages.set(seq, message)\n state.projections.add(plan.projection)\n state.contentGeneration += 1\n }\n if (plan?.kind !== 'replace') return\n return {\n seq: plan.seq,\n start: plan.start,\n end: plan.end,\n shadowedSeqs: plan.shadowedSeqs,\n }\n}\n\n/**\n * Replay a complete session log through the canonical surface fold.\n * @param events - session events in contiguous seq order.\n * @param projections - pure interpreters for plugin-owned message changes; required definitions must be supplied.\n * @returns detached current sequences and replacement history.\n * @throws when an interpreter is missing or an event violates its projection, surface metadata, source attribution, or replacement rules.\n */\nexport function foldSurface(events: readonly SessionEvent[], projections: readonly SessionMessageProjection[] = []): SurfaceFoldResult {\n const state = createFoldState()\n const replacements: SurfaceFoldReplacement[] = []\n for (const [index, event] of events.entries()) {\n const replacement = applySurfaceEvent(\n state,\n event,\n SessionSeq(index),\n events,\n SessionLogOffset(0),\n projections,\n )\n if (replacement !== undefined) replacements.push(replacement)\n }\n return { nodes: [...state.nodes], replacements, projectedMessages: new Map(state.projectedMessages) }\n}\n\n/** Incremental ordered surface view and append-boundary validator. */\nexport class SurfaceManager implements SessionSurface {\n /** Shared transition state; replacement history is not retained. */\n private _state = createFoldState()\n /** Last processed absolute seq. */\n private _lastProcessedSeq: SessionSeqCursor\n /** Candidate already validated by `validateNext`, pending exact log admission. */\n private _pendingPlan: { event: SessionEvent; expectedSeq: SessionSeq; plan: SurfacePlan | undefined } | undefined\n\n /**\n * @param log - Contiguous complete log or loaded event window.\n * @param baseSeq - Absolute sequence of the window's first event.\n * @param projections - live borrowed definitions; removing a used definition invalidates further reads.\n */\n constructor(\n private log: readonly SessionEvent[],\n private readonly baseSeq: SessionLogOffset = SessionLogOffset(0),\n private readonly projections: readonly SessionMessageProjection[] = [],\n ) {\n this._lastProcessedSeq = baseSeq === 0 ? -1 : SessionSeq(baseSeq - 1)\n }\n\n /**\n * Validate the next candidate without mutating the committed surface.\n * @param event - candidate event that has not entered the log yet.\n */\n validateNext(event: SessionEvent): void {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n const expectedSeq = SessionSeq(this.baseSeq + this.log.length)\n this._pendingPlan = {\n event,\n expectedSeq,\n plan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq, this.projections),\n }\n }\n\n /**\n * Validate consecutive candidates against an isolated surface fold.\n * @param events - candidates immediately following the committed log.\n * @returns a callback adopting the validated fold after all candidates enter the log.\n */\n prepareBatch(events: readonly SessionEvent[]): () => void {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1)\n if (events.every(event => (event.surfaceOp === undefined || event.surfaceOp === 'append')\n && !this.projections.some(projection => projection.type === event.type))) {\n const plans = events.map((event, index) => planSurfaceEvent(\n this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,\n ))\n return () => {\n for (const plan of plans) applySurfacePlan(this._state, plan)\n this._lastProcessedSeq = lastProcessedSeq\n this._pendingPlan = undefined\n }\n }\n const state: SurfaceFoldState = {\n ...this._state,\n nodes: [...this._state.nodes],\n projectedMessages: new Map(this._state.projectedMessages),\n projections: new Set(this._state.projections),\n }\n const plans = events.map((event, index) => {\n const plan = planSurfaceEvent(\n state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,\n )\n applySurfacePlan(state, plan)\n return plan\n })\n return () => {\n for (const plan of plans) applySurfacePlan(this._state, plan)\n this._lastProcessedSeq = lastProcessedSeq\n this._pendingPlan = undefined\n }\n }\n\n /** Monotonic count of folded positional replacements. */\n get replaceGeneration(): number {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n return this._state.replaceGeneration\n }\n\n /** Monotonic count of committed changes to existing model-visible content. */\n get contentGeneration(): number {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n return this._state.contentGeneration\n }\n\n /**\n * Project one message with every committed message projection applied.\n * @param event - message-producing or log-only event.\n * @returns its immutable projected message, or null when it produces none.\n */\n deriveEventMessage(event: SessionEvent): Message | null {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n return deriveEventMessage(event, this._state.projectedMessages)\n }\n\n /** Surface event sequences in model-visible order. */\n get nodes(): readonly SessionSeq[] {\n this._assertProjections()\n if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()\n return this._state.nodes\n }\n\n /** Fold events appended since the previous access. */\n private _processDelta(): void {\n const tailSeq = this.baseSeq + this.log.length - 1\n for (let seq = this._lastProcessedSeq + 1; seq <= tailSeq; seq++) {\n const index = seq - this.baseSeq\n // oxlint-disable-next-line typescript/no-non-null-assertion -- bounded by the loop condition\n const event = this.log[index]!\n const pending = this._pendingPlan\n if (pending?.event === event && pending.expectedSeq === seq) {\n applySurfacePlan(this._state, pending.plan)\n } else {\n applySurfaceEvent(this._state, event, SessionSeq(seq), this.log, this.baseSeq, this.projections)\n }\n if (pending !== undefined && pending.expectedSeq <= seq) this._pendingPlan = undefined\n this._lastProcessedSeq = SessionSeq(seq)\n }\n }\n\n /** Cached messages cannot outlive the definitions that interpreted their log. */\n private _assertProjections(): void {\n const candidate = this._pendingPlan\n const pending = candidate !== undefined && this.log[candidate.expectedSeq - this.baseSeq] === candidate.event\n ? candidate.plan : undefined\n const required = pending?.kind === 'project'\n ? [...this._state.projections, pending.projection]\n : this._state.projections\n for (const projection of required) {\n if (!this.projections.includes(projection)) {\n throw new Error(`session message projection \"${projection.type}\" was removed or replaced; restore the session with its owning plugin`)\n }\n }\n }\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n CommandNode, CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { CompactionCheckpointSource } from '@deepseek-ai/dsh-compaction/checkpoint'\nimport type {} from '@deepseek-ai/dsh-compaction/types'\nimport type {} from '@deepseek-ai/dsh-commands/types'\nimport { isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type { ManualCompactionChatData } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Ordinary slash-command lifecycle. */\n command: CommandNode\n /** Manual compact command combined with its compaction transaction. */\n 'manual-compaction': ManualCompactionChatData\n }\n}\n\ntype CommandId = CommandNode['commandId']\n\nconst COMPACT_KIND: CompactionCheckpointSource['kind'] = 'compact-checkpoint'\n\ninterface CommandState {\n readonly command: CommandNode\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\ninterface CompactionEvidence {\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\nfunction commandFromRun(match: ConversationMatch): CommandNode {\n if (match.event.type !== 'command/run') throw new Error('command start requires command/run')\n const data = match.event.data\n return {\n kind: 'command',\n seq: match.event.seq,\n time: match.event.time,\n commandId: data.commandId,\n name: data.name,\n args: data.args ?? null,\n outcome: null,\n }\n}\n\nfunction commandFromDone(match: ConversationMatch, previous?: CommandNode): CommandNode {\n if (match.event.type !== 'command/done') throw new Error('command update requires command/done')\n const data = match.event.data\n const sourceEventSeq = data.kind === 'success'\n && data.sourceEventSeq !== undefined\n && Number.isSafeInteger(data.sourceEventSeq) && data.sourceEventSeq >= 0\n ? data.sourceEventSeq\n : undefined\n return {\n kind: 'command',\n seq: previous?.seq ?? match.event.seq,\n time: previous?.time ?? match.event.time,\n commandId: data.commandId,\n name: previous?.name ?? null,\n args: previous?.args ?? null,\n outcome: {\n kind: data.kind,\n ...data.text === undefined ? {} : { text: data.text },\n ...sourceEventSeq === undefined ? {} : { sourceEventSeq },\n },\n }\n}\n\n/**\n * Read correlation identity from a compaction replacement checkpoint.\n * @param event - candidate Session event.\n * @returns correlated compaction and optional command identity.\n */\nfunction compactSource(event: Parameters<ConversationNodeDefinition['match']>[0]): {\n compactionId: string\n sourceCommandId?: CommandId\n} | undefined {\n if (event.type !== 'user/message' || !isReplacementSurfaceEvent(event)) return undefined\n const source = event.data.source as {\n kind?: unknown\n compactionId?: unknown\n sourceCommandId?: CommandId\n }\n if (source.kind !== COMPACT_KIND || typeof source.compactionId !== 'string') return undefined\n return {\n compactionId: source.compactionId,\n ...source.sourceCommandId === undefined ? {} : { sourceCommandId: source.sourceCommandId },\n }\n}\n\n/**\n * Build the visible summary marker from optional lifecycle evidence.\n * @param match - compaction/summary Match, when loaded.\n * @param checkpoint - replacement checkpoint Match.\n * @returns final compaction summary Node data.\n */\nfunction compactSummary(match: ConversationMatch | undefined, checkpoint: ConversationMatch): CompactionSummaryNode {\n let summary: string | null = null\n let shadowedItemCount: number | null = null\n let shadowedTokenCount: number | null = null\n if (match?.event.type === 'compaction/summary') {\n const data = match.event.data\n if (Array.isArray(data.summary)) {\n const text = data.summary\n .map(block => block.type === 'text' ? block.text : '')\n .join('')\n summary = text.trim() === '' ? null : text\n }\n shadowedItemCount = Array.isArray(data.shadowedSeqs)\n && data.shadowedSeqs.every(seq => Number.isSafeInteger(seq) && seq >= 0)\n ? data.shadowedSeqs.length\n : null\n shadowedTokenCount = Number.isSafeInteger(data.shadowedTokenCount)\n && data.shadowedTokenCount >= 0\n ? data.shadowedTokenCount\n : null\n }\n return {\n kind: 'compaction',\n seq: checkpoint.event.seq,\n time: checkpoint.event.time,\n summary,\n summaryEventSeq: match?.event.seq ?? null,\n shadowedItemCount,\n shadowedTokenCount,\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<CommandState>): CommandState | undefined {\n const done = context.matches.find(match => match.event.type === 'command/done')\n const checkpoint = context.matches.find(match => compactSource(match.event) !== undefined)\n const summary = context.matches.find(match => match.event.type === 'compaction/summary')\n if (checkpoint === undefined) return done === undefined ? undefined : { command: commandFromDone(done) }\n const source = compactSource(checkpoint.event)\n if (source?.sourceCommandId === undefined) return done === undefined ? undefined : { command: commandFromDone(done) }\n const fallbackCommand = done === undefined\n ? {\n kind: 'command' as const,\n seq: checkpoint.event.seq,\n time: checkpoint.event.time,\n commandId: source.sourceCommandId,\n name: 'compact',\n args: null,\n outcome: null,\n }\n : { ...commandFromDone(done), name: 'compact' }\n return {\n command: fallbackCommand,\n checkpoint,\n ...summary === undefined ? {} : { summary },\n }\n}\n\n/**\n * Fold shared compaction evidence into a Definition-owned State.\n * @param state - current business State carrying optional compaction evidence.\n * @param match - next compaction lifecycle Match.\n * @returns adopted State, preserving reference identity when the Match adds no evidence.\n */\nexport function updateCompactionState<State extends CompactionEvidence>(\n state: State,\n match: ConversationMatch,\n): State {\n if (match.event.type === 'compaction/summary') return { ...state, summary: match }\n if (compactSource(match.event) !== undefined) return { ...state, checkpoint: match }\n return state\n}\n\n/** Slash-command lifecycle, including integrated manual compaction, Definition. */\nexport const commandDefinition: ConversationNodeDefinition<CommandState> = {\n kind: 'command',\n target: 'chat',\n match: (event) => {\n if (event.type === 'command/run') {\n return { id: String(event.data.commandId), role: 'start' }\n }\n if (event.type === 'command/done') {\n return { id: String(event.data.commandId), role: 'update' }\n }\n const checkpoint = compactSource(event)\n if (checkpoint?.sourceCommandId !== undefined) {\n return { id: String(checkpoint.sourceCommandId), role: 'update' }\n }\n if (event.type === 'compaction/start'\n || event.type === 'compaction/summary'\n || event.type === 'compaction/end') {\n if (event.data.sourceCommandId !== undefined) {\n return { id: String(event.data.sourceCommandId), role: 'update' }\n }\n }\n return null\n },\n start: (_context, match) => ({ command: commandFromRun(match) }),\n update: (context, match) => {\n if (match.event.type === 'command/done') {\n return { ...context.state, command: commandFromDone(match, context.state.command) }\n }\n return updateCompactionState(context.state, match)\n },\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return null\n if (state.command.name !== 'compact') {\n return chatNode(context, 'command', state.command.seq, state.command)\n }\n const compaction = state.checkpoint === undefined\n ? null\n : compactSummary(state.summary, state.checkpoint)\n const data: ManualCompactionChatData = { command: state.command, compaction }\n return chatNode(context, 'manual-compaction', compaction?.seq ?? state.command.seq, data)\n },\n}\n\n/**\n * Register the command lifecycle business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerCommandConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(commandDefinition)\n}\n\n/** Shared structural checkpoint recognizer for automatic compaction. */\nexport { compactSource, compactSummary }\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n CompactionSummaryNode, ConversationMatch, ConversationNodeContext, ConversationNodeDefinition,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-compaction/types'\nimport { chatNode } from './common.ts'\nimport { compactSource, compactSummary, updateCompactionState } from './command.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Automatic compaction checkpoint marker. */\n compaction: CompactionSummaryNode\n }\n}\n\ninterface CompactionState {\n readonly summary?: ConversationMatch\n readonly checkpoint?: ConversationMatch\n}\n\nfunction fallbackState(context: ConversationNodeContext<CompactionState>): CompactionState {\n const summary = context.matches.find(match => match.event.type === 'compaction/summary')\n const checkpoint = context.matches.find(match => compactSource(match.event) !== undefined)\n return {\n ...summary === undefined ? {} : { summary },\n ...checkpoint === undefined ? {} : { checkpoint },\n }\n}\n\n/** Automatic compaction lifecycle and landed checkpoint Definition. */\nexport const compactionDefinition: ConversationNodeDefinition<CompactionState> = {\n kind: 'compaction',\n target: 'chat',\n match: (event) => {\n const checkpoint = compactSource(event)\n if (checkpoint !== undefined && checkpoint.sourceCommandId === undefined) {\n return { id: checkpoint.compactionId, role: 'update' }\n }\n if (event.type === 'compaction/start'\n || event.type === 'compaction/summary'\n || event.type === 'compaction/end') {\n if (event.data.sourceCommandId !== undefined) return null\n const compactionId: unknown = event.data.compactionId\n if (typeof compactionId !== 'string' || compactionId === '') return null\n return { id: compactionId, role: event.type === 'compaction/start' ? 'start' : 'update' }\n }\n return null\n },\n start: () => ({}),\n update: (context, match) => updateCompactionState(context.state, match),\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state.checkpoint === undefined) return null\n const marker = compactSummary(state.summary, state.checkpoint)\n return chatNode(context, 'compaction', marker.seq, marker)\n },\n}\n\n/**\n * Register the automatic-compaction business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerCompactionConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(compactionDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationNodeDefinition, UnknownSurfaceNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Generic presentation of an unclaimed append-surface event. */\n unknown: UnknownSurfaceNode\n }\n}\n\n/** Unclaimed append-surface fallback Definition. */\nexport const unknownFallbackDefinition: ConversationNodeDefinition<UnknownSurfaceNode> = {\n kind: 'unknown-surface',\n target: 'chat',\n match: event => event.type !== 'assistant/live-chunk' && isAppendSurfaceEvent(event)\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (_context, match) => ({\n kind: 'unknown',\n seq: match.event.seq,\n time: match.event.time,\n type: match.event.type,\n data: match.event.data,\n }),\n update: context => context.state,\n buildViewNode: context => context.state === undefined\n ? null\n : chatNode(context, 'unknown', context.state.seq, context.state),\n}\n\n/**\n * Register the unmatched append-surface fallback contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerUnknownConversationFallback(ctx: Context): void {\n ctx.uiConversation.events.registerFallback(unknownFallbackDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationNodeDefinition, ConversationPreviousContext,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\ninterface InboxIdentity {\n readonly id: string\n readonly source: { readonly kind: string }\n}\n\ninterface InboxSplice {\n readonly start: number\n readonly removedCount?: number\n readonly inserted: readonly InboxIdentity[]\n readonly outcome?: 'canceled'\n}\n\ninterface PendingSnapshot {\n readonly kind: 'snapshot'\n readonly ids: readonly InboxIdentity[]\n}\n\ninterface PendingSplice {\n readonly kind: 'splice'\n readonly previous: PendingState\n readonly start: number\n readonly removedCount: number\n readonly inserted: readonly InboxIdentity[]\n}\n\ntype PendingState = PendingSnapshot | PendingSplice\n\n/** Persistent Inbox state after one durable Inbox splice. */\nexport interface InboxState {\n /** Persistent splice chain materialized only when a batch is claimed. */\n readonly pending: PendingState\n /** Message ids in the current claim, shared until the next claim. */\n readonly currentClaimed: ReadonlySet<string>\n readonly claimSeq: number\n /**\n * First human message id of the current claim in Inbox order; undefined\n * when the claim took no human message. The AgentLoop logs a claim's\n * messages in this order, so this message is the claim's first steering row.\n */\n readonly firstClaimedHuman: string | undefined\n}\n\nconst EMPTY_PENDING: PendingState = { kind: 'snapshot', ids: [] }\nconst EMPTY_CURRENT_CLAIMED: ReadonlySet<string> = new Set()\n\nfunction materializePending(state: PendingState): InboxIdentity[] {\n const splices: PendingSplice[] = []\n let current = state\n while (current.kind === 'splice') {\n splices.push(current)\n current = current.previous\n }\n const pending = [...current.ids]\n for (const splice of splices.reverse()) {\n pending.splice(splice.start, splice.removedCount, ...splice.inserted)\n }\n return pending\n}\n\nfunction withoutInserted(\n claimed: ReadonlySet<string>,\n inserted: readonly InboxIdentity[],\n): ReadonlySet<string> {\n let next: Set<string> | undefined\n for (const { id } of inserted) {\n if (!claimed.has(id)) continue\n next ??= new Set(claimed)\n next.delete(id)\n }\n return next ?? claimed\n}\n\n/**\n * Apply one Inbox splice under the AgentLoop's durable event ordering.\n * An entered claim logs its complete message batch before another claim; a\n * rejected claim logs no messages, so only the current claim can classify a\n * later `user/message`.\n */\nfunction applySplice(\n previous: ConversationPreviousContext<InboxState> | undefined,\n splice: InboxSplice,\n seq: number,\n): InboxState {\n const priorPending = previous?.state.pending ?? EMPTY_PENDING\n const inserted = splice.inserted\n const removedCount = splice.removedCount ?? 0\n if (removedCount > 0 && splice.outcome !== 'canceled') {\n const pending = materializePending(priorPending)\n const removed = pending.splice(splice.start, removedCount, ...inserted)\n return {\n pending: { kind: 'snapshot', ids: pending },\n currentClaimed: new Set(removed.map(message => message.id)),\n claimSeq: seq,\n firstClaimedHuman: removed.find(message => message.source.kind === 'user')?.id,\n }\n }\n const currentClaimed = withoutInserted(\n previous?.state.currentClaimed ?? EMPTY_CURRENT_CLAIMED,\n inserted,\n )\n return {\n pending: {\n kind: 'splice',\n previous: priorPending,\n start: splice.start,\n removedCount,\n inserted,\n },\n currentClaimed,\n claimSeq: previous?.state.claimSeq ?? -1,\n firstClaimedHuman: previous?.state.firstClaimedHuman,\n }\n}\n\nfunction inboxDefinition(target: 'next-step' | 'next-turn'): ConversationNodeDefinition<InboxState> {\n const kind = `inbox-${target}`\n return {\n kind,\n match: event => event.type === 'agent/inbox/spliced' && event.data.target === target\n ? { id: String(event.seq), role: 'start' } : null,\n start: (_context, match, reader) => {\n if (match.event.type !== 'agent/inbox/spliced') throw new Error('inbox start requires agent/inbox/spliced')\n return applySplice(reader.previous<InboxState>(kind), match.event.data, match.event.seq)\n },\n update: context => context.state,\n publication: () => 'none',\n }\n}\n\n/** Persistent next-step claims identify messages admitted into a running Turn. */\nexport const nextStepInboxDefinition = inboxDefinition('next-step')\n\n/** Persistent next-turn claims identify messages that wake a new Turn. */\nexport const nextTurnInboxDefinition = inboxDefinition('next-turn')\n\n/**\n * Register the Inbox state used by Chat message classification.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerInboxConversationNodes(ctx: Context): void {\n ctx.uiConversation.events.register(nextStepInboxDefinition)\n ctx.uiConversation.events.register(nextTurnInboxDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ContextMessageNode, ConversationContextReader, ConversationLocation, ConversationNodeDefinition,\n SteeringMessageNode, UserMessageNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent, isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type { InboxState } from './inbox.ts'\nimport type { ProcessEvidenceState } from './turn-process.ts'\nimport { chatNode, contextLocation } from './common.ts'\nimport { contextForm, contextProducer } from './event-projection.ts'\n\ninterface ReferencedUserMessageNode extends UserMessageNode {\n /** Labels cited by the immediately following session-reference context. */\n readonly referenceLabels?: readonly string[]\n /** Skill names the same step's `skill-invocation` injections loaded. */\n readonly skillNames?: readonly string[]\n}\n\ninterface ReferencedSteeringMessageNode extends SteeringMessageNode {\n /** Labels cited by the immediately following session-reference context. */\n readonly referenceLabels?: readonly string[]\n /** Skill names the same step's `skill-invocation` injections loaded. */\n readonly skillNames?: readonly string[]\n /**\n * First human message of its `next-step` claim that Chat orders after its Turn's process control;\n * the row keeps the Turn tail slot above it.\n */\n readonly batchStart?: true\n}\n\ntype MessageNode = ReferencedUserMessageNode | ReferencedSteeringMessageNode | (ContextMessageNode & { readonly waking?: boolean })\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Ordinary turn-opening user message. */\n user: ReferencedUserMessageNode\n /** User message admitted into an active turn. */\n steering: ReferencedSteeringMessageNode\n /** Non-user context injected into model history. */\n context: ContextMessageNode\n /** Recorded notification or manual continuation that starts a Turn. */\n 'turn-trigger': ContextMessageNode\n }\n}\n\nfunction isCompactionCheckpoint(event: Parameters<ConversationNodeDefinition['match']>[0]): boolean {\n if (event.type !== 'user/message' || !isReplacementSurfaceEvent(event)) return false\n const source = event.data.source as { kind?: unknown }\n return source.kind === 'compact-checkpoint'\n}\n\n/** Context presentation shared by user-role injections and developer messages. */\nfunction contextMessage(\n event: Pick<ContextMessageNode, 'seq' | 'time'>,\n message: Pick<ContextMessageNode, 'content' | 'source'>,\n): ContextMessageNode {\n return {\n kind: 'context',\n seq: event.seq,\n time: event.time,\n content: message.content,\n source: message.source,\n producer: contextProducer(message.source),\n form: contextForm(message.source),\n }\n}\n\n/**\n * Decide whether an input follows its Turn's process control in Chat order. The control anchors at the\n * Turn's first process evidence, so the input follows it exactly when its Turn recorded evidence earlier;\n * the nearest earlier evidence record then belongs to the input's own Turn.\n * @param location - the input's Location.\n * @param reader - strictly-backward Context lookup of the input's start.\n * @returns whether Chat orders the input after the control.\n */\nfunction followsProcessEvidence(location: ConversationLocation, reader: ConversationContextReader): boolean {\n if (location.kind !== 'turn' && location.kind !== 'step') return false\n return reader.previous<ProcessEvidenceState>('process-evidence')?.state.turn === location.turn.turn\n}\n\n/** User, steering, and injected-context message classification Definition. */\nexport const messageDefinition: ConversationNodeDefinition<MessageNode> = {\n kind: 'input-message',\n target: 'chat',\n match: (event) => {\n if (event.type === 'user/message') {\n return isAppendSurfaceEvent(event) && !isCompactionCheckpoint(event)\n ? { id: String(event.data.id), role: 'start' }\n : null\n }\n return null\n },\n start: (_context, match, reader) => {\n const event = match.event\n if (event.type !== 'user/message') throw new Error('input-message start requires user/message')\n if (event.data.source.kind !== 'user') {\n const nextTurn = reader.previous<InboxState>('inbox-next-turn')?.state\n const nextStep = reader.previous<InboxState>('inbox-next-step')?.state\n const location = match.location\n const turnStart = location.kind === 'step' ? location.turn.start?.seq : undefined\n // An idle steer opens Step 1 without a next-turn claim in this Turn.\n // A human in that same next-step claim owns the opening instead of its notices.\n const idleSteer = location.kind === 'step' && location.step.step === 1\n && turnStart !== undefined && (nextStep?.claimSeq ?? -1) > turnStart\n && (nextTurn?.claimSeq ?? -1) < turnStart && nextStep !== undefined\n && nextStep.firstClaimedHuman === undefined && nextStep.currentClaimed.has(String(event.data.id))\n\n return {\n ...contextMessage(event, event.data),\n waking: nextTurn?.currentClaimed.has(String(event.data.id)) === true || idleSteer,\n }\n }\n const id = String(event.data.id)\n const claim = reader.previous<InboxState>('inbox-next-step')?.state\n return claim?.currentClaimed.has(id) === true\n ? {\n kind: 'steering',\n messageId: event.data.id,\n seq: event.seq,\n time: event.time,\n content: event.data.content,\n source: event.data.source,\n ...claim.firstClaimedHuman === id && followsProcessEvidence(match.location, reader)\n ? { batchStart: true }\n : {},\n }\n : {\n kind: 'user',\n messageId: event.data.id,\n seq: event.seq,\n time: event.time,\n content: event.data.content,\n source: event.data.source,\n }\n },\n update: context => context.state,\n buildViewNode: (context) => {\n if (context.state === undefined) return null\n const location = contextLocation(context)\n if (context.state.kind === 'context' && context.start?.event.type === 'user/message'\n && context.start.event.data.source.kind === 'retry' && context.start.event.data.content.length === 0) {\n return chatNode(context, 'turn-trigger', context.state.seq, context.state, { location, groupTree: 'input' })\n }\n const waking = context.state.kind === 'context'\n && context.start?.event.type === 'user/message'\n && context.state.waking === true\n // Human input claimed for Step 1 opens an exchange; Notice-woken Turns and\n // later steering stay in the current exchange, so they never fold earlier Turns.\n const human = context.state.kind === 'user' || context.state.kind === 'steering'\n const opensExchange = human && location.kind === 'step' && location.step.step === 1\n return chatNode(\n context,\n waking ? 'turn-trigger' : context.state.kind,\n context.state.seq,\n context.state,\n { location, groupTree: opensExchange ? 'exchange' : (human || waking) ? 'input' : undefined },\n )\n },\n}\n\n/** Developer history uses the input-message lifecycle and context presentation. */\nexport const developerMessageDefinition: ConversationNodeDefinition<MessageNode> = {\n ...messageDefinition,\n kind: 'developer-message',\n match: event => event.type === 'developer/message'\n ? { id: String(event.data.message.id), role: 'start' }\n : null,\n start: (_context, match) => {\n const event = match.event\n if (event.type !== 'developer/message') throw new Error('developer-message start requires developer/message')\n return contextMessage(event, event.data.message)\n },\n}\n\n/**\n * Register user, steering, injected-context, and developer message contributions.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerMessageConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(messageDefinition)\n ctx.uiConversation.events.register(developerMessageDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, RequestPromptInspector,\n SystemPromptState, SystemPromptInspector,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Complete system prompt rendered for one model request, or an in-history prompt update at its own position. */\n 'system-prompt': { readonly text: string; readonly update?: true }\n }\n}\n\ninterface RequestPromptState extends ReturnType<RequestPromptInspector> {\n readonly anchorSeq: number\n readonly showsPrompt: boolean\n readonly turn?: number\n readonly step?: number\n}\n\n/** Place a request's system prompt at the start of its visible message series. */\nfunction requestPromptAnchor(\n match: ConversationMatch,\n previous: Readonly<RequestPromptState> | undefined,\n isInitial: boolean,\n): number {\n if (match.location.kind !== 'step') return match.event.seq\n if (previous === undefined && !isInitial) return match.event.seq\n if (previous?.turn === match.location.turn.turn\n && previous.step === match.location.step.step) return match.event.seq\n return match.location.step.step === 1\n ? match.location.turn.start?.seq ?? match.location.step.start?.seq ?? match.event.seq\n : match.location.step.start?.seq ?? match.event.seq\n}\n\n/** Keep an already rendered prompt at its page-lifetime presentation anchor. */\nfunction stableRequestPromptAnchor(\n context: ConversationNodeContext<RequestPromptState>,\n match: ConversationMatch,\n previous: Readonly<RequestPromptState> | undefined,\n isInitial: boolean,\n): number {\n const current = context.current.get('chat') as ChatNode | null | undefined\n return current?.kind === 'system-prompt'\n ? current.anchorSeq\n : requestPromptAnchor(match, previous, isInitial)\n}\n\n/**\n * System-prompt surface node Definition for the Chat target. It owns every\n * `system/message` event on the Chat target so the unknown-surface fallback\n * never renders the prompt as a transcript row. Each nonempty append owns a\n * prompt card, even without a loaded request header. Initial cards precede\n * their step's input; in-history updates stay at their own positions. The\n * request-prompt Definition owns replacement and later-series cards. Positional\n * replacements advance the effective prompt without changing historical cards.\n * A published node becomes `hidden` under the same key while a prepended replacement\n * leaves its prompt order unknown, and `visible` again once older history resolves it.\n * @param inspect - Pure surface interpretation supplied by uiConversation.\n * @returns The Chat system-prompt Definition.\n */\nexport function systemMessageDefinition(inspect: SystemPromptInspector): ConversationNodeDefinition<SystemPromptState> {\n return {\n kind: 'system-message',\n target: 'chat',\n match: event => event.type === 'system/message'\n || ('surfaceOp' in event && event.surfaceOp !== 'append')\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (_context, match, reader) => {\n if (match.event.type === 'assistant/live-chunk') throw new Error('system-message requires a durable event')\n return inspect(reader.previous<SystemPromptState>('system-message')?.state, match.event)\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state?.introduced\n if (state === undefined || state.text === ''\n || context.start?.event.type !== 'system/message' || context.start.event.surfaceOp !== 'append') {\n const current = context.current.get('chat') as ChatNode | null | undefined\n if (current?.kind !== 'system-prompt') return null\n return chatNode(context, 'system-prompt', current.anchorSeq, current.data, { visibility: 'hidden' })\n }\n const anchor = state.update ? state.seq : requestPromptAnchor(context.start, undefined, true)\n return chatNode(context, 'system-prompt', anchor, { text: state.text, ...state.update ? { update: true } : {} })\n },\n }\n}\n\n/**\n * Request-header prompt Definition for the Chat target. Resume and explicit\n * series starts retain a prompt card even when the system text is unchanged.\n * @param inspect - the shared prompt interpretation, supplied by the\n * uiConversation service (a client bundle cannot value-import it).\n * @returns the Chat request-prompt Definition.\n */\nexport function requestPromptDefinition(inspect: RequestPromptInspector): ConversationNodeDefinition<RequestPromptState> {\n return {\n kind: 'request-prompt',\n target: 'chat',\n match: event => event.type === 'request/header'\n ? { id: String(event.seq), role: 'start' }\n : null,\n start: (context, match, reader) => {\n if (match.event.type !== 'request/header') {\n throw new Error('request-prompt start requires request/header')\n }\n const previous = reader.previous<RequestPromptState>('request-prompt')?.state\n const systemContext = reader.previous<SystemPromptState>('system-message')\n const system = systemContext?.state.effective\n const location = match.location.kind === 'step'\n ? { turn: match.location.turn.turn, step: match.location.step.step }\n : {}\n const inspection = inspect(previous?.prompt, match.event, system)\n const change = inspection.change?.kind\n // Appended prompts own their cards; a same-step header must not repeat them.\n const systemEvent = systemContext?.matches[0]?.event\n const shownByUpdate = system !== undefined\n && systemEvent?.type === 'system/message' && systemEvent.surfaceOp === 'append'\n && (system.update || previous === undefined)\n && system.turn === location.turn\n && system.step === location.step\n return {\n anchorSeq: stableRequestPromptAnchor(\n context,\n match,\n previous,\n match.event.data.reason === 'initial',\n ),\n showsPrompt: !shownByUpdate && (previous === undefined\n || match.event.data.reason !== 'change'\n || match.event.data.startsSeries === true\n || change === 'system'\n || change === 'system-and-tools'),\n ...location,\n ...inspection,\n }\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state\n if (state === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const visible = state.showsPrompt && state.prompt.system !== ''\n if (!visible && current?.kind !== 'system-prompt') return null\n return chatNode(\n context,\n 'system-prompt',\n state.anchorSeq,\n { text: state.prompt.system },\n { visibility: visible ? 'visible' : 'hidden' },\n )\n },\n }\n}\n\n/**\n * Register the system-prompt surface node and the model-request prompt card in the Chat flow.\n * @param ctx - Owning UI Conversation context.\n */\nexport function registerRequestPromptConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(systemMessageDefinition(\n (previous, event) => ctx.uiConversation.inspectSystemPrompt(previous, event),\n ))\n ctx.uiConversation.events.register(requestPromptDefinition(\n (previous, event, system) => ctx.uiConversation.inspectRequestPrompt(previous, event, system),\n ))\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationLocation, ConversationMatch, ConversationNodeDefinition, ModelRetryNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { RetryChatData } from '../contract/chat-nodes.ts'\nimport { chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Producer-correlated model retry chain. */\n 'model-retry': RetryChatData\n }\n}\n\n/** Accumulated retry attempts sharing one producer-owned RetryId. */\nexport interface RetryState {\n readonly turn: number\n readonly step: number\n readonly attempts: readonly ModelRetryNode[]\n}\n\nfunction scheduledNode(match: ConversationMatch): ModelRetryNode | undefined {\n if (match.event.type !== 'llm/retry') return undefined\n return {\n kind: 'model-retry',\n seq: match.event.seq,\n time: match.event.time,\n retryState: 'scheduled',\n ...match.event.data,\n }\n}\n\n/** A scheduled attempt is cancelled once either owning boundary closes. */\nfunction isClosed(location: ConversationLocation): boolean {\n return (location.kind === 'step' && location.step.status === 'closed')\n || ((location.kind === 'step' || location.kind === 'turn') && location.turn.status === 'closed')\n}\n\n/** Producer-correlated model retry chain Definition. */\nexport const retryDefinition: ConversationNodeDefinition<RetryState> = {\n kind: 'model-retry',\n target: 'chat',\n match: (event) => {\n if (event.type === 'llm/retry') {\n const retryId: unknown = event.data.retryId\n if (typeof retryId !== 'string' || retryId === '') return null\n return { id: retryId, role: event.data.retry === 1 ? 'start' : 'update' }\n }\n if (event.type === 'llm/retry-started') {\n const retryId: unknown = event.data.retryId\n return typeof retryId === 'string' && retryId !== '' ? { id: retryId, role: 'update' } : null\n }\n return null\n },\n start: (_context, match) => {\n const node = scheduledNode(match)\n if (node === undefined) throw new Error('model-retry start requires a valid llm/retry event')\n return { turn: node.turn, step: node.step, attempts: [node] }\n },\n update: (context, match) => {\n if (match.event.type === 'llm/retry') {\n const node = scheduledNode(match)\n return node === undefined ? context.state : { ...context.state, attempts: [...context.state.attempts, node] }\n }\n if (match.event.type !== 'llm/retry-started') return context.state\n const retry = match.event.data.retry\n return {\n ...context.state,\n attempts: context.state.attempts.map(attempt =>\n attempt.retry === retry ? { ...attempt, retryState: 'started' } : attempt),\n }\n },\n buildViewNode: (context) => {\n if (context.state === undefined || context.state.attempts.length === 0) return null\n const location = context.start?.location ?? context.matches[0]?.location ?? { kind: 'unresolved' as const }\n const stateAttempts = context.state.attempts\n const attempts = stateAttempts.map((attempt, index) =>\n index === stateAttempts.length - 1\n && attempt.retryState === 'scheduled'\n && isClosed(location)\n ? { ...attempt, retryState: 'cancelled' as const }\n : attempt)\n const current = attempts.at(-1)\n if (current === undefined) return null\n const data: RetryChatData = { attempts, current }\n return chatNode(context, 'model-retry', attempts[0]?.seq ?? current.seq, data, { groupTree: 'process' })\n },\n}\n\n/**\n * Register the correlated model-retry business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerRetryConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(retryDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, PreparingToolCall, StartedToolCall,\n ToolCallBlock, ToolResultNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { isAppendSurfaceEvent } from '@deepseek-ai/dsh-session/surface'\nimport type {} from '@deepseek-ai/dsh-tool-executor-ptc/client'\nimport { PartialArguments } from '@deepseek-ai/dsh-util-values'\nimport type { ChatNode, ToolChatData } from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode, contextLocation } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Root Tool lifecycle with recursively nested subcalls. */\n 'tool-call': ToolChatData\n }\n}\n\nconst MAX_DEPTH = 256\n\ninterface ToolState {\n /** Absent until a named delta or `tool/call` identifies the call. */\n readonly root: ToolCallBlock | undefined\n readonly children: ReadonlyMap<string, readonly ToolCallBlock[]>\n readonly parents: ReadonlyMap<string, string>\n}\n\ninterface ProjectedBlockCache {\n readonly children: readonly ToolCallBlock[]\n readonly interruptionSeq: number | undefined\n readonly interruptionTime: number | undefined\n readonly value: ToolCallBlock\n}\n\nconst projectedBlocks = new WeakMap<ToolCallBlock, ProjectedBlockCache>()\n\nfunction jsonArguments(value: unknown): string {\n return JSON.stringify(value)\n}\n\nfunction rootCall(match: ConversationMatch, previous?: ToolCallBlock): StartedToolCall {\n if (match.event.type !== 'tool/call') throw new Error('tool-call start requires tool/call')\n return {\n phase: 'start',\n callId: String(match.event.data.callId),\n name: match.event.data.name,\n argsRaw: match.event.data.arguments,\n args: previous === undefined\n ? PartialArguments.fromText(match.event.data.arguments)\n : previous.args.settle(match.event.data.arguments),\n turn: match.event.data.turn,\n step: match.event.data.step,\n time: match.event.time,\n subCalls: [],\n }\n}\n\n/**\n * Retain argument fragments in the named call's lazy view. Root replacement\n * belongs to publication, after all pending fragments can be observed together.\n */\nfunction applyDelta(state: ToolState, match: ConversationMatch): ToolState {\n const event = match.event\n if (event.type !== 'assistant/live-chunk') return state\n const chunk = event.data.chunk\n const root = state.root\n if (chunk.type === 'block-end' && chunk.block.type === 'tool-call') {\n if (root === undefined || 'kind' in root || root.phase !== 'preparing') return state\n return { ...state, root: { ...root, name: chunk.block.name, args: root.args.settle(chunk.block.arguments) } }\n }\n if (chunk.type !== 'tool-call-delta') return state\n if (root === undefined) {\n // An unnamed delta before the name is skipped; a view opened late sees a non-object prefix and reports nothing.\n if (!chunk.name) return state\n const args = new PartialArguments()\n args.append(chunk.argumentsDelta)\n return {\n ...state,\n root: {\n phase: 'preparing',\n callId: String(chunk.id), name: chunk.name,\n turn: event.data.turn, step: event.data.step, time: event.time,\n subCalls: [],\n args,\n },\n }\n }\n if ('kind' in root || root.phase !== 'preparing' || root.args.isSealed) return state\n root.args.append(chunk.argumentsDelta)\n return state\n}\n\nfunction preparingBlock(root: PreparingToolCall, current: ToolCallBlock | undefined): PreparingToolCall {\n const changed = root.args.refresh()\n if (!changed && current !== undefined && !('kind' in current)\n && current.phase === 'preparing' && current.name === root.name && current.args === root.args) return current\n return changed ? { ...root } : root\n}\n\nfunction rootResult(match: ConversationMatch, previous?: StartedToolCall): ToolResultNode | undefined {\n if (match.event.type !== 'tool/result') return undefined\n const message = match.event.data.message\n return {\n kind: 'tool-result',\n seq: match.event.seq,\n time: match.event.time,\n callId: String(message.source.callId),\n name: previous?.name ?? '',\n args: previous?.args ?? PartialArguments.EMPTY,\n call: previous === undefined ? null : { name: previous.name, argsRaw: previous.argsRaw },\n callTime: previous?.time ?? null,\n content: message.content,\n isError: message.isError === true,\n ...match.event.data.error === undefined ? {} : { error: match.event.data.error },\n meta: match.event.data.meta,\n subCalls: [],\n }\n}\n\ninterface DispatchData {\n readonly parentCallId: string\n readonly subCallId: string\n readonly name: string\n readonly arguments: unknown\n readonly isError?: boolean\n readonly error?: { name: string; code: string; reason?: string }\n readonly content?: ToolResultNode['content']\n readonly meta?: ToolResultNode['meta']\n}\n\nfunction childCall(match: ConversationMatch, data: DispatchData): StartedToolCall {\n return {\n phase: 'start',\n callId: data.subCallId,\n parentCallId: data.parentCallId,\n name: data.name,\n argsRaw: jsonArguments(data.arguments),\n args: PartialArguments.fromObject(data.arguments),\n turn: locationTurn(match),\n step: locationStep(match),\n time: match.event.time,\n subCalls: [],\n }\n}\n\nfunction childResult(match: ConversationMatch, data: DispatchData, previous?: ToolCallBlock): ToolResultNode {\n return {\n kind: 'tool-result',\n seq: match.event.seq,\n time: match.event.time,\n callId: data.subCallId,\n parentCallId: data.parentCallId,\n name: data.name,\n args: previous !== undefined && !('kind' in previous) ? previous.args : PartialArguments.fromObject(data.arguments),\n call: { name: data.name, argsRaw: jsonArguments(data.arguments) },\n callTime: previous?.time ?? null,\n content: data.content ?? [],\n meta: data.meta,\n isError: data.isError === true,\n ...data.error === undefined ? {} : { error: data.error },\n subCalls: [],\n }\n}\n\nfunction locationTurn(match: ConversationMatch): number {\n return match.location.kind === 'step' || match.location.kind === 'turn' ? match.location.turn.turn : 0\n}\n\nfunction locationStep(match: ConversationMatch): number {\n return match.location.kind === 'step' ? match.location.step.step : 0\n}\n\nfunction acceptsEdge(state: ToolState, parent: string, child: string): boolean {\n if (parent === child || state.parents.has(child)) return false\n let cursor: string | undefined = parent\n let parentDepth = 0\n const ancestors = new Set<string>()\n while (cursor !== undefined) {\n if (cursor === child || ancestors.has(cursor)) return false\n ancestors.add(cursor)\n parentDepth++\n cursor = state.parents.get(cursor)\n }\n const pending = [{ callId: child, depth: 1 }]\n const descendants = new Set<string>()\n let subtreeDepth = 0\n for (const candidate of pending) {\n if (descendants.has(candidate.callId)) return false\n descendants.add(candidate.callId)\n subtreeDepth = Math.max(subtreeDepth, candidate.depth)\n for (const nested of state.children.get(candidate.callId) ?? []) {\n pending.push({ callId: nested.callId, depth: candidate.depth + 1 })\n }\n }\n return parentDepth + subtreeDepth <= MAX_DEPTH\n}\n\nfunction updateDispatch(state: ToolState, match: ConversationMatch): ToolState {\n const event = match.event\n if (event.type !== 'tool/ptc-dispatch-start' && event.type !== 'tool/ptc-dispatch') return state\n const data = event.data\n const parentCallId = String(data.parentCallId)\n const subCallId = String(data.subCallId)\n const siblings = state.children.get(parentCallId) ?? []\n const index = siblings.findIndex(candidate => candidate.callId === subCallId)\n if (event.type === 'tool/ptc-dispatch-start') {\n if (index >= 0 || !acceptsEdge(state, parentCallId, subCallId)) return state\n const children = new Map(state.children)\n children.set(parentCallId, [...siblings, childCall(match, data)])\n const parents = new Map(state.parents)\n parents.set(subCallId, parentCallId)\n return { ...state, children, parents }\n }\n if (index < 0 && !acceptsEdge(state, parentCallId, subCallId)) return state\n const previous = index < 0 ? undefined : siblings[index]\n const settled = childResult(match, data, previous)\n const children = new Map(state.children)\n children.set(parentCallId, index < 0\n ? [...siblings, settled]\n : siblings.map((child, at) => at === index ? settled : child))\n const parents = new Map(state.parents)\n if (index < 0) parents.set(subCallId, parentCallId)\n return { ...state, children, parents }\n}\n\nfunction projectBlock(\n block: ToolCallBlock,\n state: ToolState,\n interruptedAt: { seq: number; time: number } | undefined,\n visited = new Set<string>(),\n depth = 1,\n): ToolCallBlock {\n if (!('kind' in block) && block.phase === 'preparing') return block\n if (visited.has(block.callId) || depth > MAX_DEPTH) return { ...block, subCalls: [] }\n const nextVisited = new Set(visited)\n nextVisited.add(block.callId)\n const children = (state.children.get(block.callId) ?? block.subCalls)\n .map(child => projectBlock(child, state, interruptedAt, nextVisited, depth + 1))\n const interruptionSeq = 'kind' in block ? undefined : interruptedAt?.seq\n const interruptionTime = 'kind' in block ? undefined : interruptedAt?.time\n const cached = projectedBlocks.get(block)\n if (cached !== undefined\n && cached.interruptionSeq === interruptionSeq\n && cached.interruptionTime === interruptionTime\n && sameReferences(cached.children, children)) {\n return cached.value\n }\n const projected: ToolCallBlock = 'kind' in block || interruptedAt === undefined\n ? sameReferences(block.subCalls, children) ? block : { ...block, subCalls: children }\n : {\n kind: 'tool-result',\n seq: interruptedAt.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.interruptedFollowup,\n time: interruptedAt.time,\n callId: block.callId,\n ...block.parentCallId === undefined ? {} : { parentCallId: block.parentCallId },\n name: block.name,\n args: block.args,\n call: { name: block.name, argsRaw: block.argsRaw },\n callTime: block.time,\n content: [],\n isError: true,\n error: { name: 'Interrupted', code: 'interrupted' },\n subCalls: children,\n }\n projectedBlocks.set(block, { children, interruptionSeq, interruptionTime, value: projected })\n return projected\n}\n\nfunction sameReferences<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction interruption(context: ConversationNodeContext<ToolState>): { seq: number; time: number } | undefined {\n const location = context.start?.location\n if (location?.kind === 'step' && location.step.status === 'closed') return location.step.end\n if ((location?.kind === 'step' || location?.kind === 'turn') && location.turn.status === 'closed') {\n return location.turn.end\n }\n return undefined\n}\n\nfunction fallbackState(context: ConversationNodeContext<ToolState>): ToolState | undefined {\n const match = context.matches.find(candidate => candidate.event.type === 'tool/result')\n const root = match === undefined ? undefined : rootResult(match)\n if (root === undefined) return undefined\n let state: ToolState = { root, children: new Map(), parents: new Map() }\n for (const candidate of context.matches) state = updateDispatch(state, candidate)\n return state\n}\n\n/** Root Tool preparation, dispatch, result, and nested PTC calls. */\nexport const toolDefinition: ConversationNodeDefinition<ToolState> = {\n kind: 'tool-call',\n target: 'chat',\n match: (event) => {\n if (event.type === 'assistant/live-chunk') {\n // Every delta of a call is a start candidate: the earliest opens the Context, later ones fold as updates.\n const chunk = event.data.chunk\n if (chunk.type === 'block-end' && chunk.block.type === 'tool-call') {\n return { id: String(chunk.block.id), role: 'start' }\n }\n return chunk.type === 'tool-call-delta' ? { id: String(chunk.id), role: 'start' } : null\n }\n if (event.type === 'tool/call') return { id: String(event.data.callId), role: 'start' }\n if (event.type === 'tool/result' && isAppendSurfaceEvent(event)) {\n return { id: String(event.data.message.source.callId), role: 'update' }\n }\n if (event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') {\n const rootCallId: unknown = event.data.rootCallId\n return typeof rootCallId === 'string' && rootCallId !== ''\n ? { id: rootCallId, role: 'update' }\n : null\n }\n return null\n },\n start: (_context, match) => {\n const state: ToolState = { root: undefined, children: new Map(), parents: new Map() }\n return match.event.type === 'tool/call' ? { ...state, root: rootCall(match) } : applyDelta(state, match)\n },\n update: (context, match) => {\n if (match.event.type === 'assistant/live-chunk') return applyDelta(context.state, match)\n if (match.event.type === 'tool/call') return { ...context.state, root: rootCall(match, context.state.root) }\n if (match.event.type === 'tool/result') {\n const root = context.state.root\n const running = root !== undefined && !('kind' in root) && root.phase === 'start' ? root : undefined\n const result = rootResult(match, running)\n return result === undefined ? context.state : { ...context.state, root: result }\n }\n return updateDispatch(context.state, match)\n },\n publication: match => match.event.type === 'assistant/live-chunk' ? 'animation-frame' : 'immediate',\n buildViewNode: (context) => {\n const current = context.current.get('chat') as ChatNode<'tool-call'> | null | undefined\n const state = context.state ?? fallbackState(context)\n if (state?.root === undefined) {\n return current == null ? null : current.visibility === 'hidden' ? current : { ...current, visibility: 'hidden' }\n }\n const interruptedAt = interruption(context)\n const root = !('kind' in state.root) && state.root.phase === 'preparing'\n ? preparingBlock(state.root, current?.data.root)\n : state.root\n const projected = projectBlock(root, state, interruptedAt)\n const anchor = context.start?.event.seq\n ?? ('kind' in state.root ? state.root.seq : context.matches[0]?.event.seq ?? 0)\n const preparing = !('kind' in projected) && projected.phase === 'preparing'\n const visibility = preparing && interruptedAt !== undefined ? 'hidden' : 'visible'\n const location = contextLocation(context)\n const data = current?.data.root === projected ? current.data : { root: projected } satisfies ToolChatData\n if (current?.data === data && current.anchorSeq === anchor\n && current.visibility === visibility && current.location === location) return current\n return chatNode(context, 'tool-call', anchor, data, { visibility, location })\n },\n}\n\n/**\n * Register the root Tool lifecycle and nested-subcall contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerToolConversationNode(ctx: Context): void {\n const match = toolDefinition.match.bind(toolDefinition)\n ctx.uiConversation.events.register({\n ...toolDefinition,\n match: {\n 'assistant/live-chunk': match,\n 'tool/call': match,\n 'tool/result': match,\n 'tool/ptc-dispatch-start': match,\n 'tool/ptc-dispatch': match,\n },\n })\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnErrorNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { TurnEndReason } from '@deepseek-ai/dsh-session/types'\nimport { chatNode } from './common.ts'\nimport { displayFailure } from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Terminal turn failure recorded on the turn's end reason. */\n 'turn-error': TurnErrorNode\n }\n}\n\ninterface TurnErrorState {\n readonly turn: number\n readonly failure?: {\n readonly seq: number\n readonly time: number\n readonly message: string\n readonly code?: string\n }\n}\n\nfunction lastStep(context: ConversationNodeContext<TurnErrorState>): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return 0\n return location.turn.steps.at(-1)?.step ?? 0\n}\n\n/**\n * Failure shown for a turn ending: a recorded error, a sign-out cancellation,\n * or a turn that restart recovery closed because the DSH process exited mid-turn.\n */\nfunction endFailure(reason: TurnEndReason): { readonly message: string; readonly code?: string } | undefined {\n switch (reason.kind) {\n case 'error':\n return reason.error\n case 'aborted':\n // User and parent cancellations show only the stopped turn summary.\n return reason.reason.kind === 'hook' && reason.reason.reason === 'deepseek-account/signed-out'\n ? { message: 'Stopped because you signed out of DeepSeek.', code: 'ACCOUNT_SIGNED_OUT' }\n : undefined\n case 'interrupted':\n return { message: 'The DSH process exited before this turn finished.', code: 'INTERRUPTED' }\n default:\n // Completed, blocked, max-tokens, forked, and plugin-merged endings have no failure row.\n return undefined\n }\n}\n\nfunction failureFrom(match: ConversationMatch): TurnErrorState['failure'] | undefined {\n if (match.event.type !== 'turn/end') return undefined\n const failure = endFailure(match.event.data.reason)\n if (failure === undefined) return undefined\n const display = displayFailure(failure)\n return {\n seq: match.event.seq,\n time: match.event.time,\n message: display.message,\n ...(display.code === undefined ? {} : { code: display.code }),\n }\n}\n\nfunction fallbackState(context: ConversationNodeContext<TurnErrorState>): TurnErrorState | undefined {\n const end = context.matches.find(match => failureFrom(match) !== undefined)\n if (end?.event.type !== 'turn/end') return undefined\n const failure = failureFrom(end)\n if (failure === undefined) return undefined\n return { turn: end.event.data.turn, failure }\n}\n\n/**\n * Terminal turn failure Definition. Retries run inside the failing turn, so the\n * turn's `llm/retry` history never suppresses this terminal row; the model-retry\n * node renders that history separately.\n */\nexport const turnErrorDefinition: ConversationNodeDefinition<TurnErrorState> = {\n kind: 'turn-error',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n if (event.type === 'turn/end' && endFailure(event.data.reason) !== undefined) {\n return { id: String(event.data.turn), role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-error start requires turn/start')\n return { turn: match.event.data.turn }\n },\n update: (context, match) => {\n const failure = failureFrom(match)\n return failure === undefined ? context.state : { ...context.state, failure }\n },\n buildViewNode: (context) => {\n const state = context.state ?? fallbackState(context)\n if (state?.failure === undefined) return null\n const failure = state.failure\n const node: TurnErrorNode = {\n kind: 'turn-error',\n seq: failure.seq,\n time: failure.time,\n turn: state.turn,\n step: lastStep(context),\n message: failure.message,\n ...failure.code === undefined ? {} : { code: failure.code },\n }\n return chatNode(context, 'turn-error', node.seq, node, { groupTree: 'turn' })\n },\n}\n\n/**\n * Register the terminal Turn-error business contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnErrorConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(turnErrorDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnMaxTokensNode,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Turn ended by the per-request output-token cap. */\n 'turn-max-tokens': TurnMaxTokensNode\n }\n}\n\ninterface TurnMaxTokensState {\n readonly turn: number\n readonly seq: number\n readonly time: number\n}\n\nfunction lastStep(context: ConversationNodeContext<TurnMaxTokensState>): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return 0\n return location.turn.steps.at(-1)?.step ?? 0\n}\n\n/**\n * Anchor the notice between the closing Assistant and the turn-tail so the\n * tail stays the turn's last Chat node and keeps its branch action enabled.\n * Without a closing text Assistant there is no branch action to protect, and\n * the turn/end seq keeps the notice at the truncation point.\n */\nfunction noticeAnchor(context: ConversationNodeContext<TurnMaxTokensState>, seq: number): number {\n const location = context.start?.location ?? context.matches[0]?.location\n if (location?.kind !== 'turn' && location?.kind !== 'step') return seq\n const closing = location.turn.data.get('turn-tail')?.closing\n return closing === null || closing === undefined\n ? seq\n : closing.finalNode.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.maxTokensNotice\n}\n\nfunction stateFrom(match: ConversationMatch): TurnMaxTokensState | undefined {\n if (match.event.type !== 'turn/end' || match.event.data.reason.kind !== 'max-tokens') return undefined\n return { turn: match.event.data.turn, seq: match.event.seq, time: match.event.time }\n}\n\n/** Notice Definition for a turn the provider ended at its output-token cap. */\nexport const turnMaxTokensDefinition: ConversationNodeDefinition<TurnMaxTokensState> = {\n kind: 'turn-max-tokens',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/end' && event.data.reason.kind === 'max-tokens') {\n return { id: String(event.data.turn), role: 'start' }\n }\n return null\n },\n start: (_context, match) => {\n const state = stateFrom(match)\n if (state === undefined) throw new Error('turn-max-tokens start requires a max-tokens turn/end')\n return state\n },\n update: context => context.state,\n buildViewNode: (context) => {\n const state = context.state\n if (state === undefined) return null\n const node: TurnMaxTokensNode = {\n kind: 'turn-max-tokens',\n seq: state.seq,\n time: state.time,\n turn: state.turn,\n step: lastStep(context),\n }\n return chatNode(context, 'turn-max-tokens', noticeAnchor(context, state.seq), node, { groupTree: 'turn' })\n },\n}\n\n/**\n * Register the max-tokens turn-end notice contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnMaxTokensConversationNode(ctx: Context): void {\n ctx.uiConversation.events.register(turnMaxTokensDefinition)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationLocation, ConversationNodeContext, ConversationNodeDefinition, TurnLocation,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { StreamChunk } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-tool-executor-ptc/client'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport type { AssistantChatData, ChatNode, FinalAssistantChatData } from '../contract/chat-nodes.ts'\nimport {\n isSubagentDelegationTool, sameTurnProcessSpec, type TurnProcessSpec,\n} from '../contract/turn-process.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\nimport { toAssistantBlocks } from './event-projection.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Turn-level disclosure controlling process rows before the finalized answer. */\n 'turn-process': import('../contract/chat-nodes.ts').TurnProcessChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationTurnDataMap {\n /** Process range and finalized answer boundary for this Turn. */\n 'turn-process': TurnProcessSpec\n }\n}\n\ninterface TurnProcessState {\n readonly turn: number\n readonly assistantStartByStep: ReadonlyMap<number, number>\n readonly messageCountByStep: ReadonlyMap<number, number>\n readonly otherStartSeq?: number\n readonly controlAnchorSeq?: number\n readonly messageCount: number\n readonly toolCallCount: number\n readonly subagentCount: number\n}\n\ntype ConversationEvent = Parameters<ConversationNodeDefinition['match']>[0]\n\nfunction eventTurn(event: ConversationEvent): number | undefined {\n const data = event.data as unknown as { turn?: unknown }\n return typeof data.turn === 'number' ? data.turn : undefined\n}\n\nfunction visibleChunk(chunk: StreamChunk): boolean {\n if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') return chunk.text.trim() !== ''\n if (chunk.type === 'block-start') {\n return chunk.blockType !== 'text'\n && chunk.blockType !== 'reasoning'\n && chunk.blockType !== 'tool-call'\n }\n if (chunk.type !== 'block-end') return false\n const block = chunk.block\n if (block.type === 'tool-call') return false\n if (block.type === 'text' || block.type === 'reasoning') return block.text.trim() !== ''\n return true\n}\n\nfunction visibleAssistantEvent(event: ConversationEvent): boolean {\n if (event.type === 'assistant/live-chunk') return visibleChunk(event.data.chunk)\n if (event.type === 'assistant/attempt') return false\n return event.type === 'assistant/message'\n && event.surfaceOp === 'append'\n && toAssistantBlocks(event.data.message.content).some((block) => {\n if (block.kind === 'tool-call') return false\n if (block.kind === 'text' || block.kind === 'reasoning') return block.text.trim() !== ''\n return true\n })\n}\n\ntype ProcessEvidence =\n | { readonly kind: 'assistant'; readonly seq: number; readonly step: number }\n | { readonly kind: 'other'; readonly seq: number }\n\nfunction processEvidence(event: ConversationEvent): ProcessEvidence | undefined {\n if (visibleAssistantEvent(event)) {\n if (event.type !== 'assistant/live-chunk'\n && event.type !== 'assistant/message'\n && event.type !== 'assistant/attempt') return undefined\n return { kind: 'assistant', seq: event.seq, step: event.data.step }\n }\n if (event.type === 'tool/call'\n || (event.type === 'tool/result' && event.surfaceOp === 'append')\n || event.type === 'llm/retry') return { kind: 'other', seq: event.seq }\n return undefined\n}\n\n/** Turn of one Step that recorded durable process evidence. */\nexport interface ProcessEvidenceState {\n readonly turn: number\n}\n\nfunction durableEvidenceStep(event: ConversationEvent): { readonly turn: number; readonly step: number } | undefined {\n if (processEvidence(event) === undefined) return undefined\n switch (event.type) {\n case 'assistant/message':\n case 'tool/call':\n case 'tool/result':\n case 'llm/retry':\n return { turn: event.data.turn, step: event.data.step }\n default:\n return undefined\n }\n}\n\n/**\n * State-only record of each Step whose durable events include process evidence, keyed by Turn and Step.\n * An input follows its Turn's process control exactly when its Turn recorded evidence before it, so an\n * input reads the nearest earlier record through `reader.previous`. A Step's evidence is logged before\n * a later Step admits input, so the record a later input reads no longer changes; transient live chunks\n * are not needed because a Step's durable settlement precedes the next Step's input.\n */\nexport const processEvidenceDefinition: ConversationNodeDefinition<ProcessEvidenceState> = {\n kind: 'process-evidence',\n match: (event) => {\n const coordinates = durableEvidenceStep(event)\n return coordinates === undefined ? null : { id: `${coordinates.turn}:${coordinates.step}`, role: 'start' }\n },\n start: (_context, match) => {\n const coordinates = durableEvidenceStep(match.event)\n if (coordinates === undefined) throw new Error('process-evidence start requires durable process evidence')\n return { turn: coordinates.turn }\n },\n update: context => context.state,\n publication: () => 'none',\n}\n\nfunction turnLocation(context: ConversationNodeContext<TurnProcessState>): TurnLocation | undefined {\n const location: ConversationLocation | undefined = context.start?.location ?? context.matches.at(-1)?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n}\n\nfunction fallbackState(context: ConversationNodeContext<TurnProcessState>): TurnProcessState | undefined {\n const turn = context.matches.map(match => eventTurn(match.event)).find(candidate => candidate !== undefined)\n if (turn === undefined) return undefined\n let state: TurnProcessState = {\n turn,\n assistantStartByStep: new Map(),\n messageCountByStep: new Map(),\n messageCount: 0,\n toolCallCount: 0,\n subagentCount: 0,\n }\n for (const match of context.matches) state = updateProcessState(state, match.event)\n return state\n}\n\nfunction isFinalAssistant(\n data: Readonly<AssistantChatData> | undefined,\n): data is Readonly<FinalAssistantChatData> {\n return data?.finalNode !== undefined\n}\n\nfunction latestAnswer(turn: TurnLocation): Readonly<FinalAssistantChatData> | null {\n const latestStep = turn.steps.at(-1)\n const data: Readonly<AssistantChatData> | undefined = latestStep?.data.get('assistant-step')\n if (!isFinalAssistant(data) || !hasAssistantReplyContent(data.blocks)) return null\n return data.blocks.some(block => block.kind === 'tool-call') ? null : data\n}\n\nfunction processSpec(state: TurnProcessState, turn: TurnLocation): TurnProcessSpec | null {\n const controlAnchorSeq = state.controlAnchorSeq ?? turn.start?.seq\n if (controlAnchorSeq === undefined) return null\n const answer = latestAnswer(turn)\n const counts = {\n messageCount: answer === null\n ? state.messageCount\n : [...state.messageCountByStep]\n .filter(([step]) => step < answer.step)\n .reduce((total, [, count]) => total + count, 0),\n toolCallCount: state.toolCallCount,\n subagentCount: state.subagentCount,\n }\n if (answer === null) {\n return {\n turn: turn.turn,\n controlAnchorSeq,\n processStartSeq: controlAnchorSeq,\n answerAnchorSeq: null,\n answerStep: null,\n inlineReasoning: false,\n ...counts,\n }\n }\n const inlineReasoning = answer.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '')\n const earlierAssistantSeq = Math.min(\n ...[...state.assistantStartByStep]\n .filter(([step]) => step < answer.step)\n .map(([, seq]) => seq),\n )\n const externalProcessSeq = Math.min(\n state.otherStartSeq ?? Number.POSITIVE_INFINITY,\n earlierAssistantSeq,\n )\n return {\n turn: turn.turn,\n controlAnchorSeq,\n processStartSeq: turn.start?.seq\n ?? (Number.isFinite(externalProcessSeq) ? externalProcessSeq : answer.finalNode.seq),\n answerAnchorSeq: answer.finalNode.seq,\n answerStep: answer.step,\n inlineReasoning,\n ...counts,\n }\n}\n\nfunction updateProcessState(state: TurnProcessState, event: ConversationEvent): TurnProcessState {\n let current = state\n if (event.type === 'assistant/message'\n && event.surfaceOp === 'append'\n && hasAssistantReplyContent(toAssistantBlocks(event.data.message.content))) {\n const messageCountByStep = new Map(current.messageCountByStep)\n messageCountByStep.set(event.data.step, (messageCountByStep.get(event.data.step) ?? 0) + 1)\n current = { ...current, messageCountByStep, messageCount: current.messageCount + 1 }\n }\n if (event.type === 'tool/call') {\n const subagent = isSubagentDelegationTool(event.data.name)\n current = {\n ...current,\n toolCallCount: current.toolCallCount + (subagent ? 0 : 1),\n subagentCount: current.subagentCount + (subagent ? 1 : 0),\n }\n }\n const evidence = processEvidence(event)\n if (evidence === undefined) return current\n if (evidence.kind === 'other') {\n return current.otherStartSeq === undefined\n ? {\n ...current,\n otherStartSeq: evidence.seq,\n controlAnchorSeq: Math.min(current.controlAnchorSeq ?? Number.POSITIVE_INFINITY, evidence.seq),\n }\n : current\n }\n if (current.assistantStartByStep.has(evidence.step)) return current\n const assistantStartByStep = new Map(current.assistantStartByStep)\n assistantStartByStep.set(evidence.step, evidence.seq)\n return {\n ...current,\n assistantStartByStep,\n controlAnchorSeq: Math.min(current.controlAnchorSeq ?? Number.POSITIVE_INFINITY, evidence.seq),\n }\n}\n\n/** Turn-scoped process range and answer-boundary Definition. */\nexport const turnProcessDefinition: ConversationNodeDefinition<TurnProcessState> = {\n kind: 'turn-process',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n const turn = eventTurn(event)\n if (turn === undefined) return null\n if (event.type === 'assistant/live-chunk'\n || event.type === 'assistant/message'\n || event.type === 'tool/call'\n || event.type === 'tool/result'\n || event.type === 'llm/retry'\n || event.type === 'step/start'\n || event.type === 'step/end'\n || event.type === 'turn/end') {\n return { id: String(turn), role: 'update' }\n }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-process start requires turn/start')\n return {\n turn: match.event.data.turn,\n assistantStartByStep: new Map(),\n messageCountByStep: new Map(),\n messageCount: 0,\n toolCallCount: 0,\n subagentCount: 0,\n }\n },\n update: (context, match) => updateProcessState(context.state, match.event),\n publication: (match) => {\n if (match.event.type === 'assistant/live-chunk') {\n const type = match.event.data.chunk.type\n return type === 'usage' || type === 'finish' ? 'none' : 'animation-frame'\n }\n return 'immediate'\n },\n buildLocationData: (context, scope, previous) => {\n if (scope !== 'turn') return null\n const state = context.state ?? fallbackState(context)\n if (state === undefined) return null\n const turn = turnLocation(context)\n if (turn === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const latestStep = turn.steps.at(-1)\n if (previous?.kind === 'turn'\n && previous.key === 'turn-process'\n && current?.kind === 'turn-process'\n && current.data.answerAnchorSeq === null\n && current.data.controlAnchorSeq === state.controlAnchorSeq\n && current.data.messageCount === state.messageCount\n && current.data.toolCallCount === state.toolCallCount\n && current.data.subagentCount === state.subagentCount\n && turn.status !== 'closed'\n && latestStep?.status !== 'closed') return previous\n const spec = processSpec(state, turn)\n if (spec === null) return null\n if (previous?.kind === 'turn'\n && previous.turn === spec.turn\n && previous.key === 'turn-process'\n && sameTurnProcessSpec(previous.value, spec)) return previous\n return {\n kind: 'turn',\n turn: turn.turn,\n key: 'turn-process',\n value: spec,\n }\n },\n buildViewNode: (context) => {\n const turn = turnLocation(context)\n const data = turn?.data.get('turn-process')\n if (turn === undefined || data === undefined) return null\n const current = context.current.get('chat') as ChatNode | null | undefined\n const state = context.state\n if (current?.kind === 'turn-process'\n && state !== undefined\n && current.data.answerAnchorSeq === null\n && current.data.controlAnchorSeq === state.controlAnchorSeq\n && current.data.messageCount === state.messageCount\n && current.data.toolCallCount === state.toolCallCount\n && current.data.subagentCount === state.subagentCount\n && turn.status !== 'closed'\n && turn.steps.at(-1)?.status !== 'closed'\n && current.location === (context.start?.location ?? context.matches[0]?.location)) return current\n return chatNode(\n context,\n 'turn-process',\n data.controlAnchorSeq + CHAT_SYNTHETIC_SEQ_OFFSETS.processControl,\n data,\n { groupTree: 'turn' },\n )\n },\n}\n\n/**\n * Register the Turn-scoped process disclosure projection and its per-Step evidence record.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnProcess(ctx: Context): void {\n const match = turnProcessDefinition.match.bind(turnProcessDefinition)\n ctx.uiConversation.events.register({\n ...turnProcessDefinition,\n match: {\n 'turn/start': match,\n 'assistant/live-chunk': match,\n 'assistant/message': match,\n 'tool/call': match,\n 'tool/result': match,\n 'llm/retry': match,\n 'step/start': match,\n 'step/end': match,\n 'turn/end': match,\n },\n })\n const evidence = processEvidenceDefinition.match.bind(processEvidenceDefinition)\n ctx.uiConversation.events.register({\n ...processEvidenceDefinition,\n match: {\n 'assistant/message': evidence,\n 'tool/call': evidence,\n 'tool/result': evidence,\n 'llm/retry': evidence,\n },\n })\n}\n","/**\n * Lossless compact representation of one model-stream attempt, plus record-level\n * readers that answer common consumer questions without materializing members.\n * Readers trust the static record type; expandAssistantStream is the validating\n * path for records read at a durable boundary.\n */\n\nimport { assertNever, deepFreeze, snapshotJsonValue } from '@deepseek-ai/dsh-util-values'\nimport { BlockAssembler } from './assembler.ts'\nimport type { ToolCallId } from './brand.ts'\nimport type { ContentBlock, StreamChunk } from './types.ts'\n\n/** One model chunk paired with its original Session timestamp. */\nexport interface TimedStreamChunk {\n readonly time: number\n readonly chunk: StreamChunk\n}\n\n/** Lossless compact records embedded in durable Assistant attempt events. */\nexport type AssistantStreamRecord =\n | {\n readonly type: 'text-chunks'\n readonly time0: number\n readonly index: number\n readonly dt: readonly number[]\n readonly texts: readonly string[]\n }\n | {\n readonly type: 'reasoning-chunks'\n readonly time0: number\n readonly index: number\n readonly dt: readonly number[]\n readonly texts: readonly string[]\n }\n | {\n readonly type: 'tool-call-chunks'\n readonly time0: number\n readonly index: number\n readonly dt: readonly number[]\n readonly id: ToolCallId\n readonly name?: string\n readonly args: readonly string[]\n }\n | { readonly type: 'chunk'; readonly time: number; readonly chunk: StreamChunk }\n\n/** One packed delta run: every compact record except a raw `chunk`. */\nexport type AssistantStreamRun = Exclude<AssistantStreamRecord, { type: 'chunk' }>\n\n/**\n * Chunk types the accumulator never packs into runs, so every occurrence is a raw\n * `chunk` record. Delta types are excluded because their packed members are not raw chunks.\n */\nexport type RawStreamChunkType = Exclude<StreamChunk['type'], 'text-delta' | 'reasoning-delta' | 'tool-call-delta'>\n\ntype MutableRecord =\n | {\n type: 'text-chunks' | 'reasoning-chunks'\n time0: number\n index: number\n dt: number[]\n texts: string[]\n lastTime: number\n }\n | {\n type: 'tool-call-chunks'\n time0: number\n index: number\n dt: number[]\n id: ToolCallId\n name?: string\n args: string[]\n lastTime: number\n }\n | { type: 'chunk'; time: number; chunk: StreamChunk }\n\nfunction safeTime(value: number): number {\n if (!Number.isSafeInteger(value)) throw new TypeError(`Assistant stream time must be a safe integer, got ${String(value)}`)\n return value\n}\n\nfunction safeIndex(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {\n throw new TypeError(`${label} index must be a non-negative safe integer`)\n }\n return value\n}\n\nfunction snapshotChunk(chunk: StreamChunk): StreamChunk {\n const snapshot = snapshotJsonValue(chunk)\n if (snapshot === undefined) throw new TypeError('Assistant stream chunk must be losslessly JSON-serializable')\n return snapshot\n}\n\nfunction safeGap(previous: number, next: number): number | undefined {\n const gap = next - previous\n return Number.isSafeInteger(gap) && previous + gap === next ? gap : undefined\n}\n\n/** Incrementally compacts one attempt without retaining a second raw-chunk list. */\nexport class AssistantStreamAccumulator {\n private readonly records: MutableRecord[] = []\n\n /**\n * Add one timed chunk to the compact attempt stream.\n * @param value - model chunk and its original Session timestamp.\n * @returns a detached immutable copy for assembly and live publication.\n */\n push(value: TimedStreamChunk): TimedStreamChunk {\n const time = safeTime(value.time)\n const chunk = snapshotChunk(value.chunk)\n const timed = deepFreeze({ time, chunk })\n const previous = this.records.at(-1)\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta': {\n safeIndex(chunk.index, chunk.type)\n if (typeof chunk.text !== 'string') throw new TypeError(`${chunk.type} text must be a string`)\n const type = chunk.type === 'text-delta' ? 'text-chunks' : 'reasoning-chunks'\n const gap = previous !== undefined && previous.type === type ? safeGap(previous.lastTime, time) : undefined\n if (previous !== undefined && previous.type === type && previous.index === chunk.index && gap !== undefined) {\n previous.dt.push(gap)\n previous.texts.push(chunk.text)\n previous.lastTime = time\n } else {\n this.records.push({ type, time0: time, index: chunk.index, dt: [], texts: [chunk.text], lastTime: time })\n }\n return timed\n }\n case 'tool-call-delta': {\n safeIndex(chunk.index, chunk.type)\n if (typeof chunk.id !== 'string') throw new TypeError('tool-call-delta id must be a string')\n if (Object.hasOwn(chunk, 'name') && typeof chunk.name !== 'string') {\n throw new TypeError('tool-call-delta name must be a string')\n }\n if (typeof chunk.argumentsDelta !== 'string') {\n throw new TypeError('tool-call-delta argumentsDelta must be a string')\n }\n if (chunk.id.length === 0 || chunk.name === '') {\n this.records.push({ type: 'chunk', time, chunk })\n return timed\n }\n const gap = previous?.type === 'tool-call-chunks' ? safeGap(previous.lastTime, time) : undefined\n const sameName = previous?.type === 'tool-call-chunks'\n && Object.hasOwn(previous, 'name') === Object.hasOwn(chunk, 'name')\n && previous.name === chunk.name\n if (previous?.type === 'tool-call-chunks'\n && previous.index === chunk.index\n && previous.id === chunk.id\n && sameName\n && gap !== undefined) {\n previous.dt.push(gap)\n previous.args.push(chunk.argumentsDelta)\n previous.lastTime = time\n } else {\n this.records.push({\n type: 'tool-call-chunks',\n time0: time,\n index: chunk.index,\n dt: [],\n id: chunk.id,\n ...Object.hasOwn(chunk, 'name') ? { name: chunk.name } : {},\n args: [chunk.argumentsDelta],\n lastTime: time,\n })\n }\n return timed\n }\n case 'block-start':\n case 'block-end':\n case 'usage':\n case 'finish':\n this.records.push({ type: 'chunk', time, chunk })\n return timed\n default:\n return assertNever(chunk, 'AssistantStreamAccumulator.push')\n }\n }\n\n /**\n * Return the current compact attempt stream.\n * @returns a detached immutable record list suitable for a durable event.\n */\n snapshot(): readonly AssistantStreamRecord[] {\n const records = this.records.map((record): AssistantStreamRecord => {\n if (record.type === 'chunk') return { ...record }\n const { lastTime: _lastTime, ...durable } = record\n if (durable.type === 'tool-call-chunks') {\n return { ...durable, dt: [...durable.dt], args: [...durable.args] }\n }\n return { ...durable, dt: [...durable.dt], texts: [...durable.texts] }\n })\n return deepFreeze(records)\n }\n}\n\n/**\n * Expand compact records into the exact timed chunk sequence.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns detached timed chunks with every original delta boundary preserved.\n * @throws {TypeError} when a record or reconstructed timestamp is invalid.\n */\nexport function expandAssistantStream(stream: readonly AssistantStreamRecord[]): readonly TimedStreamChunk[] {\n const chunks: TimedStreamChunk[] = []\n for (const candidate of stream) {\n const record = validateRecord(candidate)\n if (record.type === 'chunk') {\n chunks.push({ time: record.time, chunk: record.chunk })\n continue\n }\n const members = record.type === 'tool-call-chunks' ? record.args : record.texts\n let time = record.time0\n for (let index = 0; index < members.length; index += 1) {\n if (index > 0) time += record.dt[index - 1] as number\n let chunk: StreamChunk\n if (record.type === 'text-chunks') {\n chunk = { type: 'text-delta', index: record.index, text: members[index] as string }\n } else if (record.type === 'reasoning-chunks') {\n chunk = { type: 'reasoning-delta', index: record.index, text: members[index] as string }\n } else {\n chunk = {\n type: 'tool-call-delta',\n index: record.index,\n id: record.id,\n ...Object.hasOwn(record, 'name') ? { name: record.name } : {},\n argumentsDelta: members[index] as string,\n }\n }\n chunks.push({ time, chunk })\n }\n }\n return chunks\n}\n\nfunction hasNonWhitespace(text: string): boolean {\n return /\\S/.test(text)\n}\n\nfunction blockIsVisible(block: ContentBlock): boolean {\n if (block.type === 'tool-call') return false\n if (block.type === 'text' || block.type === 'reasoning') return hasNonWhitespace(block.text)\n return true\n}\n\n/**\n * Whether one chunk carries the model's first output token for latency measurement.\n * @param chunk - any stream chunk.\n * @returns true for a non-empty text, reasoning, or Tool-call arguments fragment and for\n * every name-bearing Tool-call delta; false for block, usage, and finish chunks.\n */\nexport function isTokenDelta(chunk: StreamChunk): boolean {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return chunk.text !== ''\n case 'tool-call-delta':\n return chunk.argumentsDelta !== '' || chunk.name !== undefined\n default:\n return false\n }\n}\n\n/**\n * Whether one chunk by itself contributes reader-visible transcript content.\n * Text and reasoning count only with non-whitespace content, streamed as a delta or\n * completed as a block; a block of any other kind counts at its start and its end,\n * except a Tool call, which is protocol rather than content. Usage and finish never count.\n * @param chunk - any stream chunk.\n * @returns whether a transcript reader would see this chunk.\n */\nexport function isVisibleChunk(chunk: StreamChunk): boolean {\n switch (chunk.type) {\n case 'text-delta':\n case 'reasoning-delta':\n return hasNonWhitespace(chunk.text)\n case 'block-start':\n return chunk.blockType !== 'text' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'tool-call'\n case 'block-end':\n return blockIsVisible(chunk.block)\n default:\n return false\n }\n}\n\n/**\n * Whether one chunk carries non-whitespace text, as a text delta or a completed text block.\n * Reasoning, Tool calls, and other block kinds never count.\n * @param chunk - any stream chunk.\n * @returns whether the chunk contributes visible text.\n */\nexport function chunkHasVisibleText(chunk: StreamChunk): boolean {\n if (chunk.type === 'text-delta') return hasNonWhitespace(chunk.text)\n return chunk.type === 'block-end' && chunk.block.type === 'text' && hasNonWhitespace(chunk.block.text)\n}\n\nfunction firstRunMemberTime(run: AssistantStreamRun, predicate: (fragment: string) => boolean): number | undefined {\n const fragments = run.type === 'tool-call-chunks' ? run.args : run.texts\n let time = run.time0\n for (let index = 0; index < fragments.length; index += 1) {\n if (index > 0) time += run.dt[index - 1] as number\n if (predicate(fragments[index] as string)) return time\n }\n return undefined\n}\n\n/**\n * Time of the first member of one packed run that {@link isTokenDelta} accepts: a\n * name-bearing Tool-call run starts at its first member, otherwise the first non-empty fragment.\n * Stops scanning at that member.\n * @param run - one packed delta run.\n * @returns the member's reconstructed time, or undefined when no member qualifies.\n */\nexport function runFirstTokenTime(run: AssistantStreamRun): number | undefined {\n if (run.type === 'tool-call-chunks' && run.name !== undefined) return run.time0\n return firstRunMemberTime(run, fragment => fragment !== '')\n}\n\n/**\n * Time of the first member of one packed run that {@link isVisibleChunk} accepts: the first\n * non-whitespace text or reasoning fragment. A Tool-call run has none. Stops scanning at that member.\n * @param run - one packed delta run.\n * @returns the member's reconstructed time, or undefined when no member qualifies.\n */\nexport function runFirstVisibleTime(run: AssistantStreamRun): number | undefined {\n return run.type === 'tool-call-chunks' ? undefined : firstRunMemberTime(run, hasNonWhitespace)\n}\n\n/**\n * Time of the first token in one compact stream per {@link isTokenDelta}, read from the\n * records themselves and stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns the first token's time, or undefined when the stream carries no token.\n */\nexport function assistantStreamFirstTokenTime(stream: readonly AssistantStreamRecord[]): number | undefined {\n for (const record of stream) {\n const time = record.type === 'chunk'\n ? (isTokenDelta(record.chunk) ? record.time : undefined)\n : runFirstTokenTime(record)\n if (time !== undefined) return time\n }\n return undefined\n}\n\n/**\n * Whether one compact stream carries any reader-visible content per {@link isVisibleChunk},\n * stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns whether a transcript reader would see anything from this stream.\n */\nexport function assistantStreamHasVisibleContent(stream: readonly AssistantStreamRecord[]): boolean {\n return stream.some(record => record.type === 'chunk'\n ? isVisibleChunk(record.chunk)\n : runFirstVisibleTime(record) !== undefined)\n}\n\n/**\n * Whether one compact stream carries non-whitespace text per {@link chunkHasVisibleText},\n * stopping at the first qualifying member.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns whether the stream contributes visible text.\n */\nexport function assistantStreamHasVisibleText(stream: readonly AssistantStreamRecord[]): boolean {\n return stream.some(record => record.type === 'text-chunks'\n ? record.texts.some(hasNonWhitespace)\n : record.type === 'chunk' && chunkHasVisibleText(record.chunk))\n}\n\n/**\n * The last raw chunk of one never-packed type, scanning backwards and stopping at the first hit.\n * @param stream - compact records from one durable Assistant settlement.\n * @param type - chunk type that only appears as a raw record.\n * @returns the stream's final chunk of that type, or undefined when it has none.\n */\nexport function lastAssistantStreamChunk<T extends RawStreamChunkType>(\n stream: readonly AssistantStreamRecord[],\n type: T,\n): Extract<StreamChunk, { type: T }> | undefined {\n for (let index = stream.length - 1; index >= 0; index -= 1) {\n const record = stream[index] as AssistantStreamRecord\n if (record.type === 'chunk' && record.chunk.type === type) return record.chunk as Extract<StreamChunk, { type: T }>\n }\n return undefined\n}\n\n/**\n * Every raw chunk of one never-packed type, in stream order.\n * @param stream - compact records from one durable Assistant settlement.\n * @param type - chunk type that only appears as a raw record.\n * @returns the matching chunks; empty when the stream has none.\n */\nexport function assistantStreamChunks<T extends RawStreamChunkType>(\n stream: readonly AssistantStreamRecord[],\n type: T,\n): readonly Extract<StreamChunk, { type: T }>[] {\n const chunks: Extract<StreamChunk, { type: T }>[] = []\n for (const record of stream) {\n if (record.type === 'chunk' && record.chunk.type === type) chunks.push(record.chunk as Extract<StreamChunk, { type: T }>)\n }\n return chunks\n}\n\n/**\n * Every streamed text-delta fragment joined in stream order; reasoning and Tool-call fragments are excluded.\n * @param stream - compact records from one durable Assistant settlement.\n * @returns the joined text, empty when the stream carries no text delta.\n */\nexport function joinAssistantStreamText(stream: readonly AssistantStreamRecord[]): string {\n const parts: string[] = []\n for (const record of stream) {\n if (record.type === 'text-chunks') parts.push(record.texts.join(''))\n else if (record.type === 'chunk' && record.chunk.type === 'text-delta') parts.push(record.chunk.text)\n }\n return parts.join('')\n}\n\n/**\n * Feed one compact stream into a {@link BlockAssembler} without materializing members.\n * Each run contributes one delta carrying its joined fragments, which assembles the same\n * blocks as the original per-member deltas because assembly only concatenates them;\n * raw chunks are pushed as recorded. The records are trusted, not validated: validate a\n * stream read at a durable boundary with {@link expandAssistantStream} first.\n * @param stream - compact records from one durable Assistant settlement.\n * @param assembler - assembler to feed; a fresh one by default.\n * @returns the same assembler after every record was pushed.\n */\nexport function assembleAssistantStream(\n stream: readonly AssistantStreamRecord[],\n assembler = new BlockAssembler(),\n): BlockAssembler {\n for (const record of stream) {\n switch (record.type) {\n case 'chunk':\n assembler.push(record.chunk)\n break\n case 'text-chunks':\n assembler.push({ type: 'text-delta', index: record.index, text: record.texts.join('') })\n break\n case 'reasoning-chunks':\n assembler.push({ type: 'reasoning-delta', index: record.index, text: record.texts.join('') })\n break\n case 'tool-call-chunks':\n assembler.push({\n type: 'tool-call-delta',\n index: record.index,\n id: record.id,\n ...record.name === undefined ? {} : { name: record.name },\n argumentsDelta: record.args.join(''),\n })\n break\n default:\n assertNever(record, 'assembleAssistantStream')\n }\n }\n return assembler\n}\n\nfunction validateRecord(value: unknown): AssistantStreamRecord {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new TypeError('Assistant stream record must be an object')\n }\n const record = value as Record<string, unknown>\n switch (record.type) {\n case 'text-chunks':\n case 'reasoning-chunks': {\n exactKeys(record, ['type', 'time0', 'index', 'dt', 'texts'], record.type)\n const texts = stringArray(record.texts, `${record.type} texts`)\n if (texts.length === 0) throw new TypeError(`${record.type} texts must be non-empty`)\n validateRun(record, texts.length, record.type)\n return record as AssistantStreamRecord\n }\n case 'tool-call-chunks': {\n const keys = Object.hasOwn(record, 'name')\n ? ['type', 'time0', 'index', 'dt', 'id', 'name', 'args']\n : ['type', 'time0', 'index', 'dt', 'id', 'args']\n exactKeys(record, keys, record.type)\n const args = stringArray(record.args, 'tool-call-chunks args')\n if (args.length === 0) throw new TypeError('tool-call-chunks args must be non-empty')\n if (typeof record.id !== 'string' || record.id.length === 0) {\n throw new TypeError('tool-call-chunks id must be a non-empty string')\n }\n if (record.name !== undefined && (typeof record.name !== 'string' || record.name.length === 0)) {\n throw new TypeError('tool-call-chunks name must be a non-empty string')\n }\n validateRun(record, args.length, record.type)\n return record as AssistantStreamRecord\n }\n case 'chunk': {\n exactKeys(record, ['type', 'time', 'chunk'], 'chunk')\n const time = safeTime(record.time as number)\n if (typeof record.chunk !== 'object'\n || record.chunk === null\n || Array.isArray(record.chunk)) {\n throw new TypeError('Assistant stream raw chunk must be a lossless JSON object')\n }\n let chunk: StreamChunk\n try {\n chunk = snapshotChunk(record.chunk as StreamChunk)\n } catch (error: unknown) {\n throw new TypeError('Assistant stream raw chunk must be a lossless JSON object', { cause: error })\n }\n return deepFreeze({ type: 'chunk', time, chunk })\n }\n default:\n throw new TypeError(`Unsupported Assistant stream record ${JSON.stringify(record.type)}`)\n }\n}\n\nfunction validateRun(record: Record<string, unknown>, members: number, label: string): void {\n safeTime(record.time0 as number)\n safeIndex(record.index as number, label)\n if (!Array.isArray(record.dt) || record.dt.some(value => !Number.isSafeInteger(value))) {\n throw new TypeError(`${label} dt must contain safe integers`)\n }\n if (record.dt.length !== members - 1) {\n throw new TypeError(`${label} dt length must be one less than its members`)\n }\n let time = record.time0 as number\n for (const gap of record.dt as number[]) {\n time += gap\n if (!Number.isSafeInteger(time)) throw new TypeError(`${label} member times must stay safe integers`)\n }\n}\n\nfunction stringArray(value: unknown, label: string): string[] {\n if (!Array.isArray(value) || value.some(member => typeof member !== 'string')) {\n throw new TypeError(`${label} must be a string array`)\n }\n return value as string[]\n}\n\nfunction exactKeys(record: Record<string, unknown>, keys: readonly string[], label: string): void {\n if (Object.keys(record).length !== keys.length || !keys.every(key => Object.hasOwn(record, key))) {\n throw new TypeError(`${label} Assistant stream record must contain exactly ${keys.join(', ')}`)\n }\n}\n","import { lastAssistantStreamChunk } from '@deepseek-ai/dsh-llm/assistant-stream'\nimport type { AssistantMessage, TokenUsage } from '@deepseek-ai/dsh-llm/types'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session/types'\n\n/** One provider/model route that contributed a billed request attempt. */\nexport interface TurnTokenUsageRoute {\n readonly provider: string\n readonly model: string\n}\n\n/** Exact provider-reported token accounting for every attempt in one completed Turn. */\nexport interface TurnTokenUsage {\n /** Sum of uncached prompt input across all attempts. */\n readonly uncachedInputTokens: number\n readonly outputTokens: number\n /** Exact aggregate prompt plus output total across all attempts. */\n readonly totalTokens: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheReadTokens?: number\n /** Present only when every attempt reported the bucket. */\n readonly cacheWriteTokens?: number\n /** Output subset, present only when every attempt reported it. */\n readonly reasoningTokens?: number\n /** Present only when every billed attempt has provider/model attribution. */\n readonly routes?: readonly TurnTokenUsageRoute[]\n}\n\ninterface NormalizedAttempt {\n readonly inputTokens: number\n readonly outputTokens: number\n readonly totalTokens: number\n readonly cacheReadTokens?: number\n readonly cacheWriteTokens?: number\n readonly reasoningTokens?: number\n readonly route?: TurnTokenUsageRoute\n}\n\ntype AttemptState =\n | { readonly kind: 'idle' }\n | {\n readonly kind: 'open'\n readonly turn: number\n readonly step: number\n readonly sample?: TokenUsage\n }\n | {\n readonly kind: 'finishClosed'\n readonly turn: number\n readonly step: number\n }\n | {\n readonly kind: 'settled'\n readonly turn: number\n readonly step: number\n readonly by: 'message' | 'retry'\n }\n\nfunction isCount(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction safeSum(values: readonly number[]): number | undefined {\n let total = 0\n for (const value of values) {\n total += value\n if (!Number.isSafeInteger(total)) return undefined\n }\n return total\n}\n\nfunction messageRoute(message: AssistantMessage): TurnTokenUsageRoute | undefined {\n const { provider, model } = message.source\n return provider.length > 0 && model.length > 0 ? { provider, model } : undefined\n}\n\nfunction streamUsage(stream: SessionEvent<'assistant/message'>['data']['stream']): TokenUsage | undefined {\n return lastAssistantStreamChunk(stream, 'usage')?.usage\n}\n\nfunction normalizeUsage(usage: TokenUsage, route?: TurnTokenUsageRoute): NormalizedAttempt | undefined {\n const {\n inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens, totalTokens,\n } = usage\n if (!isCount(inputTokens) || !isCount(outputTokens)) return undefined\n if (cacheReadTokens !== undefined && !isCount(cacheReadTokens)) return undefined\n if (cacheWriteTokens !== undefined && !isCount(cacheWriteTokens)) return undefined\n if (reasoningTokens !== undefined && (!isCount(reasoningTokens) || reasoningTokens > outputTokens)) {\n return undefined\n }\n\n const knownPrompt = safeSum([\n inputTokens,\n ...cacheReadTokens === undefined ? [] : [cacheReadTokens],\n ...cacheWriteTokens === undefined ? [] : [cacheWriteTokens],\n ])\n if (knownPrompt === undefined) return undefined\n\n let exactTotal: number\n if (totalTokens !== undefined) {\n if (!isCount(totalTokens)) return undefined\n const exactPrompt = totalTokens - outputTokens\n if (!isCount(exactPrompt) || exactPrompt < knownPrompt) return undefined\n if (cacheReadTokens !== undefined && cacheWriteTokens !== undefined && exactPrompt !== knownPrompt) {\n return undefined\n }\n exactTotal = totalTokens\n } else {\n if (cacheReadTokens === undefined || cacheWriteTokens === undefined) return undefined\n const derivedTotal = safeSum([knownPrompt, outputTokens])\n if (derivedTotal === undefined) return undefined\n exactTotal = derivedTotal\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens: exactTotal,\n ...cacheReadTokens === undefined ? {} : { cacheReadTokens },\n ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },\n ...reasoningTokens === undefined ? {} : { reasoningTokens },\n ...route === undefined ? {} : { route },\n }\n}\n\nfunction aggregateAttempts(attempts: readonly NormalizedAttempt[]): TurnTokenUsage | undefined {\n if (attempts.length === 0) return undefined\n const inputTokens = safeSum(attempts.map(attempt => attempt.inputTokens))\n const outputTokens = safeSum(attempts.map(attempt => attempt.outputTokens))\n const totalTokens = safeSum(attempts.map(attempt => attempt.totalTokens))\n if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined) return undefined\n\n const cacheRead = attempts.map(attempt => attempt.cacheReadTokens)\n const cacheWrite = attempts.map(attempt => attempt.cacheWriteTokens)\n const reasoning = attempts.map(attempt => attempt.reasoningTokens)\n const cacheReadTokens = cacheRead.every(isCount) ? safeSum(cacheRead) : undefined\n const cacheWriteTokens = cacheWrite.every(isCount) ? safeSum(cacheWrite) : undefined\n const reasoningTokens = reasoning.every(isCount) ? safeSum(reasoning) : undefined\n // A present cache bucket is bounded by exact prompt, and reasoning is bounded\n // by output. Safe required aggregates therefore imply safe optional sums.\n\n let routes: readonly TurnTokenUsageRoute[] | undefined\n const attributed = attempts.map(attempt => attempt.route)\n if (attributed.every((route): route is TurnTokenUsageRoute => route !== undefined)) {\n const unique = new Map<string, TurnTokenUsageRoute>()\n for (const route of attributed) unique.set(`${route.provider}\\0${route.model}`, route)\n routes = [...unique.values()]\n }\n\n return {\n uncachedInputTokens: inputTokens,\n outputTokens,\n totalTokens,\n ...cacheReadTokens === undefined ? {} : { cacheReadTokens },\n ...cacheWriteTokens === undefined ? {} : { cacheWriteTokens },\n ...reasoningTokens === undefined ? {} : { reasoningTokens },\n ...routes === undefined ? {} : { routes },\n }\n}\n\nfunction sameAttempt(\n state: Exclude<AttemptState, { kind: 'idle' }>,\n turn: number,\n step: number,\n): boolean {\n return state.turn === turn && state.step === step\n}\n\n/**\n * Fold one complete Turn's durable attempt lifecycle into exact token accounting.\n *\n * No attempt is inferred from a usage sample. Any missing lifecycle boundary,\n * incomplete attempt usage, unsafe count, or contradictory exact total makes\n * the whole disclosure unavailable.\n * @param events - Turn-local durable events from `turn/start` through `turn/end`.\n * @returns exact aggregate usage, or undefined when it cannot be proven.\n */\nexport function deriveTurnTokenUsage(events: readonly SessionEvent[]): TurnTokenUsage | undefined {\n let state: AttemptState = { kind: 'idle' }\n const attempts: NormalizedAttempt[] = []\n let turn: number | undefined\n let sawEnd = false\n let invalid = false\n\n const closeOpen = (route?: TurnTokenUsageRoute): boolean => {\n if (state.kind !== 'open' || state.sample === undefined) return false\n const normalized = normalizeUsage(state.sample, route)\n if (normalized === undefined) return false\n attempts.push(normalized)\n return true\n }\n\n for (const event of events) {\n if (invalid) break\n if (event.type === 'turn/start') {\n if (turn !== undefined || state.kind !== 'idle') invalid = true\n else turn = event.data.turn\n continue\n }\n if (turn === undefined) {\n invalid = true\n break\n }\n if (event.type === 'turn/end') {\n if (event.data.turn !== turn || state.kind !== 'idle' || sawEnd) invalid = true\n else sawEnd = true\n continue\n }\n if (sawEnd) {\n invalid = true\n break\n }\n if (event.type === 'step/start') {\n if (event.data.turn !== turn || state.kind !== 'idle') invalid = true\n else state = { kind: 'open', turn, step: event.data.step }\n continue\n }\n if (event.type === 'llm/retry-started') {\n if (event.data.turn !== turn\n || state.kind !== 'settled'\n || state.by !== 'retry'\n || !sameAttempt(state, event.data.turn, event.data.step)) invalid = true\n else state = { kind: 'open', turn, step: event.data.step }\n continue\n }\n if (event.type === 'assistant/attempt') {\n if (event.data.turn !== turn\n || state.kind !== 'open'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true\n continue\n }\n const sample: TokenUsage | undefined = streamUsage(event.data.stream) ?? state.sample\n state = { kind: 'open', turn, step: event.data.step, ...(sample === undefined ? {} : { sample }) }\n if (!closeOpen()) invalid = true\n else state = { kind: 'finishClosed', turn, step: event.data.step }\n continue\n }\n if (event.type === 'assistant/message') {\n if (event.data.turn !== turn\n || state.kind !== 'open'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true\n continue\n }\n const sample = event.data.usage ?? streamUsage(event.data.stream)\n if (sample !== undefined) state = { ...state, sample }\n if (!closeOpen(messageRoute(event.data.message))) invalid = true\n else state = { kind: 'settled', turn, step: event.data.step, by: 'message' }\n continue\n }\n if (event.type === 'llm/retry') {\n if (event.data.turn !== turn || state.kind === 'idle'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true\n continue\n }\n if (state.kind === 'settled' || (state.kind === 'open' && !closeOpen())) invalid = true\n if (!invalid) state = { kind: 'settled', turn, step: event.data.step, by: 'retry' }\n continue\n }\n if (event.type === 'step/end') {\n if (event.data.turn !== turn || state.kind === 'idle'\n || !sameAttempt(state, event.data.turn, event.data.step)) {\n invalid = true\n continue\n }\n if (state.kind === 'open' && !closeOpen()) invalid = true\n if (!invalid) state = { kind: 'idle' }\n }\n }\n\n return invalid || !sawEnd || state.kind !== 'idle' ? undefined : aggregateAttempts(attempts)\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {\n ConversationMatch, ConversationNodeContext, ConversationNodeDefinition, TurnLocation,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-llm-retry/types'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session/types'\nimport { deriveTurnTokenUsage } from '@deepseek-ai/dsh-token-meter/client'\nimport type {\n AssistantChatData, FinalAssistantChatData, TurnTailChatData,\n} from '../contract/chat-nodes.ts'\nimport { CHAT_SYNTHETIC_SEQ_OFFSETS, chatNode } from './common.ts'\n\ndeclare module '../contract/chat-nodes.ts' {\n interface ChatNodeDataMap {\n /** Completed-turn actions and extension tail. */\n 'turn-tail': TurnTailChatData\n }\n}\n\ndeclare module '@deepseek-ai/dsh-client-ui-conversation/client' {\n interface ConversationTurnDataMap {\n /** Closing Assistant and footer facts derived for this completed Turn. */\n 'turn-tail': TurnTailChatData\n }\n}\n\ninterface TurnTailState {\n readonly turn: number\n readonly end?: ConversationMatch\n}\n\nfunction isSessionEvent(event: ConversationMatch['event']): event is SessionEvent {\n return event.type !== 'assistant/live-chunk'\n}\n\nfunction turnCoordinates(event: Parameters<ConversationNodeDefinition['match']>[0]): {\n readonly turn: number\n readonly step?: number\n} | undefined {\n if (event.type === 'assistant/message'\n || event.type === 'assistant/attempt'\n || event.type === 'assistant/live-chunk'\n || event.type === 'step/start'\n || event.type === 'step/end') {\n return { turn: event.data.turn, step: event.data.step }\n }\n if (event.type === 'llm/retry' || event.type === 'llm/retry-started') {\n return { turn: event.data.turn, step: event.data.step }\n }\n return undefined\n}\n\nfunction turnLocation(context: ConversationNodeContext<TurnTailState>): TurnLocation | undefined {\n const location = context.start?.location ?? context.matches[0]?.location\n return location?.kind === 'turn' || location?.kind === 'step' ? location.turn : undefined\n}\n\nfunction hasText(data: AssistantChatData): data is FinalAssistantChatData {\n return data.finalNode !== undefined\n && data.blocks.some(block => block.kind === 'text' && block.text.trim() !== '')\n}\n\nfunction tailData(context: ConversationNodeContext<TurnTailState>): TurnTailChatData | null {\n const end = context.state === undefined\n ? context.matches.find(match => match.event.type === 'turn/end')\n : context.state.end\n if (end?.event.type !== 'turn/end') return null\n const turn = turnLocation(context)\n if (turn === undefined) return null\n const assistants = turn.steps\n .map(step => step.data.get('assistant-step'))\n .filter((candidate): candidate is Readonly<AssistantChatData> => candidate !== undefined)\n const finalized = assistants\n .filter((candidate): candidate is Readonly<FinalAssistantChatData> => candidate.finalNode !== undefined)\n .sort((left, right) => left.finalNode.seq - right.finalNode.seq)\n const closing = finalized.findLast(hasText) ?? null\n let latestTranscriptSeq = finalized.at(-1)?.finalNode.seq\n for (const match of context.matches) {\n const event = match.event\n const candidate = event.type === 'tool/call'\n || (event.type === 'tool/result' && event.surfaceOp === 'append')\n || (event.type === 'turn/end' && event.data.reason.kind === 'error')\n || event.type === 'llm/retry'\n ? event.seq\n : undefined\n if (candidate !== undefined && (latestTranscriptSeq === undefined || candidate > latestTranscriptSeq)) {\n latestTranscriptSeq = candidate\n }\n }\n const tokenUsage = context.start?.event.type === 'turn/start'\n ? deriveTurnTokenUsage(context.matches.map(match => match.event).filter(isSessionEvent))\n : undefined\n return {\n turn: end.event.data.turn,\n seq: end.event.seq,\n time: end.event.time,\n closing,\n branchUnavailable: closing === null || latestTranscriptSeq !== closing.finalNode.seq,\n ...tokenUsage === undefined ? {} : { tokenUsage },\n }\n}\n\n/** Completed-turn footer Definition independent of any Assistant row. */\nexport const turnTailDefinition: ConversationNodeDefinition<TurnTailState> = {\n kind: 'turn-tail',\n target: 'chat',\n match: (event) => {\n if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' }\n if (event.type === 'turn/end') return { id: String(event.data.turn), role: 'update' }\n if (event.type === 'tool/call' || event.type === 'tool/result') {\n return { id: String(event.data.turn), role: 'update' }\n }\n const coordinates = turnCoordinates(event)\n if (coordinates !== undefined) return { id: String(coordinates.turn), role: 'update' }\n return null\n },\n start: (_context, match) => {\n if (match.event.type !== 'turn/start') throw new Error('turn-tail start requires turn/start')\n return { turn: match.event.data.turn }\n },\n update: (context, match) => match.event.type === 'turn/end'\n ? { ...context.state, end: match }\n : context.state,\n publication: match => match.event.type === 'turn/end' ? 'immediate' : 'none',\n buildLocationData: (context, scope) => {\n if (scope !== 'turn') return null\n const value = tailData(context)\n return value === null ? null : {\n kind: 'turn',\n turn: value.turn,\n key: 'turn-tail',\n value,\n }\n },\n buildViewNode: (context) => {\n const turn = turnLocation(context)\n const data = turn?.data.get('turn-tail')\n return data === undefined ? null : chatNode(context, 'turn-tail', data.seq + CHAT_SYNTHETIC_SEQ_OFFSETS.finalizedFollowup, data, { groupTree: 'turn' })\n },\n}\n\n/**\n * Register completed-Turn footer data and its Chat node contribution.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerTurnTailConversationNode(ctx: Context): void {\n const match = turnTailDefinition.match.bind(turnTailDefinition)\n ctx.uiConversation.events.register({\n ...turnTailDefinition,\n match: {\n 'turn/start': match,\n 'turn/end': match,\n 'tool/call': match,\n 'tool/result': match,\n 'assistant/message': match,\n 'assistant/attempt': match,\n 'assistant/live-chunk': match,\n 'step/start': match,\n 'step/end': match,\n 'llm/retry': match,\n 'llm/retry-started': match,\n },\n })\n}\n","/** Tool-category and live-detail interpretation owned by Chat grouping. */\nimport { reasoningText } from '../reasoning-text.ts'\nimport type { ToolArgs } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ProcessActivity, ProcessActivitySummary, RunningProcessActivity } from '../contract/process-groups.ts'\nimport type { ChatNode } from '../contract/chat-nodes.ts'\nimport { isRunningTool } from '../contract/chat-nodes.ts'\nimport type { ToolCallBlock } from '../contract/snapshot.ts'\n\nfunction activity(name: string): RunningProcessActivity {\n if (name === 'read') return 'read'\n if (name === 'read_image') return 'readImage'\n if (name === 'grep' || name === 'glob' || name.endsWith('_inspect')) return 'search'\n if (name === 'write') return 'write'\n if (name === 'edit' || name === 'apply_patch') return 'edit'\n if (['bash', 'pwsh', 'exec_command', 'write_stdin'].includes(name) || name.startsWith('terminal_')) return 'commands'\n if (name === 'run_code') return 'code'\n if (name === 'web_search') return 'webSearch'\n if (name === 'web_fetch') return 'webFetch'\n if (name === 'subagent' || name.startsWith('subagent_')) return 'subagents'\n if (['todo_write', 'create_goal', 'update_goal', 'get_goal'].includes(name)) return 'plan'\n if (name === 'ask_user_question' || name === 'request_user_input') return 'questions'\n return 'tools'\n}\n\nconst LIVE_TOOL_DETAIL_MAX_CHARS = 160\nconst LIVE_TOOL_DETAIL_PREFIX_CHARS = 512\nconst LIVE_TOOL_DETAIL_SEGMENTER = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\nconst LIVE_TOOL_DETAIL_KEYS = [\n 'title', 'description', 'objective', 'task', 'task_name', 'name', 'question', 'questions', 'prompt', 'message',\n 'command', 'cmd', 'queries', 'query', 'pattern', 'url', 'uri', 'file_path', 'path', 'target', 'action', 'status',\n] as const\n\ninterface NormalizedDetail {\n readonly text: string\n readonly truncated: boolean\n}\n\nfunction normalizeLiveToolText(text: string): NormalizedDetail {\n const normalized = text.replace(/\\s+/g, ' ').trim()\n if (normalized.length <= LIVE_TOOL_DETAIL_MAX_CHARS) return { text: normalized, truncated: false }\n const chars: string[] = []\n for (const { segment } of LIVE_TOOL_DETAIL_SEGMENTER.segment(normalized)) {\n if (chars.length === LIVE_TOOL_DETAIL_MAX_CHARS) {\n return {\n text: `${chars.slice(0, LIVE_TOOL_DETAIL_MAX_CHARS - 1).join('').trimEnd()}…`,\n truncated: true,\n }\n }\n chars.push(segment)\n }\n return { text: normalized, truncated: false }\n}\n\nfunction normalizeLiveToolDetail(value: unknown): string {\n const text = typeof value === 'string'\n ? value\n : Array.isArray(value) && value.every(item => typeof item === 'string')\n ? value.join(', ')\n : ''\n return normalizeLiveToolText(text).text\n}\n\nfunction argumentTextDetail(args: ToolArgs, key: string): string | undefined {\n let limit = LIVE_TOOL_DETAIL_PREFIX_CHARS\n while (true) {\n let prefix = args.textPrefix(key, limit)\n if (prefix === undefined) return undefined\n const last = prefix.charCodeAt(prefix.length - 1)\n if (last >= 0xd800 && last <= 0xdbff) {\n // The extra prefix read also observes a low surrogate arriving in a later delta.\n const extended = args.textPrefix(key, limit + 1) as string\n const next = extended.charCodeAt(prefix.length)\n if (next >= 0xdc00 && next <= 0xdfff) {\n prefix = extended\n limit++\n } else if (extended.length === prefix.length && !args.isSealed && !args.complete(key)) {\n prefix = prefix.slice(0, -1)\n }\n }\n const detail = normalizeLiveToolText(prefix)\n if (detail.truncated || !args.stringExceeds(key, limit)) return detail.text\n limit *= 2\n }\n}\n\nfunction questionDetail(value: unknown): string {\n if (!Array.isArray(value)) return ''\n for (const item of value) {\n if (item === null || typeof item !== 'object') continue\n const detail = normalizeLiveToolDetail(Reflect.get(item, 'question'))\n if (detail !== '') return detail\n }\n return ''\n}\n\nfunction liveReasoningDetail(nodes: readonly ChatNode[]): string {\n for (let nodeIndex = nodes.length - 1; nodeIndex >= 0; nodeIndex--) {\n const node = nodes[nodeIndex]\n if (node?.kind !== 'assistant-step' || node.data.status !== 'running') continue\n for (let blockIndex = node.data.blocks.length - 1; blockIndex >= 0; blockIndex--) {\n const block = node.data.blocks[blockIndex]\n if (block?.kind !== 'reasoning') continue\n const paragraphs = reasoningText(block.text).split(/\\r?\\n[\\t ]*\\r?\\n/)\n for (let paragraphIndex = paragraphs.length - 1; paragraphIndex >= 0; paragraphIndex--) {\n const detail = normalizeLiveToolDetail(paragraphs[paragraphIndex]?.replaceAll('**', ''))\n if (detail !== '') return detail\n }\n }\n }\n return ''\n}\n\n/**\n * One-line task detail from the argument view, read the same way while the\n * arguments stream and after dispatch: the first detail key present with text\n * so far or a closed value. Without one, the tool name stands in once no further\n * field can arrive; a field still to come is not named early.\n */\nfunction liveToolDetail(name: string, args: ToolArgs): string {\n for (const key of LIVE_TOOL_DETAIL_KEYS) {\n if (!args.has(key)) continue\n const detail = key === 'questions'\n ? questionDetail(args.value(key))\n : argumentTextDetail(args, key) ?? normalizeLiveToolDetail(args.value(key))\n if (detail !== '') return detail\n }\n return args.closed() ? normalizeLiveToolDetail(name) : ''\n}\n\n/**\n * Rank categories by distinct call count, breaking ties by first appearance.\n * A group whose members are all Context reports one `context` category counting those members; Context beside other members adds no count.\n * @param nodes - process members, including recursive tools.\n * @returns all ranked categories and the latest running tool category and bounded task detail.\n */\nexport function processActivity(nodes: readonly ChatNode[]): ProcessActivitySummary {\n const counts = new Map<ProcessActivity, number>()\n const seen = new Set<string>()\n let running: RunningProcessActivity | undefined\n let runningDetail = ''\n let runningTime = -Infinity\n let preparing: boolean | undefined\n const visit = (tool: ToolCallBlock): void => {\n if (seen.has(tool.callId)) return\n seen.add(tool.callId)\n const call = isRunningTool(tool) ? tool : tool.call\n if (call !== null) {\n const kind = activity(call.name)\n if (isRunningTool(tool) && tool.time >= runningTime) {\n running = kind\n preparing = tool.phase === 'preparing'\n runningDetail = liveToolDetail(tool.name, tool.args)\n runningTime = tool.time\n }\n counts.set(kind, (counts.get(kind) ?? 0) + 1)\n }\n for (const child of tool.subCalls) visit(child)\n }\n for (const node of nodes) {\n if (node.kind === 'tool-call') visit(node.data.root)\n }\n if (running === undefined) runningDetail = liveReasoningDetail(nodes)\n if (nodes.length > 0 && nodes.every(node => node.kind === 'context')) counts.set('context', nodes.length)\n return {\n counts: [...counts].map(([kind, count]) => ({ kind, count })).sort((a, b) => b.count - a.count),\n running,\n runningDetail,\n ...preparing ? { preparing: true } : {},\n }\n}\n","/** Chat-owned segmentation and incremental summaries over materialized Node inputs. */\nimport { brandString } from '@deepseek-ai/dsh-brand'\nimport type {\n ConversationGroupDefinition, ConversationGroupInput, GroupKey, GroupSnapshot,\n GroupUpdate, NodeKey, NodeReference, RenderEntry,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type { ChatConversationViewNode, ChatNode } from '../contract/chat-nodes.ts'\nimport type { ProcessActivitySummary, ProcessGroupData } from '../contract/process-groups.ts'\nimport { hasAssistantReplyContent } from '../contract/assistant-content.ts'\nimport { isVisibleChatNode } from '../contract/chat-visibility.ts'\nimport { isAtOrOutside } from '../contract/group-tree.ts'\nimport { processActivity } from './process-activity.ts'\n\ntype ProcessInput = ConversationGroupInput<ChatConversationViewNode>\n\nfunction turnOf(node: ChatNode): number | undefined {\n const location = node.location\n return location.kind === 'turn' || location.kind === 'step' ? location.turn.turn : undefined\n}\n\nfunction reasoning(node: ChatNode): boolean {\n return node.kind === 'assistant-step'\n && node.data.blocks.some(block => block.kind === 'reasoning' && block.text.trim() !== '')\n}\n\nfunction reply(node: ChatNode): boolean {\n return node.kind === 'assistant-step' && hasAssistantReplyContent(node.data.blocks)\n}\n\nfunction sameSummary(left: ProcessActivitySummary, right: ProcessActivitySummary): boolean {\n return left.running === right.running && left.runningDetail === right.runningDetail\n && left.preparing === right.preparing\n && left.counts.length === right.counts.length && left.counts.every((value, index) =>\n value.kind === right.counts[index]?.kind && value.count === right.counts[index].count)\n}\n\nfunction sameMembers(left: readonly NodeReference[], right: readonly NodeReference[]): boolean {\n return left.length === right.length && left.every((value, index) =>\n value.key === right[index]?.key && value.groupPart === right[index].groupPart)\n}\n\nfunction structureChanged(previous: ChatNode | undefined, current: ChatNode): boolean {\n if (!isVisibleChatNode(current) && (previous === undefined || !isVisibleChatNode(previous))) return false\n return previous === undefined || previous.kind !== current.kind\n || turnOf(previous) !== turnOf(current)\n || isVisibleChatNode(previous) !== isVisibleChatNode(current)\n || previous.groupTree !== current.groupTree\n || reasoning(previous) !== reasoning(current) || reply(previous) !== reply(current)\n}\n\nfunction readNode(input: ProcessInput, key: NodeKey): ChatNode {\n const node = input.readNode(key) as ChatNode | undefined\n if (node === undefined) throw new Error(`Chat grouping input is missing Node ${key}`)\n return node\n}\n\n/** One group's members and cached summary, refreshed together when its content changes. */\nclass ProcessGroup {\n private nodes: readonly ChatNode[] = []\n snapshot: GroupSnapshot<ProcessGroupData>\n\n constructor(readonly key: GroupKey, readonly turn: number, readonly members: readonly NodeReference[]) {\n this.snapshot = { key, members, data: { turn, closed: false, summary: { counts: [], running: undefined, runningDetail: '' } } }\n }\n\n refresh(input: ProcessInput, closed: boolean): void {\n const nodes = this.members.map(member => readNode(input, member.key))\n const unchanged = nodes.length === this.nodes.length && nodes.every((node, index) => node === this.nodes[index])\n const previous = this.snapshot.data\n const activity = unchanged && previous.closed === closed ? previous.summary : processActivity(nodes)\n const summary = closed ? { counts: activity.counts, running: undefined, runningDetail: '' } : activity\n this.nodes = nodes\n if (previous.closed !== closed || !sameSummary(previous.summary, summary)) {\n this.snapshot = {\n key: this.key, members: this.members,\n data: { turn: this.turn, closed, summary },\n }\n }\n }\n}\n\n/** One Turn's grouping result and member lookup; summaries stay with their groups. */\nclass TurnGroups {\n private groups = new Map<GroupKey, ProcessGroup>()\n private membership = new Map<NodeKey, GroupKey>()\n private roots = new Map<NodeKey, readonly RenderEntry[]>()\n\n constructor(readonly turn: number) {}\n\n references(key: NodeKey): readonly RenderEntry[] {\n return this.roots.get(key) ?? []\n }\n\n snapshots(): GroupSnapshot<ProcessGroupData>[] {\n return [...this.groups.values()].map(group => group.snapshot)\n }\n\n refresh(input: ProcessInput, changed: ReadonlySet<NodeKey>): GroupSnapshot<ProcessGroupData>[] {\n const dirty = new Set<GroupKey>()\n for (const node of changed) {\n const group = this.membership.get(node)\n if (group !== undefined) dirty.add(group)\n }\n const ended = input.timeline.turns.get(this.turn)?.status === 'closed'\n if (ended) {\n for (const group of this.groups.values()) {\n if (!group.snapshot.data.closed) dirty.add(group.key)\n }\n }\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n for (const key of dirty) {\n const group = this.groups.get(key) as ProcessGroup\n const previous = group.snapshot\n group.refresh(input, previous.data.closed || ended)\n if (group.snapshot !== previous) upserts.push(group.snapshot)\n }\n return upserts\n }\n\n rebuild(input: ProcessInput, added: ReadonlySet<NodeKey>): { upserts: GroupSnapshot<ProcessGroupData>[]; removes: GroupKey[] } {\n const roots = new Map<NodeKey, readonly RenderEntry[]>()\n const groups = new Map<GroupKey, ProcessGroup>()\n const membership = new Map<NodeKey, GroupKey>()\n let pending: NodeReference[] = []\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n const emit = (key: NodeKey, entry: RenderEntry): void => {\n roots.set(key, [...roots.get(key) ?? [], entry])\n }\n const flush = (closed: boolean): void => {\n const first = pending[0]\n if (first === undefined) return\n const retained = this.extendedGroup(pending, added)\n const key = retained?.key ?? brandString<GroupKey>(JSON.stringify(['process', first.key, first.groupPart ?? null]))\n const previous = this.groups.get(key)\n const before = previous?.snapshot\n const group = previous !== undefined && sameMembers(previous.members, pending)\n ? previous : new ProcessGroup(key, this.turn, pending)\n group.refresh(input, closed || input.timeline.turns.get(this.turn)?.status === 'closed')\n groups.set(group.key, group)\n emit(first.key, { kind: 'group', key: group.key })\n for (const member of pending) membership.set(member.key, group.key)\n if (group.snapshot !== before) upserts.push(group.snapshot)\n pending = []\n }\n let previous: NodeKey | undefined\n let followed = false\n for (const key of input.readTurn(this.turn)) {\n const position = readPosition(input, key)\n if (previous !== undefined && position.previous !== previous) flush(true)\n previous = key\n followed = position.next !== undefined\n const node = readNode(input, key)\n if (isAtOrOutside(node, 'process')) {\n flush(true)\n emit(key, { kind: 'node', key })\n } else if (node.kind === 'assistant-step') {\n // One Node, two rows: reasoning joins the step run, a reply stands outside it.\n if (reasoning(node)) pending.push({ kind: 'node', key, groupPart: 'reasoning' })\n if (reply(node)) {\n flush(true)\n emit(key, { kind: 'node', key, groupPart: 'response' })\n }\n } else pending.push({ kind: 'node', key })\n }\n flush(followed)\n const removes = [...this.groups.keys()].filter(key => !groups.has(key))\n this.groups = groups\n this.membership = membership\n this.roots = roots\n return { upserts, removes }\n }\n\n private extendedGroup(members: readonly NodeReference[], added: ReadonlySet<NodeKey>): ProcessGroup | undefined {\n // Reuse identity only while the complete old group remains between newly visible members.\n const offset = members.findIndex(member => !added.has(member.key))\n const first = members[offset]\n if (first === undefined) return undefined\n const key = this.membership.get(first.key)\n const previous = key === undefined ? undefined : this.groups.get(key)\n if (previous === undefined || offset + previous.members.length > members.length) return undefined\n for (let index = 0; index < previous.members.length; index++) {\n const before = previous.members[index] as NodeReference\n const after = members[offset + index] as NodeReference\n if (before.key !== after.key || before.groupPart !== after.groupPart) return undefined\n }\n for (let index = offset + previous.members.length; index < members.length; index++) {\n if (!added.has((members[index] as NodeReference).key)) return undefined\n }\n return previous\n }\n}\n\nfunction readPosition(input: ProcessInput, key: NodeKey) {\n const position = input.readPosition(key)\n if (position === undefined) throw new Error(`Chat grouping order is missing position for Node ${key}`)\n return position\n}\n\n/** Session-local Turn results; ordinary updates never read other Turns' Node contents. */\nexport class ProcessState {\n private turns = new Map<number, TurnGroups>()\n private order: readonly NodeKey[] = []\n private pending: GroupUpdate<ProcessGroupData> | null = null\n\n /**\n * Consume one synchronous Builder input without retaining its readers.\n * @param input - projected Node changes, indexed positions, and Turn lifecycle.\n */\n accept(input: ProcessInput): void {\n if (input.kind === 'replace') {\n const previousKeys = new Set(this.order)\n const added = new Set(input.order.filter(key => !previousKeys.has(key)))\n const turns = new Map<number, TurnGroups>()\n for (const key of input.order) {\n const turn = readPosition(input, key).turn\n if (turn === undefined || turns.has(turn)) continue\n const groups = this.turns.get(turn) ?? new TurnGroups(turn)\n groups.rebuild(input, added)\n turns.set(turn, groups)\n }\n this.turns = turns\n this.order = input.order\n this.pending = {\n entries: this.rootEntries(input),\n groups: { kind: 'replace', snapshots: [...turns.values()].flatMap(turn => turn.snapshots()) },\n }\n return\n }\n\n const regroup = new Set(input.changedTurnOrders)\n const added = new Set<NodeKey>()\n const changed = new Map<number, Set<NodeKey>>()\n const touch = (turn: number): Set<NodeKey> => {\n let keys = changed.get(turn)\n if (keys === undefined) {\n keys = new Set()\n changed.set(turn, keys)\n }\n return keys\n }\n for (const change of input.changes) {\n const before = change.previous as ChatNode | undefined\n const after = change.current as ChatNode\n const turn = turnOf(after)\n if (before === undefined || !isVisibleChatNode(before)) added.add(after.key as NodeKey)\n if (structureChanged(before, after)) {\n const previousTurn = before === undefined ? undefined : turnOf(before)\n if (previousTurn !== undefined) regroup.add(previousTurn)\n if (turn !== undefined) regroup.add(turn)\n }\n if (turn !== undefined) touch(turn).add(after.key as NodeKey)\n }\n for (const turn of input.changedTurns) touch(turn)\n\n const upserts: GroupSnapshot<ProcessGroupData>[] = []\n const removes: GroupKey[] = []\n for (const turn of regroup) {\n const groups = this.turns.get(turn) ?? new TurnGroups(turn)\n const update = groups.rebuild(input, added)\n upserts.push(...update.upserts)\n removes.push(...update.removes)\n if (input.readTurn(turn).length === 0) this.turns.delete(turn)\n else this.turns.set(turn, groups)\n }\n for (const [turn, keys] of changed) {\n if (!regroup.has(turn)) upserts.push(...this.turns.get(turn)?.refresh(input, keys) ?? [])\n }\n const reordered = input.order !== this.order || regroup.size > 0\n this.order = input.order\n const installed = new Set(upserts.map(group => group.key))\n this.pending = reordered || upserts.length > 0 || removes.length > 0\n ? {\n ...reordered ? { entries: this.rootEntries(input) } : {},\n groups: { kind: 'apply', upserts, removes: removes.filter(key => !installed.has(key)) },\n }\n : null\n }\n\n private rootEntries(input: ProcessInput): RenderEntry[] {\n return input.order.flatMap<RenderEntry>((key) => {\n const turn = readPosition(input, key).turn\n if (turn === undefined) return [{ kind: 'node', key }]\n const groups = this.turns.get(turn)\n if (groups === undefined) throw new Error(`Chat grouping order is missing Turn ${turn}`)\n return groups.references(key)\n })\n }\n\n /**\n * Read pending output without advancing State.\n * @returns the repeatable update for the last input batch.\n */\n output(): GroupUpdate<ProcessGroupData> | null { return this.pending }\n}\n\n/** Chat's registered business grouping; presentation modes never enter its State. */\nexport const processGroupDefinition: ConversationGroupDefinition<ChatConversationViewNode, ProcessState, ProcessGroupData>\n & { readonly target: 'chat' } = {\n kind: 'process-groups', target: 'chat',\n create: () => new ProcessState(),\n update: (context, input) => { context.state.accept(input); return context.state },\n buildGroups: context => context.state.output(),\n }\n","import type { Context } from '@deepseek-ai/cordis'\nimport { registerAssistantConversationNode } from './assistant.ts'\nimport { registerChatConversationView } from './chat-snapshot-builder.ts'\nimport { registerCommandConversationNode } from './command.ts'\nimport { registerCompactionConversationNode } from './compaction.ts'\nimport { registerUnknownConversationFallback } from './fallback.ts'\nimport { registerInboxConversationNodes } from './inbox.ts'\nimport { registerMessageConversationNode } from './message.ts'\nimport { registerRequestPromptConversationNode } from './request-prompt.ts'\nimport { registerRetryConversationNode } from './retry.ts'\nimport { registerToolConversationNode } from './tool.ts'\nimport { registerTurnErrorConversationNode } from './turn-error.ts'\nimport { registerTurnMaxTokensConversationNode } from './turn-max-tokens.ts'\nimport { registerTurnProcess } from './turn-process.ts'\nimport { registerTurnTailConversationNode } from './turn-tail.ts'\nimport { processGroupDefinition } from './process-groups.ts'\n\n/**\n * Register the Chat business Definitions and target builder contributed by this package.\n * @param ctx - owning UI Conversation context.\n */\nexport function registerConversationNodes(ctx: Context): void {\n registerInboxConversationNodes(ctx)\n registerMessageConversationNode(ctx)\n registerRequestPromptConversationNode(ctx)\n registerAssistantConversationNode(ctx)\n registerTurnProcess(ctx)\n registerToolConversationNode(ctx)\n registerCommandConversationNode(ctx)\n registerCompactionConversationNode(ctx)\n registerRetryConversationNode(ctx)\n registerTurnErrorConversationNode(ctx)\n registerTurnMaxTokensConversationNode(ctx)\n registerTurnTailConversationNode(ctx)\n registerUnknownConversationFallback(ctx)\n registerChatConversationView(ctx)\n ctx.uiConversation.groups.register(processGroupDefinition)\n}\n","/** Chat's language layers for Markdown fences: display math and unified-diff rows. */\nimport { useMemo } from 'react'\nimport type { ReactNode } from 'react'\nimport { FenceCodeBlock, FenceMathBlock } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { HocShare, PropsLocale, PropsRuntime, SlotMap } from '@deepseek-ai/dsh-client-ui-slots'\nimport { markdownLabels } from '../markdown-labels.ts'\n\n/** Props of the math layer: the fence and the next inner content. */\nexport type MathFenceLayerProps = PropsRuntime<'conversation.chat.markdown.fence'> & HocShare<SlotMap['conversation.chat.markdown.fence']>\n\n/** Props of the diff layer: the fence and the Chat locale seat. */\nexport type DiffFenceLayerProps = PropsRuntime<'conversation.chat.markdown.fence'> & PropsLocale<'chat'>\n\n/**\n * Show a `math` fence as display TeX once its document settles; while it\n * streams, the inner code block shows the source so a partial formula never\n * renders as an error.\n * @param props - the fence and the inner content.\n * @returns the formula, or the inner content while streaming.\n */\nexport function MathFenceLayer({ code, streaming, children }: MathFenceLayerProps): ReactNode {\n return streaming ? children : <FenceMathBlock code={code} />\n}\n\n/**\n * Show a `diff` or `patch` fence as unified-diff rows in place of the inner code block.\n * @param props - the fence and the Chat locale seat.\n * @returns the diff code block.\n */\nexport function DiffFenceLayer({ lang, code, streaming, t }: DiffFenceLayerProps): ReactNode {\n const labels = useMemo(() => markdownLabels(t).code, [t])\n return <FenceCodeBlock lang={lang} code={code} streaming={streaming} labels={labels} diff />\n}\n","/** Registration of Chat's Markdown fence layers. */\nimport type { Context } from '@deepseek-ai/cordis'\nimport { NS } from '../locale.ts'\nimport { DiffFenceLayer, MathFenceLayer } from './FenceLayers.tsx'\n\n/**\n * Register Chat's fence layers into the flow's language-keyed fence Slot;\n * they follow its declaration and the plugin's lifetime. Ids stay literal so\n * the Client slot catalog can name each occupied layer.\n * @param ctx - the Chat plugin context.\n */\nexport function registerFenceLayers(ctx: Context): void {\n ctx.slots.inject('conversation.chat.markdown.fence', () => ctx.slots.register({\n name: 'conversation.chat.markdown.fence', key: 'math', id: '@deepseek-ai/dsh-client-ui-chat/fence/math',\n }, MathFenceLayer))\n ctx.slots.inject('conversation.chat.markdown.fence', () => ctx.slots.register({\n name: 'conversation.chat.markdown.fence', key: 'diff', id: '@deepseek-ai/dsh-client-ui-chat/fence/diff', locale: NS,\n }, DiffFenceLayer))\n ctx.slots.inject('conversation.chat.markdown.fence', () => ctx.slots.register({\n name: 'conversation.chat.markdown.fence', key: 'patch', id: '@deepseek-ai/dsh-client-ui-chat/fence/diff', locale: NS,\n }, DiffFenceLayer))\n}\n","/**\n * The frame-wide `shell.overlay` host for quota notices. It holds the one live\n * notice for the whole app, so leaving the Chat panel does not drop it. A\n * `shell.quota-notice` entry may replace the generic Toast for codes it claims.\n */\nimport { Fragment } from 'react'\nimport { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { QuotaNoticeHostProps, QuotaNoticeOwnerProps } from '../contract/slots.ts'\n\n/**\n * @param props - the live notice, its dismissal, the chain outlet, and the locale seat.\n * @returns the notice on display, or null while none is live.\n */\nexport function QuotaNoticeHost({ useNotice, dismissNotice, keepNoticeOpen, renderSlotChain, t }: QuotaNoticeHostProps) {\n const notice = useNotice(current => current)\n if (notice === null) return null\n const owner: QuotaNoticeOwnerProps = {\n code: notice.code, message: t('message.failure.quota'), dismiss: dismissNotice, keepOpen: keepNoticeOpen,\n }\n return (\n <Fragment key={`quota-notice-${String(notice.seq)}`}>\n {renderSlotChain('shell.quota-notice', owner, {\n fallback: <Toast text={owner.message} icon={<IconWarningOutlineRegular size={18} />} onDone={dismissNotice} />,\n })}\n </Fragment>\n )\n}\n","//#region lib/types/misc.js\n/** No-op callback returning `undefined` at runtime and `any` at type level. */\nfunction noop() {}\n/** Return true when a value is `null` or `undefined`. */\nfunction isNullable(value) {\n\treturn value === null || value === void 0;\n}\n/** Return true when a value is neither `null` nor `undefined`. */\nfunction isNonNullable(value) {\n\treturn !isNullable(value);\n}\n/** Return true for non-array object values. */\nfunction isPlainObject(data) {\n\treturn data && typeof data === \"object\" && !Array.isArray(data);\n}\n/** Filter object entries and return a new object. */\nfunction filterKeys(object, filter) {\n\treturn Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));\n}\n/** Map object values while preserving the original key set. */\nfunction mapValues(object, transform) {\n\treturn Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));\n}\n/** Pick selected keys from an object, optionally including `undefined` values. */\nfunction pick(source, keys, forced) {\n\tif (!keys) return { ...source };\n\tconst result = {};\n\tfor (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];\n\treturn result;\n}\n/** Omit selected keys from a shallow object copy. */\nfunction omit(source, keys) {\n\tif (!keys) return { ...source };\n\tconst result = { ...source };\n\tfor (const key of keys) Reflect.deleteProperty(result, key);\n\treturn result;\n}\n/** Define a non-enumerable writable property and return the object. */\nfunction defineProperty(object, key, value) {\n\treturn Object.defineProperty(object, key, {\n\t\twritable: true,\n\t\tvalue,\n\t\tenumerable: false\n\t});\n}\n//#endregion\n//#region lib/types/array.js\n/** Return true when every item in `array2` is present in `array1`. */\nfunction contain(array1, array2) {\n\treturn array2.every((item) => array1.includes(item));\n}\n/** Return items that appear in both arrays. */\nfunction intersection(array1, array2) {\n\treturn array1.filter((item) => array2.includes(item));\n}\n/** Return items from `array1` that do not appear in `array2`. */\nfunction difference(array1, array2) {\n\treturn array1.filter((item) => !array2.includes(item));\n}\n/** Return the set-union of two arrays while preserving first occurrence order. */\nfunction union(array1, array2) {\n\treturn Array.from(new Set([...array1, ...array2]));\n}\n/** Remove duplicate values while preserving first occurrence order. */\nfunction deduplicate(array) {\n\treturn [...new Set(array)];\n}\n/** Remove one item from an array and report whether it was found. */\nfunction remove(list, item) {\n\tconst index = list?.indexOf(item);\n\tif (index >= 0) {\n\t\tlist.splice(index, 1);\n\t\treturn true;\n\t} else return false;\n}\n/** Normalize nullish, scalar, or array input to an array. */\nfunction makeArray(source) {\n\treturn Array.isArray(source) ? source : isNullable(source) ? [] : [source];\n}\n//#endregion\n//#region lib/types/volatile.js\n/** Shared config references used by schema validators and plugin runtimes. */\nconst write = Symbol.for(\"cosmokit.volatile.write\");\nfunction snapshot(value, ancestors = /* @__PURE__ */ new Set()) {\n\tif (typeof value === \"function\") throw new TypeError(\"volatile config cannot contain functions\");\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (ancestors.has(value)) throw new TypeError(\"volatile config cannot contain cycles\");\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));\n\t\tif (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError(\"volatile config objects must be plain objects or arrays\");\n\t\treturn Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n/**\n* Create a detached reference containing an immutable copy of the supplied data.\n* @param value - validated config data; class instances and functions are unsupported.\n* @returns a reference whose value is updated only by its owning runtime.\n*/\nfunction createVolatile(value) {\n\tlet current = snapshot(value);\n\treturn Object.freeze({\n\t\tget: () => current,\n\t\t[write]: (value) => {\n\t\t\tcurrent = value;\n\t\t}\n\t});\n}\n/**\n* Identify references across ESM/CJS copies of the shared library.\n* @param value - a parsed config value.\n* @returns whether the value implements the shared reference protocol.\n*/\nfunction isVolatile(value) {\n\treturn typeof value === \"object\" && value !== null && write in value;\n}\n/**\n* Collect config references without descending into their snapshots or opaque objects.\n* @internal\n* @param value - parsed config; cyclic ordinary fields are visited once per path.\n* @returns references and their object-key paths, including an empty path for a root reference.\n*/\nfunction volatileEntries(value) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction visit(value, path) {\n\t\tif (isVolatile(value)) return [{\n\t\t\tpath,\n\t\t\tref: value\n\t\t}];\n\t\tif (!value || typeof value !== \"object\" || ancestors.has(value)) return [];\n\t\tif (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [];\n\t\tancestors.add(value);\n\t\ttry {\n\t\t\treturn Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]));\n\t\t} finally {\n\t\t\tancestors.delete(value);\n\t\t}\n\t}\n\treturn visit(value, []);\n}\n/**\n* Commit an already validated immutable snapshot from another reference.\n* @internal\n* @param target - the owning plugin's stable reference.\n* @param source - a newly parsed candidate reference.\n*/\nfunction updateVolatile(target, source) {\n\ttarget[write](source.get());\n}\n//#endregion\n//#region lib/types/types.js\n/** Test values using `instanceof` with a `toStringTag` fallback. */\nfunction is(type, value) {\n\tif (arguments.length === 1) return (value) => is(type, value);\n\treturn type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;\n}\nfunction isArrayBufferLike(value) {\n\treturn is(\"ArrayBuffer\", value) || is(\"SharedArrayBuffer\", value);\n}\nfunction isArrayBufferSource(value) {\n\treturn isArrayBufferLike(value) || ArrayBuffer.isView(value);\n}\n/** Binary source detection and base64/hex conversion helpers. */\nvar Binary;\n(function(Binary) {\n\tBinary.is = isArrayBufferLike;\n\tBinary.isSource = isArrayBufferSource;\n\tfunction fromSource(source) {\n\t\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\t\telse return source;\n\t}\n\tBinary.fromSource = fromSource;\n\tfunction toBase64(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"base64\");\n\t\tlet binary = \"\";\n\t\tconst bytes = new Uint8Array(source);\n\t\tfor (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);\n\t\treturn btoa(binary);\n\t}\n\tBinary.toBase64 = toBase64;\n\tfunction fromBase64(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"base64\"));\n\t\treturn Uint8Array.from(atob(source), (c) => c.charCodeAt(0));\n\t}\n\tBinary.fromBase64 = fromBase64;\n\tfunction toHex(source) {\n\t\tsource = fromSource(source);\n\t\tif (typeof Buffer !== \"undefined\") return Buffer.from(source).toString(\"hex\");\n\t\treturn Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\t}\n\tBinary.toHex = toHex;\n\tfunction fromHex(source) {\n\t\tif (typeof Buffer !== \"undefined\") return fromSource(Buffer.from(source, \"hex\"));\n\t\tconst hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);\n\t\tconst buffer = [];\n\t\tfor (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));\n\t\treturn Uint8Array.from(buffer).buffer;\n\t}\n\tBinary.fromHex = fromHex;\n})(Binary || (Binary = {}));\n/** Decode a base64 string into binary data. */\nconst base64ToArrayBuffer = Binary.fromBase64;\n/** Encode binary data as base64. */\nconst arrayBufferToBase64 = Binary.toBase64;\n/** Decode a hex string into binary data. */\nconst hexToArrayBuffer = Binary.fromHex;\n/** Encode binary data as hex. */\nconst arrayBufferToHex = Binary.toHex;\n/** Deep-clone common JavaScript values while preserving prototypes and cycles. */\nfunction clone(source, refs = /* @__PURE__ */ new Map()) {\n\tif (!source || typeof source !== \"object\") return source;\n\tif (is(\"Date\", source)) return new Date(source.valueOf());\n\tif (is(\"RegExp\", source)) return new RegExp(source.source, source.flags);\n\tif (isArrayBufferLike(source)) return source.slice(0);\n\tif (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);\n\tconst cached = refs.get(source);\n\tif (cached) return cached;\n\tif (Array.isArray(source)) {\n\t\tconst result = [];\n\t\trefs.set(source, result);\n\t\tsource.forEach((value, index) => {\n\t\t\tresult[index] = Reflect.apply(clone, null, [value, refs]);\n\t\t});\n\t\treturn result;\n\t}\n\tconst result = Object.create(Object.getPrototypeOf(source));\n\trefs.set(source, result);\n\tfor (const key of Reflect.ownKeys(source)) {\n\t\tconst descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };\n\t\tif (\"value\" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);\n\t\tReflect.defineProperty(result, key, descriptor);\n\t}\n\treturn result;\n}\n/**\n* Compare values recursively, treating two volatile references as equal regardless of value.\n* Strict comparison distinguishes null/undefined, treats opaque objects by identity,\n* compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.\n* @param a - first value.\n* @param b - second value.\n* @param strict - whether to require strict data equality outside volatile references.\n* @returns whether the values compare equal.\n*/\nfunction deepEqual(a, b, strict) {\n\tconst ancestors = /* @__PURE__ */ new Set();\n\tfunction compare(a, b) {\n\t\tif (a === b) return true;\n\t\tif (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);\n\t\tif (!strict && isNullable(a) && isNullable(b)) return true;\n\t\tif (typeof a !== typeof b || typeof a !== \"object\" || !a || !b) return false;\n\t\tif (ancestors.has(a)) return false;\n\t\tfunction check(test, then) {\n\t\t\treturn test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;\n\t\t}\n\t\tancestors.add(a);\n\t\ttry {\n\t\t\treturn check(Array.isArray, (a, b) => {\n\t\t\t\tif (a.length !== b.length) return false;\n\t\t\t\tfor (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? 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) => {\n\t\t\t\tif (a.byteLength !== b.byteLength) return false;\n\t\t\t\tconst viewA = new Uint8Array(a);\n\t\t\t\tconst viewB = new Uint8Array(b);\n\t\t\t\tfor (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;\n\t\t\t\treturn true;\n\t\t\t}) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({\n\t\t\t\t...a,\n\t\t\t\t...b\n\t\t\t}).every((key) => compare(a[key], b[key])));\n\t\t} finally {\n\t\t\tancestors.delete(a);\n\t\t}\n\t}\n\treturn compare(a, b);\n}\n//#endregion\n//#region lib/types/string.js\n/** Uppercase the first character of a string. */\nfunction capitalize(source) {\n\treturn source.charAt(0).toUpperCase() + source.slice(1);\n}\n/** Lowercase the first character of a string. */\nfunction uncapitalize(source) {\n\treturn source.charAt(0).toLowerCase() + source.slice(1);\n}\n/** Convert dash or underscore delimited text to camelCase. */\nfunction camelCase(source) {\n\treturn source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());\n}\nfunction tokenize(source, delimiters, delimiter) {\n\tconst output = [];\n\tlet state = 0;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst code = source.charCodeAt(i);\n\t\tif (code >= 65 && code <= 90) {\n\t\t\tif (state === 1) {\n\t\t\t\tconst next = source.charCodeAt(i + 1);\n\t\t\t\tif (next >= 97 && next <= 122) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t} else {\n\t\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\t\toutput.push(code + 32);\n\t\t\t}\n\t\t\tstate = 1;\n\t\t} else if (code >= 97 && code <= 122) {\n\t\t\toutput.push(code);\n\t\t\tstate = 2;\n\t\t} else if (delimiters.includes(code)) {\n\t\t\tif (state !== 0) output.push(delimiter);\n\t\t\tstate = 0;\n\t\t} else output.push(code);\n\t}\n\treturn String.fromCharCode(...output);\n}\n/** Convert text to dash-delimited parameter case. */\nfunction paramCase(source) {\n\treturn tokenize(source, [45, 95], 45);\n}\n/** Convert text to underscore-delimited snake case. */\nfunction snakeCase(source) {\n\treturn tokenize(source, [45, 95], 95);\n}\n/** Runtime alias for `camelCase`. */\nconst camelize = camelCase;\n/** Runtime alias for `paramCase`. */\nconst hyphenate = paramCase;\n/** Format a property key as a JavaScript member access suffix. */\nfunction formatProperty(key) {\n\tif (typeof key !== \"string\") return `[${key.toString()}]`;\n\treturn /^[a-z_$][\\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n}\n/** Remove one trailing slash from a path string. */\nfunction trimSlash(source) {\n\treturn source.replace(/\\/$/, \"\");\n}\n/** Ensure a path starts with `/` and has no trailing slash. */\nfunction sanitize(source) {\n\tif (!source.startsWith(\"/\")) source = \"/\" + source;\n\treturn trimSlash(source);\n}\n//#endregion\n//#region lib/types/time.js\n/** Time constants plus parsing and formatting helpers. */\nvar Time;\n(function(Time) {\n\tTime.millisecond = 1;\n\tTime.second = 1e3;\n\tTime.minute = Time.second * 60;\n\tTime.hour = Time.minute * 60;\n\tTime.day = Time.hour * 24;\n\tTime.week = Time.day * 7;\n\tlet timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();\n\tfunction setTimezoneOffset(offset) {\n\t\ttimezoneOffset = offset;\n\t}\n\tTime.setTimezoneOffset = setTimezoneOffset;\n\tfunction getTimezoneOffset() {\n\t\treturn timezoneOffset;\n\t}\n\tTime.getTimezoneOffset = getTimezoneOffset;\n\tfunction getDateNumber(date = /* @__PURE__ */ new Date(), offset) {\n\t\tif (typeof date === \"number\") date = new Date(date);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn Math.floor((date.valueOf() / Time.minute - offset) / 1440);\n\t}\n\tTime.getDateNumber = getDateNumber;\n\tfunction fromDateNumber(value, offset) {\n\t\tconst date = new Date(value * Time.day);\n\t\tif (offset === void 0) offset = timezoneOffset;\n\t\treturn new Date(+date + offset * Time.minute);\n\t}\n\tTime.fromDateNumber = fromDateNumber;\n\tconst numeric = /\\d+(?:\\.\\d+)?/.source;\n\tconst timeRegExp = new RegExp(`^${[\n\t\t\"w(?:eek(?:s)?)?\",\n\t\t\"d(?:ay(?:s)?)?\",\n\t\t\"h(?:our(?:s)?)?\",\n\t\t\"m(?:in(?:ute)?(?:s)?)?\",\n\t\t\"s(?:ec(?:ond)?(?:s)?)?\"\n\t].map((unit) => `(${numeric}${unit})?`).join(\"\")}$`);\n\tfunction parseTime(source) {\n\t\tconst capture = timeRegExp.exec(source);\n\t\tif (!capture) return 0;\n\t\treturn (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);\n\t}\n\tTime.parseTime = parseTime;\n\tfunction parseDate(date) {\n\t\tconst parsed = parseTime(date);\n\t\tif (parsed) date = Date.now() + parsed;\n\t\telse if (/^\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;\n\t\telse if (/^\\d{1,2}-\\d{1,2}-\\d{1,2}(:\\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;\n\t\treturn date ? new Date(date) : /* @__PURE__ */ new Date();\n\t}\n\tTime.parseDate = parseDate;\n\tfunction format(ms) {\n\t\tconst abs = Math.abs(ms);\n\t\tif (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + \"d\";\n\t\telse if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + \"h\";\n\t\telse if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + \"m\";\n\t\telse if (abs >= Time.second) return Math.round(ms / Time.second) + \"s\";\n\t\treturn ms + \"ms\";\n\t}\n\tTime.format = format;\n\tfunction toDigits(source, length = 2) {\n\t\treturn source.toString().padStart(length, \"0\");\n\t}\n\tTime.toDigits = toDigits;\n\tfunction template(template, time = /* @__PURE__ */ new Date()) {\n\t\treturn 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));\n\t}\n\tTime.template = template;\n})(Time || (Time = {}));\n//#endregion\nexport { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, createVolatile, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, isVolatile, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union, updateVolatile, volatileEntries };\n","import { Binary, clone, createVolatile, deepEqual, filterKeys, isNullable, isPlainObject, isVolatile, pick, valueMap } from \"@deepseek-ai/cosmokit\";\n//#region lib/types/index.js\nconst kSchema = Symbol.for(\"schemastery\");\nconst kValidationError = Symbol.for(\"ValidationError\");\nglobalThis.__schemastery_index__ ??= 0;\nglobalThis.__schemastery_refs__ = void 0;\nvar ValidationError = class extends TypeError {\n\toptions;\n\tname = \"ValidationError\";\n\tconstructor(message, options) {\n\t\tlet prefix = \"$\";\n\t\tfor (const segment of options.path || []) if (typeof segment === \"string\") prefix += \".\" + segment;\n\t\telse if (typeof segment === \"number\") prefix += \"[\" + segment + \"]\";\n\t\telse if (typeof segment === \"symbol\") prefix += `[Symbol(${segment.toString()})]`;\n\t\tif (prefix.startsWith(\".\")) prefix = prefix.slice(1);\n\t\tsuper((prefix === \"$\" ? \"\" : `${prefix} `) + message);\n\t\tthis.options = options;\n\t}\n\tstatic is(error) {\n\t\treturn !!error?.[kValidationError];\n\t}\n};\nObject.defineProperty(ValidationError.prototype, kValidationError, { value: true });\nconst Schema = function(options) {\n\tconst schema = function(data, options = {}) {\n\t\treturn Schema.resolve(data, schema, options)[0];\n\t};\n\tif (options.refs) {\n\t\tconst refs = valueMap(options.refs, (options) => new Schema(options));\n\t\tconst getRef = (uid) => refs[uid];\n\t\tfor (const key in refs) {\n\t\t\tconst options = refs[key];\n\t\t\toptions.sKey = getRef(options.sKey);\n\t\t\toptions.inner = getRef(options.inner);\n\t\t\toptions.list = options.list && options.list.map(getRef);\n\t\t\toptions.dict = options.dict && valueMap(options.dict, getRef);\n\t\t}\n\t\treturn refs[options.uid];\n\t}\n\tObject.assign(schema, options);\n\tif (typeof schema.callback === \"string\") try {\n\t\tschema.callback = new Function(\"return \" + schema.callback)();\n\t} catch {}\n\tObject.defineProperty(schema, \"uid\", { value: globalThis.__schemastery_index__++ });\n\tObject.setPrototypeOf(schema, Schema.prototype);\n\tschema.meta ||= {};\n\tschema.toString = schema.toString.bind(schema);\n\treturn schema;\n};\nSchema.prototype = Object.create(Function.prototype);\nSchema.prototype[kSchema] = true;\nObject.defineProperty(Schema.prototype, \"~standard\", { get() {\n\treturn {\n\t\tversion: 1,\n\t\tvendor: \"schemastery\",\n\t\tvalidate: (value) => {\n\t\t\ttry {\n\t\t\t\treturn { value: Schema.resolve(value, this, {})[0] };\n\t\t\t} catch (error) {\n\t\t\t\tif (ValidationError.is(error)) return { issues: [{\n\t\t\t\t\tmessage: error.message,\n\t\t\t\t\tpath: error.options.path\n\t\t\t\t}] };\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t};\n} });\nSchema.ValidationError = ValidationError;\nSchema.prototype.toJSON = function toJSON() {\n\tif (globalThis.__schemastery_refs__) {\n\t\tglobalThis.__schemastery_refs__[this.uid] ??= JSON.parse(JSON.stringify({ ...this }));\n\t\treturn this.uid;\n\t}\n\tglobalThis.__schemastery_refs__ = { [this.uid]: { ...this } };\n\tglobalThis.__schemastery_refs__[this.uid] = JSON.parse(JSON.stringify({ ...this }));\n\tconst result = {\n\t\tuid: this.uid,\n\t\trefs: globalThis.__schemastery_refs__\n\t};\n\tglobalThis.__schemastery_refs__ = void 0;\n\treturn result;\n};\nSchema.prototype.set = function set(key, value) {\n\tthis.dict[key] = value;\n\treturn this;\n};\nSchema.prototype.push = function push(value) {\n\tthis.list.push(value);\n\treturn this;\n};\nfunction mergeDesc(original, messages) {\n\tconst result = typeof original === \"string\" ? { \"\": original } : { ...original };\n\tfor (const locale in messages) {\n\t\tconst value = messages[locale];\n\t\tif (value?.$description || value?.$desc) result[locale] = value.$description || value.$desc;\n\t\telse if (typeof value === \"string\") result[locale] = value;\n\t}\n\treturn result;\n}\nfunction getInner(value) {\n\treturn value?.$value ?? value?.$inner;\n}\nfunction extractKeys(data) {\n\treturn filterKeys(data ?? {}, (key) => !key.startsWith(\"$\"));\n}\nSchema.prototype.i18n = function i18n(messages) {\n\tconst schema = Schema(this);\n\tconst desc = mergeDesc(schema.meta.description, messages);\n\tif (Object.keys(desc).length) schema.meta.description = desc;\n\tif (schema.dict) schema.dict = valueMap(schema.dict, (inner, key) => {\n\t\treturn inner.i18n(valueMap(messages, (data) => getInner(data)?.[key] ?? data?.[key]));\n\t});\n\tif (schema.list) schema.list = schema.list.map((inner, index) => {\n\t\treturn inner.i18n(valueMap(messages, (data = {}) => {\n\t\t\tif (Array.isArray(getInner(data))) return getInner(data)[index];\n\t\t\tif (Array.isArray(data)) return data[index];\n\t\t\treturn extractKeys(data);\n\t\t}));\n\t});\n\tif (schema.inner) schema.inner = schema.inner.i18n(valueMap(messages, (data) => {\n\t\tif (getInner(data)) return getInner(data);\n\t\treturn extractKeys(data);\n\t}));\n\tif (schema.sKey) schema.sKey = schema.sKey.i18n(valueMap(messages, (data) => data?.$key));\n\treturn schema;\n};\nSchema.prototype.extra = function extra(key, value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"required\",\n\t\"disabled\",\n\t\"collapse\",\n\t\"hidden\",\n\t\"loose\"\n]) Object.assign(Schema.prototype, { [key](value = true) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.deprecated = function deprecated() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"deprecated\",\n\t\ttype: \"danger\"\n\t});\n\treturn schema;\n};\nSchema.prototype.experimental = function experimental() {\n\tconst schema = Schema(this);\n\tschema.meta.badges ||= [];\n\tschema.meta.badges.push({\n\t\ttext: \"experimental\",\n\t\ttype: \"warning\"\n\t});\n\treturn schema;\n};\nSchema.prototype.pattern = function pattern(regexp) {\n\tconst schema = Schema(this);\n\tconst pattern = pick(regexp, [\"source\", \"flags\"]);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\tpattern\n\t};\n\treturn schema;\n};\nSchema.prototype.simplify = function simplify(value) {\n\tif (isVolatile(value)) value = value.get();\n\tif (deepEqual(value, this.meta.default, this.type === \"dict\")) return null;\n\tif (isNullable(value)) return value;\n\tif (this.type === \"object\" || this.type === \"dict\") {\n\t\tconst result = {};\n\t\tfor (const key in value) {\n\t\t\tconst item = (this.type === \"object\" ? this.dict[key] : this.inner)?.simplify(value[key]);\n\t\t\tif (this.type === \"dict\" || !isNullable(item)) result[key] = item;\n\t\t}\n\t\tif (deepEqual(result, this.meta.default, this.type === \"dict\")) return null;\n\t\treturn result;\n\t} else if (this.type === \"array\" || this.type === \"tuple\") {\n\t\tconst result = [];\n\t\tvalue.forEach((value, index) => {\n\t\t\tconst schema = this.type === \"array\" ? this.inner : this.list[index];\n\t\t\tconst item = schema ? schema.simplify(value) : value;\n\t\t\tresult.push(item);\n\t\t});\n\t\treturn result;\n\t} else if (this.type === \"intersect\") {\n\t\tconst result = {};\n\t\tfor (const item of this.list) Object.assign(result, item.simplify(value));\n\t\treturn result;\n\t} else if (this.type === \"union\") for (const schema of this.list) try {\n\t\tSchema.resolve(value, schema, {});\n\t\treturn schema.simplify(value);\n\t} catch {}\n\treturn value;\n};\nSchema.prototype.toString = function toString(inline) {\n\treturn formatters[this.type]?.(this, inline) ?? `Schema<${this.type}>`;\n};\nSchema.prototype.role = function role(role, extra) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\trole,\n\t\textra\n\t};\n\treturn schema;\n};\nfor (const key of [\n\t\"default\",\n\t\"link\",\n\t\"comment\",\n\t\"description\",\n\t\"max\",\n\t\"min\",\n\t\"step\"\n]) Object.assign(Schema.prototype, { [key](value) {\n\tconst schema = Schema(this);\n\tschema.meta = {\n\t\t...schema.meta,\n\t\t[key]: value\n\t};\n\treturn schema;\n} });\nSchema.prototype.volatile = function volatile() {\n\tif (this.meta.volatile) throw new TypeError(\"volatile schema is already wrapped\");\n\treturn this.extra(\"volatile\", true);\n};\nconst resolvers = {};\nconst checkedVolatile = Symbol(\"checked-volatile-schema\");\nfunction validateVolatileSchema(schema, path = [], blocked = false, seen = /* @__PURE__ */ new Map()) {\n\tconst states = seen.get(schema) ?? /* @__PURE__ */ new Set();\n\tif (states.has(blocked)) return;\n\tstates.add(blocked);\n\tseen.set(schema, states);\n\tif (schema.meta?.volatile && blocked) throw new ValidationError(\"volatile fields require a fixed object path without an enclosing volatile field\", { path });\n\tconst nested = blocked || !!schema.meta?.volatile;\n\tif (schema.dict) for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path, key], nested, seen);\n\tif (schema.sKey) validateVolatileSchema(schema.sKey, [...path, \"<key>\"], true, seen);\n\tif (schema.inner && (schema.type !== \"lazy\" || schema.inner[kSchema])) validateVolatileSchema(schema.inner, [...path, \"*\"], true, seen);\n\tif (schema.list) for (let index = 0; index < schema.list.length; index++) validateVolatileSchema(schema.list[index], [...path, String(index)], true, seen);\n}\nSchema.extend = function extend(type, resolve) {\n\tresolvers[type] = resolve;\n};\nSchema.resolve = function resolve(data, schema, options = {}, strict = false) {\n\tif (!schema) return [data];\n\tif (!options[checkedVolatile]) {\n\t\tvalidateVolatileSchema(schema, options.path);\n\t\toptions = {\n\t\t\t...options,\n\t\t\t[checkedVolatile]: true\n\t\t};\n\t}\n\tif (schema.meta?.volatile) {\n\t\tconst inner = Schema(schema);\n\t\tinner.meta = {\n\t\t\t...schema.meta,\n\t\t\tvolatile: false\n\t\t};\n\t\tconst [value, adapted] = Schema.resolve(data, inner, options, strict);\n\t\ttry {\n\t\t\treturn [createVolatile(value), adapted];\n\t\t} catch (error) {\n\t\t\tthrow new ValidationError(error instanceof Error ? error.message : String(error), options);\n\t\t}\n\t}\n\tif (options.ignore?.(data, schema)) return [data];\n\tif (isNullable(data) && schema.type !== \"lazy\") {\n\t\tif (schema.meta.required) throw new ValidationError(`missing required value`, options);\n\t\tlet current = schema;\n\t\tlet fallback = schema.meta.default;\n\t\twhile (current?.type === \"intersect\" && isNullable(fallback)) {\n\t\t\tcurrent = current.list[0];\n\t\t\tfallback = current?.meta.default;\n\t\t}\n\t\tif (isNullable(fallback)) return [data];\n\t\tdata = clone(fallback);\n\t}\n\tconst callback = resolvers[schema.type];\n\tif (!callback) throw new ValidationError(`unsupported type \"${schema.type}\"`, options);\n\ttry {\n\t\treturn callback(data, schema, options, strict);\n\t} catch (error) {\n\t\tif (!schema.meta.loose) throw error;\n\t\treturn [schema.meta.default];\n\t}\n};\nSchema.from = function from(source) {\n\tif (isNullable(source)) return Schema.any();\n\telse if ([\n\t\t\"string\",\n\t\t\"number\",\n\t\t\"boolean\"\n\t].includes(typeof source)) return Schema.const(source).required();\n\telse if (source[kSchema]) return source;\n\telse if (typeof source === \"function\") switch (source) {\n\t\tcase String: return Schema.string().required();\n\t\tcase Number: return Schema.number().required();\n\t\tcase Boolean: return Schema.boolean().required();\n\t\tcase Function: return Schema.function().required();\n\t\tdefault: return Schema.is(source).required();\n\t}\n\telse throw new TypeError(`cannot infer schema from ${source}`);\n};\nSchema.lazy = function lazy(builder) {\n\tconst toJSON = () => {\n\t\tif (!schema.inner[kSchema]) {\n\t\t\tschema.inner = schema.builder();\n\t\t\tschema.inner.meta = {\n\t\t\t\t...schema.meta,\n\t\t\t\t...schema.inner.meta\n\t\t\t};\n\t\t}\n\t\treturn schema.inner.toJSON();\n\t};\n\tconst schema = new Schema({\n\t\ttype: \"lazy\",\n\t\tbuilder,\n\t\tinner: { toJSON }\n\t});\n\treturn schema;\n};\nSchema.natural = function natural() {\n\treturn Schema.number().step(1).min(0);\n};\nSchema.percent = function percent() {\n\treturn Schema.number().step(.01).min(0).max(1).role(\"slider\");\n};\nSchema.date = function date() {\n\treturn Schema.union([Schema.is(Date), Schema.transform(Schema.string().role(\"datetime\"), (value, options) => {\n\t\tconst date = new Date(value);\n\t\tif (isNaN(+date)) throw new ValidationError(`invalid date \"${value}\"`, options);\n\t\treturn date;\n\t}, true)]);\n};\nSchema.regExp = function regExp(flag = \"\") {\n\treturn Schema.union([Schema.is(RegExp), Schema.transform(Schema.string().role(\"regexp\", { flag }), (value, options) => {\n\t\ttry {\n\t\t\treturn new RegExp(value, flag);\n\t\t} catch (e) {\n\t\t\tthrow new ValidationError(e.message, options);\n\t\t}\n\t}, true)]);\n};\nSchema.arrayBuffer = function arrayBuffer(encoding) {\n\treturn Schema.union([\n\t\tSchema.is(ArrayBuffer),\n\t\tSchema.is(SharedArrayBuffer),\n\t\tSchema.transform(Schema.any(), (value, options) => {\n\t\t\tif (Binary.isSource(value)) return Binary.fromSource(value);\n\t\t\tthrow new ValidationError(`expected ArrayBufferSource but got ${value}`, options);\n\t\t}, true),\n\t\t...encoding ? [Schema.transform(Schema.string(), (value, options) => {\n\t\t\ttry {\n\t\t\t\treturn encoding === \"base64\" ? Binary.fromBase64(value) : Binary.fromHex(value);\n\t\t\t} catch (e) {\n\t\t\t\tthrow new ValidationError(e.message, options);\n\t\t\t}\n\t\t}, true)] : []\n\t]);\n};\nSchema.extend(\"lazy\", (data, schema, options, strict) => {\n\tif (!schema.inner[kSchema]) {\n\t\tschema.inner = schema.builder();\n\t\tschema.inner.meta = {\n\t\t\t...schema.meta,\n\t\t\t...schema.inner.meta\n\t\t};\n\t\tvalidateVolatileSchema(schema.inner, options.path, true);\n\t}\n\treturn Schema.resolve(data, schema.inner, options, strict);\n});\nSchema.extend(\"any\", (data) => {\n\treturn [data];\n});\nSchema.extend(\"never\", (data, _, options) => {\n\tthrow new ValidationError(`expected nullable but got ${data}`, options);\n});\nSchema.extend(\"const\", (data, { value }, options) => {\n\tif (deepEqual(data, value)) return [value];\n\tthrow new ValidationError(`expected ${value} but got ${data}`, options);\n});\nfunction checkWithinRange(data, meta, description, options, skipMin = false) {\n\tconst { max = Infinity, min = -Infinity } = meta;\n\tif (data > max) throw new ValidationError(`expected ${description} <= ${max} but got ${data}`, options);\n\tif (data < min && !skipMin) throw new ValidationError(`expected ${description} >= ${min} but got ${data}`, options);\n}\nSchema.extend(\"string\", (data, { meta }, options) => {\n\tif (typeof data !== \"string\") throw new ValidationError(`expected string but got ${data}`, options);\n\tif (meta.pattern) {\n\t\tconst regexp = new RegExp(meta.pattern.source, meta.pattern.flags);\n\t\tif (!regexp.test(data)) throw new ValidationError(`expect string to match regexp ${regexp}`, options);\n\t}\n\tcheckWithinRange(data.length, meta, \"string length\", options);\n\treturn [data];\n});\nfunction decimalShift(data, digits) {\n\tconst str = data.toString();\n\tif (str.includes(\"e\")) return data * Math.pow(10, digits);\n\tconst index = str.indexOf(\".\");\n\tif (index === -1) return data * Math.pow(10, digits);\n\tconst frac = str.slice(index + 1);\n\tconst integer = str.slice(0, index);\n\tif (frac.length <= digits) return +(integer + frac.padEnd(digits, \"0\"));\n\treturn +(integer + frac.slice(0, digits) + \".\" + frac.slice(digits));\n}\nfunction isMultipleOf(data, min, step) {\n\tstep = Math.abs(step);\n\tif (!/^\\d+\\.\\d+$/.test(step.toString())) return (data - min) % step === 0;\n\tconst index = step.toString().indexOf(\".\");\n\tconst digits = step.toString().slice(index + 1).length;\n\treturn Math.abs(decimalShift(data, digits) - decimalShift(min, digits)) % decimalShift(step, digits) === 0;\n}\nSchema.extend(\"number\", (data, { meta }, options) => {\n\tif (typeof data !== \"number\") throw new ValidationError(`expected number but got ${data}`, options);\n\tcheckWithinRange(data, meta, \"number\", options);\n\tconst { step } = meta;\n\tif (step && !isMultipleOf(data, meta.min ?? 0, step)) throw new ValidationError(`expected number multiple of ${step} but got ${data}`, options);\n\treturn [data];\n});\nSchema.extend(\"boolean\", (data, _, options) => {\n\tif (typeof data === \"boolean\") return [data];\n\tthrow new ValidationError(`expected boolean but got ${data}`, options);\n});\nSchema.extend(\"bitset\", (data, { bits, meta }, options) => {\n\tlet value = 0, keys = [];\n\tif (typeof data === \"number\") {\n\t\tvalue = data;\n\t\tfor (const key in bits) if (data & bits[key]) keys.push(key);\n\t} else if (Array.isArray(data)) {\n\t\tkeys = data;\n\t\tfor (const key of keys) {\n\t\t\tif (typeof key !== \"string\") throw new ValidationError(`expected string but got ${key}`, options);\n\t\t\tif (key in bits) value |= bits[key];\n\t\t}\n\t} else throw new ValidationError(`expected number or array but got ${data}`, options);\n\tif (value === meta.default) return [value];\n\treturn [value, keys];\n});\nSchema.extend(\"function\", (data, _, options) => {\n\tif (typeof data === \"function\") return [data];\n\tthrow new ValidationError(`expected function but got ${data}`, options);\n});\nSchema.extend(\"is\", (data, { constructor }, options) => {\n\tif (typeof constructor === \"function\") {\n\t\tif (data instanceof constructor) return [data];\n\t\tthrow new ValidationError(`expected ${constructor.name} but got ${data}`, options);\n\t} else {\n\t\tif (isNullable(data)) throw new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t\tlet prototype = Object.getPrototypeOf(data);\n\t\twhile (prototype) {\n\t\t\tif (prototype.constructor?.name === constructor) return [data];\n\t\t\tprototype = Object.getPrototypeOf(prototype);\n\t\t}\n\t\tthrow new ValidationError(`expected ${constructor} but got ${data}`, options);\n\t}\n});\nfunction property(data, key, schema, options) {\n\ttry {\n\t\tconst [value, adapted] = Schema.resolve(data[key], schema, {\n\t\t\t...options,\n\t\t\tpath: [...options.path || [], key]\n\t\t});\n\t\tif (adapted !== void 0) data[key] = adapted;\n\t\treturn value;\n\t} catch (e) {\n\t\tif (!options?.autofix) throw e;\n\t\tdelete data[key];\n\t\treturn schema.meta.volatile ? createVolatile(schema.meta.default) : schema.meta.default;\n\t}\n}\nSchema.extend(\"array\", (data, { inner, meta }, options) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tcheckWithinRange(data.length, meta, \"array length\", options, !isNullable(inner.meta.default));\n\treturn [data.map((_, index) => property(data, index, inner, options))];\n});\nSchema.extend(\"dict\", (data, { inner, sKey }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in data) {\n\t\tlet rKey;\n\t\ttry {\n\t\t\trKey = Schema.resolve(key, sKey, options)[0];\n\t\t} catch (error) {\n\t\t\tif (strict) continue;\n\t\t\tthrow error;\n\t\t}\n\t\tresult[rKey] = property(data, key, inner, options);\n\t\tdata[rKey] = data[key];\n\t\tif (key !== rKey) delete data[key];\n\t}\n\treturn [result];\n});\nSchema.extend(\"tuple\", (data, { list }, options, strict) => {\n\tif (!Array.isArray(data)) throw new ValidationError(`expected array but got ${data}`, options);\n\tconst result = list.map((inner, index) => property(data, index, inner, options));\n\tif (strict) return [result];\n\tresult.push(...data.slice(list.length));\n\treturn [result];\n});\nfunction merge(result, data) {\n\tfor (const key in data) {\n\t\tif (key in result) continue;\n\t\tresult[key] = data[key];\n\t}\n}\nSchema.extend(\"object\", (data, { dict }, options, strict) => {\n\tif (!isPlainObject(data)) throw new ValidationError(`expected object but got ${data}`, options);\n\tconst result = {};\n\tfor (const key in dict) {\n\t\tconst value = property(data, key, dict[key], options);\n\t\tif (!isNullable(value) || key in data) result[key] = value;\n\t}\n\tif (!strict) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"union\", (data, { list, toString }, options, strict) => {\n\tconst messages = [];\n\tfor (const inner of list) try {\n\t\treturn Schema.resolve(data, inner, options, strict);\n\t} catch (error) {\n\t\tmessages.push(error);\n\t}\n\tthrow new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n});\nSchema.extend(\"intersect\", (data, { list, toString }, options, strict) => {\n\tif (!list.length) return [data];\n\tlet result;\n\tfor (const inner of list) {\n\t\tconst value = Schema.resolve(data, inner, options, true)[0];\n\t\tif (isNullable(value)) continue;\n\t\tif (isNullable(result)) result = value;\n\t\telse if (typeof result !== typeof value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t\telse if (typeof value === \"object\") merge(result ??= {}, value);\n\t\telse if (result !== value) throw new ValidationError(`expected ${toString()} but got ${JSON.stringify(data)}`, options);\n\t}\n\tif (!strict && isPlainObject(data)) merge(result, data);\n\treturn [result];\n});\nSchema.extend(\"transform\", (data, { inner, callback, preserve }, options) => {\n\tconst [result, adapted = data] = Schema.resolve(data, inner, options, true);\n\tif (preserve) return [callback(result)];\n\telse return [callback(result), callback(adapted)];\n});\nconst formatters = {};\nfunction defineMethod(name, keys, format) {\n\tformatters[name] = format;\n\tObject.assign(Schema, { [name](...args) {\n\t\tconst schema = new Schema({ type: name });\n\t\tkeys.forEach((key, index) => {\n\t\t\tswitch (key) {\n\t\t\t\tcase \"sKey\":\n\t\t\t\t\tschema.sKey = args[index] ?? Schema.string();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tschema.inner = Schema.from(args[index]);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"list\":\n\t\t\t\t\tschema.list = args[index].map(Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"dict\":\n\t\t\t\t\tschema.dict = valueMap(args[index], Schema.from);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"bits\":\n\t\t\t\t\tschema.bits = {};\n\t\t\t\t\tfor (const key in args[index]) {\n\t\t\t\t\t\tif (typeof args[index][key] !== \"number\") continue;\n\t\t\t\t\t\tschema.bits[key] = args[index][key];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"callback\": {\n\t\t\t\t\tconst callback = schema.callback = args[index];\n\t\t\t\t\tcallback[\"toJSON\"] ||= () => callback.toString();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"constructor\": {\n\t\t\t\t\tconst constructor = schema.constructor = args[index];\n\t\t\t\t\tif (typeof constructor === \"function\") constructor[\"toJSON\"] ||= () => constructor[\"name\"];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: schema[key] = args[index];\n\t\t\t}\n\t\t});\n\t\tif (name === \"object\" || name === \"dict\") schema.meta.default = {};\n\t\telse if (name === \"array\" || name === \"tuple\") schema.meta.default = [];\n\t\telse if (name === \"bitset\") schema.meta.default = 0;\n\t\treturn schema;\n\t} });\n}\ndefineMethod(\"is\", [\"constructor\"], ({ constructor }) => {\n\tif (typeof constructor === \"function\") return constructor.name;\n\telse return constructor;\n});\ndefineMethod(\"any\", [], () => \"any\");\ndefineMethod(\"never\", [], () => \"never\");\ndefineMethod(\"const\", [\"value\"], ({ value }) => typeof value === \"string\" ? JSON.stringify(value) : value);\ndefineMethod(\"string\", [], () => \"string\");\ndefineMethod(\"number\", [], () => \"number\");\ndefineMethod(\"boolean\", [], () => \"boolean\");\ndefineMethod(\"bitset\", [\"bits\"], () => \"bitset\");\ndefineMethod(\"function\", [], () => \"function\");\ndefineMethod(\"array\", [\"inner\"], ({ inner }) => `${inner.toString(true)}[]`);\ndefineMethod(\"dict\", [\"inner\", \"sKey\"], ({ inner, sKey }) => `{ [key: ${sKey.toString()}]: ${inner.toString()} }`);\ndefineMethod(\"tuple\", [\"list\"], ({ list }) => `[${list.map((inner) => inner.toString()).join(\", \")}]`);\ndefineMethod(\"object\", [\"dict\"], ({ dict }) => {\n\tif (Object.keys(dict).length === 0) return \"{}\";\n\treturn `{ ${Object.entries(dict).map(([key, inner]) => {\n\t\treturn `${key}${inner.meta.required ? \"\" : \"?\"}: ${inner.toString()}`;\n\t}).join(\", \")} }`;\n});\ndefineMethod(\"union\", [\"list\"], ({ list }, inline) => {\n\tconst result = list.map(({ toString: format }) => format()).join(\" | \");\n\treturn inline ? `(${result})` : result;\n});\ndefineMethod(\"intersect\", [\"list\"], ({ list }) => {\n\treturn `${list.map((inner) => inner.toString(true)).join(\" & \")}`;\n});\ndefineMethod(\"transform\", [\n\t\"inner\",\n\t\"callback\",\n\t\"preserve\"\n], ({ inner }, isInner) => inner.toString(isInner));\n//#endregion\nexport { Schema as default };\n","/** Chat display preferences stored in the Host user-settings document. */\n\nimport z from '@deepseek-ai/schemastery'\n\n/** Settings namespace owned by the Chat target. */\nexport const CHAT_SETTINGS_NAMESPACE = 'ui-chat'\n\n/** Field carrying the work-details presentation mode. */\nexport const TRANSCRIPT_VIEW_FIELD = 'transcriptView'\n\n/** Field carrying the independent work-details collapse timing. */\nexport const COLLAPSE_TIMING_FIELD = 'collapseTiming'\n\n/** Available points when a completed Turn returns to its historical presentation. */\nexport const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const\n\n/** When a completed Turn returns to its historical presentation. */\nexport type CollapseTiming = typeof COLLAPSE_TIMINGS[number]\n\n/** Preserve completion-time folding when no timing preference is saved. */\nexport const DEFAULT_COLLAPSE_TIMING: CollapseTiming = 'completion'\n\n/** Field carrying which Assistant replies stay visible in a folded Turn. */\nexport const FOLDED_REPLIES_FIELD = 'foldedReplies'\n\n/** Assistant replies kept visible while a completed Turn folds its process: every reply, or only the final answer. */\nexport const FOLDED_REPLIES = ['all', 'final'] as const\n\n/** Which Assistant replies stay visible while a completed Turn folds its process. */\nexport type FoldedReplies = typeof FOLDED_REPLIES[number]\n\n/** Keep every Assistant reply visible when no folded-reply preference is saved. */\nexport const DEFAULT_FOLDED_REPLIES: FoldedReplies = 'all'\n\n/** Work-details presentation modes a user can choose. */\nexport const TRANSCRIPT_VIEW_MODES = ['compact', 'standard', 'detailed', 'verbose'] as const\n\n/** Work-details presentation mode. */\nexport type TranscriptViewMode = typeof TRANSCRIPT_VIEW_MODES[number]\n\n/**\n * Saved value from the two-mode generation of this setting. Read as `detailed`;\n * never offered as a choice and never written back.\n */\nexport const LEGACY_TRANSCRIPT_VIEW_MODE = 'normal'\n\n/** Saved `expanded` values read as `detailed`, without being offered or written back. */\nexport const LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE = 'expanded'\n\n/** Every value the durable field accepts: current modes plus legacy saved values. */\nconst TRANSCRIPT_VIEW_SETTING_VALUES = [\n ...TRANSCRIPT_VIEW_MODES, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE,\n] as const\n\n/** Default work details for non-Desktop Web clients. */\nexport const DEFAULT_TRANSCRIPT_VIEW_MODE: TranscriptViewMode = 'detailed'\n\n/** Performance and usage detail levels accepted by user settings. */\nexport const PERFORMANCE_USAGE_MODES = ['compact', 'detailed'] as const\n\n/** Performance and usage presentation. */\nexport type PerformanceUsageMode = typeof PERFORMANCE_USAGE_MODES[number]\n\n/** Preserve detailed accounting for users without an explicit preference. */\nexport const DEFAULT_PERFORMANCE_USAGE: PerformanceUsageMode = 'detailed'\n\n/** Destinations for ordinary clicks on Chat HTTP(S) links. */\nexport type LinkOpening = 'sidebar' | 'new-tab'\n\n/** Preserve the built-in browser for users without an explicit preference. */\nexport const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar'\n\n/** Durable Chat section shared by the Host schema and browser scope. */\nexport interface ChatSettings {\n /** Work-details preference; absence uses the client default, and legacy saved values remain accepted. */\n transcriptView?: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE | typeof LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE | null\n /** Independent collapse timing; absence preserves completion-time folding. */\n collapseTiming?: CollapseTiming\n /** Replies kept visible in a folded Turn; absence keeps every reply. */\n foldedReplies?: FoldedReplies\n /** Detail level for composer statistics and completed-Turn usage. */\n performanceUsage: PerformanceUsageMode\n /** Default destination for Chat HTTP(S) links. */\n linkOpening: LinkOpening\n}\n\n/** Durable Chat schema; also the wire envelope the browser scope validates against. */\nexport const ChatSettingsFields = {\n [COLLAPSE_TIMING_FIELD]: z.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING),\n [FOLDED_REPLIES_FIELD]: z.union([...FOLDED_REPLIES]).default(DEFAULT_FOLDED_REPLIES),\n linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING),\n performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE),\n // Missing and unrecognized modes defer to the client's default.\n [TRANSCRIPT_VIEW_FIELD]: z.union([...TRANSCRIPT_VIEW_SETTING_VALUES]).loose(),\n}\n\n/** Schema for shared configuration values. */\nexport const ChatSettingsSchema = z.object(ChatSettingsFields)\n","/** Chat presentation derived from Host-backed detail, collapse timing, and folded replies. */\n\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport { DEFAULT_FOLDED_REPLIES, type CollapseTiming, type FoldedReplies, type TranscriptViewMode } from '../chat-settings.ts'\nexport { COLLAPSE_TIMINGS, FOLDED_REPLIES, type CollapseTiming, type FoldedReplies } from '../chat-settings.ts'\n\n/** Presentation capabilities that one work-details mode enables. */\nexport interface ChatPresentationPolicy {\n /** Preference identity for layout resets and diagnostics; renderers select the capabilities below. */\n readonly mode: TranscriptViewMode\n /** Saved collapse timing; completion retains the default immediate folding and scrolling. */\n readonly collapseTiming: CollapseTiming\n /** Assistant replies that stay visible while a completed Turn folds: every reply, or only the final answer. */\n readonly foldedReplies: FoldedReplies\n /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */\n readonly foldCompletedTurns: boolean\n /** Collapsible group headers for all Turns, historical Turns only, or no Turns. */\n readonly stepGrouping: 'collapsed' | 'history' | 'none'\n /** Show the running command, path, query, or reasoning detail in group titles. */\n readonly liveProcessDetail: boolean\n /** Whether a settled reasoning row previews its first line beside the Think title. */\n readonly settledReasoningPreview: boolean\n}\n\nconst POLICIES: Readonly<Record<TranscriptViewMode, Omit<ChatPresentationPolicy, 'collapseTiming' | 'foldedReplies'>>> = {\n compact: {\n mode: 'compact',\n foldCompletedTurns: true,\n stepGrouping: 'collapsed',\n liveProcessDetail: false,\n settledReasoningPreview: false,\n },\n standard: {\n mode: 'standard',\n foldCompletedTurns: true,\n stepGrouping: 'collapsed',\n liveProcessDetail: true,\n settledReasoningPreview: true,\n },\n detailed: {\n mode: 'detailed',\n foldCompletedTurns: true,\n stepGrouping: 'history',\n liveProcessDetail: true,\n settledReasoningPreview: true,\n },\n verbose: {\n mode: 'verbose',\n foldCompletedTurns: false,\n stepGrouping: 'none',\n liveProcessDetail: false,\n settledReasoningPreview: true,\n },\n}\n\nfunction withTiming(\n collapseTiming: CollapseTiming,\n foldedReplies: FoldedReplies,\n): Readonly<Record<TranscriptViewMode, ChatPresentationPolicy>> {\n return {\n compact: { ...POLICIES.compact, collapseTiming, foldedReplies },\n standard: { ...POLICIES.standard, collapseTiming, foldedReplies },\n detailed: { ...POLICIES.detailed, collapseTiming, foldedReplies },\n verbose: { ...POLICIES.verbose, collapseTiming, foldedReplies },\n }\n}\n\nconst TIMING_POLICIES = {\n completion: { all: withTiming('completion', 'all'), final: withTiming('completion', 'final') },\n 'next-input': { all: withTiming('next-input', 'all'), final: withTiming('next-input', 'final') },\n}\n\n/**\n * Resolve a stable policy for one detail mode, collapse timing, and folded-reply choice.\n * @param mode - persisted work-details mode.\n * @param collapseTiming - persisted timing; defaults to immediate completion folding.\n * @param foldedReplies - persisted folded-reply choice; defaults to keeping every reply visible.\n * @returns the same policy object for the same choices.\n */\nexport function presentationPolicyFor(\n mode: TranscriptViewMode,\n collapseTiming: CollapseTiming = 'completion',\n foldedReplies: FoldedReplies = DEFAULT_FOLDED_REPLIES,\n): ChatPresentationPolicy {\n return TIMING_POLICIES[collapseTiming][foldedReplies][mode]\n}\n\n/**\n * Combine Host-backed detail, persisted timing, and folded replies without owning subscriptions.\n * @param mode - live work-details mode.\n * @param collapseTiming - live Host-backed collapse timing.\n * @param foldedReplies - live Host-backed folded-reply choice.\n * @returns observable policy whose subscriptions follow all three preferences.\n */\nexport function derivePresentationPolicy(\n mode: ObservableSnapshot<TranscriptViewMode>,\n collapseTiming: ObservableSnapshot<CollapseTiming>,\n foldedReplies: ObservableSnapshot<FoldedReplies>,\n): ObservableSnapshot<ChatPresentationPolicy> {\n return {\n getSnapshot: () => presentationPolicyFor(mode.getSnapshot(), collapseTiming.getSnapshot(), foldedReplies.getSnapshot()),\n subscribe: (listener) => {\n const unsubscribeMode = mode.subscribe(listener)\n const unsubscribeTiming = collapseTiming.subscribe(listener)\n const unsubscribeReplies = foldedReplies.subscribe(listener)\n return () => { unsubscribeMode(); unsubscribeTiming(); unsubscribeReplies() }\n },\n }\n}\n","/** Localized two-column selector shared by Chat preference rows. */\nimport { useRef, useState } from 'react'\nimport { IconChevronDownOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives'\nimport css from './PreferenceRow.module.css'\n\n/**\n * Render a preference label and its menu; selection restores focus before publishing the new value.\n * @param props - localized copy, selected value, choices, and mutation callback.\n * @returns the settings row.\n */\nexport function PreferenceRow({ title, description, value, selectedLabel, options, onSelect }: {\n title: string\n description: string\n value: string\n selectedLabel: string\n options: readonly { id: string; label: string }[]\n onSelect: (value: string) => void\n}) {\n const [open, setOpen] = useState(false)\n const selectorRef = useRef<HTMLButtonElement>(null)\n const closeMenu = () => { setOpen(false) }\n const selectMode = (id: string) => {\n selectorRef.current?.focus({ preventScroll: true })\n closeMenu()\n onSelect(id)\n }\n const selector = (\n <button\n ref={selectorRef}\n type=\"button\"\n className={css.selector}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n onClick={() => { setOpen(value => !value) }}\n >\n {selectedLabel}\n <IconChevronDownOutlineRegular className={css.chevron} />\n </button>\n )\n\n return (\n <div className={css.row}>\n <div className={css.rowText}>\n <div className={css.title}>{title}</div>\n <div className={css.desc}>{description}</div>\n </div>\n <Menu\n open={open}\n onClose={closeMenu}\n items={options}\n selectedId={value}\n onSelect={selectMode}\n align=\"end\"\n portal\n anchor={selector}\n />\n </div>\n )\n}\n","/** General Settings row for work-details presentation. */\n\nimport type { SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport { TRANSCRIPT_VIEW_MODES, type TranscriptViewMode } from '../../chat-settings.ts'\nimport type { ChatKey } from '../locale.ts'\nimport { COLLAPSE_TIMINGS, FOLDED_REPLIES, type CollapseTiming, type FoldedReplies } from '../presentation-policy.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side work-details preference face. */\nexport interface TranscriptViewRowInjected {\n hooks: {\n /** Persisted work-details preference bound as useTranscriptView. */\n transcriptView: SnapshotStore<TranscriptViewMode>\n /** Persisted collapse timing bound as useCollapseTiming. */\n collapseTiming: SnapshotStore<CollapseTiming>\n /** Persisted folded-reply choice bound as useFoldedReplies. */\n foldedReplies: SnapshotStore<FoldedReplies>\n }\n /** Change the work-details presentation. */\n setTranscriptView: (mode: TranscriptViewMode) => void\n /** Persist collapse timing independently of the work-details mode. */\n setCollapseTiming: (timing: CollapseTiming) => void\n /** Persist which Assistant replies stay visible in a folded Turn. */\n setFoldedReplies: (replies: FoldedReplies) => void\n}\n\n/** Full Settings-row props. */\nexport type TranscriptViewRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<TranscriptViewRowInjected>\n\nconst LABELS = {\n compact: 'settings.transcript.compact',\n standard: 'settings.transcript.standard',\n detailed: 'settings.transcript.detailed',\n verbose: 'settings.transcript.verbose',\n} as const satisfies Record<TranscriptViewMode, ChatKey>\n\nconst COLLAPSE_LABELS = {\n completion: 'settings.collapse.completion',\n 'next-input': 'settings.collapse.nextInput',\n} as const satisfies Record<CollapseTiming, ChatKey>\n\nconst FOLDED_REPLY_LABELS = {\n all: 'settings.foldedReplies.all',\n final: 'settings.foldedReplies.final',\n} as const satisfies Record<FoldedReplies, ChatKey>\n\n/**\n * Render the independent, Host-backed work-details, collapse-timing, and folded-reply selectors.\n * Verbose never folds a Turn, so it omits the folded-reply selector.\n * @param props - composed Settings slot props.\n * @returns the preference row.\n */\nexport function TranscriptViewRow({\n useTranscriptView, setTranscriptView, useCollapseTiming, setCollapseTiming, useFoldedReplies, setFoldedReplies, t,\n}: TranscriptViewRowProps) {\n const mode = useTranscriptView(value => value)\n const timing = useCollapseTiming(value => value)\n const replies = useFoldedReplies(value => value)\n return (\n <>\n <PreferenceRow\n title={t('settings.transcript.title')}\n description={t('settings.transcript.description')}\n value={mode}\n selectedLabel={t(LABELS[mode])}\n options={TRANSCRIPT_VIEW_MODES.map(id => ({ id, label: t(LABELS[id]) }))}\n onSelect={(value) => { setTranscriptView(value as TranscriptViewMode) }}\n />\n <PreferenceRow\n title={t('settings.collapse.title')}\n description={t('settings.collapse.description')}\n value={timing}\n selectedLabel={t(COLLAPSE_LABELS[timing])}\n options={COLLAPSE_TIMINGS.map(id => ({ id, label: t(COLLAPSE_LABELS[id]) }))}\n onSelect={(value) => { setCollapseTiming(value as CollapseTiming) }}\n />\n {mode !== 'verbose' && (\n <PreferenceRow\n title={t('settings.foldedReplies.title')}\n description={t('settings.foldedReplies.description')}\n value={replies}\n selectedLabel={t(FOLDED_REPLY_LABELS[replies])}\n options={FOLDED_REPLIES.map(id => ({ id, label: t(FOLDED_REPLY_LABELS[id]) }))}\n onSelect={(value) => { setFoldedReplies(value as FoldedReplies) }}\n />\n )}\n </>\n )\n}\n","/** Independent work-details preferences backed by the same Host configuration form. */\n\nimport { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type { CollapseTiming, FoldedReplies } from './presentation-policy.ts'\nimport {\n COLLAPSE_TIMING_FIELD, DEFAULT_COLLAPSE_TIMING, DEFAULT_FOLDED_REPLIES, FOLDED_REPLIES_FIELD,\n DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD,\n type ChatSettings, type TranscriptViewMode,\n} from '../chat-settings.ts'\n\n/** Live work-details preference consumed by Chat and its Settings row. */\nexport class TranscriptViewPolicy {\n private readonly unsubscribe: () => void\n /** Reactive current mode, including the client default before Host settings arrive. */\n readonly mode: SnapshotStore<TranscriptViewMode>\n /** Reactive collapse timing, defaulting to completion until Host settings arrive. */\n readonly collapseTiming: SnapshotStore<CollapseTiming> = createSnapshotStore<CollapseTiming>(DEFAULT_COLLAPSE_TIMING)\n /** Reactive folded-reply choice, keeping every reply until Host settings arrive. */\n readonly foldedReplies: SnapshotStore<FoldedReplies> = createSnapshotStore<FoldedReplies>(DEFAULT_FOLDED_REPLIES)\n\n /**\n * @param host - durable Chat settings scope.\n * @param defaultMode - presentation used without an explicit saved mode.\n */\n constructor(\n private readonly host: ConfigForm<ChatSettings>,\n private readonly defaultMode: TranscriptViewMode = DEFAULT_TRANSCRIPT_VIEW_MODE,\n ) {\n this.mode = createSnapshotStore(defaultMode)\n this.unsubscribe = host.subscribe(() => { this.adopt() })\n this.adopt()\n }\n\n /** Release the accepted-value subscription. */\n dispose(): void { this.unsubscribe() }\n\n /**\n * Publish and persist one explicit user choice.\n * @param mode - Compact, Standard, Detailed, or Verbose work details.\n */\n setMode(mode: TranscriptViewMode): void {\n if (this.mode.getSnapshot() === mode) return\n this.mode.set(mode)\n void this.host.set(TRANSCRIPT_VIEW_FIELD, mode)\n }\n\n /**\n * Publish and persist collapse timing without changing the work-details mode.\n * @param timing - immediate completion folding or deferred folding at the next input.\n */\n setCollapseTiming(timing: CollapseTiming): void {\n if (this.collapseTiming.getSnapshot() === timing) return\n this.collapseTiming.set(timing)\n void this.host.set(COLLAPSE_TIMING_FIELD, timing)\n }\n\n /**\n * Publish and persist which Assistant replies stay visible in a folded Turn.\n * @param replies - every reply, or only the final answer.\n */\n setFoldedReplies(replies: FoldedReplies): void {\n if (this.foldedReplies.getSnapshot() === replies) return\n this.foldedReplies.set(replies)\n void this.host.set(FOLDED_REPLIES_FIELD, replies)\n }\n\n /** Adopt the latest accepted Host section without writing it back. */\n private adopt(): void {\n const section = this.host.getSnapshot().value\n if (section === undefined) return\n const saved = section.transcriptView\n const mode = saved === LEGACY_TRANSCRIPT_VIEW_MODE || saved === LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE\n ? 'detailed' : saved ?? this.defaultMode\n if (this.mode.getSnapshot() !== mode) this.mode.set(mode)\n const timing = section.collapseTiming ?? DEFAULT_COLLAPSE_TIMING\n if (this.collapseTiming.getSnapshot() !== timing) this.collapseTiming.set(timing)\n const replies = section.foldedReplies ?? DEFAULT_FOLDED_REPLIES\n if (this.foldedReplies.getSnapshot() !== replies) this.foldedReplies.set(replies)\n }\n}\n","/** General Settings row for Chat HTTP(S) link destinations. */\nimport type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { LinkOpening } from '../../chat-settings.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side link-opening preference. */\nexport interface LinkOpeningRowInjected {\n hooks: {\n /** Current destination, bound as useLinkOpening. */\n linkOpening: ObservableSnapshot<LinkOpening>\n /** Whether the built-in browser is registered, bound as useBrowserAvailable. */\n browserAvailable: ObservableSnapshot<boolean>\n }\n /** Change the default destination for Chat HTTP(S) links. */\n setLinkOpening: (destination: LinkOpening) => void\n}\n\n/** Full Settings-row props. */\nexport type LinkOpeningRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<LinkOpeningRowInjected>\n\n/**\n * Render the link-opening destination selector.\n * @param props - Composed Settings slot props.\n * @returns The preference row.\n */\nexport function LinkOpeningRow({ useLinkOpening, useBrowserAvailable, setLinkOpening, t }: LinkOpeningRowProps) {\n const destination = useLinkOpening(value => value)\n const browserAvailable = useBrowserAvailable(value => value)\n if (!browserAvailable) return null\n return (\n <PreferenceRow\n title={t('settings.links.title')}\n description={t('settings.links.description')}\n value={destination}\n selectedLabel={t(destination === 'sidebar' ? 'settings.links.sidebar' : 'settings.links.newTab')}\n options={[\n { id: 'sidebar', label: t('settings.links.sidebar') },\n { id: 'new-tab', label: t('settings.links.newTab') },\n ]}\n onSelect={(value) => { setLinkOpening(value as LinkOpening) }}\n />\n )\n}\n","/** General Settings row for performance and usage detail. */\n\nimport type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { PerformanceUsageMode } from '../../chat-settings.ts'\nimport type { PerformanceUsageInjected } from '../contract/slots.ts'\nimport type { ChatKey } from '../locale.ts'\nimport { PreferenceRow } from './PreferenceRow.tsx'\n\n/** Registration-side performance and usage preference face. */\nexport interface PerformanceUsageRowInjected extends PerformanceUsageInjected {\n /** Change the performance and usage detail. */\n setPerformanceUsage: (mode: PerformanceUsageMode) => void\n}\n\n/** Full Settings-row props. */\nexport type PerformanceUsageRowProps =\n PropsRuntime<'settings.general.item'>\n & PropsLocale<'chat'>\n & InjectFace<PerformanceUsageRowInjected>\n\nconst OPTIONS: readonly { id: PerformanceUsageMode; label: ChatKey }[] = [\n { id: 'compact', label: 'settings.performance.compact' },\n { id: 'detailed', label: 'settings.performance.detailed' },\n]\n\n/**\n * Render the performance and usage detail selector.\n * @param props - composed Settings slot props.\n * @returns the preference row.\n */\nexport function PerformanceUsageRow({ usePerformanceUsage, setPerformanceUsage, t }: PerformanceUsageRowProps) {\n const mode = usePerformanceUsage(value => value)\n const selectedLabel = mode === 'detailed'\n ? 'settings.performance.detailed'\n : 'settings.performance.compact'\n return (\n <PreferenceRow\n title={t('settings.performance.title')}\n description={t('settings.performance.description')}\n value={mode}\n selectedLabel={t(selectedLabel)}\n options={OPTIONS.map(option => ({ id: option.id, label: t(option.label) }))}\n onSelect={(value) => { setPerformanceUsage(value as PerformanceUsageMode) }}\n />\n )\n}\n","/** Performance detail preference, live immediately and reconciled with accepted Host settings. */\nimport { createSnapshotStore } from '@deepseek-ai/dsh-client-store'\nimport type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client'\nimport { DEFAULT_PERFORMANCE_USAGE, type ChatSettings, type PerformanceUsageMode } from '../chat-settings.ts'\n\n/** Shared live preference for the settings row and chat statistics. */\nexport class PerformanceUsagePolicy {\n private readonly unsubscribe: () => void\n /** Current choice, reconciled with accepted Host settings when available. */\n readonly mode = createSnapshotStore<PerformanceUsageMode>(DEFAULT_PERFORMANCE_USAGE)\n\n /** @param host - Chat settings scope persisted through the Host. */\n constructor(private readonly host: ConfigForm<ChatSettings>) {\n const adopt = (): void => {\n const accepted = host.getSnapshot().value?.performanceUsage\n if (accepted !== undefined) this.mode.set(accepted)\n }\n this.unsubscribe = host.subscribe(adopt)\n adopt()\n }\n\n /** Release the accepted-value subscription. */\n dispose(): void { this.unsubscribe() }\n\n /**\n * Publish a choice immediately and queue its Host write.\n * @param mode - Statistics detail selected by the user.\n */\n setMode(mode: PerformanceUsageMode): void {\n if (mode === this.mode.getSnapshot()) return\n this.mode.set(mode)\n void this.host.set('performanceUsage', mode)\n }\n}\n","import { useSyncExternalStore } from 'react'\nimport type {\n ConversationLocationDataSource, ConversationLocationDataStore, ConversationTurnDataMap,\n} from '@deepseek-ai/dsh-client-ui-conversation/client'\n\nconst EMPTY_SOURCE: ConversationLocationDataSource<undefined> = {\n getSnapshot: () => undefined,\n subscribe: () => () => {},\n}\n\n/**\n * Subscribe to one value from a Turn's keyed Location-data store.\n * @param data - current Turn data store, or absence for a Node outside a Turn.\n * @param key - declaration-merged business key.\n * @returns the current value for that key.\n */\nexport function useTurnDataValue<Key extends Extract<keyof ConversationTurnDataMap, string>>(\n data: ConversationLocationDataStore<ConversationTurnDataMap> | undefined,\n key: Key,\n): Readonly<ConversationTurnDataMap[Key]> | undefined {\n const source = data?.source(key) ?? EMPTY_SOURCE\n return useSyncExternalStore(source.subscribe, source.getSnapshot)\n}\n","import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client'\n/** Register the Chat Conversation target, renderers, stats, and details surface. */\nimport type {} from '@deepseek-ai/dsh-client-ui-file-drag/client'\nimport type {} from '@deepseek-ai/dsh-client-product-analytics/client'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment'\nimport type {} from '@deepseek-ai/dsh-api-remotes/client'\nimport type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client'\nimport type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store'\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-input-trigger/client'\n// The `file` entry of `SidebarRightResourceParamsMap`, which types `{ params: { line } }` below.\nimport type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client'\nimport { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path'\n// Type-only service and declaration merges used by the apply world.\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-layout/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-session/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-settings/client'\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\nimport type {\n ChatFlowDataInjected, ChatFlowInjected, ChatNodeInjected, ChatScrollPosition, ChatViewInjected,\n QuotaNoticeInjected, QuotaNoticeState,\n} from './contract/slots.ts'\nimport type { ChatSnapshot } from './contract/snapshot.ts'\nimport { EMPTY_CHAT_SNAPSHOT } from './contract/snapshot.ts'\nimport { ApprovalCommand } from './chat/ApprovalCommand.tsx'\nimport { sessionFilePath } from './file-path.ts'\nimport { ChatView } from './chat/ChatView.tsx'\nimport { ChatFlow } from './chat/ChatFlow.tsx'\nimport { registerChatNodeRenderers } from './chat/register-node-renderers.ts'\nimport { UserContent } from './chat/UserContent.tsx'\nimport { ActivityPill, UsagePill } from './chat/StatsPills.tsx'\nimport { registerConversationNodes } from './conversation-nodes/register.ts'\nimport { registerFenceLayers } from './fence/register.ts'\nimport { QuotaNoticeHost } from './chat/QuotaNoticeHost.tsx'\nimport { en, ja, es, fr, de, ru, pt, NS, zh } from './locale.ts'\nimport { TranscriptViewRow, type TranscriptViewRowInjected } from './settings/TranscriptViewRow.tsx'\nimport { createChatStore } from './stores.ts'\nimport { TranscriptViewPolicy } from './transcript-view.ts'\nimport { derivePresentationPolicy } from './presentation-policy.ts'\nimport { CHAT_SETTINGS_NAMESPACE, DEFAULT_LINK_OPENING, DEFAULT_TRANSCRIPT_VIEW_MODE, type ChatSettings } from '../chat-settings.ts'\nimport { LinkOpeningRow, type LinkOpeningRowInjected } from './settings/LinkOpeningRow.tsx'\nimport { PerformanceUsageRow, type PerformanceUsageRowInjected } from './settings/PerformanceUsageRow.tsx'\nimport { PerformanceUsagePolicy } from './performance-usage.ts'\nimport { useTurnDataValue } from './chat/use-turn-data.ts'\nimport { bindDisclosure } from './chat/use-disclosure.ts'\nimport { useFlowHidden, useMotionHidden } from './chat/flow-motion.ts'\n\n/** Bind group and header visibility to the viewport of one flow render. */\nexport const CHAT_FLOW_INJECT: ChatFlowInjected = {\n hooks: {\n groupAction: (_standard, { motion }) => function useGroupAction(hidden, reveal) {\n return useFlowHidden(hidden, reveal, motion)\n },\n groupHeaderAction: (_standard, { motion }) => function useGroupHeaderAction(ref, hidden) {\n useMotionHidden(ref, hidden, motion)\n },\n },\n}\n\n/** Bind node-local sources and forward the flow's existing visibility hook. */\nexport const CHAT_NODE_INJECT: ChatNodeInjected = {\n hooks: {\n turnData: (_standard, { turnData }) => function useTurnData(key) {\n return useTurnDataValue(turnData, key)\n },\n disclosure: (_standard, { disclosureReset }) => bindDisclosure(disclosureReset),\n groupAction: (_standard, { useGroupAction }) => useGroupAction,\n },\n}\n\n/** Services required by the Chat target and its presentation registrations. */\nexport const inject = [\n 'slots', 'sessions', 'uiWorkspace', 'uiSession', 'uiConversation', 'locale',\n 'configForms', 'connection', 'remote', 'remote.session', 'sidebarRight', 'fileDrag',\n]\n\n/**\n * Mount all Chat-owned contributions.\n * @param ctx - Client root context.\n */\nexport function apply(ctx: Context): void {\n const quotaNotice = createSnapshotStore<QuotaNoticeState | null>(null)\n let quotaNoticeSeq = 0\n // Each hold is its own token, so a release can only drop the hold it was\n // issued for: one arriving after a dismissal or a later acquisition leaves\n // that newer hold alone.\n const quotaNoticeHolds = new Set<symbol>()\n const chatSources = new WeakMap<SessionBinding, ObservableSnapshot<ChatSnapshot>>()\n const quotaSubscriptions = new Set<() => Promise<void>>()\n ctx.effect(() => async () => {\n await Promise.all([...quotaSubscriptions].map(dispose => dispose()))\n }, 'ui-chat: live quota notices')\n const chatSource = (binding: SessionBinding): ObservableSnapshot<ChatSnapshot> => {\n let source = chatSources.get(binding)\n if (source === undefined) {\n // One live quota failure publishes one frame-wide notice; history\n // replacement or paging never does, because an old failure scrolling\n // back into view is not news.\n const dispose = binding.ctx.effect(() => {\n const stop = binding.eventSource.subscribe(() => {\n const { change } = binding.eventSource.getSnapshot()\n if (change.kind !== 'append') return\n for (const { event } of change.entries) {\n if (event.type !== 'turn/end' || event.data.reason.kind !== 'error') continue\n const { code } = event.data.reason.error\n if (quotaNoticeHolds.size > 0 || (code !== 'QUOTA' && code !== 'ACCOUNT_QUOTA')) continue\n quotaNotice.set({ code, seq: ++quotaNoticeSeq })\n }\n })\n return () => {\n stop()\n chatSources.delete(binding)\n quotaSubscriptions.delete(dispose)\n }\n }, 'ui-chat: Provider binding quota notices')\n quotaSubscriptions.add(dispose)\n const target = ctx.uiConversation.binding(binding).target('chat')\n source = {\n getSnapshot: () => target.getSnapshot() ?? EMPTY_CHAT_SNAPSHOT,\n subscribe: listener => target.subscribe(listener),\n }\n chatSources.set(binding, source)\n }\n return source\n }\n registerConversationNodes(ctx)\n ctx.uiSession.provide({\n hooks: ['chat'],\n resolve: binding => ({ hooks: { chat: chatSource(binding) } }),\n })\n\n ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'ui-chat: dictionaries')\n const t = ctx.locale.bind(NS)\n const chatStore = createChatStore()\n const chatScrollPositions = new Map<SessionId, ChatScrollPosition>()\n const chatSettings = ctx.configForms.get<ChatSettings>(CHAT_SETTINGS_NAMESPACE)\n const linkOpening = createSnapshotStore(chatSettings.getSnapshot().value?.linkOpening ?? DEFAULT_LINK_OPENING)\n ctx.effect(() => chatSettings.subscribe(() => {\n const accepted = chatSettings.getSnapshot().value?.linkOpening\n if (accepted !== undefined) linkOpening.set(accepted)\n }))\n ctx.inject(['sidebarRightTabs'], (scope) => {\n const tabs = scope.sidebarRightTabs\n const browserAvailable: ObservableSnapshot<boolean> = {\n getSnapshot: () => tabs.get('browser') !== undefined,\n subscribe: listener => tabs.subscribe(listener),\n }\n scope.slots.inject('settings.general.item', () => scope.slots.register({\n name: 'settings.general.item',\n id: 'link-opening',\n order: 17,\n locale: NS,\n inject: (): LinkOpeningRowInjected => ({\n hooks: { linkOpening, browserAvailable },\n setLinkOpening: (destination) => {\n linkOpening.set(destination)\n void chatSettings.set('linkOpening', destination).catch((_error: unknown) => {\n // The local choice remains usable when persistence is unavailable.\n })\n },\n }),\n }, LinkOpeningRow))\n })\n const transcriptView = new TranscriptViewPolicy(chatSettings, 'dshDesktop' in globalThis ? 'standard' : DEFAULT_TRANSCRIPT_VIEW_MODE)\n const presentation = derivePresentationPolicy(transcriptView.mode, transcriptView.collapseTiming, transcriptView.foldedReplies)\n const performancePolicy = new PerformanceUsagePolicy(chatSettings)\n ctx.effect(() => () => { transcriptView.dispose(); performancePolicy.dispose() })\n const performanceUsage = performancePolicy.mode\n registerChatNodeRenderers(ctx, performanceUsage, presentation)\n ctx.slots.registerFactory({\n name: 'conversation.chat.user.content', scope: 'session', locale: NS,\n children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } },\n }, UserContent)\n\n ctx.slots.inject('settings.general.item', () => ctx.slots.register({\n name: 'settings.general.item',\n id: 'performance-usage',\n order: 30,\n locale: NS,\n inject: (): PerformanceUsageRowInjected => ({\n hooks: { performanceUsage },\n setPerformanceUsage: (mode) => { performancePolicy.setMode(mode) },\n }),\n }, PerformanceUsageRow))\n\n ctx.slots.inject('settings.general.item', () => ctx.slots.register({\n name: 'settings.general.item',\n id: 'transcript-view',\n order: 12,\n locale: NS,\n inject: (): TranscriptViewRowInjected => ({\n hooks: {\n transcriptView: transcriptView.mode,\n collapseTiming: transcriptView.collapseTiming,\n foldedReplies: transcriptView.foldedReplies,\n },\n setTranscriptView: (mode) => { transcriptView.setMode(mode) },\n setCollapseTiming: (timing) => { transcriptView.setCollapseTiming(timing) },\n setFoldedReplies: (replies) => { transcriptView.setFoldedReplies(replies) },\n }),\n }, TranscriptViewRow))\n\n const connectionState = (ctx.get('connection') as ConnectionHandle).state\n const nodeSources = (binding: SessionBinding): Pick<ChatViewInjected, 'keyedHooks'> => {\n const chat = chatSource(binding)\n const conversation = ctx.uiConversation.binding(binding)\n return {\n keyedHooks: {\n chatNode: key => chat.getSnapshot().nodes.source(key),\n chatNodeBottom: key => chat.getSnapshot().nodes.bottomSource(key),\n chatNodeProcess: key => chat.getSnapshot().nodes.processSource(key),\n chatGroup: key => conversation.snapshot.getSnapshot().views.grouped('chat')?.groupSource(key as GroupKey),\n },\n }\n }\n\n ctx.slots.inject('conversation.chat.flow', () => ctx.slots.register({\n name: 'conversation.chat.flow', locale: NS, store: chatStore,\n children: {\n 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT },\n },\n inject: (sessionId: SessionId): ChatFlowDataInjected => {\n const binding = ctx.sessions.binding(sessionId)\n if (binding === undefined) throw new Error(`ui-chat: unknown session \"${sessionId}\"`)\n return { ...nodeSources(binding), hooks: { presentation, connectionState } }\n },\n }, ChatFlow))\n\n ctx.slots.inject('conversation.view', () => {\n const disposeView = ctx.slots.register({\n name: 'conversation.view',\n id: 'chat',\n order: 0,\n label: () => t('view.chat'),\n locale: NS,\n children: {\n 'conversation.chat.flow': { kind: 'single', scope: 'session', inject: CHAT_FLOW_INJECT },\n 'conversation.chat.text-interaction': { kind: 'keyed', scope: 'session' },\n 'conversation.chat.markdown.fence': { kind: 'hoc', scope: 'session' },\n },\n store: chatStore,\n inject: (sessionId: SessionId): ChatViewInjected => {\n const binding = ctx.sessions.binding(sessionId)\n if (binding === undefined) throw new Error(`ui-chat: unknown session \"${sessionId}\"`)\n const session = binding.session\n const chat = chatSource(binding)\n return {\n ...nodeSources(binding),\n fileDrag: ctx.fileDrag.actions,\n hooks: { presentation, interactionIds: ctx.uiConversation.interactions },\n dispatchInteraction: gesture => ctx.uiConversation.interactions.dispatch(sessionId, gesture),\n // Files open in the right Sidebar, not in a desktop application: the\n // content stays in the product, beside the conversation that produced\n // it. A relative path resolves from the Session's working directory\n // at click time, which a directory change can move away from the\n // workspace root; links from earlier Turns follow later changes. A\n // path inside the workspace is addressed under this\n // session's scope, `dsh-resource://file/session/<id>/<path>`; an\n // absolute path elsewhere keeps its absolute spelling in the same\n // Session's address. Which tab type claims the address is the\n // Sidebar's decision, not this call site's.\n // A line travels as a navigation parameter, not as part of the\n // address: the file is one piece of content whether it is opened at\n // its top or at line 400, so the same tab is revealed and told where\n // to land.\n openFile: async (path, options) => {\n const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd\n const current = session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined\n const url = fileAddressFor(sessionId, cwd, resolveWorkspacePath(current ?? undefined, path))\n if (options?.line === undefined) ctx.sidebarRight.openResource(url)\n else ctx.sidebarRight.openResource(url, { params: { line: options.line } })\n await Promise.resolve()\n },\n resolveFilePath: sessionFilePath(ctx, sessionId),\n openExternalLink: (url) => {\n if (linkOpening.getSnapshot() === 'sidebar' && ctx.get('sidebarRightTabs')?.get('browser') !== undefined) {\n ctx.sidebarRight.openTab('browser', { params: { url } })\n } else {\n window.open(url, '_blank', 'noopener,noreferrer')\n }\n },\n loadOlder: () => { void session.loadOlder({ deferConsumption: true }) },\n consumeOlder: () => session.consumeOlder(),\n loadThrough: seq => session.loadThrough(seq),\n loadImage: Object.assign(\n (attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),\n { peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },\n ),\n chatScroll: {\n save: (position) => {\n if (position === null) chatScrollPositions.delete(sessionId)\n else chatScrollPositions.set(sessionId, position)\n },\n read: () => chatScrollPositions.get(sessionId) ?? null,\n },\n forkAt: (seq) => {\n const turn = [...chat.getSnapshot().timeline.turns.values()].find(turn => turn.end?.seq === seq)\n const messageId = turn?.data.get('turn-tail')?.closing?.finalNode.messageId\n ctx.sessions.fork({ sessionId, atSeq: seq, increaseTitle: true, onCreated: (childId) => {\n ctx.get('productAnalytics')?.track('branch_session_click', { session_id: childId, parent_session_id: sessionId, ...messageId === undefined ? {} : { parent_message_id: messageId }, click_position: 'footer' })\n } })\n .then((childId) => { ctx.uiWorkspace.openSession(childId) })\n .catch(() => {\n // Fork or child-title failure leaves the source view unchanged.\n })\n },\n }\n },\n }, ChatView)\n return disposeView\n })\n registerFenceLayers(ctx)\n\n // The quota notice host lives in the frame-wide layer so a notice outlives\n // the Chat panel that reported it. Its chain child lets a package with a\n // billing surface claim the one live notice without importing Chat.\n ctx.slots.inject('shell.overlay', () => ctx.slots.register({\n name: 'shell.overlay', id: 'chat.quota-notice', locale: NS,\n children: { 'shell.quota-notice': { kind: 'chain', scope: 'root' } },\n inject: (): QuotaNoticeInjected => ({\n hooks: { notice: quotaNotice },\n dismissNotice: () => { quotaNoticeHolds.clear(); quotaNotice.set(null) },\n keepNoticeOpen: () => {\n // Nothing live to retain: later failures must still publish.\n if (quotaNotice.getSnapshot() === null) return () => {}\n const token = Symbol('ui-chat quota notice hold')\n quotaNoticeHolds.add(token)\n return () => { quotaNoticeHolds.delete(token) }\n },\n }),\n }, QuotaNoticeHost))\n\n // One dock entry per pill, so a plugin replaces or adds a single pill by id.\n const statPillInject = () => ({ hooks: { performanceUsage } })\n ctx.slots.inject('conversation.composer.dock', function* () {\n yield ctx.slots.register({\n name: 'conversation.composer.dock', id: 'activity', order: 0, locale: NS, inject: statPillInject,\n }, ActivityPill)\n yield ctx.slots.register({\n name: 'conversation.composer.dock', id: 'usage', order: 1, locale: NS, inject: statPillInject,\n }, UsagePill)\n })\n\n ctx.slots.inject('conversation.approval.detail', () =>\n ctx.slots.register({ name: 'conversation.approval.detail' }, ApprovalCommand))\n\n}\n"],"mappings":";iiBAQA,MAAA,oBAAA,uBAEA,SAAA,cAAA,QAAA,wDAEA,CAEA,SAAA,WAAA,KAAA,oDAEA,CAWA,SAAA,mBAAA,UAAA,KAAA,8JAGA,CA0DA,SAAA,mBAAA,MAAA,8DAEA,CAMA,SAAA,wBAAA,KAAA,sDAEA,CAOA,SAAA,qBAAA,IAAA,KAAA,6OAKA,CA0DA,SAAA,eAAA,UAAA,IAAA,KAAA,mbAOA,CAmBA,SAAA,aAAA,KAAA,KAAA,iPAGA,CCxEA,MAAA,aAAA,CAAA,EACA,MAAA,eAAA,qCAA8F,EAC9F,MAAA,kBAAA,8CAIA,MAAA,oBAAA,6CAIA,MAAA,0BAAA,8CAIA,MAAA,uBAAA,oDAMA,MAAA,oBAAA,8bCjIA,SAAA,UAAA,KAAA,wNASA,CAOA,SAAA,gBAAA,CAAA,OAAA,SAAA,6OASA,CC7BA,SAAA,gBAAA,IAAA,UAAA,yOAMA,CCQA,MAAA,MAAA,oCAAmG,EAQnG,SAAA,cAAA,KAAA,SAAA,uEAEA,CC1BA,SAAA,eAAA,EAAA,4MAKA,k5ICaA,MAAA,gBAAA,GAEA,MAAA,cAAA,EAEA,MAAA,QAAA,GAEA,SAAA,yBAAA,8GAIA,CAaA,MAAA,UAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,SAAA,CAAA,KAAA,MAAA,OAAA,KAAA,UAAA,gBAAA,WAAA,UAAA,cAAA,GAAA,i1BA2BA,CAAA,EAEA,SAAA,kBAAA,CAAA,MAAA,WAAA,SAAA,WAAA,GAAA,IAAA,+rNA4MA,CAUA,MAAA,eAAA,EAAA,MAAA,KAAA,AAAA,EAAA,EAAA,MAAA,WAAA,AAAA,CAAA,iBAAA,CAAA,ECnRA,SAAA,YAAA,MAAA,aAEA,CAMA,SAAA,YAAA,MAAA,aAEA,CCUA,SAAA,WAAA,MAAA,oLAKA,CCnBA,MAAA,cAAA,CAAA,EASA,SAAA,aAAA,MAAA,icAWA,CAGA,SAAA,eAAA,QAAA,oDAEA,CAYA,SAAA,mBAAA,OAAA,QAAA,umBA0BA,CCtFA,MAAA,qBAAA,IAAA,IAAA,4NAKA,MAAA,oBAAA,IAAA,IAAA,CAAA,KAAA,IAAA,CAAA,EAEA,SAAA,SAAA,QAAA,wQAIA,CAEA,SAAA,kBAAA,KAAA;IAIA,CAEA,SAAA,mBAAA,SAAA,QAAA;;;uCAKA,CAOA,SAAA,cAAA,KAAA;qaAoCA,CAcA,SAAA,kBAAA,KAAA;;;;6fA4CA,CAEA,SAAA,gBAAA,WAAA,UAAA,OAAA,+SAYA,CAcA,SAAA,kBAAA,KAAA,UAAA,udASA,CAOA,SAAA,aAAA,UAAA,uVAQA,CC3JA,SAAA,WAAA,KAAA,2FAEA,CAEA,SAAA,WAAA,EAAA,EAAA,sEAEA,CAEA,SAAA,UAAA,EAAA,EAAA,iKAGA,CAEA,SAAA,UAAA,KAAA,OAAA,soBAYA,CAEA,SAAA,aAAA,KAAA,+FAEA,CAEA,SAAA,cAAA,KAAA,OAAA,KAAA,y0BAuBA,CAUA,SAAA,mBAAA,QAAA,WAAA,oBAAA,cAAA,wsQAiNA,CC3QA,IAAA,eAAA,KAAA,o7KA6QA,SAAA,kBAAA,SAAA,QAAA,MAAA,2eASA,CCrSA,SAAA,cAAA,QAAA,qHAGA,CAGA,IAAA,aAAA,MAAA,YAAA,yrEA6JA,SAAA,gBAAA,QAAA,UAAA,wFAGA,CC9KA,MAAA,0BAAA,IAmBA,IAAA,YAAA,KAAA,irJAkPA,SAAA,eAAA,SAAA,MAAA,YAAA,4eAcA,CCzQA,SAAA,oBAAA,OAAA,OAAA,WAAA,ymBA2BA,CCnCA,MAAA,YAAA,GAEA,MAAA,eAAA,GACA,MAAA,SAAA,IAEA,MAAA,aAAA,qBACA,MAAA,OAAA,+BAgFA,SAAA,cAAA,QAAA,oJAGA,CAOA,SAAA,mBAAA,QAAA,+EAEA,CAQA,SAAA,cAAA,IAAA,SAAA,uFAGA,CA+BA,SAAA,iBAAA,OAAA,eAAA,kBAAA,mrRAgWA,CAEA,SAAA,kBAAA,OAAA,KAAA,2wBAuBA,CASA,SAAA,cAAA,OAAA,OAAA,OAAA,0EAEA,CAQA,SAAA,gBAAA,IAAA,OAAA,OAAA,kRAUA,CCneA,MAAA,gBAAA,2DAAuF,EACvF,MAAA,cAAA,IAAA,IAAA,2DAA6F,CAAA,EAG7F,IAAA,aAAA,KAAA,88xBA+gCA,SAAA,iBAAA,gWAcA,CCxjCA,SAAA,cAAA,MAAA,24KA+JA,guSCvLA,SAAA,mBAAA,MAAA,SAAA,sGAGA,CAOA,SAAA,eAAA,MAAA,MAAA,oiBAgBA,CAKA,MAAA,eAAA,IAMA,SAAA,SAAA,CAAA,WAAA,QAAA,gBAAA,YAAA,WAAA,UAAA,SAAA,iBAAA,gBAAA,eAAA,UAAA,aAAA,YAAA,UAAA,YAAA,WAAA,OAAA,gBAAA,cAAA,kBAAA,oBAAA,EAAA,UAAA,inSAqQA,CAGA,SAAA,oBAAA,CAAA,QAAA,KAAA,QAAA,QAAA,GAAA,mmBAwBA,CCpVA,MAAA,eAAA;cASA,EACA,MAAA,eAAA,qBACA,SAAA,aAAA,EAAA;oBAEA,CACA,SAAA,MAAA,EAAA,sDAEA,CAOA,IAAA,iBAAA,MAAA,gBAAA,ynWAmlBA,EAUA,SAAA,YAAA,MAAA,QAAA,sIAGA,CCznBA,SAAA,yBAAA,OAAA,iKAMA,CCWA,SAAA,oBAAA,KAAA,MAAA,wXAUA,CAQA,SAAA,yBAAA,KAAA,uDAEA,CAOA,SAAA,sBAAA,KAAA,mPAKA,CCrCA,SAAA,uBAAA,MAAA,KAAA,0DAKA,CAUA,SAAA,gBAAA,MAAA,KAAA,YAAA,oKAQA,CAMA,SAAA,iBAAA,wWAYA,CC3BA,SAAA,WAAA,KAAA,gHAGA,CAEA,SAAA,SAAA,KAAA,gHAGA,CAOA,MAAA,cAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,aAAA,CAAA,QAAA,UAAA,YAAA,mBAAA,gBAAA,IAAA,SAAA,YAAA,OAAA,UAAA,SAAA,QAAA,WAAA,EAAA,kBAAA,cAAA,gBAAA,8yIAiIA,CAAA,ECzKA,SAAA,cAAA,MAAA,wLAMA,CCLA,SAAA,aAAA,QAAA,EAAA,2sBAiBA,CCjBA,SAAA,cAAA,QAAA,EAAA,qTAUA,CAOA,SAAA,eAAA,MAAA,gNAOA,CC7BA,MAAA,QAAA,sCAAuE,EACvE,MAAA,YAAA,IAAA,IAAA,2DAA6F,CAAA,EAY7F,SAAA,iBAAA,QAAA,WAAA,KAAA,QAAA,orEAqEA,ixGC5DA,MAAA,yBAAA,IAUA,MAAA,cAAA,2iDAkBA,SAAA,qBAAA,KAAA,MAAA,oGAEA,CAEA,SAAA,0BAAA,QAAA,OAAA,otBAuBA,CAGA,MAAA,cAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,aAAA,CAAA,QAAA,GAAA,OAAA,uLAKA,CAAA,EAEA,MAAA,oBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,mBAAA,CAAA,SAAA,aAAA,gBAAA,EAAA,KAAA,OAAA,QAAA,u1DAqCA,CAAA,EAGA,MAAA,eAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,cAAA,CAAA,SAAA,aAAA,qBAAA,GAAA,OAAA,sxHA2EA,CAAA,whPCjLA,MAAA,gBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,eAAA,CAAA,KAAA,MAAA,gBAAA,GAAA,+iEA6CA,CAAA,w9FC7DA,MAAA,UAAA,IAGA,MAAA,YAAA,IAKA,SAAA,WAAA,MAAA,+EAIA,CAeA,SAAA,YAAA,QAAA,iOAYA,CAGA,SAAA,cAAA,QAAA,uEAEA,CAGA,SAAA,YAAA,KAAA,EAAA,2GAIA,CAOA,SAAA,WAAA,MAAA,EAAA,0IAKA,CAUA,SAAA,aAAA,CAAA,OAAA,aAAA,GAAA,mqBAoBA,CASA,SAAA,cAAA,CAAA,OAAA,GAAA,qRAaA,CASA,SAAA,mBAAA,CAAA,QAAA,GAAA,kdAoBA,CASA,SAAA,WAAA,CAAA,QAAA,OAAA,GAAA,0MAWA,CAkBA,SAAA,mBAAA,OAAA,glBAqBA,CAUA,SAAA,kBAAA,OAAA,SAAA,4NAQA,CAWA,SAAA,iBAAA,CAAA,QAAA,OAAA,GAAA,mzBAuBA,CAcA,SAAA,eAAA,OAAA,wZAgBA,CAYA,SAAA,YAAA,CAAA,QAAA,OAAA,GAAA,4uCAmCA,CASA,SAAA,iBAAA,OAAA,iaAcA,CAkBA,SAAA,aAAA,CAAA,QAAA,OAAA,GAAA,81BAuBA,CAUA,SAAA,WAAA,CAAA,QAAA,GAAA,gEAMA,CAUA,SAAA,UAAA,CAAA,QAAA,OAAA,GAAA,saAgBA,CAGA,SAAA,YAAA,OAAA,8GAGA,CAWA,SAAA,iBAAA,OAAA,qmBAqBA,CAYA,SAAA,WAAA,CAAA,QAAA,OAAA,GAAA,+7BA4BA,CAGA,SAAA,cAAA,OAAA,0GAGA,CAcA,SAAA,YAAA,KAAA,MAAA,6nCAyCA,uvDCjjBA,SAAA,oBAAA,CAAA,QAAA,OAAA,SAAA,KAAA,GAAA,2xGA+DA,CCjFA,MAAA,2BAAA,IAEA,SAAA,KAAA,EAAA,iCAEA,CAOA,SAAA,gBAAA,GAAA,4DAIA,CAOA,SAAA,yBAAA,GAAA,qFAIA,CAeA,SAAA,kBAAA,GAAA,EAAA,qdAUA,CAOA,SAAA,sBAAA,IAAA,+GAGA,CAYA,SAAA,mBAAA,KAAA,EAAA,IAAA,KAAA,IAAA,EAAA,oXAcA,CCxFA,SAAA,gBAAA,0UAaA,q3FCoBA,SAAA,mBAAA,CAAA,KAAA,KAAA,MAAA,SAAA,kBAAA,MAAA,UAAA,aAAA,YAAA,GAAA,6jEA6CA,CC1EA,MAAA,iBAAA,CAAA,EAIA,SAAA,aAAA,QAAA,ibAoBA,CAEA,SAAA,aAAA,aAAA,+CAEA,CAOA,SAAA,eAAA,QAAA,KAAA,EAAA,sWAUA,CAEA,SAAA,eAAA,CAAA,KAAA,OAAA,GAAA,6mEAkEA,CAGA,SAAA,cAAA,CAAA,KAAA,GAAA,62BAcA,CAGA,SAAA,kBAAA,CAAA,GAAA,gnBAYA,CAYA,MAAA,gBAAA,+BAA4E,EAG5E,MAAA,sBAAA,KAGA,SAAA,gBAAA,CAAA,KAAA,gBAAA,QAAA,UAAA,kBAAA,QAAA,QAAA,MAAA,KAAA,MAAA,WAAA,MAAA,gBAAA,WAAA,mBAAA,MAAA,WAAA,iBAAA,YAAA,OAAA,k7BAyDA,CAQA,SAAA,sBAAA,CAAA,QAAA,UAAA,kBAAA,GAAA,+RAuBA,CAUA,SAAA,wBAAA,CAAA,WAAA,UAAA,kBAAA,GAAA,03BA8CA,CASA,MAAA,qBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,oBAAA,CAAA,KAAA,kBAAA,UAAA,gBAAA,GAAA,wfA6BA,CAAA,EAGA,MAAA,wBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,uBAAA,CAAA,KAAA,GAAA,4JAWA,CAAA,EAGA,MAAA,oBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,mBAAA,CAAA,KAAA,GAAA,mEAEA,CAAA,EAGA,MAAA,eAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,cAAA,CAAA,KAAA,GAAA,wIAGA,CAAA,EAGA,MAAA,mBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,kBAAA,CAAA,KAAA,GAAA,kEAEA,CAAA,EAGA,MAAA,uBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,sBAAA,CAAA,GAAA,uDAEA,CAAA,EAGA,MAAA,iBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,gBAAA,CAAA,KAAA,GAAA,+TAWA,CAAA,ECtZA,MAAA,UAAA,siBAMA,SAAA,kBAAA,+cASA,2kBCMA,MAAA,eAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,cAAA,CAAA,UAAA,OAAA,QAAA,MAAA,GAAA,wtCAuBA,CAAA,EChCA,SAAA,kBAAA,KAAA,yBAEA,CAGA,SAAA,iBAAA,KAAA,8DAEA,CAGA,MAAA,UAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,SAAA,CAAA,QAAA,cAAA,cAAA,cAAA,WAAA,QAAA,YAAA,kBAAA,mBAAA,aAAA,gBAAA,mBAAA,SAAA,QAAA,WAAA,kBAAA,EAAA,eAAA,qBAAA,IAAA,SAAA,YAAA,OAAA,WAAA,2zEA0EA,CAAA,EChGA,MAAA,GAAA,OAGA,MAAA,GAAA,+3PAsNA,MAAA,GAAA,isUAmNA,MAAA,GAAA,smRAmNA,MAAA,GAAA,kvWAmNA,MAAA,GAAA,s0WAmNA,MAAA,GAAA,m9WAmNA,MAAA,GAAA,y+VAmNA,MAAA,GAAA,ypWCv8CA,SAAA,cAAA,KAAA;;8CAiBA,owDCfA,MAAA,YAAA,EAAA,kBAAA,IAAA,AAAA,CAAA,sCAAA,wBAAA,CAAA,KAAA,EAAA,CAAA,EAEA,SAAA,UAAA,KAAA;iDAGA,CAEA,SAAA,kCAAA,KAAA;;0PAgBA,CAgBA,MAAA,cAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,aAAA,CAAA,KAAA,QAAA,QAAA,sBAAA,MAAA,gBAAA,cAAA,WAAA,GAAA,snEA+DA,CAAA,stDCzFA,SAAA,kBAAA,KAAA,MAAA,8GAKA,CA8BA,MAAA,mBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,kBAAA,CAAA,OAAA,UAAA,sBAAA,MAAA,YAAA,UAAA,UAAA,cAAA,gBAAA,MAAA,gBAAA,cAAA,SAAA,WAAA,eAAA,GAAA,6mEAoGA,CAAA,EAEA,SAAA,iBAAA,CAAA,OAAA,OAAA,eAAA,UAAA,oIAQA,CAEA,MAAA,SAAA,CAAA,ECxJA,MAAA,mBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,kBAAA,CAAA,KAAA,UAAA,cAAA,eAAA,YAAA,YAAA,SAAA,UAAA,aAAA,gBAAA,WAAA,EAAA,UAAA,eAAA,iBAAA,47CAiDA,CAAA,26CC1DA,MAAA,cAAA,EAAA,kBAAA,IAAA,AAAA,CAAA,sCAAA,sBAAA,CAAA,KAAA,EAAA,CAAA,EAGA,SAAA,QAAA,QAAA,6EAGA,CAcA,MAAA,oBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,mBAAA,CAAA,KAAA,EAAA,gBAAA;ulDA8CA,CAAA,EC9DA,SAAA,sBAAA,CAAA,KAAA,WAAA,GAAA,+WAaA,CCbA,MAAA,iBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,gBAAA,CAAA,KAAA,WAAA,GAAA,wUAWA,CAAA,EAGA,MAAA,0BAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,yBAAA,CAAA,KAAA,GAAA,sPAaA,CAAA,EC1BA,MAAA,kBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,iBAAA,CAAA,KAAA,QAAA,OAAA,GAAA,kMAGA,CAAA,EAOA,SAAA,qBAAA,CAAA,KAAA,QAAA,mBAAA,+EAEA,CCDA,SAAA,gBAAA,CAAA,KAAA,OAAA,MAAA,GAAA,stBAkBA,CAGA,MAAA,sBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,qBAAA,CAAA,KAAA,GAAA,wGAIA,CAAA,2iDCxCA,MAAA,qBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,oBAAA,CAAA,KAAA,YAAA,GAAA,ymEAoDA,CAAA,ECrDA,SAAA,aAAA,MAAA,EAAA,mQAMA,CAQA,SAAA,kBAAA,MAAA,EAAA,qLAOA,CAGA,SAAA,oBAAA,gBAAA,YAAA,cAAA,scAiBA,CAEA,SAAA,oBAAA,MAAA,cAAA,sJAKA,CAUA,SAAA,sBAAA,gBAAA,aAAA,cAAA,EAAA,8yBA+BA,CC7EA,SAAA,eAAA,6yBAkCA,67JCrCA,SAAA,mBAAA,MAAA,EAAA,kEAEA,CAEA,SAAA,iBAAA,MAAA,EAAA,uEAEA,CAOA,SAAA,eAAA,CAAA,MAAA,GAAA,oxGA+EA,CCtGA,SAAA,cAAA,OAAA,2EAEA,wkBCMA,SAAA,YAAA,SAAA,KAAA,YAAA,6QASA,CAGA,MAAA,kBAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,iBAAA,CAAA,KAAA,SAAA,OAAA,WAAA,EAAA,UAAA,QAAA,qBAAA,izDAqDA,CAAA,ECzEA,SAAA,OAAA,MAAA,6EAEA,CAEA,SAAA,MAAA,OAAA,IAAA,oDAEA,CAGA,SAAA,cAAA,OAAA,maAWA,CAOA,SAAA,mBAAA,KAAA,w6BAqDA,uxECzEA,MAAA,cAAA,qxBAeA,SAAA,oBAAA,CAAA,KAAA,GAAA,2gEA2BA,CC9BA,SAAA,0BAAA,IAAA,iBAAA,aAAA,knGAyEA,CC7FA,MAAA,aAAA,CAAA,EAQA,SAAA,YAAA,CAAA,QAAA,UAAA,MAAA,YAAA,MAAA,SAAA,MAAA,WAAA,kBAAA,GAAA,6oEA6CA,CCrCA,SAAA,kBAAA,MAAA,gKAIA,CAOA,SAAA,qBAAA,KAAA,6UASA,y7CCUA,SAAA,YAAA,MAAA,ivBA+BA,CAOA,SAAA,eAAA,GAAA,EAAA,uMAQA,CASA,SAAA,gBAAA,MAAA,2GAGA,CAOA,SAAA,kBAAA,MAAA,8EAEA,CAuBA,SAAA,WAAA,MAAA,EAAA,uEAEA,CAGA,SAAA,QAAA,MAAA,OAAA,2RAYA,CAMA,SAAA,gBAAA,QAAA,cAAA,uLAIA,CAEA,SAAA,YAAA,MAAA,EAAA,yGAIA,CAGA,MAAA,qBAAA,wDAA6F,EAG7F,SAAA,UAAA,CAAA,KAAA,KAAA,MAAA,MAAA,ucAYA,CAOA,SAAA,WAAA,CAAA,KAAA,KAAA,MAAA,KAAA,MAAA,WAAA,UAAA,izCA4CA,CAMA,MAAA,cAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,aAAA,CAAA,QAAA,cAAA,oBAAA,GAAA,8wDA2CA,CAAA,EAGA,MAAA,WAAA,EAAA,MAAA,KAAA,AAAA,CAAA,SAAA,UAAA,CAAA,cAAA,oBAAA,GAAA,20DAmDA,CAAA,EC7UA,MAAA,2BAAA,+GAaA,SAAA,gBAAA,QAAA,kFAEA,CAOA,SAAA,oBAAA,SAAA,qJAIA,CAWA,SAAA,SAAA,QAAA,KAAA,UAAA,KAAA,QAAA,CAAA,EAAA,iMAsBA,CChEA,SAAA,SAAA,MAAA,+EAIA,CAEA,SAAA,WAAA,OAAA,IAAA,kFAGA,CAEA,SAAA,QAAA,OAAA,OAAA,MAAA,2PAUA,CAEA,SAAA,OAAA,MAAA,4CAEA,CAGA,MAAA,YAAA,gEASA,SAAA,YAAA,OAAA,+IAMA,CAOA,SAAA,gBAAA,OAAA,0eAgBA,CAOA,SAAA,oBAAA,OAAA,qJAIA,CAOA,SAAA,oBAAA,OAAA,4IAIA,CAOA,SAAA,kBAAA,QAAA,qCAEA,CAOA,SAAA,iBAAA,MAAA,qUAQA,CAOA,SAAA,oBAAA,UAAA,yNAOA,CAaA,SAAA,eAAA,QAAA,0TAWA,CAOA,SAAA,aAAA,MAAA,mLAUA,CCtIA,SAAA,aAAA,KAAA,KAAA,6JAaA,CAEA,SAAA,cAAA,OAAA,4CAEA,CAEA,SAAA,eAAA,MAAA,oJAIA,CAEA,SAAA,kBAAA,OAAA,mCAEA,CAEA,SAAA,wBAAA,OAAA,wHAKA,CAEA,SAAA,cAAA,MAAA,mFAKA,CAEA,SAAA,YAAA,MAAA,MAAA,IAAA,KAAA,k0EAqFA,CAEA,SAAA,cAAA,MAAA,MAAA,MAAA,mQAeA,CAEA,SAAA,eAAA,SAAA,0PASA,CAEA,SAAA,UAAA,MAAA,QAAA,63BAsCA,CAEA,SAAA,gBAAA,QAAA,qfAkBA,CASA,SAAA,iBAAA,QAAA,0uBA0BA,CAEA,SAAA,uBAAA,QAAA,wJAKA,CAGA,MAAA,oBAAA,6iEAqEA,SAAA,kCAAA,IAAA,iOAWA,CCpQA,SAAA,cAAA,MAAA,qBAEA,CAOA,SAAA,cAAA,MAAA,4BAEA,CC7HA,SAAA,kBAAA,KAAA,mSAUA,CCfA,MAAA,SAAA,CAAA,EAUA,IAAA,kBAAA,KAAA,84CCHA,MAAA,qBAAA,GACA,MAAA,uBAAA,IAMA,SAAA,QAAA,MAAA,MAAA,6ZAsBA,CAGA,SAAA,WAAA,KAAA,0IAGA,CAEA,SAAA,aAAA,KAAA,qJAMA,CAQA,SAAA,uBAAA,KAAA,MAAA,iLAOA,CASA,SAAA,mBAAA,KAAA,UAAA,MAAA,gaAkBA,CCzFA,SAAA,SAAA,KAAA,gHAGA,CAEA,SAAA,iBAAA,KAAA,MAAA,2UAYA,CAEA,SAAA,mBAAA,KAAA,UAAA,MAAA,86CAsDA,CAGA,IAAA,yBAAA,KAAA,izBC/DA,MAAA,WAAA,CAAA,EACA,MAAA,YAAA,CAAA,EACA,MAAA,YAAA,CAAA,EACA,MAAA,WAAA,CAAA,EAEA,SAAA,iBAAA,KAAA,MAAA,mFAEA,CAEA,SAAA,aAAA,QAAA,IAAA,OAAA,sGAWA,CAGA,IAAA,kBAAA,KAAA,8ZA4BA,IAAA,cAAA,KAAA,+kBAmCA,IAAA,qBAAA,KAAA,ytHA6JA,IAAA,yBAAA,KAAA,ygEAiFA,SAAA,YAAA,SAAA,YAAA,2TAaA,CASA,IAAA,2BAAA,KAAA,o6BAgDA,SAAA,QAAA,KAAA,KAAA,wBAEA,CAEA,SAAA,mBAAA,SAAA,kFAEA,CAEA,SAAA,gCAAA,SAAA,KAAA,WAAA,gVAaA,CAQA,SAAA,yBAAA,MAAA,04BAgCA,CAQA,SAAA,qBAAA,IAAA,cAAA,o2BA6BA,CASA,SAAA,wBAAA,MAAA,kcAaA,CAEA,SAAA,oBAAA,KAAA,2GAKA,CAEA,SAAA,gBAAA,KAAA,2JAUA,CAEA,SAAA,oBAAA,KAAA,OAAA,0aAaA,CAGA,IAAA,wBAAA,KAAA,29CA0DA,SAAA,eAAA,KAAA,MAAA,gZAaA,CAkBA,SAAA,aAAA,KAAA,iXAUA,CAEA,SAAA,eAAA,KAAA,MAAA,4EAEA,CAoBA,IAAA,mBAAA,KAAA,woFAsJA,MAAA,mBAAA,yDAOA,SAAA,mBAAA,IAAA,uvCA+DA,CAEA,SAAA,iBAAA,KAAA,MAAA,iQAQA,CAGA,IAAA,mBAAA,KAAA,mgGAkHA,SAAA,wBAAA,MAAA,IAAA,aAAA,QAAA,8DAQA,CAEA,SAAA,6BAAA,SAAA,KAAA,uLAOA,CAEA,SAAA,2BAAA,SAAA,KAAA,6HAOA,CAEA,SAAA,2BAAA,SAAA,KAAA,mPASA,CAGA,IAAA,oBAAA,KAAA,y9GAuIA,SAAA,QAAA,MAAA,8IAOA,CAEA,SAAA,iBAAA,SAAA,yHAGA,CAGA,MAAA,mBAAA,0IAUA,SAAA,6BAAA,IAAA,sDAEA,CC1qCA,MAAA,oBAAA,IAAA,IAAA,yFAsBA,SAAA,eAAA,MAAA,qFAIA,CAaA,SAAA,qBAAA,MAAA,yDAIA,CASA,SAAA,0BAAA,MAAA,yDAIA,CCnFA,MAAA,aAAA,qBAaA,SAAA,eAAA,MAAA,iQAYA,CAEA,SAAA,gBAAA,MAAA,SAAA,+jBAqBA,CAOA,SAAA,cAAA,MAAA,0TAeA,CAQA,SAAA,eAAA,MAAA,WAAA,itBA8BA,CAEA,SAAA,gBAAA,QAAA,+sBAuBA,CAQA,SAAA,sBAAA,MAAA,MAAA,gKAOA,CAGA,MAAA,kBAAA,guCAgDA,SAAA,gCAAA,IAAA,sDAEA,CC3MA,SAAA,gBAAA,QAAA,qPAOA,CAGA,MAAA,qBAAA,+1BAgCA,SAAA,mCAAA,IAAA,yDAEA,CCjDA,MAAA,0BAAA,4aAuBA,SAAA,oCAAA,IAAA,sEAEA,CCOA,MAAA,cAAA,uBAA+D,EAC/D,MAAA,sBAAA,IAAA,IAEA,SAAA,mBAAA,MAAA,yQAYA,CAEA,SAAA,gBAAA,QAAA,SAAA,6HAWA,CAQA,SAAA,YAAA,SAAA,OAAA,IAAA,ixBAkCA,CAEA,SAAA,gBAAA,OAAA,waAaA,CAGA,MAAA,wBAAA,gBAAA,WAAA,EAGA,MAAA,wBAAA,gBAAA,WAAA,EAMA,SAAA,+BAAA,IAAA,wHAGA,CCtGA,SAAA,uBAAA,MAAA,oIAIA,CAGA,SAAA,eAAA,MAAA,QAAA,6KAaA,CAUA,SAAA,uBAAA,SAAA,OAAA,2IAGA,CAGA,MAAA,kBAAA,kwEAgFA,MAAA,2BAAA,+VAiBA,SAAA,gCAAA,IAAA,qHAGA,CC9JA,SAAA,oBAAA,MAAA,SAAA,UAAA,iYAYA,CAGA,SAAA,0BAAA,QAAA,MAAA,SAAA,UAAA,iJAUA,CAeA,SAAA,wBAAA,QAAA,i7BAyBA,CASA,SAAA,wBAAA,QAAA,kiDA0DA,CAMA,SAAA,sCAAA,IAAA,2RAOA,CClJA,SAAA,cAAA,MAAA,gKASA,CAGA,SAAA,SAAA,SAAA,kJAGA,CAGA,MAAA,gBAAA,0kDAsDA,SAAA,8BAAA,IAAA,oDAEA,CC9EA,MAAA,UAAA,IAgBA,MAAA,gBAAA,IAAA,QAEA,SAAA,cAAA,MAAA,6BAEA,CAEA,SAAA,SAAA,MAAA,SAAA,yaAeA,CAMA,SAAA,WAAA,MAAA,MAAA,kyBA6BA,CAEA,SAAA,eAAA,KAAA,QAAA,mNAKA,CAEA,SAAA,WAAA,MAAA,SAAA,khBAkBA,CAaA,SAAA,UAAA,MAAA,KAAA,qQAaA,CAEA,SAAA,YAAA,MAAA,KAAA,SAAA,ucAiBA,CAEA,SAAA,aAAA,MAAA,6FAEA,CAEA,SAAA,aAAA,MAAA,+DAEA,CAEA,SAAA,YAAA,MAAA,OAAA,MAAA,wqBAuBA,CAEA,SAAA,eAAA,MAAA,MAAA,0iCA0BA,CAEA,SAAA,aAAA,MAAA,MAAA,cAAA,QAAA,IAAA,IAAA,MAAA,EAAA,+wCAyCA,CAEA,SAAA,eAAA,KAAA,MAAA,mFAEA,CAEA,SAAA,aAAA,QAAA,4OAOA,CAEA,SAAA,gBAAA,QAAA,gTAOA,CAGA,MAAA,eAAA,q5EAmEA,SAAA,6BAAA,IAAA,mPAYA,CCzVA,SAAA,WAAA,QAAA,6KAIA,CAMA,SAAA,WAAA,OAAA,6WAeA,CAEA,SAAA,YAAA,MAAA,mSAWA,CAEA,SAAA,gBAAA,QAAA,2NAMA,CAOA,MAAA,oBAAA,25BAuCA,SAAA,kCAAA,IAAA,wDAEA,CCpGA,SAAA,SAAA,QAAA,6KAIA,CAQA,SAAA,aAAA,QAAA,IAAA,4SAOA,CAEA,SAAA,UAAA,MAAA,yKAGA,CAGA,MAAA,wBAAA,6oBAiCA,SAAA,sCAAA,IAAA,4DAEA,CCvCA,SAAA,UAAA,MAAA,0EAGA,CAEA,SAAA,aAAA,MAAA,4ZAYA,CAEA,SAAA,sBAAA,MAAA,oYAUA,CAMA,SAAA,gBAAA,MAAA,uWAWA,CAOA,SAAA,oBAAA,MAAA,gNAWA,CASA,MAAA,0BAAA,ubAeA,SAAA,eAAA,QAAA,sJAGA,CAEA,SAAA,cAAA,QAAA,qVAaA,CAEA,SAAA,iBAAA,KAAA,gCAIA,CAEA,SAAA,aAAA,KAAA,2MAKA,CAEA,SAAA,YAAA,MAAA,KAAA,kkCA4CA,CAEA,SAAA,mBAAA,MAAA,MAAA,8pCAoCA,CAGA,MAAA,sBAAA,+qFAmGA,SAAA,oBAAA,IAAA,0jBA0BA,CCDA,SAAA,yBAAA,OAAA,KAAA,oJASA,CCnUA,SAAA,QAAA,MAAA,sEAEA,CAEA,SAAA,QAAA,OAAA,+GAOA,CAEA,SAAA,aAAA,QAAA,sGAGA,CAEA,SAAA,YAAA,OAAA,uDAEA,CAEA,SAAA,eAAA,MAAA,MAAA,mxCA2CA,CAEA,SAAA,kBAAA,SAAA,gtCAiCA,CAEA,SAAA,YAAA,MAAA,KAAA,KAAA,4CAMA,CAWA,SAAA,qBAAA,OAAA,24EAgGA,CClPA,SAAA,eAAA,MAAA,2CAEA,CAEA,SAAA,gBAAA,MAAA,iUAeA,CAEA,SAAA,aAAA,QAAA,kJAGA,CAEA,SAAA,QAAA,KAAA,qGAGA,CAEA,SAAA,SAAA,QAAA,uuCAsCA,CAGA,MAAA,mBAAA,knCA0CA,SAAA,iCAAA,IAAA,6WAkBA,CC3JA,SAAA,SAAA,KAAA,0rBAcA,CAEA,MAAA,2BAAA,IACA,MAAA,8BAAA,IACA,MAAA,2BAAA,IAAA,KAAA,UAAA,IAAA,GAAA,CAAA,YAAA,UAAA,CAAA,EACA,MAAA,sBAAA,8MAUA,SAAA,sBAAA,KAAA,waAcA,CAEA,SAAA,wBAAA,MAAA,qJAOA,CAEA,SAAA,mBAAA,KAAA,IAAA,wjBAqBA,CAEA,SAAA,eAAA,MAAA,oNAQA,CAEA,SAAA,oBAAA,MAAA,ykBAeA,CAQA,SAAA,eAAA,KAAA,KAAA,4RASA,CAQA,SAAA,gBAAA,MAAA,+4BAkCA,CC1JA,SAAA,OAAA,KAAA,6GAGA,CAEA,SAAA,UAAA,KAAA,oHAGA,CAEA,SAAA,MAAA,KAAA,gFAEA,CAEA,SAAA,YAAA,KAAA,MAAA,6QAKA,CAEA,SAAA,YAAA,KAAA,MAAA,sIAGA,CAEA,SAAA,iBAAA,SAAA,QAAA,wWAOA,CAEA,SAAA,SAAA,MAAA,IAAA,0HAIA,CAGA,IAAA,aAAA,KAAA,2xBAyBA,IAAA,WAAA,KAAA,u7FA8GA,SAAA,aAAA,MAAA,IAAA,uJAIA,CAGA,IAAA,aAAA,KAAA,iyEAiGA,MAAA,uBAAA,yLCnRA,SAAA,0BAAA,IAAA,okBAgBA,CCjBA,SAAA,eAAA,CAAA,KAAA,UAAA,UAAA,iHAEA,CAOA,SAAA,eAAA,CAAA,KAAA,KAAA,UAAA,GAAA,+KAGA,CCrBA,SAAA,oBAAA,IAAA,wlBAUA,CCRA,SAAA,gBAAA,CAAA,UAAA,cAAA,eAAA,gBAAA,GAAA,wiBAaA,CCtBA,SAAA,WAAA,MAAA,oCAEA,CAMA,SAAA,cAAA,KAAA,0DAEA,CAEA,SAAA,WAAA,OAAA,OAAA,2FAEA,CAEA,SAAA,UAAA,OAAA,UAAA,iGAEA,CAEA,SAAA,KAAA,OAAA,KAAA,OAAA,uIAKA,CAqDA,MAAA,MAAA,OAAA,IAAA,yBAAA,EACA,SAAA,SAAA,MAAA,UAAA,IAAA,IAAA,mpBAYA,CAMA,SAAA,eAAA,MAAA,mGAQA,CAMA,SAAA,WAAA,MAAA,6DAEA,CAqCA,SAAA,GAAA,KAAA,MAAA,4KAGA,CACA,SAAA,kBAAA,MAAA,8DAEA,CACA,SAAA,oBAAA,MAAA,2DAEA,CAEA,IAAA,2yCAqCA,EAAA,AAAA,CAAA,SAAA,OAAA,CAAA,EAAA,EAEA,MAAA,oBAAA,OAAA,WAEA,MAAA,oBAAA,OAAA,SAEA,MAAA,iBAAA,OAAA,QAEA,MAAA,iBAAA,OAAA,MAEA,SAAA,MAAA,OAAA,KAAA,IAAA,IAAA,q4BAwBA,CAUA,SAAA,UAAA,EAAA,EAAA,OAAA,gpCAgCA,CAqEA,IAAA,ohFAoEA,EAAA,AAAA,CAAA,OAAA,KAAA,CAAA,EAAA,EC7ZA,MAAA,QAAA,OAAA,IAAA,aAAA,EACA,MAAA,iBAAA,OAAA,IAAA,iBAAA,EACA,WAAA,wBAAA,EACA,WAAA,qBAAA,IAAA,GACA,IAAA,gBAAA,cAAA,SAAA,gdAeA,EACA,OAAA,eAAA,gBAAA,UAAA,iBAAA,CAAA,MAAA,IAAA,CAAA,EACA,MAAA,OAAA,SAAA,QAAA,ixBAyBA,EACA,OAAA,UAAA,OAAA,OAAA,SAAA,SAAA,EACA,OAAA,UAAA,SAAA,KACA,OAAA,eAAA,OAAA,UAAA,YAAA,CAAA,KAAA,oOAgBA,CAAA,CAAA,EACA,OAAA,gBAAA,gBACA,OAAA,UAAA,OAAA,SAAA,QAAA,mYAaA,EACA,OAAA,UAAA,IAAA,SAAA,IAAA,IAAA,MAAA,iCAGA,EACA,OAAA,UAAA,KAAA,SAAA,KAAA,MAAA,kCAGA,EACA,SAAA,UAAA,SAAA,SAAA,sRAQA,CACA,SAAA,SAAA,MAAA,oCAEA,CACA,SAAA,YAAA,KAAA,sDAEA,CACA,OAAA,UAAA,KAAA,SAAA,KAAA,SAAA,0vBAoBA,EACA,OAAA,UAAA,MAAA,SAAA,MAAA,IAAA,MAAA,iFAOA,EACA,IAAA,MAAA,MAAA,kDAMA,EAAA,OAAA,OAAA,OAAA,UAAA,CAAA,CAAA,KAAA,MAAA,KAAA,iFAOA,CAAA,CAAA,EACA,OAAA,UAAA,WAAA,SAAA,YAAA,2HAQA,EACA,OAAA,UAAA,aAAA,SAAA,cAAA,8HAQA,EACA,OAAA,UAAA,QAAA,SAAA,QAAA,OAAA,2HAQA,EACA,OAAA,UAAA,SAAA,SAAA,SAAA,MAAA,u8BA6BA,EACA,OAAA,UAAA,SAAA,SAAA,SAAA,OAAA,oEAEA,EACA,OAAA,UAAA,KAAA,SAAA,KAAA,KAAA,MAAA,gFAQA,EACA,IAAA,MAAA,MAAA,4DAQA,EAAA,OAAA,OAAA,OAAA,UAAA,CAAA,CAAA,KAAA,MAAA,iFAOA,CAAA,CAAA,EACA,OAAA,UAAA,SAAA,SAAA,UAAA,mHAGA,EACA,MAAA,UAAA,CAAA,EACA,MAAA,gBAAA,OAAA,yBAAA,EACA,SAAA,uBAAA,OAAA,KAAA,CAAA,EAAA,QAAA,MAAA,KAAA,IAAA,IAAA,uwBAWA,CACA,OAAA,OAAA,SAAA,OAAA,KAAA,QAAA,wBAEA,EACA,OAAA,QAAA,SAAA,QAAA,KAAA,OAAA,QAAA,CAAA,EAAA,OAAA,MAAA,4jCA0CA,EACA,OAAA,KAAA,SAAA,KAAA,OAAA,ghBAgBA,EACA,OAAA,KAAA,SAAA,KAAA,QAAA,6OAiBA,EACA,OAAA,QAAA,SAAA,SAAA,sCAEA,EACA,OAAA,QAAA,SAAA,SAAA,8DAEA,EACA,OAAA,KAAA,SAAA,MAAA,sOAMA,EACA,OAAA,OAAA,SAAA,OAAA,KAAA,GAAA,kNAQA,EACA,OAAA,YAAA,SAAA,YAAA,SAAA,6dAgBA,EACA,OAAA,OAAA,QAAA,KAAA,OAAA,QAAA,SAAA,gOAUA,CAAA,EACA,OAAA,OAAA,MAAA,MAAA,aAEA,CAAA,EACA,OAAA,OAAA,SAAA,KAAA,EAAA,UAAA,uEAEA,CAAA,EACA,OAAA,OAAA,SAAA,KAAA,CAAA,OAAA,UAAA,8GAGA,CAAA,EACA,SAAA,iBAAA,KAAA,KAAA,YAAA,QAAA,QAAA,MAAA,uPAIA,CACA,OAAA,OAAA,UAAA,KAAA,CAAA,MAAA,UAAA,2VAQA,CAAA,EACA,SAAA,aAAA,KAAA,OAAA,sVASA,CACA,SAAA,aAAA,KAAA,IAAA,KAAA,mRAMA,CACA,OAAA,OAAA,UAAA,KAAA,CAAA,MAAA,UAAA,iTAMA,CAAA,EACA,OAAA,OAAA,WAAA,KAAA,EAAA,UAAA,8GAGA,CAAA,EACA,OAAA,OAAA,UAAA,KAAA,CAAA,KAAA,MAAA,UAAA,ybAcA,CAAA,EACA,OAAA,OAAA,YAAA,KAAA,EAAA,UAAA,gHAGA,CAAA,EACA,OAAA,OAAA,MAAA,KAAA,CAAA,aAAA,UAAA,sfAaA,CAAA,EACA,SAAA,SAAA,KAAA,IAAA,OAAA,QAAA,qSAaA,CACA,OAAA,OAAA,SAAA,KAAA,CAAA,MAAA,MAAA,UAAA,sPAIA,CAAA,EACA,OAAA,OAAA,QAAA,KAAA,CAAA,MAAA,MAAA,QAAA,SAAA,uVAgBA,CAAA,EACA,OAAA,OAAA,SAAA,KAAA,CAAA,MAAA,QAAA,SAAA,qPAMA,CAAA,EACA,SAAA,MAAA,OAAA,KAAA,wEAKA,CACA,OAAA,OAAA,UAAA,KAAA,CAAA,MAAA,QAAA,SAAA,uRASA,CAAA,EACA,OAAA,OAAA,SAAA,KAAA,CAAA,KAAA,UAAA,QAAA,SAAA,6NAQA,CAAA,EACA,OAAA,OAAA,aAAA,KAAA,CAAA,KAAA,UAAA,QAAA,SAAA,wiBAaA,CAAA,EACA,OAAA,OAAA,aAAA,KAAA,CAAA,MAAA,SAAA,UAAA,UAAA,wJAIA,CAAA,EACA,MAAA,WAAA,CAAA,EACA,SAAA,aAAA,KAAA,KAAA,OAAA,y+BA2CA,CACA,aAAA,KAAA,CAAA,aAAA,GAAA,CAAA,eAAA,mFAGA,CAAA,EACA,aAAA,MAAA,CAAA,MAAA,KAAA,EACA,aAAA,QAAA,CAAA,MAAA,OAAA,EACA,aAAA,QAAA,CAAA,OAAA,GAAA,CAAA,SAAA,OAAA,QAAA,SAAA,KAAA,UAAA,KAAA,EAAA,KAAA,EACA,aAAA,SAAA,CAAA,MAAA,QAAA,EACA,aAAA,SAAA,CAAA,MAAA,QAAA,EACA,aAAA,UAAA,CAAA,MAAA,SAAA,EACA,aAAA,SAAA,CAAA,MAAA,MAAA,QAAA,EACA,aAAA,WAAA,CAAA,MAAA,UAAA,EACA,aAAA,QAAA,CAAA,OAAA,GAAA,CAAA,SAAA,GAAA,MAAA,SAAA,IAAA,EAAA,GAAA,EACA,aAAA,OAAA,CAAA,QAAA,MAAA,GAAA,CAAA,MAAA,QAAA,WAAA,KAAA,SAAA,EAAA,KAAA,MAAA,SAAA,EAAA,GAAA,EACA,aAAA,QAAA,CAAA,MAAA,GAAA,CAAA,QAAA,IAAA,KAAA,IAAA,OAAA,MAAA,SAAA,CAAA,CAAA,CAAA,KAAA,IAAA,EAAA,EAAA,EACA,aAAA,SAAA,CAAA,MAAA,GAAA,CAAA,QAAA,iLAKA,CAAA,EACA,aAAA,QAAA,CAAA,MAAA,GAAA,CAAA,MAAA,SAAA,oGAGA,CAAA,EACA,aAAA,YAAA,CAAA,MAAA,GAAA,CAAA,QAAA,6DAEA,CAAA,EACA,aAAA,YAAA,8BAIA,GAAA,CAAA,OAAA,UAAA,MAAA,SAAA,OAAA,CAAA,ECnnBA,MAAA,wBAAA,UAGA,MAAA,sBAAA,iBAGA,MAAA,sBAAA,iBAGA,MAAA,iBAAA,CAAA,aAAA,YAAA,EAMA,MAAA,wBAAA,aAGA,MAAA,qBAAA,gBAGA,MAAA,eAAA,CAAA,MAAA,OAAA,EAMA,MAAA,uBAAA,MAGA,MAAA,sBAAA,0CAAkF,EASlF,MAAA,4BAAA,SAGA,MAAA,qCAAA,WAGA,MAAA,+BAAA,4FAKA,MAAA,6BAAA,WAGA,MAAA,wBAAA,CAAA,UAAA,UAAA,EAMA,MAAA,0BAAA,WAMA,MAAA,qBAAA,UAiBA,MAAA,mBAAA,saAUA,MAAA,mBAAA,OAAA,OAAA,kBAAA,ECzEA,MAAA,SAAA,2fA+BA,SAAA,WAAA,eAAA,cAAA,wPAUA,CAEA,MAAA,gBAAA,kLAYA,SAAA,sBAAA,KAAA,eAAA,aAAA,cAAA,MAAA,4DAMA,CASA,SAAA,yBAAA,KAAA,eAAA,cAAA,6XAcA,w+CClGA,SAAA,cAAA,CAAA,MAAA,YAAA,MAAA,cAAA,QAAA,UAAA,8qCAgDA,CCzBA,MAAA,OAAA,8JAOA,MAAA,gBAAA,uFAKA,MAAA,oBAAA,wEAWA,SAAA,kBAAA,CAAA,kBAAA,kBAAA,kBAAA,kBAAA,iBAAA,iBAAA,GAAA,ilCAoCA,CChFA,IAAA,qBAAA,KAAA,+3CCiBA,SAAA,eAAA,CAAA,eAAA,oBAAA,eAAA,GAAA,6dAiBA,CC1BA,MAAA,QAAA,CAAA,kDACwD,EAAA,oDACE,CAAA,EAQ1D,SAAA,oBAAA,CAAA,oBAAA,oBAAA,GAAA,sbAeA,CCvCA,IAAA,uBAAA,KAAA,kcCDA,MAAA,aAAA,8CAWA,SAAA,iBAAA,KAAA,IAAA,uHAMA,CCkCA,MAAA,iBAAA,CAAA,MAAA,8OAYA,MAAA,iBAAA,CAAA,MAAA,wOAWA,MAAA,OAAA,wJASA,SAAA,MAAA,IAAA,0/PA0QA"}