vibe64 0.1.64 → 0.1.65

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 (125) hide show
  1. package/bin/upgrade-state.js +1631 -1630
  2. package/dist/assets/{GithubBrowserTabs-Cf6ce1lO.js → GithubBrowserTabs-D21Nl3QI.js} +1 -1
  3. package/dist/assets/{LocalDatabaseServer-0VGIcy5Q.js → LocalDatabaseServer-POxY1K1U.js} +1 -1
  4. package/dist/assets/{SelectField-RGWl_ms9.js → SelectField-Dezd0B3y.js} +1 -1
  5. package/dist/assets/{ShellOutlet-CdjsJfg9.js → ShellOutlet-DfF9vsWA.js} +1 -1
  6. package/dist/assets/{StudioErrorNotice-CCT_T6mT.js → StudioErrorNotice-vDR4qneB.js} +1 -1
  7. package/dist/assets/{VAutocomplete-BnpXAJGa.js → VAutocomplete-NpBcbYkR.js} +1 -1
  8. package/dist/assets/VBtn-Com1gNEe.js +1 -0
  9. package/dist/assets/{VCard-BFqQSnAE.js → VCard-DY_DdI8Z.js} +1 -1
  10. package/dist/assets/{VCheckbox-BK0ss4F4.js → VCheckbox-CkezAf4Z.js} +1 -1
  11. package/dist/assets/{VCheckboxBtn-DDlYJnth.js → VCheckboxBtn-8g4R-c2w.js} +1 -1
  12. package/dist/assets/{VChip-D2IukBZw.js → VChip-tORFnf7z.js} +1 -1
  13. package/dist/assets/{VDialog-BCIrX462.js → VDialog-CapFiCqp.js} +1 -1
  14. package/dist/assets/{VExpansionPanels-BHw1Id_o.js → VExpansionPanels-B6U2XdWH.js} +1 -1
  15. package/dist/assets/{VMenu-Bql3E6DV.js → VMenu-CO6B6LWk.js} +1 -1
  16. package/dist/assets/{VOverlay-EPzW7eVB.js → VOverlay-CrfaXCOL.js} +1 -1
  17. package/dist/assets/{VRadioGroup-CL3HTmyT.js → VRadioGroup-BrPW6foD.js} +1 -1
  18. package/dist/assets/{VRow-Dz87sIhY.js → VRow-DHETsEMn.js} +1 -1
  19. package/dist/assets/{VSelect-Ch00dyiM.js → VSelect-gYJ6qrBP.js} +1 -1
  20. package/dist/assets/{VSheet-D5wAuyc2.js → VSheet-_Grtwpfz.js} +1 -1
  21. package/dist/assets/{VSkeletonLoader-Bl9P5wdh.js → VSkeletonLoader-CQXCEJsR.js} +1 -1
  22. package/dist/assets/VSpacer-VLYDmg7o.js +1 -0
  23. package/dist/assets/{VSwitch-DftK1EyR.js → VSwitch-ffi-Y2TU.js} +1 -1
  24. package/dist/assets/{VTable-DHazU0Xx.js → VTable-Cver5Vl3.js} +1 -1
  25. package/dist/assets/{VTextField-B9R7EIjg.js → VTextField-DP6b7Qaf.js} +1 -1
  26. package/dist/assets/{VTextarea-CMgyRNk-.js → VTextarea-7mdIF4I0.js} +1 -1
  27. package/dist/assets/{VToolbar-C8ydxLzq.js → VToolbar-CYz3lneF.js} +1 -1
  28. package/dist/assets/{Vibe64AsyncModuleState-9bN0_H45.js → Vibe64AsyncModuleState-CO1rMrtD.js} +1 -1
  29. package/dist/assets/{Vibe64AuthSettingsButton-BGtVvQq0.js → Vibe64AuthSettingsButton-I3ufyScN.js} +1 -1
  30. package/dist/assets/{Vibe64ConversationLog-Cv_BE9yH.js → Vibe64ConversationLog-C04oOQ2g.js} +1 -1
  31. package/dist/assets/{Vibe64DashboardPageHeader-xfRLZ94G.js → Vibe64DashboardPageHeader-CobvMlFm.js} +1 -1
  32. package/dist/assets/{Vibe64DashboardShell-B3TN3NBS.js → Vibe64DashboardShell-BbrOUmRD.js} +1 -1
  33. package/dist/assets/{Vibe64DatabaseWorkspace-CU0jCfP_.js → Vibe64DatabaseWorkspace-VPEM2o1v.js} +1 -1
  34. package/dist/assets/{Vibe64DestinationButton-CdyyK9tj.js → Vibe64DestinationButton-B4Zz4a7J.js} +1 -1
  35. package/dist/assets/{Vibe64FileArea-BWl-q11N.js → Vibe64FileArea-C_nC2bPk.js} +1 -1
  36. package/dist/assets/{Vibe64OutputControls-DnfGKZHs.js → Vibe64OutputControls-DTO3Fw3x.js} +1 -1
  37. package/dist/assets/{Vibe64RepositoryWorkspace-3UKN_pPs.js → Vibe64RepositoryWorkspace-B8xcCOvL.js} +1 -1
  38. package/dist/assets/{Vibe64SessionFiles-B1U6XSWQ.js → Vibe64SessionFiles-Cb9Mxsyq.js} +1 -1
  39. package/dist/assets/{Vibe64SessionSourceEditor-De1QyTOd.js → Vibe64SessionSourceEditor-CVQ3NRjh.js} +1 -1
  40. package/dist/assets/{Vibe64UiStoryboardView-JRGcklim.js → Vibe64UiStoryboardView-BV4JFgcZ.js} +1 -1
  41. package/dist/assets/{Vibe64UnavailableSessions-Bd_-gPuL.js → Vibe64UnavailableSessions-DGQAxYE-.js} +1 -1
  42. package/dist/assets/{_pageId_-DIPouI7Z.js → _pageId_-CkG15vv4.js} +1 -1
  43. package/dist/assets/{_sessionId_-qH7uIGNl.js → _sessionId_-Bka3RUmK.js} +1 -1
  44. package/dist/assets/{_slug_-CaHlSQ8I.js → _slug_-7Oo7pGKn.js} +6 -6
  45. package/dist/assets/{_slug_-CZmGS16g.css → _slug_-BaxjtsgP.css} +1 -1
  46. package/dist/assets/{access-O4hOM9ov.js → access-Xo3unxGO.js} +1 -1
  47. package/dist/assets/{app-CXljwZ0u.js → app-B0spNegd.js} +1 -1
  48. package/dist/assets/assistantRouting-B9cub38g.js +3 -0
  49. package/dist/assets/{changes-C5gleyWS.js → changes-DFv4tuoO.js} +1 -1
  50. package/dist/assets/{client-CI-o7ITq.js → client-BjMjS6lX.js} +2 -2
  51. package/dist/assets/{client-DMEf6RSZ.js → client-CVuXqm4b.js} +1 -1
  52. package/dist/assets/{client-BRcncaFt.js → client-CevjVK2b.js} +1 -1
  53. package/dist/assets/{client-Do8szX_w.js → client-DR0w56e8.js} +2 -2
  54. package/dist/assets/{client-fF-hq8nJ.js → client-Dlg1kjjO.js} +1 -1
  55. package/dist/assets/{conversation-RscSzQxq.css → conversation-DReMq0MF.css} +1 -1
  56. package/dist/assets/{conversation-DiL2PEct.js → conversation-OkWbkHjm.js} +3 -3
  57. package/dist/assets/{dashboard-BWlG0Nli.js → dashboard-CAca9MQn.js} +1 -1
  58. package/dist/assets/{english-definitions-DcuZfQ4p.js → english-definitions-BtX8KA5g.js} +1 -1
  59. package/dist/assets/{env-D3DVC-Gd.js → env-DrNyBVkB.js} +1 -1
  60. package/dist/assets/errorMessageHelpers-B49LyMJi.js +1 -0
  61. package/dist/assets/{fileTypes-2k5HCkMT.js → fileTypes-iPZyrJA1.js} +1 -1
  62. package/dist/assets/{health-B9ZoQC78.js → health-B5yTW5Tt.js} +1 -1
  63. package/dist/assets/{history-BrWT8DRp.js → history-S3anp6xg.js} +1 -1
  64. package/dist/assets/{i18n-BkxO7BMl.js → i18n-DQPYjuW7.js} +1 -1
  65. package/dist/assets/{index-Ctygjyf8.css → index-DSyb-mRJ.css} +1 -1
  66. package/dist/assets/{index-HrVsvggI.js → index-JBqyg0mr.js} +3 -3
  67. package/dist/assets/{integrations-C4p_QTuv.js → integrations-C7dj7el_.js} +1 -1
  68. package/dist/assets/{issues-KxOOLtSM.js → issues-OkV4v4GX.js} +1 -1
  69. package/dist/assets/{layout-B_cpKP4k.js → layout-DMZV-nbg.js} +1 -1
  70. package/dist/assets/{lazy-vXRXMwYF.js → lazy-mtFmsnct.js} +1 -1
  71. package/dist/assets/{learning-BWqH7wag.js → learning-lW9nBGjT.js} +1 -1
  72. package/dist/assets/{pages-DcNh-g_z.js → pages-shOT9IVe.js} +1 -1
  73. package/dist/assets/{project-files-C3a_vnA4.js → project-files-D_K1N0JF.js} +1 -1
  74. package/dist/assets/{publish-B1f2baHh.js → publish-Bxe4ZCqe.js} +1 -1
  75. package/dist/assets/{pull-requests-BHq5Yafl.js → pull-requests-CQvk0TeH.js} +1 -1
  76. package/dist/assets/{repository-DMBew8kp.js → repository-CI2CqDwF.js} +1 -1
  77. package/dist/assets/{session-B5MoHBVk.js → session-FRkCCzYt.js} +1 -1
  78. package/dist/assets/{settings-DDpgGhWO.js → settings-DIVrFrs4.js} +1 -1
  79. package/dist/assets/{useArchivedVibe64Sessions-C5Qguyob.js → useArchivedVibe64Sessions-BkWrTOzg.js} +1 -1
  80. package/dist/assets/useAssistantAttachments-DqlNFiha.js +2 -0
  81. package/dist/assets/useCommand-D-MIMmhp.js +1 -0
  82. package/dist/assets/useEndpointResource-DZTjr9gg.js +1 -0
  83. package/dist/assets/useUiFeedback-BU4NyMq8.js +1 -0
  84. package/dist/assets/{useVibe64ConversationLog-BZ5g9Jp7.js → useVibe64ConversationLog-BADhWyNY.js} +2 -2
  85. package/dist/assets/{useVibe64Learning-DiLAIKbI.js → useVibe64Learning-CbsI-XHB.js} +1 -1
  86. package/dist/assets/{useVibe64SessionData-D9d4NfDo.js → useVibe64SessionData-DvFvAJC-.js} +1 -1
  87. package/dist/assets/{useVibe64SessionSelection-DT1rJVvx.js → useVibe64SessionSelection-BukDTAxb.js} +1 -1
  88. package/dist/assets/vibe64RepositoryRealtime-CRAyGyRD.css +1 -0
  89. package/dist/assets/vibe64RepositoryRealtime-DX2DEqIz.js +1 -0
  90. package/dist/assets/{vibe64SessionFocus-CLtCTOxq.js → vibe64SessionFocus-CzuP3qPT.js} +1 -1
  91. package/dist/index.html +37 -37
  92. package/docs/colleague-usage/ai-tasks.md +7 -0
  93. package/docs/colleague-usage/coding-agent-goal-pause.md +4 -4
  94. package/docs/colleague-usage/coding-agent-goals.md +18 -12
  95. package/docs/colleague-usage/coding-agents.md +22 -8
  96. package/docs/colleague-usage/project-messages.md +4 -1
  97. package/node_modules/@jskit-ai/assistant-core/CHANGELOG.md +5 -0
  98. package/node_modules/@jskit-ai/assistant-core/locales/en.json +5 -4
  99. package/node_modules/@jskit-ai/assistant-core/package.json +1 -1
  100. package/node_modules/@jskit-ai/assistant-runtime/package.json +1 -1
  101. package/node_modules/@jskit-ai/assistant-voice/package.json +1 -1
  102. package/node_modules/@jskit-ai/connector-google-calendar/package.json +1 -1
  103. package/node_modules/@jskit-ai/connectors-catalog/package.json +1 -1
  104. package/node_modules/@jskit-ai/connectors-core/package.json +1 -1
  105. package/node_modules/@jskit-ai/http-runtime/package.json +1 -1
  106. package/node_modules/@jskit-ai/kernel/CHANGELOG.md +1 -0
  107. package/node_modules/@jskit-ai/kernel/package.json +1 -1
  108. package/node_modules/@jskit-ai/payments-core/package.json +1 -1
  109. package/node_modules/@jskit-ai/realtime/package.json +1 -1
  110. package/node_modules/@jskit-ai/resource-core/package.json +1 -1
  111. package/node_modules/@jskit-ai/uploads-runtime/package.json +1 -1
  112. package/node_modules/@local/vibe64-core/package.json +1 -0
  113. package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +14 -14
  114. package/package.json +14 -14
  115. package/server.bundle.mjs +30898 -30856
  116. package/dist/assets/VBtn-2vbH580C.js +0 -1
  117. package/dist/assets/VSpacer-GgPR_AzN.js +0 -1
  118. package/dist/assets/assistantRouting-BS0ZW5Ki.js +0 -3
  119. package/dist/assets/errorMessageHelpers-BjIt31kK.js +0 -1
  120. package/dist/assets/useAssistantAttachments-DvEl7gX6.js +0 -2
  121. package/dist/assets/useCommand-CNDe8gM-.js +0 -1
  122. package/dist/assets/useEndpointResource-CmMwteuX.js +0 -1
  123. package/dist/assets/useUiFeedback-CWb6o71Z.js +0 -1
  124. package/dist/assets/vibe64RepositoryRealtime-kSshUn2K.js +0 -1
  125. package/dist/assets/vibe64RepositoryRealtime-rnWlv9jw.css +0 -1
@@ -1 +0,0 @@
1
- import{Ct as toRef,Kt as normalizeClass,M as mergeProps,N as nextTick,Xt as toDisplayString,Yt as normalizeStyle,b as createVNode,d as createBaseVNode,i as Fragment,it as watch,st as withDirectives,u as computed,xt as shallowRef}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{A as makeSizeProps,Bn as useElementSize,Bt as propsFactory,C as makeGroupItemProps,D as genOverlays,E as useGroupItem,F as useLocation,G as useRounded,I as makeElevationProps,In as PREFERS_REDUCED_MOTION,It as provideDefaults,J as useTextColor,Jn as isObject,L as useElevation,M as makeDensityProps,N as useDensity,O as makeVariantProps,P as makeLocationProps,R as makeBorderProps,S as VIcon,St as IconValue,T as useGroup,Tt as useRender,Un as isBoolean,W as makeRoundedProps,X as useDimension,Y as makeDimensionProps,Z as VDefaultsProvider,at as makeThemeProps,b as circularWavePath,c as makeRouterProps,f as makePositionProps,g as useLoader,h as makeLoaderProps,j as useSize,jt as genericComponent,k as useVariant,nn as clamp,nt as makeTagProps,ot as provideTheme,p as usePosition,rn as convertToUnit,s as Ripple,u as useLink,v as makeRevealProps,w as makeGroupProps,x as hasWave,y as useReveal,z as useBorder,zn as useElementIntersection,zt as makeComponentProps}from"./VChip-D2IukBZw.js";var makeVBtnGroupProps=propsFactory({baseColor:String,connected:Boolean,divided:Boolean,direction:{type:String,default:`horizontal`},...makeBorderProps(),...makeComponentProps(),...makeDensityProps(),...makeElevationProps(),...makeRoundedProps(),...makeSizeProps({size:void 0}),...makeTagProps(),...makeThemeProps(),...makeVariantProps()},`VBtnGroup`);var VBtnGroup=genericComponent()({name:`VBtnGroup`,props:makeVBtnGroupProps(),setup(props,{slots}){const{themeClasses}=provideTheme(props);const{densityClasses}=useDensity(props);const{borderClasses}=useBorder(props);const{elevationClasses}=useElevation(props);const{roundedClasses,roundedStyles}=useRounded(props);provideDefaults({VBtn:{height:toRef(()=>props.direction===`horizontal`&&props.size==null?`auto`:null),baseColor:toRef(()=>props.baseColor),color:toRef(()=>props.color),density:toRef(()=>props.density),flat:true,size:toRef(()=>props.size),variant:toRef(()=>props.variant)}});useRender(()=>{return createVNode(props.tag,{"class":normalizeClass([`v-btn-group`,`v-btn-group--${props.direction}`,{"v-btn-group--connected":props.connected,"v-btn-group--divided":props.divided,"v-btn-group--has-size":props.size!=null},`v-btn-group--size-${props.size??`default`}`,themeClasses.value,borderClasses.value,densityClasses.value,elevationClasses.value,roundedClasses.value,props.class]),"style":normalizeStyle([roundedStyles.value,props.style])},slots)})}});var VBtnToggleSymbol=Symbol.for(`vuetify:v-btn-toggle`);var makeVBtnToggleProps=propsFactory({...makeVBtnGroupProps(),...makeGroupProps()},`VBtnToggle`);var VBtnToggle=genericComponent()({name:`VBtnToggle`,props:makeVBtnToggleProps(),emits:{"update:modelValue":value=>true},setup(props,{slots}){const{isSelected,next,prev,select,selected}=useGroup(props,VBtnToggleSymbol);useRender(()=>{const btnGroupProps=VBtnGroup.filterProps(props);return createVNode(VBtnGroup,mergeProps({"class":[`v-btn-toggle`,{"v-btn-toggle--has-color":!!props.color},props.class]},btnGroupProps,{"style":props.style}),{default:()=>[slots.default?.({isSelected,next,prev,select,selected})]})});return{next,prev,select}}});var WAVE_AMPLITUDE=1.6;var WAVELENGTH=15;var WAVE_GAP=4;var makeVProgressCircularProps=propsFactory({bgColor:String,color:String,indeterminate:[Boolean,String],rounded:Boolean,modelValue:{type:[Number,String],default:0},rotate:{type:[Number,String],default:0},shape:{type:String,default:`flat`,validator:v=>[`flat`,`wavy`].includes(v)},variant:{type:String,default:void 0,validator:v=>[`split`].includes(v)},transition:{type:[Boolean,Object],default:void 0},width:{type:[Number,String],default:4},...makeComponentProps(),...makeRevealProps(),...makeSizeProps(),...makeTagProps({tag:`div`}),...makeThemeProps()},`VProgressCircular`);var VProgressCircular=genericComponent()({name:`VProgressCircular`,props:makeVProgressCircularProps(),setup(props,{slots}){const MAGIC_RADIUS_CONSTANT=20;const CIRCUMFERENCE=2*Math.PI*MAGIC_RADIUS_CONSTANT;const root=shallowRef();const{themeClasses}=provideTheme(props);const{sizeClasses,sizeStyles}=useSize(props);const{textColorClasses,textColorStyles}=useTextColor(()=>props.color);const{textColorClasses:underlayColorClasses,textColorStyles:underlayColorStyles}=useTextColor(()=>props.bgColor);const{width:containerWidth}=useElementSize(root);const{isIntersecting}=useElementIntersection(root);const{state:revealState,duration:revealDuration}=useReveal(props);const normalizedValue=toRef(()=>revealState.value===`initial`?0:clamp(parseFloat(props.modelValue),0,100));const width=toRef(()=>Number(props.width));const transitionDuration=toRef(()=>props.transition===false?void 0:convertToUnit(isObject(props.transition)?props.transition.duration:void 0,`ms`));const size=toRef(()=>{return sizeStyles.value?Number(props.size):containerWidth.value?containerWidth.value:Math.max(width.value,32)});const diameter=toRef(()=>MAGIC_RADIUS_CONSTANT/(1-width.value/size.value)*2);const strokeWidth=toRef(()=>width.value/size.value*diameter.value);const strokeDashOffset=toRef(()=>{const baseLength=(100-normalizedValue.value)/100*CIRCUMFERENCE;return props.rounded&&normalizedValue.value>0&&normalizedValue.value<100?convertToUnit(Math.min(CIRCUMFERENCE-.01,baseLength+strokeWidth.value)):convertToUnit(baseLength)});const startAngle=computed(()=>{const baseAngle=Number(props.rotate);return props.rounded?baseAngle+strokeWidth.value/2/CIRCUMFERENCE*360:baseAngle});const isWavy=toRef(()=>props.shape===`wavy`);const geometry=computed(()=>{if(props.variant!==`split`&&!isWavy.value)return void 0;const scale=diameter.value/size.value;const radius=MAGIC_RADIUS_CONSTANT;const amplitude=isWavy.value&&(props.indeterminate||hasWave(normalizedValue.value))?WAVE_AMPLITUDE*scale:0;const waves=Math.max(3,Math.floor(CIRCUMFERENCE/(WAVELENGTH*scale)));const center=diameter.value/2;const arc=`A ${radius} ${radius} 0 1 1`;const roundCaps=props.rounded||isWavy.value;return{waves,linecap:roundCaps?`round`:`butt`,gap:(WAVE_GAP*scale+(roundCaps?strokeWidth.value:0))/CIRCUMFERENCE*100,track:`M ${center+radius} ${center}`+` ${arc} ${center-radius} ${center} ${arc} ${center+radius} ${center}`.repeat(2),wave:circularWavePath(center,radius-amplitude,amplitude,waves)}});useRender(()=>createVNode(props.tag,{"ref":root,"class":normalizeClass([`v-progress-circular`,{"v-progress-circular--indeterminate":!!props.indeterminate,"v-progress-circular--visible":isIntersecting.value,"v-progress-circular--variant-split":props.variant===`split`,"v-progress-circular--shape-wavy":isWavy.value,"v-progress-circular--disable-shrink":props.indeterminate&&(props.indeterminate===`disable-shrink`||PREFERS_REDUCED_MOTION()),"v-progress-circular--revealing":[`initial`,`pending`].includes(revealState.value),"v-progress-circular--no-transition":props.transition===false},themeClasses.value,sizeClasses.value,textColorClasses.value,props.class]),"style":normalizeStyle([sizeStyles.value,textColorStyles.value,{"--v-progress-reveal-duration":`${revealDuration.value}ms`,"--v-progress-circular-transition-duration":transitionDuration.value},props.style]),"role":`progressbar`,"aria-valuemin":`0`,"aria-valuemax":`100`,"aria-valuenow":props.indeterminate?void 0:normalizedValue.value},{default:()=>[createBaseVNode(`svg`,{"style":{transform:`rotate(calc(-90deg + ${startAngle.value}deg))`},"xmlns":`http://www.w3.org/2000/svg`,"viewBox":`0 0 ${diameter.value} ${diameter.value}`},[geometry.value?createBaseVNode(`g`,{"class":`v-progress-circular__split`,"style":{"--v-progress-circular-value":normalizedValue.value,"--v-progress-circular-stroke":convertToUnit(strokeWidth.value),"--v-progress-circular-waves":geometry.value.waves,"--v-progress-circular-gap":geometry.value.gap}},[createBaseVNode(`path`,{"class":normalizeClass([`v-progress-circular__underlay`,`v-progress-circular__track`,underlayColorClasses.value]),"style":normalizeStyle(underlayColorStyles.value),"d":geometry.value.track,"pathLength":`200`,"stroke-linecap":geometry.value.linecap},null),createBaseVNode(`path`,{"class":`v-progress-circular__wave`,"style":{d:`path("${geometry.value.wave}")`},"d":geometry.value.wave,"pathLength":100+100/geometry.value.waves,"stroke-linecap":geometry.value.linecap},null)]):createBaseVNode(Fragment,null,[createBaseVNode(`circle`,{"class":normalizeClass([`v-progress-circular__underlay`,underlayColorClasses.value]),"style":normalizeStyle(underlayColorStyles.value),"fill":`transparent`,"cx":`50%`,"cy":`50%`,"r":MAGIC_RADIUS_CONSTANT,"stroke-width":strokeWidth.value,"stroke-dasharray":CIRCUMFERENCE,"stroke-dashoffset":0},null),createBaseVNode(`circle`,{"class":`v-progress-circular__overlay`,"fill":`transparent`,"cx":`50%`,"cy":`50%`,"r":MAGIC_RADIUS_CONSTANT,"stroke-width":strokeWidth.value,"stroke-dasharray":CIRCUMFERENCE,"stroke-dashoffset":strokeDashOffset.value,"stroke-linecap":props.rounded?`round`:void 0},null)])]),slots.default&&createBaseVNode(`div`,{"class":`v-progress-circular__content`},[slots.default({value:normalizedValue.value})])]}));return{}}});function useSelectLink(link,select){watch(()=>link.isActive?.value,isActive=>{if(link.isLink.value&&isBoolean(isActive)&&select)nextTick(()=>{select(isActive)})},{immediate:true})}var makeVBtnProps=propsFactory({active:{type:Boolean,default:void 0},activeColor:String,baseColor:String,symbol:{type:null,default:VBtnToggleSymbol},flat:Boolean,icon:[Boolean,String,Function,Object],prependIcon:IconValue,appendIcon:IconValue,block:Boolean,readonly:Boolean,slim:Boolean,stacked:Boolean,spaced:String,ripple:{type:[Boolean,Object],default:true},text:{type:[String,Number,Boolean],default:void 0},...makeBorderProps(),...makeComponentProps(),...makeDensityProps(),...makeDimensionProps(),...makeElevationProps(),...makeGroupItemProps(),...makeLoaderProps(),...makeLocationProps(),...makePositionProps(),...makeRoundedProps(),...makeRouterProps(),...makeSizeProps(),...makeTagProps({tag:`button`}),...makeThemeProps(),...makeVariantProps({variant:`elevated`})},`VBtn`);var VBtn=genericComponent()({name:`VBtn`,props:makeVBtnProps(),emits:{"group:selected":val=>true},setup(props,{attrs,slots}){const{themeClasses}=provideTheme(props);const{borderClasses}=useBorder(props);const{densityClasses}=useDensity(props);const{dimensionStyles}=useDimension(props);const{elevationClasses}=useElevation(props);const{loaderClasses}=useLoader(props);const{locationStyles}=useLocation(props);const{positionClasses}=usePosition(props);const{roundedClasses,roundedStyles}=useRounded(props);const{sizeClasses,sizeStyles}=useSize(props);const group=useGroupItem(props,props.symbol,false);const link=useLink(props,attrs);const isActive=computed(()=>{if(props.active!==void 0)return props.active;if(link.isRouterLink.value)return link.isActive?.value;return group?.isSelected.value});const color=toRef(()=>isActive.value?props.activeColor??props.color:props.color);const variantProps=computed(()=>{return{color:group?.isSelected.value&&(!link.isLink.value||link.isActive?.value)||!group||link.isActive?.value?color.value??props.baseColor:props.baseColor,variant:props.variant}});const{colorClasses,colorStyles,variantClasses}=useVariant(variantProps);const isDisabled=computed(()=>group?.disabled.value||props.disabled);const isElevated=toRef(()=>{return props.variant===`elevated`&&!(props.disabled||props.flat||props.border)});const valueAttr=computed(()=>{if(props.value===void 0||typeof props.value===`symbol`)return void 0;return Object(props.value)===props.value?JSON.stringify(props.value,null,0):props.value});function onClick(e){if(isDisabled.value||link.isLink.value&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||attrs.target===`_blank`))return;if(link.isRouterLink.value)link.navigate.value?.(e);else group?.toggle()}useSelectLink(link,group?.select);useRender(()=>{const Tag=link.isLink.value?`a`:props.tag;const hasPrepend=!!(props.prependIcon||slots.prepend);const hasAppend=!!(props.appendIcon||slots.append);const hasIcon=!!(props.icon&&props.icon!==true);return withDirectives(createVNode(Tag,mergeProps(link.linkProps,{"type":Tag===`a`?void 0:`button`,"class":[`v-btn`,group?.selectedClass.value,{"v-btn--active":isActive.value,"v-btn--block":props.block,"v-btn--disabled":isDisabled.value,"v-btn--elevated":isElevated.value,"v-btn--flat":props.flat,"v-btn--icon":!!props.icon,"v-btn--loading":props.loading,"v-btn--readonly":props.readonly,"v-btn--slim":props.slim,"v-btn--stacked":props.stacked},props.spaced?[`v-btn--spaced`,`v-btn--spaced-${props.spaced}`]:[],themeClasses.value,borderClasses.value,colorClasses.value,densityClasses.value,elevationClasses.value,loaderClasses.value,positionClasses.value,roundedClasses.value,sizeClasses.value,variantClasses.value,props.class],"style":[colorStyles.value,dimensionStyles.value,locationStyles.value,sizeStyles.value,roundedStyles.value,props.style],"aria-busy":props.loading?true:void 0,"disabled":isDisabled.value&&Tag!==`a`||void 0,"tabindex":props.loading||props.readonly?-1:void 0,"onClick":onClick,"value":Tag!==`a`?valueAttr.value:void 0}),{default:()=>[genOverlays(true,`v-btn`),!props.icon&&hasPrepend&&createBaseVNode(`span`,{"key":`prepend`,"class":`v-btn__prepend`},[!slots.prepend?createVNode(VIcon,{"key":`prepend-icon`,"icon":props.prependIcon},null):createVNode(VDefaultsProvider,{"key":`prepend-defaults`,"disabled":!props.prependIcon,"defaults":{VIcon:{icon:props.prependIcon}}},slots.prepend)]),createBaseVNode(`span`,{"class":`v-btn__content`,"data-no-activator":``},[!slots.default&&hasIcon?createVNode(VIcon,{"key":`content-icon`,"icon":props.icon},null):createVNode(VDefaultsProvider,{"key":`content-defaults`,"disabled":!hasIcon,"defaults":{VIcon:{icon:props.icon}}},{default:()=>[slots.default?.()??toDisplayString(props.text)]})]),!props.icon&&hasAppend&&createBaseVNode(`span`,{"key":`append`,"class":`v-btn__append`},[!slots.append?createVNode(VIcon,{"key":`append-icon`,"icon":props.appendIcon},null):createVNode(VDefaultsProvider,{"key":`append-defaults`,"disabled":!props.appendIcon,"defaults":{VIcon:{icon:props.appendIcon}}},slots.append)]),!!props.loading&&createBaseVNode(`span`,{"key":`loader`,"class":`v-btn__loader`},[slots.loader?.()??createVNode(VProgressCircular,{"color":isBoolean(props.loading)?void 0:props.loading,"indeterminate":true,"width":`2`},null)])]}),[[Ripple,!isDisabled.value&&props.ripple,``,{center:!!props.icon}]])});return{group}}});export{VBtnToggle as i,makeVBtnProps as n,VProgressCircular as r,VBtn as t};
@@ -1 +0,0 @@
1
- import{r as createSimpleFunctional}from"./lazy-vXRXMwYF.js";var VSpacer=createSimpleFunctional(`v-spacer`,`div`,`VSpacer`);export{VSpacer as t};
@@ -1,3 +0,0 @@
1
- import{t as AppError}from"./errors-D17nJYne.js";import{b as sameVibe64AssistantSelection,c as vibe64AssistantSelectionLabel,y as defineVibe64AssistantSelection}from"./shared-B6plZPQ_.js";var ASSISTANT_FINISHING_DEFAULTS=Object.freeze({review:true,deslop:true,uiPass:true,autoSave:true});var ASSISTANT_FINISHING_STEPS=Object.freeze([{id:`review`,name:`Review`,setting:`Automatically review changes`,genesisTask:`review`},{id:`deslop`,name:`Deslop`,setting:`Automatically deslop changes`,genesisTask:`deslop`},{id:`uiPass`,name:`UI pass`,setting:`Automatically UI pass changes`,genesisTask:`ui-pass`},{id:`autoSave`,name:`Save`,setting:`Automatically save changes`}].map(Object.freeze));var ASSISTANT_NO_FINISHING=Object.freeze(Object.fromEntries(ASSISTANT_FINISHING_STEPS.map(({id})=>[id,false])));var ASSISTANT_MODES=Object.freeze([{id:`custom`,label:`Custom`,description:`Choose a model and thinking level for this chat.`},{id:`senior`,label:`Senior`,description:`Talk directly to your most capable model. Ask questions or request changes.`},{id:`junior`,label:`Junior`,description:`Talk directly to your everyday model. Ask questions or request changes.`},{id:`auto`,label:`Auto`,description:`Name either role, or let Senior handle plans and finishing steps and Junior handle other requests.`}]);var ASSISTANT_FIX_MODE=Object.freeze({id:`fix`,label:`Fix it with AI`,description:`Repair what went wrong with the Fix it with AI model.`});var ASSISTANT_ROUTING_METADATA=`assistant_routing`;var ASSISTANT_SETUP_ROLES=Object.freeze({owner:Object.freeze([`senior`,`junior`,`router`,`colleague`,`fix`,`explain`,`quickHelper`]),nonOwner:Object.freeze([`colleague`,`fix`,`explain`,`quickHelper`])});var ASSISTANT_FOLLOWING_ROLES=Object.freeze([`colleague`,`fix`,`explain`]);var ASSISTANT_ROUTING_ROLE_DEFINITIONS=Object.freeze([{id:`senior`,label:`Senior`,description:`Plans, reviews, Deslop and UI passes in main chat. Your most capable model.`,group:`main`},{id:`junior`,label:`Junior`,description:`Everyday changes in main chat.`,group:`main`},{id:`router`,label:`Router`,description:`Chooses Senior or Junior when main chat is on Auto.`,group:`main`},{id:`colleague`,label:`Colleague`,description:`The default for Colleague. Each person can change their own.`,group:`helpers`},{id:`fix`,label:`Fix it with AI`,description:`Repair chats opened from errors and conflicts. Can run in a different tool from the chat it fixes.`,group:`helpers`},{id:`explain`,label:`Explain & check`,description:`Explain this code, the database assistant and Check my work.`,group:`helpers`},{id:`quickHelper`,label:`Quick helper`,description:`Titles, commit messages, prompt hints and summaries.`,group:`helpers`}].map(Object.freeze));var ASSISTANT_ROLE_DEFAULT_FOLLOWS=Object.freeze({owner:Object.freeze({colleague:`senior`,fix:`junior`,explain:`quickHelper`}),nonOwner:Object.freeze({fix:`colleague`,explain:`quickHelper`})});var ROUTING_REASONS=Object.freeze([`conversation`,`planning`,`implementation`,`review`]);var MAIN_CHAT_PURPOSES=Object.freeze([`custom`,`senior`,`junior`,`auto`,`review`,`deslop`,`ui_pass`,`request_routing`]);var ASSISTANT_PURPOSE_ROLES=Object.freeze({custom:`custom`,senior:`senior`,junior:`junior`,review:`senior`,deslop:`senior`,ui_pass:`senior`,request_routing:`router`,colleague:`colleague`,fix:`fix`,source_explanation:`explain`,database_assistant:`explain`,lesson_review:`explain`,commit_title:`quickHelper`,session_title:`quickHelper`,prompt_hint:`quickHelper`,conversation_summary:`quickHelper`,voice_turn:`quickHelper`,quick_helper:`quickHelper`});var ASSISTANT_ROLE_PURPOSES=Object.freeze({senior:`senior`,junior:`junior`,router:`request_routing`,colleague:`colleague`,fix:`fix`,explain:`source_explanation`,quickHelper:`prompt_hint`});function assistantModeLabel(mode){return ASSISTANT_MODES.find(({id})=>id===mode)?.label||(mode===`fix`?ASSISTANT_FIX_MODE.label:``)||{review:`Senior review`,deslop:`Senior Deslop`,ui_pass:`Senior UI pass`}[mode]||ASSISTANT_ROUTING_ROLE_DEFINITIONS.find(({id})=>id===mode)?.label||``}function routingError(message,code,options={}){return new AppError(409,message,{...options,code})}var upgradeRequired=()=>routingError(`This saved request predates the current AI setup. The administrator must run the state upgrade.`,`vibe64_assistant_routing_upgrade_required`);var choosesAutomation=mode=>mode!==`fix`;function assistantRoutingPreferences(value={}){if(!value||typeof value!==`object`||Array.isArray(value)||![...ASSISTANT_MODES,ASSISTANT_FIX_MODE].some(({id})=>id===value.mode))throw routingError(`Choose Custom, Senior, Junior, or Auto.`,`vibe64_assistant_mode_invalid`);if(Object.hasOwn(value,`workflowEngineId`))throw upgradeRequired();if(value.mode===`custom`&&!value.override)throw routingError(`Choose a custom model first.`,`vibe64_assistant_custom_model_required`);const automation=choosesAutomation(value.mode)?assistantRoutingAutomation(value):ASSISTANT_NO_FINISHING;return{mode:value.mode,...automation,...value.override&&![`auto`,`fix`].includes(value.mode)?{override:defineVibe64AssistantSelection(value.override)}:{}}}function assistantRoutingAutomation(value){const chosen=value&&choosesAutomation(value.mode)?value:{};return Object.fromEntries(ASSISTANT_FINISHING_STEPS.map(({id})=>[id,typeof chosen[id]===`boolean`?chosen[id]:ASSISTANT_FINISHING_DEFAULTS[id]]))}var ASSISTANT_TASK_PURPOSES=Object.freeze({deslop:`deslop`,"ui-pass":`ui_pass`});function assistantRoutingFromMetadata(metadata={}){if(!metadata[`assistant_routing`])return null;const saved=JSON.parse(metadata[ASSISTANT_ROUTING_METADATA]);if(saved&&typeof saved===`object`&&typeof saved.deslop!==`boolean`)throw upgradeRequired();return assistantRoutingPreferences(saved)}var assistantRoutingRequestFromMetadata=metadata=>JSON.parse(metadata?.assistant_routing_request||`null`);function assistantRoutingRequestForDisplay(metadata={}){try{return assistantRoutingRequestFromMetadata(metadata)}catch{return null}}var ASSISTANT_WORKFLOW_STATUSES=Object.freeze([`working`,`waiting`,`complete`]);var ASSISTANT_WORKFLOW_DELIVERIES=Object.freeze([`routing`,`pending`,`sending`,`uncertain`,`accepted`,`failed`]);var assistantWorkflowRole=request=>request.stage===`review`&&request.followup&&request.mode===`auto`?`senior`:request.resolvedMode;function assistantSetupRoleValue(setupValues,role){const value=setupValues[role];return value?.follows?{value:setupValues[value.follows]??null,followedRole:value.follows}:{value:value??null,followedRole:``}}function assistantRoutingStatusIsPending(request){return request?.status!==`complete`&&[`routing`,`pending`,`sending`,`uncertain`].includes(request?.delivery)}function assistantRoutingRequestCanBeReplaced(request,selection){if(request?.helper)return false;const previous=request?.deliverySelection||request?.observedSelection;if(request?.stopped&&previous&&selection&&!sameVibe64AssistantSelection(previous,selection))return true;return request?.delivery===`pending`&&(request.status===`waiting`||Boolean(request.error))&&!request.attemptedMessageId}function assistantRoutingRequestIsUnresolved(request,selection){return assistantRoutingStatusIsPending(request)&&!assistantRoutingRequestCanBeReplaced(request,selection)}function assistantModePrompt(mode,message,options={}){let{planInstructions=``,intent=``,browserReview=false}=options;const{rework=`junior`}=options;const direct=`Work directly from the user's request and conversation, answering questions or implementing changes as requested. You may edit application files when requested. Make ordinary local choices using established project patterns, ask about unresolved scope or design decisions, preserve unrelated work, and verify changes with relevant checks.`;const instructions={custom:direct,senior:direct,junior:direct,fix:direct,deslop:[`Perform Deslop directly using the project's Deslop guidance.`,`You may edit code for behavior-preserving cleanup; earlier Auto planning restrictions do not apply.`,`Preserve existing behavior, unrelated work and staging.`,`Use the user's selected commits or scope; otherwise clean up only the current task's changes.`,`Do not implement features, fix behavior-changing defects, create an implementation plan, or delegate cleanup to another model.`,`Report discovered defects separately without fixing them.`,`Run focused checks, then report what became simpler and what was verified.`,`Do not commit, push or deploy.`].join(` `),ui_pass:[`Perform the UI pass directly using the project's UI pass guidance, on the scope this request names.`,`You may edit code to bring those screens in line with the project's UI guidance; earlier Auto planning restrictions do not apply.`,`Preserve each screen's behavior, unrelated work and staging.`,`Do not implement features, fix behavior-changing defects, create an implementation plan, or delegate the pass to another model.`,`Report discovered defects separately without fixing them.`,`Check the screens you changed in the managed browser, run focused checks, then report what changed and what was verified.`,`Do not commit, push or deploy.`].join(` `),review:[`Review the preceding coding work against the original request and accepted steering.`,`Inspect actual files and relevant surrounding code. You may directly fix in-scope defects.`,`Earlier Auto planning restrictions do not apply.`,`Preserve unrelated work and staging, and report out-of-scope defects without fixing them.`,`For a cleanup-only request, apply the project's Deslop guidance and preserve behavior; report behavior-changing defects separately without fixing them.`,`Perform the review yourself in this turn. Cleanup is optional and only runs when requested in this review's instructions.`,`If implementation is missing or coding stopped for a decision, report that and preserve the decision for the user; do not start the original implementation from scratch.`,`Run relevant checks, then report findings, fixes, actual checks and anything unverified.`,`You own browser verification for this review. Exercise the requested user flow and inspect meaningful visual checkpoints yourself using the supplied managed browser tools; the implementer's code tests do not replace these checks. Reuse reliable passing evidence and avoid repeating unaffected checks. Report browser or visual checks that could not be performed, and do not claim verified completion while required checks remain unfinished.`,`Do not Save, push or invent new product requirements. For substantial necessary rework within the agreed outcome, `+{junior:`update the technical plan and hand back to Junior through the workflow outcome command. Junior implementation will receive another Senior review and any enabled Deslop and UI pass.`,self:`return to your own implementation through the workflow outcome command; this finishing turn then runs again over that rework.`,report:`report what it needs instead of starting it in this review.`}[rework]].join(` `)};if(!instructions[mode])throw routingError(`Unknown assistant mode.`,`vibe64_assistant_mode_unknown`);let instruction=instructions[intent]||instructions[mode];switch(intent){case`conversation`:instruction=`Answer or investigate the user's question. You may use vibe64-helper plan read or history to inspect a referenced plan. Do not create or update a plan, change its status, edit application files, run state-changing operations, or delegate implementation. Explain missing or completed plans without reopening them.`;break;case`planning`:instruction=`Discuss and manage the plan as requested through vibe64-helper plan. Do not change application files in a planning-only request. Clarify ambiguous references before changing a plan. Junior may update paired Progress and existing checklist ticks as work is verified; agreed Plan scope and lifecycle changes require Senior.`;break;case`implementation`:instruction=direct+` Implement the requested work, including any explicitly requested planning changes within your role's authority. `+`For a plan's explicitly authorised removal or deferral, record the exact deferred requirement and its agreed timing in a Deferred work section of paired Progress before removing it from Plan's current acceptance scope. Preserve completed implementation evidence and do not perform deferred work. Reassess the remaining requirements against that evidence; if none remain to implement, hand off for review rather than treating the scope edit as planning-only. Junior still cannot edit Plan scope. `+`Continue until the authorised scope is implemented and checked. Task size, context compaction, or finishing one useful slice is not a reason to end the task. `+`Stop for an unresolved architectural or product decision outside the agreed scope only where it blocks the remaining work; continue independent authorised work. `+`The latest execution request supersedes earlier planning-only wording, while explicit remaining approval boundaries still apply. `+`If work remains, lead with Implementation incomplete and name the exact blocker and unfinished scope; never open with Done for partial implementation. `+`A separate Senior turn will review the result, even when you are Senior. `+`Leave the plan active for that review; do not mark it completed in this implementation turn or request permission for the automatic review.`}if(!planInstructions&&intent!==`conversation`)planInstructions=`This direct request is independent of the current Auto plan unless the user explicitly refers to it. Senior may use vibe64-helper plan to manage it; Junior may update Progress and existing checklist ticks after reading both documents, never change scope or mark the plan completed.`;if(intent!==`conversation`&&intent!==`planning`&&intent!==`deslop`&&intent!==`ui_pass`&&intent!==`review`&&mode!==`review`&&mode!==`deslop`&&mode!==`ui_pass`){instruction+=` When the requested feature is implemented, its required runtime resources are prepared and Preview is responding, promptly tell the user: Ready to try—give it a spin. Verification is still running. Do not claim full completion before verification, and do not wait for the user to test before continuing your checks. If Preview is unavailable, report that instead of inviting the user to try it.`;instruction+=browserReview?` A separate Senior review owns in-depth browser testing and visual inspection. Do not run those checks in this implementation turn. Run relevant focused code tests and basic smoke checks: confirm server startup, relevant routes and API responses, and if needed make a brief managed-browser check that the changed page renders and its main control is present. Leave full end-to-end browser suites, multi-step user journeys and visual inspection to Senior; do not expand the smoke check into those checks. Prepare the app and report exact checks, remaining gaps and browser acceptance cases to Senior; browser verification pending is an expected handoff, not an implementation blocker. Tell the user that Senior will perform the remaining browser checks.`:` You own the remaining verification, including relevant browser checks and visual inspection using the supplied tools. Tell the user those checks are next, keep the app usable during checking and report anything unverified if checking is interrupted or unavailable.`}return`[Vibe64 role: ${assistantModeLabel(mode)}. Applies only to this request; earlier per-turn mode instructions no longer apply.]\n${instruction}${planInstructions?`\n${planInstructions}`:``}\n\n${message}`}function assistantGoalObjective(objective,pinned){if(pinned?.objective&&[`custom`,`senior`,`junior`].some(mode=>objective===assistantModePrompt(mode,pinned.objective)))return pinned.objective;return objective}function assistantGoalManagementMessage(message,turn={}){if(!message||message.receipt===false||turn.user?.receipt===false||turn.optimistic&&turn.optimistic.status!==`accepted`||turn.system?.delivery)return false;const native=message.data?.native;if(!(turn.metadata?.engineId===`claude`||turn.metadata?.assistantSelection?.engineId===`claude`||native?.engineId===`claude`))return false;const text=String(message.text||``);if(message.role===`user`)return Boolean(turn.metadata?.upstreamMessageId||message.receipt===true)&&/^\/goal(?:\s|$)/u.test(text);if(![`assistant`,`commentary`].includes(message.role))return false;if(native?.command)return native.engineId===`claude`&&([`assistant`,`result`].includes(native.type)||native.type===`system`&&[`local_command`,`local_command_output`].includes(native.subtype))&&native.command===`goal`&&native.output===`stdout`;const prefix=[`Goal set: `,`Goal cleared: `,`Goal active: `].find(value=>text.startsWith(value));if(prefix){const objective=text.slice(prefix.length);const separator=objective.indexOf(`
2
-
3
- `);if(separator!==-1&&assistantGoalObjective(objective,{objective:objective.slice(separator+2)})!==objective)return true}return native?.type===`system`&&native.subtype===`local_command_output`&&Boolean(prefix||text===`No goal set`||text==="No goal set. Usage: `/goal <condition>`")}function assistantRoutingOutcomeNotice(request){if(!request?.messageId||!request.outcome||request.stopped)return null;const auto=request.mode===`auto`;let handoff=auto?`Returning to Junior for rework.`:`Returning to implementation for rework.`;if(request.status===`complete`)handoff=`Work finished.`;else if(request.stage===`review`)handoff=auto?`Ready for Senior review.`:`Ready for review.`;const headings={continue:`Continuing work.`,handoff,wait:`Waiting to continue.`,complete:request.stage===`review`?`Review complete.`:`Finished.`};return{messageId:`assistant-routing-outcome:${request.messageId}:${request.outcome.turnId}:${request.outcome.decision}`,text:`${headings[request.outcome.decision]}\n\n${request.outcome.explanation}`}}function assistantRoutingStatusLabel(request){if(!request)return``;const selection=request.assignments?.[assistantWorkflowRole(request)];const recipient=selection?vibe64AssistantSelectionLabel(selection):``;const stage=(request.mode===`auto`||request.stage===`review`)&&{planning:`Planning`,implementation:`Implementing`,review:`Reviewing`}[request.stage]||assistantModeLabel(request.resolvedMode);if(request.delivery===`uncertain`)return`Delivery unconfirmed · ${recipient}`;if(request.status===`waiting`)return request.stopped?`Paused at your request.`:`${stage} waiting · ${recipient}`;if(request.status===`complete`){if(!request.workflow)return`Reply finished.`;if(request.stage===`review`)return`Review complete — read the findings above.`;return request.outcome?.decision===`handoff`?`Work finished.`:`Reply finished.`}if(request.delivery===`routing`)return`Choosing the recipient with Router…`;if(request.delivery===`failed`)return`Request not sent`;if(request.delivery===`pending`)return`${stage} ready to continue · ${recipient}`;if(request.delivery===`sending`)return`${stage} · ${recipient} · awaiting receipt…`;return`${stage} · ${recipient}`}var __testables=Object.freeze({MAIN_CHAT_PURPOSES});export{assistantRoutingStatusIsPending as _,ASSISTANT_ROLE_PURPOSES as a,ASSISTANT_FINISHING_DEFAULTS as b,assistantGoalManagementMessage as c,assistantRoutingAutomation as d,assistantRoutingFromMetadata as f,assistantRoutingRequestIsUnresolved as g,assistantRoutingRequestForDisplay as h,ASSISTANT_ROLE_DEFAULT_FOLLOWS as i,assistantGoalObjective as l,assistantRoutingRequestCanBeReplaced as m,ASSISTANT_FOLLOWING_ROLES as n,ASSISTANT_ROUTING_ROLE_DEFINITIONS as o,assistantRoutingOutcomeNotice as p,ASSISTANT_MODES as r,ASSISTANT_SETUP_ROLES as s,ASSISTANT_FIX_MODE as t,assistantModeLabel as u,assistantRoutingStatusLabel as v,ASSISTANT_FINISHING_STEPS as x,assistantSetupRoleValue as y};
@@ -1 +0,0 @@
1
- import{d as resolveFieldErrors,l as isGenericHttpErrorMessage}from"./httpClient-Bwitq9Xf.js";import{r as useJskitText}from"./i18n-BuXRXGaO.js";import"./i18n-BkxO7BMl.js";var{t,text,serverMessage,fieldErrorMessages}=useJskitText();function toUiErrorMessage(error,fallbackMessage=``,defaultMessage=``){const normalizedFallback=text(fallbackMessage).trim();const normalizedMessage=String(error?.message||``).trim();if(normalizedMessage&&!isGenericHttpErrorMessage(error))return serverMessage(error).trim();if(normalizedFallback)return normalizedFallback;if(normalizedMessage)return serverMessage(error).trim();return text(defaultMessage).trim()||t(`jskit.http.feedback.requestFailed`)}function toQueryErrorMessage(error,fallbackMessage=``,defaultMessage=``){return error?toUiErrorMessage(error,fallbackMessage,defaultMessage):``}function toUiFieldErrors(error){return fieldErrorMessages({fieldErrors:resolveFieldErrors(error),fieldErrorCodes:error?.fieldErrorCodes||error?.details?.fieldErrorCodes})}export{toUiErrorMessage as n,toUiFieldErrors as r,toQueryErrorMessage as t};
@@ -1,2 +0,0 @@
1
- import{Tt as toValue,gt as reactive,it as watch,mt as onScopeDispose,u as computed,ut as getCurrentScope,vt as ref}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import"./client-4uCr4dYG.js";import{r as useJskitText,t as registerJskitMessages}from"./i18n-BuXRXGaO.js";var jskit=JSON.parse(`{"assistant":{"api":{"requestFailed":"Assistant request failed."},"attachments":{"announcement":{"cancelled":"{count} attachment cancelled. | {count} attachments cancelled.","inProgress":"{count} attachment is in progress. | {count} attachments are in progress.","needAttention":"{count} attachment needs attention. | {count} attachments need attention.","ready":"{count} attachment ready. | {count} attachments ready."},"attached":"Attached files","bytes":"{sent} / {size}","bytesPercent":"{sent} / {size} · {percent}%","cancelItem":"Cancel {name}","close":"Close","download":"Download","error":{"cleanupFailed":"Attachment cleanup failed.","localFilePaste":"Copied local files cannot be pasted from this browser. Drop the file or use Attach files.","noFile":"The prepared attachment did not produce a file.","preparationFailed":"Attachment preparation failed.","tooLarge":"{fileName} is larger than the {limit} attachment limit.","tooMany":"A message can keep at most {count} attachments.","unusable":"Uploaded attachment could not be used.","uploadFailed":"Attachment upload failed."},"limit":"{count} / {max}","preparingName":"Preparing attachment…","previewUnavailable":"Preview is unavailable for this file. You can download it below.","queue":"Message attachments","removeItem":"Remove {name}","retryItem":"Retry {name}","sizeBytes":"{size} B","sizeKilobytes":"{size} KB","sizeMebibytes":"{size} MiB","sizeMegabytes":"{size} MB","status":{"cancelled":"Cancelled","delivering":"Sending to Codex","preparationFailed":"Preparation failed","preparing":"Preparing","queued":"Queued","ready":"Ready","sendingFailed":"Sending failed","uploadFailed":"Upload failed","uploading":"Uploading"},"summary":{"cancelled":"{completed} ready · {cancelled} cancelled","inProgress":"{completed} of {total} ready · in progress","needAttention":"{completed} of {total} ready · {count} needs attention | {completed} of {total} ready · {count} need attention","percent":"{completed} of {total} ready · {percent}%","ready":"{completed} of {total} ready"},"unnamed":"attachment","uploadProgress":"Upload progress for {name}"},"chat":{"attachFiles":"Attach files","avatar":"Conversation avatar","discardUnsent":"Discard unsent message","editUnsent":"Edit unsent message","label":"Assistant conversation","messageAssistant":"Message AI assistant","minimiseAvatar":"Minimise avatar","reviewAttachedFiles":"Please review the attached files.","sendingToAssistant":"Sending to assistant…","showAvatar":"Show avatar","working":"Assistant is working…"},"composer":{"cannotSendYet":"Your words are in the chat box, but this conversation cannot send yet.","chatChanged":"The chat changed before sending. Review the draft before sending.","notReady":"The chat composer is not ready yet.","send":"Send","sendMessage":"Send message","sending":"Sending…","stop":"Stop","stopping":"Stopping…","suggestedPrompts":"Suggested prompts","suggestionsAvailable":"{count} suggested prompts are available before the message controls.","thinkingOfIdeas":"Thinking of a few ideas","thinkingOfIdeasStatus":"Thinking of a few ideas.","useSuggestion":"Use suggestion: {prompt}"},"delivery":{"cancelling":"Cancelling…","cancelUnreachable":"Couldn't reach the server — Cancel again","checkBeforeResend":"Check delivery before resending.","checkPrevious":"Check the previous message's delivery before sending again.","checking":"Checking…","notConfirmed":"Message delivery is not confirmed.","notSent":"Message could not be sent.","retry":"Retry","retryCheck":"Retry delivery check","unconfirmed":"Delivery could not be confirmed.","unconfirmedShort":"Delivery unconfirmed."},"goal":{"blocked":"Goal blocked","budgetLimited":"Goal budget reached","cancel":"Cancel goal","cancelInterruptsTurn":"Cancel stops the current turn and clears the goal.","cancelRemovesGoal":"Cancel removes this goal. Use Stop to interrupt a turn already running.","cancelling":"Cancelling…","complete":"Goal complete","elapsed":"{label}: {elapsed}","goal":"Goal","loading":"Loading goal…","notRunning":"Goal not running","notRunningHint":"Nothing is working on this goal right now. Your next message continues it.","objective":"Goal objective","outOfCredit":"Out of credit: top up or switch AI account","pause":"Pause goal","pauseInterruptsTurn":"Pause stops the current turn and keeps the goal for later.","pausePreventsTurns":"Pausing prevents further automatic turns. Use Stop to interrupt the current turn.","paused":"Goal paused","pausing":"Pausing…","resume":"Resume goal","resuming":"Resuming…","running":"Goal running","runningTime":"Running time","set":"Set goal","start":"Start goal","starting":"Starting…","tokenBudget":"Token budget (optional)","unavailable":"Goal unavailable","usageLimited":"Waiting: AI usage limit","usageLimitedHint":"The goal does not continue by itself. Choose Resume goal once the AI account can work again.","usageLimitedUntil":"Waiting: AI usage limit, resets at {time}"},"longText":{"details":"Details","table":"Table"},"model":{"apply":"Apply","applying":"Applying…","chooseAi":"Choose AI","chooseModel":"Choose model","controls":"AI controls","loading":"Loading available AIs","model":"Model","noMatchingModels":"No matching models","noModels":"No available models.","noneConfigured":"No configured AIs are available for this session.","provider":"Provider","selector":"AI session selector","thinking":"Thinking","tryAgain":"Try again","viewOnly":"AI choices are view-only while the assistant is working.","waitBeforeChanging":"Wait for the active turn to finish before changing models."},"progress":{"hide":"Hide progress updates","showAll":"Show all {count} progress update | Show all {count} progress updates","showLatest":"Show latest {count} progress update | Show latest {count} progress updates"},"questions":{"answerNormally":"Answer normally instead","answerRequired":"Answer question {number}.","fieldLabel":"[{number}] {label}","label":"Assistant questions","suggestedAnswers":"Suggested answers"},"settings":{"readOnly":"Read-only","systemPromptTooLong":"Assistant system prompt must be at most {max} characters.","systemPromptInvalid":"Assistant system prompt must be valid text."},"transcript":{"assistant":"Assistant","cancel":"Cancel","edit":"Edit","failed":"Failed: {error}","history":"Conversation history","loadOlder":"Load older messages","loading":"Loading conversation","loadingOlder":"Loading older messages…","messages":"Conversation messages","pending":"Pending","pendingReason":"Pending: {reason}","preparing":"Preparing conversation","progress":"{name} progress","readMore":"Read more","recommended":" · Recommended","reload":"Reload chat","reloading":"Reloading chat","reloadingShort":"Reloading…","reviewMessage":"Review your message","showLess":"Show less","status":"Status"},"turn":{"failed":"Assistant stopped with an error.","stopped":"Stopped.","invalidResponse":"The assistant returned an invalid response.","requestIncomplete":"The assistant could not complete this request."},"conversation":{"handleClosed":"This conversation handle is closed.","handleDisposed":"This conversation handle is disposed.","runtimeClosed":"This conversation runtime is closed.","pagedHistoryUnsupported":"This conversation does not supply paged history.","completedEnvelopesNeedNativeOwner":"Completed envelopes require a runtime-owned native conversation.","completedEnvelopesNotOwned":"This conversation does not own completed envelopes.","goalAttachmentContentUnsupported":"Native goals require extracted text or supported image bytes for attachments.","originalSendOnly":"This conversation supports its original application Send operation.","attachmentIdsOnly":"Supply attachmentIds; only the application's resolver can supply file content.","attachmentsNotConfigured":"File attachments are not configured for this conversation.","steeringUnsupported":"This connection does not support steering.","goalsUnsupported":"This connection does not support native goals.","goalTokenBudgetsUnsupported":"This connection does not support goal token budgets.","goalCommandUnsupported":"This connection does not support that goal command.","goalAttachmentsUnsupported":"This engine's native goal commands do not accept attachments.","completedEnvelopesNeedNativeEngine":"Completed envelopes require a native engine.","replacementPolicyRetained":"This conversation retains its original replacement policy.","selectedProfileRetained":"This scoped conversation retains its original selected profile.","hostSelectionRequired":"This host requires its authorized assistant selection operation.","liveSettingsUnsupported":"This provider does not support live native settings.","completedEnvelopesNeedStorage":"Completed envelopes require runtime-owned canonical storage.","originalReadOnly":"This conversation uses its original read and subscription operations.","messageCancelUnsupported":"This conversation cannot cancel one message.","messageCancelled":"This message was cancelled. Send it again as a new message.","authorizedSelectionRequired":"Use the conversation's authorized selection operation.","eventDeliveryRetained":"This scoped conversation retains its original event delivery.","engineChanged":"The selected native engine changed.","useReplaceForEngine":"Use replace() to change this conversation's engine.","rewindInspectionBeforeOpen":"This conversation has an unfinished Undo operation from an earlier runtime. Inspect its saved native and local history offline before opening it; no history was changed.","rewindInspectionBeforeReplace":"This conversation has an unfinished Undo operation from an earlier runtime. Inspect its saved native and local history offline before replacing it; no history was changed.","responseOwnerChanged":"The completed response owner changed.","newerResponseOwnsWorker":"A newer completed response owns this worker.","responseIdentityChanged":"The completed response identity changed.","applicationToolMessageStale":"This application tool's admitted message is no longer current.","nativeCompletionMessageStale":"This native completion's admitted message is no longer current.","toolObservationRetired":"The native tool observation belongs to a retired response.","toolObservationReceiptLost":"The native tool observation lost its exact admitted receipt.","waitForNativeResponse":"Wait for the native response to finish.","waitForAnswer":"Wait for this answer or use steer to send another instruction.","waitForTurnSaving":"Wait for the current turn to finish saving before starting the goal.","waitForInstructionAdmission":"Wait for the pending instruction to be admitted before steering again.","waitForGoalCommand":"Wait for the goal command to be admitted.","waitForSubmission":"Wait for the current submission before checking delivery.","stopBeforeReplace":"Stop the current turn before replacing its native conversation.","stopBeforeSettings":"Stop the current turn before changing its settings.","completedResponseNoReceipt":"The completed response has no current verified receipt.","completedResponseNoTurnReceipt":"The completed response has no exact native turn receipt.","completedClaudeNoToolEvidence":"The completed Claude response has no native tool-attempt evidence.","responseAssociationUnverified":"The native owner could not verify this response association.","responseOtherOperation":"This response already belongs to a different application operation.","completedResponseNoPlainReply":"This completed response does not own a plain reply.","completedReplyNoTarget":"The completed reply has no current plain authored target.","publishedReplyChanged":"The published reply target or text changed.","replyTargetUsed":"This plain reply target already has unassociated content or consumption.","operationResponseIdentity":"The operation has a different completed response identity.","plainReplyPublished":"This completed response already published its plain reply.","savedOperationChanged":"The saved response operation changed.","turnFinishedBeforeSend":"The native turn finished before this instruction was sent. Send it as a new message.","noActiveTurnToSteer":"There is no active native turn to steer. Send a new message.","briefingBeforeTerminal":"Send a chat message to deliver the saved continuity briefing before starting a native terminal or goal.","briefingBeforeGoal":"Send a message to catch this AI up before starting or resuming its goal.","briefingBeforeReplacement":"Deliver the previous replacement's briefing before replacing native history again.","historyExclusionsInvalid":"Native history exclusions require a server-owned completed application wake and exact message IDs.","messageContentRequired":"Bounded text or attachment IDs and a stable messageId are required.","steerNotBoolean":"steer must be a boolean.","applicationDataInvalid":"Application data must be a JSON object within the conversation input limit.","goalMessageIdRequired":"A stable messageId is required for this goal command.","goalConversationChanged":"The conversation changed before this goal command was sent.","goalNeedsNativeConversation":"This command requires an existing native conversation.","messageIdExclusionsConflict":"This messageId already belongs to different native history exclusions.","messageIdContentConflict":"This messageId already belongs to different content.","completedClaudeNotSteerable":"Completed Claude responses cannot share a native steering turn. Wait for the response or stop it.","replacementPendingBeforeSend":"Finish the pending native replacement before sending another message.","replacementPendingBeforeRecovery":"Finish the native replacement before recovering output.","replacementUnfinished":"Retry the unfinished native replacement before starting another one.","replacementPendingBeforeSettings":"Finish the pending native replacement before changing settings.","retainedDeliveryUncertain":"This message has uncertain delivery in a retained conversation. Select that engine and check its receipt before submitting it again.","previousInstructionUnchecked":"Check delivery of the previous instruction before preparing another completed response.","previousSubmissionUncertain":"The previous submission has uncertain delivery. It will not be resent automatically.","goalCommandDeliveryUncertain":"Check the uncertain command's delivery before changing the goal.","earlierGoalCommandUnresolved":"A goal command from an earlier runtime has unresolved delivery. Inspect its saved state before changing the goal.","pendingDeliveryBeforeReplace":"Resolve pending delivery before replacing native history. Another engine may be selected while its receipt stays pending.","deliveryUncertainBeforeSettings":"Resolve uncertain delivery before changing settings.","goalActionRequired":"A goal action and current conversation segment are required.","goalObjectiveInvalid":"A bounded objective and optional positive token budget are required.","goalToResumeRequired":"Select the goal to resume.","goalToStopRequired":"Select the goal to stop.","replacementRequestInvalid":"Replacement needs an operationId, exact predecessor segment, and an engine-change, model-change or renewal reason.","replacementBriefingRequired":"Native replacement requires a continuity briefing.","predecessorChanged":"The native predecessor has changed. Read the conversation before replacing it.","replacementOperationConflict":"This replacement operationId already belongs to another request.","replacementChangedBeforeWrite":"The saved replacement changed before it could be written.","replacementChangedBeforeRelease":"The saved replacement changed before its binding was released.","predecessorChangedBeforeRelease":"The native predecessor identity changed before its binding was released.","predecessorIncomplete":"The native predecessor identity changed or is incomplete.","hostScopeMismatch":"This open conversation already belongs to another host scope. Dispose its handle before reopening it on the original host.","cleanupNeedsOriginalConversation":"Native cleanup requires its original bound conversation.","deliveryUnconfirmed":"Native delivery could not be confirmed.","messageNotSent":"This message was not sent. Review it before sending a new message.","attachmentIdsInvalid":"Attachments require at most {max} distinct, nonempty attachment IDs.","attachmentResolverIncomplete":"The attachment resolver must return a receipt for every requested file and bounded model content.","attachmentLocalFilesUnsupported":"This engine cannot accept local attachment files. Supply extracted text or supported image bytes.","attachmentReceiptInvalid":"Attachment receipts require the requested ID, a bounded fileName and a nonnegative size.","attachmentLocalFileInvalid":"Local attachment files require their exact requested receipt and an authorized absolute native path.","attachmentFormatUnsupported":"This engine cannot accept that attachment format. Supply extracted text or a supported image.","attachmentTextEmpty":"Attachment text must be nonempty.","attachmentBytesRequired":"Attachments require authorized bytes and a supported media type; remote URLs and paths are not accepted.","attachmentBytesExceeded":"Attachment content exceeds the configured byte limit for this request.","replacementRetryMismatch":"Replacement retry does not match the saved operation.","previousReplacementUnfinished":"Finish the previous native conversation replacement first.","previousReleaseUndoUnfinished":"An unfinished conversation Undo from a previous release blocks assistant work. Complete it using the previous release before upgrading.","pendingDeliveryBeforeContextReplace":"Finish pending delivery before replacing native context.","shutdownUnconfirmed":"Native conversation shutdown was not confirmed.","submissionInterrupted":"The previous submission was interrupted. Check delivery before submitting it again.","restartInterrupted":"The application restarted before this answer completed. The request was not replayed.","copiedInterrupted":"Copied into a stopped development environment. This request was not replayed.","operationResultUnsaved":"The application operation result could not be saved. Restore storage access and retry saving.","progressUnsaved":"Conversation progress could not be saved. Restore access to its storage before continuing.","requestTimedOut":"The conversation request exceeded its time limit.","workStopped":"Work stopped.","stoppedByUser":"Stopped by user.","apiHistoryLimit":"This conversation exceeds the configured API history limit. Start another conversation or increase the limit.","outputTokenLimit":"The model reached its output token limit before completing the answer. Increase maxOutputTokens in the conversation limits.","toolCallsUnconfirmed":"The model stream ended without confirming its application tool calls.","answerUnconfirmed":"The model stream ended without confirming a completed answer.","toolProgressLimit":"Application tool progress text exceeds the configured API limit.","finalReplyLimit":"The assistant exceeded the configured final reply limit.","historyBudgetExceeded":"Conversation updates exceed the configured history budget. Renew the context with a continuity briefing before continuing.","briefingBudgetExceeded":"The continuity briefing exceeds the configured history budget.","contextChangedInstallingPrompt":"Conversation context changed while installing its system prompt. Retry before sending.","contextChangedReadingInstructions":"Conversation context changed while reading instructions. Retry before sending.","messageNotAcknowledged":"The engine did not acknowledge the message.","stopTemporaryBeforeChange":"Stop this temporary conversation before changing its AI.","toolArgumentsTooLarge":"The application tool arguments exceed their size limit.","toolCallLimit":"The assistant reached the application tool-call limit for this turn."},"claude":{"goalChanged":"The Claude goal changed. Refresh before trying again.","goalTokenBudgetUnsupported":"Claude goals do not support a token budget.","goalBlockerReasonRequired":"An active Claude goal needs a blocker reason of up to 1,000 characters.","goalConditionRequired":"Enter a goal condition of up to 4,000 characters.","goalAlreadySet":"Cancel the existing goal before setting another.","goalActionUnknown":"Unknown Claude goal action.","compactWhileWorking":"Claude is still working. Wait for it to finish before freeing its context.","noActiveTurn":"Claude has no active turn for this message.","steeringUnavailable":"This Claude turn cannot accept steering now.","settingsChangeWhileWorking":"Stop the current Claude turn before changing its settings.","notConnected":"Claude Code is not connected.","accountStatusInvalid":"Claude Code returned an invalid account status.","accountChangedRefreshModels":"The signed-in Claude account changed. Refresh the model list.","accountQueryCancelled":"Claude account query was cancelled for reconnection.","accountQueryCleanupUnconfirmed":"Claude account query process cleanup could not be confirmed.","answerInterrupted":"Claude interrupted this answer.","chooseConnectedModel":"Choose a connected Claude Code model.","closedOrWorking":"This Claude conversation is closed or already working.","connectionClosed":"Claude connection is closed.","connectionWasClosed":"Claude connection was closed.","controlNeedsTerminal":"This control request requires the native Claude Code terminal.","eventConnectionEnded":"Claude event connection ended unexpectedly.","exitedUnexpectedly":"Claude exited unexpectedly.","modelUnsupported":"This exact provider/model is not supported by the Claude integration. Choose a supported model without renaming it.","noTurnToSteer":"Claude has no active turn to steer.","otherHostConfiguration":"This Claude conversation belongs to another working directory or credential home. Restore its original host configuration.","reasoningEffortUnsupported":"The selected Claude model does not support this reasoning effort.","reconnecting":"Claude is reconnecting.","sendNowUnsupported":"This Claude version does not support targeted Send now.","signInRequired":"Sign in with claude auth login before using this conversation.","stopBeforeReset":"Stop Claude before resetting its turn view.","toolCallLimit":"Claude exceeded the application tool-call limit.","turnStillWorking":"This Claude turn is still working.","workEnded":"Claude work ended.","outputTooLarge":"Claude output exceeded its size limit."},"codex":{"helperThreadUnavailable":"This low-cost assistant thread is no longer available. Start the background task again instead of reusing another assistant conversation.","helperOwnershipBlocked":"{applicationName} could not prove ownership of a persisted low-cost assistant thread.","threadDeleteUnavailable":"Codex app-server thread deletion is not available.","goalActionInvalid":"Choose set, pause, resume, or cancel.","goalObjectiveInvalid":"Enter a goal objective and an optional positive whole-number token budget.","goalConversationChanged":"The Codex conversation changed. Refresh the goal before trying again.","goalConversationStopped":"Resume or send a message to restore the stopped conversation before setting a goal.","goalChangedBeforeSet":"The Codex goal changed. Refresh it before setting a new goal.","goalChanged":"The Codex goal changed. Refresh it before trying again.","goalAlreadyStopped":"This goal is already stopped. Refresh its details.","goalStopUnconfirmed":"Codex has not yet confirmed a stop. Retry after the service has stopped.","goalNotResumable":"This goal cannot be resumed from its current status. Refresh its details.","stopUnverified":"Codex's stop could not be verified. Its runtime owner is unavailable.","turnNotReady":"The active assistant turn is not ready to accept this message yet.","messageEmpty":"Codex message is empty.","messageInputEmpty":"Codex message input is empty.","operationNotSteerable":"The active assistant operation cannot accept messages yet.","temporaryConversationBusy":"Temporary AI is already working on this conversation.","accountChangedSendAgain":"Codex (OpenAI) changed account. Send your message again.","accountUnavailable":"The selected Codex account is unavailable. Reconnect Codex and retry.","assistantChangedRefresh":"The assistant changed. Refresh before resuming.","authChangedReopen":"Codex authentication changed. Reopen the conversation with its original account.","authModeUnsupported":"The selected Codex authentication mode is unsupported. Reconnect Codex and retry.","authRecordInvalid":"The selected Codex authentication record is invalid. Reconnect Codex and retry.","authRecordTooLarge":"The selected Codex authentication record is too large. Reconnect Codex and retry.","authRecordUnreadable":"The selected Codex authentication record could not be read. Reconnect Codex and retry.","authorizedSettingsRequired":"Codex requires current authorized settings before resuming this conversation.","connectionClosedBeforeSettings":"The assistant connection closed before confirming its settings.","connectionUnverified":"The assistant connection could not be verified. Your conversation and files are preserved. Retry the connection, or renew the session to continue in a fresh conversation.","credentialsUnreadable":"Codex credential data could not be read. Restore its account configuration.","ephemeralInstructionsFixed":"Start a new ephemeral conversation to change its instructions.","goalPauseUnconfirmed":"Codex did not confirm that the same goal was paused.","goalsAreControls":"Codex goals are controls. Inspect any unresolved goal-message record before continuing.","helperAccessTokenStale":"The selected Codex account has not produced a newer access token yet. Reconnect Codex and retry.","helperAccountActivationFailed":"Codex could not activate the selected account for isolated helper work. Reconnect Codex and retry.","helperAccountChanged":"The selected Codex account changed during helper work. Retry the task with the current account.","helperAccountChangedBeforeRun":"The selected Codex account changed before low-cost assistant work could run. Retry the task with the current account.","helperAccountChangedStarting":"The selected Codex account changed while helper execution was starting. Retry the task.","helperAccountIdentityInvalid":"The requested low-cost assistant account identity is invalid. Refresh the task and retry.","helperAuthRefreshRejected":"Codex helper authentication refresh was rejected. Reconnect Codex and retry.","helperAuthUnavailable":"Codex helper authentication is unavailable. Reconnect Codex and retry.","helperExecutionFailed":"Codex isolated helper execution failed. Retry the task.","helperThreadReconnectAccount":"Reconnect the original Codex account to resume or delete this helper thread.","historyFormatStartFresh":"This conversation uses an unsupported Codex history format. Start a fresh conversation.","historyFormatUnsupported":"This conversation uses an unsupported Codex history format. Renew the session to keep your files and saved chat and start a fresh conversation. You can write the handover yourself.","loadedThreadsInvalid":"Codex returned an invalid loaded-thread inventory. Restore its connection before retrying.","modelDiscoveryUnavailable":"Codex live model discovery is unavailable.","modelUnsupported":"This exact provider/model is not supported by the Codex integration. Choose a supported model without renaming it.","nativeGoalChanged":"The native goal changed. Read it again before changing it.","observationLostStopUnverified":"Codex observation was lost and a stop is not yet verified. Retry after the service has stopped.","oldThreadUnreadable":"The old assistant thread cannot be read. Write or edit the handover manually instead.","otherAccount":"This conversation belongs to another Codex account. Restore that account or start a new conversation.","otherHostConfiguration":"This Codex conversation belongs to another working directory or credential home. Restore its original host configuration.","otherProviderAccount":"This conversation belongs to another Codex provider account. Restore that connection or start a new conversation.","outputTooLarge":"Codex output exceeded the configured limit.","paginatedConversationHistoryMissing":"Codex did not create the required paginated conversation history. Update Codex before starting a conversation.","paginatedHistoryMissing":"Codex did not create the required paginated history. Update Codex before starting this conversation.","reasoningEffortUnsupported":"The selected Codex model does not support this reasoning effort.","reconnectOpenAi":"Reconnect the OpenAI account before using this model.","responseTimeout":"Timed out waiting for Codex app-server response.","signInRequired":"Sign in with codex login before using this conversation.","stillReconnecting":"Codex is still reconnecting: its shared runtime is busy starting or stopping. Please try again shortly.","stoppedUseResume":"Codex is stopped. Use Resume or Send to continue.","temporaryConnectionLost":"Connection to Codex was lost while the temporary AI was working.","temporaryConversationClosed":"Temporary AI conversation was closed.","temporaryTurnStopped":"Temporary AI turn was stopped.","threadInventoryUntrusted":"Codex returned an untrustworthy thread/provider inventory. Restore its connection before changing credentials.","toolEntryPointsChanged":"This Codex conversation was created with different application tool entry points. Start a new conversation to enable or remove application tools.","turnStopUnconfirmed":"Codex did not confirm that its turn stopped."},"provider":{"notConfigured":"Assistant provider is not configured.","requestFailed":"Assistant provider request failed.","requestRejected":"Request failed."},"stream":{"failed":"Assistant stream failed.","requestFailed":"Request failed."},"opencode":{"cleanupUnconfirmed":"OpenCode process cleanup could not be confirmed. Restore its execution host before continuing.","closedOrWorking":"This OpenCode conversation is closed or already working.","messageNotAcknowledged":"OpenCode did not acknowledge the message.","modelDefinitionUnavailable":"OpenCode could not load the configured model definition. Check the selected integration before sending.","nativeStillWorking":"The native OpenCode conversation is still working. Stop or inspect it before sending another message.","noTurnToSteer":"OpenCode has no active turn to steer.","otherAccount":"This conversation belongs to another OpenCode account. Restore that connection or start a new conversation.","otherHistoryStore":"This OpenCode conversation belongs to another native history store. Restore its original host configuration.","otherHistoryStoreOrRuntime":"This OpenCode conversation belongs to another native history store or runtime. Restore its original host configuration.","otherWorkingDirectory":"This OpenCode conversation belongs to another working directory or native state directory. Restore its original host configuration.","reasoningEffortUnsupported":"The selected OpenCode model does not support this reasoning effort.","reopenTerminalToAttach":"Reopen the OpenCode terminal before attaching files.","savedConversationUnavailable":"The saved OpenCode conversation is unavailable. Restore its native history before continuing.","turnFailed":"OpenCode turn failed.","turnUnreadable":"The exact OpenCode turn did not produce a readable result.","turnNotFinished":"OpenCode did not finish the turn."}},"errors":{"conversation_forbidden":"This conversation is not available to this identity.","conversation_storage_version":"This conversation needs its offline runtime-state upgrade before it can be opened. Its saved requests were not replayed or changed.","conversation_configuration_mismatch":"Use configure() to change a saved conversation's settings.","conversation_goal_stopped":"The goal command was stopped before delivery.","conversation_attachment_manifest_changed":"Authorized attachment paths changed after this instruction was prepared. Restore the original files or send a new message.","conversation_receipt_unavailable":"The native receipt has no stored authored message.","conversation_goal_unavailable":"The native goal is unavailable. Try reading its status again.","assistant_provider_invalid_response":"Assistant provider returned an invalid response payload.","assistant_opencode_conversation_busy":"This conversation is still working.","assistant_opencode_key_verification_failed":"OpenCode rejected the API-key verification request.","assistant_opencode_turn_thread_mismatch":"The OpenCode predecessor history changed before handover generation.","assistant_opencode_turn_fresh_thread_required":"The renewed OpenCode conversation does not own the expected fresh native history.","assistant_opencode_turn_unrelated_history":"The successor OpenCode history contains unrelated conversation and cannot be used for renewal.","conversation_claude_turn_timeout":"Claude did not finish within the time limit.","conversation_claude_renewal_history_mismatch":"The Claude renewal conversation does not match the expected native history.","conversation_claude_renewal_unrelated_history":"The successor Claude conversation already contains unrelated messages.","conversation_claude_renewal_turn_active":"Stop the current turn before renewing this conversation.","conversation_claude_unavailable":"This Claude conversation is unavailable.","conversation_claude_retained_goal_invalid":"The retained Claude goal is invalid. Restore its saved conversation state.","conversation_claude_retained_goal_conflict":"The saved Claude goal cannot be both paused and blocked.","conversation_claude_session_closing":"This session is closing.","conversation_claude_preparation_stopped":"Claude preparation was stopped while this session was closing or changing.","conversation_claude_terminal_turn_active":"Stop the current turn before opening the Claude Code terminal.","conversation_claude_still_working":"This conversation is still working.","conversation_claude_history_retire_busy":"Stop the saved Claude process and its terminal before retiring native history.","conversation_claude_message_required":"Enter a message for Claude.","conversation_claude_command_stopped":"The goal command was stopped before delivery.","conversation_claude_context_usage_unavailable":"Claude's current context usage is unavailable.","conversation_claude_goal_clear_unconfirmed":"Claude has not saved the retained goal's native clear receipt.","conversation_claude_saved_state_unreadable":"The saved Claude conversation {conversationId} is unreadable. Restore its saved conversation state.","conversation_tool_not_executed":"Execution stopped before the action began.","conversation_tool_outcome_unknown":"The application operation did not return a verified result. Inspect its target before requesting another execution.","conversation_unsupported":"This original scoped conversation has no canonical message or goal receipt.","assistant_claude_goal_attachment_pending":"Claude accepted the goal command, but its goal attachment is not available yet. Check its original receipt before trying again.","assistant_claude_admission_unknown":"Claude has not acknowledged this prompt. Its delivery is uncertain.","assistant_claude_startup_exited":"Claude exited before initialization completed.","claude_stop_unconfirmed":"Claude process cleanup could not be confirmed. Restore its execution host before continuing.","claude_account_changed":"This conversation belongs to another Claude account. Reconnect that account or start a new session.","assistant_opencode_recovery_order_unconfirmed":"OpenCode could not confirm that the new input follows its final-answer recovery. The admitted message was not resent.","assistant_opencode_interrupt_unconfirmed":"OpenCode did not confirm Stop. Try Stop again.","assistant_opencode_interrupt_timeout":"OpenCode did not confirm Stop within 5 seconds. Try Stop again.","assistant_opencode_key_verification_unavailable":"OpenCode API-key verification could not run.","assistant_opencode_stop_unverified":"OpenCode process exit could not be verified.","assistant_opencode_connection_reload_failed":"OpenCode could not load the changed AI connection for this work. Send your message again.","assistant_opencode_response_too_large":"OpenCode returned more data than the bridge accepts.","assistant_opencode_event_too_large":"An OpenCode event exceeded the bridge limit.","assistant_opencode_directory_unavailable":"OpenCode did not confirm its conversation directory is ready.","assistant_opencode_catalog_invalid":"OpenCode returned an invalid provider catalogue.","assistant_opencode_catalog_stop_failed":"The temporary OpenCode catalogue process did not stop cleanly.","assistant_opencode_events_timeout":"OpenCode's event connection did not become ready.","assistant_opencode_observation_lost":"OpenCode's event connection ended before observation was closed.","assistant_opencode_parent_unverified":"The subagent's parent session could not be verified.","assistant_opencode_start_timeout":"OpenCode did not become ready before the startup deadline.","assistant_opencode_version_mismatch":"OpenCode {installed} is installed; this host requires {required}.","assistant_opencode_zen_catalog_unavailable":"OpenCode Zen's current model list could not be read. Try again.","assistant_agent_control_binding_retained":"Another native subscriber retained the previous assistant settings. Close the native assistant terminal and retry Resume.","assistant_codex_provider_binding_retained":"Another native subscriber retained the previous model provider. Close the native assistant terminal and retry.","assistant_codex_provider_switch_busy":"Stop the current turn before immediately changing model providers.","assistant_codex_history_request_too_large":"Codex history exceeds the adapter request limit.","assistant_codex_history_request_unreadable":"Codex sent an unreadable or oversized history request.","assistant_custom_endpoint_unreachable":"Your model server at {upstream} isn't answering. Start it, then send your message again.","assistant_codex_app_server_message_too_large":"Codex app-server message exceeded the configured transport limit.","codex_reconnect_required":"Sign in with codex login before continuing.","codex_provider_connection_changed":"This Codex provider connection changed. Work is stopped; use Send or Resume after reconnecting.","codex_runtime_invalidated":"Codex's native runtime was invalidated.","assistant_provider_fetch_missing":"Global fetch is not available for anthropic provider.","assistant_tool_arguments_invalid":"Tool arguments must be a JSON object.","assistant_tool_result_unserializable":"Tool result could not be serialized.","assistant_tool_result_too_large":"Tool result exceeds the assistant size limit. Narrow the request and try again.","assistant_tool_contract_too_large":"Action contract exceeds the assistant size limit. Narrow the request and try again.","assistant_tool_arguments_too_large":"Tool arguments exceed the assistant size limit. Narrow the request and try again.","assistant_action_cursor_invalid":"Action search cursor is invalid for this query.","assistant_action_unknown":"Action is not available.","assistant_action_contract_required":"Load this action's exact contract before executing it.","assistant_tool_output_invalid":"Assistant tool output validation failed.","assistant_tool_unknown":"Unknown tool.","assistant_claude_control_timeout":"Claude {request} timed out."}}`);var en_default={jskit};registerJskitMessages(en_default);function attachmentSizeLabel(size){const bytes=Number(size);if(!Number.isFinite(bytes)||bytes<0)return``;if(bytes<1024)return`${bytes} B`;if(bytes<1048576)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/1048576).toFixed(1)} MB`}var jskitText=useJskitText();var{formatNumber,t:t$3}=jskitText;var WHOLE=Object.freeze({useGrouping:false});var ONE_DECIMAL=Object.freeze({maximumFractionDigits:1,minimumFractionDigits:1,useGrouping:false});function attachmentSizeText(size){if(!jskitText.locale)return attachmentSizeLabel(size);const bytes=Number(size);if(!Number.isFinite(bytes)||bytes<0)return``;if(bytes<1024)return t$3(`jskit.assistant.attachments.sizeBytes`,{size:formatNumber(bytes,WHOLE)});if(bytes<1048576)return t$3(`jskit.assistant.attachments.sizeKilobytes`,{size:formatNumber(bytes/1024,ONE_DECIMAL)});return t$3(`jskit.assistant.attachments.sizeMegabytes`,{size:formatNumber(bytes/1048576,ONE_DECIMAL)})}function attachmentLimitText(maxBytes){if(!jskitText.locale)return maxBytes%1048576===0?`${maxBytes/1048576} MiB`:`${maxBytes/1e6} MB`;return maxBytes%1048576===0?t$3(`jskit.assistant.attachments.sizeMebibytes`,{size:formatNumber(maxBytes/1048576,WHOLE)}):t$3(`jskit.assistant.attachments.sizeMegabytes`,{size:formatNumber(maxBytes/1e6,{useGrouping:false})})}var{t:t$2}=useJskitText();function assistantAttachmentFiles(fileList){return Array.from(fileList||[]).filter(file=>file&&file.size>=0)}function assistantAttachmentFilesFromTransferItems(items){return assistantAttachmentFiles(Array.from(items||[]).map(item=>{if(item?.kind!==`file`||typeof item.getAsFile!==`function`)return null;return item.getAsFile()}))}function assistantAttachmentFilesFromDropEvent(event){const dataTransfer=event?.dataTransfer;const itemFiles=assistantAttachmentFilesFromTransferItems(dataTransfer?.items);if(itemFiles.length>0)return itemFiles;return assistantAttachmentFiles(dataTransfer?.files)}function assistantAttachmentFilesFromPasteEvent(event){const clipboardData=event?.clipboardData;const itemFiles=assistantAttachmentFilesFromTransferItems(clipboardData?.items);if(itemFiles.length>0)return itemFiles;return assistantAttachmentFiles(clipboardData?.files)}function assistantAttachmentEventHasFiles(event){const dataTransfer=event?.dataTransfer;return assistantAttachmentFilesFromDropEvent(event).length>0||Array.from(dataTransfer?.items||[]).some(item=>item?.kind===`file`)||Array.from(dataTransfer?.types||[]).some(type=>type===`Files`||type===`application/x-moz-file`)}function assistantAttachmentClipboardText(event){if(typeof event?.clipboardData?.getData!==`function`)return``;return String(event.clipboardData.getData(`text/plain`)||``)}function assistantAttachmentClipboardLocalFileReference(event){const clipboardData=event?.clipboardData;if(!clipboardData||typeof clipboardData.getData!==`function`)return``;const types=Array.from(clipboardData.types||[]);const text=[clipboardData.getData(`x-special/gnome-copied-files`),clipboardData.getData(`text/uri-list`),clipboardData.getData(`text/plain`)].map(value=>String(value||``).trim()).filter(Boolean).join(`
2
- `);if(types.includes(`Files`)||types.includes(`application/x-moz-file`)||types.includes(`x-special/gnome-copied-files`)||/^file:/imu.test(text))return text||`file://`;return``}function useAttachmentDropTarget({uploadFiles,reportAttachmentError}){const dragDepth=ref(0);const dragActive=computed(()=>dragDepth.value>0);function resetDragState(){dragDepth.value=0}function handleDragEnter(event){if(!assistantAttachmentEventHasFiles(event))return;dragDepth.value+=1;if(event?.dataTransfer)event.dataTransfer.dropEffect=`copy`}function handleDragOver(event){if(event?.dataTransfer)event.dataTransfer.dropEffect=`copy`}function handleDragLeave(){dragDepth.value=Math.max(0,dragDepth.value-1)}async function handleDrop(event){resetDragState();return uploadFiles(assistantAttachmentFilesFromDropEvent(event))}async function handlePaste(event){const files=assistantAttachmentFilesFromPasteEvent(event);if(files.length<1){if(assistantAttachmentClipboardLocalFileReference(event))reportAttachmentError(t$2(`jskit.assistant.attachments.error.localFilePaste`));return[]}if(!assistantAttachmentClipboardText(event))event?.preventDefault?.();return uploadFiles(files)}return{dragActive,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,resetDragState}}var{t:t$1}=useJskitText();function attachmentUploadError(attachment){return attachment?.error||attachment?.errors?.[0]?.message||``}function attachmentIdentity(attachment){return String(attachment?.clientId||attachment?.attachmentId||attachment?.path||attachment?.fileName||``)}var attachmentClientSequence=0;function nextAttachmentClientId(){attachmentClientSequence+=1;return`attachment-${Date.now().toString(36)}-${attachmentClientSequence.toString(36)}`}function attachmentFileName(file){return String(file?.name||`attachment`)}function attachmentUploadResult(upload=null){if(upload&&typeof upload.then===`function`)return{cancel:typeof upload.cancel===`function`?()=>upload.cancel():null,promise:upload};if(upload?.promise&&typeof upload.promise.then===`function`)return{cancel:typeof upload.abort===`function`?()=>upload.abort():typeof upload.cancel===`function`?()=>upload.cancel():null,promise:upload.promise};return{cancel:null,promise:Promise.resolve(upload)}}function attachmentProgress(progress={},possibleTotal,fallbackTotal=0){const directNumericProgress=typeof progress===`number`?progress:null;const progressObject=progress&&typeof progress===`object`?progress:{};const totalBytes=Math.max(0,Number(progressObject.totalBytes??progressObject.total??possibleTotal??fallbackTotal)||0);const bytesValue=progressObject.bytesSent??progressObject.loaded??progressObject.uploadedBytes??directNumericProgress;const bytesKnown=bytesValue!==null&&bytesValue!==void 0&&bytesValue!==``;let bytesSent=bytesKnown?Number(bytesValue)||0:0;const directPercent=progressObject.percent;let percent=directPercent!==null&&directPercent!==void 0&&directPercent!==``?Number(directPercent):null;const progressValue=progressObject.progress;if(!Number.isFinite(percent)&&progressValue!==null&&progressValue!==void 0&&progressValue!==``){const numericProgressValue=Number(progressValue);if(Number.isFinite(numericProgressValue))percent=numericProgressValue<=1?numericProgressValue*100:numericProgressValue}if(!Number.isFinite(percent))percent=bytesKnown&&totalBytes>0?bytesSent/totalBytes*100:null;if(percent!==null)percent=Math.max(0,Math.min(100,percent));if(totalBytes>0){const inferredBytes=percent===null?0:totalBytes*percent/100;bytesSent=Math.max(0,Math.min(totalBytes,bytesSent||inferredBytes))}else bytesSent=Math.max(0,bytesSent);return{bytesSent,percent,totalBytes}}function attachmentReceipt(row,uploaded){return{...uploaded,attachmentId:String(uploaded?.attachmentId||``),clientId:row.clientId,fileName:String(uploaded?.fileName||row.fileName),sessionId:row.sessionId,size:Number(uploaded?.size??row.size)||0}}function createWaiter(row){let resolve=null;row.waiter={promise:new Promise(currentResolve=>{resolve=currentResolve}),resolve,settled:false};return row.waiter}function settleWaiter(row,value=null,waiter=row.waiter){if(!waiter||waiter.settled)return;waiter.settled=true;waiter.resolve(value)}function updateRowProgress(row,progress,total){if(!row.retained||row.phase!==`uploading`)return;const next=attachmentProgress(progress,total,row.totalBytes);row.bytesSent=Math.max(row.bytesSent,next.bytesSent);row.totalBytes=next.totalBytes||row.totalBytes;if(next.percent!==null)row.progress=Math.max(Number(row.progress)||0,next.percent)}function buildQueueRow({currentSessionId,file=null,fileName=`attachment`,phase=`queued`,producer=null,size=0}={}){const normalizedSize=Number(file?.size??size)||0;return reactive({activeHandoffToken:null,activeToken:null,attachmentId:``,bytesSent:0,clientId:nextAttachmentClientId(),error:``,failureStage:``,file,fileName:file?attachmentFileName(file):String(fileName||`attachment`),path:``,phase,producer,producerAbortController:null,producerToken:null,progress:null,receipt:null,retained:true,sessionId:currentSessionId,size:normalizedSize,totalBytes:normalizedSize,waiter:null})}function createReceiptCleanup({deleteAttachment,deletesUnsentUploads,reportAttachmentError}){const cleanupTasks=new Set;const receiptCleanupById=new Map;const cleanedReceiptIds=new Set;function trackCleanup(task){const cleanup=Promise.resolve(task).catch(error=>{reportAttachmentError(error,t$1(`jskit.assistant.attachments.error.cleanupFailed`));return false});cleanupTasks.add(cleanup);cleanup.finally(()=>cleanupTasks.delete(cleanup));return cleanup}async function deleteUploadedAttachment(currentSessionId,attachment){const attachmentId=String(attachment?.attachmentId||``).trim();if(!attachmentId||!deletesUnsentUploads)return false;const response=await deleteAttachment(currentSessionId,attachmentId);if(response?.ok===false)throw new Error(attachmentUploadError(response)||t$1(`jskit.assistant.attachments.error.cleanupFailed`));return true}function cleanupReceipt(currentSessionId,receipt){const attachmentId=String(receipt?.attachmentId||``).trim();const cleanupId=`${currentSessionId}:${attachmentId}`;if(!attachmentId)return Promise.resolve(false);if(cleanedReceiptIds.has(cleanupId))return Promise.resolve(false);if(receiptCleanupById.has(cleanupId))return receiptCleanupById.get(cleanupId);const cleanup=trackCleanup(deleteUploadedAttachment(currentSessionId,receipt)).then(deleted=>{if(deleted)cleanedReceiptIds.add(cleanupId);return deleted});receiptCleanupById.set(cleanupId,cleanup);cleanup.finally(()=>receiptCleanupById.delete(cleanupId));return cleanup}async function waitForAttachmentCleanup(){while(cleanupTasks.size>0)await Promise.allSettled([...cleanupTasks])}return Object.freeze({cleanupReceipt,waitForAttachmentCleanup})}var{serverMessage,t}=useJskitText();function attachmentErrorText(error,fallback){return String(error&&typeof error===`object`&&serverMessage(error)||error?.message||error||fallback)}function assistantAttachmentSessionId(sessionId){return String(toValue(sessionId)||``).trim()}function assistantAttachmentUploadAllowed(canUpload){return toValue(canUpload)!==false}var ASSISTANT_ATTACHMENT_MAX_BYTES=1e8;var ASSISTANT_ATTACHMENT_UPLOAD_CONCURRENCY=2;var ASSISTANT_ATTACHMENT_UNRESOLVED_PHASES=new Set([`preparing`,`queued`,`uploading`,`delivering`,`failed`]);function keepAttachmentErrorInStatus(){}async function keepUploadedAttachmentsReady(){return null}function useAssistantAttachments({canUpload=()=>true,deleteAttachment,onError=keepAttachmentErrorInStatus,onUploaded=keepUploadedAttachmentsReady,sessionId,uploadAttachment,maxBytes=ASSISTANT_ATTACHMENT_MAX_BYTES,maxItems=10,uploadConcurrency=2}){if(![maxBytes,maxItems,uploadConcurrency].every(value=>Number.isSafeInteger(value)&&value>0))throw new TypeError(`Attachment limits must be positive integers.`);const attachments=ref([]);const queueItems=ref([]);const status=ref(``);const activeUploadCount=ref(0);const uploadQueue=[];const rowsById=new Map;const activeAttempts=new Map;let disposed=false;const uploading=computed(()=>activeUploadCount.value>0||queueItems.value.some(item=>[`preparing`,`uploading`,`delivering`].includes(item.phase)));const hasUnresolved=computed(()=>queueItems.value.some(item=>ASSISTANT_ATTACHMENT_UNRESOLVED_PHASES.has(item.phase)));const canSubmit=computed(()=>!hasUnresolved.value);const retainedItemCount=computed(()=>queueItems.value.filter(item=>item.phase!==`cancelled`).length);const atCapacity=computed(()=>retainedItemCount.value>=maxItems);const canAddFiles=computed(()=>Boolean(!disposed&&assistantAttachmentSessionId(sessionId)&&assistantAttachmentUploadAllowed(canUpload)&&!atCapacity.value));const aggregateProgress=computed(()=>{const retainedItems=queueItems.value.filter(item=>item.phase!==`cancelled`);const totalBytes=retainedItems.reduce((sum,item)=>sum+item.totalBytes,0);const bytesSent=retainedItems.reduce((sum,item)=>sum+item.bytesSent,0);return{bytesSent,percent:totalBytes>0?Math.round(bytesSent/totalBytes*100):0,totalBytes}});const tooLarge=row=>t(`jskit.assistant.attachments.error.tooLarge`,{fileName:row.fileName,limit:attachmentLimitText(maxBytes)});const tooMany=()=>t(`jskit.assistant.attachments.error.tooMany`,{count:maxItems});function reportAttachmentError(error,fallbackMessage=t(`jskit.assistant.attachments.error.uploadFailed`),{notify=true}={}){const message=attachmentErrorText(error,fallbackMessage);status.value=message;if(notify)try{onError(error||new Error(message),fallbackMessage)}catch{}return message}function clearStatus(){status.value=``}function failRow(row,failureStage,error,fallbackMessage){row.error=attachmentErrorText(error,fallbackMessage);row.failureStage=failureStage;row.phase=`failed`;reportAttachmentError(error,fallbackMessage,{notify:false})}function canonicalRow(attachment={}){const identity=attachmentIdentity(attachment);return identity?rowsById.get(identity)||queueItems.value.find(row=>attachmentIdentity(row)===identity||row.attachmentId===identity):null}const{cleanupReceipt,waitForAttachmentCleanup}=createReceiptCleanup({deleteAttachment,deletesUnsentUploads:typeof deleteAttachment===`function`,reportAttachmentError});const{dragActive,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,resetDragState}=useAttachmentDropTarget({uploadFiles,reportAttachmentError});function removeReadyReceipt(row){const removed=attachments.value.filter(attachment=>attachment.clientId===row.clientId);attachments.value=attachments.value.filter(attachment=>attachment.clientId!==row.clientId);return removed}async function handOffUploadedAttachment(row,receipt,waiter=row.waiter){const token=Symbol(`${row.clientId}-handoff`);row.activeHandoffToken=token;row.phase=`delivering`;if(!attachments.value.some(attachment=>attachment.clientId===row.clientId))attachments.value.push(receipt);try{const accepted=(await onUploaded([receipt]))?.accepted===true;if(row.activeHandoffToken!==token||!row.retained||row.phase===`cancelled`){removeReadyReceipt(row);if(!accepted)await cleanupReceipt(row.sessionId,receipt);settleWaiter(row,null,waiter);return null}row.activeHandoffToken=null;row.error=``;row.failureStage=``;if(accepted){removeReadyReceipt(row);row.retained=false;rowsById.delete(row.clientId);queueItems.value=queueItems.value.filter(candidate=>candidate.clientId!==row.clientId);settleWaiter(row,receipt,waiter);return receipt}row.phase=`ready`;settleWaiter(row,receipt,waiter);return receipt}catch(error){if(row.activeHandoffToken!==token||!row.retained||row.phase===`cancelled`){await cleanupReceipt(row.sessionId,receipt);settleWaiter(row,null,waiter);return null}row.activeHandoffToken=null;removeReadyReceipt(row);failRow(row,`handoff`,error,t(`jskit.assistant.attachments.error.unusable`));settleWaiter(row,null,waiter);return null}}async function finishUploadAttempt(attempt,uploaded,uploadError=null){activeAttempts.delete(attempt.token);activeUploadCount.value=activeAttempts.size;pumpQueue();const{row}=attempt;const isCurrentAttempt=row.activeToken===attempt.token;const uploadSucceeded=Boolean(!uploadError&&uploaded&&uploaded.ok!==false&&String(uploaded.attachmentId||``).trim());if(!isCurrentAttempt||!row.retained||disposed){if(uploadSucceeded)await cleanupReceipt(attempt.sessionId,uploaded);settleWaiter(row,null,attempt.waiter);pumpQueue();return}row.activeToken=null;if(uploadSucceeded){const receipt=attachmentReceipt(row,uploaded);row.receipt=receipt;row.attachmentId=receipt.attachmentId;row.path=String(receipt.path||``);row.bytesSent=row.totalBytes;row.progress=100;row.error=``;row.failureStage=``;await handOffUploadedAttachment(row,receipt,attempt.waiter)}else{failRow(row,`upload`,uploadError||new Error(attachmentUploadError(uploaded)||t(`jskit.assistant.attachments.error.uploadFailed`)),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null,attempt.waiter)}pumpQueue()}function startUpload(row){const token=Symbol(row.clientId);const abortController=new AbortController;const attempt={abortController,cancel:null,row,sessionId:row.sessionId,settled:null,token,waiter:row.waiter};row.activeToken=token;row.phase=`uploading`;row.error=``;activeAttempts.set(token,attempt);activeUploadCount.value=activeAttempts.size;try{const transport=attachmentUploadResult(uploadAttachment(row.sessionId,row.file,{onProgress:(progress,total)=>updateRowProgress(row,progress,total),signal:abortController.signal}));attempt.cancel=transport.cancel;attempt.settled=transport.promise.then(uploaded=>finishUploadAttempt(attempt,uploaded),error=>finishUploadAttempt(attempt,null,error))}catch(error){attempt.settled=finishUploadAttempt(attempt,null,error)}}function pumpQueue(){if(disposed)return;while(activeAttempts.size<uploadConcurrency&&uploadQueue.length>0){const row=uploadQueue.shift();if(!row?.retained||row.phase!==`queued`)continue;startUpload(row)}}function cancelAttachment(attachment={}){const row=canonicalRow(attachment);if(!row||!row.retained||![`preparing`,`queued`,`uploading`].includes(row.phase))return false;const token=row.activeToken;row.activeToken=null;row.activeHandoffToken=null;row.phase=`cancelled`;row.error=``;const receipt=row.receipt;removeReadyReceipt(row);if(receipt)cleanupReceipt(row.sessionId,receipt);row.receipt=null;row.failureStage=``;settleWaiter(row,null);const attempt=token?activeAttempts.get(token):null;try{row.producerAbortController?.abort();attempt?.abortController.abort();attempt?.cancel?.()}catch{}row.producerAbortController=null;row.producerToken=null;pumpQueue();return true}function retryAttachment(attachment={}){const row=canonicalRow(attachment);if(!row||!row.retained||![`failed`,`cancelled`].includes(row.phase)||row.sessionId!==assistantAttachmentSessionId(sessionId)||!assistantAttachmentUploadAllowed(canUpload))return Promise.resolve(null);if(row.phase===`cancelled`&&retainedItemCount.value>=maxItems){reportAttachmentError(tooMany());return Promise.resolve(null)}if(row.failureStage===`handoff`&&row.receipt){row.error=``;row.phase=`uploading`;const waiter=createWaiter(row);handOffUploadedAttachment(row,row.receipt,waiter);return waiter.promise}if(row.producer&&!row.file){const waiter=createWaiter(row);startAttachmentProducer(row);return waiter.promise}if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));return Promise.resolve(null)}row.bytesSent=0;row.progress=null;row.error=``;row.failureStage=``;row.phase=`queued`;const waiter=createWaiter(row);uploadQueue.push(row);pumpQueue();return waiter.promise}function detachRow(row){if([`preparing`,`queued`,`uploading`].includes(row.phase))cancelAttachment(row);row.retained=false;rowsById.delete(row.clientId);settleWaiter(row,null)}function removeAttachment(attachment={}){const row=canonicalRow(attachment);if(!row)return[];const removedReceipts=removeReadyReceipt(row);const removed=removedReceipts.length>0?removedReceipts:[row];const receiptToClean=removedReceipts[0]||row.receipt;detachRow(row);queueItems.value=queueItems.value.filter(candidate=>candidate.clientId!==row.clientId);if(receiptToClean)cleanupReceipt(row.sessionId,receiptToClean);return removed}function clearAttachments({accepted=true,attachmentIds=null}={}){if(!accepted)return abandonAttachments();const selectedIds=Array.isArray(attachmentIds)?new Set(attachmentIds):null;const cleared=attachments.value.filter(attachment=>!selectedIds||selectedIds.has(attachment.attachmentId));const readyIds=new Set(cleared.map(attachment=>attachment.clientId));const remaining=[];for(const row of[...queueItems.value]){if(selectedIds&&!readyIds.has(row.clientId)){remaining.push(row);continue}if(readyIds.has(row.clientId)){row.retained=false;rowsById.delete(row.clientId);continue}detachRow(row);if(row.receipt)cleanupReceipt(row.sessionId,row.receipt)}attachments.value=attachments.value.filter(attachment=>!readyIds.has(attachment.clientId));queueItems.value=remaining;return cleared}async function abandonAttachments({onlySessionId=``}={}){const normalizedSessionId=String(onlySessionId||``).trim();const rows=queueItems.value.filter(row=>!normalizedSessionId||row.sessionId===normalizedSessionId);const rowIds=new Set(rows.map(row=>row.clientId));const readyReceipts=rows.map(row=>row.receipt).filter(Boolean);const attempts=[...activeAttempts.values()].filter(attempt=>rowIds.has(attempt.row.clientId));for(const row of rows)detachRow(row);queueItems.value=queueItems.value.filter(row=>!rowIds.has(row.clientId));attachments.value=attachments.value.filter(attachment=>!rowIds.has(attachment.clientId));const readyCleanup=readyReceipts.map(attachment=>cleanupReceipt(attachment.sessionId,attachment));await Promise.allSettled([...readyCleanup,...attempts.map(attempt=>attempt.settled).filter(Boolean)]);await waitForAttachmentCleanup();return rows}async function disposeAttachments(){if(disposed){await waitForAttachmentCleanup();return[]}disposed=true;stopSessionWatch();return abandonAttachments()}function createQueueRow(options){const row=buildQueueRow(options);rowsById.set(row.clientId,row);queueItems.value.push(row);createWaiter(row);return row}function queuePreparedFile(row,file,waiter=row.waiter){const preparedFile=assistantAttachmentFiles([file])[0];if(!preparedFile)throw Object.assign(new Error(`The prepared attachment did not produce a file.`),{messageCode:`assistant.attachments.error.noFile`,messageParams:{}});row.file=preparedFile;row.fileName=attachmentFileName(preparedFile);row.size=Number(preparedFile.size)||0;row.totalBytes=row.size;if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null,waiter);return false}row.phase=`queued`;uploadQueue.push(row);pumpQueue();return true}function startAttachmentProducer(row){const token=Symbol(`${row.clientId}-producer`);const waiter=row.waiter;const abortController=new AbortController;row.file=null;row.producerAbortController=abortController;row.producerToken=token;row.phase=`preparing`;row.error=``;row.failureStage=``;row.producerSettled=Promise.resolve().then(()=>row.producer({signal:abortController.signal})).then(file=>{if(row.producerToken!==token||!row.retained||disposed){settleWaiter(row,null,waiter);return null}row.producerAbortController=null;row.producerToken=null;try{queuePreparedFile(row,file,waiter)}catch(error){failRow(row,`preparing`,error,t(`jskit.assistant.attachments.error.preparationFailed`));settleWaiter(row,null,waiter)}return file},error=>{if(row.producerToken!==token||!row.retained||disposed){settleWaiter(row,null,waiter);return null}row.producerAbortController=null;row.producerToken=null;if(error?.name===`AbortError`){row.phase=`cancelled`;row.error=``}else failRow(row,`preparing`,error,t(`jskit.assistant.attachments.error.preparationFailed`));settleWaiter(row,null,waiter);return null})}function uploadFileProducer({fileName=t(`jskit.assistant.attachments.preparingName`),produce}={}){const currentSessionId=assistantAttachmentSessionId(sessionId);if(!canAddFiles.value||typeof produce!==`function`){if(atCapacity.value)reportAttachmentError(tooMany());return Promise.resolve(null)}status.value=``;const row=createQueueRow({currentSessionId,fileName,phase:`preparing`,producer:produce});const waiter=row.waiter;startAttachmentProducer(row);return waiter.promise}async function uploadFiles(files=[]){const uploadableFiles=assistantAttachmentFiles(files);const currentSessionId=assistantAttachmentSessionId(sessionId);if(uploadableFiles.length<1||!currentSessionId||disposed||!assistantAttachmentUploadAllowed(canUpload))return[];status.value=``;const availableSlots=Math.max(0,maxItems-retainedItemCount.value);const acceptedFiles=uploadableFiles.slice(0,availableSlots);if(acceptedFiles.length<uploadableFiles.length)reportAttachmentError(tooMany());const waiters=[];for(const file of acceptedFiles){const row=createQueueRow({currentSessionId,file});const waiter=row.waiter;waiters.push(waiter.promise);if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null)}else uploadQueue.push(row)}pumpQueue();return(await Promise.all(waiters)).filter(attachment=>attachment&&attachments.value.some(candidate=>candidate.clientId===attachment.clientId))}const stopSessionWatch=watch(()=>assistantAttachmentSessionId(sessionId),(nextSessionId,previousSessionId)=>{if(nextSessionId!==previousSessionId&&previousSessionId)abandonAttachments({onlySessionId:previousSessionId})},{flush:`sync`});if(getCurrentScope())onScopeDispose(()=>{disposeAttachments()});return{maxBytes,maxItems,abandonAttachments,aggregateProgress,attachments,atCapacity,canAddFiles,cancelAttachment,canSubmit,clearAttachments,clearStatus,disposeAttachments,dragActive,hasUnresolved,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,queueItems,removeAttachment,resetDragState,retryAttachment,status,uploading,uploadFiles,uploadFileProducer,waitForAttachmentCleanup}}export{en_default as a,attachmentSizeText as i,assistantAttachmentFilesFromDropEvent as n,assistantAttachmentFilesFromPasteEvent as r,useAssistantAttachments as t};
@@ -1 +0,0 @@
1
- import{Et as unref,gt as reactive,ht as proxyRefs,it as watch,u as computed}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as useShellWebErrorRuntime}from"./error-BQ7r64JO.js";import{N as useQueryClient,a as ensureAccessModeCompatibility,c as normalizePermissions,d as resolveEnabled,f as resolvePermissionAccess,i as emptyRecord,l as resolveAccessModeEnabled,m as resolveEnabledRef,n as useOperationRealtime,o as normalizeAccessMode,p as resolveQueryKey,r as asPlainObject,s as normalizeOwnershipFilter,t as useEndpointResource,u as resolveApiSuffix}from"./useEndpointResource-CmMwteuX.js";import{o as normalizeLowerText,u as normalizeText}from"./normalize-BD25VwNK.js";import{n as validateSchemaPayload}from"./validators-HqYRjxEO.js";import{c as normalizePermissionList,n as getHttpWebClient,r as buildValidationFailure,s as hasPermission}from"./httpClient-Bwitq9Xf.js";import{n as resolveScopedRouteBase}from"./surface-CBlx7sF_.js";import{r as useJskitText}from"./i18n-BuXRXGaO.js";import{n as ROUTE_VISIBILITY_WORKSPACE}from"./visibility-Cq31Xy7I.js";import"./i18n-BkxO7BMl.js";import{r as toUiFieldErrors}from"./errorMessageHelpers-BjIt31kK.js";import{m as useWebPlacementContext,r as resolveSurfaceDefinitionFromPlacementContext}from"./placement-1lT0lW3-.js";import{n as useSurfaceRouteContext,t as usePaths}from"./usePaths-CvUbx5-V.js";import{t as useUiFeedback}from"./useUiFeedback-CWb6o71Z.js";var{t:t$3,text:text$1}=useJskitText();var SILENT_FIELD_BAG=Object.freeze({apply(){}});var SILENT_FEEDBACK=Object.freeze({error(){}});function validateOperationInput({input,rawPayload={},fieldBag=SILENT_FIELD_BAG,feedback=SILENT_FEEDBACK,validationMessage=``}){if(!input)return{ok:true,parsedInput:rawPayload};try{return{ok:true,parsedInput:validateSchemaPayload(input,rawPayload,{phase:`input`,context:`operation input`})}}catch(error){if(!error?.fieldErrors||typeof error.fieldErrors!==`object`)throw error;const fieldErrorCodes=error.fieldErrorCodes||error.details?.fieldErrorCodes;const failure={...buildValidationFailure({error:text$1(validationMessage)||t$3(`jskit.http.feedback.validationFailed`),code:`validation_failed`,fieldErrors:error?.fieldErrors}),...fieldErrorCodes?{fieldErrorCodes}:{}};fieldBag.apply(toUiFieldErrors(failure));feedback.error(failure,failure.error);return{ok:false,failure,parsedInput:null}}}var{t:t$2,text}=useJskitText();function useCommandCore({model,resource,writeMethod=`POST`,canRun,fieldBag,feedback,input,buildRawPayload=emptyRecord,buildCommandPayload,buildCommandOptions=emptyRecord,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={}}){const queryClient=useQueryClient();const normalizedWriteMethod=String(writeMethod||`POST`).trim().toUpperCase();const running=resource.isSaving;const fieldErrors=fieldBag.errors;const message=feedback.message;const messageType=feedback.messageType;async function run(context={}){if(!canRun.value||running.value)return null;feedback.clear();fieldBag.clear();const rawPayload=buildRawPayload(model,{queryClient,resource,context});const validationResult=validateOperationInput({input,rawPayload,fieldBag,feedback,validationMessage:text(messages.validation)||t$2(`jskit.http.feedback.validationFailed`)});if(!validationResult.ok)return null;const{parsedInput}=validationResult;const payload=typeof buildCommandPayload===`function`?buildCommandPayload(parsedInput,{rawPayload,queryClient,resource,context}):normalizedWriteMethod===`DELETE`?void 0:parsedInput;const options=buildCommandOptions(parsedInput,{rawPayload,queryClient,resource,context});try{const response=await resource.save(payload,options);if(onRunSuccess)await onRunSuccess(response,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});if(!suppressSuccessMessage)feedback.success(text(messages.success)||t$2(`jskit.http.feedback.completed`));return response}catch(error){fieldBag.apply(toUiFieldErrors(error));if(onRunError)await onRunError(error,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});feedback.error(error,text(messages.error)||t$2(`jskit.http.feedback.actionFailed`));throw error}}return{running,fieldErrors,message,messageType,run}}var{t:t$1}=useJskitText();function asPermissionList(value){if(Array.isArray(value))return value;if(value===void 0||value===null||value===``)return[];return[value]}function useAccess({enabled=true,access=`always`,hasPermissionRequirements=false}={}){const normalizedAccessMode=normalizeAccessMode(access);const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements:hasPermissionRequirements===true});const{context:placementContext}=useWebPlacementContext();const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&accessRequired);const hasPlacementPermissions=computed(()=>{const source=placementContext.value;if(!source||typeof source!==`object`)return false;return Object.hasOwn(source,`permissions`)});const placementPermissions=computed(()=>normalizePermissionList(placementContext.value?.permissions));const permissions=computed(()=>{if(!queryEnabled.value||!hasPlacementPermissions.value)return[];return placementPermissions.value});const permissionsUnavailableError=computed(()=>{if(!queryEnabled.value||hasPlacementPermissions.value)return``;return t$1(`jskit.http.access.permissionsUnavailable`)});const awaitingPlacementPermissions=computed(()=>queryEnabled.value&&!hasPlacementPermissions.value);function can(permission){return hasPermission(permissions.value,permission)}function canAny(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(can(entry))return true;return false}function canAll(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(!can(entry))return false;return true}return{accessMode:normalizedAccessMode,accessRequired,permissions,permissionsUnavailableError,awaitingPlacementPermissions,can,canAny,canAll}}function toRouteParamValue(value){if(Array.isArray(value))return toRouteParamValue(value[0]);if(value==null)return``;return String(value).trim()}function extractRouteParamNames(pathTemplate=``){const normalizedTemplate=String(pathTemplate||``).trim();if(!normalizedTemplate)return[];const names=[];const seen=new Set;const pattern=/:([A-Za-z][A-Za-z0-9_]*)/g;let match=null;while((match=pattern.exec(normalizedTemplate))!=null){const name=String(match[1]||``).trim();if(!name||seen.has(name))continue;seen.add(name);names.push(name)}return names}var{t}=useJskitText();function resolveScopedRouteParamNames(placementContext=null,surfaceId=``){const routeBase=resolveSurfaceDefinitionFromPlacementContext(placementContext,surfaceId)?.routeBase||`/`;return extractRouteParamNames(resolveScopedRouteBase(routeBase))}function useScopeRuntime({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,accessMode=`auto`,hasPermissionRequirements=false}={}){const normalizedOwnershipFilter=normalizeOwnershipFilter(ownershipFilter);const normalizedAccessMode=ensureAccessModeCompatibility({accessMode,hasPermissionRequirements,caller:`useScopeRuntime`});const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements});const routeContext=useSurfaceRouteContext();const paths=usePaths({routeContext});const resolvedSurfaceId=computed(()=>{const explicitSurfaceId=normalizeLowerText(surfaceId);if(explicitSurfaceId)return explicitSurfaceId;return normalizeLowerText(routeContext.currentSurfaceId.value)});const scopedRouteParamNames=computed(()=>resolveScopedRouteParamNames(routeContext.placementContext.value,resolvedSurfaceId.value));const routeScopeParams=computed(()=>{const source=paths.routeParams.value;const next={};for(const paramName of scopedRouteParamNames.value){const paramValue=toRouteParamValue(source[paramName]);if(paramValue)next[paramName]=paramValue}return Object.freeze(next)});const missingScopedRouteParamNames=computed(()=>scopedRouteParamNames.value.filter(paramName=>!routeScopeParams.value[paramName]));const requiresScopedRouteParams=computed(()=>scopedRouteParamNames.value.length>0);const hasRequiredRouteScope=computed(()=>missingScopedRouteParamNames.value.length<1);const scopeParamValue=computed(()=>{const[primaryScopeParamName=``]=scopedRouteParamNames.value;return primaryScopeParamName?routeScopeParams.value[primaryScopeParamName]||``:``});const routeScopeError=computed(()=>{if(!requiresScopedRouteParams.value||hasRequiredRouteScope.value)return``;const missingParams=missingScopedRouteParamNames.value.join(`, `);return t(`jskit.http.access.routeParamsRequired`,{params:missingParams,surface:resolvedSurfaceId.value||`<unknown>`})});const accessRuntime=useAccess({enabled:computed(()=>accessRequired&&hasRequiredRouteScope.value),access:normalizedAccessMode,hasPermissionRequirements});function resolveApiPath(apiSuffix=``,context={}){if(routeScopeError.value)return``;const suffix=resolveApiSuffix(apiSuffix,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,...asPlainObject(context)});return paths.api(suffix,{surface:resolvedSurfaceId.value,params:routeScopeParams.value})}function requireRouteScope(caller=`useScopeRuntime`){if(routeScopeError.value)throw new Error(`${caller}: ${routeScopeError.value}`)}return{normalizedOwnershipFilter,requiresScopedRouteParams:requiresScopedRouteParams.value,resolvedSurfaceId,accessMode:normalizedAccessMode,accessRequired,routeContext,scopedRouteParamNames,routeScopeParams,scopeParamValue,hasRequiredRouteScope,routeScopeError,access:accessRuntime,resolveApiPath,requireRouteScope}}function normalizePermissionSets(permissionSets={}){const source=permissionSets&&typeof permissionSets===`object`&&!Array.isArray(permissionSets)?permissionSets:{};const normalized={};for(const[key,value]of Object.entries(source))normalized[key]=normalizePermissions(value);return normalized}function hasAnyPermissions(permissionSets={}){for(const list of Object.values(permissionSets))if(Array.isArray(list)&&list.length>0)return true;return false}function useOperationScope({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,model,readEnabled=true,queryKeyFactory,permissionSets={},realtime}){const normalizedPermissionSets=normalizePermissionSets(permissionSets);const scopeRuntime=useScopeRuntime({ownershipFilter,surfaceId,accessMode:access,hasPermissionRequirements:hasAnyPermissions(normalizedPermissionSets)});const normalizedOwnershipFilter=scopeRuntime.normalizedOwnershipFilter;const routeContext=scopeRuntime.routeContext;const scopeParamValue=scopeRuntime.scopeParamValue;const hasRequiredRouteScope=scopeRuntime.hasRequiredRouteScope;const accessRuntime=scopeRuntime.access;const apiPath=computed(()=>scopeRuntime.resolveApiPath(apiSuffix,{model}));const queryEnabled=computed(()=>resolveEnabled(readEnabled,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,model}));const queryKey=computed(()=>resolveQueryKey(queryKeyFactory,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter}));const realtimeBinding=useOperationRealtime({realtime,queryKey:typeof queryKeyFactory===`function`?queryKey:null,enabled:computed(()=>hasRequiredRouteScope.value&&Boolean(apiPath.value))});function queryCanRun(accessGate=true){return computed(()=>queryEnabled.value&&hasRequiredRouteScope.value&&Boolean(apiPath.value)&&Boolean(unref(accessGate)))}function permissionGate(key=``){const list=normalizedPermissionSets[String(key||``)]||[];return computed(()=>resolvePermissionAccess(accessRuntime,list))}function loadError(baseError=``){return computed(()=>{if(scopeRuntime.routeScopeError.value)return scopeRuntime.routeScopeError.value;const permissionsError=String(accessRuntime.permissionsUnavailableError.value||``).trim();if(permissionsError)return permissionsError;if(baseError===void 0||baseError===null||baseError===``)return``;return String(unref(baseError)||``).trim()})}function isLoading(baseLoading=false){return computed(()=>Boolean(unref(baseLoading))||accessRuntime.awaitingPlacementPermissions.value)}return{scopeRuntime,routeContext,normalizedOwnershipFilter,scopeParamValue,hasRequiredRouteScope,access:accessRuntime,apiPath,queryEnabled,queryKey,queryCanRun,realtime:realtimeBinding,permissionGate,loadError,isLoading}}function normalizeFieldErrorKeys(keys){return Array.isArray(keys)?keys.map(entry=>String(entry||``).trim()).filter(Boolean):[]}function useFieldErrorBag(keys=[]){const normalizedKeys=normalizeFieldErrorKeys(keys);const hasFixedKeys=normalizedKeys.length>0;const errors=reactive(Object.fromEntries(normalizedKeys.map(key=>[key,``])));function clear(){const keysToClear=hasFixedKeys?normalizedKeys:Object.keys(errors);for(const key of keysToClear)errors[key]=``}function apply(source={}){const fieldErrorMap=source&&typeof source===`object`?source:{};if(hasFixedKeys){for(const key of normalizedKeys)errors[key]=String(fieldErrorMap[key]||``);return}clear();for(const[field,message]of Object.entries(fieldErrorMap)){const key=String(field||``).trim();if(!key)continue;errors[key]=String(message||``)}}function set(field,message){const key=String(field||``).trim();if(!key)return;if(hasFixedKeys&&!(key in errors))return;errors[key]=String(message||``)}return{errors,clear,apply,set}}function normalizeMessage(value){return String(value||``).trim()}function noRetryAction(){return null}function setupOperationErrorReporting({enabled=true,source=`http-web.operation`,loadError=null,notFoundError=null,loadActionFactory=noRetryAction,notFoundActionFactory=noRetryAction,loadChannel=``,notFoundChannel=``,loadSeverity=`error`,notFoundSeverity=`warning`,dedupeWindowMs=2e3}={}){if(!enabled)return;const runtime=useShellWebErrorRuntime();const normalizedSource=normalizeMessage(source)||`http-web.operation`;function watchMessage(value,{kind=`load`,channel=``,intent=`resource-load`,severity=`error`,actionFactory=noRetryAction}={}){let lastMessage=``;let lastPresentationId=``;watch(()=>normalizeMessage(value.value),nextMessage=>{if(!nextMessage){lastMessage=``;if(lastPresentationId){runtime.dismiss(lastPresentationId);lastPresentationId=``}return}if(nextMessage===lastMessage)return;lastMessage=nextMessage;const action=actionFactory({message:nextMessage,kind});const reportResult=runtime.report({source:normalizedSource,message:nextMessage,intent,severity,channel,action,dedupeKey:`${normalizedSource}:${kind}:${nextMessage}`,dedupeWindowMs});const nextPresentationId=String(reportResult?.presentationId||``).trim();if(nextPresentationId){if(lastPresentationId&&lastPresentationId!==nextPresentationId)runtime.dismiss(lastPresentationId);lastPresentationId=nextPresentationId}},{immediate:true})}if(loadError)watchMessage(loadError,{kind:`load`,channel:loadChannel,intent:`resource-load`,severity:loadSeverity,actionFactory:loadActionFactory});if(notFoundError)watchMessage(notFoundError,{kind:`not-found`,channel:notFoundChannel,intent:`resource-load`,severity:notFoundSeverity,actionFactory:notFoundActionFactory})}function setupRouteChangeCleanup({enabled=true,route,feedback,onClear}){if(!enabled)return;watch(()=>route?.fullPath,()=>{feedback.clear();onClear()})}var CRUD_API_ACCESS_AUTHENTICATED=`authenticated`;var CRUD_API_ACCESS_PUBLIC=`public`;var CRUD_API_ACCESS_VALUES=Object.freeze([CRUD_API_ACCESS_AUTHENTICATED,CRUD_API_ACCESS_PUBLIC]);var publicCrudClients=new WeakSet;function normalizeCrudApiAccess(value=``){const normalized=normalizeText(value).toLowerCase()||`authenticated`;if(CRUD_API_ACCESS_VALUES.includes(normalized))return normalized;throw new TypeError(`CRUD resource apiAccess must be one of: ${CRUD_API_ACCESS_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveCrudHttpClient(resource=null,{client=getHttpWebClient()}={}){if(normalizeCrudApiAccess(resource?.apiAccess)!==`public`)return client;if(publicCrudClients.has(client))return client;const publicClient=Object.freeze({request(url,options={}){const requestOptions=options&&typeof options===`object`&&!Array.isArray(options)?options:{};return client.request(url,{...requestOptions,csrf:false})}});publicCrudClients.add(publicClient);return publicClient}function useCommand({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,runPermissions=[],writeMethod=`POST`,client,resource:commandResource=null,transport,placementSource=`http-web.command`,fallbackRunError=`jskit.http.feedback.actionFailed`,fieldErrorKeys,clearOnRouteChange=true,model,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={},realtime}){const operationScope=useOperationScope({ownershipFilter,surfaceId,access,apiSuffix,model,readEnabled:false,permissionSets:{run:runPermissions},realtime});const routeContext=operationScope.routeContext;const canRun=operationScope.permissionGate(`run`);const endpointResource=useEndpointResource({path:operationScope.apiPath,enabled:false,client:resolveCrudHttpClient(commandResource,{client}),writeMethod,transport,fallbackSaveError:fallbackRunError});const feedback=useUiFeedback({source:`${placementSource}.feedback`});const fieldBag=useFieldErrorBag(fieldErrorKeys);const command=useCommandCore({model,resource:endpointResource,writeMethod,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage:Boolean(suppressSuccessMessage),messages:{validation:`jskit.http.feedback.fixInvalidValues`,success:`jskit.http.feedback.completed`,error:String(fallbackRunError||`jskit.http.feedback.actionFailed`),...messages&&typeof messages===`object`?messages:{}}});setupRouteChangeCleanup({enabled:clearOnRouteChange,route:routeContext.route,feedback,onClear:fieldBag.clear});const loadError=operationScope.loadError();const isLoading=operationScope.isLoading();setupOperationErrorReporting({source:`${placementSource}.load`,loadError});return proxyRefs({canRun,isLoading,loadError,isRunning:command.running,fieldErrors:command.fieldErrors,message:command.message,messageType:command.messageType,run:command.run,resource:endpointResource})}export{useCommand as t};
@@ -1 +0,0 @@
1
- import{D as hasInjectionContext,Et as unref,N as nextTick,O as inject,Tt as toValue,_t as readonly,bt as shallowReadonly,ft as isRef,gt as reactive,it as watch,mt as onScopeDispose,u as computed,wt as toRefs,yt as shallowReactive}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{n as hasValue,r as isRecord,u as normalizeText}from"./normalize-BD25VwNK.js";import{n as getHttpWebClient}from"./httpClient-Bwitq9Xf.js";import{n as ROUTE_VISIBILITY_WORKSPACE,r as ROUTE_VISIBILITY_WORKSPACE_USER,t as ROUTE_VISIBILITY_TOKENS}from"./visibility-Cq31Xy7I.js";import{r as useRealtimeEvent}from"./useRealtimeEvent-B4oRg9Dt.js";import{t as toQueryErrorMessage}from"./errorMessageHelpers-BjIt31kK.js";var VUE_QUERY_CLIENT=`VUE_QUERY_CLIENT`;function getClientKey(key){const suffix=key?`:${key}`:``;return`${VUE_QUERY_CLIENT}${suffix}`}function updateState(state,update){Object.keys(state).forEach(key=>{state[key]=update[key]})}function _cloneDeep(value,customize,currentKey=``,currentLevel=0){if(customize){const result=customize(value,currentKey,currentLevel);if(result===void 0&&isRef(value))return result;if(result!==void 0)return result}if(Array.isArray(value))return value.map((val,index)=>_cloneDeep(val,customize,String(index),currentLevel+1));if(typeof value===`object`&&isPlainObject$1(value)){const entries=Object.entries(value).map(([key,val])=>[key,_cloneDeep(val,customize,key,currentLevel+1)]);return Object.fromEntries(entries)}return value}function cloneDeep(value,customize){return _cloneDeep(value,customize)}function cloneDeepUnref(obj,unrefGetters=false){return cloneDeep(obj,(val,key,level)=>{if(level===1&&key===`queryKey`)return cloneDeepUnref(val,true);if(unrefGetters&&isFunction(val))return cloneDeepUnref(val(),unrefGetters);if(isRef(val))return cloneDeepUnref(unref(val),unrefGetters)})}function isPlainObject$1(value){if(Object.prototype.toString.call(value)!==`[object Object]`)return false;const prototype=Object.getPrototypeOf(value);return prototype===null||prototype===Object.prototype}function isFunction(value){return typeof value===`function`}function useQueryClient(id=``){if(!hasInjectionContext())throw new Error(`vue-query hooks can only be used inside setup() function or functions that support injection context.`);const key=getClientKey(id);const queryClient=inject(key);if(!queryClient)throw new Error(`No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.`);return queryClient}var defaultTimeoutProvider={setTimeout:(callback,delay)=>setTimeout(callback,delay),clearTimeout:timeoutId=>clearTimeout(timeoutId),setInterval:(callback,delay)=>setInterval(callback,delay),clearInterval:intervalId=>clearInterval(intervalId)};var TimeoutManager=class{#provider=defaultTimeoutProvider;#providerCalled=false;setTimeoutProvider(provider){this.#provider=provider}setTimeout(callback,delay){return this.#provider.setTimeout(callback,delay)}clearTimeout(timeoutId){this.#provider.clearTimeout(timeoutId)}setInterval(callback,delay){return this.#provider.setInterval(callback,delay)}clearInterval(intervalId){this.#provider.clearInterval(intervalId)}};var timeoutManager=new TimeoutManager;function systemSetTimeoutZero(callback){setTimeout(callback,0)}var isServer$1=typeof window===`undefined`||`Deno`in globalThis;function noop(){}function functionalUpdate(updater,input){return typeof updater===`function`?updater(input):updater}function isValidTimeout(value){return typeof value===`number`&&value>=0&&value!==Infinity}function timeUntilStale(updatedAt,staleTime){return Math.max(updatedAt+(staleTime||0)-Date.now(),0)}function resolveQueryValue(value,query){return typeof value===`function`?value(query):value}function matchQuery(filters,query){const{type=`all`,exact,fetchStatus,predicate,queryKey,stale}=filters;if(queryKey){if(exact){if(query.queryHash!==hashQueryKeyByOptions(queryKey,query.options))return false}else if(!partialMatchKey(query.queryKey,queryKey))return false}if(type!==`all`){const isActive=query.isActive();if(type===`active`&&!isActive)return false;if(type===`inactive`&&isActive)return false}if(typeof stale===`boolean`&&query.isStale()!==stale)return false;if(fetchStatus&&fetchStatus!==query.state.fetchStatus)return false;if(predicate&&!predicate(query))return false;return true}function matchMutation(filters,mutation){const{exact,status,predicate,mutationKey}=filters;if(mutationKey){if(!mutation.options.mutationKey)return false;if(exact){if(hashKey(mutation.options.mutationKey)!==hashKey(mutationKey))return false}else if(!partialMatchKey(mutation.options.mutationKey,mutationKey))return false}if(status&&mutation.state.status!==status)return false;if(predicate&&!predicate(mutation))return false;return true}function hashQueryKeyByOptions(queryKey,options){return(options?.queryKeyHashFn||hashKey)(queryKey)}function hashKey(queryKey){return JSON.stringify(queryKey,(_,val)=>isPlainObject(val)?Object.keys(val).sort().reduce((result,key)=>{result[key]=val[key];return result},{}):val)}function partialMatchKey(a,b){if(a===b)return true;if(typeof a!==typeof b)return false;if(a&&b&&typeof a===`object`&&typeof b===`object`){if(Array.isArray(a)&&Array.isArray(b)){if(b.length>a.length)return false;for(let i=0;i<b.length;i++)if(!partialMatchKey(a[i],b[i]))return false;return true}const bKeys=Object.keys(b);for(const key of bKeys)if(!partialMatchKey(a[key],b[key]))return false;return true}return false}var hasOwn=Object.prototype.hasOwnProperty;function replaceEqualDeep(a,b,depth=0){if(a===b)return a;if(depth>500)return b;const array=isPlainArray(a)&&isPlainArray(b);if(!array&&!(isPlainObject(a)&&isPlainObject(b)))return b;const aSize=(array?a:Object.keys(a)).length;const bItems=array?b:Object.keys(b);const bSize=bItems.length;const copy=array?new Array(bSize):{};let equalItems=0;for(let i=0;i<bSize;i++){const key=array?i:bItems[i];const aItem=a[key];const bItem=b[key];if(aItem===bItem){copy[key]=aItem;if(array?i<aSize:hasOwn.call(a,key))equalItems++;continue}if(aItem===null||bItem===null||typeof aItem!==`object`||typeof bItem!==`object`){copy[key]=bItem;continue}const v=replaceEqualDeep(aItem,bItem,depth+1);copy[key]=v;if(v===aItem)equalItems++}return aSize===bSize&&equalItems===aSize?a:copy}function shallowEqualObjects(a,b){if(!b||Object.keys(a).length!==Object.keys(b).length)return false;for(const key in a)if(a[key]!==b[key])return false;return true}function isPlainArray(value){return Array.isArray(value)&&value.length===Object.keys(value).length}function isPlainObject(o){if(!hasObjectPrototype(o))return false;const objectPrototype=Object.getPrototypeOf(o);const ctor=objectPrototype?.constructor;if(ctor===void 0)return true;if(typeof ctor!==`function`)return false;const prot=ctor.prototype;if(!hasObjectPrototype(prot))return false;if(!prot.hasOwnProperty(`isPrototypeOf`))return false;if(objectPrototype!==Object.prototype)return false;return true}function hasObjectPrototype(o){return Object.prototype.toString.call(o)===`[object Object]`}function sleep(timeout){return new Promise(resolve=>{timeoutManager.setTimeout(resolve,timeout)})}function replaceData(prevData,data,options){if(typeof options.structuralSharing===`function`)return options.structuralSharing(prevData,data);else if(options.structuralSharing!==false)return replaceEqualDeep(prevData,data);return data}function addToEnd(items,item,max=0){const newItems=[...items,item];return max&&newItems.length>max?newItems.slice(1):newItems}function addToStart(items,item,max=0){const newItems=[item,...items];return max&&newItems.length>max?newItems.slice(0,-1):newItems}var skipToken=Symbol();function ensureQueryFn(options,fetchOptions){if(!options.queryFn&&fetchOptions?.initialPromise)return()=>fetchOptions.initialPromise;if(!options.queryFn||options.queryFn===skipToken)return()=>Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`));return options.queryFn}function shouldThrowError(throwOnError,params){if(typeof throwOnError===`function`)return throwOnError(...params);return!!throwOnError}function addConsumeAwareSignal(object,getSignal,onCancelled){let consumed=false;let signal;Object.defineProperty(object,"signal",{enumerable:true,get:()=>{signal??=getSignal();if(consumed)return signal;consumed=true;if(signal.aborted)onCancelled();else signal.addEventListener(`abort`,onCancelled,{once:true});return signal}});return object}var isServerFn=()=>isServer$1;var isServer=()=>isServerFn();var environmentManager={isServer,setIsServer(isServerValue){isServerFn=isServerValue}};var Subscribable=class{constructor(){this.listeners=new Set;this.subscribe=this.subscribe.bind(this)}subscribe(listener){this.listeners.add(listener);this.onSubscribe();return()=>{this.listeners.delete(listener);this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var FocusManager=class extends Subscribable{#focused;#cleanup;#setup;constructor(){super();this.#setup=onFocus=>{if(typeof window!==`undefined`&&window.addEventListener){const listener=()=>onFocus();window.addEventListener(`visibilitychange`,listener,false);return()=>{window.removeEventListener(`visibilitychange`,listener)}}}}onSubscribe(){if(!this.#cleanup)this.setEventListener(this.#setup)}onUnsubscribe(){if(!this.hasListeners()){this.#cleanup?.();this.#cleanup=void 0}}setEventListener(setup){this.#setup=setup;this.#cleanup?.();this.#cleanup=setup(focused=>{if(typeof focused===`boolean`)this.setFocused(focused);else this.onFocus()})}setFocused(focused){if(this.#focused!==focused){this.#focused=focused;this.onFocus()}}onFocus(){const isFocused=this.isFocused();this.listeners.forEach(listener=>{listener(isFocused)})}isFocused(){if(typeof this.#focused===`boolean`)return this.#focused;return globalThis.document?.visibilityState!==`hidden`}};var focusManager=new FocusManager;var defaultScheduler=systemSetTimeoutZero;function createNotifyManager(){let queue=[];let transactions=0;let notifyFn=callback=>{callback()};let batchNotifyFn=callback=>{callback()};let scheduleFn=defaultScheduler;const schedule=callback=>{if(transactions)queue.push(callback);else scheduleFn(()=>{notifyFn(callback)})};const flush=()=>{const originalQueue=queue;queue=[];if(originalQueue.length)scheduleFn(()=>{batchNotifyFn(()=>{originalQueue.forEach(callback=>{notifyFn(callback)})})})};return{batch:callback=>{let result;transactions++;try{result=callback()}finally{transactions--;if(!transactions)flush()}return result},batchCalls:callback=>{return(...args)=>{schedule(()=>{callback(...args)})}},schedule,setNotifyFunction:fn=>{notifyFn=fn},setBatchNotifyFunction:fn=>{batchNotifyFn=fn},setScheduler:fn=>{scheduleFn=fn}}}var notifyManager=createNotifyManager();var OnlineManager=class extends Subscribable{#online=true;#cleanup;#setup;constructor(){super();this.#setup=onOnline=>{if(typeof window!==`undefined`&&window.addEventListener){const onlineListener=()=>onOnline(true);const offlineListener=()=>onOnline(false);window.addEventListener(`online`,onlineListener,false);window.addEventListener(`offline`,offlineListener,false);return()=>{window.removeEventListener(`online`,onlineListener);window.removeEventListener(`offline`,offlineListener)}}}}onSubscribe(){if(!this.#cleanup)this.setEventListener(this.#setup)}onUnsubscribe(){if(!this.hasListeners()){this.#cleanup?.();this.#cleanup=void 0}}setEventListener(setup){this.#setup=setup;this.#cleanup?.();this.#cleanup=setup(this.setOnline.bind(this))}setOnline(online){if(this.#online!==online){this.#online=online;this.listeners.forEach(listener=>{listener(online)})}}isOnline(){return this.#online}};var onlineManager=new OnlineManager;function defaultRetryDelay(failureCount){return Math.min(1e3*2**failureCount,3e4)}function canFetch(networkMode){return(networkMode??`online`)===`online`?onlineManager.isOnline():true}var CancelledError=class extends Error{constructor(options){super(`CancelledError`);this.revert=options?.revert;this.silent=options?.silent}};function createRetryer(config){let isRetryCancelled=false;let failureCount=0;let continueFn;let status=`pending`;let promiseResolve;let promiseReject;const promise=new Promise((resolve,reject)=>{promiseResolve=resolve;promiseReject=reject});promise.catch(noop);const isResolved=()=>status!==`pending`;const cancel=cancelOptions=>{if(!isResolved()){const error=new CancelledError(cancelOptions);reject(error);config.onCancel?.(error)}};const cancelRetry=()=>{isRetryCancelled=true};const continueRetry=()=>{isRetryCancelled=false};const canContinue=()=>focusManager.isFocused()&&(config.networkMode===`always`||onlineManager.isOnline())&&config.canRun();const canStart=()=>canFetch(config.networkMode)&&config.canRun();const resolve=value=>{if(!isResolved()){continueFn?.();status=`resolved`;promiseResolve(value)}};const reject=value=>{if(!isResolved()){continueFn?.();status=`rejected`;promiseReject(value)}};const pause=()=>{return new Promise(continueResolve=>{continueFn=value=>{if(isResolved()||canContinue())continueResolve(value)};config.onPause?.()}).then(()=>{continueFn=void 0;if(!isResolved())config.onContinue?.()})};const run=()=>{if(isResolved())return;let promiseOrValue;const initialPromise=failureCount===0?config.initialPromise:void 0;try{promiseOrValue=initialPromise??config.fn()}catch(error){promiseOrValue=Promise.reject(error)}Promise.resolve(promiseOrValue).then(resolve).catch(error=>{if(isResolved())return;const retry=config.retry??(isServer()?0:3);const retryDelay=config.retryDelay??defaultRetryDelay;const delay=typeof retryDelay===`function`?retryDelay(failureCount,error):retryDelay;const shouldRetry=retry===true||typeof retry===`number`&&failureCount<retry||typeof retry===`function`&&retry(failureCount,error);if(isRetryCancelled||!shouldRetry){reject(error);return}failureCount++;config.onFail?.(failureCount,error);sleep(delay).then(()=>{return canContinue()?void 0:pause()}).then(()=>{if(isRetryCancelled)reject(error);else run()})})};return{promise,status:()=>status,cancel,continue:()=>{continueFn?.();return promise},cancelRetry,continueRetry,canStart,start:()=>{if(canStart())run();else pause().then(run);return promise}}}var Removable=class{#gcTimeout;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout();if(isValidTimeout(this.gcTime))this.#gcTimeout=timeoutManager.setTimeout(()=>{this.optionalRemove()},this.gcTime)}updateGcTime(newGcTime){this.gcTime=Math.max(this.gcTime||0,newGcTime??(isServer()?Infinity:3e5))}clearGcTimeout(){if(this.#gcTimeout!==void 0){timeoutManager.clearTimeout(this.#gcTimeout);this.#gcTimeout=void 0}}};function infiniteQueryBehavior(pages){return{onFetch:(context,query)=>{const options=context.options;const direction=context.fetchOptions?.meta?.fetchMore?.direction;const oldPages=context.state.data?.pages||[];const oldPageParams=context.state.data?.pageParams||[];let result={pages:[],pageParams:[]};let currentPage=0;const fetchFn=async()=>{let cancelled=false;const addSignalProperty=object=>{addConsumeAwareSignal(object,()=>context.signal,()=>cancelled=true)};const queryFn=ensureQueryFn(context.options,context.fetchOptions);const fetchPage=async(data,param,previous)=>{if(cancelled)return Promise.reject(context.signal.reason);if(param==null&&data.pages.length)return Promise.resolve(data);const createQueryFnContext=()=>{const queryFnContext={client:context.client,queryKey:context.queryKey,pageParam:param,direction:previous?`backward`:`forward`,meta:context.options.meta};addSignalProperty(queryFnContext);return queryFnContext};const queryFnContext=createQueryFnContext();const page=await queryFn(queryFnContext);const{maxPages}=context.options;const addTo=previous?addToStart:addToEnd;return{pages:addTo(data.pages,page,maxPages),pageParams:addTo(data.pageParams,param,maxPages)}};if(direction&&oldPages.length){const previous=direction===`backward`;const pageParamFn=previous?getPreviousPageParam:getNextPageParam;const oldData={pages:oldPages,pageParams:oldPageParams};result=await fetchPage(oldData,pageParamFn(options,oldData),previous)}else{const remainingPages=pages??oldPages.length;do{const param=currentPage===0?oldPageParams[0]??options.initialPageParam:getNextPageParam(options,result);if(currentPage>0&&param==null)break;result=await fetchPage(result,param);currentPage++}while(currentPage<remainingPages)}return result};if(context.options.persister)context.fetchFn=()=>{return context.options.persister?.(fetchFn,{client:context.client,queryKey:context.queryKey,meta:context.options.meta,signal:context.signal},query)};else context.fetchFn=fetchFn}}}function getNextPageParam(options,{pages,pageParams}){const lastIndex=pages.length-1;return pages.length>0?options.getNextPageParam(pages[lastIndex],pages,pageParams[lastIndex],pageParams):void 0}function getPreviousPageParam(options,{pages,pageParams}){return pages.length>0?options.getPreviousPageParam?.(pages[0],pages,pageParams[0],pageParams):void 0}var Query=class extends Removable{#queryType;#initialState;#revertState;#cache;#client;#retryer;#defaultOptions;#abortSignalConsumed;constructor(config){super();this.#abortSignalConsumed=false;this.#defaultOptions=config.defaultOptions;this.setOptions(config.options);this.observers=[];this.#client=config.client;this.#cache=this.#client.getQueryCache();this.queryKey=config.queryKey;this.queryHash=config.queryHash;this.#initialState=getDefaultState$1(this.options);this.state=config.state??this.#initialState;this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#queryType}get promise(){return this.#retryer?.promise}setOptions(options){this.options={...this.#defaultOptions,...options};if(options?._type)this.#queryType=options._type;this.updateGcTime(this.options.gcTime);if(this.state&&this.state.data===void 0){const defaultState=getDefaultState$1(this.options);if(defaultState.data!==void 0){this.setState(successState(defaultState.data,defaultState.dataUpdatedAt));this.#initialState=defaultState}}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus===`idle`)this.#cache.remove(this)}setData(newData,options){const data=replaceData(this.state.data,newData,this.options);this.#dispatch({data,type:`success`,dataUpdatedAt:options?.updatedAt,manual:options?.manual});return data}setState(state){this.#dispatch({type:`setState`,state})}cancel(options){const promise=this.#retryer?.promise;this.#retryer?.cancel(options);return promise?promise.then(noop).catch(noop):Promise.resolve()}destroy(){super.destroy();this.cancel({silent:true})}get resetState(){return this.#initialState}reset(){this.destroy();this.setState(this.resetState)}isActive(){return this.observers.some(observer=>resolveQueryValue(observer.options.enabled,this)!==false)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===skipToken||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){if(this.getObserversCount()>0)return this.observers.some(observer=>resolveQueryValue(observer.options.staleTime,this)===`static`);return false}isStale(){if(this.getObserversCount()>0)return this.observers.some(observer=>observer.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(staleTime=0){if(this.state.data===void 0)return true;if(staleTime===`static`)return false;if(this.state.isInvalidated)return true;return!timeUntilStale(this.state.dataUpdatedAt,staleTime)}onFocus(){this.observers.find(x=>x.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:false});this.#retryer?.continue()}onOnline(){this.observers.find(x=>x.shouldFetchOnReconnect())?.refetch({cancelRefetch:false});this.#retryer?.continue()}addObserver(observer){if(!this.observers.includes(observer)){this.observers.push(observer);this.clearGcTimeout();this.#cache.notify({type:`observerAdded`,query:this,observer})}}removeObserver(observer){const index=this.observers.indexOf(observer);if(index!==-1){this.observers.splice(index,1);if(!this.observers.length){if(this.#retryer){if(this.#abortSignalConsumed||this.state.fetchStatus===`paused`&&this.state.status===`pending`)this.#retryer.cancel({revert:true});else this.#retryer.cancelRetry()}this.scheduleGc()}this.#cache.notify({type:`observerRemoved`,query:this,observer})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#dispatch({type:`invalidate`})}async fetch(options,fetchOptions){if(this.state.fetchStatus!==`idle`&&this.#retryer?.status()!==`rejected`){if(this.state.data!==void 0&&fetchOptions?.cancelRefetch)this.cancel({silent:true});else if(this.#retryer){this.#retryer.continueRetry();return this.#retryer.promise}}if(options)this.setOptions(options);if(!this.options.queryFn){const observer=this.observers.find(x=>x.options.queryFn);if(observer)this.setOptions(observer.options)}const abortController=new AbortController;const addSignalProperty=object=>{Object.defineProperty(object,"signal",{enumerable:true,get:()=>{this.#abortSignalConsumed=true;return abortController.signal}})};const fetchFn=()=>{const queryFn=ensureQueryFn(this.options,fetchOptions);const createQueryFnContext=()=>{const queryFnContext={client:this.#client,queryKey:this.queryKey,meta:this.meta};addSignalProperty(queryFnContext);return queryFnContext};const queryFnContext=createQueryFnContext();this.#abortSignalConsumed=false;if(this.options.persister)return this.options.persister(queryFn,queryFnContext,this);return queryFn(queryFnContext)};const createFetchContext=()=>{const context={fetchOptions,options:this.options,queryKey:this.queryKey,client:this.#client,state:this.state,fetchFn};addSignalProperty(context);return context};const context=createFetchContext();(this.#queryType===`infinite`?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(context,this);this.#revertState=this.state;if(this.state.fetchStatus===`idle`||this.state.fetchMeta!==context.fetchOptions?.meta)this.#dispatch({type:`fetch`,meta:context.fetchOptions?.meta});const retryer=this.#retryer=createRetryer({initialPromise:fetchOptions?.initialPromise,fn:context.fetchFn,onCancel:error=>{if(error instanceof CancelledError&&error.revert)this.setState({...this.#revertState,fetchStatus:`idle`});abortController.abort()},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue:()=>{this.#dispatch({type:`continue`})},retry:context.options.retry,retryDelay:context.options.retryDelay,networkMode:context.options.networkMode,canRun:()=>true});try{const data=await retryer.start();if(data===void 0)throw new Error(`${this.queryHash} data is undefined`);this.setData(data);this.#cache.config.onSuccess?.(data,this);this.#cache.config.onSettled?.(data,this.state.error,this);return data}catch(error){if(error instanceof CancelledError){if(error.silent)return this.#retryer.promise;else if(error.revert){if(this.state.data===void 0)throw error;return this.state.data}}this.#dispatch({type:`error`,error});this.#cache.config.onError?.(error,this);this.#cache.config.onSettled?.(this.state.data,error,this);throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.scheduleGc()}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,fetchFailureCount:action.failureCount,fetchFailureReason:action.error};case`pause`:return{...state,fetchStatus:`paused`};case`continue`:return{...state,fetchStatus:`fetching`};case`fetch`:return{...state,...fetchState(state.data,this.options),fetchMeta:action.meta??null};case`success`:const newState={...state,...successState(action.data,action.dataUpdatedAt),dataUpdateCount:state.dataUpdateCount+1,...!action.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};this.#revertState=action.manual?newState:void 0;return newState;case`error`:const error=action.error;return{...state,error,errorUpdateCount:state.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:state.fetchFailureCount+1,fetchFailureReason:error,fetchStatus:`idle`,status:`error`,isInvalidated:true};case`invalidate`:return{...state,isInvalidated:true};case`setState`:return{...state,...action.state}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.observers.slice().forEach(observer=>{observer.onQueryUpdate()});this.#cache.notify({query:this,type:`updated`,action})})}};function fetchState(data,options){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(options.networkMode)?`fetching`:`paused`,...data===void 0&&{error:null,status:`pending`}}}function successState(data,dataUpdatedAt){return{data,dataUpdatedAt:dataUpdatedAt??Date.now(),error:null,isInvalidated:false,status:`success`}}function getDefaultState$1(options){const data=typeof options.initialData===`function`?options.initialData():options.initialData;const hasData=data!==void 0;const initialDataUpdatedAt=hasData?typeof options.initialDataUpdatedAt===`function`?options.initialDataUpdatedAt():options.initialDataUpdatedAt:0;return{data,dataUpdateCount:0,dataUpdatedAt:hasData?initialDataUpdatedAt??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:false,status:hasData?`success`:`pending`,fetchStatus:`idle`}}var QueryObserver=class extends Subscribable{#client;#currentQuery=void 0;#currentQueryInitialState=void 0;#currentResult=void 0;#currentResultState;#currentResultOptions;#selectError;#selectFn;#selectResult;#lastQueryWithDefinedData;#staleTimeoutId;#refetchIntervalId;#currentRefetchInterval;#trackedProps=new Set;constructor(client,options){super();this.options=options;this.#client=client;this.#selectError=null;this.bindMethods();this.setOptions(options)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){if(this.listeners.size===1){this.#currentQuery.addObserver(this);if(shouldFetchOnMount(this.#currentQuery,this.options))this.#executeFetch();else this.updateResult();this.#updateTimers()}}onUnsubscribe(){if(!this.hasListeners())this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set;this.#clearStaleTimeout();this.#clearRefetchInterval();this.#currentQuery.removeObserver(this)}setOptions(options){const prevOptions=this.options;const prevQuery=this.#currentQuery;this.options=this.#client.defaultQueryOptions(options);if(this.options.enabled!==void 0&&typeof this.options.enabled!==`boolean`&&typeof this.options.enabled!==`function`&&typeof resolveQueryValue(this.options.enabled,this.#currentQuery)!==`boolean`)throw new Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#updateQuery();this.#currentQuery.setOptions(this.options);if(prevOptions._defaulted&&!shallowEqualObjects(this.options,prevOptions))this.#client.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#currentQuery,observer:this});const mounted=this.hasListeners();if(mounted&&shouldFetchOptionally(this.#currentQuery,prevQuery,this.options,prevOptions))this.#executeFetch();this.updateResult();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||resolveQueryValue(this.options.staleTime,this.#currentQuery)!==resolveQueryValue(prevOptions.staleTime,this.#currentQuery)))this.#updateStaleTimeout();const nextRefetchInterval=this.#computeRefetchInterval();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||nextRefetchInterval!==this.#currentRefetchInterval))this.#updateRefetchInterval(nextRefetchInterval)}getOptimisticResult(options){const query=this.#client.getQueryCache().build(this.#client,options);const result=this.createResult(query,options);if(!shallowEqualObjects(this.getCurrentResult(),result)){this.#currentResult=result;this.#currentResultOptions=this.options;this.#currentResultState=this.#currentQuery.state}return result}getCurrentResult(){return this.#currentResult}trackResult(result,onPropTracked){return new Proxy(result,{get:(target,key)=>{this.trackProp(key);onPropTracked?.(key);return Reflect.get(target,key)}})}trackProp(key){this.#trackedProps.add(key)}getCurrentQuery(){return this.#currentQuery}refetch({...options}={}){return this.fetch({...options})}fetchOptimistic(options){const defaultedOptions=this.#client.defaultQueryOptions(options);const query=this.#client.getQueryCache().build(this.#client,defaultedOptions);let unsubscribe=()=>{};let resolveEarly;const cachePromise=new Promise(resolve=>{resolveEarly=resolve;unsubscribe=this.#client.getQueryCache().subscribe(event=>{if(event.type===`updated`&&event.query.queryHash===query.queryHash&&query.state.data!==void 0){unsubscribe();resolve(this.createResult(query,defaultedOptions))}})});return Promise.race([query.fetch().then(()=>{const result=this.createResult(query,defaultedOptions);resolveEarly?.(result);return result}).finally(()=>{unsubscribe()}),cachePromise])}fetch(fetchOptions){return this.#executeFetch({...fetchOptions,cancelRefetch:fetchOptions.cancelRefetch??true}).then(()=>{this.updateResult();return this.#currentResult})}#executeFetch(fetchOptions){this.#updateQuery();let promise=this.#currentQuery.fetch(this.options,fetchOptions);if(!fetchOptions?.throwOnError)promise=promise.catch(noop);return promise}#shouldScheduleTimer(timeout){return!isServer()&&resolveQueryValue(this.options.enabled,this.#currentQuery)!==false&&isValidTimeout(timeout)}#updateStaleTimeout(){this.#clearStaleTimeout();const staleTime=resolveQueryValue(this.options.staleTime,this.#currentQuery);if(this.#currentResult.isStale||!this.#shouldScheduleTimer(staleTime))return;const timeout=timeUntilStale(this.#currentResult.dataUpdatedAt,staleTime)+1;this.#staleTimeoutId=timeoutManager.setTimeout(()=>{if(!this.#currentResult.isStale)this.updateResult()},timeout)}#computeRefetchInterval(){return resolveQueryValue(this.options.refetchInterval,this.#currentQuery)??false}#updateRefetchInterval(nextInterval){this.#clearRefetchInterval();this.#currentRefetchInterval=nextInterval;if(this.#currentRefetchInterval===0||!this.#shouldScheduleTimer(this.#currentRefetchInterval))return;this.#refetchIntervalId=timeoutManager.setInterval(()=>{if(this.options.refetchIntervalInBackground||focusManager.isFocused())this.#executeFetch()},this.#currentRefetchInterval)}#updateTimers(){this.#updateStaleTimeout();this.#updateRefetchInterval(this.#computeRefetchInterval())}#clearStaleTimeout(){if(this.#staleTimeoutId!==void 0){timeoutManager.clearTimeout(this.#staleTimeoutId);this.#staleTimeoutId=void 0}}#clearRefetchInterval(){if(this.#refetchIntervalId!==void 0){timeoutManager.clearInterval(this.#refetchIntervalId);this.#refetchIntervalId=void 0}}createResult(query,options){const prevQuery=this.#currentQuery;const prevOptions=this.options;const prevResult=this.#currentResult;const prevResultState=this.#currentResultState;const prevResultOptions=this.#currentResultOptions;const queryInitialState=query!==prevQuery?query.state:this.#currentQueryInitialState;const{state}=query;let newState={...state};let isPlaceholderData=false;let data;if(options._optimisticResults){const mounted=this.hasListeners();const fetchOnMount=!mounted&&shouldFetchOnMount(query,options);const fetchOptionally=mounted&&shouldFetchOptionally(query,prevQuery,options,prevOptions);if(fetchOnMount||fetchOptionally)newState={...newState,...fetchState(state.data,query.options)};if(options._optimisticResults===`isRestoring`)newState.fetchStatus=`idle`}let{error,errorUpdatedAt,status}=newState;data=newState.data;let skipSelect=false;if(options.placeholderData!==void 0&&data===void 0&&status===`pending`){let placeholderData;if(prevResult?.isPlaceholderData&&options.placeholderData===prevResultOptions?.placeholderData){placeholderData=prevResult.data;skipSelect=true}else placeholderData=typeof options.placeholderData===`function`?options.placeholderData(this.#lastQueryWithDefinedData?.state.data,this.#lastQueryWithDefinedData):options.placeholderData;if(placeholderData!==void 0){status=`success`;data=replaceData(prevResult?.data,placeholderData,options);isPlaceholderData=true}}if(options.select&&data!==void 0&&!skipSelect){if(prevResult&&data===prevResultState?.data&&options.select===this.#selectFn)data=this.#selectResult;else try{this.#selectFn=options.select;data=options.select(data);data=replaceData(prevResult?.data,data,options);this.#selectResult=data;this.#selectError=null}catch(selectError){this.#selectError=selectError}}else if(data===void 0)this.#selectError=null;if(this.#selectError){error=this.#selectError;data=this.#selectResult;errorUpdatedAt=Date.now();status=`error`;isPlaceholderData=false}const isFetching=newState.fetchStatus===`fetching`;const isPending=status===`pending`;const isError=status===`error`;const isLoading=isPending&&isFetching;const hasData=data!==void 0;return{status,fetchStatus:newState.fetchStatus,isPending,isSuccess:status===`success`,isError,isInitialLoading:isLoading,isLoading,data,dataUpdatedAt:newState.dataUpdatedAt,error,errorUpdatedAt,failureCount:newState.fetchFailureCount,failureReason:newState.fetchFailureReason,errorUpdateCount:newState.errorUpdateCount,isFetched:query.isFetched(),isFetchedAfterMount:newState.dataUpdateCount>queryInitialState.dataUpdateCount||newState.errorUpdateCount>queryInitialState.errorUpdateCount,isFetching,isRefetching:isFetching&&!isPending,isLoadingError:isError&&!hasData,isPaused:newState.fetchStatus===`paused`,isPlaceholderData,isRefetchError:isError&&hasData,isStale:isStale(query,options),refetch:this.refetch,isEnabled:resolveQueryValue(options.enabled,query)!==false}}updateResult(){const prevResult=this.#currentResult;const nextResult=this.createResult(this.#currentQuery,this.options);this.#currentResultState=this.#currentQuery.state;this.#currentResultOptions=this.options;if(this.#currentResultState.data!==void 0)this.#lastQueryWithDefinedData=this.#currentQuery;if(shallowEqualObjects(nextResult,prevResult))return;this.#currentResult=nextResult;const shouldNotifyListeners=()=>{if(!prevResult)return true;const{notifyOnChangeProps}=this.options;const notifyOnChangePropsValue=typeof notifyOnChangeProps===`function`?notifyOnChangeProps():notifyOnChangeProps;if(notifyOnChangePropsValue===`all`||!notifyOnChangePropsValue&&!this.#trackedProps.size)return true;const includedProps=new Set(notifyOnChangePropsValue??this.#trackedProps);if(this.options.throwOnError)includedProps.add(`error`);return Object.keys(this.#currentResult).some(key=>{const typedKey=key;return this.#currentResult[typedKey]!==prevResult[typedKey]&&includedProps.has(typedKey)})};const notifyListeners=shouldNotifyListeners();notifyManager.batch(()=>{if(notifyListeners)this.listeners.forEach(listener=>{listener(this.#currentResult)});this.#client.getQueryCache().notify({query:this.#currentQuery,type:`observerResultsUpdated`})})}#updateQuery(){const query=this.#client.getQueryCache().build(this.#client,this.options);if(query===this.#currentQuery)return;const prevQuery=this.#currentQuery;this.#currentQuery=query;this.#currentQueryInitialState=query.state;if(this.hasListeners()){prevQuery?.removeObserver(this);query.addObserver(this)}}onQueryUpdate(){this.updateResult();if(this.hasListeners())this.#updateTimers()}};function shouldLoadOnMount(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.state.data===void 0&&!(query.state.status===`error`&&resolveQueryValue(options.retryOnMount,query)===false)}function shouldFetchOnMount(query,options){return shouldLoadOnMount(query,options)||query.state.data!==void 0&&shouldFetchOn(query,options,options.refetchOnMount)}function shouldFetchOn(query,options,field){if(resolveQueryValue(options.enabled,query)!==false&&resolveQueryValue(options.staleTime,query)!==`static`){const value=resolveQueryValue(field,query);return value===`always`||value!==false&&isStale(query,options)}return false}function shouldFetchOptionally(query,prevQuery,options,prevOptions){return(query!==prevQuery||resolveQueryValue(prevOptions.enabled,query)===false)&&(!options.suspense||query.state.status!==`error`)&&isStale(query,options)}function isStale(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.isStaleByTime(resolveQueryValue(options.staleTime,query))}var Mutation=class extends Removable{#client;#observers;#mutationCache;#retryer;constructor(config){super();this.#client=config.client;this.mutationId=config.mutationId;this.#mutationCache=config.mutationCache;this.#observers=[];this.state=config.state||getDefaultState();this.setOptions(config.options);this.scheduleGc()}setOptions(options){this.options=options;this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(observer){if(!this.#observers.includes(observer)){this.#observers.push(observer);this.clearGcTimeout();this.#mutationCache.notify({type:`observerAdded`,mutation:this,observer})}}removeObserver(observer){this.#observers=this.#observers.filter(x=>x!==observer);this.scheduleGc();this.#mutationCache.notify({type:`observerRemoved`,mutation:this,observer})}optionalRemove(){if(!this.#observers.length){if(this.state.status===`pending`)this.scheduleGc();else this.#mutationCache.remove(this)}}continue(){return this.#retryer?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(variables){const onContinue=()=>{this.#dispatch({type:`continue`})};const mutationFnContext={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};const retryer=this.#retryer=createRetryer({fn:()=>{if(!this.options.mutationFn)return Promise.reject(new Error(`No mutationFn found`));return this.options.mutationFn(variables,mutationFnContext)},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#mutationCache.canRun(this)});const restored=this.state.status===`pending`;const isPaused=!retryer.canStart();try{if(restored)onContinue();else{this.#dispatch({type:`pending`,variables,isPaused});if(this.#mutationCache.config.onMutate)await this.#mutationCache.config.onMutate(variables,this,mutationFnContext);const context=await this.options.onMutate?.(variables,mutationFnContext);if(context!==this.state.context)this.#dispatch({type:`pending`,context,variables,isPaused})}const data=await retryer.start();await this.#mutationCache.config.onSuccess?.(data,variables,this.state.context,this,mutationFnContext);await this.options.onSuccess?.(data,variables,this.state.context,mutationFnContext);await this.#mutationCache.config.onSettled?.(data,null,this.state.variables,this.state.context,this,mutationFnContext);await this.options.onSettled?.(data,null,variables,this.state.context,mutationFnContext);this.#dispatch({type:`success`,data});return data}catch(error){try{await this.#mutationCache.config.onError?.(error,variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onError?.(error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.#mutationCache.config.onSettled?.(void 0,error,this.state.variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}this.#dispatch({type:`error`,error});throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.#mutationCache.runNext(this)}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,failureCount:action.failureCount,failureReason:action.error};case`pause`:return{...state,isPaused:true};case`continue`:return{...state,isPaused:false};case`pending`:return{...state,context:action.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:action.isPaused,status:`pending`,variables:action.variables,submittedAt:Date.now()};case`success`:return{...state,data:action.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:false};case`error`:return{...state,data:void 0,error:action.error,failureCount:state.failureCount+1,failureReason:action.error,isPaused:false,status:`error`}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.#observers.forEach(observer=>{observer.onMutationUpdate(action)});this.#mutationCache.notify({mutation:this,type:`updated`,action})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:false,status:`idle`,variables:void 0,submittedAt:0}}var MutationObserver=class extends Subscribable{#client;#currentResult=void 0;#currentMutation;#mutateOptions;constructor(client,options){super();this.#client=client;this.setOptions(options);this.bindMethods();this.#updateResult()}bindMethods(){this.mutate=this.mutate.bind(this);this.reset=this.reset.bind(this)}setOptions(options){const prevOptions=this.options;this.options=this.#client.defaultMutationOptions(options);if(!shallowEqualObjects(this.options,prevOptions))this.#client.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#currentMutation,observer:this});if(prevOptions?.mutationKey&&this.options.mutationKey&&hashKey(prevOptions.mutationKey)!==hashKey(this.options.mutationKey))this.reset();else if(this.#currentMutation?.state.status===`pending`)this.#currentMutation.setOptions(this.options)}onSubscribe(){if(this.listeners.size===1&&this.#currentMutation){this.#currentMutation.addObserver(this);this.#updateResult()}}onUnsubscribe(){if(!this.hasListeners())this.#currentMutation?.removeObserver(this)}onMutationUpdate(action){this.#updateResult();this.#notify(action)}getCurrentResult(){return this.#currentResult}reset(){this.#currentMutation?.removeObserver(this);this.#currentMutation=void 0;this.#updateResult();this.#notify()}mutate(variables,options){this.#mutateOptions=options;this.#currentMutation?.removeObserver(this);this.#currentMutation=this.#client.getMutationCache().build(this.#client,this.options);this.#currentMutation.addObserver(this);return this.#currentMutation.execute(variables)}#updateResult(){const state=this.#currentMutation?.state??getDefaultState();this.#currentResult={...state,isPending:state.status===`pending`,isSuccess:state.status===`success`,isError:state.status===`error`,isIdle:state.status===`idle`,mutate:this.mutate,reset:this.reset}}#notify(action){notifyManager.batch(()=>{if(this.#mutateOptions&&this.hasListeners()){const variables=this.#currentResult.variables;const onMutateResult=this.#currentResult.context;const context={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};if(action?.type===`success`){try{this.#mutateOptions.onSuccess?.(action.data,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(action.data,null,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}else if(action?.type===`error`){try{this.#mutateOptions.onError?.(action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(void 0,action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}}this.listeners.forEach(listener=>{listener(this.#currentResult)})})}};function useBaseQuery(Observer,options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{let resolvedOptions=options;if(typeof resolvedOptions===`function`)resolvedOptions=resolvedOptions();const clonedOptions=cloneDeepUnref(resolvedOptions);if(typeof clonedOptions.enabled===`function`)clonedOptions.enabled=clonedOptions.enabled();const defaulted=client.defaultQueryOptions(clonedOptions);defaulted._optimisticResults=client.isRestoring?.value?`isRestoring`:`optimistic`;return defaulted});const observer=new Observer(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());let unsubscribe=()=>{};if(client.isRestoring)watch(client.isRestoring,isRestoring=>{if(!isRestoring){unsubscribe();unsubscribe=observer.subscribe(result=>{updateState(state,result)})}},{immediate:true});const updater=()=>{observer.setOptions(defaultedOptions.value);updateState(state,observer.getCurrentResult())};watch(defaultedOptions,updater);onScopeDispose(()=>{unsubscribe()});const refetch=(...args)=>{updater();return state.refetch(...args)};const suspense=()=>{return new Promise((resolve,reject)=>{let stopWatch=()=>{};const run=()=>{if(defaultedOptions.value.enabled!==false){observer.setOptions(defaultedOptions.value);const optimisticResult=observer.getOptimisticResult(defaultedOptions.value);if(optimisticResult.isStale){stopWatch();observer.fetchOptimistic(defaultedOptions.value).then(resolve,error=>{if(shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))reject(error);else resolve(observer.getCurrentResult())})}else{stopWatch();resolve(optimisticResult)}}};run();stopWatch=watch(defaultedOptions,run)})};watch(()=>state.error,error=>{if(state.isError&&!state.isFetching&&shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))throw error});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const object=toRefs(readonlyState);for(const key in state)if(typeof state[key]===`function`)object[key]=state[key];object.suspense=suspense;object.refetch=refetch;return object}function useQuery(options,queryClient){return useBaseQuery(QueryObserver,options,queryClient)}function useMutation(options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{const resolvedOptions=typeof options===`function`?options():options;return client.defaultMutationOptions(cloneDeepUnref(resolvedOptions))});const observer=new MutationObserver(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());const unsubscribe=observer.subscribe(result=>{updateState(state,result)});const mutate=(...args)=>{observer.mutate(args[0],args[1]).catch(()=>{})};watch(defaultedOptions,()=>{observer.setOptions(defaultedOptions.value)});onScopeDispose(()=>{unsubscribe()});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const resultRefs=toRefs(readonlyState);watch(()=>state.error,error=>{if(error&&shouldThrowError(defaultedOptions.value.throwOnError,[error]))throw error});return{...resultRefs,mutate,mutateAsync:state.mutate,reset:state.reset}}function resolveEnabledRef(value){if(value===void 0)return true;return Boolean(toValue(value))}function resolveTextRef(value){return String(unref(value)||``).trim()}var OWNERSHIP_FILTER_VALUES=ROUTE_VISIBILITY_TOKENS;var SCOPED_OWNERSHIP_FILTER_SET=new Set([ROUTE_VISIBILITY_WORKSPACE,ROUTE_VISIBILITY_WORKSPACE_USER]);var ACCESS_MODE_VALUES=Object.freeze([`auto`,`always`,`never`]);function asPlainObject(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function emptyRecord(){return{}}function normalizePermissions(value){if(Array.isArray(value))return value.map(entry=>String(entry||``).trim()).filter(Boolean);const one=String(value||``).trim();return one?[one]:[]}function resolvePermissionAccess(access,normalizedPermissions=[]){if(normalizedPermissions.length<1)return true;return access.canAny(normalizedPermissions)}function normalizeAccessMode(value=`auto`){const normalized=String(value||`auto`).trim().toLowerCase();if(ACCESS_MODE_VALUES.includes(normalized))return normalized;throw new TypeError(`access must be one of: ${ACCESS_MODE_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveAccessModeEnabled(accessMode=`auto`,{hasPermissionRequirements=false}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`always`)return true;if(normalizedMode===`never`)return false;return hasPermissionRequirements===true}function ensureAccessModeCompatibility({accessMode=`auto`,hasPermissionRequirements=false,caller=`http-web`}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`never`&&hasPermissionRequirements)throw new TypeError(`${caller} cannot use access:\"never\" when permission requirements are configured.`);return normalizedMode}function resolveApiSuffix(apiSuffix,context={}){if(typeof apiSuffix===`function`)return resolveTextRef(apiSuffix(context));return resolveTextRef(apiSuffix)}function resolveEnabled(value,context={}){if(typeof value===`function`)return Boolean(value(context));return resolveEnabledRef(value)}function normalizeOwnershipFilter(value=ROUTE_VISIBILITY_WORKSPACE){const normalized=String(value||`workspace`).trim().toLowerCase();if(OWNERSHIP_FILTER_VALUES.includes(normalized))return normalized;throw new TypeError(`ownershipFilter must be one of: ${OWNERSHIP_FILTER_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function isScopedOwnershipFilter(ownershipFilter){return SCOPED_OWNERSHIP_FILTER_SET.has(ownershipFilter)}function resolveQueryKey(queryKeyFactory,{surfaceId=``,scopeParamValue=``,ownershipFilter=ROUTE_VISIBILITY_WORKSPACE}={}){if(isScopedOwnershipFilter(ownershipFilter))return queryKeyFactory(surfaceId,scopeParamValue,ownershipFilter);return queryKeyFactory(surfaceId,ownershipFilter)}function normalizeRealtimeOptions(value={}){if(value===null||value===void 0||value===false)return{};if(typeof value!==`object`||Array.isArray(value))throw new TypeError(`realtime must be an object when configured.`);return value}function toQueryKeyList(value){const resolved=toValue(value);if(!Array.isArray(resolved)||resolved.length<1)return[];if(Array.isArray(resolved[0]))return resolved.filter(entry=>Array.isArray(entry)&&entry.length>0).map(entry=>Object.freeze([...entry]));return[Object.freeze([...resolved])]}var followUpReads=new WeakMap;function refetchAfterCurrentRead(queryClient,query){if(followUpReads.has(query))return followUpReads.get(query);const read=()=>queryClient.refetchQueries({queryKey:query.queryKey,exact:true},{cancelRefetch:false});if(query.state.fetchStatus!==`fetching`)return read();const followUp=read().then(()=>{followUpReads.delete(query);return read()});followUpReads.set(query,followUp);return followUp}async function refreshQueriesWithoutCancelling(queryClient,queryKey){await queryClient.invalidateQueries({queryKey,refetchType:`none`});await nextTick();await Promise.all(queryClient.getQueryCache().findAll({queryKey,type:`active`}).map(query=>refetchAfterCurrentRead(queryClient,query)))}function useRealtimeQueryInvalidation({event=``,enabled=true,matches,queryKey=null,onEvent}){const queryClient=useQueryClient();const normalizedEvent=computed(()=>normalizeText(unref(event)));const active=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedEvent.value));return{active:useRealtimeEvent({event:normalizedEvent,enabled:active,matches,onEvent:async context=>{if(onEvent)await onEvent(context);const keys=toQueryKeyList(queryKey);for(const key of keys)await refreshQueriesWithoutCancelling(queryClient,key)}}).active}}function useOperationRealtime({realtime=null,queryKey=null,enabled=true}={}){const source=normalizeRealtimeOptions(realtime);const eventList=[];if(Object.hasOwn(source,`event`)){const normalizedEvent=normalizeText(source.event);if(normalizedEvent)eventList.push(normalizedEvent)}if(Object.hasOwn(source,`events`)){if(!Array.isArray(source.events))throw new TypeError(`realtime.events must be an array when configured.`);for(const entry of source.events){const normalizedEvent=normalizeText(entry);if(!normalizedEvent||eventList.includes(normalizedEvent))continue;eventList.push(normalizedEvent)}}if(eventList.length<1)return null;const{matches,onEvent}=source;const resolvedQueryKey=Object.hasOwn(source,`queryKey`)?source.queryKey:queryKey;const active=computed(()=>{const sourceEnabled=Object.hasOwn(source,`enabled`)?source.enabled:true;return resolveEnabledRef(enabled)&&resolveEnabledRef(sourceEnabled)});const bindings=eventList.map(event=>useRealtimeQueryInvalidation({event,enabled:active,matches,queryKey:resolvedQueryKey,onEvent}));return{active:computed(()=>bindings.some(binding=>Boolean(binding.active.value)))}}function hasResolvedQueryData({query=null,data=null}={}){const querySucceeded=Boolean(unref(query?.isSuccess));const hasDataPayload=unref(data)!=null;return querySucceeded||hasDataPayload}function mergeQueryMeta(queryOptions=null,meta={}){const sourceOptions=isRecord(queryOptions)?queryOptions:{};const sourceMeta=isRecord(sourceOptions.meta)?sourceOptions.meta:{};return{...sourceOptions,meta:{...sourceMeta,...meta,jskit:{...isRecord(sourceMeta.jskit)?sourceMeta.jskit:{},...isRecord(meta.jskit)?meta.jskit:{}}}}}var REQUEST_RECOVERY_META_KEYS=Object.freeze({label:`requestRecoveryLabel`,source:`requestRecoverySource`,dedupeKey:`requestRecoveryDedupeKey`,method:`requestRecoveryMethod`,dedupeWindowMs:`requestRecoveryDedupeWindowMs`});var DISABLED_REQUEST_RECOVERY_META=Object.freeze({jskit:Object.freeze({requestRecovery:false})});function normalizeRequestRecoveryInput(requestRecovery=null){if(typeof requestRecovery===`string`)return{label:requestRecovery};const source=isRecord(requestRecovery)?requestRecovery:{};for(const key of Object.keys(source))if(key!==`enabled`&&!Object.hasOwn(REQUEST_RECOVERY_META_KEYS,key))throw new TypeError(`requestRecovery.${key} is not supported; use ${Object.keys(REQUEST_RECOVERY_META_KEYS).join(`, `)} or enabled.`);return source}function normalizeRequestRecoveryValue(name,value){if(name===`dedupeWindowMs`){const numberValue=value==null||value===``?NaN:Number(value);return Number.isFinite(numberValue)?Math.max(0,numberValue):null}const text=normalizeText(value);if(!text)return null;return name===`method`?text.toUpperCase():text}function buildRequestRecoveryMeta(requestRecovery=null,defaults={}){if(requestRecovery===false)return DISABLED_REQUEST_RECOVERY_META;const source=normalizeRequestRecoveryInput(requestRecovery);if(source.enabled===false)return DISABLED_REQUEST_RECOVERY_META;const fallback=isRecord(defaults)?defaults:{};const jskit={};for(const[name,metaKey]of Object.entries(REQUEST_RECOVERY_META_KEYS)){const value=normalizeRequestRecoveryValue(name,source[name])??normalizeRequestRecoveryValue(name,fallback[name]);if(value!==null)jskit[metaKey]=value}return Object.keys(jskit).length>0?{jskit}:{}}function mergeRequestRecoveryQueryMeta(queryOptions=null,requestRecovery=null,defaults={}){const sourceOptions=isRecord(queryOptions)?queryOptions:{};let meta;if(requestRecovery==null){const presetMeta=isRecord(sourceOptions.meta?.jskit)?sourceOptions.meta.jskit:{};if(presetMeta.requestRecovery===false)return sourceOptions;const fallback=isRecord(defaults)?defaults:{};const unsetDefaults={};for(const[name,metaKey]of Object.entries(REQUEST_RECOVERY_META_KEYS))if(!hasValue(presetMeta[metaKey]))unsetDefaults[name]=fallback[name];meta=buildRequestRecoveryMeta(null,unsetDefaults)}else meta=buildRequestRecoveryMeta(requestRecovery,defaults);return Object.keys(meta).length>0?mergeQueryMeta(sourceOptions,meta):sourceOptions}function buildEndpointReadRequestOptions({method=`GET`,query=null,transport=null}={}){const requestOptions={method:String(method||`GET`).toUpperCase()};const normalizedQuery=resolveRequestQuery(query);if(normalizedQuery)requestOptions.query=normalizedQuery;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function resolveRequestQuery(value=null){const source=unref(value);if(!source||typeof source!==`object`||Array.isArray(source))return null;return source}function buildEndpointWriteRequestOptions({method=`PATCH`,body=void 0,options=null,transport=null}={}){const requestOptions={method:String(method||`PATCH`).toUpperCase(),...asPlainObject(options)};if(body!==void 0)requestOptions.body=body;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function useEndpointResource({queryKey,path=``,enabled=true,client=getHttpWebClient(),readMethod=`GET`,writeMethod=`PATCH`,readQuery,transport,refreshOnPull=false,realtime,queryOptions=null,mutationOptions=null,requestRecovery=null,requestRecoveryLabel=``,fallbackLoadError=`jskit.http.resource.loadFailed`,fallbackSaveError=`jskit.http.resource.saveFailed`}){const normalizedPath=computed(()=>resolveTextRef(path));const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedPath.value));const query=useQuery({queryKey,queryFn:({signal})=>{const requestPath=normalizedPath.value;if(!requestPath)throw new Error(`Resource path is required.`);return client.request(requestPath,{...buildEndpointReadRequestOptions({method:readMethod,query:readQuery,transport}),signal})},enabled:queryEnabled,...mergeRequestRecoveryQueryMeta(refreshOnPull?mergeQueryMeta(asPlainObject(queryOptions),{jskit:{refreshOnPull:true}}):asPlainObject(queryOptions),requestRecovery,{label:requestRecoveryLabel,method:readMethod})});const realtimeBinding=useOperationRealtime({realtime,queryKey,enabled:queryEnabled});const mutation=useMutation({mutationFn:async(request={})=>{const options=asPlainObject(request);const requestPath=resolveTextRef(options.path||normalizedPath.value);if(!requestPath)throw new Error(`Resource path is required.`);const method=String(options.method||writeMethod||`PATCH`).toUpperCase();const body=Object.hasOwn(options,`body`)?options.body:options.payload;return client.request(requestPath,buildEndpointWriteRequestOptions({method,body,options:options.options,transport}))},...asPlainObject(mutationOptions)});const data=computed(()=>query.data.value);const hasResolvedData=computed(()=>hasResolvedQueryData({query,data}));const isInitialLoading=computed(()=>Boolean(queryEnabled.value&&query.isPending.value&&!hasResolvedData.value));const isFetching=computed(()=>Boolean(queryEnabled.value&&query.isFetching.value));const isRefetching=computed(()=>Boolean(isFetching.value&&!isInitialLoading.value));const isLoading=computed(()=>Boolean(isInitialLoading.value||isFetching.value));const isSaving=computed(()=>Boolean(mutation.isPending.value));const loadError=computed(()=>toQueryErrorMessage(query.error.value,fallbackLoadError));const saveError=computed(()=>toQueryErrorMessage(mutation.error.value,fallbackSaveError));async function reload(){return query.refetch()}async function save(payload,options={}){return mutation.mutateAsync({...asPlainObject(options),payload})}return{query,mutation,data,isInitialLoading,isFetching,isRefetching,isLoading,isSaving,loadError,saveError,realtime:realtimeBinding,reload,save}}export{partialMatchKey as A,environmentManager as C,matchMutation as D,hashQueryKeyByOptions as E,getClientKey as F,skipToken as M,useQueryClient as N,matchQuery as O,cloneDeepUnref as P,Subscribable as S,hashKey as T,Mutation as _,ensureAccessModeCompatibility as a,notifyManager as b,normalizePermissions as c,resolveEnabled as d,resolvePermissionAccess as f,useQuery as g,useMutation as h,emptyRecord as i,resolveQueryValue as j,noop as k,resolveAccessModeEnabled as l,resolveEnabledRef as m,useOperationRealtime as n,normalizeAccessMode as o,resolveQueryKey as p,asPlainObject as r,normalizeOwnershipFilter as s,useEndpointResource as t,resolveApiSuffix as u,Query as v,functionalUpdate as w,focusManager as x,onlineManager as y};
@@ -1 +0,0 @@
1
- import{vt as ref}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as useShellWebErrorRuntime}from"./error-BQ7r64JO.js";import{n as toUiErrorMessage}from"./errorMessageHelpers-BjIt31kK.js";function useUiFeedback({initialType=`success`,source=`http-web.ui-feedback`,successChannel=``,errorChannel=``,dedupeWindowMs=2e3}={}){const message=ref(``);const messageType=ref(String(initialType||`success`));const errorRuntime=useShellWebErrorRuntime();const normalizedSource=String(source||``).trim()||`http-web.ui-feedback`;let lastErrorPresentation=null;function rememberErrorPresentation(reportResult=null){const presentationId=String(reportResult?.presentationId||``).trim();const presenterId=String(reportResult?.decision?.presenterId||``).trim();if(!presentationId||!presenterId)return;lastErrorPresentation=Object.freeze({presentationId,presenterId})}function dismissLastErrorPresentation(){if(!lastErrorPresentation)return;errorRuntime.dismiss(lastErrorPresentation.presentationId,{presenterId:lastErrorPresentation.presenterId});lastErrorPresentation=null}function clear(){message.value=``}function success(nextMessage=``){messageType.value=`success`;const normalizedMessage=String(nextMessage||``).trim();message.value=normalizedMessage;dismissLastErrorPresentation();if(!normalizedMessage)return;errorRuntime.report({source:normalizedSource,message:normalizedMessage,intent:`action-feedback`,severity:`success`,channel:successChannel,dedupeKey:`${normalizedSource}:success:${normalizedMessage}`,dedupeWindowMs})}function error(errorValue,fallbackMessage=``){messageType.value=`error`;message.value=toUiErrorMessage(errorValue,fallbackMessage);if(!message.value)return;const reportResult=errorRuntime.report({source:normalizedSource,message:message.value,cause:errorValue||null,intent:`action-feedback`,severity:`error`,channel:errorChannel,dedupeKey:`${normalizedSource}:error:${message.value}`,dedupeWindowMs});if(!reportResult?.skipped)rememberErrorPresentation(reportResult)}return{message,messageType,clear,success,error}}export{useUiFeedback as t};
@@ -1 +0,0 @@
1
- import{$ as useId,Et as unref,G as renderList,H as openBlock,K as renderSlot,Kt as normalizeClass,N as nextTick,O as inject,Tt as toValue,Xt as toDisplayString,_ as createSlots,b as createVNode,d as createBaseVNode,f as createBlock,gt as reactive,i as Fragment,it as watch,m as createElementBlock,mt as onScopeDispose,ot as withCtx,p as createCommentVNode,st as withDirectives,u as computed,vt as ref,xt as shallowRef,y as createTextVNode}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{S as VIcon,cr as vShow,lr as withKeys,mt as useDisplay,ur as withModifiers}from"./VChip-D2IukBZw.js";import{s as normalizeObject}from"./normalize-BD25VwNK.js";import{r as VProgressCircular,t as VBtn}from"./VBtn-2vbH580C.js";import{t as VDialog}from"./VDialog-BCIrX462.js";import{t as _plugin_vue_export_helper_default}from"./_plugin-vue_export-helper-DNW4j-dv.js";import{y as LongTextInlineParts_default}from"./conversation-DiL2PEct.js";import{r as useRealtimeEvent}from"./useRealtimeEvent-B4oRg9Dt.js";var VIBE64_AI_TASKS_KEY=Symbol(`vibe64.ai-tasks`);var NO_AI_TASKS=Object.freeze({available:false});var AI_TASK_PHASES=Object.freeze({STARTING:`starting`,WORKING:`working`,CHECKING:`checking`,NEEDS_YOU:`needs_you`,CANCELLING:`cancelling`,DONE:`done`,NOT_DONE:`not_done`});var AI_TASK_REASONS=Object.freeze({AI_STUCK:`ai_stuck`,AI_UNAVAILABLE:`ai_unavailable`,ARCHIVED:`archived`,CANCELLED:`cancelled`,CHECK_STUCK:`check_stuck`,DRAFT_WAITING:`draft_waiting`,INTERRUPTED:`interrupted`,NO_RESULT:`no_result`,QUESTION:`question`,STOPPED:`stopped`,TURN_FAILED:`turn_failed`,UNCONFIRMED:`unconfirmed`,YOUR_TURN:`your_turn`});var AI_TASK_CHECKERS=Object.freeze({AGENT:`agent`,PERSON:`person`,VIBE64:`vibe64`});var AI_TASK_ACTIVE_PHASES=Object.freeze([AI_TASK_PHASES.STARTING,AI_TASK_PHASES.WORKING,AI_TASK_PHASES.CHECKING,AI_TASK_PHASES.CANCELLING]);var AI_TASK_ENDED_PHASES=Object.freeze([AI_TASK_PHASES.DONE,AI_TASK_PHASES.NOT_DONE]);function aiTaskEnded(task){return AI_TASK_ENDED_PHASES.includes(task.phase)}var AI_TASK_MESSAGES=Object.freeze({actions:Object.freeze({aiSetup:`Open AI setup`,answer:`Answer`,back:`Back`,cancel:`Cancel`,cancelling:`Cancelling…`,checkNow:`Check now`,close:`Close`,closing:`Closing…`,continue:`Continue`,details:`Details`,endNotDone:`End as not done`,finish:`Finish`,hide:`Hide`,keepGoing:`Keep going`,openChat:`Open chat`,review:`Review resolved conflicts`,waitForAi:`Wait for the AI`}),button:Object.freeze({busy:`Being fixed…`,fix:`Fix it with AI`,opening:`Opening…`,result:`See result`}),chat:Object.freeze({answer:`Type your answer…`,message:`Message the AI…`}),outcome:Object.freeze({done:`Done`,notDone:`Not done`,problem:`The problem`,seeConversation:`See the conversation`,showResult:`Show the result`,whatHappened:`What happened`,whatTheAiDid:`What the AI did`,whatsNext:`What's next`}),progress:Object.freeze({activity:`Activity`,unavailable:`Nothing is lost. The fix continues from here.`}),status:Object.freeze({aiStuck:`The AI could not finish this`,aiUnavailable:`The AI account can't run this right now`,cancelling:`Cancelling…`,draftWaiting:`The check failed. Your unsent message is waiting.`,interrupted:`Vibe64 restarted while the AI was working`,noResult:`The AI stopped without saying it finished`,question:`The AI needs your answer`,starting:`Starting…`,stopped:`Stopped. Tell the AI what to do next.`,turnFailed:`The AI ran into an error`,unconfirmed:`Vibe64 couldn't confirm the result`,working:`The AI is working on this`,yourTurn:`Your turn`}),tray:Object.freeze({cancelling:`Cancelling…`,done:`Done`,needsYou:`Needs you`,notDone:`Not done`,yourTurn:`Your turn`}),views:Object.freeze({chat:`Chat`,label:`Task views`,progress:`Progress`,waiting:`The AI is waiting for your answer`}),closeFailed:`That didn't finish. Try again.`,requestFailed:`That didn't reach Vibe64. Try again.`,attempt:(attempt,limit)=>`Attempt ${attempt} of ${limit}`,retrying:(attempt,limit)=>`The AI is trying again (attempt ${attempt} of ${limit})`,cancelQuestion:noun=>`Cancel this ${noun}? The AI stops. Anything it has changed stays in the session.`,cancelConfirm:noun=>`Cancel ${noun}`,cancelledByYou:noun=>`You cancelled this ${noun}.`,cancelledBy:(name,noun)=>`${name} cancelled this ${noun}.`,mainChatSince:time=>time?`The main chat's AI has been working since ${time}.`:`The main chat's AI is working.`,whatsNext:()=>`The problem is still there. Anything the AI changed stays in the session. To try again, close this and choose Fix it with AI.`,toast:(title,outcome)=>`${title}: ${outcome}.`});var AI_TASK_ACTIONS=Object.freeze({AI_SETUP:`ai-setup`,ANSWER:`answer`,CHECK:`check`,CONTINUE:`continue`,END:`end`,FINISH:`finish`,OPEN_CHAT:`open-chat`,REVIEW:`review`,RUN_NOW:`run-now`,WAIT_FOR_AI:`wait-for-ai`});var action=(id,label,primary=false)=>Object.freeze({id,label,primary});var OPEN_CHAT=action(AI_TASK_ACTIONS.OPEN_CHAT,AI_TASK_MESSAGES.actions.openChat);var CHECK_NOW=action(AI_TASK_ACTIONS.CHECK,AI_TASK_MESSAGES.actions.checkNow,true);var CONTINUE=action(AI_TASK_ACTIONS.CONTINUE,AI_TASK_MESSAGES.actions.continue,true);var NEEDS_YOU=Object.freeze({[AI_TASK_REASONS.QUESTION]:{status:AI_TASK_MESSAGES.status.question,chat:true,dot:true,actions:[action(AI_TASK_ACTIONS.ANSWER,AI_TASK_MESSAGES.actions.answer,true)]},[AI_TASK_REASONS.YOUR_TURN]:{glyph:`turn`,status:AI_TASK_MESSAGES.status.yourTurn,tray:AI_TASK_MESSAGES.tray.yourTurn,chat:true,dot:true,actions:[action(AI_TASK_ACTIONS.FINISH,AI_TASK_MESSAGES.actions.finish,true)]},[AI_TASK_REASONS.AI_STUCK]:{status:AI_TASK_MESSAGES.status.aiStuck,chat:true,actions:[action(AI_TASK_ACTIONS.END,AI_TASK_MESSAGES.actions.endNotDone),action(AI_TASK_ACTIONS.OPEN_CHAT,AI_TASK_MESSAGES.actions.openChat,true)]},[AI_TASK_REASONS.CHECK_STUCK]:{check:true,diagnostic:true,actions:[OPEN_CHAT,CHECK_NOW]},[AI_TASK_REASONS.NO_RESULT]:{status:AI_TASK_MESSAGES.status.noResult,actions:[OPEN_CHAT,CHECK_NOW]},[AI_TASK_REASONS.STOPPED]:{status:AI_TASK_MESSAGES.status.stopped,actions:[OPEN_CHAT,CONTINUE]},[AI_TASK_REASONS.AI_UNAVAILABLE]:{status:AI_TASK_MESSAGES.status.aiUnavailable,note:AI_TASK_MESSAGES.progress.unavailable,actions:[action(AI_TASK_ACTIONS.AI_SETUP,AI_TASK_MESSAGES.actions.aiSetup),CONTINUE]},[AI_TASK_REASONS.TURN_FAILED]:{status:AI_TASK_MESSAGES.status.turnFailed,actions:[OPEN_CHAT,CONTINUE]},[AI_TASK_REASONS.INTERRUPTED]:{status:AI_TASK_MESSAGES.status.interrupted,actions:[CONTINUE]},[AI_TASK_REASONS.UNCONFIRMED]:{status:AI_TASK_MESSAGES.status.unconfirmed,check:true,actions:[CHECK_NOW]},[AI_TASK_REASONS.DRAFT_WAITING]:{status:AI_TASK_MESSAGES.status.draftWaiting,chat:true,check:true,diagnostic:true,actions:[action(AI_TASK_ACTIONS.OPEN_CHAT,AI_TASK_MESSAGES.actions.openChat,true)]}});function stepsOf(task,needs){const[work,check]=task.steps;const counted=task.check.retryLimit>0?AI_TASK_MESSAGES.attempt(task.attempt,task.check.retryLimit):``;const ended=aiTaskEnded(task);const atCheck=task.phase===AI_TASK_PHASES.CHECKING||task.checkRunning||needs?.check===true;const passed=task.phase===AI_TASK_PHASES.DONE;const workState=passed||atCheck?`done`:ended?`failed`:`active`;const checkState=passed?`done`:needs?.check||ended&&atCheck?`failed`:atCheck?`active`:`pending`;const steps=[{label:work,state:workState,attempt:workState===`active`?counted:``}];if(check)steps.push({label:check,state:checkState,attempt:atCheck&&!ended?counted:``});return steps}function endedMessage(task,viewerId){if(task.message)return task.message;const by=task.endedBy;return by?.name&&by.id!==viewerId?AI_TASK_MESSAGES.cancelledBy(by.name,task.noun):AI_TASK_MESSAGES.cancelledByYou(task.noun)}function outcomeOf(task,viewerId){if(task.phase===AI_TASK_PHASES.DONE)return{heading:AI_TASK_MESSAGES.outcome.done,happened:task.message,report:task.report,next:``};return{heading:AI_TASK_MESSAGES.outcome.notDone,happened:endedMessage(task,viewerId),report:``,next:AI_TASK_MESSAGES.whatsNext()}}function runningStatus(task){if(task.phase===AI_TASK_PHASES.STARTING)return AI_TASK_MESSAGES.status.starting;if(task.phase===AI_TASK_PHASES.CANCELLING)return AI_TASK_MESSAGES.status.cancelling;if(task.phase===AI_TASK_PHASES.CHECKING)return task.waiting?task.message:task.check.label;return task.attempt>1?AI_TASK_MESSAGES.retrying(task.attempt,task.check.retryLimit):AI_TASK_MESSAGES.status.working}function noteOf(task,needs){if(task.phase===AI_TASK_PHASES.CANCELLING)return task.checkRunning?task.check.unstoppable:``;if(!needs)return``;return[needs.status&&task.message!==needs.status?task.message:``,needs.diagnostic&&!task.message.includes(task.diagnostic)?task.diagnostic:``,needs.note].filter(Boolean).join(` `)}function projectAiTask(task,{viewerId}){const ended=aiTaskEnded(task);const needs=task.phase===AI_TASK_PHASES.NEEDS_YOU?NEEDS_YOU[task.reason]:null;const whileAiWorks=task.phase===AI_TASK_PHASES.CHECKING&&task.waiting&&task.mainChatSince?task.check.whileAiWorks:null;const review=needs?.check&&task.reason===AI_TASK_REASONS.CHECK_STUCK&&task.conflictReview?[action(AI_TASK_ACTIONS.REVIEW,AI_TASK_MESSAGES.actions.review)]:[];const done=task.phase===AI_TASK_PHASES.DONE;const running=!ended&&!needs;return{glyph:done?`done`:ended?`not-done`:needs?needs.glyph||`attention`:`working`,status:done?AI_TASK_MESSAGES.outcome.done:ended?AI_TASK_MESSAGES.outcome.notDone:needs?needs.status||task.message:runningStatus(task),tray:done?AI_TASK_MESSAGES.tray.done:ended?AI_TASK_MESSAGES.tray.notDone:task.phase===AI_TASK_PHASES.CANCELLING?AI_TASK_MESSAGES.tray.cancelling:needs?needs.tray||AI_TASK_MESSAGES.tray.needsYou:task.tray,ended,chatDot:needs?.dot===true,opensOn:needs?.chat?`chat`:`progress`,composerOpen:Boolean(needs)||task.phase===AI_TASK_PHASES.WORKING,composerHint:task.reason===AI_TASK_REASONS.QUESTION?AI_TASK_MESSAGES.chat.answer:AI_TASK_MESSAGES.chat.message,note:whileAiWorks?`${AI_TASK_MESSAGES.mainChatSince(aiTaskTime(task.mainChatSince))} ${whileAiWorks.note}`:running&&task.phase!==AI_TASK_PHASES.CANCELLING?``:noteOf(task,needs),steps:stepsOf(task,needs),actions:needs?[...review,...needs.actions]:whileAiWorks?[action(AI_TASK_ACTIONS.WAIT_FOR_AI,AI_TASK_MESSAGES.actions.waitForAi),action(AI_TASK_ACTIONS.RUN_NOW,whileAiWorks.action,true)]:[],cancelQuestion:AI_TASK_MESSAGES.cancelQuestion(task.noun),outcome:ended?outcomeOf(task,viewerId):null}}function aiTaskFooterActions(actions,view){if(view!==`chat`)return actions;return actions.filter(({id})=>id!==AI_TASK_ACTIONS.ANSWER&&id!==AI_TASK_ACTIONS.OPEN_CHAT)}function aiTaskTime(at){const date=new Date(at);return Number.isNaN(date.getTime())?``:date.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}var SESSION_CHANGED_EVENT=`vibe64.session.changed`;var AI_TASK_CHANGED=`ai-task-changed`;function useAiTasks({sessionId,sessionsApiPath,projectSlug,enabled,request,onClosed}){const task=shallowRef(null);const loaded=ref(false);const error=ref(``);const cancelRequested=ref(false);const closing=ref(false);const starting=ref(false);const viewerId=ref(``);let readGeneration=0;const tasksPath=()=>`${toValue(sessionsApiPath)}/${encodeURIComponent(toValue(sessionId))}/ai-tasks`;const taskPath=(suffix=``)=>`${tasksPath()}/${encodeURIComponent(task.value.id)}${suffix}`;function remember(next){if(task.value?.id===next.id&&next.revision<task.value.revision)return;task.value=next}async function load(){const generation=++readGeneration;if(!toValue(enabled)||!toValue(sessionId))return;try{const{tasks,viewerId:viewer}=await request(tasksPath(),{method:`GET`});if(generation!==readGeneration)return;viewerId.value=viewer;const[saved=null]=tasks;if(saved)remember(saved);else task.value=null;loaded.value=true}catch{}}async function start(kind,input){error.value=``;starting.value=true;try{const answer=await request(tasksPath(),{method:`POST`,body:{kind,input}});remember(answer.task);return answer.task}catch(failure){error.value=failure.message||AI_TASK_MESSAGES.requestFailed;return null}finally{starting.value=false}}async function act(suffix,body={}){error.value=``;try{remember((await request(taskPath(suffix),{method:`POST`,body})).task)}catch(failure){error.value=failure.message||AI_TASK_MESSAGES.requestFailed;load()}}async function cancel(){cancelRequested.value=true;await act(`/cancel`);cancelRequested.value=false}const check=(input={})=>act(`/check`,input);const continueTask=()=>act(`/continue`);const finish=()=>act(`/finish`);async function close(){error.value=``;closing.value=true;try{await request(taskPath(),{method:`DELETE`});task.value=null}catch{error.value=AI_TASK_MESSAGES.closeFailed}finally{closing.value=false}}const matchesSession=payload=>payload.projectSlug===toValue(projectSlug)&&payload.sessionId===toValue(sessionId)&&payload.reason===AI_TASK_CHANGED;useRealtimeEvent({enabled:computed(()=>toValue(enabled)),event:SESSION_CHANGED_EVENT,matches:({payload={}}={})=>matchesSession(payload),onEvent({payload}){if(payload.aiTask){remember(payload.aiTask);return}if(payload.aiTaskClosed?.id!==task.value?.id)return;const closedHere=closing.value;task.value=null;if(!closedHere)onClosed(payload.aiTaskClosed)}});useRealtimeEvent({enabled:computed(()=>toValue(enabled)),event:`connect`,onEvent:()=>void load()});watch(()=>[toValue(sessionId),toValue(enabled)],([,on],previous)=>{if(previous?.[0]!==toValue(sessionId)){task.value=null;loaded.value=false}if(on)load()},{immediate:true});return{cancel,cancelRequested,check,close,closing,continueTask,error,finish,load,loaded,start,starting,task,viewerId}}var WINDOW_QUERY=`aiTask`;function useAiTaskWindow({task,loaded,active,opensOn,route,router}){const view=ref(`progress`);const transcriptOpen=ref(false);let opener=null;const wanted=computed(()=>String(route.query[WINDOW_QUERY]||``));const open=computed(()=>toValue(active)&&Boolean(wanted.value)&&toValue(task)?.id===wanted.value);function withoutWindow(){const{[WINDOW_QUERY]:_taskId,...query}=route.query;return{path:route.path,query,hash:route.hash}}async function show(element=null){const current=toValue(task);if(!current)return;opener=element;if(open.value)return;await router.push({path:route.path,query:{...route.query,[WINDOW_QUERY]:current.id},hash:route.hash})}function hide(){if(wanted.value)router.replace(withoutWindow())}function setView(next){view.value=next}watch(open,isOpen=>{if(!isOpen)return;view.value=toValue(opensOn);transcriptOpen.value=false},{immediate:true});watch(()=>[wanted.value,toValue(loaded),toValue(task)?.id,toValue(active)],()=>{if(wanted.value&&toValue(active)&&toValue(loaded)&&toValue(task)?.id!==wanted.value)router.replace(withoutWindow())},{immediate:true});return{hide,open,opener:()=>opener?.isConnected?opener:null,setView,show,transcriptOpen,view}}function useAiTaskHost({sessionId,sessionsApiPath,projectSlug,enabled,active,request,route,router,openAiSetup,reviewResolved,fallbackFocus}){const toast=ref(null);const tasks=useAiTasks({sessionId,sessionsApiPath,projectSlug,enabled,request,onClosed(closed){const heading=closed.phase===`done`?AI_TASK_MESSAGES.outcome.done:AI_TASK_MESSAGES.outcome.notDone;toast.value={text:AI_TASK_MESSAGES.toast(closed.title,heading),action:false}}});const projection=computed(()=>tasks.task.value&&projectAiTask(tasks.task.value,{viewerId:tasks.viewerId.value}));const taskWindow=useAiTaskWindow({task:tasks.task,loaded:tasks.loaded,active,opensOn:()=>projection.value?.opensOn||`progress`,route,router});function returnFocusTarget(){return taskWindow.opener()||document.querySelector(`[data-vibe64-ai-task-tray]`)||fallbackFocus()}async function start(kind,opener,input){const task=await tasks.start(kind,input);if(task)await nextTick();if(task)taskWindow.show(opener);else toast.value={text:tasks.error.value,action:false};return task}async function close(){const target=returnFocusTarget();await tasks.close();if(tasks.task.value)return;taskWindow.hide();await nextTick();(target?.isConnected?target:fallbackFocus())?.focus({preventScroll:true})}async function waitForAi(){taskWindow.hide();await nextTick();fallbackFocus()?.focus({preventScroll:true})}function run(actionId){const{task}=tasks;if(actionId===AI_TASK_ACTIONS.ANSWER||actionId===AI_TASK_ACTIONS.OPEN_CHAT)taskWindow.setView(`chat`);else if(actionId===AI_TASK_ACTIONS.CHECK)tasks.check();else if(actionId===AI_TASK_ACTIONS.RUN_NOW)tasks.check({whileAiWorks:true});else if(actionId===AI_TASK_ACTIONS.WAIT_FOR_AI)waitForAi();else if(actionId===AI_TASK_ACTIONS.CONTINUE)tasks.continueTask();else if(actionId===AI_TASK_ACTIONS.FINISH)tasks.finish();else if(actionId===AI_TASK_ACTIONS.END)tasks.cancel();else if(actionId===AI_TASK_ACTIONS.AI_SETUP)openAiSetup();else if(actionId===AI_TASK_ACTIONS.REVIEW&&task.value)reviewResolved()}function seeToastResult(){toast.value=null;taskWindow.show(null)}watch(()=>tasks.task.value&&aiTaskEnded(tasks.task.value),(ended,wasEnded)=>{if(!ended||wasEnded!==false||taskWindow.open.value||!toValue(active))return;toast.value={text:AI_TASK_MESSAGES.toast(tasks.task.value.title,projection.value.outcome.heading),action:true}});return reactive({cancel:tasks.cancel,cancelRequested:tasks.cancelRequested,check:tasks.check,close,closing:tasks.closing,error:tasks.error,hide:taskWindow.hide,open:taskWindow.open,projection,returnFocusTarget,run,seeToastResult,setTranscript:open=>{taskWindow.transcriptOpen.value=open},setView:taskWindow.setView,show:taskWindow.show,start,starting:tasks.starting,task:tasks.task,toast,transcriptOpen:taskWindow.transcriptOpen,view:taskWindow.view})}var _sfc_main$4={__name:`Vibe64AiTaskButton`,props:{kind:{required:true,type:String},allowed:{required:true,type:Boolean},title:{required:true,type:String},input:{required:true,type:Object}},emits:[`done`],setup(__props,{emit:__emit}){const props=__props;const emit=__emit;const tasks=inject(VIBE64_AI_TASKS_KEY);const own=computed(()=>tasks.task?.kind===props.kind?tasks.task:null);const linked=computed(()=>Boolean(own.value));const label=computed(()=>{if(tasks.starting)return AI_TASK_MESSAGES.button.opening;if(!own.value)return AI_TASK_MESSAGES.button.fix;return tasks.projection.ended?AI_TASK_MESSAGES.button.result:AI_TASK_MESSAGES.button.busy});const disabled=computed(()=>!own.value&&(!props.allowed||tasks.starting));watch(()=>own.value?.phase===AI_TASK_PHASES.DONE?own.value.id:``,doneId=>{if(doneId)emit(`done`)});function activate(event){const opener=event.currentTarget;if(own.value)tasks.show(opener);else tasks.start(props.kind,opener,props.input)}return(_ctx,_cache)=>{return openBlock(),createBlock(VBtn,{"aria-busy":label.value===unref(AI_TASK_MESSAGES).button.opening?`true`:void 0,class:`vibe64-ai-task-button`,"data-vibe64-ai-task-button":``,disabled:disabled.value,"prepend-icon":`$smartToy`,size:`small`,title:__props.title,type:`button`,variant:`tonal`,onClick:activate},createSlots({default:withCtx(()=>[createTextVNode(toDisplayString(label.value)+` `,1)]),_:2},[linked.value?{name:`append`,fn:withCtx(()=>[createVNode(VIcon,{icon:`$arrowForward`,size:`16`,"aria-hidden":`true`})]),key:`0`}:void 0]),1032,[`aria-busy`,`disabled`,`title`])}}};var Vibe64AiTaskButton_default=_plugin_vue_export_helper_default(_sfc_main$4,[[`__scopeId`,`data-v-2233af9d`]]);var _hoisted_1$3=[`aria-label`,`title`];var _hoisted_2$3={class:`vibe64-ai-task-tray__label`};var _sfc_main$3={__name:`Vibe64AiTaskTray`,setup(__props){const tasks=inject(VIBE64_AI_TASKS_KEY);const glyphIcons={attention:`$errorFilled`,done:`$checkCircleFilled`,"not-done":`$cancel`,turn:`$circle`};return(_ctx,_cache)=>{return openBlock(),createElementBlock(`button`,{"aria-label":`${unref(tasks).task.title}: ${unref(tasks).projection.tray}`,class:normalizeClass([`vibe64-ai-task-tray`,`vibe64-ai-task-tray--${unref(tasks).projection.glyph}`]),"data-vibe64-ai-task-tray":``,title:unref(tasks).projection.tray,type:`button`,onClick:_cache[0]||(_cache[0]=$event=>unref(tasks).show($event.currentTarget))},[unref(tasks).projection.glyph===`working`?(openBlock(),createBlock(VProgressCircular,{key:0,indeterminate:``,size:`16`,width:`2`,"aria-hidden":`true`})):(openBlock(),createBlock(VIcon,{key:1,icon:glyphIcons[unref(tasks).projection.glyph],size:`18`,"aria-hidden":`true`},null,8,[`icon`])),createBaseVNode(`span`,_hoisted_2$3,toDisplayString(unref(tasks).projection.tray),1)],10,_hoisted_1$3)}}};var Vibe64AiTaskTray_default=_plugin_vue_export_helper_default(_sfc_main$3,[[`__scopeId`,`data-v-56857b35`]]);var PHONE_WIDTH=600;var SHORT_HEIGHT=560;var EXPANDED_WIDTH=960;function aiTaskFit(width,height){const phone=width<PHONE_WIDTH;if(phone||height<SHORT_HEIGHT)return{fullscreen:true,phone,width:void 0,height:void 0};return width<EXPANDED_WIDTH?{fullscreen:false,phone,width:`min(92vw, 46rem)`,height:`88dvh`}:{fullscreen:false,phone,width:`46rem`,height:`min(80dvh, 46rem)`}}var REDUCED_MOTION=`(prefers-reduced-motion: reduce)`;function useAiTaskFocus({title,views,selectedView,setView,returnFocusTarget}){const tabElements=new Map;const motionQuery=globalThis.matchMedia(REDUCED_MOTION);const reducedMotion=ref(motionQuery.matches);const noteMotion=event=>{reducedMotion.value=event.matches};motionQuery.addEventListener(`change`,noteMotion);onScopeDispose(()=>motionQuery.removeEventListener(`change`,noteMotion));function focusTitle(){title.value?.focus({preventScroll:true})}function returnFocus(){returnFocusTarget()?.focus({preventScroll:true})}function setTab(view,element){if(element)tabElements.set(view,element);else tabElements.delete(view)}async function moveBetweenViews(event){const index=views.indexOf(selectedView());const next={ArrowLeft:views[(index+views.length-1)%views.length],ArrowRight:views[(index+1)%views.length],End:views.at(-1),Home:views[0]}[event.key];if(!next)return;event.preventDefault();setView(next);await nextTick();tabElements.get(next)?.focus()}return{focusTitle,moveBetweenViews,reducedMotion,returnFocus,setTab}}var _hoisted_1$2={class:`ai-task-outcome`};var _hoisted_2$2={key:0};var _hoisted_3$2={key:1};var _sfc_main$2={__name:`Vibe64AiTaskOutcome`,props:{task:{required:true,type:Object},projection:{required:true,type:Object}},emits:[`see-conversation`],setup(__props,{emit:__emit}){const emit=__emit;return(_ctx,_cache)=>{return openBlock(),createElementBlock(`div`,_hoisted_1$2,[createBaseVNode(`section`,null,[createBaseVNode(`h3`,null,toDisplayString(unref(AI_TASK_MESSAGES).outcome.problem),1),createBaseVNode(`p`,null,[createVNode(unref(LongTextInlineParts_default),{text:__props.task.problem.summary},null,8,[`text`])])]),createBaseVNode(`section`,null,[createBaseVNode(`h3`,null,toDisplayString(unref(AI_TASK_MESSAGES).outcome.whatHappened),1),createBaseVNode(`p`,null,[createVNode(unref(LongTextInlineParts_default),{text:__props.projection.outcome.happened},null,8,[`text`])])]),__props.projection.outcome.report?(openBlock(),createElementBlock(`section`,_hoisted_2$2,[createBaseVNode(`h3`,null,toDisplayString(unref(AI_TASK_MESSAGES).outcome.whatTheAiDid),1),createBaseVNode(`p`,null,[createVNode(unref(LongTextInlineParts_default),{text:__props.projection.outcome.report},null,8,[`text`])])])):createCommentVNode(``,true),__props.projection.outcome.next?(openBlock(),createElementBlock(`section`,_hoisted_3$2,[createBaseVNode(`h3`,null,toDisplayString(unref(AI_TASK_MESSAGES).outcome.whatsNext),1),createBaseVNode(`p`,null,toDisplayString(__props.projection.outcome.next),1)])):createCommentVNode(``,true),createVNode(VBtn,{class:`ai-task-outcome__conversation`,"data-vibe64-ai-task-transcript":``,variant:`text`,onClick:_cache[0]||(_cache[0]=$event=>emit(`see-conversation`))},{default:withCtx(()=>[createTextVNode(toDisplayString(unref(AI_TASK_MESSAGES).outcome.seeConversation),1)]),_:1})])}}};var Vibe64AiTaskOutcome_default=_plugin_vue_export_helper_default(_sfc_main$2,[[`__scopeId`,`data-v-a9609028`]]);var _hoisted_1$1={class:`ai-task-progress`};var _hoisted_2$1={class:`ai-task-progress__steps`};var _hoisted_3$1={class:`ai-task-progress__label`};var _hoisted_4$1={key:0,class:`ai-task-progress__attempt`};var _hoisted_5$1={key:0,class:`ai-task-progress__note`};var _hoisted_6$1={key:1,class:`ai-task-progress__output`};var _hoisted_7$1=[`aria-label`];var _hoisted_8$1={class:`ai-task-progress__heading`};var _hoisted_9$1=[`datetime`];var _sfc_main$1={__name:`Vibe64AiTaskProgress`,props:{task:{required:true,type:Object},projection:{required:true,type:Object},output:{required:true,type:Boolean},commentary:{required:true,type:Array}},setup(__props){const props=__props;const stepIcons={active:`$radioOn`,done:`$checkCircleFilled`,failed:`$cancel`,pending:`$circle`};const activity=computed(()=>[...props.task.log,...props.commentary].sort((a,b)=>a.at.localeCompare(b.at)));return(_ctx,_cache)=>{return openBlock(),createElementBlock(`div`,_hoisted_1$1,[createBaseVNode(`ol`,_hoisted_2$1,[(openBlock(true),createElementBlock(Fragment,null,renderList(__props.projection.steps,step=>{return openBlock(),createElementBlock(`li`,{key:step.label,class:normalizeClass([`ai-task-progress__step`,`ai-task-progress__step--${step.state}`])},[createVNode(VIcon,{icon:stepIcons[step.state],size:`18`,"aria-hidden":`true`},null,8,[`icon`]),createBaseVNode(`span`,_hoisted_3$1,toDisplayString(step.label),1),step.attempt?(openBlock(),createElementBlock(`span`,_hoisted_4$1,toDisplayString(step.attempt),1)):createCommentVNode(``,true)],2)}),128))]),__props.projection.note?(openBlock(),createElementBlock(`p`,_hoisted_5$1,[createVNode(unref(LongTextInlineParts_default),{text:__props.projection.note},null,8,[`text`])])):createCommentVNode(``,true),_ctx.$slots[`check-output`]&&__props.output?(openBlock(),createElementBlock(`details`,_hoisted_6$1,[createBaseVNode(`summary`,null,toDisplayString(__props.task.check.output),1),renderSlot(_ctx.$slots,`check-output`,{},void 0,true)])):createCommentVNode(``,true),createBaseVNode(`section`,{class:`ai-task-progress__activity`,"aria-label":unref(AI_TASK_MESSAGES).progress.activity},[createBaseVNode(`h3`,_hoisted_8$1,toDisplayString(unref(AI_TASK_MESSAGES).progress.activity),1),createBaseVNode(`ol`,null,[(openBlock(true),createElementBlock(Fragment,null,renderList(activity.value,entry=>{return openBlock(),createElementBlock(`li`,{key:`${entry.at}:${entry.text}`},[createBaseVNode(`time`,{datetime:entry.at},toDisplayString(unref(aiTaskTime)(entry.at)),9,_hoisted_9$1),createBaseVNode(`span`,null,toDisplayString(entry.text),1)])}),128))])],8,_hoisted_7$1)])}}};var Vibe64AiTaskProgress_default=_plugin_vue_export_helper_default(_sfc_main$1,[[`__scopeId`,`data-v-8b486df1`]]);var _hoisted_1=[`aria-labelledby`,`data-vibe64-ai-task-phase`,`data-vibe64-ai-task-reason`];var _hoisted_2={class:`ai-task__header`};var _hoisted_3={class:`ai-task__heading`};var _hoisted_4=[`id`];var _hoisted_5={"aria-live":`polite`,class:`ai-task__status`,"data-vibe64-ai-task-status":``};var _hoisted_6={key:0,class:`ai-task__commands`};var _hoisted_7={class:`ai-task__problem`};var _hoisted_8=[`title`];var _hoisted_9=[`aria-expanded`,`aria-label`];var _hoisted_10={class:`ai-task__details-word`};var _hoisted_11={key:0,class:`ai-task__details`,"data-vibe64-ai-task-details-text":``,tabindex:`0`};var _hoisted_12=[`aria-label`];var _hoisted_13=[`id`,`aria-controls`,`aria-selected`,`data-vibe64-ai-task-view`,`tabindex`,`onClick`];var _hoisted_14=[`aria-label`];var _hoisted_15={class:`ai-task__body`};var _hoisted_16=[`id`,`aria-labelledby`];var _hoisted_17=[`id`,`aria-labelledby`,`role`];var _hoisted_18={key:1,class:`ai-task__error`,role:`alert`};var _hoisted_19={key:2,class:`ai-task__footer ai-task__footer--question`};var _hoisted_20={class:`ai-task__actions`};var _hoisted_21={key:3,class:`ai-task__footer`};var _hoisted_22={class:`ai-task__actions`};var _hoisted_23={key:4,class:`ai-task__footer`};var _hoisted_24={class:`ai-task__actions`};var _sfc_main={__name:`Vibe64AiTaskWindow`,props:{source:{required:true,type:Object},commentary:{required:true,type:Array},output:{required:true,type:Boolean}},setup(__props){const props=__props;const glyphIcons={attention:`$errorFilled`,done:`$checkCircleFilled`,"not-done":`$cancel`,turn:`$circle`};const titleId=useId();const title=ref(null);const task=computed(()=>props.source.task);const projection=computed(()=>props.source.projection);const footerActions=computed(()=>aiTaskFooterActions(projection.value.actions,props.source.view));const{width,height}=useDisplay();const fit=computed(()=>aiTaskFit(width.value,height.value));const detailsOpen=ref(false);const confirmingCancel=ref(false);const cancelling=computed(()=>props.source.cancelRequested||task.value.phase===`cancelling`);const tabs=[{id:`progress`,label:AI_TASK_MESSAGES.views.progress},{id:`chat`,label:AI_TASK_MESSAGES.views.chat}];const{focusTitle,moveBetweenViews,reducedMotion,returnFocus,setTab}=useAiTaskFocus({title,views:tabs.map(tab=>tab.id),selectedView:()=>props.source.view,setView:view=>props.source.setView(view),returnFocusTarget:()=>props.source.returnFocusTarget()});function requestCancel(){if(cancelling.value)props.source.cancel();else confirmingCancel.value=true}function cancel(){confirmingCancel.value=false;props.source.cancel()}function escape(){if(projection.value.ended)props.source.close();else props.source.hide()}watch(()=>projection.value.ended,async ended=>{if(!ended)return;confirmingCancel.value=false;await nextTick();focusTitle()});return(_ctx,_cache)=>{return openBlock(),createBlock(VDialog,{"aria-labelledby":unref(titleId),fullscreen:fit.value.fullscreen,height:fit.value.height,"model-value":__props.source.open,"no-click-animation":``,persistent:``,width:fit.value.width,transition:unref(reducedMotion)?false:void 0,onAfterEnter:unref(focusTitle),onAfterLeave:unref(returnFocus),onKeydown:withKeys(withModifiers(escape,[`stop`,`prevent`]),[`esc`])},{default:withCtx(()=>[createBaseVNode(`section`,{"aria-labelledby":unref(titleId),class:normalizeClass([`ai-task`,{"ai-task--fullscreen":fit.value.fullscreen,"ai-task--ended":projection.value.ended}]),"data-vibe64-ai-task":``,"data-vibe64-ai-task-phase":task.value.phase,"data-vibe64-ai-task-reason":task.value.reason},[createBaseVNode(`header`,_hoisted_2,[createBaseVNode(`span`,{class:normalizeClass([`ai-task__glyph`,`ai-task__glyph--${projection.value.glyph}`]),"aria-hidden":`true`},[projection.value.glyph===`working`?(openBlock(),createBlock(VProgressCircular,{key:0,indeterminate:!unref(reducedMotion),"model-value":unref(reducedMotion)?60:void 0,size:`20`,width:`2`},null,8,[`indeterminate`,`model-value`])):(openBlock(),createBlock(VIcon,{key:1,icon:glyphIcons[projection.value.glyph],size:`22`},null,8,[`icon`]))],2),createBaseVNode(`div`,_hoisted_3,[createBaseVNode(`h2`,{id:unref(titleId),ref_key:`title`,ref:title,tabindex:`-1`},toDisplayString(projection.value.ended?projection.value.outcome.heading:task.value.title),9,_hoisted_4),createBaseVNode(`p`,_hoisted_5,[projection.value.ended?(openBlock(),createElementBlock(Fragment,{key:0},[createTextVNode(toDisplayString(task.value.title),1)],64)):(openBlock(),createBlock(unref(LongTextInlineParts_default),{key:1,text:projection.value.status},null,8,[`text`]))])]),!projection.value.ended?(openBlock(),createElementBlock(`div`,_hoisted_6,[createVNode(VBtn,{"data-vibe64-ai-task-hide":``,variant:`text`,onClick:__props.source.hide},{default:withCtx(()=>[createTextVNode(toDisplayString(unref(AI_TASK_MESSAGES).actions.hide),1)]),_:1},8,[`onClick`]),createVNode(VBtn,{"aria-busy":cancelling.value?`true`:void 0,"data-vibe64-ai-task-cancel":``,variant:`text`,onClick:requestCancel},{default:withCtx(()=>[createTextVNode(toDisplayString(cancelling.value?unref(AI_TASK_MESSAGES).actions.cancelling:unref(AI_TASK_MESSAGES).actions.cancel),1)]),_:1},8,[`aria-busy`])])):createCommentVNode(``,true)]),!projection.value.ended?(openBlock(),createElementBlock(Fragment,{key:0},[createBaseVNode(`div`,_hoisted_7,[createBaseVNode(`span`,{class:`ai-task__problem-line`,title:task.value.problem.summary},[createVNode(unref(LongTextInlineParts_default),{text:task.value.problem.summary},null,8,[`text`])],8,_hoisted_8),task.value.problem.details?(openBlock(),createElementBlock(`button`,{key:0,"aria-expanded":detailsOpen.value?`true`:`false`,"aria-label":unref(AI_TASK_MESSAGES).actions.details,class:`ai-task__details-toggle`,"data-vibe64-ai-task-details":``,type:`button`,onClick:_cache[0]||(_cache[0]=$event=>detailsOpen.value=!detailsOpen.value)},[createBaseVNode(`span`,_hoisted_10,toDisplayString(unref(AI_TASK_MESSAGES).actions.details),1),createVNode(VIcon,{icon:detailsOpen.value?`$collapse`:`$expand`,size:`18`,"aria-hidden":`true`},null,8,[`icon`])],8,_hoisted_9)):createCommentVNode(``,true)]),detailsOpen.value?(openBlock(),createElementBlock(`pre`,_hoisted_11,toDisplayString(task.value.problem.details),1)):createCommentVNode(``,true),createBaseVNode(`div`,{"aria-label":unref(AI_TASK_MESSAGES).views.label,class:`ai-task__views`,role:`tablist`,onKeydown:_cache[1]||(_cache[1]=(...args)=>unref(moveBetweenViews)&&unref(moveBetweenViews)(...args))},[(openBlock(),createElementBlock(Fragment,null,renderList(tabs,tab=>{return createBaseVNode(`button`,{id:`${unref(titleId)}-${tab.id}-tab`,key:tab.id,ref_for:true,ref:element=>unref(setTab)(tab.id,element),"aria-controls":`${unref(titleId)}-${tab.id}`,"aria-selected":__props.source.view===tab.id?`true`:`false`,class:normalizeClass([`ai-task__view`,{"ai-task__view--selected":__props.source.view===tab.id}]),"data-vibe64-ai-task-view":tab.id,role:`tab`,tabindex:__props.source.view===tab.id?0:-1,type:`button`,onClick:$event=>__props.source.setView(tab.id)},[createTextVNode(toDisplayString(tab.label)+` `,1),tab.id===`chat`&&projection.value.chatDot?(openBlock(),createElementBlock(`span`,{key:0,class:`ai-task__dot`,role:`img`,"aria-label":unref(AI_TASK_MESSAGES).views.waiting},null,8,_hoisted_14)):createCommentVNode(``,true)],10,_hoisted_13)}),64))],40,_hoisted_12)],64)):createCommentVNode(``,true),createBaseVNode(`div`,_hoisted_15,[!projection.value.ended?withDirectives((openBlock(),createElementBlock(`section`,{key:0,id:`${unref(titleId)}-progress`,"aria-labelledby":`${unref(titleId)}-progress-tab`,class:`ai-task__panel`,role:`tabpanel`},[createVNode(Vibe64AiTaskProgress_default,{commentary:__props.commentary,output:__props.output,projection:projection.value,task:task.value},{"check-output":withCtx(()=>[renderSlot(_ctx.$slots,`check-output`,{},void 0,true)]),_:3},8,[`commentary`,`output`,`projection`,`task`])],8,_hoisted_16)),[[vShow,__props.source.view===`progress`]]):!__props.source.transcriptOpen?(openBlock(),createBlock(Vibe64AiTaskOutcome_default,{key:1,projection:projection.value,task:task.value,onSeeConversation:_cache[2]||(_cache[2]=$event=>__props.source.setTranscript(true))},null,8,[`projection`,`task`])):createCommentVNode(``,true),withDirectives(createBaseVNode(`section`,{id:`${unref(titleId)}-chat`,"aria-labelledby":projection.value.ended?void 0:`${unref(titleId)}-chat-tab`,class:`ai-task__panel`,role:projection.value.ended?void 0:`tabpanel`},[renderSlot(_ctx.$slots,`chat`,{visible:__props.source.open&&(projection.value.ended?__props.source.transcriptOpen:__props.source.view===`chat`)},void 0,true)],8,_hoisted_17),[[vShow,!projection.value.ended?__props.source.view===`chat`:__props.source.transcriptOpen]])]),__props.source.error?(openBlock(),createElementBlock(`p`,_hoisted_18,toDisplayString(__props.source.error),1)):createCommentVNode(``,true),confirmingCancel.value?(openBlock(),createElementBlock(`footer`,_hoisted_19,[createBaseVNode(`p`,null,toDisplayString(projection.value.cancelQuestion),1),createBaseVNode(`div`,_hoisted_20,[createVNode(VBtn,{"data-vibe64-ai-task-keep-going":``,variant:`text`,onClick:_cache[3]||(_cache[3]=$event=>confirmingCancel.value=false)},{default:withCtx(()=>[createTextVNode(toDisplayString(unref(AI_TASK_MESSAGES).actions.keepGoing),1)]),_:1}),createVNode(VBtn,{color:`error`,"data-vibe64-ai-task-cancel-confirm":``,variant:`flat`,onClick:cancel},{default:withCtx(()=>[createTextVNode(toDisplayString(unref(AI_TASK_MESSAGES).cancelConfirm(task.value.noun)),1)]),_:1})])])):projection.value.ended?(openBlock(),createElementBlock(`footer`,_hoisted_21,[createBaseVNode(`div`,_hoisted_22,[__props.source.transcriptOpen?(openBlock(),createBlock(VBtn,{key:0,variant:`text`,onClick:_cache[4]||(_cache[4]=$event=>__props.source.setTranscript(false))},{default:withCtx(()=>[createTextVNode(toDisplayString(unref(AI_TASK_MESSAGES).outcome.showResult),1)]),_:1})):createCommentVNode(``,true),createVNode(VBtn,{"aria-busy":__props.source.closing?`true`:void 0,color:`primary`,"data-vibe64-ai-task-close":``,variant:`flat`,onClick:__props.source.close},{default:withCtx(()=>[createTextVNode(toDisplayString(__props.source.closing?unref(AI_TASK_MESSAGES).actions.closing:unref(AI_TASK_MESSAGES).actions.close),1)]),_:1},8,[`aria-busy`,`onClick`])])])):footerActions.value.length?(openBlock(),createElementBlock(`footer`,_hoisted_23,[createBaseVNode(`div`,_hoisted_24,[(openBlock(true),createElementBlock(Fragment,null,renderList(footerActions.value,item=>{return openBlock(),createBlock(VBtn,{key:item.id,color:item.primary?`primary`:void 0,"data-vibe64-ai-task-action":item.id,variant:item.primary?`flat`:`text`,onClick:$event=>__props.source.run(item.id)},{default:withCtx(()=>[createTextVNode(toDisplayString(item.label),1)]),_:2},1032,[`color`,`data-vibe64-ai-task-action`,`variant`,`onClick`])}),128))])])):createCommentVNode(``,true)],10,_hoisted_1)]),_:3},8,[`aria-labelledby`,`fullscreen`,`height`,`model-value`,`width`,`transition`,`onAfterEnter`,`onAfterLeave`,`onKeydown`])}}};var Vibe64AiTaskWindow_default=_plugin_vue_export_helper_default(_sfc_main,[[`__scopeId`,`data-v-43823fc5`]]);var REPOSITORY_STATUS_SESSION_REASONS=new Set([`claude-stream-turn-idle`,`codex-app-server-turn-idle`,`opencode-server-turn-idle`,`repository-canonical-changed`,`session-pull-request`,`session-repository-checked`,`session-save-completed`,`session-save-failed`,`session-save-started`,`session-save-update-required`,`session-starter-applied`,`session-turn-checkpoint-failed`,`session-turn-checkpoint-updated`,`session-update-completed`,`session-update-failed`,`session-update-started`]);var REPOSITORY_UPDATE_CHECK_FAILED_REASON=`session-repository-check-failed`;var REPOSITORY_CANONICAL_RECHECK_REASONS=new Set([`repository-canonical-changed`,`session-pull-request`,`session-save-failed`,`session-save-update-required`,`session-update-failed`]);function repositoryStatusSessionId(payload={}){const event=normalizeObject(payload);return String(event.sessionId||event.session?.sessionId||``).trim()}function repositoryStatusRealtimeShouldRefresh(payload={}){return REPOSITORY_STATUS_SESSION_REASONS.has(String(normalizeObject(payload).reason||``).trim())}function repositoryStatusRealtimeNeedsCanonicalCheck(payload={}){return REPOSITORY_CANONICAL_RECHECK_REASONS.has(String(normalizeObject(payload).reason||``).trim())}export{Vibe64AiTaskWindow_default as a,useAiTaskHost as c,repositoryStatusSessionId as i,AI_TASK_PHASES as l,repositoryStatusRealtimeNeedsCanonicalCheck as n,Vibe64AiTaskTray_default as o,repositoryStatusRealtimeShouldRefresh as r,Vibe64AiTaskButton_default as s,REPOSITORY_UPDATE_CHECK_FAILED_REASON as t,VIBE64_AI_TASKS_KEY as u};