vibe64 0.1.35 → 0.1.36

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 (208) hide show
  1. package/bin/run.js +1919 -1660
  2. package/bin/server.js +158 -111
  3. package/bin/upgrade-state.js +5783 -5605
  4. package/dist/assets/GithubBrowserTabs-BzJF4k9Y.js +1 -0
  5. package/dist/assets/{StudioErrorNotice-sQfmeR-z.js → StudioErrorNotice-BdllGqRy.js} +1 -1
  6. package/dist/assets/{Vibe64AsyncModuleState-Dx7YKRPp.js → Vibe64AsyncModuleState-Bi0TqlIu.js} +1 -1
  7. package/dist/assets/Vibe64AuthSettingsButton-BuvmwGiT.js +5 -0
  8. package/dist/assets/Vibe64AuthSettingsButton-M44SSmZ9.css +1 -0
  9. package/dist/assets/{Vibe64DashboardBackButton-yE6cyYg2.js → Vibe64DashboardBackButton-Ccd4hpD6.js} +1 -1
  10. package/dist/assets/Vibe64DashboardShell-D67m4aWz.js +1 -0
  11. package/dist/assets/{Vibe64DashboardShell-MBkUHjs-.css → Vibe64DashboardShell-De2mbdpI.css} +1 -1
  12. package/dist/assets/{Vibe64DatabaseWorkspace-BONJdxBS.js → Vibe64DatabaseWorkspace-D3uK1gDm.js} +3 -3
  13. package/dist/assets/{Vibe64DatabaseWorkspace-CR4pzzcf.css → Vibe64DatabaseWorkspace-DPDMxhAW.css} +1 -1
  14. package/dist/assets/Vibe64OutputControls-BfESn5kJ.js +8 -0
  15. package/dist/assets/Vibe64OutputControls-D2CCECo5.css +1 -0
  16. package/dist/assets/{Vibe64RepositoryWorkspace-ByQlZbyO.js → Vibe64RepositoryWorkspace-0jAxvdA8.js} +2 -2
  17. package/dist/assets/{Vibe64RepositoryWorkspace-CVHcT93M.css → Vibe64RepositoryWorkspace-Agyt4O-V.css} +1 -1
  18. package/dist/assets/Vibe64SessionFiles-B3ONZrBL.css +1 -0
  19. package/dist/assets/Vibe64SessionFiles-BCOJ4QmR.js +41 -0
  20. package/dist/assets/{Vibe64TemporaryAiFixAction-BGlcrq4d.js → Vibe64TemporaryAiFixAction-DM2jpPbQ.js} +1 -1
  21. package/dist/assets/{Vibe64UiStoryboardView-Brlwdvqi.js → Vibe64UiStoryboardView-DP5af46a.js} +1 -1
  22. package/dist/assets/{Vibe64UnavailableSessions-zwlWlcZD.js → Vibe64UnavailableSessions-C7XwH1SS.js} +1 -1
  23. package/dist/assets/{_sessionId_-CvOkQbVy.js → _sessionId_-B1Ymr7c_.js} +1 -1
  24. package/dist/assets/{_sessionTool_-Dwod5ns9.js → _sessionTool_-DVYdREoI.js} +1 -1
  25. package/dist/assets/_slug_-CQseA9pt.css +1 -0
  26. package/dist/assets/_slug_-CYO2vjCd.js +24 -0
  27. package/dist/assets/{access-BVu5XYm2.js → access-Cb7dkN53.js} +1 -1
  28. package/dist/assets/app-BvgY7oVf.js +1 -0
  29. package/dist/assets/app-CZu7oxUO.css +1 -0
  30. package/dist/assets/{assistantRouting-CwbwfkwB.js → assistantRouting-B38ujQ7x.js} +1 -1
  31. package/dist/assets/{changes-olY8cnFK.js → changes-lsBcuikn.js} +1 -1
  32. package/dist/assets/client-CRI5CNKl.js +2 -0
  33. package/dist/assets/client-TGaWwOhc.css +1 -0
  34. package/dist/assets/conversation-CDEt9jBx.js +17 -0
  35. package/dist/assets/conversation-vxJGwmtW.css +1 -0
  36. package/dist/assets/{dashboard-BnXD-H4R.js → dashboard-D8HOAw46.js} +1 -1
  37. package/dist/assets/definitions-DLTX17nI.js +1 -0
  38. package/dist/assets/{env-DJhnLOH7.css → env-BzRtyO0w.css} +1 -1
  39. package/dist/assets/env-DJezQixO.js +1 -0
  40. package/dist/assets/health-BJvooRnJ.css +1 -0
  41. package/dist/assets/health-CtKdN_Nf.js +1 -0
  42. package/dist/assets/{history-BxlpB-YH.js → history-BdZFOtz4.js} +1 -1
  43. package/dist/assets/{incoming-BOxRVlOM.js → incoming-VsQNnL9m.js} +1 -1
  44. package/dist/assets/index-C-osVUKw.css +1 -0
  45. package/dist/assets/index-C4K3ntms.js +138 -0
  46. package/dist/assets/{integrations-BFltGDVI.js → integrations-CMQ9EDmt.js} +2 -2
  47. package/dist/assets/issues-DHpY5hSr.js +1 -0
  48. package/dist/assets/learning-DXlMuwzh.js +1 -0
  49. package/dist/assets/mdi-yXT-CQ6u.js +1 -0
  50. package/dist/assets/placement-NpX2s7u8.js +1 -0
  51. package/dist/assets/pull-requests-BcKNEUYH.js +1 -0
  52. package/dist/assets/{repository-JWLVST3D.js → repository-ClEgntHW.js} +1 -1
  53. package/dist/assets/roboto-latin-wght-normal-ccAYIvAh.woff2 +0 -0
  54. package/dist/assets/{session-C5Nj8Dlq.js → session-BlD46q-d.js} +1 -1
  55. package/dist/assets/settings-BwukeIKe.js +1 -0
  56. package/dist/assets/shared-BM2SV6fi.js +2 -0
  57. package/dist/assets/studioGateApi-DcCqiD9V.js +1 -0
  58. package/dist/assets/studioUrls-DmMMIScP.js +1 -0
  59. package/dist/assets/useArchivedVibe64Sessions-D5zUA-BC.js +1 -0
  60. package/dist/assets/useCommand-Bqxb-naz.js +1 -0
  61. package/dist/assets/useEndpointResource-DWoQ2keu.js +1 -0
  62. package/dist/assets/useRealtimeEvent-Bwapstla.js +1 -0
  63. package/dist/assets/{useUiFeedback-0FqKuZRP.js → useUiFeedback-BPBF_0bp.js} +1 -1
  64. package/dist/assets/useVibe64ConversationLog-Dy6YTPQn.js +1 -0
  65. package/dist/assets/useVibe64DatabaseTools-d6L09ugW.js +1 -0
  66. package/dist/assets/useVibe64Learning-cNKTv64W.js +1 -0
  67. package/dist/assets/useVibe64ProjectScope-Bp1ImZlz.js +1 -0
  68. package/dist/assets/useVibe64SessionData-C_jqncih.js +1 -0
  69. package/dist/assets/useVibe64SessionSelection-uCEIWd3b.js +1 -0
  70. package/dist/assets/useVibe64SystemGraph-B4RmsC9Y.js +1 -0
  71. package/dist/assets/{useVibe64Terminal-BPnN25WH.js → useVibe64Terminal-BbghGR4x.js} +1 -1
  72. package/dist/assets/vibe64AssistantHost-BL1bnKm8.js +1 -0
  73. package/dist/assets/{vibe64SessionFocus-kqPOPaOH.js → vibe64SessionFocus-DSJKVuRN.js} +1 -1
  74. package/dist/assets/{vibe64SessionInfo-BHxtTrLX.js → vibe64SessionInfo-B_r1OMN0.js} +1 -1
  75. package/dist/assets/{vibe64SessionPanelModel-BMf64fv7.js → vibe64SessionPanelModel-DDorOuiL.js} +1 -1
  76. package/dist/assets/{vibe64SessionToolDefinitions-NfLd1HZI.js → vibe64SessionToolDefinitions-BualCK_5.js} +1 -1
  77. package/dist/index.html +21 -20
  78. package/docs/colleague-usage/account-profile-and-appearance.md +8 -2
  79. package/docs/colleague-usage/ai-accounts-and-routing.md +123 -15
  80. package/docs/colleague-usage/ai-onboarding.md +230 -0
  81. package/docs/colleague-usage/coding-agent-goal-pause.md +5 -5
  82. package/docs/colleague-usage/coding-agents.md +17 -0
  83. package/docs/colleague-usage/colleague-watches.md +4 -23
  84. package/docs/colleague-usage/colleague.md +10 -2
  85. package/docs/colleague-usage/connected-projects.md +2 -2
  86. package/docs/colleague-usage/conversation-context.md +2 -0
  87. package/docs/colleague-usage/dashboard-navigation.md +19 -27
  88. package/docs/colleague-usage/database.md +6 -11
  89. package/docs/colleague-usage/development-copies.md +2 -1
  90. package/docs/colleague-usage/development-env.md +6 -0
  91. package/docs/colleague-usage/github-work.md +9 -0
  92. package/docs/colleague-usage/health-checks.md +11 -5
  93. package/docs/colleague-usage/integrations.md +3 -1
  94. package/docs/colleague-usage/learning-code-questions.md +23 -51
  95. package/docs/colleague-usage/learning-course-catalogue.md +8 -6
  96. package/docs/colleague-usage/learning-environment.md +345 -0
  97. package/docs/colleague-usage/learning-history.md +70 -101
  98. package/docs/colleague-usage/learning-mode-ui.md +122 -214
  99. package/docs/colleague-usage/learning-practice-projects.md +168 -78
  100. package/docs/colleague-usage/learning-teacher-guide.md +48 -26
  101. package/docs/colleague-usage/learning-with-colleague.md +171 -216
  102. package/docs/colleague-usage/lesson-authoring.md +32 -24
  103. package/docs/colleague-usage/managed-app-access.md +7 -0
  104. package/docs/colleague-usage/message-delivery-recovery.md +7 -6
  105. package/docs/colleague-usage/preview-browser-checks.md +9 -1
  106. package/docs/colleague-usage/preview-starting-application.md +0 -1
  107. package/docs/colleague-usage/preview.md +9 -1
  108. package/docs/colleague-usage/project-messages.md +2 -2
  109. package/docs/colleague-usage/project-setup.md +9 -2
  110. package/docs/colleague-usage/running-vibe64-on-your-computer.md +61 -0
  111. package/docs/colleague-usage/sessions.md +25 -33
  112. package/docs/colleague-usage/teaching-content.md +11 -40
  113. package/docs/colleague-usage/temporary-chats.md +23 -2
  114. package/docs/colleague-usage/voice-chat.md +5 -10
  115. package/docs/colleague-usage/voice-face-and-speaking-voice.md +6 -8
  116. package/docs/colleague-usage/voice-recovery.md +3 -2
  117. package/docs/templates/learn-topic/README.md +6 -6
  118. package/docs/templates/learn-topic/training/lessons/TOPIC-01/lesson.json +28 -7
  119. package/docs/templates/learn-topic/training/lessons/TOPIC-01/notes.md +19 -0
  120. package/docs/templates/learn-topic/training/lessons/TOPIC-01/steps/check-understanding.md +3 -0
  121. package/docs/templates/learn-topic/training/lessons/TOPIC-01/steps/explain-idea.md +3 -0
  122. package/docs/templates/learn-topic/training/lessons/TOPIC-01/steps/try-it.md +3 -0
  123. package/docs/templates/learn-topic/training/outline.md +1 -1
  124. package/docs/training-content.md +179 -65
  125. package/node_modules/@jskit-ai/assistant-core/package.json +1 -1
  126. package/node_modules/@jskit-ai/assistant-runtime/package.json +1 -1
  127. package/node_modules/@jskit-ai/assistant-runtime/patterns/assistant-surface/PATTERN.md +3 -2
  128. package/node_modules/@jskit-ai/assistant-runtime/patterns/assistant-surface/example/integrations.json +3 -2
  129. package/node_modules/@jskit-ai/assistant-voice/package.json +1 -1
  130. package/node_modules/@jskit-ai/connectors-catalog/package.json +1 -1
  131. package/node_modules/@jskit-ai/connectors-catalog/patterns/ai-connections/PATTERN.md +4 -3
  132. package/node_modules/@jskit-ai/connectors-catalog/src/shared/ai-models.json +0 -1
  133. package/node_modules/@local/vibe64-accounts/package.json +1 -0
  134. package/node_modules/@local/vibe64-colleague/package.json +2 -1
  135. package/node_modules/@local/vibe64-core/package.json +3 -0
  136. package/node_modules/@local/vibe64-execution/package.json +1 -0
  137. package/node_modules/@local/vibe64-execution/src/host/execHelper.js +171 -174
  138. package/node_modules/@local/vibe64-execution/src/server/engines/stdioBridge.js +9 -9
  139. package/node_modules/@local/vibe64-genesis/README.md +10 -37
  140. package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +790 -779
  141. package/node_modules/@local/vibe64-genesis/package.json +1 -0
  142. package/node_modules/@local/vibe64-genesis/src/server/agentSpecs.js +255 -0
  143. package/node_modules/@local/vibe64-genesis/src/server/index.js +473 -450
  144. package/node_modules/@local/vibe64-genesis/src/server/promptContext.js +148 -148
  145. package/node_modules/@local/vibe64-project/package.json +2 -1
  146. package/node_modules/@local/vibe64-runtime/package.json +1 -2
  147. package/node_modules/@local/vibe64-runtime/src/server/codexAppServerProcess.js +526 -512
  148. package/node_modules/@local/vibe64-runtime/src/shared/assistantRoutingScores.json +0 -1
  149. package/node_modules/@local/vibe64-source-editor/package.json +1 -0
  150. package/node_modules/@local/vibe64-terminals/package.json +1 -0
  151. package/node_modules/@local/vibe64-terminals/src/server/opencodeSessionEnvironmentPlugin.js +129 -131
  152. package/node_modules/@local/vibe64-terminals/src/server/sessionWorkOperationCommand.js +1508 -1456
  153. package/node_modules/@local/vibe64-training/package.json +13 -27
  154. package/package.json +7 -7
  155. package/server.bundle.mjs +40946 -41456
  156. package/dist/assets/GithubBrowserTabs-DO5PHon-.js +0 -1
  157. package/dist/assets/GithubMarkdown-BQ6MfCDJ.js +0 -3
  158. package/dist/assets/GithubMarkdown-U7-j-qNI.css +0 -1
  159. package/dist/assets/Vibe64DashboardShell-CuCVMhOc.js +0 -1
  160. package/dist/assets/Vibe64OutputControls-DAAmA09l.js +0 -8
  161. package/dist/assets/Vibe64OutputControls-DPBsyDZM.css +0 -1
  162. package/dist/assets/Vibe64SessionFiles-B0u9HKdF.js +0 -107
  163. package/dist/assets/Vibe64SessionFiles-NjOMVwPR.css +0 -1
  164. package/dist/assets/_slug_-B31c15cc.css +0 -1
  165. package/dist/assets/_slug_-Dy35qLo1.js +0 -1
  166. package/dist/assets/app-DRXCcv05.css +0 -1
  167. package/dist/assets/app-zt7HwQKT.js +0 -1
  168. package/dist/assets/client-BrV4QPwG.js +0 -2
  169. package/dist/assets/client-C1bwIlu6.css +0 -1
  170. package/dist/assets/definitions-DaOPIkyB.js +0 -1
  171. package/dist/assets/env-DN0vW4EI.js +0 -1
  172. package/dist/assets/health-7oIQODer.css +0 -1
  173. package/dist/assets/health-Z6m96GDr.js +0 -1
  174. package/dist/assets/index-BUq-MczL.js +0 -86
  175. package/dist/assets/index-DtmBqE3h.css +0 -1
  176. package/dist/assets/issues-1iS5zoed.js +0 -1
  177. package/dist/assets/layout-BkWVNT37.js +0 -1
  178. package/dist/assets/mdi-C54lQ0i_.js +0 -1
  179. package/dist/assets/placement-DLsU3pCW.js +0 -1
  180. package/dist/assets/pull-requests-BJOwNL4k.js +0 -1
  181. package/dist/assets/settings-c273Ikrm.js +0 -1
  182. package/dist/assets/shared-YZb7ocaK.js +0 -2
  183. package/dist/assets/studioGateApi-DhA9IJGZ.js +0 -1
  184. package/dist/assets/studioUrls-Dj8rXeXO.js +0 -1
  185. package/dist/assets/useArchivedVibe64Sessions-CVZx2Rtm.js +0 -1
  186. package/dist/assets/useCommand-DWuxfAV0.js +0 -1
  187. package/dist/assets/useEndpointResource-MWVNfmMa.js +0 -1
  188. package/dist/assets/useVibe64ConversationLog-8cKh1eDm.js +0 -1
  189. package/dist/assets/useVibe64DatabaseTools-BcRG1s3i.js +0 -1
  190. package/dist/assets/useVibe64LearningMode-Bl0dGdCh.js +0 -28
  191. package/dist/assets/useVibe64LearningMode-C3PcXdVg.css +0 -1
  192. package/dist/assets/useVibe64ProjectScope-DOEVkBqX.js +0 -1
  193. package/dist/assets/useVibe64SessionData-DFTyLzci.js +0 -1
  194. package/dist/assets/useVibe64SessionSelection-j9lsllx4.js +0 -1
  195. package/dist/assets/useVibe64SystemGraph-tNkIwSBQ.js +0 -1
  196. package/dist/assets/vibe64AssistantHost-DdE_-lZF.js +0 -1
  197. package/dist/assets/vibe64LessonDashboard-DlKYjisq.js +0 -1
  198. package/dist/assets/vibe64ProjectScope.local-DqT6e5un.js +0 -1
  199. package/docs/colleague-usage/learning-chat-retention.md +0 -74
  200. package/docs/colleague-usage/learning-diagrams-and-voice.md +0 -97
  201. package/docs/colleague-usage/learning-lesson-watch.md +0 -95
  202. package/docs/colleague-usage/learning-native-session.md +0 -206
  203. package/docs/colleague-usage/learning-practical-exercises.md +0 -71
  204. package/docs/colleague-usage/learning-practical-gestures.md +0 -48
  205. package/docs/colleague-usage/learning-session-creation.md +0 -95
  206. package/docs/colleague-usage/lesson-practical-assessment.md +0 -54
  207. package/docs/colleague-usage/preview-lesson-presentation.md +0 -56
  208. package/docs/templates/learn-topic/training/lessons/TOPIC-01/lesson.md +0 -44
@@ -1,2 +0,0 @@
1
- var VIBE64_ASSISTANT_ENGINE_IDS=Object.freeze({CLAUDE:`claude`,CODEX:`codex`,OPENCODE:`opencode`});var VIBE64_ASSISTANT_TRANSPORT_IDS=Object.freeze({CLAUDE_STREAM_JSON:`claude_stream_json`,CODEX_APP_SERVER:`codex_app_server`,OPENCODE_SERVER:`opencode_server`});var VIBE64_ASSISTANT_SELECTION_SCHEMA=`vibe64.assistant-selection.v1`;var VIBE64_ASSISTANT_CATALOG_REVISION_PATTERN=/^sha256:[a-f0-9]{64}$/u;var VIBE64_ASSISTANT_ENGINE_ID_SET=new Set(Object.values(VIBE64_ASSISTANT_ENGINE_IDS));var VIBE64_ASSISTANT_SELECTION_ERROR_CODES=Object.freeze({CATALOG_STALE:`vibe64_assistant_catalog_stale`,CONNECTION_REQUIRED:`vibe64_assistant_connection_required`,ENGINE_IMMUTABLE:`vibe64_assistant_engine_immutable`,INVALID:`vibe64_assistant_selection_invalid`,TURN_ACTIVE:`vibe64_assistant_selection_turn_active`,UNAVAILABLE:`vibe64_assistant_selection_unavailable`});function record(value){return value&&typeof value===`object`&&!Array.isArray(value)?value:{}}function text(value=``){return String(value??``).trim()}function selectionError(code,message,details={}){const error=new Error(message);error.code=code;error.details=Object.freeze({...details});error.statusCode=409;return error}function containsControlCharacter(value=``){return Array.from(value).some(character=>{const codePoint=character.codePointAt(0);return codePoint<=31||codePoint===127})}function boundedIdentifier(value,field,{allowEmpty=false,maxLength=512}={}){const normalized=text(value);if(!normalized&&!allowEmpty||normalized.length>maxLength||containsControlCharacter(normalized))throw selectionError(VIBE64_ASSISTANT_SELECTION_ERROR_CODES.INVALID,`Assistant ${field} is invalid.`,{field});return normalized}function catalogRevision(value,field=`catalogRevision`){const revision=text(value);if(!VIBE64_ASSISTANT_CATALOG_REVISION_PATTERN.test(revision))throw selectionError(VIBE64_ASSISTANT_SELECTION_ERROR_CODES.INVALID,`Assistant catalog revision is invalid.`,{field});return revision}function defineVibe64AssistantSelection(value={}){const input=record(value);const engineId=boundedIdentifier(input.engineId,`engineId`,{maxLength:64});if(!VIBE64_ASSISTANT_ENGINE_ID_SET.has(engineId))throw selectionError(VIBE64_ASSISTANT_SELECTION_ERROR_CODES.INVALID,`Unknown assistant engine: ${engineId}.`,{engineId,field:`engineId`});const schema=text(input.schema)||`vibe64.assistant-selection.v1`;if(schema!==`vibe64.assistant-selection.v1`)throw selectionError(VIBE64_ASSISTANT_SELECTION_ERROR_CODES.INVALID,`Assistant selection schema is unsupported.`,{field:`schema`,schema});return Object.freeze({agentId:boundedIdentifier(input.agentId,`agentId`,{maxLength:256}),catalogRevision:catalogRevision(input.catalogRevision),engineId,modelId:boundedIdentifier(input.modelId,`modelId`),modelProviderId:boundedIdentifier(input.modelProviderId,`modelProviderId`,{maxLength:256}),schema,variantId:boundedIdentifier(input.variantId,`variantId`,{allowEmpty:true,maxLength:256})})}var model$1=(id,contextWindow,variants,options={})=>Object.freeze({id,contextWindow,variants:Object.freeze(variants),...options});var NATIVE_AI_PROVIDERS=Object.freeze([Object.freeze({id:`deepseek`,baseUrl:`https://api.deepseek.com/`,claudeBaseUrl:`https://api.deepseek.com/anthropic`,claudeAutoCompactWindow:786432,webSearch:false,models:Object.freeze([model$1(`deepseek-flash`,1048576,[`low`,`high`,`max`],{images:true,freeformPatch:true,codexHistoryRouting:true}),model$1(`deepseek-v4-pro`,1048576,[`low`,`high`,`max`],{freeformPatch:true})])}),Object.freeze({id:`zai-coding-plan`,baseUrl:`https://api.z.ai/api/v1`,claudeBaseUrl:`https://api.z.ai/api/anthropic`,claudeAutoCompactWindow:1e6,webSearch:false,models:Object.freeze([model$1(`glm-5.3`,1048576,[`low`,`high`,`max`],{freeformPatch:true,codexHistoryRouting:true})])}),Object.freeze({id:`zai`,baseUrl:`https://api.z.ai/api/v1`,claudeBaseUrl:`https://api.z.ai/api/anthropic`,claudeAutoCompactWindow:1e6,webSearch:false,models:Object.freeze([model$1(`glm-5.3`,1048576,[`low`,`high`,`max`],{freeformPatch:true,codexHistoryRouting:true})])})]);function nativeAiProvider(id){return NATIVE_AI_PROVIDERS.find(provider=>provider.id===id)||null}function nativeAiModel(id,providerId=``){for(const provider of NATIVE_AI_PROVIDERS){if(providerId&&provider.id!==providerId)continue;const model=provider.models.find(candidate=>candidate.id===id);if(model)return{...model,modelProviderId:provider.id}}return null}var model=(providerId,id,label,defaultThinking)=>{const{modelProviderId:_provider,...definition}=nativeAiModel(id,providerId);return Object.freeze({...definition,label,defaultThinking})};var CURATED_CODEX_PROVIDERS=Object.freeze([Object.freeze({...nativeAiProvider(`deepseek`),label:`DeepSeek`,description:`DeepSeek API key · usage-based billing`,keyUrl:`https://platform.deepseek.com/api_keys`,guideUrl:`https://api-docs.deepseek.com/quick_start/agent_integrations/codex/`,ownerOnly:false,models:Object.freeze([model(`deepseek`,`deepseek-flash`,`DeepSeek V4.1 Flash`,`high`),model(`deepseek`,`deepseek-v4-pro`,`DeepSeek V4 Pro`,`high`)])}),Object.freeze({...nativeAiProvider(`zai-coding-plan`),label:`GLM · Coding Plan`,description:`Z.AI Coding Plan key · uses your subscription quota`,keyUrl:`https://z.ai/manage-apikey/apikey-list`,guideUrl:`https://docs.z.ai/devpack/tool/codex`,ownerOnly:true,models:Object.freeze([model(`zai-coding-plan`,`glm-5.3`,`GLM 5.3`,`max`)])}),Object.freeze({...nativeAiProvider(`zai`),label:`GLM · Pay-as-you-go API`,description:`Z.AI API key · pay-as-you-go account`,keyUrl:`https://z.ai/manage-apikey/apikey-list`,guideUrl:`https://docs.z.ai/guides/overview/quick-start`,setupNote:`Use a key from a Z.AI account without a Coding Plan. Pay-as-you-go access through Codex and Claude Code still needs live verification; a successful check confirms model access, not billing.`,ownerOnly:false,models:Object.freeze([model(`zai`,`glm-5.3`,`GLM 5.3`,`max`)])})]);function curatedCodexProvider(id){return CURATED_CODEX_PROVIDERS.find(provider=>provider.id===id)||null}var VIBE64_AGENT_EXECUTION_PROFILE_IDS=Object.freeze({HELPER:`helper`});var VIBE64_AGENT_EXECUTION_WORKLOAD_IDS=Object.freeze({COMMIT_TITLE:`commit_title`,CONVERSATION_SUMMARY:`conversation_summary`,TRAINING_ASSESSMENT:`training_assessment`,VOICE_TURN:`voice_turn`,DATABASE_ASSISTANT:`database_assistant`,PROMPT_HINT:`prompt_hint`,REQUEST_ROUTING:`request_routing`,SESSION_TITLE:`session_title`,SOURCE_EXPLANATION:`source_explanation`});var VIBE64_AGENT_HELPER_WORKLOAD_LIMITS=Object.freeze({[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.COMMIT_TITLE]:Object.freeze({maxInputCharacters:24e3,maxOutputCharacters:512,timeoutMs:12e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.VOICE_TURN]:Object.freeze({maxInputCharacters:12e3,maxOutputCharacters:512,timeoutMs:1e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.TRAINING_ASSESSMENT]:Object.freeze({maxInputCharacters:24e3,maxOutputCharacters:8192,timeoutMs:12e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.CONVERSATION_SUMMARY]:Object.freeze({maxInputCharacters:2e5,maxOutputCharacters:16e3,timeoutMs:12e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.DATABASE_ASSISTANT]:Object.freeze({maxInputCharacters:5e5,maxOutputCharacters:16e3,timeoutMs:18e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.PROMPT_HINT]:Object.freeze({maxInputCharacters:24e3,maxOutputCharacters:2500,timeoutMs:12e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.REQUEST_ROUTING]:Object.freeze({maxInputCharacters:128e3,maxOutputCharacters:8192,timeoutMs:6e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.SESSION_TITLE]:Object.freeze({maxInputCharacters:24e3,maxOutputCharacters:512,timeoutMs:3e4}),[VIBE64_AGENT_EXECUTION_WORKLOAD_IDS.SOURCE_EXPLANATION]:Object.freeze({maxInputCharacters:1e5,maxOutputCharacters:32e3,timeoutMs:18e4})});var VIBE64_AGENT_EXECUTION_TOOL_POLICIES=Object.freeze({NONE:`none`});var VIBE64_AGENT_EXECUTION_PROFILE_LIMIT_CEILINGS=Object.freeze({MAX_INPUT_CHARACTERS:5e5,MAX_OUTPUT_CHARACTERS:32e3,MAX_TIMEOUT_MS:3e5});var VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES=Object.freeze({INVALID:`vibe64_agent_execution_profile_invalid`,MODEL_UNAVAILABLE:`vibe64_agent_execution_profile_model_unavailable`,POLICY_UNENFORCEABLE:`vibe64_agent_execution_profile_policy_unenforceable`,PROFILE_UNKNOWN:`vibe64_agent_execution_profile_unknown`,REASONING_UNSUPPORTED:`vibe64_agent_execution_profile_reasoning_unsupported`,UNBOUNDED:`vibe64_agent_execution_profile_unbounded`,UNSAFE:`vibe64_agent_execution_profile_unsafe`,WORKLOAD_UNSUPPORTED:`vibe64_agent_execution_profile_workload_unsupported`});var VIBE64_AGENT_EXECUTION_PROFILE_VALUES=new Set(Object.values(VIBE64_AGENT_EXECUTION_PROFILE_IDS));var VIBE64_AGENT_EXECUTION_WORKLOAD_VALUES=new Set(Object.values(VIBE64_AGENT_EXECUTION_WORKLOAD_IDS));var Vibe64AgentExecutionProfileError=class extends Error{constructor(code,message,details={}){super(message);this.name=`Vibe64AgentExecutionProfileError`;this.code=code;this.details=Object.freeze({...details});for(const[name,value]of Object.entries(this.details))if(![`code`,`details`,`message`,`name`].includes(name))this[name]=value}};function executionProfileError(code,message,details={}){return new Vibe64AgentExecutionProfileError(code,message,details)}function isPlainRecord(value){if(!value||typeof value!==`object`||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function requiredRecord(value,fieldName){if(!isPlainRecord(value))throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile ${fieldName} must be an object.`,{field:fieldName});return value}function requireOnlyFields(value,allowedFields,fieldName){const allowed=new Set(allowedFields);const unexpected=Object.keys(value).find(name=>!allowed.has(name));if(unexpected)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile ${fieldName} contains an unsupported field: ${unexpected}.`,{field:`${fieldName}.${unexpected}`})}function requiredText(value,fieldName,maximumLength=256){if(typeof value!==`string`)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile ${fieldName} must be text.`,{field:fieldName});const normalized=value.trim();if(!normalized||normalized.length>maximumLength)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile ${fieldName} is invalid.`,{field:fieldName});return normalized}function requiredBoolean(value,fieldName){if(typeof value!==`boolean`)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile ${fieldName} must be a boolean.`,{field:fieldName});return value}function requireSafeFalse(value,fieldName){if(requiredBoolean(value,fieldName)!==false)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.UNSAFE,`Execution profile ${fieldName} must be disabled.`,{field:fieldName});return false}function boundedPositiveInteger(value,fieldName,maximum){if(!Number.isSafeInteger(value)||value<=0||value>maximum)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.UNBOUNDED,`Execution profile ${fieldName} must be a positive integer no greater than ${maximum}.`,{field:fieldName,maximum});return value}function requiredLimits(value){if(!isPlainRecord(value))throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.UNBOUNDED,`Execution profile limits are required.`,{field:`limits`});return value}function normalizeProfileId(value){const profileId=requiredText(value,`profileId`,64);if(!VIBE64_AGENT_EXECUTION_PROFILE_VALUES.has(profileId))throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.PROFILE_UNKNOWN,`Unknown execution profile: ${profileId}.`,{profileId});return profileId}function normalizeWorkloadId(value){const workloadId=requiredText(value,`workloadId`,64);if(!VIBE64_AGENT_EXECUTION_WORKLOAD_VALUES.has(workloadId))throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.WORKLOAD_UNSUPPORTED,`Unsupported execution profile workload: ${workloadId}.`,{workloadId});return workloadId}function normalizedExecutionProfileRequest(input){return Object.freeze({profileId:normalizeProfileId(input.profileId),workloadId:normalizeWorkloadId(input.workloadId)})}function defineVibe64AgentExecutionProfileResolution(value){const input=requiredRecord(value,`resolution`);const executionProfile=normalizedExecutionProfileRequest(input);const request=requiredRecord(input.request,`request policy`);const policy=requiredRecord(input.policy,`tool policy`);const limits=requiredLimits(input.limits);requireOnlyFields(request,[`allowProviderModelFallback`,`reasoning`,`summary`],`request`);requireOnlyFields(policy,[`environmentAccess`,`networkAccess`,`repositoryWrite`,`tools`],`policy`);requireOnlyFields(limits,[`maxInputCharacters`,`maxOutputCharacters`,`timeoutMs`],`limits`);const reasoning=requiredBoolean(request.reasoning,`request.reasoning`);if(typeof input.thinking!==`string`)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile thinking must be text.`,{field:`thinking`});const thinking=input.thinking.trim();if(reasoning&&!thinking||!reasoning&&thinking)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.UNSAFE,`Execution profile thinking must agree with its reasoning request.`,{field:`thinking`});if(thinking.length>64)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.INVALID,`Execution profile thinking is invalid.`,{field:`thinking`});if(policy.tools!==VIBE64_AGENT_EXECUTION_TOOL_POLICIES.NONE)throw executionProfileError(VIBE64_AGENT_EXECUTION_PROFILE_ERROR_CODES.UNSAFE,`Execution profile tools must be disabled.`,{field:`policy.tools`});return Object.freeze({limits:Object.freeze({maxInputCharacters:boundedPositiveInteger(limits.maxInputCharacters,`limits.maxInputCharacters`,VIBE64_AGENT_EXECUTION_PROFILE_LIMIT_CEILINGS.MAX_INPUT_CHARACTERS),maxOutputCharacters:boundedPositiveInteger(limits.maxOutputCharacters,`limits.maxOutputCharacters`,VIBE64_AGENT_EXECUTION_PROFILE_LIMIT_CEILINGS.MAX_OUTPUT_CHARACTERS),timeoutMs:boundedPositiveInteger(limits.timeoutMs,`limits.timeoutMs`,VIBE64_AGENT_EXECUTION_PROFILE_LIMIT_CEILINGS.MAX_TIMEOUT_MS)}),model:requiredText(input.model,`model`),policy:Object.freeze({environmentAccess:requireSafeFalse(policy.environmentAccess,`policy.environmentAccess`),networkAccess:requireSafeFalse(policy.networkAccess,`policy.networkAccess`),repositoryWrite:requireSafeFalse(policy.repositoryWrite,`policy.repositoryWrite`),tools:VIBE64_AGENT_EXECUTION_TOOL_POLICIES.NONE}),profileId:executionProfile.profileId,providerId:requiredText(input.providerId,`providerId`,64),request:Object.freeze({allowProviderModelFallback:requireSafeFalse(request.allowProviderModelFallback,`request.allowProviderModelFallback`),reasoning,summary:requireSafeFalse(request.summary,`request.summary`)}),revision:requiredText(input.revision,`revision`,128),thinking,workloadId:executionProfile.workloadId})}function vibe64AgentExecutionProfileAuditSnapshot(value){return defineVibe64AgentExecutionProfileResolution(value)}var VIBE64_ASSISTANT_ACCESS_ERROR_CODES=Object.freeze({RESTRICTED:`vibe64_assistant_owner_required`,UNAVAILABLE:`vibe64_assistant_connection_unavailable`});var VIBE64_AGENT_PROVIDER_IDS=Object.freeze({CLAUDE:`claude`,CODEX:`codex`,OPENCODE:`opencode`});var VIBE64_AGENT_PROVIDER_UNKNOWN_CODE=`vibe64_agent_provider_unknown`;var VIBE64_AGENT_PARAMETER_IDS=Object.freeze({MODEL:`model`,THINKING:`thinking`});var VIBE64_DEFAULT_AGENT_PROVIDER_ID=VIBE64_AGENT_PROVIDER_IDS.CODEX;var VIBE64_CODEX_SOL_MODEL=`gpt-5.6-sol`;var VIBE64_CODEX_GPT_5_5_MODEL=`gpt-5.5`;var VIBE64_CODEX_DEFAULT_MODEL=VIBE64_CODEX_SOL_MODEL;var VIBE64_CODEX_DEFAULT_THINKING=`xhigh`;var VIBE64_CODEX_SPARK_MODEL=`gpt-5.3-codex-spark`;var VIBE64_CODEX_STANDARD_THINKING_VALUES=Object.freeze([`low`,`medium`,`high`,`xhigh`]);var VIBE64_CODEX_SOL_THINKING_VALUES=Object.freeze([...VIBE64_CODEX_STANDARD_THINKING_VALUES,`max`]);var VIBE64_AGENT_PROVIDERS=Object.freeze([Object.freeze({executionProfiles:Object.freeze([VIBE64_AGENT_EXECUTION_PROFILE_IDS.HELPER]),id:VIBE64_AGENT_PROVIDER_IDS.CODEX,implemented:true,label:`Codex`,parameters:Object.freeze([Object.freeze({id:VIBE64_AGENT_PARAMETER_IDS.MODEL,defaultValue:VIBE64_CODEX_DEFAULT_MODEL,label:`Model`,options:Object.freeze([Object.freeze({label:`Automatic (GPT-5.6 Sol)`,value:``}),Object.freeze({label:`GPT-5.6 Sol`,supportedThinking:VIBE64_CODEX_SOL_THINKING_VALUES,value:VIBE64_CODEX_DEFAULT_MODEL}),Object.freeze({label:`GPT-5.5`,supportedThinking:VIBE64_CODEX_STANDARD_THINKING_VALUES,value:VIBE64_CODEX_GPT_5_5_MODEL}),Object.freeze({label:`Codex Spark`,request:Object.freeze({summary:false}),supportedThinking:VIBE64_CODEX_STANDARD_THINKING_VALUES,value:VIBE64_CODEX_SPARK_MODEL})])}),Object.freeze({id:VIBE64_AGENT_PARAMETER_IDS.THINKING,defaultValue:VIBE64_CODEX_DEFAULT_THINKING,label:`Thinking`,options:Object.freeze([Object.freeze({label:`Automatic`,value:``}),Object.freeze({label:`Low`,value:`low`}),Object.freeze({label:`Medium`,value:`medium`}),Object.freeze({label:`High`,value:`high`}),Object.freeze({label:`X High`,value:`xhigh`}),Object.freeze({label:`Max`,value:`max`})])})])}),Object.freeze({executionProfiles:Object.freeze([VIBE64_AGENT_EXECUTION_PROFILE_IDS.HELPER]),id:VIBE64_AGENT_PROVIDER_IDS.CLAUDE,implemented:true,label:`Claude Code`,parameters:Object.freeze([])}),Object.freeze({executionProfiles:Object.freeze([]),id:VIBE64_AGENT_PROVIDER_IDS.OPENCODE,implemented:false,label:`OpenCode`,parameters:Object.freeze([])})]);function agentProviderDefinition(providerId=``){const normalizedProviderId=normalizeAgentSettingText(providerId)||VIBE64_DEFAULT_AGENT_PROVIDER_ID;const provider=VIBE64_AGENT_PROVIDERS.find(candidate=>candidate.id===normalizedProviderId);if(provider)return provider;const error=new Error(`Unknown assistant provider: ${normalizedProviderId}.`);error.code=VIBE64_AGENT_PROVIDER_UNKNOWN_CODE;error.providerId=normalizedProviderId;throw error}function agentProviderParameter(provider={},parameterId=``){const normalizedParameterId=normalizeAgentSettingText(parameterId);return(Array.isArray(provider.parameters)?provider.parameters:[]).find(parameter=>parameter.id===normalizedParameterId)||null}function normalizeAgentSettingText(value=``){return String(value||``).trim()}function normalizeVibe64AgentSettings(value={}){const input=value&&typeof value===`object`&&!Array.isArray(value)?value:{};const provider=agentProviderDefinition(input.providerId||input.provider);const model=normalizeAgentSettingText(input.model);return{model,providerId:provider.id,thinking:normalizedAgentThinkingValue(provider,model,input.thinking)}}function defaultVibe64AgentSettings(providerId=VIBE64_DEFAULT_AGENT_PROVIDER_ID){return normalizeVibe64AgentSettings({providerId})}function effectiveAgentParameterValue(provider={},parameterId=``,value=``){const parameter=agentProviderParameter(provider,parameterId);return normalizeAgentSettingText(value)||normalizeAgentSettingText(parameter?.defaultValue)}function effectiveAgentParameterOption(provider={},parameterId=``,value=``){const parameter=agentProviderParameter(provider,parameterId);const effectiveValue=effectiveAgentParameterValue(provider,parameterId,value);return(Array.isArray(parameter?.options)?parameter.options:[]).find(option=>normalizeAgentSettingText(option.value)===effectiveValue)||null}function supportedAgentThinkingValues(provider={},model=``){const modelOption=effectiveAgentParameterOption(provider,VIBE64_AGENT_PARAMETER_IDS.MODEL,model);return Array.isArray(modelOption?.supportedThinking)?new Set(modelOption.supportedThinking.map(value=>normalizeAgentSettingText(value))):null}function normalizedAgentThinkingValue(provider={},model=``,value=``){const normalized=normalizeAgentSettingText(value);if(provider.id===VIBE64_AGENT_PROVIDER_IDS.CODEX)return normalized;const supported=supportedAgentThinkingValues(provider,model);if(!supported||!normalized||supported.has(normalized))return normalized;const fallback=normalizeAgentSettingText(agentProviderParameter(provider,VIBE64_AGENT_PARAMETER_IDS.THINKING)?.defaultValue);return supported.has(fallback)?fallback:``}function vibe64AssistantSelectionLabel(selection,{includeThinking=true}={}){const engine=VIBE64_AGENT_PROVIDERS.find(({id})=>id===selection.engineId)?.label||selection.engineId;if(!includeThinking)return`${engine} (${selection.modelId})`;const thinking=selection.variantId===``?`default`:selection.variantId||`not recorded`;return`${engine} (${selection.modelId} ${thinking})`}var VIBE64_AGENT_TASK_STATES=Object.freeze({COMPLETED:`completed`,RUNNING:`running`,STARTING:`starting`,STOPPED:`stopped`,STOPPING:`stopping`,WAITING:`waiting`});var VIBE64_AGENT_TASK_ACTIVE_STATES=new Set([VIBE64_AGENT_TASK_STATES.RUNNING,VIBE64_AGENT_TASK_STATES.STARTING,VIBE64_AGENT_TASK_STATES.STOPPING,VIBE64_AGENT_TASK_STATES.WAITING]);var VIBE64_AGENT_TASK_RESULT_KINDS=Object.freeze({COMPLETE:`complete`,CONTINUE:`continue`});var VIBE64_AGENT_TASK_RESULT_SCHEMA=Object.freeze({additionalProperties:false,properties:{kind:{enum:Object.values(VIBE64_AGENT_TASK_RESULT_KINDS),type:`string`},message:{description:`Normal Markdown shown to the user for this task turn.`,type:`string`},report:{description:`A concise factual handoff for the main conversation when the task is complete; otherwise an empty string.`,type:`string`}},required:[`kind`,`message`,`report`],type:`object`});var VIBE64_CONVERSATION_ATTACHMENT_MAX_ITEMS=10;var VIBE64_CONVERSATION_ATTACHMENT_FILE_NAME_MAX_CHARACTERS=160;var ATTACHMENT_ID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;var IMAGE_TYPES=Object.freeze({avif:`image/avif`,bmp:`image/bmp`,gif:`image/gif`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,webp:`image/webp`});function conversationAttachmentContentType(fileName=``){const extension=String(fileName).split(`.`).at(-1).toLowerCase();return Object.hasOwn(IMAGE_TYPES,extension)?IMAGE_TYPES[extension]:`application/octet-stream`}function conversationAttachmentReference(attachment={},number=1){return`[${conversationAttachmentContentType(attachment.fileName).startsWith(`image/`)?`Image`:`File`} #${number}]`}function conversationAttachmentFileName(value=``){const normalized=Array.from(String(value??``),character=>{const codePoint=character.codePointAt(0);return codePoint<=31||codePoint===127?` `:character}).join(``).trim();return Array.from(normalized).slice(0,VIBE64_CONVERSATION_ATTACHMENT_FILE_NAME_MAX_CHARACTERS).join(``)}function normalizeVibe64ConversationAttachments(value=[]){return(Array.isArray(value)?value:[]).slice(0,VIBE64_CONVERSATION_ATTACHMENT_MAX_ITEMS).map(candidate=>{if(!candidate||typeof candidate!==`object`||Array.isArray(candidate)||typeof candidate.fileName!==`string`)return null;const fileName=conversationAttachmentFileName(candidate.fileName);if(!fileName)return null;return{...ATTACHMENT_ID_PATTERN.test(String(candidate.attachmentId||``))?{attachmentId:candidate.attachmentId}:{},.../^\[(?:Image|File) #[1-9][0-9]{0,3}\]$/u.test(candidate.reference||``)?{reference:candidate.reference}:{},fileName,...Number.isSafeInteger(candidate.size)&&candidate.size>=0?{size:candidate.size}:{}}}).filter(Boolean)}var VIBE64_PROMPT_HINT_LABEL_MAX_CHARACTERS=24;var VIBE64_PROMPT_HINT_PROMPT_MAX_CHARACTERS=108;function normalizedPromptHintDraft(value=``){return Array.from(String(value??``).replace(/\r\n?/gu,`
2
- `).trim()).slice(-4e3).join(``)}var VIBE64_PROMPT_HINT_OUTPUT_SCHEMA=Object.freeze({additionalProperties:false,properties:Object.freeze({suggestions:Object.freeze({items:Object.freeze({additionalProperties:false,properties:Object.freeze({label:Object.freeze({maxLength:24,minLength:1,type:`string`}),prompt:Object.freeze({maxLength:108,minLength:1,type:`string`})}),required:Object.freeze([`label`,`prompt`]),type:`object`}),maxItems:3,minItems:3,type:`array`})}),required:Object.freeze([`suggestions`]),type:`object`});var VIBE64_PROMPT_HINT_STATIC_STARTERS=Object.freeze({existingProject:Object.freeze([Object.freeze({label:`Tour this project`,prompt:`Give me a quick tour of this project`}),Object.freeze({label:`Find first improvement`,prompt:`What should I improve first?`}),Object.freeze({label:`Plan safe change`,prompt:`Help me plan a small safe change`})]),greenfield:Object.freeze([Object.freeze({label:`Shape app idea`,prompt:`Help me shape my app idea`}),Object.freeze({label:`Plan first version`,prompt:`Show me the simplest useful first version`}),Object.freeze({label:`Decide first steps`,prompt:`What should we decide first?`})])});function normalizedPromptHintSuggestion(suggestion={}){if(!suggestion||typeof suggestion!==`object`||Array.isArray(suggestion)||Object.keys(suggestion).length!==2||!Object.hasOwn(suggestion,`label`)||!Object.hasOwn(suggestion,`prompt`)||typeof suggestion.label!==`string`||typeof suggestion.prompt!==`string`||[suggestion.label,suggestion.prompt].some(text=>Array.from(text).some(character=>{const codePoint=character.codePointAt(0);return codePoint<=31||codePoint===127})))return null;const label=suggestion.label.trim().replace(/[\t ]+/gu,` `);const prompt=suggestion.prompt.trim().replace(/[\t ]+/gu,` `);const labelWordCount=label?label.split(/\s+/u).length:0;return label&&prompt&&Array.from(label).length<=24&&Array.from(prompt).length<=108&&labelWordCount>=2&&labelWordCount<=4?{label,prompt}:null}function normalizedPromptHintSuggestions(value=[]){if(!Array.isArray(value)||value.length!==3)return[];const suggestions=value.map(normalizedPromptHintSuggestion).filter(Boolean);return suggestions.length===3&&new Set(suggestions.map(({label})=>label.toLocaleLowerCase())).size===3&&new Set(suggestions.map(({prompt})=>prompt.toLocaleLowerCase())).size===3?suggestions:[]}export{curatedCodexProvider as _,conversationAttachmentReference as a,vibe64AssistantSelectionLabel as c,defaultVibe64AgentSettings as d,normalizeVibe64AgentSettings as f,CURATED_CODEX_PROVIDERS as g,vibe64AgentExecutionProfileAuditSnapshot as h,conversationAttachmentContentType as i,VIBE64_AGENT_PROVIDERS as l,VIBE64_AGENT_EXECUTION_WORKLOAD_IDS as m,normalizedPromptHintSuggestion as n,normalizeVibe64ConversationAttachments as o,VIBE64_ASSISTANT_ACCESS_ERROR_CODES as p,normalizedPromptHintSuggestions as r,VIBE64_AGENT_TASK_RESULT_SCHEMA as s,normalizedPromptHintDraft as t,VIBE64_DEFAULT_AGENT_PROVIDER_ID as u,VIBE64_ASSISTANT_ENGINE_IDS as v,defineVibe64AssistantSelection as y};
@@ -1 +0,0 @@
1
- import{o as vibe64ProjectQueryScope}from"./vibe64ProjectScope.local-DqT6e5un.js";import{i as studioApiPath}from"./studioUrls-Dj8rXeXO.js";var VIBE64_PROJECT_CREATE_API_SUFFIX=`/vibe64/projects`;var VIBE64_ENV_SECRET_REVEAL_API_SUFFIX=`/vibe64/env/reveal`;var VIBE64_DEVELOPMENT_DATABASE_API_SUFFIX=`/vibe64/settings/development-database`;var VIBE64_ENGINEERING_API_SUFFIX=`/vibe64/settings/engineering`;var VIBE64_COLLABORATION_API_SUFFIX=`/vibe64/settings/collaboration`;var VIBE64_PROMPT_HINTS_SETTINGS_API_SUFFIX=`/vibe64/settings/prompt-hints`;var VIBE64_ENV_USER_VALUES_API_SUFFIX=`/vibe64/env/user-values`;var VIBE64_PREVIEW_IDENTITIES_API_SUFFIX=`/vibe64/preview-identities`;var VIBE64_PROJECT_SELECT_API_SUFFIX=`/vibe64/projects/select`;var VIBE64_CONNECTIONS_CHANGED_EVENT=`vibe64.connections.changed`;var VIBE64_PROJECT_CHANGED_EVENT=`vibe64.project.changed`;var TARGET_PROJECT_ENDPOINT=studioApiPath(`studio/current-app`);var STUDIO_HEALTH_ENDPOINT=studioApiPath(`studio/health`);var VIBE64_ENDPOINT=studioApiPath(`vibe64`);var PROJECT_SELECTION_ENDPOINT=`${VIBE64_ENDPOINT}/projects`;var ENV_ENDPOINT=`${VIBE64_ENDPOINT}/env`;var ENV_SECRET_REVEAL_ENDPOINT=`${ENV_ENDPOINT}/reveal`;var PROJECT_SETTINGS_ENDPOINT=`${VIBE64_ENDPOINT}/settings`;var DEVELOPMENT_DATABASE_ENDPOINT=`${PROJECT_SETTINGS_ENDPOINT}/development-database`;var ENGINEERING_ENDPOINT=`${PROJECT_SETTINGS_ENDPOINT}/engineering`;var COLLABORATION_ENDPOINT=`${PROJECT_SETTINGS_ENDPOINT}/collaboration`;var PROMPT_HINTS_SETTINGS_ENDPOINT=`${PROJECT_SETTINGS_ENDPOINT}/prompt-hints`;var ENV_USER_VALUES_ENDPOINT=`${ENV_ENDPOINT}/user-values`;var PREVIEW_IDENTITIES_ENDPOINT=`${VIBE64_ENDPOINT}/preview-identities`;function projectSelectionQueryKey(surfaceId,ownershipFilter,projectSlug){return[`vibe64`,...vibe64ProjectQueryScope(projectSlug),surfaceId,ownershipFilter,`projects`]}function envQueryKey(surfaceId,ownershipFilter,projectSlug){return[`vibe64`,...vibe64ProjectQueryScope(projectSlug),surfaceId,ownershipFilter,`env`]}function projectSettingsQueryKey(surfaceId,ownershipFilter,projectSlug,sessionId=``){return[`vibe64`,...vibe64ProjectQueryScope(projectSlug),surfaceId,ownershipFilter,`settings`,String(sessionId||``).trim()||`selected-source`]}function engineeringSettingsQueryKey(surfaceId,ownershipFilter,projectSlug,sessionId=``){return[`vibe64`,...vibe64ProjectQueryScope(projectSlug),surfaceId,ownershipFilter,`engineering`,String(sessionId||``).trim()||`selected-source`]}function previewIdentitiesQueryKey(surfaceId,ownershipFilter,projectSlug){return[`vibe64`,...vibe64ProjectQueryScope(projectSlug),surfaceId,ownershipFilter,`preview-identities`]}function studioHealthQueryKey(surfaceId,ownershipFilter){return[`vibe64`,surfaceId,ownershipFilter,`studio-health`]}export{engineeringSettingsQueryKey as C,projectSettingsQueryKey as D,projectSelectionQueryKey as E,studioHealthQueryKey as O,VIBE64_PROMPT_HINTS_SETTINGS_API_SUFFIX as S,previewIdentitiesQueryKey as T,VIBE64_ENV_USER_VALUES_API_SUFFIX as _,ENV_SECRET_REVEAL_ENDPOINT as a,VIBE64_PROJECT_CREATE_API_SUFFIX as b,PROJECT_SELECTION_ENDPOINT as c,STUDIO_HEALTH_ENDPOINT as d,VIBE64_COLLABORATION_API_SUFFIX as f,VIBE64_ENV_SECRET_REVEAL_API_SUFFIX as g,VIBE64_ENGINEERING_API_SUFFIX as h,ENV_ENDPOINT as i,PROJECT_SETTINGS_ENDPOINT as l,VIBE64_DEVELOPMENT_DATABASE_API_SUFFIX as m,DEVELOPMENT_DATABASE_ENDPOINT as n,ENV_USER_VALUES_ENDPOINT as o,VIBE64_CONNECTIONS_CHANGED_EVENT as p,ENGINEERING_ENDPOINT as r,PREVIEW_IDENTITIES_ENDPOINT as s,COLLABORATION_ENDPOINT as t,PROMPT_HINTS_SETTINGS_ENDPOINT as u,VIBE64_PREVIEW_IDENTITIES_API_SUFFIX as v,envQueryKey as w,VIBE64_PROJECT_SELECT_API_SUFFIX as x,VIBE64_PROJECT_CHANGED_EVENT as y};
@@ -1 +0,0 @@
1
- import{t as resolveScopedApiBasePath}from"./surface-DY1u73tB.js";import{t as currentProjectSlugFromLocation}from"./vibe64ProjectScope.local-DqT6e5un.js";function studioApiPath(relativePath){return resolveScopedApiBasePath({routeBase:`/`,relativePath,strictParams:false})}function resolveStudioRequestUrl(url){return scopedDevelopmentApiUrl(url,currentProjectSlugFromLocation())}function scopedDevelopmentApiUrl(url,slug=currentProjectSlugFromLocation(),{scopeGlobalPaths=false}={}){const projectSlug=String(slug||``).trim();if(!projectSlug)return url;const source=String(url||``).trim();if(!source)return url;const absolute=/^[a-z][a-z0-9+.-]*:\/\//iu.test(source);const base=typeof window===`undefined`?`http://vibe64.local`:window.location.origin;const parsed=new URL(source,base);const pathname=scopedDevelopmentApiPathname(parsed.pathname,projectSlug,{scopeGlobalPaths});if(pathname===parsed.pathname)return url;parsed.pathname=pathname;return absolute?parsed.toString():`${parsed.pathname}${parsed.search}${parsed.hash}`}function scopedDevelopmentApiPathname(pathname=``,slug=``,{scopeGlobalPaths=false}={}){const normalizedPathname=String(pathname||``).trim();if(!slug||normalizedPathname.startsWith(`/api/app/`)||!scopeGlobalPaths&&isGlobalApiPathname(normalizedPathname)||!isDevelopmentApiPathname(normalizedPathname))return normalizedPathname;return`/api/app/${encodeURIComponent(slug)}${normalizedPathname.slice(4)}`}function isGlobalApiPathname(pathname=``){return pathname===`/api/studio/health`||pathname===`/api/studio/browser-lifecycle/ws`||pathname===`/api/vibe64/projects`||pathname.startsWith(`/api/vibe64/projects/`)||pathname===`/api/vibe64/colleague`||pathname.startsWith(`/api/vibe64/colleague/`)||pathname===`/api/vibe64/training`||pathname.startsWith(`/api/vibe64/training/`)||pathname===`/api/vibe64/voice`||pathname.startsWith(`/api/vibe64/voice/`)||pathname===`/api/vibe64/launcher`||pathname.startsWith(`/api/vibe64/launcher/`)||pathname===`/api/vibe64/github`||pathname.startsWith(`/api/vibe64/github/`)}function isDevelopmentApiPathname(pathname=``){return pathname===`/api/studio`||pathname.startsWith(`/api/studio/`)||pathname===`/api/vibe64`||pathname.startsWith(`/api/vibe64/`)}function resolveWebSocketUrl(pathname,browserWindow=window){const protocol=browserWindow.location.protocol===`https:`?`wss:`:`ws:`;const scopedPathname=scopedDevelopmentApiUrl(pathname,currentProjectSlugFromLocation());return`${protocol}//${browserWindow.location.host}${scopedPathname}`}export{studioApiPath as i,resolveWebSocketUrl as n,scopedDevelopmentApiUrl as r,resolveStudioRequestUrl as t};
@@ -1 +0,0 @@
1
- import{Ht as watch,g as computed,hn as proxyRefs}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{T as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource}from"./useEndpointResource-MWVNfmMa.js";import{g as useRoute}from"./useApi-BPuI6ZR9-CFWU1m37.js";import{r as projectAppPath}from"./vibe64ProjectScope.local-DqT6e5un.js";import{Fn as mdiRefresh,Kn as mdiSourceCommit,Wn as mdiSourceBranch,ht as mdiEyeOutline,m as mdiArchiveOutline,xt as mdiFileDocumentOutline}from"./mdi-C54lQ0i_.js";import{t as usePaths}from"./usePaths-Db88-HOm.js";import{t as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DOEVkBqX.js";import{i as lessonDashboardApiPath,s as useVibe64LessonDashboard}from"./vibe64LessonDashboard-DlKYjisq.js";import{C as VIBE64_ARCHIVED_SESSIONS_API_SUFFIX,Q as vibe64SessionPath,T as VIBE64_SESSIONS_API_SUFFIX,nt as vibe64SessionQueryKey,rt as vibe64SessionsQueryKey}from"./index-BUq-MczL.js";import{n as enrichVibe64SessionForDisplay}from"./vibe64SessionPanelModel-BMf64fv7.js";import{c as vibe64SessionStatusLabel,r as shortVibe64SessionId,s as vibe64SessionStatusColor}from"./vibe64SessionViewModel-DR4tOlGM.js";import{t as useVibe64ConversationLog}from"./useVibe64ConversationLog-8cKh1eDm.js";var archivedVibe64SessionsEmits=[`loading-changed`];var archivedAtFormatter=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`});var archivedVibe64SessionsProps={description:{default:``,type:String},emptyText:{default:``,type:String},emptyTitle:{default:`No sessions`,type:String},showRefresh:{default:true,type:Boolean},title:{default:``,type:String}};function useArchivedVibe64Sessions(emit){const paths=usePaths();const projectSlug=useVibe64ProjectSlug();const lessonDashboard=useVibe64LessonDashboard();const sessionsApiPath=computed(()=>lessonDashboardApiPath(lessonDashboard.value,paths.api(VIBE64_ARCHIVED_SESSIONS_API_SUFFIX,{surface:`app`})));const sessionListResource=useEndpointResource({fallbackLoadError:`Archived sessions could not be loaded.`,path:sessionsApiPath,queryKey:computed(()=>[...vibe64SessionsQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,lessonDashboard.value?`lesson:${lessonDashboard.value.attemptId}`:projectSlug.value),`archived`]),requestRecoveryLabel:`Archived sessions`});const loading=computed(()=>Boolean(sessionListResource.isLoading.value));const error=computed(()=>String(sessionListResource.loadError.value||``));const sessions=computed(()=>{const payload=sessionListResource.data.value;return(Array.isArray(payload?.sessions)?payload.sessions:[]).map(enrichVibe64SessionForDisplay).filter(sessionIsInArchive)});watch(loading,isLoading=>{emit(`loading-changed`,isLoading)},{immediate:true});return{archiveIcon:mdiArchiveOutline,unavailableSessions:computed(()=>sessionListResource.data.value?.unavailableSessions||[]),error,loadSessions,loading,formatArchivedAt,mdiEyeOutline,mdiRefresh,mdiSourceBranch,sessionRoute,sessions,shortSessionId,statusColor,statusLabel};function sessionIsInArchive(session={}){return String(session.status||``)===`archived`}async function loadSessions(){await sessionListResource.reload()}function sessionRoute(session={}){return archivedSessionDetailRoute({projectSlug:projectSlug.value,sessionId:session.sessionId})}}function useArchivedVibe64SessionDetail(){const route=useRoute();const paths=usePaths();const projectSlug=useVibe64ProjectSlug(route);const sessionId=computed(()=>firstRouteParam(route.params.sessionId));const lessonDashboard=useVibe64LessonDashboard();const sessionsApiPath=computed(()=>lessonDashboardApiPath(lessonDashboard.value,paths.api(VIBE64_SESSIONS_API_SUFFIX,{surface:`app`})));const sessionPath=computed(()=>sessionId.value?vibe64SessionPath(sessionsApiPath.value,sessionId.value):``);const sessionResource=useEndpointResource({enabled:computed(()=>Boolean(sessionId.value)),fallbackLoadError:`Archived session could not be loaded.`,path:sessionPath,queryKey:computed(()=>[...vibe64SessionQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,lessonDashboard.value?`lesson:${lessonDashboard.value.attemptId}`:projectSlug.value),`archive-detail`,sessionId.value]),readQuery:computed(()=>projectSlug.value&&!lessonDashboard.value?{projectSlug:projectSlug.value}:null),requestRecoveryLabel:`Archived session`});const session=computed(()=>{const payload=sessionResource.data.value;if(!payload||typeof payload!==`object`||Array.isArray(payload))return null;if(String(payload.sessionId||``).trim()!==sessionId.value)return null;const enrichedSession=enrichVibe64SessionForDisplay(payload);return String(enrichedSession.status||``)===`archived`?enrichedSession:null});return{backTo:computed(()=>({path:`${projectAppPath(projectSlug.value)}/dashboard/history`})),conversationLog:proxyRefs(useVibe64ConversationLog({active:computed(()=>Boolean(session.value)),session,sessionsApiPath,learningAttemptId:lessonDashboard.value?.attemptId})),error:computed(()=>String(sessionResource.loadError.value||``)),loading:computed(()=>Boolean(sessionResource.isLoading.value||sessionResource.isInitialLoading?.value)),mdiRefresh,reload:sessionResource.reload,session,sessionId,sessionsApiPath,projectSlug}}function shortSessionId(sessionId){return shortVibe64SessionId(sessionId)}function statusLabel(status){return vibe64SessionStatusLabel(status)}function statusColor(status){return vibe64SessionStatusColor(status)}function formatArchivedAt(value=``){const date=new Date(String(value||``));return Number.isNaN(date.getTime())?`time unavailable`:archivedAtFormatter.format(date)}function archivedSessionDetailRoute({projectSlug=``,sessionId=``}={}){return{path:`${projectAppPath(projectSlug)}/dashboard/history/${encodeURIComponent(String(sessionId||``).trim())}`}}function firstRouteParam(value){return String(Array.isArray(value)?value[0]:value||``).trim()}function metadataValue(session={},name=``){return String(session.metadata?.[name]||``).trim()}function archiveFactRows(session={}){return[{icon:mdiSourceBranch,label:`Branch`,value:session.branch||metadataValue(session,`source_recovery_branch`)},{icon:mdiSourceCommit,label:`Head`,value:metadataValue(session,`source_recovery_head`)||metadataValue(session,`base_commit`)},{icon:mdiFileDocumentOutline,label:`Saved patch`,value:metadataValue(session,`source_recovery_patch_artifact`)||`No saved patch`},{icon:mdiFileDocumentOutline,label:`Untracked files`,value:metadataValue(session,`source_recovery_untracked_artifact`)||`No saved untracked archive`}].filter(row=>row.value)}export{useArchivedVibe64SessionDetail as a,shortSessionId as i,archivedVibe64SessionsEmits as n,useArchivedVibe64Sessions as o,archivedVibe64SessionsProps as r,archiveFactRows as t};
@@ -1 +0,0 @@
1
- import{Ht as watch,On as unref,g as computed,gn as reactive,hn as proxyRefs}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{n as useShellWebErrorRuntime}from"./error-Dug56can.js";import{J as useQueryClient,S as resolveTextRef,_ as resolvePermissionAccess,b as ROUTE_VISIBILITY_WORKSPACE,d as normalizeAccessMode,f as normalizeOwnershipFilter,g as resolveEnabled,h as resolveApiSuffix,l as asPlainObject,m as resolveAccessModeEnabled,p as normalizePermissions,r as useOperationRealtime,t as useEndpointResource,u as ensureAccessModeCompatibility,v as resolveQueryKey,x as resolveEnabledRef}from"./useEndpointResource-MWVNfmMa.js";import{a as normalizeSurfaceId,n as resolveScopedRouteBase}from"./surface-DY1u73tB.js";import{r as resolveSurfaceDefinitionFromPlacementContext,s as useWebPlacementContext}from"./placement-CwTqWLQH.js";import{b as hasPermission,g as createValidationFailure,k as resolveFieldErrors,u as getHttpWebClient,w as validateSchemaPayload,x as normalizePermissionList}from"./vibe64ProjectScope.local-DqT6e5un.js";import{d as normalizeText}from"./normalize-CO2KHj_d.js";import{r as useSurfaceRouteContext,t as usePaths}from"./usePaths-Db88-HOm.js";import{t as useUiFeedback}from"./useUiFeedback-0FqKuZRP.js";function validateOperationInput({input,rawPayload={},fieldBag=null,feedback=null,validationMessage=`Validation failed.`}={}){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 failure=createValidationFailure({error:String(validationMessage||`Validation failed.`),code:`validation_failed`,fieldErrors:error?.fieldErrors});fieldBag?.apply?.(resolveFieldErrors(failure));feedback?.error?.(failure,failure.error);return{ok:false,failure,parsedInput:null}}}function useCommandCore({model,resource,writeMethod=`POST`,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions,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=typeof buildRawPayload===`function`?buildRawPayload(model,{queryClient,resource,context}):{};const validationResult=validateOperationInput({input,rawPayload,fieldBag,feedback,validationMessage:String(messages.validation||`Validation failed.`)});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=typeof buildCommandOptions===`function`?buildCommandOptions(parsedInput,{rawPayload,queryClient,resource,context}):{};try{const response=await resource.save(payload,options);if(typeof onRunSuccess===`function`)await onRunSuccess(response,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});if(!suppressSuccessMessage)feedback?.success?.(String(messages.success||`Completed.`));return response}catch(error){fieldBag?.apply?.(resolveFieldErrors(error));if(typeof onRunError===`function`)await onRunError(error,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});feedback?.error?.(error,String(messages.error||`Unable to complete action.`));throw error}}return Object.freeze({running,fieldErrors,message,messageType,run})}function asPermissionList(value){if(Array.isArray(value))return value;if(value===void 0||value===null||value===``)return[];return[value]}function useAccess({scopeParamValue=``,enabled=true,access=`always`,hasPermissionRequirements=false}={}){const normalizedAccessMode=normalizeAccessMode(access);const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements:hasPermissionRequirements===true});const{context:placementContext}=useWebPlacementContext();const normalizedScopeParamValue=computed(()=>resolveTextRef(scopeParamValue));const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&accessRequired);const hasPlacementBootstrapPermissions=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||!hasPlacementBootstrapPermissions.value)return[];return placementPermissions.value});const bootstrapError=computed(()=>{if(!queryEnabled.value||hasPlacementBootstrapPermissions.value)return``;return`Permissions are unavailable in placement context.`});const isBootstrapping=computed(()=>queryEnabled.value&&!hasPlacementBootstrapPermissions.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}async function refreshBootstrap(){return null}return Object.freeze({accessMode:normalizedAccessMode,accessRequired,scopeParamValue:normalizedScopeParamValue,permissions,bootstrapError,isBootstrapping,can,canAny,canAll,refreshBootstrap})}var ROUTE_PARAM_NAME_PATTERN=/^[A-Za-z][A-Za-z0-9_]*$/;function normalizeRouteParamName(value=``,{context=`http-web route param`}={}){const normalizedValue=String(value||``).trim();if(!normalizedValue)throw new TypeError(`${context} must be a non-empty route parameter name.`);if(!ROUTE_PARAM_NAME_PATTERN.test(normalizedValue))throw new TypeError(`${context} "${normalizedValue}" is invalid. Use letters, numbers, and underscores only.`);return normalizedValue}function toRouteParamValue(value){if(Array.isArray(value))return toRouteParamValue(value[0]);if(value==null)return``;return String(value).trim()}function resolveRouteSourceValue(source=null){if(typeof source===`function`)return source();return unref(source)}function resolveRouteParamsSource(source=null){return asPlainObject(resolveRouteSourceValue(source))}function normalizeRouteParamNameList(value=[]){return(Array.isArray(value)?value:[]).map(entry=>String(entry||``).trim()).filter(Boolean)}function resolveRouteParamNamesSource(source=[]){return normalizeRouteParamNameList(resolveRouteSourceValue(source))}function normalizeRoutePathname(value=``){const sanitizedPathname=String(value||``).trim().split(/[?#]/u,1)[0]||``;if(!sanitizedPathname)return`/`;return sanitizedPathname.startsWith(`/`)?sanitizedPathname:`/${sanitizedPathname}`}function resolveRoutePathnameSource(source=``){return normalizeRoutePathname(resolveRouteSourceValue(source))}function segmentMatchesParamValue(segment=``,paramValue=``){const normalizedSegment=String(segment||``).trim();const normalizedParamValue=toRouteParamValue(paramValue);if(!normalizedSegment||!normalizedParamValue)return false;if(normalizedSegment===encodeURIComponent(normalizedParamValue))return true;try{return decodeURIComponent(normalizedSegment)===normalizedParamValue}catch{return false}}function findRouteParamSegmentIndex(segments=[],paramValue=``,fromIndex=0){const source=Array.isArray(segments)?segments:[];const cursor=Number.isInteger(fromIndex)&&fromIndex>0?fromIndex:0;for(let index=cursor;index<source.length;index+=1)if(segmentMatchesParamValue(source[index],paramValue))return index;return-1}function normalizePathPrefix(segments=[],endIndex=-1){const source=Array.isArray(segments)?segments:[];if(!Number.isInteger(endIndex)||endIndex<0)return`/`;return`/${source.slice(0,endIndex+1).join(`/`)}`}function resolveAnchorEndIndex(segmentIndex=-1,totalSegments=0,anchorMode=`at`){const normalizedSegmentIndex=Number.isInteger(segmentIndex)?segmentIndex:-1;if(normalizedSegmentIndex<0)return-1;const normalizedTotalSegments=Number.isInteger(totalSegments)&&totalSegments>0?totalSegments:0;const normalizedMode=String(anchorMode||`at`).trim().toLowerCase();if(normalizedMode===`before`)return normalizedSegmentIndex-1;if(normalizedMode===`after`)return normalizedTotalSegments>0?Math.min(normalizedSegmentIndex+1,normalizedTotalSegments-1):normalizedSegmentIndex+1;return normalizedSegmentIndex}function resolveScopedRoutePathname({currentPathname=`/`,params={},orderedParamNames=[],anchorParamName=``,anchorParamValue=``,anchorMode=`at`}={}){const normalizedCurrentPathname=resolveRoutePathnameSource(currentPathname);const normalizedAnchorParamName=String(anchorParamName||``).trim();if(!normalizedAnchorParamName)return normalizedCurrentPathname;const sourceParams=asPlainObject(params);const segments=normalizedCurrentPathname.split(`/`).filter(Boolean);if(segments.length<1)return normalizedCurrentPathname;const paramNames=resolveRouteParamNamesSource(orderedParamNames);let cursor=0;for(const paramName of paramNames){const segmentIndex=findRouteParamSegmentIndex(segments,sourceParams[paramName],cursor);if(segmentIndex<0)continue;if(paramName===normalizedAnchorParamName)return normalizePathPrefix(segments,resolveAnchorEndIndex(segmentIndex,segments.length,anchorMode));cursor=segmentIndex+1}const fallbackAnchorValue=toRouteParamValue(anchorParamValue)||toRouteParamValue(sourceParams[normalizedAnchorParamName]);if(!fallbackAnchorValue)return normalizedCurrentPathname;const fallbackSegmentIndex=findRouteParamSegmentIndex(segments,fallbackAnchorValue,0);if(fallbackSegmentIndex<0)return normalizedCurrentPathname;return normalizePathPrefix(segments,resolveAnchorEndIndex(fallbackSegmentIndex,segments.length,anchorMode))}function resolveRouteTemplatePath(routeTemplate=``,params={}){const normalizedTemplate=String(routeTemplate||``).trim();if(!normalizedTemplate)return``;const source=asPlainObject(params);const missingParams=[];const resolvedPath=normalizedTemplate.replace(/:([A-Za-z][A-Za-z0-9_]*)/g,(_,key)=>{const value=toRouteParamValue(source[key]);if(!value){missingParams.push(key);return`:${key}`}return encodeURIComponent(value)});if(missingParams.length>0)return``;return resolvedPath}function resolveRouteTemplateLocation(routeTemplate=``,{params={},currentPathname=`/`}={}){const resolvedTemplatePath=resolveRouteTemplatePath(routeTemplate,params);if(!resolvedTemplatePath)return``;if(resolvedTemplatePath.startsWith(`/`))return resolvedTemplatePath;const normalizedCurrentPathname=resolveRoutePathnameSource(currentPathname);const basePathname=normalizedCurrentPathname.endsWith(`/`)?normalizedCurrentPathname:`${normalizedCurrentPathname}/`;const resolvedPathname=new URL(resolvedTemplatePath,`https://jskit.local${basePathname}`).pathname;if(resolvedPathname.length>1&&resolvedPathname.endsWith(`/`))return resolvedPathname.slice(0,-1);return resolvedPathname}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}function resolveRouteParamNamesInOrder(route=null){const sourceRoute=route&&typeof route===`object`?route:{};const matched=Array.isArray(sourceRoute.matched)?sourceRoute.matched:[];const names=[];const seen=new Set;for(const entry of matched){const entryPath=String(entry?.path||``).trim();if(!entryPath)continue;for(const name of extractRouteParamNames(entryPath)){if(seen.has(name))continue;seen.add(name);names.push(name)}}if(names.length>0)return names;return Object.keys(asPlainObject(sourceRoute.params)).map(entry=>String(entry||``).trim()).filter(Boolean)}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,placementSource=`http-web.scope-runtime`}={}){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=normalizeSurfaceId(surfaceId);if(explicitSurfaceId)return explicitSurfaceId;return normalizeSurfaceId(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``;return`Route parameters ${missingScopedRouteParamNames.value.join(`, `)} are required for surface "${resolvedSurfaceId.value||`<unknown>`}".`});const accessRuntime=useAccess({scopeParamValue,enabled:computed(()=>accessRequired&&hasRequiredRouteScope.value),access:normalizedAccessMode,hasPermissionRequirements,placementSource:String(placementSource||`http-web.scope-runtime`)});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 Object.freeze({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`,placementSource=`http-web.operation`,apiSuffix=``,model,readEnabled=true,queryKeyFactory=null,permissionSets={},realtime=null}={}){const normalizedPermissionSets=normalizePermissionSets(permissionSets);const scopeRuntime=useScopeRuntime({ownershipFilter,surfaceId,accessMode:access,hasPermissionRequirements:hasAnyPermissions(normalizedPermissionSets),placementSource});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 bootstrapError=String(accessRuntime.bootstrapError.value||``).trim();if(bootstrapError)return bootstrapError;if(baseError===void 0||baseError===null||baseError===``)return``;return String(unref(baseError)||``).trim()})}function isLoading(baseLoading=false){return computed(()=>Boolean(unref(baseLoading))||accessRuntime.isBootstrapping.value)}return Object.freeze({scopeRuntime,routeContext,normalizedOwnershipFilter,scopeParamValue,hasRequiredRouteScope,access:accessRuntime,apiPath,queryEnabled,queryKey,queryCanRun,realtime:realtimeBinding,permissionGate,loadError,isLoading})}function normalizeKeys(keys){return Array.isArray(keys)?keys.map(entry=>String(entry||``).trim()).filter(Boolean):[]}function useFieldErrorBag(keys=[]){const normalizedKeys=normalizeKeys(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 Object.freeze({errors,clear,apply,set})}function normalizeMessage(value){return String(value||``).trim()}function setupOperationErrorReporting({enabled=true,source=`http-web.operation`,loadError=null,notFoundError=null,loadActionFactory=null,notFoundActionFactory=null,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=null}={}){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=typeof actionFactory===`function`?actionFactory({message:nextMessage,kind}):null;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=null,feedback=null,fieldBag=null,onClear=null}={}){if(!enabled)return;watch(()=>route?.fullPath,()=>{feedback?.clear?.();fieldBag?.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=null}={}){const activeClient=client||getHttpWebClient();if(!activeClient||typeof activeClient.request!==`function`)throw new TypeError(`resolveCrudHttpClient requires a client with request().`);if(normalizeCrudApiAccess(resource?.apiAccess)!==`public`)return activeClient;if(publicCrudClients.has(activeClient))return activeClient;const publicClient=Object.freeze({request(url,options={}){const requestOptions=options&&typeof options===`object`&&!Array.isArray(options)?options:{};return activeClient.request(url,{...requestOptions,csrf:false})}});publicCrudClients.add(publicClient);return publicClient}function useCommand({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,runPermissions=[],writeMethod=`POST`,client=null,resource:commandResource=null,transport=null,placementSource=`http-web.command`,fallbackRunError=`Unable to complete action.`,fieldErrorKeys=[],clearOnRouteChange=true,model,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={},realtime=null}={}){const operationScope=useOperationScope({ownershipFilter,surfaceId,access,placementSource,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:`Fix invalid values and try again.`,success:`Completed.`,error:String(fallbackRunError||`Unable to complete action.`),...messages&&typeof messages===`object`?messages:{}}});setupRouteChangeCleanup({enabled:clearOnRouteChange,route:routeContext.route,feedback,fieldBag});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{useOperationScope as a,resolveRouteParamsSource as c,toRouteParamValue as d,useAccess as f,useFieldErrorBag as i,resolveRouteTemplateLocation as l,setupOperationErrorReporting as n,normalizeRouteParamName as o,validateOperationInput as p,setupRouteChangeCleanup as r,resolveRouteParamNamesInOrder as s,useCommand as t,resolveScopedRoutePathname as u};
@@ -1 +0,0 @@
1
- import{H as hasInjectionContext,Ht as watch,J as inject,On as unref,Tn as toRefs,_n as readonly,bn as shallowReadonly,g as computed,gn as reactive,pn as onScopeDispose,un as isRef,yn as shallowReactive}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{j as useRealtimeEvent,u as getHttpWebClient}from"./vibe64ProjectScope.local-DqT6e5un.js";import{d as normalizeText$1}from"./normalize-CO2KHj_d.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}function hasNextPage(options,data){if(!data)return false;return getNextPageParam(options,data)!=null}function hasPreviousPage(options,data){if(!data||!options.getPreviousPageParam)return false;return getPreviousPageParam(options,data)!=null}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}}var AUTH_POLICY_PUBLIC=`public`;var AUTH_POLICY_AUTHENTICATED=`authenticated`;var ROUTE_VISIBILITY_PUBLIC=AUTH_POLICY_PUBLIC;var ROUTE_VISIBILITY_USER=`user`;function resolveEnabledRef(value){if(value===void 0)return true;if(typeof value===`function`)return Boolean(value());return Boolean(unref(value))}function resolveTextRef(value){return String(unref(value)||``).trim()}var ROUTE_VISIBILITY_LEVELS=Object.freeze([ROUTE_VISIBILITY_PUBLIC,ROUTE_VISIBILITY_USER]);var ROUTE_VISIBILITY_LEVEL_SET=new Set(ROUTE_VISIBILITY_LEVELS);var ROUTE_VISIBILITY_WORKSPACE=`workspace`;var ROUTE_VISIBILITY_WORKSPACE_USER=`workspace_user`;var ROUTE_VISIBILITY_TOKENS=Object.freeze([ROUTE_VISIBILITY_PUBLIC,ROUTE_VISIBILITY_USER,ROUTE_VISIBILITY_WORKSPACE,ROUTE_VISIBILITY_WORKSPACE_USER]);var ROUTE_VISIBILITY_TOKEN_SET=new Set(ROUTE_VISIBILITY_TOKENS);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 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$1(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(typeof queryKeyFactory!==`function`)throw new TypeError(`queryKeyFactory is required.`);if(isScopedOwnershipFilter(ownershipFilter))return queryKeyFactory(surfaceId,scopeParamValue,ownershipFilter);return queryKeyFactory(surfaceId,ownershipFilter)}function resolveResourceMessages(resource,defaults={}){const defaultMessages=asPlainObject(defaults);const resourceMessages=asPlainObject(asPlainObject(resource).messages);return{...defaultMessages,...resourceMessages}}function normalizeErrorStatus(error){if(error==null||typeof error!==`object`)return null;const hasStatus=Object.prototype.hasOwnProperty.call(error,`status`);const hasStatusCode=Object.prototype.hasOwnProperty.call(error,`statusCode`);if(!hasStatus&&!hasStatusCode)return null;const status=Number(hasStatus?error.status:error.statusCode);return Number.isInteger(status)?status:null}function isGenericTransportMessage(error){const normalizedMessage=String(error?.message||``).trim();if(!normalizedMessage)return false;const status=normalizeErrorStatus(error);if(status===0)return true;return status!=null&&status>=400&&normalizedMessage===`Request failed with status ${status}.`}function toQueryErrorMessage(error,fallbackMessage=``,defaultMessage=`Request failed.`){if(!error)return``;const normalizedFallback=String(fallbackMessage||``).trim();const normalizedMessage=String(error?.message||``).trim();if(normalizedMessage&&!isGenericTransportMessage(error))return normalizedMessage;if(normalizedFallback)return normalizedFallback;if(normalizedMessage)return normalizedMessage;return String(defaultMessage||`Request failed.`).trim()}function toUiErrorMessage(error,fallbackMessage=``,defaultMessage=`Request failed.`){const normalizedFallback=String(fallbackMessage||``).trim();const normalizedMessage=String(error?.message||``).trim();if(normalizedMessage&&!isGenericTransportMessage(error))return normalizedMessage;if(normalizedFallback)return normalizedFallback;if(normalizedMessage)return normalizedMessage;return String(defaultMessage||`Request failed.`).trim()}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=queryOptions&&typeof queryOptions===`object`&&!Array.isArray(queryOptions)?queryOptions:{};const sourceMeta=sourceOptions.meta&&typeof sourceOptions.meta===`object`&&!Array.isArray(sourceOptions.meta)?sourceOptions.meta:{};const sourceJskitMeta=sourceMeta.jskit&&typeof sourceMeta.jskit===`object`&&!Array.isArray(sourceMeta.jskit)?sourceMeta.jskit:{};const nextJskitMeta=meta.jskit&&typeof meta.jskit===`object`&&!Array.isArray(meta.jskit)?meta.jskit:{};return{...sourceOptions,meta:{...sourceMeta,...meta,jskit:{...sourceJskitMeta,...nextJskitMeta}}}}function normalizeText(value=``){return String(value||``).trim()}function firstNormalizedText(...values){for(const value of values){const normalized=normalizeText(value);if(normalized)return normalized}return``}function firstNonNegativeFiniteNumber(...values){for(const value of values){const numberValue=Number(value);if(Number.isFinite(numberValue))return Math.max(0,numberValue)}return null}function normalizePlainObject(value=null){return value&&typeof value===`object`&&!Array.isArray(value)?value:{}}function normalizeRequestRecoveryInput(requestRecovery=null){if(typeof requestRecovery===`string`)return{label:requestRecovery};return normalizePlainObject(requestRecovery)}function normalizeRequestRecoveryMethod(value=``){return normalizeText(value).toUpperCase()}function isRequestRecoveryMetaDisabled(sourceJskitMeta={}){return sourceJskitMeta.requestRecovery===false}function hasUsableMetaValue(source={},key=``){return Object.hasOwn(source,key)&&source[key]!==void 0&&source[key]!==null&&source[key]!==``}function buildRequestRecoveryMeta(requestRecovery=null,defaults={}){if(requestRecovery===false)return{jskit:{requestRecovery:false}};const fallback=normalizePlainObject(defaults);const source=normalizeRequestRecoveryInput(requestRecovery);if(source.requestRecovery===false||source.enabled===false)return{jskit:{requestRecovery:false}};const label=firstNormalizedText(source.requestRecoveryLabel,source.label,fallback.requestRecoveryLabel,fallback.label);const recoverySource=firstNormalizedText(source.requestRecoverySource,source.source,fallback.requestRecoverySource,fallback.source);const dedupeKey=firstNormalizedText(source.requestRecoveryDedupeKey,source.dedupeKey,fallback.requestRecoveryDedupeKey,fallback.dedupeKey);const method=normalizeRequestRecoveryMethod(firstNormalizedText(source.requestRecoveryMethod,source.method,fallback.requestRecoveryMethod,fallback.method));const dedupeWindowMs=firstNonNegativeFiniteNumber(source.requestRecoveryDedupeWindowMs,source.dedupeWindowMs,fallback.requestRecoveryDedupeWindowMs,fallback.dedupeWindowMs);const jskit={};if(label)jskit.requestRecoveryLabel=label;if(recoverySource)jskit.requestRecoverySource=recoverySource;if(dedupeKey)jskit.requestRecoveryDedupeKey=dedupeKey;if(method)jskit.requestRecoveryMethod=method;if(dedupeWindowMs!==null)jskit.requestRecoveryDedupeWindowMs=dedupeWindowMs;return Object.keys(jskit).length>0?{jskit}:{}}function resolveRequestRecoveryDefaults(queryOptions=null,defaults={}){const sourceJskitMeta=normalizePlainObject(normalizePlainObject(normalizePlainObject(queryOptions).meta).jskit);const fallback=normalizePlainObject(defaults);if(isRequestRecoveryMetaDisabled(sourceJskitMeta))return{};const hasExplicitLabel=hasUsableMetaValue(sourceJskitMeta,`requestRecoveryLabel`);const hasExplicitSource=hasUsableMetaValue(sourceJskitMeta,`requestRecoverySource`);const hasExplicitDedupeKey=hasUsableMetaValue(sourceJskitMeta,`requestRecoveryDedupeKey`);const hasExplicitDedupeWindowMs=hasUsableMetaValue(sourceJskitMeta,`requestRecoveryDedupeWindowMs`);const hasExplicitMethod=hasUsableMetaValue(sourceJskitMeta,`requestRecoveryMethod`);return{...fallback,requestRecoveryLabel:hasExplicitLabel?``:fallback.requestRecoveryLabel,label:hasExplicitLabel?``:fallback.label,requestRecoverySource:hasExplicitSource?``:fallback.requestRecoverySource,source:hasExplicitSource?``:fallback.source,requestRecoveryDedupeKey:hasExplicitDedupeKey?``:fallback.requestRecoveryDedupeKey,dedupeKey:hasExplicitDedupeKey?``:fallback.dedupeKey,requestRecoveryDedupeWindowMs:hasExplicitDedupeWindowMs?``:fallback.requestRecoveryDedupeWindowMs,dedupeWindowMs:hasExplicitDedupeWindowMs?``:fallback.dedupeWindowMs,requestRecoveryMethod:hasExplicitMethod?``:fallback.requestRecoveryMethod,method:hasExplicitMethod?``:fallback.method}}function mergeRequestRecoveryQueryMeta(queryOptions=null,requestRecovery=null,defaults={}){const sourceOptions=normalizePlainObject(queryOptions);const meta=buildRequestRecoveryMeta(requestRecovery,requestRecovery==null?resolveRequestRecoveryDefaults(sourceOptions,defaults):normalizePlainObject(defaults));if(Object.keys(meta).length<1)return sourceOptions;return mergeQueryMeta(sourceOptions,meta)}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 hasRealtimeEventConfig(value={}){const source=normalizeRealtimeOptions(value);return Object.hasOwn(source,`event`)||Object.hasOwn(source,`events`)}function resolveOperationRealtimeOptions({realtime=void 0,fallbackRealtime=null}={}){if(realtime===false)return null;const fallback=normalizeRealtimeOptions(fallbackRealtime);const explicit=realtime==null?{}:normalizeRealtimeOptions(realtime);if(hasRealtimeEventConfig(explicit)||!hasRealtimeEventConfig(fallback))return Object.keys(explicit).length>0?explicit:null;return Object.freeze({...fallback,...explicit})}function resolveEnabled(value){if(typeof value===`undefined`)return true;return Boolean(unref(value))}function toQueryKeyList(value){const resolved=typeof value===`function`?value():unref(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])]}function useRealtimeQueryInvalidation({event=``,enabled=true,matches=null,queryKey=null,onEvent=null}={}){const queryClient=useQueryClient();const normalizedEvent=computed(()=>normalizeText$1(unref(event)));const active=computed(()=>resolveEnabled(enabled)&&Boolean(normalizedEvent.value));const listener=useRealtimeEvent({event:normalizedEvent,enabled:active,matches,onEvent:async context=>{if(typeof onEvent===`function`)await onEvent(context);const keys=toQueryKeyList(queryKey);for(const key of keys)await queryClient.invalidateQueries({queryKey:key})}});return Object.freeze({active:listener.active})}function useOperationRealtime({realtime=null,queryKey=null,enabled=true}={}){const source=normalizeRealtimeOptions(realtime);const eventList=[];if(Object.hasOwn(source,`event`)){const normalizedEvent=normalizeText$1(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$1(entry);if(!normalizedEvent||eventList.includes(normalizedEvent))continue;eventList.push(normalizedEvent)}}if(eventList.length<1)return null;const matches=typeof source.matches===`function`?source.matches:null;const onEvent=typeof source.onEvent===`function`?source.onEvent:null;const resolvedQueryKey=Object.hasOwn(source,`queryKey`)?source.queryKey:queryKey;const active=computed(()=>{const sourceEnabled=Object.hasOwn(source,`enabled`)?source.enabled:true;return resolveEnabled(enabled)&&resolveEnabled(sourceEnabled)});const bindings=eventList.map(event=>useRealtimeQueryInvalidation({event,enabled:active,matches,queryKey:resolvedQueryKey,onEvent}));return Object.freeze({active:computed(()=>bindings.some(binding=>Boolean(binding?.active?.value)))})}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=null,readMethod=`GET`,writeMethod=`PATCH`,readQuery=null,transport=null,refreshOnPull=false,realtime=null,queryOptions=null,mutationOptions=null,requestRecovery=null,requestRecoveryLabel=`Request`,fallbackLoadError=`Unable to load resource.`,fallbackSaveError=`Unable to save resource.`}={}){const activeClient=client||getHttpWebClient();if(!activeClient||typeof activeClient.request!==`function`)throw new TypeError(`useEndpointResource requires a client with request().`);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 activeClient.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 activeClient.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,`Request failed.`));const saveError=computed(()=>toQueryErrorMessage(mutation.error.value,fallbackSaveError,`Request failed.`));async function reload(){return query.refetch()}async function save(payload,options={}){return mutation.mutateAsync({...asPlainObject(options),payload})}return Object.freeze({query,mutation,data,isInitialLoading,isFetching,isRefetching,isLoading,isSaving,loadError,saveError,realtime:realtimeBinding,reload,save})}export{QueryObserver as A,hashKey as B,AUTH_POLICY_AUTHENTICATED as C,useQuery as D,useMutation as E,notifyManager as F,partialMatchKey as G,matchMutation as H,focusManager as I,useQueryClient as J,resolveQueryValue as K,Subscribable as L,hasNextPage as M,hasPreviousPage as N,useBaseQuery as O,onlineManager as P,environmentManager as R,resolveTextRef as S,ROUTE_VISIBILITY_PUBLIC as T,matchQuery as U,hashQueryKeyByOptions as V,noop as W,getClientKey as X,cloneDeepUnref as Y,resolvePermissionAccess as _,mergeQueryMeta as a,ROUTE_VISIBILITY_WORKSPACE as b,toUiErrorMessage as c,normalizeAccessMode as d,normalizeOwnershipFilter as f,resolveEnabled$1 as g,resolveApiSuffix as h,useRealtimeQueryInvalidation as i,Query as j,Mutation as k,asPlainObject as l,resolveAccessModeEnabled as m,resolveOperationRealtimeOptions as n,mergeRequestRecoveryQueryMeta as o,normalizePermissions as p,skipToken as q,useOperationRealtime as r,toQueryErrorMessage as s,useEndpointResource as t,ensureAccessModeCompatibility as u,resolveQueryKey as v,AUTH_POLICY_PUBLIC as w,resolveEnabledRef as x,resolveResourceMessages as y,functionalUpdate as z};
@@ -1 +0,0 @@
1
- import{Ht as watch,g as computed,pn as onScopeDispose,vn as ref,xn as shallowRef}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{J as useQueryClient,T as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource}from"./useEndpointResource-MWVNfmMa.js";import{M as useRealtimeSocket,j as useRealtimeEvent,u as getHttpWebClient}from"./vibe64ProjectScope.local-DqT6e5un.js";import{t as usePaths}from"./usePaths-Db88-HOm.js";import{o as normalizeVibe64ConversationAttachments}from"./shared-YZb7ocaK.js";import{t as useVibe64ProjectSlug}from"./useVibe64ProjectScope-DOEVkBqX.js";import{Ct as applyConversationLogPatch$1,Dt as mergeConversationLogPages,E as VIBE64_SESSION_CHANGED_EVENT,Et as conversationLogReadQuery,I as vibe64ConversationLogPath,L as vibe64ConversationLogQueryKey,Ot as normalizeConversationLogPage,Q as vibe64SessionPath,T as VIBE64_SESSIONS_API_SUFFIX,Tt as normalizeConversationTurn$1,Z as vibe64SessionEventMatchesScope,_ as readRefOrGetterValue,jt as mergeConversationStream,kt as normalizeConversationLogPagination,wt as normalizeConversationMessage$1}from"./index-BUq-MczL.js";import{o as vibe64SessionDebugError,s as vibe64SessionDebugLog}from"./vibe64SessionPanelModel-BMf64fv7.js";import{t as connectorDefinitions}from"./definitions-DaOPIkyB.js";var CONVERSATION_LOG_REALTIME_REASONS=new Set([`project-message-changed`,`conversation-rewound`,`session-assistant-selection-updated`,`assistant-stream`,`integration-setup-skipped`,`integration-setup-completed`,`assistant-response-bundle`,`codex-app-server-agent-result`,`codex-app-server-agent-result-invalid`,`codex-app-server-agent-result-missing`,`codex-app-server-agent-result-provider-failed`,`codex-app-server-commentary`,`codex-app-server-final-assistant-message`,`codex-app-server-live-progress`,`codex-app-server-reasoning-summary`,`codex-app-server-terminal-assistant-message`,`codex-app-server-terminal-thinking-message`,`codex-app-server-terminal-user-message`,`codex-turn-outcome`,`codex-app-server-message-delivered`,`opencode-credential-failure`,`opencode-provider-failure`,`opencode-server-assistant-message`,`opencode-server-message-delivered`,`opencode-server-reasoning`,`opencode-server-tool`,`opencode-server-turn-idle`,`claude-stream-turn-idle`,`claude-stream-message`,`claude-stream-message-delivered`,`session-agent-message-cancelled`,`session-agent-message-accepted`,`session-agent-message-delivered`,`session-agent-message-failed`]);function normalizeConversationMessage(message={}){return normalizeConversationMessage$1(message,{normalizeAttachments:normalizeVibe64ConversationAttachments})}function normalizeConversationTurn(turn={},index=0){const normalized=normalizeConversationTurn$1(turn,index,{normalizeAttachments:normalizeVibe64ConversationAttachments});return normalized&&{...normalized,...isRecord(turn.integrationSetup)?{integrationSetup:turn.integrationSetup}:{}}}function isRecord(value){return Boolean(value&&typeof value===`object`&&!Array.isArray(value))}function normalizeConversationLog(payload={},options={}){return conversationTurnsWithPending((Array.isArray(payload?.conversationLog)?payload.conversationLog:[]).map((turn,index)=>normalizeConversationTurn(turn,index)).filter(Boolean),options.pending)}function conversationTurnsWithPending(turns,pending){const pendingTurnIndex=pending===true?turns.length-1:-1;return turns.map((turn,index)=>{if(index===pendingTurnIndex&&turn.user&&!turn.assistant)return{...turn,pending:true};return turn})}function conversationLogRealtimePatch(payload={}){const reason=String(payload?.reason||``).trim();const patch=isRecord(payload?.conversationLogPatch)?payload.conversationLogPatch:null;if(![`assistant-response-bundle`,`codex-app-server-commentary`,`codex-app-server-final-assistant-message`,`codex-app-server-reasoning-summary`,`codex-app-server-live-progress`,`codex-app-server-terminal-assistant-message`,`codex-app-server-terminal-thinking-message`,`codex-app-server-terminal-user-message`,`codex-app-server-message-delivered`,`opencode-credential-failure`,`opencode-provider-failure`,`opencode-server-assistant-message`,`opencode-server-message-delivered`,`opencode-server-reasoning`,`opencode-server-tool`].includes(reason)||patch?.type!==`upsert-turn`||!isRecord(patch.turn))return null;const assistant=normalizeConversationMessage(patch.turn.assistant);const commentary=Array.isArray(patch.turn.commentary)?patch.turn.commentary.map(normalizeConversationMessage).filter(Boolean):[];const thinking=Array.isArray(patch.turn.thinking)?patch.turn.thinking.map(normalizeConversationMessage).filter(Boolean):[];if([`codex-app-server-reasoning-summary`,`codex-app-server-live-progress`].includes(reason)&&(!thinking.length||assistant))return null;if(reason===`codex-app-server-commentary`&&(!commentary.length||assistant))return null;if([`assistant-response-bundle`,`codex-app-server-final-assistant-message`].includes(reason)&&!assistant)return null;return{turn:patch.turn,type:`upsert-turn`}}function applyConversationLogPatch(payload={},patch=null,options={}){return applyConversationLogPatch$1(payload,patch,{...options,normalizeAttachments:normalizeVibe64ConversationAttachments})}function sessionIsAwaitingCodex(session={}){return(session&&typeof session===`object`&&!Array.isArray(session)?session:{}).agentSession?.turn?.active===true}function conversationLogRealtimeShouldRefresh({payload={}}={},sessionId=``){const normalizedSessionId=String(sessionId||``).trim();const changedSessionId=String(payload.sessionId||payload.entityId||``).trim();if(!normalizedSessionId||changedSessionId!==normalizedSessionId)return false;const reason=String(payload.reason||``).trim();return Boolean(payload.conversationStream)||!reason||CONVERSATION_LOG_REALTIME_REASONS.has(reason)}function conversationLogRecoveryStateKey(session={}){const source=session&&typeof session===`object`&&!Array.isArray(session)?session:{};return[source.sessionId,source.status,source.revision,source.updatedAt,source.agentSession?.turn?.active?`active`:`idle`,source.agentSession?.turn?.id].map(value=>String(value||``).trim()).join(`|`)}function conversationLogCompletedTurnKey(session={}){const source=isRecord(session)?session:{};const turn=isRecord(source.agentSession?.turn)?source.agentSession.turn:{};const sessionId=String(source.sessionId||``).trim();const turnId=String(turn.id||``).trim();const revision=Number(source.revision);if(!sessionId||!turnId||turn.active!==false||!Number.isSafeInteger(revision)||revision<0)return``;return`${sessionId}|${revision}|${turnId}`}function useConversationIntegrationActions({turns,enabled,sessionId,projectSlug,sessionsApiPath,reloadConversationLog,httpClient}){const integrationActionPending=shallowRef(null);const integrationActionError=ref(null);const integrationConnections=shallowRef({});function connectIntegrationRequest(request={}){return runIntegrationRequestAction(request,`connect`)}function checkIntegrationRequest(request={}){return runIntegrationRequestAction(request,`status`)}function cancelIntegrationRequest(request={}){return runIntegrationRequestAction(request,`cancel`)}function skipIntegrationRequest(request={}){return runIntegrationRequestAction(request,`skip`)}function resumeIntegrationRequest(request={}){return runIntegrationRequestAction(request,`resume`)}async function runIntegrationRequestAction(request,action){const turn=turns.value.find(entry=>entry.turnId===request.turnId);if(!enabled.value||request.sessionId!==sessionId.value||integrationActionPending.value||turn?.integrationSetup?.outcome!==(action===`resume`?`completed`:`pending`)||turn.integrationSetup.requestId!==request.requestId)return false;const selection={sessionId:sessionId.value,turnId:request.turnId,requestId:request.requestId};integrationActionPending.value=selection;integrationActionError.value=null;try{if([`connect`,`cancel`,`status`].includes(action)){const path=vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integrations`);const config=await httpClient.request(path);if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;const integrationId=turn.integrationSetup.integrationId;const integration=config?.configuration?.integrations?.[integrationId];if(!integration)throw new Error(`Choose Configure to set up this integration first.`);if(connectorDefinitions.some(provider=>provider.id===integration.provider&&(provider.configurationOnly||provider.configurationOnlyForSettings?.(integration?.settings||{})))){integrationConnections.value={...integrationConnections.value,[selection.requestId]:{status:`configuration-only`}};return true}if(integration.accountMode===`per-user`)throw new Error(`Each app user connects their account inside the application. Choose Configure for setup instructions.`);const endpoint=`${path}/${encodeURIComponent(integrationId)}/setup`;const previous=integrationConnections.value[selection.requestId];if(action===`cancel`&&!previous?.attemptId)return false;let connection=await httpClient.request(endpoint,{method:`POST`,body:{operation:action,...action===`cancel`?{attemptId:previous.attemptId}:{setupRequest:{turnId:selection.turnId,requestId:selection.requestId,configurationHash:config.baseHash}}}});if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;if(action===`cancel`){connection=await httpClient.request(endpoint,{method:`POST`,body:{operation:`status`}});if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false}integrationConnections.value={...integrationConnections.value,[selection.requestId]:connection};if(connection.integrationSetup?.outcome===`completed`&&connection.integrationSetup.continuation?.status!==`accepted`){const resumed=await httpClient.request(vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integration-setup/resume`),{method:`POST`,body:{turnId:selection.turnId,requestId:selection.requestId}});if(resumed?.ok!==true)throw new Error(resumed?.error||`Assistant continuation is not yet confirmed.`)}if(integrationActionPending.value===selection&&sessionId.value===selection.sessionId)await reloadConversationLog();return true}const result=await httpClient.request(vibe64SessionPath(sessionsApiPath.value,selection.sessionId,`/integration-setup/${action}`),{method:`POST`,body:{turnId:selection.turnId,requestId:selection.requestId}});if(result?.ok!==true)throw new Error(result?.error||`Could not update integration setup.`);if(integrationActionPending.value===selection&&sessionId.value===selection.sessionId)await reloadConversationLog();return true}catch(error){if(sessionId.value===selection.sessionId&&integrationActionPending.value===selection){integrationActionError.value={turnId:selection.turnId,message:String(error?.message||`Could not update integration setup.`)};if(action===`resume`||action===`connect`||action===`status`)await reloadConversationLog()}return false}finally{if(sessionId.value===selection.sessionId&&integrationActionPending.value===selection)integrationActionPending.value=null}}onScopeDispose(()=>{integrationActionPending.value=null});watch([sessionId,projectSlug],()=>{integrationActionPending.value=null;integrationActionError.value=null;integrationConnections.value={}});return{integrationConnections,connectIntegrationRequest,checkIntegrationRequest,cancelIntegrationRequest,integrationActionPending,integrationActionError,skipIntegrationRequest,resumeIntegrationRequest}}function useVibe64ConversationLog({active=true,projectSlug:projectSlugInput,sessionsApiPath:sessionsApiPathInput,learningAttemptId,session,conversation=null}={}){const paths=usePaths();const httpClient=getHttpWebClient();const projectSlug=projectSlugInput===void 0?useVibe64ProjectSlug():computed(()=>readRefOrGetterValue(projectSlugInput));const currentSession=computed(()=>readRefOrGetterValue(session)||null);const sessionId=computed(()=>String(currentSession.value?.sessionId||``).trim());const enabled=computed(()=>Boolean(readRefOrGetterValue(active)!==false&&sessionId.value));const sessionsApiPath=computed(()=>readRefOrGetterValue(sessionsApiPathInput)||paths.api(`/vibe64/sessions`,{surface:`app`}));if(conversation){const turns=computed(()=>conversationTurnsWithPending(conversation.turns.value,sessionIsAwaitingCodex(currentSession.value)));const integrationActions=useConversationIntegrationActions({turns,enabled,sessionId,projectSlug,sessionsApiPath,reloadConversationLog:conversation.reload,httpClient});let realtimeCompletionKey=``;const realtime=useRealtimeEvent({enabled,event:VIBE64_SESSION_CHANGED_EVENT,matches:context=>([`session-assistant-selection-updated`,`integration-setup-skipped`,`integration-setup-completed`].includes(context?.payload?.reason)||conversationLogCompletedTurnKey(context?.payload))&&conversationLogRealtimeShouldRefresh(context,sessionId.value)&&vibe64SessionEventMatchesScope(context?.payload,{projectSlug:projectSlug.value,learningAttemptId}),onEvent:({payload={}}={})=>{realtimeCompletionKey=conversationLogCompletedTurnKey(payload)||realtimeCompletionKey;return payload.reason===`session-assistant-selection-updated`?conversation.reload({resubscribe:true}):conversation.reload()}});watch(()=>conversationLogCompletedTurnKey(currentSession.value),key=>{if(!enabled.value||!key)return;if(key===realtimeCompletionKey){realtimeCompletionKey=``;return}conversation.reload()?.catch(()=>{})},{flush:`post`});return{...integrationActions,turns,error:conversation.error,errorReloadable:computed(()=>conversation.accessDenied?.value===false),hasMoreBefore:conversation.hasMoreBefore,loadMore:conversation.loadMore,loadMoreError:conversation.loadMoreError,loading:conversation.loading,initializing:computed(()=>!conversation.snapshot.value&&conversation.loading.value),loadingMore:conversation.loadingMore,reload:conversation.reload,realtime,visible:computed(()=>Boolean(conversation.loading.value||conversation.error.value||turns.value.length))}}const queryClient=useQueryClient();const olderPages=ref([]);const loadingMore=ref(false);const loadMoreError=ref(``);const queryKey=computed(()=>[...vibe64ConversationLogQueryKey(`app`,ROUTE_VISIBILITY_PUBLIC,sessionId.value,projectSlug.value)]);const conversationLogPath=computed(()=>sessionId.value?vibe64ConversationLogPath(sessionsApiPath.value,sessionId.value):``);const pendingReads=new Set;const resource=useEndpointResource({enabled,fallbackLoadError:`Conversation history could not be loaded.`,path:conversationLogPath,queryKey,queryOptions:{async queryFn({signal}){const read={sessionId:sessionId.value,projectSlug:projectSlug.value,patches:[]};pendingReads.add(read);try{let payload=await httpClient.request(conversationLogPath.value,{method:`GET`,query:conversationLogReadQuery(),signal});for(const patch of read.patches)payload=applyConversationLogPatch(payload,patch,{limit:10});return payload}finally{pendingReads.delete(read)}},placeholderData:previousData=>previousData,refetchOnMount:false,refetchOnWindowFocus:false},readMethod:`GET`,refreshOnPull:true,requestRecoveryLabel:`Conversation history`,realtime:null});let reloadInFlight=null;let reloadQueued=false;let recoveredErrorKey=``;let realtimeCompletionKey=``;const conversationStream=shallowRef(null);function receiveConversationStream(snapshot){if(snapshot&&(!conversationStream.value||snapshot.revision>=conversationStream.value.revision))conversationStream.value=snapshot}watch(()=>resource.data.value,data=>receiveConversationStream(data?.conversationStream),{immediate:true});async function reloadConversationLog(){if(reloadInFlight){reloadQueued=true;vibe64SessionDebugLog(`client.conversationLog.reload.join`,{sessionId:sessionId.value});return reloadInFlight}olderPages.value=[];loadMoreError.value=``;vibe64SessionDebugLog(`client.conversationLog.reload.start`,{sessionId:sessionId.value});reloadInFlight=resource.reload();try{const result=await reloadInFlight;vibe64SessionDebugLog(`client.conversationLog.reload.done`,{sessionId:sessionId.value});return result}finally{reloadInFlight=null;if(reloadQueued){reloadQueued=false;reloadConversationLog()}}}const realtimeSocket=useRealtimeSocket({required:false});const reconcileConversationAfterRealtimeConnect=()=>{if(enabled.value){conversationStream.value=null;reloadConversationLog().catch(()=>{})}};realtimeSocket.on(`connect`,reconcileConversationAfterRealtimeConnect);onScopeDispose(()=>{realtimeSocket.off(`connect`,reconcileConversationAfterRealtimeConnect)});function applyRealtimeConversationLogPatch(payload={}){const patch=conversationLogRealtimePatch(payload);if(!patch)return false;const key=queryKey.value;const currentPayload=queryClient.getQueryData(key);const nextPayload=applyConversationLogPatch(currentPayload,patch,{limit:10});if(!nextPayload){vibe64SessionDebugLog(`client.conversationLog.patch.miss`,{hasCurrentPayload:Boolean(currentPayload),patchType:String(patch?.type||``),sessionId:sessionId.value});return false}for(const read of pendingReads)if(read.sessionId===sessionId.value&&read.projectSlug===projectSlug.value)read.patches.push(patch);queryClient.setQueryData(key,nextPayload);vibe64SessionDebugLog(`client.conversationLog.patch.done`,{patchType:String(patch.type||``),sessionId:sessionId.value,turnId:String(patch.turn?.turnId||``)});return true}const realtime=useRealtimeEvent({enabled,event:VIBE64_SESSION_CHANGED_EVENT,matches:context=>conversationLogRealtimeShouldRefresh(context,sessionId.value),onEvent:({payload={}}={})=>{receiveConversationStream(payload.conversationStream);realtimeCompletionKey=conversationLogCompletedTurnKey(payload)||realtimeCompletionKey;vibe64SessionDebugLog(`client.conversationLog.realtime`,{hasPatch:Boolean(conversationLogRealtimePatch(payload)),reason:String(payload.reason||``),sessionId:sessionId.value});if(applyRealtimeConversationLogPatch(payload))return null;if(payload.reason===`assistant-stream`)return null;return reloadConversationLog()}});const recoveryStateKey=computed(()=>conversationLogRecoveryStateKey(currentSession.value));const completedTurnKey=computed(()=>conversationLogCompletedTurnKey(currentSession.value));watch(completedTurnKey,key=>{if(!enabled.value||!key)return;if(key===realtimeCompletionKey){realtimeCompletionKey=``;return}vibe64SessionDebugLog(`client.conversationLog.completion.reconcile`,{completedTurnKey:key,sessionId:sessionId.value});reloadConversationLog().catch(()=>{})},{flush:`post`});const recoveryErrorKey=computed(()=>[enabled.value?`enabled`:`disabled`,sessionId.value,recoveryStateKey.value,resource.loadError.value].join(`|`));watch(recoveryErrorKey,()=>{const loadError=String(resource.loadError.value||``).trim();if(!enabled.value||!loadError){recoveredErrorKey=``;return}const key=recoveryErrorKey.value;if(recoveredErrorKey===key)return;recoveredErrorKey=key;vibe64SessionDebugLog(`client.conversationLog.recover.start`,{error:loadError,recoveryStateKey:recoveryStateKey.value,sessionId:sessionId.value});reloadConversationLog().then(()=>{vibe64SessionDebugLog(`client.conversationLog.recover.done`,{recoveryStateKey:recoveryStateKey.value,sessionId:sessionId.value})}).catch(error=>{vibe64SessionDebugLog(`client.conversationLog.recover.error`,{error:vibe64SessionDebugError(error),recoveryStateKey:recoveryStateKey.value,sessionId:sessionId.value})})},{flush:`post`});const latestPage=computed(()=>normalizeConversationLogPage(resource.data.value||{}));const loadedPages=computed(()=>[...olderPages.value,latestPage.value]);const oldestLoadedPage=computed(()=>olderPages.value[0]||latestPage.value);const hasMoreBefore=computed(()=>Boolean(normalizeConversationLogPagination(oldestLoadedPage.value?.pagination).hasMoreBefore));const turns=computed(()=>{const savedTurns=normalizeConversationLog(mergeConversationLogPages(loadedPages.value),{pending:sessionIsAwaitingCodex(currentSession.value)});return mergeConversationStream(savedTurns,conversationStream.value)});const visible=computed(()=>Boolean(resource.isLoading.value||resource.loadError.value||turns.value.length));async function loadMoreConversationLog({complete}={}){const finish=result=>{if(typeof complete===`function`)complete(result)};const pagination=normalizeConversationLogPagination(oldestLoadedPage.value?.pagination);const beforeTurnId=pagination.nextBeforeTurnId||pagination.oldestTurnId||String(turns.value[0]?.turnId||``).trim();if(!enabled.value||!conversationLogPath.value||!hasMoreBefore.value||loadingMore.value||!beforeTurnId){finish({changed:false,loaded:false});return false}loadingMore.value=true;loadMoreError.value=``;vibe64SessionDebugLog(`client.conversationLog.loadMore.start`,{beforeTurnId,sessionId:sessionId.value});try{const page=await httpClient.request(conversationLogPath.value,{method:`GET`,query:conversationLogReadQuery({beforeTurnId,limit:10})});const previousOldestTurnId=String(turns.value[0]?.turnId||``).trim();const previousMessageCount=turns.value.reduce((count,turn)=>count+(turn.messages?.length||0),0);olderPages.value=[normalizeConversationLogPage(page),...olderPages.value];const nextOldestTurnId=String(turns.value[0]?.turnId||``).trim();const nextMessageCount=turns.value.reduce((count,turn)=>count+(turn.messages?.length||0),0);const changed=Boolean(nextOldestTurnId&&(nextOldestTurnId!==previousOldestTurnId||nextMessageCount!==previousMessageCount));vibe64SessionDebugLog(`client.conversationLog.loadMore.done`,{beforeTurnId,sessionId:sessionId.value,turnCount:Array.isArray(page?.conversationLog)?page.conversationLog.length:0});finish({changed,loaded:true});return true}catch(error){loadMoreError.value=String(error?.message||error||`Older conversation history could not be loaded.`);vibe64SessionDebugLog(`client.conversationLog.loadMore.error`,{beforeTurnId,error:vibe64SessionDebugError(error),sessionId:sessionId.value});finish({changed:false,loaded:false});return false}finally{loadingMore.value=false}}const integrationActions=useConversationIntegrationActions({turns,enabled,sessionId,projectSlug,sessionsApiPath,reloadConversationLog,httpClient});watch([sessionId,projectSlug],()=>{conversationStream.value=null;olderPages.value=[];loadMoreError.value=``});return{...integrationActions,error:resource.loadError,hasMoreBefore,loadMore:loadMoreConversationLog,loadMoreError,loading:resource.isLoading,initializing:resource.isInitialLoading,loadingMore,reload:reloadConversationLog,realtime,turns,visible}}export{useVibe64ConversationLog as t};
@@ -1 +0,0 @@
1
- import{H as hasInjectionContext,J as inject,On as unref,g as computed}from"./runtime-core.esm-bundler-DGXg_mpN.js";import{T as ROUTE_VISIBILITY_PUBLIC,t as useEndpointResource}from"./useEndpointResource-MWVNfmMa.js";import{n as VIBE64_ASSISTANT_VIEWER_KEY}from"./vibe64AssistantHost-DdE_-lZF.js";import{d as VIBE64_CONNECTIONS_CHANGED_EVENT,u as VIBE64_ACCOUNTS_CHANGED_EVENT}from"./client-BrV4QPwG.js";import{t as usePaths}from"./usePaths-Db88-HOm.js";import{t as useCommand}from"./useCommand-DWuxfAV0.js";var VIBE64_DATABASE_LAYOUT_CHANGED_EVENT=`vibe64.database.layout.changed`;var DATABASE_API_SUFFIX=`/vibe64/database`;var DATABASE_SURFACE=`app`;function encodeSegment(value=``){return encodeURIComponent(String(value||``).trim())}function databaseSessionPath(apiPath=``,sessionId=``,suffix=``){return`${apiPath}/sessions/${encodeSegment(sessionId)}${suffix}`}function useVibe64DatabaseTools({active=true,learningAttemptId=``,projectSlug=``,sessionId=``}={}){const paths=usePaths();const viewer=hasInjectionContext()?inject(VIBE64_ASSISTANT_VIEWER_KEY,{actorKey:`local`}):{actorKey:`local`};const actorKey=computed(()=>unref(viewer)?.actorKey||``);const normalizedSessionId=computed(()=>String(unref(sessionId)||``).trim());const normalizedProjectSlug=computed(()=>String(unref(projectSlug)||``).trim());const enabled=computed(()=>Boolean(unref(active)&&normalizedSessionId.value&&actorKey.value));const apiPath=computed(()=>String(unref(learningAttemptId)||``)?`/api/learning/${encodeSegment(unref(learningAttemptId))}${DATABASE_API_SUFFIX}`:paths.api(DATABASE_API_SUFFIX,{surface:DATABASE_SURFACE}));const sessionPath=computed(()=>databaseSessionPath(apiPath.value,normalizedSessionId.value));const stateResource=useEndpointResource({enabled,fallbackLoadError:`The session database workspace could not be loaded.`,path:computed(()=>enabled.value?sessionPath.value:``),queryKey:computed(()=>[`vibe64`,`database`,normalizedProjectSlug.value,normalizedSessionId.value,actorKey.value,`state`]),realtime:{events:[VIBE64_DATABASE_LAYOUT_CHANGED_EVENT,VIBE64_ACCOUNTS_CHANGED_EVENT,VIBE64_CONNECTIONS_CHANGED_EVENT],matches:({event,payload={}}={})=>event!==`vibe64.database.layout.changed`||payload.projectSlug===normalizedProjectSlug.value&&payload.sessionId===normalizedSessionId.value},requestRecoveryLabel:`Session database`});function databaseCommand({fallback,method=`POST`,placement,success=`Completed.`,suppressSuccessMessage=false}={}){return useCommand({access:`never`,apiSuffix:DATABASE_API_SUFFIX,buildCommandOptions:(_input,{context})=>({method:context.method||method,path:context.path||sessionPath.value}),buildRawPayload:(_model,{context})=>context.payload||{},fallbackRunError:fallback,messages:{error:fallback,success},ownershipFilter:ROUTE_VISIBILITY_PUBLIC,placementSource:`vibe64.database.${placement}`,suppressSuccessMessage,surfaceId:DATABASE_SURFACE,writeMethod:method})}const refreshCommand=databaseCommand({fallback:`The database schema could not be refreshed.`,placement:`schema.refresh`,success:`Database schema refreshed.`});const queryCommand=databaseCommand({fallback:`The SQL statement could not be run.`,placement:`query.run`,success:`SQL statement completed.`});const defaultQueryCommand=databaseCommand({fallback:`The table data could not be loaded.`,placement:`query.default`,suppressSuccessMessage:true});const cancelCommand=databaseCommand({fallback:`The database query could not be cancelled.`,placement:`query.cancel`,suppressSuccessMessage:true});const updateCommand=databaseCommand({fallback:`The database value could not be saved.`,method:`PATCH`,placement:`cell.update`,success:`Database value saved.`});const insertCommand=databaseCommand({fallback:`The database row could not be inserted.`,placement:`row.insert`,success:`Database row inserted.`});const deleteCommand=databaseCommand({fallback:`The database row could not be deleted.`,placement:`row.delete`,success:`Database row deleted.`});const lookupCommand=databaseCommand({fallback:`The lookup table could not be searched.`,placement:`lookup.search`,suppressSuccessMessage:true});const layoutCommand=databaseCommand({fallback:`The ERD layout could not be saved.`,method:`PUT`,placement:`layout.save`,suppressSuccessMessage:true});const overviewCommand=databaseCommand({fallback:`The main actor grouping could not be saved.`,method:`PUT`,placement:`overview.save`,success:`Main actors saved in project source.`});const snippetCommand=databaseCommand({fallback:`The SQL snippet could not be saved.`,method:`PUT`,placement:`snippet.save`,success:`SQL snippet saved.`});const snippetDeleteCommand=databaseCommand({fallback:`The SQL snippet could not be deleted.`,method:`DELETE`,placement:`snippet.delete`,success:`SQL snippet deleted.`});const assistantCommand=databaseCommand({fallback:`The database copilot could not answer.`,placement:`assistant.ask`,suppressSuccessMessage:true});async function reload(){if(enabled.value)return stateResource.reload()}async function refreshSchema(){const result=await refreshCommand.run({path:`${sessionPath.value}/schema/refresh`});await reload();return result}function runQuery(payload={}){return(payload.automatic===true?defaultQueryCommand:queryCommand).run({path:`${sessionPath.value}/queries`,payload})}function cancelQuery(queryId=``){return cancelCommand.run({path:`${sessionPath.value}/queries/${encodeSegment(queryId)}/cancel`})}function updateCell(payload={}){return updateCommand.run({path:`${sessionPath.value}/cells`,payload})}function insertRow(payload={}){return insertCommand.run({path:`${sessionPath.value}/rows`,payload})}function deleteRow(payload={}){return deleteCommand.run({path:`${sessionPath.value}/rows/delete`,payload})}function searchLookup(payload={}){return lookupCommand.run({path:`${sessionPath.value}/lookups/search`,payload})}function saveLayout(layout={}){return layoutCommand.run({path:`${sessionPath.value}/layout`,payload:{layout}})}async function saveOverview(payload){const result=await overviewCommand.run({path:`${sessionPath.value}/overview`,payload});if(result?.ok!==false)await reload();return result}function saveSnippet(snippet={}){return snippetCommand.run({path:`${sessionPath.value}/snippets`,payload:{snippet}})}function deleteSnippet(snippetId=``){return snippetDeleteCommand.run({method:`DELETE`,path:`${sessionPath.value}/snippets/${encodeSegment(snippetId)}`})}return{assistantCommand,assistantEndpoint:computed(()=>`${sessionPath.value}/assistant`),assistantBusy:computed(()=>assistantCommand.isRunning===true),cancelQuery,cancelling:computed(()=>cancelCommand.isRunning===true),deleteRow,deleteSnippet,deleting:computed(()=>deleteCommand.isRunning===true),error:stateResource.loadError,insertRow,inserting:computed(()=>insertCommand.isRunning===true),layoutSaving:computed(()=>layoutCommand.isRunning===true),loading:stateResource.isLoading,lookupBusy:computed(()=>lookupCommand.isRunning===true),refreshSchema,refreshing:computed(()=>refreshCommand.isRunning===true),reload,runQuery,running:computed(()=>queryCommand.isRunning===true||defaultQueryCommand.isRunning===true),saveLayout,saveOverview,saveSnippet,searchLookup,state:computed(()=>actorKey.value?stateResource.data.value||null:null),updateCell,updating:computed(()=>updateCommand.isRunning===true)}}export{useVibe64DatabaseTools as t};