vibe64 0.1.63 → 0.1.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/upgrade-state.js +3597 -3590
- package/dist/assets/{GithubBrowserTabs-DEq5_tSs.js → GithubBrowserTabs-D21Nl3QI.js} +1 -1
- package/dist/assets/{LocalDatabaseServer-CrQ9aolO.js → LocalDatabaseServer-POxY1K1U.js} +1 -1
- package/dist/assets/{SelectField-RGWl_ms9.js → SelectField-Dezd0B3y.js} +1 -1
- package/dist/assets/{ShellOutlet-CdjsJfg9.js → ShellOutlet-DfF9vsWA.js} +1 -1
- package/dist/assets/{StudioErrorNotice-CCT_T6mT.js → StudioErrorNotice-vDR4qneB.js} +1 -1
- package/dist/assets/{VAutocomplete-BnpXAJGa.js → VAutocomplete-NpBcbYkR.js} +1 -1
- package/dist/assets/VBtn-Com1gNEe.js +1 -0
- package/dist/assets/{VCard-BFqQSnAE.js → VCard-DY_DdI8Z.js} +1 -1
- package/dist/assets/{VCheckbox-BK0ss4F4.js → VCheckbox-CkezAf4Z.js} +1 -1
- package/dist/assets/{VCheckboxBtn-DDlYJnth.js → VCheckboxBtn-8g4R-c2w.js} +1 -1
- package/dist/assets/{VChip-D2IukBZw.js → VChip-tORFnf7z.js} +1 -1
- package/dist/assets/{VDialog-BCIrX462.js → VDialog-CapFiCqp.js} +1 -1
- package/dist/assets/{VExpansionPanels-BHw1Id_o.js → VExpansionPanels-B6U2XdWH.js} +1 -1
- package/dist/assets/{VMenu-Bql3E6DV.js → VMenu-CO6B6LWk.js} +1 -1
- package/dist/assets/{VOverlay-EPzW7eVB.js → VOverlay-CrfaXCOL.js} +1 -1
- package/dist/assets/{VRadioGroup-CL3HTmyT.js → VRadioGroup-BrPW6foD.js} +1 -1
- package/dist/assets/{VRow-Dz87sIhY.js → VRow-DHETsEMn.js} +1 -1
- package/dist/assets/{VSelect-Ch00dyiM.js → VSelect-gYJ6qrBP.js} +1 -1
- package/dist/assets/{VSheet-D5wAuyc2.js → VSheet-_Grtwpfz.js} +1 -1
- package/dist/assets/{VSkeletonLoader-Bl9P5wdh.js → VSkeletonLoader-CQXCEJsR.js} +1 -1
- package/dist/assets/VSpacer-VLYDmg7o.js +1 -0
- package/dist/assets/{VSwitch-DftK1EyR.js → VSwitch-ffi-Y2TU.js} +1 -1
- package/dist/assets/{VTable-DHazU0Xx.js → VTable-Cver5Vl3.js} +1 -1
- package/dist/assets/{VTextField-B9R7EIjg.js → VTextField-DP6b7Qaf.js} +1 -1
- package/dist/assets/{VTextarea-CMgyRNk-.js → VTextarea-7mdIF4I0.js} +1 -1
- package/dist/assets/{VToolbar-C8ydxLzq.js → VToolbar-CYz3lneF.js} +1 -1
- package/dist/assets/{Vibe64AsyncModuleState-9bN0_H45.js → Vibe64AsyncModuleState-CO1rMrtD.js} +1 -1
- package/dist/assets/{Vibe64AuthSettingsButton-Bbgu_IRu.js → Vibe64AuthSettingsButton-I3ufyScN.js} +1 -1
- package/dist/assets/{Vibe64ConversationLog-MGFaNVSu.js → Vibe64ConversationLog-C04oOQ2g.js} +1 -1
- package/dist/assets/{Vibe64DashboardPageHeader-xfRLZ94G.js → Vibe64DashboardPageHeader-CobvMlFm.js} +1 -1
- package/dist/assets/{Vibe64DashboardShell-i01oU7QS.js → Vibe64DashboardShell-BbrOUmRD.js} +1 -1
- package/dist/assets/{Vibe64DatabaseWorkspace-BqOIE7at.js → Vibe64DatabaseWorkspace-VPEM2o1v.js} +1 -1
- package/dist/assets/{Vibe64DestinationButton-CdyyK9tj.js → Vibe64DestinationButton-B4Zz4a7J.js} +1 -1
- package/dist/assets/{Vibe64FileArea-B8_Tqtgv.js → Vibe64FileArea-C_nC2bPk.js} +1 -1
- package/dist/assets/{Vibe64OutputControls-eaoCQsYn.js → Vibe64OutputControls-DTO3Fw3x.js} +1 -1
- package/dist/assets/{Vibe64RepositoryWorkspace-CoSH_5qZ.js → Vibe64RepositoryWorkspace-B8xcCOvL.js} +1 -1
- package/dist/assets/{Vibe64SessionFiles-Dt1EY-Qo.js → Vibe64SessionFiles-Cb9Mxsyq.js} +1 -1
- package/dist/assets/{Vibe64SessionSourceEditor-D5-abooo.js → Vibe64SessionSourceEditor-CVQ3NRjh.js} +1 -1
- package/dist/assets/{Vibe64UiStoryboardView-CyuufVBB.js → Vibe64UiStoryboardView-BV4JFgcZ.js} +1 -1
- package/dist/assets/{Vibe64UnavailableSessions-CaLRMl-0.js → Vibe64UnavailableSessions-DGQAxYE-.js} +1 -1
- package/dist/assets/{_pageId_-M5CNslNQ.js → _pageId_-CkG15vv4.js} +1 -1
- package/dist/assets/{_sessionId_-jSlkZQLV.js → _sessionId_-Bka3RUmK.js} +1 -1
- package/dist/assets/{_slug_-ClQKNEA9.js → _slug_-7Oo7pGKn.js} +6 -6
- package/dist/assets/{_slug_-CZmGS16g.css → _slug_-BaxjtsgP.css} +1 -1
- package/dist/assets/{access-BqnqYSZR.js → access-Xo3unxGO.js} +1 -1
- package/dist/assets/{app-D7V6OMMB.js → app-B0spNegd.js} +1 -1
- package/dist/assets/assistantRouting-B9cub38g.js +3 -0
- package/dist/assets/{changes-odK1bV6J.js → changes-DFv4tuoO.js} +1 -1
- package/dist/assets/{client-P5LOKvwh.js → client-BjMjS6lX.js} +2 -2
- package/dist/assets/{client-rknXpZ1o.js → client-CVuXqm4b.js} +1 -1
- package/dist/assets/{client-BRcncaFt.js → client-CevjVK2b.js} +1 -1
- package/dist/assets/{client-DwF9Q0VQ.js → client-DR0w56e8.js} +2 -2
- package/dist/assets/{client-BLY6SeL-.js → client-Dlg1kjjO.js} +1 -1
- package/dist/assets/contracts-CNUMi5L0.js +3 -0
- package/dist/assets/{conversation-BMyk8R_u.css → conversation-DReMq0MF.css} +1 -1
- package/dist/assets/{conversation-BoB7Drme.js → conversation-OkWbkHjm.js} +3 -3
- package/dist/assets/{dashboard-D6JkBdZg.js → dashboard-CAca9MQn.js} +1 -1
- package/dist/assets/{english-definitions-CwCZ8VJ-.js → english-definitions-BtX8KA5g.js} +1 -1
- package/dist/assets/env-DrNyBVkB.js +1 -0
- package/dist/assets/{env-CCUgAwiV.css → env-i_R_LXlE.css} +1 -1
- package/dist/assets/errorMessageHelpers-B49LyMJi.js +1 -0
- package/dist/assets/{fileTypes-2k5HCkMT.js → fileTypes-iPZyrJA1.js} +1 -1
- package/dist/assets/{health-B9ZoQC78.js → health-B5yTW5Tt.js} +1 -1
- package/dist/assets/{history-IBqZqdSL.js → history-S3anp6xg.js} +1 -1
- package/dist/assets/{i18n-BkxO7BMl.js → i18n-DQPYjuW7.js} +1 -1
- package/dist/assets/{index-Ctygjyf8.css → index-DSyb-mRJ.css} +1 -1
- package/dist/assets/{index-DAareKn3.js → index-JBqyg0mr.js} +3 -3
- package/dist/assets/{integrations-BBMdyyMq.js → integrations-C7dj7el_.js} +1 -1
- package/dist/assets/{issues-DwUO1HjX.js → issues-OkV4v4GX.js} +1 -1
- package/dist/assets/{layout-B_cpKP4k.js → layout-DMZV-nbg.js} +1 -1
- package/dist/assets/{lazy-vXRXMwYF.js → lazy-mtFmsnct.js} +1 -1
- package/dist/assets/{learning-DAIqaO0B.js → learning-lW9nBGjT.js} +1 -1
- package/dist/assets/{pages-DoUMcieZ.js → pages-shOT9IVe.js} +1 -1
- package/dist/assets/{project-files-DilujZdI.js → project-files-D_K1N0JF.js} +1 -1
- package/dist/assets/{publish-KZQ_gdoN.js → publish-Bxe4ZCqe.js} +1 -1
- package/dist/assets/{pull-requests-BB3CAadu.js → pull-requests-CQvk0TeH.js} +1 -1
- package/dist/assets/{repository-B90tiuN6.js → repository-CI2CqDwF.js} +1 -1
- package/dist/assets/{session-B5MoHBVk.js → session-FRkCCzYt.js} +1 -1
- package/dist/assets/{settings-DdbhtNHb.js → settings-DIVrFrs4.js} +1 -1
- package/dist/assets/{useArchivedVibe64Sessions-B_pM75gN.js → useArchivedVibe64Sessions-BkWrTOzg.js} +1 -1
- package/dist/assets/useAssistantAttachments-DqlNFiha.js +2 -0
- package/dist/assets/useCommand-D-MIMmhp.js +1 -0
- package/dist/assets/useEndpointResource-DZTjr9gg.js +1 -0
- package/dist/assets/useUiFeedback-BU4NyMq8.js +1 -0
- package/dist/assets/{useVibe64ConversationLog-Ch0ZbnCG.js → useVibe64ConversationLog-BADhWyNY.js} +2 -2
- package/dist/assets/{useVibe64Learning-DiLAIKbI.js → useVibe64Learning-CbsI-XHB.js} +1 -1
- package/dist/assets/{useVibe64SessionData-COsXmbMm.js → useVibe64SessionData-DvFvAJC-.js} +1 -1
- package/dist/assets/{useVibe64SessionSelection-CKBC-ZJw.js → useVibe64SessionSelection-BukDTAxb.js} +1 -1
- package/dist/assets/vibe64RepositoryRealtime-CRAyGyRD.css +1 -0
- package/dist/assets/vibe64RepositoryRealtime-DX2DEqIz.js +1 -0
- package/dist/assets/{vibe64SavedEnvValues-CU_SdjKx.js → vibe64SavedEnvValues-CgfMvj_h.js} +1 -1
- package/dist/assets/{vibe64SessionFocus-C0LfHXbF.js → vibe64SessionFocus-CzuP3qPT.js} +1 -1
- package/dist/index.html +37 -37
- package/docs/colleague-usage/ai-tasks.md +7 -0
- package/docs/colleague-usage/coding-agent-goal-pause.md +7 -6
- package/docs/colleague-usage/coding-agent-goals.md +44 -30
- package/docs/colleague-usage/coding-agents.md +22 -8
- package/docs/colleague-usage/development-env.md +37 -5
- package/docs/colleague-usage/project-messages.md +4 -1
- package/node_modules/@jskit-ai/assistant-core/CHANGELOG.md +11 -1
- package/node_modules/@jskit-ai/assistant-core/locales/en.json +7 -5
- package/node_modules/@jskit-ai/assistant-core/package.json +1 -1
- package/node_modules/@jskit-ai/assistant-runtime/CHANGELOG.md +1 -0
- package/node_modules/@jskit-ai/assistant-runtime/package.json +1 -1
- package/node_modules/@jskit-ai/assistant-voice/package.json +1 -1
- package/node_modules/@jskit-ai/connector-google-calendar/package.json +1 -1
- package/node_modules/@jskit-ai/connectors-catalog/package.json +1 -1
- package/node_modules/@jskit-ai/connectors-core/package.json +1 -1
- package/node_modules/@jskit-ai/http-runtime/package.json +1 -1
- package/node_modules/@jskit-ai/kernel/CHANGELOG.md +1 -0
- package/node_modules/@jskit-ai/kernel/package.json +1 -1
- package/node_modules/@jskit-ai/payments-core/package.json +1 -1
- package/node_modules/@jskit-ai/realtime/package.json +1 -1
- package/node_modules/@jskit-ai/resource-core/package.json +1 -1
- package/node_modules/@jskit-ai/uploads-runtime/package.json +1 -1
- package/node_modules/@local/vibe64-core/package.json +1 -0
- package/node_modules/@local/vibe64-execution/src/host/execHelper.js +671 -572
- package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +480 -479
- package/node_modules/@local/vibe64-genesis/src/server/index.js +22 -21
- package/node_modules/@local/vibe64-genesis/src/server/promptContext.js +103 -102
- package/node_modules/@local/vibe64-runtime/src/server/codexAppServerProcess.js +790 -740
- package/package.json +14 -14
- package/server.bundle.mjs +40248 -40119
- package/dist/assets/VBtn-2vbH580C.js +0 -1
- package/dist/assets/VSpacer-GgPR_AzN.js +0 -1
- package/dist/assets/assistantRouting-BS0ZW5Ki.js +0 -3
- package/dist/assets/contracts-CCZaLqSE.js +0 -1
- package/dist/assets/env-CIy7uwLb.js +0 -1
- package/dist/assets/errorMessageHelpers-BjIt31kK.js +0 -1
- package/dist/assets/useAssistantAttachments-BkYZckgz.js +0 -2
- package/dist/assets/useCommand-CNDe8gM-.js +0 -1
- package/dist/assets/useEndpointResource-CmMwteuX.js +0 -1
- package/dist/assets/useUiFeedback-CWb6o71Z.js +0 -1
- package/dist/assets/vibe64RepositoryRealtime-BIXVm4u9.js +0 -1
- package/dist/assets/vibe64RepositoryRealtime-rnWlv9jw.css +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Tt as toValue,gt as reactive,it as watch,mt as onScopeDispose,u as computed,ut as getCurrentScope,vt as ref}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import"./client-4uCr4dYG.js";import{r as useJskitText,t as registerJskitMessages}from"./i18n-BuXRXGaO.js";var jskit=JSON.parse(`{"assistant":{"api":{"requestFailed":"Assistant request failed."},"attachments":{"announcement":{"cancelled":"{count} attachment cancelled. | {count} attachments cancelled.","inProgress":"{count} attachment is in progress. | {count} attachments are in progress.","needAttention":"{count} attachment needs attention. | {count} attachments need attention.","ready":"{count} attachment ready. | {count} attachments ready."},"attached":"Attached files","bytes":"{sent} / {size}","bytesPercent":"{sent} / {size} · {percent}%","cancelItem":"Cancel {name}","close":"Close","download":"Download","error":{"cleanupFailed":"Attachment cleanup failed.","localFilePaste":"Copied local files cannot be pasted from this browser. Drop the file or use Attach files.","noFile":"The prepared attachment did not produce a file.","preparationFailed":"Attachment preparation failed.","tooLarge":"{fileName} is larger than the {limit} attachment limit.","tooMany":"A message can keep at most {count} attachments.","unusable":"Uploaded attachment could not be used.","uploadFailed":"Attachment upload failed."},"limit":"{count} / {max}","preparingName":"Preparing attachment…","previewUnavailable":"Preview is unavailable for this file. You can download it below.","queue":"Message attachments","removeItem":"Remove {name}","retryItem":"Retry {name}","sizeBytes":"{size} B","sizeKilobytes":"{size} KB","sizeMebibytes":"{size} MiB","sizeMegabytes":"{size} MB","status":{"cancelled":"Cancelled","delivering":"Sending to Codex","preparationFailed":"Preparation failed","preparing":"Preparing","queued":"Queued","ready":"Ready","sendingFailed":"Sending failed","uploadFailed":"Upload failed","uploading":"Uploading"},"summary":{"cancelled":"{completed} ready · {cancelled} cancelled","inProgress":"{completed} of {total} ready · in progress","needAttention":"{completed} of {total} ready · {count} needs attention | {completed} of {total} ready · {count} need attention","percent":"{completed} of {total} ready · {percent}%","ready":"{completed} of {total} ready"},"unnamed":"attachment","uploadProgress":"Upload progress for {name}"},"chat":{"attachFiles":"Attach files","avatar":"Conversation avatar","discardUnsent":"Discard unsent message","editUnsent":"Edit unsent message","label":"Assistant conversation","messageAssistant":"Message AI assistant","minimiseAvatar":"Minimise avatar","reviewAttachedFiles":"Please review the attached files.","sendingToAssistant":"Sending to assistant…","showAvatar":"Show avatar","working":"Assistant is working…"},"composer":{"cannotSendYet":"Your words are in the chat box, but this conversation cannot send yet.","chatChanged":"The chat changed before sending. Review the draft before sending.","notReady":"The chat composer is not ready yet.","send":"Send","sendMessage":"Send message","sending":"Sending…","stop":"Stop","stopping":"Stopping…","suggestedPrompts":"Suggested prompts","suggestionsAvailable":"{count} suggested prompts are available before the message controls.","thinkingOfIdeas":"Thinking of a few ideas","thinkingOfIdeasStatus":"Thinking of a few ideas.","useSuggestion":"Use suggestion: {prompt}"},"delivery":{"cancelling":"Cancelling…","cancelUnreachable":"Couldn't reach the server — Cancel again","checkBeforeResend":"Check delivery before resending.","checkPrevious":"Check the previous message's delivery before sending again.","checking":"Checking…","notConfirmed":"Message delivery is not confirmed.","notSent":"Message could not be sent.","retry":"Retry","retryCheck":"Retry delivery check","unconfirmed":"Delivery could not be confirmed.","unconfirmedShort":"Delivery unconfirmed."},"goal":{"blocked":"Goal blocked","budgetLimited":"Goal budget reached","cancel":"Cancel goal","cancelInterruptsTurn":"Cancel stops the current turn and clears the goal.","cancelRemovesGoal":"Cancel removes this goal. Use Stop to interrupt a turn already running.","cancelling":"Cancelling…","complete":"Goal complete","elapsed":"{label}: {elapsed}","goal":"Goal","loading":"Loading goal…","notRunning":"Goal not running","notRunningHint":"Nothing is working on this goal right now. Your next message continues it.","objective":"Goal objective","outOfCredit":"Goal paused: no credit","outOfCreditHint":"The AI account is out of credit. The goal does not continue by itself: top up or switch AI account, then choose Resume goal.","pause":"Pause goal","pauseInterruptsTurn":"Pause stops the current turn and keeps the goal for later.","pausePreventsTurns":"Pausing prevents further automatic turns. Use Stop to interrupt the current turn.","paused":"Goal paused","pausing":"Pausing…","resume":"Resume goal","resuming":"Resuming…","running":"Goal running","runningTime":"Running time","set":"Set goal","start":"Start goal","starting":"Starting…","tokenBudget":"Token budget (optional)","unavailable":"Goal unavailable","usageLimited":"Goal paused: usage limit","usageLimitedHint":"The AI account reached its usage limit. The goal does not continue by itself: choose Resume goal once the AI account can work again.","usageLimitedUntilHint":"The AI account reached its usage limit, which resets at {time}. The goal does not continue by itself: choose Resume goal once it resets."},"longText":{"details":"Details","table":"Table"},"model":{"apply":"Apply","applying":"Applying…","chooseAi":"Choose AI","chooseModel":"Choose model","controls":"AI controls","loading":"Loading available AIs","model":"Model","noMatchingModels":"No matching models","noModels":"No available models.","noneConfigured":"No configured AIs are available for this session.","provider":"Provider","selector":"AI session selector","thinking":"Thinking","tryAgain":"Try again","viewOnly":"AI choices are view-only while the assistant is working.","waitBeforeChanging":"Wait for the active turn to finish before changing models."},"progress":{"hide":"Hide progress updates","showAll":"Show all {count} progress update | Show all {count} progress updates","showLatest":"Show latest {count} progress update | Show latest {count} progress updates"},"questions":{"answerNormally":"Answer normally instead","answerRequired":"Answer question {number}.","fieldLabel":"[{number}] {label}","label":"Assistant questions","suggestedAnswers":"Suggested answers"},"settings":{"readOnly":"Read-only","systemPromptTooLong":"Assistant system prompt must be at most {max} characters.","systemPromptInvalid":"Assistant system prompt must be valid text."},"transcript":{"assistant":"Assistant","cancel":"Cancel","edit":"Edit","failed":"Failed: {error}","history":"Conversation history","loadOlder":"Load older messages","loading":"Loading conversation","loadingOlder":"Loading older messages…","messages":"Conversation messages","pending":"Pending","pendingReason":"Pending: {reason}","preparing":"Preparing conversation","progress":"{name} progress","readMore":"Read more","recommended":" · Recommended","reload":"Reload chat","reloading":"Reloading chat","reloadingShort":"Reloading…","reviewMessage":"Review your message","showLess":"Show less","status":"Status"},"turn":{"failed":"Assistant stopped with an error.","stopped":"Stopped.","invalidResponse":"The assistant returned an invalid response.","requestIncomplete":"The assistant could not complete this request."},"conversation":{"handleClosed":"This conversation handle is closed.","handleDisposed":"This conversation handle is disposed.","runtimeClosed":"This conversation runtime is closed.","pagedHistoryUnsupported":"This conversation does not supply paged history.","completedEnvelopesNeedNativeOwner":"Completed envelopes require a runtime-owned native conversation.","completedEnvelopesNotOwned":"This conversation does not own completed envelopes.","goalAttachmentContentUnsupported":"Native goals require extracted text or supported image bytes for attachments.","originalSendOnly":"This conversation supports its original application Send operation.","attachmentIdsOnly":"Supply attachmentIds; only the application's resolver can supply file content.","attachmentsNotConfigured":"File attachments are not configured for this conversation.","steeringUnsupported":"This connection does not support steering.","goalsUnsupported":"This connection does not support native goals.","goalTokenBudgetsUnsupported":"This connection does not support goal token budgets.","goalCommandUnsupported":"This connection does not support that goal command.","goalAttachmentsUnsupported":"This engine's native goal commands do not accept attachments.","completedEnvelopesNeedNativeEngine":"Completed envelopes require a native engine.","replacementPolicyRetained":"This conversation retains its original replacement policy.","selectedProfileRetained":"This scoped conversation retains its original selected profile.","hostSelectionRequired":"This host requires its authorized assistant selection operation.","liveSettingsUnsupported":"This provider does not support live native settings.","completedEnvelopesNeedStorage":"Completed envelopes require runtime-owned canonical storage.","originalReadOnly":"This conversation uses its original read and subscription operations.","messageCancelUnsupported":"This conversation cannot cancel one message.","messageCancelled":"This message was cancelled. Send it again as a new message.","authorizedSelectionRequired":"Use the conversation's authorized selection operation.","eventDeliveryRetained":"This scoped conversation retains its original event delivery.","engineChanged":"The selected native engine changed.","useReplaceForEngine":"Use replace() to change this conversation's engine.","rewindInspectionBeforeOpen":"This conversation has an unfinished Undo operation from an earlier runtime. Inspect its saved native and local history offline before opening it; no history was changed.","rewindInspectionBeforeReplace":"This conversation has an unfinished Undo operation from an earlier runtime. Inspect its saved native and local history offline before replacing it; no history was changed.","responseOwnerChanged":"The completed response owner changed.","newerResponseOwnsWorker":"A newer completed response owns this worker.","responseIdentityChanged":"The completed response identity changed.","applicationToolMessageStale":"This application tool's admitted message is no longer current.","nativeCompletionMessageStale":"This native completion's admitted message is no longer current.","toolObservationRetired":"The native tool observation belongs to a retired response.","toolObservationReceiptLost":"The native tool observation lost its exact admitted receipt.","waitForNativeResponse":"Wait for the native response to finish.","waitForAnswer":"Wait for this answer or use steer to send another instruction.","waitForTurnSaving":"Wait for the current turn to finish saving before starting the goal.","waitForInstructionAdmission":"Wait for the pending instruction to be admitted before steering again.","waitForGoalCommand":"Wait for the goal command to be admitted.","waitForSubmission":"Wait for the current submission before checking delivery.","stopBeforeReplace":"Stop the current turn before replacing its native conversation.","stopBeforeSettings":"Stop the current turn before changing its settings.","completedResponseNoReceipt":"The completed response has no current verified receipt.","completedResponseNoTurnReceipt":"The completed response has no exact native turn receipt.","completedClaudeNoToolEvidence":"The completed Claude response has no native tool-attempt evidence.","responseAssociationUnverified":"The native owner could not verify this response association.","responseOtherOperation":"This response already belongs to a different application operation.","completedResponseNoPlainReply":"This completed response does not own a plain reply.","completedReplyNoTarget":"The completed reply has no current plain authored target.","publishedReplyChanged":"The published reply target or text changed.","replyTargetUsed":"This plain reply target already has unassociated content or consumption.","operationResponseIdentity":"The operation has a different completed response identity.","plainReplyPublished":"This completed response already published its plain reply.","savedOperationChanged":"The saved response operation changed.","turnFinishedBeforeSend":"The native turn finished before this instruction was sent. Send it as a new message.","noActiveTurnToSteer":"There is no active native turn to steer. Send a new message.","briefingBeforeTerminal":"Send a chat message to deliver the saved continuity briefing before starting a native terminal or goal.","briefingBeforeGoal":"Send a message to catch this AI up before starting or resuming its goal.","briefingBeforeReplacement":"Deliver the previous replacement's briefing before replacing native history again.","historyExclusionsInvalid":"Native history exclusions require a server-owned completed application wake and exact message IDs.","messageContentRequired":"Bounded text or attachment IDs and a stable messageId are required.","steerNotBoolean":"steer must be a boolean.","applicationDataInvalid":"Application data must be a JSON object within the conversation input limit.","goalMessageIdRequired":"A stable messageId is required for this goal command.","goalConversationChanged":"The conversation changed before this goal command was sent.","goalNeedsNativeConversation":"This command requires an existing native conversation.","messageIdExclusionsConflict":"This messageId already belongs to different native history exclusions.","messageIdContentConflict":"This messageId already belongs to different content.","completedClaudeNotSteerable":"Completed Claude responses cannot share a native steering turn. Wait for the response or stop it.","replacementPendingBeforeSend":"Finish the pending native replacement before sending another message.","replacementPendingBeforeRecovery":"Finish the native replacement before recovering output.","replacementUnfinished":"Retry the unfinished native replacement before starting another one.","replacementPendingBeforeSettings":"Finish the pending native replacement before changing settings.","retainedDeliveryUncertain":"This message has uncertain delivery in a retained conversation. Select that engine and check its receipt before submitting it again.","previousInstructionUnchecked":"Check delivery of the previous instruction before preparing another completed response.","previousSubmissionUncertain":"The previous submission has uncertain delivery. It will not be resent automatically.","goalCommandDeliveryUncertain":"Check the uncertain command's delivery before changing the goal.","earlierGoalCommandUnresolved":"A goal command from an earlier runtime has unresolved delivery. Inspect its saved state before changing the goal.","pendingDeliveryBeforeReplace":"Resolve pending delivery before replacing native history. Another engine may be selected while its receipt stays pending.","deliveryUncertainBeforeSettings":"Resolve uncertain delivery before changing settings.","goalActionRequired":"A goal action and current conversation segment are required.","goalObjectiveInvalid":"A bounded objective and optional positive token budget are required.","goalToResumeRequired":"Select the goal to resume.","goalToStopRequired":"Select the goal to stop.","replacementRequestInvalid":"Replacement needs an operationId, exact predecessor segment, and an engine-change, model-change or renewal reason.","replacementBriefingRequired":"Native replacement requires a continuity briefing.","predecessorChanged":"The native predecessor has changed. Read the conversation before replacing it.","replacementOperationConflict":"This replacement operationId already belongs to another request.","replacementChangedBeforeWrite":"The saved replacement changed before it could be written.","replacementChangedBeforeRelease":"The saved replacement changed before its binding was released.","predecessorChangedBeforeRelease":"The native predecessor identity changed before its binding was released.","predecessorIncomplete":"The native predecessor identity changed or is incomplete.","hostScopeMismatch":"This open conversation already belongs to another host scope. Dispose its handle before reopening it on the original host.","cleanupNeedsOriginalConversation":"Native cleanup requires its original bound conversation.","deliveryUnconfirmed":"Native delivery could not be confirmed.","messageNotSent":"This message was not sent. Review it before sending a new message.","attachmentIdsInvalid":"Attachments require at most {max} distinct, nonempty attachment IDs.","attachmentResolverIncomplete":"The attachment resolver must return a receipt for every requested file and bounded model content.","attachmentLocalFilesUnsupported":"This engine cannot accept local attachment files. Supply extracted text or supported image bytes.","attachmentReceiptInvalid":"Attachment receipts require the requested ID, a bounded fileName and a nonnegative size.","attachmentLocalFileInvalid":"Local attachment files require their exact requested receipt and an authorized absolute native path.","attachmentFormatUnsupported":"This engine cannot accept that attachment format. Supply extracted text or a supported image.","attachmentTextEmpty":"Attachment text must be nonempty.","attachmentBytesRequired":"Attachments require authorized bytes and a supported media type; remote URLs and paths are not accepted.","attachmentBytesExceeded":"Attachment content exceeds the configured byte limit for this request.","replacementRetryMismatch":"Replacement retry does not match the saved operation.","previousReplacementUnfinished":"Finish the previous native conversation replacement first.","previousReleaseUndoUnfinished":"An unfinished conversation Undo from a previous release blocks assistant work. Complete it using the previous release before upgrading.","pendingDeliveryBeforeContextReplace":"Finish pending delivery before replacing native context.","shutdownUnconfirmed":"Native conversation shutdown was not confirmed.","submissionInterrupted":"The previous submission was interrupted. Check delivery before submitting it again.","restartInterrupted":"The application restarted before this answer completed. The request was not replayed.","copiedInterrupted":"Copied into a stopped development environment. This request was not replayed.","operationResultUnsaved":"The application operation result could not be saved. Restore storage access and retry saving.","progressUnsaved":"Conversation progress could not be saved. Restore access to its storage before continuing.","requestTimedOut":"The conversation request exceeded its time limit.","workStopped":"Work stopped.","stoppedByUser":"Stopped by user.","apiHistoryLimit":"This conversation exceeds the configured API history limit. Start another conversation or increase the limit.","outputTokenLimit":"The model reached its output token limit before completing the answer. Increase maxOutputTokens in the conversation limits.","toolCallsUnconfirmed":"The model stream ended without confirming its application tool calls.","answerUnconfirmed":"The model stream ended without confirming a completed answer.","toolProgressLimit":"Application tool progress text exceeds the configured API limit.","finalReplyLimit":"The assistant exceeded the configured final reply limit.","historyBudgetExceeded":"Conversation updates exceed the configured history budget. Renew the context with a continuity briefing before continuing.","briefingBudgetExceeded":"The continuity briefing exceeds the configured history budget.","contextChangedInstallingPrompt":"Conversation context changed while installing its system prompt. Retry before sending.","contextChangedReadingInstructions":"Conversation context changed while reading instructions. Retry before sending.","messageNotAcknowledged":"The engine did not acknowledge the message.","stopTemporaryBeforeChange":"Stop this temporary conversation before changing its AI.","toolArgumentsTooLarge":"The application tool arguments exceed their size limit.","toolCallLimit":"The assistant reached the application tool-call limit for this turn."},"claude":{"goalChanged":"The Claude goal changed. Refresh before trying again.","goalTokenBudgetUnsupported":"Claude goals do not support a token budget.","goalBlockerReasonRequired":"An active Claude goal needs a blocker reason of up to 1,000 characters.","goalConditionRequired":"Enter a goal condition of up to 4,000 characters.","goalAlreadySet":"Cancel the existing goal before setting another.","goalActionUnknown":"Unknown Claude goal action.","compactWhileWorking":"Claude is still working. Wait for it to finish before freeing its context.","noActiveTurn":"Claude has no active turn for this message.","steeringUnavailable":"This Claude turn cannot accept steering now.","settingsChangeWhileWorking":"Stop the current Claude turn before changing its settings.","notConnected":"Claude Code is not connected.","accountStatusInvalid":"Claude Code returned an invalid account status.","accountChangedRefreshModels":"The signed-in Claude account changed. Refresh the model list.","accountQueryCancelled":"Claude account query was cancelled for reconnection.","accountQueryCleanupUnconfirmed":"Claude account query process cleanup could not be confirmed.","answerInterrupted":"Claude interrupted this answer.","chooseConnectedModel":"Choose a connected Claude Code model.","closedOrWorking":"This Claude conversation is closed or already working.","connectionClosed":"Claude connection is closed.","connectionWasClosed":"Claude connection was closed.","controlNeedsTerminal":"This control request requires the native Claude Code terminal.","eventConnectionEnded":"Claude event connection ended unexpectedly.","exitedUnexpectedly":"Claude exited unexpectedly.","modelUnsupported":"This exact provider/model is not supported by the Claude integration. Choose a supported model without renaming it.","noTurnToSteer":"Claude has no active turn to steer.","otherHostConfiguration":"This Claude conversation belongs to another working directory or credential home. Restore its original host configuration.","reasoningEffortUnsupported":"The selected Claude model does not support this reasoning effort.","reconnecting":"Claude is reconnecting.","sendNowUnsupported":"This Claude version does not support targeted Send now.","signInRequired":"Sign in with claude auth login before using this conversation.","stopBeforeReset":"Stop Claude before resetting its turn view.","toolCallLimit":"Claude exceeded the application tool-call limit.","turnStillWorking":"This Claude turn is still working.","workEnded":"Claude work ended.","outputTooLarge":"Claude output exceeded its size limit."},"codex":{"helperThreadUnavailable":"This low-cost assistant thread is no longer available. Start the background task again instead of reusing another assistant conversation.","helperOwnershipBlocked":"{applicationName} could not prove ownership of a persisted low-cost assistant thread.","threadDeleteUnavailable":"Codex app-server thread deletion is not available.","goalActionInvalid":"Choose set, pause, resume, or cancel.","goalObjectiveInvalid":"Enter a goal objective and an optional positive whole-number token budget.","goalConversationChanged":"The Codex conversation changed. Refresh the goal before trying again.","goalConversationStopped":"Resume or send a message to restore the stopped conversation before setting a goal.","goalChangedBeforeSet":"The Codex goal changed. Refresh it before setting a new goal.","goalChanged":"The Codex goal changed. Refresh it before trying again.","goalAlreadyStopped":"This goal is already stopped. Refresh its details.","goalStopUnconfirmed":"Codex has not yet confirmed a stop. Retry after the service has stopped.","goalNotResumable":"This goal cannot be resumed from its current status. Refresh its details.","stopUnverified":"Codex's stop could not be verified. Its runtime owner is unavailable.","turnNotReady":"The active assistant turn is not ready to accept this message yet.","messageEmpty":"Codex message is empty.","messageInputEmpty":"Codex message input is empty.","operationNotSteerable":"The active assistant operation cannot accept messages yet.","temporaryConversationBusy":"Temporary AI is already working on this conversation.","accountChangedSendAgain":"Codex (OpenAI) changed account. Send your message again.","accountUnavailable":"The selected Codex account is unavailable. Reconnect Codex and retry.","assistantChangedRefresh":"The assistant changed. Refresh before resuming.","authChangedReopen":"Codex authentication changed. Reopen the conversation with its original account.","authModeUnsupported":"The selected Codex authentication mode is unsupported. Reconnect Codex and retry.","authRecordInvalid":"The selected Codex authentication record is invalid. Reconnect Codex and retry.","authRecordTooLarge":"The selected Codex authentication record is too large. Reconnect Codex and retry.","authRecordUnreadable":"The selected Codex authentication record could not be read. Reconnect Codex and retry.","authorizedSettingsRequired":"Codex requires current authorized settings before resuming this conversation.","connectionClosedBeforeSettings":"The assistant connection closed before confirming its settings.","connectionUnverified":"The assistant connection could not be verified. Your conversation and files are preserved. Retry the connection, or renew the session to continue in a fresh conversation.","credentialsUnreadable":"Codex credential data could not be read. Restore its account configuration.","ephemeralInstructionsFixed":"Start a new ephemeral conversation to change its instructions.","goalPauseUnconfirmed":"Codex did not confirm that the same goal was paused.","goalsAreControls":"Codex goals are controls. Inspect any unresolved goal-message record before continuing.","helperAccessTokenStale":"The selected Codex account has not produced a newer access token yet. Reconnect Codex and retry.","helperAccountActivationFailed":"Codex could not activate the selected account for isolated helper work. Reconnect Codex and retry.","helperAccountChanged":"The selected Codex account changed during helper work. Retry the task with the current account.","helperAccountChangedBeforeRun":"The selected Codex account changed before low-cost assistant work could run. Retry the task with the current account.","helperAccountChangedStarting":"The selected Codex account changed while helper execution was starting. Retry the task.","helperAccountIdentityInvalid":"The requested low-cost assistant account identity is invalid. Refresh the task and retry.","helperAuthRefreshRejected":"Codex helper authentication refresh was rejected. Reconnect Codex and retry.","helperAuthUnavailable":"Codex helper authentication is unavailable. Reconnect Codex and retry.","helperExecutionFailed":"Codex isolated helper execution failed. Retry the task.","helperThreadReconnectAccount":"Reconnect the original Codex account to resume or delete this helper thread.","historyFormatStartFresh":"This conversation uses an unsupported Codex history format. Start a fresh conversation.","historyFormatUnsupported":"This conversation uses an unsupported Codex history format. Renew the session to keep your files and saved chat and start a fresh conversation. You can write the handover yourself.","loadedThreadsInvalid":"Codex returned an invalid loaded-thread inventory. Restore its connection before retrying.","modelDiscoveryUnavailable":"Codex live model discovery is unavailable.","modelUnsupported":"This exact provider/model is not supported by the Codex integration. Choose a supported model without renaming it.","nativeGoalChanged":"The native goal changed. Read it again before changing it.","observationLostStopUnverified":"Codex observation was lost and a stop is not yet verified. Retry after the service has stopped.","oldThreadUnreadable":"The old assistant thread cannot be read. Write or edit the handover manually instead.","otherAccount":"This conversation belongs to another Codex account. Restore that account or start a new conversation.","otherHostConfiguration":"This Codex conversation belongs to another working directory or credential home. Restore its original host configuration.","otherProviderAccount":"This conversation belongs to another Codex provider account. Restore that connection or start a new conversation.","outputTooLarge":"Codex output exceeded the configured limit.","paginatedConversationHistoryMissing":"Codex did not create the required paginated conversation history. Update Codex before starting a conversation.","paginatedHistoryMissing":"Codex did not create the required paginated history. Update Codex before starting this conversation.","reasoningEffortUnsupported":"The selected Codex model does not support this reasoning effort.","reconnectOpenAi":"Reconnect the OpenAI account before using this model.","responseTimeout":"Timed out waiting for Codex app-server response.","signInRequired":"Sign in with codex login before using this conversation.","stillReconnecting":"Codex is still reconnecting: its shared runtime is busy starting or stopping. Please try again shortly.","stoppedUseResume":"Codex is stopped. Use Resume or Send to continue.","temporaryConnectionLost":"Connection to Codex was lost while the temporary AI was working.","temporaryConversationClosed":"Temporary AI conversation was closed.","temporaryTurnStopped":"Temporary AI turn was stopped.","threadInventoryUntrusted":"Codex returned an untrustworthy thread/provider inventory. Restore its connection before changing credentials.","toolEntryPointsChanged":"This Codex conversation was created with different application tool entry points. Start a new conversation to enable or remove application tools.","turnStopUnconfirmed":"Codex did not confirm that its turn stopped."},"provider":{"notConfigured":"Assistant provider is not configured.","requestFailed":"Assistant provider request failed.","requestRejected":"Request failed."},"stream":{"failed":"Assistant stream failed.","requestFailed":"Request failed."},"opencode":{"cleanupUnconfirmed":"OpenCode process cleanup could not be confirmed. Restore its execution host before continuing.","closedOrWorking":"This OpenCode conversation is closed or already working.","messageNotAcknowledged":"OpenCode did not acknowledge the message.","modelDefinitionUnavailable":"OpenCode could not load the configured model definition. Check the selected integration before sending.","nativeStillWorking":"The native OpenCode conversation is still working. Stop or inspect it before sending another message.","noTurnToSteer":"OpenCode has no active turn to steer.","otherAccount":"This conversation belongs to another OpenCode account. Restore that connection or start a new conversation.","otherHistoryStore":"This OpenCode conversation belongs to another native history store. Restore its original host configuration.","otherHistoryStoreOrRuntime":"This OpenCode conversation belongs to another native history store or runtime. Restore its original host configuration.","otherWorkingDirectory":"This OpenCode conversation belongs to another working directory or native state directory. Restore its original host configuration.","reasoningEffortUnsupported":"The selected OpenCode model does not support this reasoning effort.","reopenTerminalToAttach":"Reopen the OpenCode terminal before attaching files.","savedConversationUnavailable":"The saved OpenCode conversation is unavailable. Restore its native history before continuing.","turnFailed":"OpenCode turn failed.","turnUnreadable":"The exact OpenCode turn did not produce a readable result.","turnNotFinished":"OpenCode did not finish the turn."}},"errors":{"conversation_forbidden":"This conversation is not available to this identity.","conversation_storage_version":"This conversation needs its offline runtime-state upgrade before it can be opened. Its saved requests were not replayed or changed.","conversation_configuration_mismatch":"Use configure() to change a saved conversation's settings.","conversation_goal_stopped":"The goal command was stopped before delivery.","conversation_attachment_manifest_changed":"Authorized attachment paths changed after this instruction was prepared. Restore the original files or send a new message.","conversation_receipt_unavailable":"The native receipt has no stored authored message.","conversation_goal_unavailable":"The native goal is unavailable. Try reading its status again.","assistant_provider_invalid_response":"Assistant provider returned an invalid response payload.","assistant_opencode_conversation_busy":"This conversation is still working.","assistant_opencode_key_verification_failed":"OpenCode rejected the API-key verification request.","assistant_opencode_turn_thread_mismatch":"The OpenCode predecessor history changed before handover generation.","assistant_opencode_turn_fresh_thread_required":"The renewed OpenCode conversation does not own the expected fresh native history.","assistant_opencode_turn_unrelated_history":"The successor OpenCode history contains unrelated conversation and cannot be used for renewal.","conversation_claude_turn_timeout":"Claude did not finish within the time limit.","conversation_claude_renewal_history_mismatch":"The Claude renewal conversation does not match the expected native history.","conversation_claude_renewal_unrelated_history":"The successor Claude conversation already contains unrelated messages.","conversation_claude_renewal_turn_active":"Stop the current turn before renewing this conversation.","conversation_claude_unavailable":"This Claude conversation is unavailable.","conversation_claude_retained_goal_invalid":"The retained Claude goal is invalid. Restore its saved conversation state.","conversation_claude_retained_goal_conflict":"The saved Claude goal cannot be both paused and blocked.","conversation_claude_session_closing":"This session is closing.","conversation_claude_preparation_stopped":"Claude preparation was stopped while this session was closing or changing.","conversation_claude_terminal_turn_active":"Stop the current turn before opening the Claude Code terminal.","conversation_claude_still_working":"This conversation is still working.","conversation_claude_history_retire_busy":"Stop the saved Claude process and its terminal before retiring native history.","conversation_claude_message_required":"Enter a message for Claude.","conversation_claude_command_stopped":"The goal command was stopped before delivery.","conversation_claude_context_usage_unavailable":"Claude's current context usage is unavailable.","conversation_claude_goal_clear_unconfirmed":"Claude has not saved the retained goal's native clear receipt.","conversation_claude_saved_state_unreadable":"The saved Claude conversation {conversationId} is unreadable. Restore its saved conversation state.","conversation_tool_not_executed":"Execution stopped before the action began.","conversation_tool_outcome_unknown":"The application operation did not return a verified result. Inspect its target before requesting another execution.","conversation_unsupported":"This original scoped conversation has no canonical message or goal receipt.","assistant_claude_goal_attachment_pending":"Claude accepted the goal command, but its goal attachment is not available yet. Check its original receipt before trying again.","assistant_claude_admission_unknown":"Claude has not acknowledged this prompt. Its delivery is uncertain.","assistant_claude_startup_exited":"Claude exited before initialization completed.","claude_stop_unconfirmed":"Claude process cleanup could not be confirmed. Restore its execution host before continuing.","claude_account_changed":"This conversation belongs to another Claude account. Reconnect that account or start a new session.","assistant_opencode_recovery_order_unconfirmed":"OpenCode could not confirm that the new input follows its final-answer recovery. The admitted message was not resent.","assistant_opencode_interrupt_unconfirmed":"OpenCode did not confirm Stop. Try Stop again.","assistant_opencode_interrupt_timeout":"OpenCode did not confirm Stop within 5 seconds. Try Stop again.","assistant_opencode_key_verification_unavailable":"OpenCode API-key verification could not run.","assistant_opencode_stop_unverified":"OpenCode process exit could not be verified.","assistant_opencode_connection_reload_failed":"OpenCode could not load the changed AI connection for this work. Send your message again.","assistant_opencode_response_too_large":"OpenCode returned more data than the bridge accepts.","assistant_opencode_event_too_large":"An OpenCode event exceeded the bridge limit.","assistant_opencode_directory_unavailable":"OpenCode did not confirm its conversation directory is ready.","assistant_opencode_catalog_invalid":"OpenCode returned an invalid provider catalogue.","assistant_opencode_catalog_stop_failed":"The temporary OpenCode catalogue process did not stop cleanly.","assistant_opencode_events_timeout":"OpenCode's event connection did not become ready.","assistant_opencode_observation_lost":"OpenCode's event connection ended before observation was closed.","assistant_opencode_parent_unverified":"The subagent's parent session could not be verified.","assistant_opencode_start_timeout":"OpenCode did not become ready before the startup deadline.","assistant_opencode_version_mismatch":"OpenCode {installed} is installed; this host requires {required}.","assistant_opencode_zen_catalog_unavailable":"OpenCode Zen's current model list could not be read. Try again.","assistant_agent_control_binding_retained":"Another native subscriber retained the previous assistant settings. Close the native assistant terminal and retry Resume.","assistant_codex_provider_binding_retained":"Another native subscriber retained the previous model provider. Close the native assistant terminal and retry.","assistant_codex_provider_switch_busy":"Stop the current turn before immediately changing model providers.","assistant_codex_history_request_too_large":"Codex history exceeds the adapter request limit.","assistant_codex_history_request_unreadable":"Codex sent an unreadable or oversized history request.","assistant_custom_endpoint_unreachable":"Your model server at {upstream} isn't answering. Start it, then send your message again.","assistant_codex_app_server_message_too_large":"Codex app-server message exceeded the configured transport limit.","codex_reconnect_required":"Sign in with codex login before continuing.","codex_provider_connection_changed":"This Codex provider connection changed. Work is stopped; use Send or Resume after reconnecting.","codex_runtime_invalidated":"Codex's native runtime was invalidated.","assistant_provider_fetch_missing":"Global fetch is not available for anthropic provider.","assistant_tool_arguments_invalid":"Tool arguments must be a JSON object.","assistant_tool_result_unserializable":"Tool result could not be serialized.","assistant_tool_result_too_large":"Tool result exceeds the assistant size limit. Narrow the request and try again.","assistant_tool_contract_too_large":"Action contract exceeds the assistant size limit. Narrow the request and try again.","assistant_tool_arguments_too_large":"Tool arguments exceed the assistant size limit. Narrow the request and try again.","assistant_action_cursor_invalid":"Action search cursor is invalid for this query.","assistant_action_unknown":"Action is not available.","assistant_action_contract_required":"Load this action's exact contract before executing it.","assistant_tool_output_invalid":"Assistant tool output validation failed.","assistant_tool_unknown":"Unknown tool.","assistant_claude_control_timeout":"Claude {request} timed out."}}`);var en_default={jskit};registerJskitMessages(en_default);function attachmentSizeLabel(size){const bytes=Number(size);if(!Number.isFinite(bytes)||bytes<0)return``;if(bytes<1024)return`${bytes} B`;if(bytes<1048576)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/1048576).toFixed(1)} MB`}var jskitText=useJskitText();var{formatNumber,t:t$3}=jskitText;var WHOLE=Object.freeze({useGrouping:false});var ONE_DECIMAL=Object.freeze({maximumFractionDigits:1,minimumFractionDigits:1,useGrouping:false});function attachmentSizeText(size){if(!jskitText.locale)return attachmentSizeLabel(size);const bytes=Number(size);if(!Number.isFinite(bytes)||bytes<0)return``;if(bytes<1024)return t$3(`jskit.assistant.attachments.sizeBytes`,{size:formatNumber(bytes,WHOLE)});if(bytes<1048576)return t$3(`jskit.assistant.attachments.sizeKilobytes`,{size:formatNumber(bytes/1024,ONE_DECIMAL)});return t$3(`jskit.assistant.attachments.sizeMegabytes`,{size:formatNumber(bytes/1048576,ONE_DECIMAL)})}function attachmentLimitText(maxBytes){if(!jskitText.locale)return maxBytes%1048576===0?`${maxBytes/1048576} MiB`:`${maxBytes/1e6} MB`;return maxBytes%1048576===0?t$3(`jskit.assistant.attachments.sizeMebibytes`,{size:formatNumber(maxBytes/1048576,WHOLE)}):t$3(`jskit.assistant.attachments.sizeMegabytes`,{size:formatNumber(maxBytes/1e6,{useGrouping:false})})}var{t:t$2}=useJskitText();function assistantAttachmentFiles(fileList){return Array.from(fileList||[]).filter(file=>file&&file.size>=0)}function assistantAttachmentFilesFromTransferItems(items){return assistantAttachmentFiles(Array.from(items||[]).map(item=>{if(item?.kind!==`file`||typeof item.getAsFile!==`function`)return null;return item.getAsFile()}))}function assistantAttachmentFilesFromDropEvent(event){const dataTransfer=event?.dataTransfer;const itemFiles=assistantAttachmentFilesFromTransferItems(dataTransfer?.items);if(itemFiles.length>0)return itemFiles;return assistantAttachmentFiles(dataTransfer?.files)}function assistantAttachmentFilesFromPasteEvent(event){const clipboardData=event?.clipboardData;const itemFiles=assistantAttachmentFilesFromTransferItems(clipboardData?.items);if(itemFiles.length>0)return itemFiles;return assistantAttachmentFiles(clipboardData?.files)}function assistantAttachmentEventHasFiles(event){const dataTransfer=event?.dataTransfer;return assistantAttachmentFilesFromDropEvent(event).length>0||Array.from(dataTransfer?.items||[]).some(item=>item?.kind===`file`)||Array.from(dataTransfer?.types||[]).some(type=>type===`Files`||type===`application/x-moz-file`)}function assistantAttachmentClipboardText(event){if(typeof event?.clipboardData?.getData!==`function`)return``;return String(event.clipboardData.getData(`text/plain`)||``)}function assistantAttachmentClipboardLocalFileReference(event){const clipboardData=event?.clipboardData;if(!clipboardData||typeof clipboardData.getData!==`function`)return``;const types=Array.from(clipboardData.types||[]);const text=[clipboardData.getData(`x-special/gnome-copied-files`),clipboardData.getData(`text/uri-list`),clipboardData.getData(`text/plain`)].map(value=>String(value||``).trim()).filter(Boolean).join(`
|
|
2
|
+
`);if(types.includes(`Files`)||types.includes(`application/x-moz-file`)||types.includes(`x-special/gnome-copied-files`)||/^file:/imu.test(text))return text||`file://`;return``}function useAttachmentDropTarget({uploadFiles,reportAttachmentError}){const dragDepth=ref(0);const dragActive=computed(()=>dragDepth.value>0);function resetDragState(){dragDepth.value=0}function handleDragEnter(event){if(!assistantAttachmentEventHasFiles(event))return;dragDepth.value+=1;if(event?.dataTransfer)event.dataTransfer.dropEffect=`copy`}function handleDragOver(event){if(event?.dataTransfer)event.dataTransfer.dropEffect=`copy`}function handleDragLeave(){dragDepth.value=Math.max(0,dragDepth.value-1)}async function handleDrop(event){resetDragState();return uploadFiles(assistantAttachmentFilesFromDropEvent(event))}async function handlePaste(event){const files=assistantAttachmentFilesFromPasteEvent(event);if(files.length<1){if(assistantAttachmentClipboardLocalFileReference(event))reportAttachmentError(t$2(`jskit.assistant.attachments.error.localFilePaste`));return[]}if(!assistantAttachmentClipboardText(event))event?.preventDefault?.();return uploadFiles(files)}return{dragActive,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,resetDragState}}var{t:t$1}=useJskitText();function attachmentUploadError(attachment){return attachment?.error||attachment?.errors?.[0]?.message||``}function attachmentIdentity(attachment){return String(attachment?.clientId||attachment?.attachmentId||attachment?.path||attachment?.fileName||``)}var attachmentClientSequence=0;function nextAttachmentClientId(){attachmentClientSequence+=1;return`attachment-${Date.now().toString(36)}-${attachmentClientSequence.toString(36)}`}function attachmentFileName(file){return String(file?.name||`attachment`)}function attachmentUploadResult(upload=null){if(upload&&typeof upload.then===`function`)return{cancel:typeof upload.cancel===`function`?()=>upload.cancel():null,promise:upload};if(upload?.promise&&typeof upload.promise.then===`function`)return{cancel:typeof upload.abort===`function`?()=>upload.abort():typeof upload.cancel===`function`?()=>upload.cancel():null,promise:upload.promise};return{cancel:null,promise:Promise.resolve(upload)}}function attachmentProgress(progress={},possibleTotal,fallbackTotal=0){const directNumericProgress=typeof progress===`number`?progress:null;const progressObject=progress&&typeof progress===`object`?progress:{};const totalBytes=Math.max(0,Number(progressObject.totalBytes??progressObject.total??possibleTotal??fallbackTotal)||0);const bytesValue=progressObject.bytesSent??progressObject.loaded??progressObject.uploadedBytes??directNumericProgress;const bytesKnown=bytesValue!==null&&bytesValue!==void 0&&bytesValue!==``;let bytesSent=bytesKnown?Number(bytesValue)||0:0;const directPercent=progressObject.percent;let percent=directPercent!==null&&directPercent!==void 0&&directPercent!==``?Number(directPercent):null;const progressValue=progressObject.progress;if(!Number.isFinite(percent)&&progressValue!==null&&progressValue!==void 0&&progressValue!==``){const numericProgressValue=Number(progressValue);if(Number.isFinite(numericProgressValue))percent=numericProgressValue<=1?numericProgressValue*100:numericProgressValue}if(!Number.isFinite(percent))percent=bytesKnown&&totalBytes>0?bytesSent/totalBytes*100:null;if(percent!==null)percent=Math.max(0,Math.min(100,percent));if(totalBytes>0){const inferredBytes=percent===null?0:totalBytes*percent/100;bytesSent=Math.max(0,Math.min(totalBytes,bytesSent||inferredBytes))}else bytesSent=Math.max(0,bytesSent);return{bytesSent,percent,totalBytes}}function attachmentReceipt(row,uploaded){return{...uploaded,attachmentId:String(uploaded?.attachmentId||``),clientId:row.clientId,fileName:String(uploaded?.fileName||row.fileName),sessionId:row.sessionId,size:Number(uploaded?.size??row.size)||0}}function createWaiter(row){let resolve=null;row.waiter={promise:new Promise(currentResolve=>{resolve=currentResolve}),resolve,settled:false};return row.waiter}function settleWaiter(row,value=null,waiter=row.waiter){if(!waiter||waiter.settled)return;waiter.settled=true;waiter.resolve(value)}function updateRowProgress(row,progress,total){if(!row.retained||row.phase!==`uploading`)return;const next=attachmentProgress(progress,total,row.totalBytes);row.bytesSent=Math.max(row.bytesSent,next.bytesSent);row.totalBytes=next.totalBytes||row.totalBytes;if(next.percent!==null)row.progress=Math.max(Number(row.progress)||0,next.percent)}function buildQueueRow({currentSessionId,file=null,fileName=`attachment`,phase=`queued`,producer=null,size=0}={}){const normalizedSize=Number(file?.size??size)||0;return reactive({activeHandoffToken:null,activeToken:null,attachmentId:``,bytesSent:0,clientId:nextAttachmentClientId(),error:``,failureStage:``,file,fileName:file?attachmentFileName(file):String(fileName||`attachment`),path:``,phase,producer,producerAbortController:null,producerToken:null,progress:null,receipt:null,retained:true,sessionId:currentSessionId,size:normalizedSize,totalBytes:normalizedSize,waiter:null})}function createReceiptCleanup({deleteAttachment,deletesUnsentUploads,reportAttachmentError}){const cleanupTasks=new Set;const receiptCleanupById=new Map;const cleanedReceiptIds=new Set;function trackCleanup(task){const cleanup=Promise.resolve(task).catch(error=>{reportAttachmentError(error,t$1(`jskit.assistant.attachments.error.cleanupFailed`));return false});cleanupTasks.add(cleanup);cleanup.finally(()=>cleanupTasks.delete(cleanup));return cleanup}async function deleteUploadedAttachment(currentSessionId,attachment){const attachmentId=String(attachment?.attachmentId||``).trim();if(!attachmentId||!deletesUnsentUploads)return false;const response=await deleteAttachment(currentSessionId,attachmentId);if(response?.ok===false)throw new Error(attachmentUploadError(response)||t$1(`jskit.assistant.attachments.error.cleanupFailed`));return true}function cleanupReceipt(currentSessionId,receipt){const attachmentId=String(receipt?.attachmentId||``).trim();const cleanupId=`${currentSessionId}:${attachmentId}`;if(!attachmentId)return Promise.resolve(false);if(cleanedReceiptIds.has(cleanupId))return Promise.resolve(false);if(receiptCleanupById.has(cleanupId))return receiptCleanupById.get(cleanupId);const cleanup=trackCleanup(deleteUploadedAttachment(currentSessionId,receipt)).then(deleted=>{if(deleted)cleanedReceiptIds.add(cleanupId);return deleted});receiptCleanupById.set(cleanupId,cleanup);cleanup.finally(()=>receiptCleanupById.delete(cleanupId));return cleanup}async function waitForAttachmentCleanup(){while(cleanupTasks.size>0)await Promise.allSettled([...cleanupTasks])}return Object.freeze({cleanupReceipt,waitForAttachmentCleanup})}var{serverMessage,t}=useJskitText();function attachmentErrorText(error,fallback){return String(error&&typeof error===`object`&&serverMessage(error)||error?.message||error||fallback)}function assistantAttachmentSessionId(sessionId){return String(toValue(sessionId)||``).trim()}function assistantAttachmentUploadAllowed(canUpload){return toValue(canUpload)!==false}var ASSISTANT_ATTACHMENT_MAX_BYTES=1e8;var ASSISTANT_ATTACHMENT_UPLOAD_CONCURRENCY=2;var ASSISTANT_ATTACHMENT_UNRESOLVED_PHASES=new Set([`preparing`,`queued`,`uploading`,`delivering`,`failed`]);function keepAttachmentErrorInStatus(){}async function keepUploadedAttachmentsReady(){return null}function useAssistantAttachments({canUpload=()=>true,deleteAttachment,onError=keepAttachmentErrorInStatus,onUploaded=keepUploadedAttachmentsReady,sessionId,uploadAttachment,maxBytes=ASSISTANT_ATTACHMENT_MAX_BYTES,maxItems=10,uploadConcurrency=2}){if(![maxBytes,maxItems,uploadConcurrency].every(value=>Number.isSafeInteger(value)&&value>0))throw new TypeError(`Attachment limits must be positive integers.`);const attachments=ref([]);const queueItems=ref([]);const status=ref(``);const activeUploadCount=ref(0);const uploadQueue=[];const rowsById=new Map;const activeAttempts=new Map;let disposed=false;const uploading=computed(()=>activeUploadCount.value>0||queueItems.value.some(item=>[`preparing`,`uploading`,`delivering`].includes(item.phase)));const hasUnresolved=computed(()=>queueItems.value.some(item=>ASSISTANT_ATTACHMENT_UNRESOLVED_PHASES.has(item.phase)));const canSubmit=computed(()=>!hasUnresolved.value);const retainedItemCount=computed(()=>queueItems.value.filter(item=>item.phase!==`cancelled`).length);const atCapacity=computed(()=>retainedItemCount.value>=maxItems);const canAddFiles=computed(()=>Boolean(!disposed&&assistantAttachmentSessionId(sessionId)&&assistantAttachmentUploadAllowed(canUpload)&&!atCapacity.value));const aggregateProgress=computed(()=>{const retainedItems=queueItems.value.filter(item=>item.phase!==`cancelled`);const totalBytes=retainedItems.reduce((sum,item)=>sum+item.totalBytes,0);const bytesSent=retainedItems.reduce((sum,item)=>sum+item.bytesSent,0);return{bytesSent,percent:totalBytes>0?Math.round(bytesSent/totalBytes*100):0,totalBytes}});const tooLarge=row=>t(`jskit.assistant.attachments.error.tooLarge`,{fileName:row.fileName,limit:attachmentLimitText(maxBytes)});const tooMany=()=>t(`jskit.assistant.attachments.error.tooMany`,{count:maxItems});function reportAttachmentError(error,fallbackMessage=t(`jskit.assistant.attachments.error.uploadFailed`),{notify=true}={}){const message=attachmentErrorText(error,fallbackMessage);status.value=message;if(notify)try{onError(error||new Error(message),fallbackMessage)}catch{}return message}function clearStatus(){status.value=``}function failRow(row,failureStage,error,fallbackMessage){row.error=attachmentErrorText(error,fallbackMessage);row.failureStage=failureStage;row.phase=`failed`;reportAttachmentError(error,fallbackMessage,{notify:false})}function canonicalRow(attachment={}){const identity=attachmentIdentity(attachment);return identity?rowsById.get(identity)||queueItems.value.find(row=>attachmentIdentity(row)===identity||row.attachmentId===identity):null}const{cleanupReceipt,waitForAttachmentCleanup}=createReceiptCleanup({deleteAttachment,deletesUnsentUploads:typeof deleteAttachment===`function`,reportAttachmentError});const{dragActive,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,resetDragState}=useAttachmentDropTarget({uploadFiles,reportAttachmentError});function removeReadyReceipt(row){const removed=attachments.value.filter(attachment=>attachment.clientId===row.clientId);attachments.value=attachments.value.filter(attachment=>attachment.clientId!==row.clientId);return removed}async function handOffUploadedAttachment(row,receipt,waiter=row.waiter){const token=Symbol(`${row.clientId}-handoff`);row.activeHandoffToken=token;row.phase=`delivering`;if(!attachments.value.some(attachment=>attachment.clientId===row.clientId))attachments.value.push(receipt);try{const accepted=(await onUploaded([receipt]))?.accepted===true;if(row.activeHandoffToken!==token||!row.retained||row.phase===`cancelled`){removeReadyReceipt(row);if(!accepted)await cleanupReceipt(row.sessionId,receipt);settleWaiter(row,null,waiter);return null}row.activeHandoffToken=null;row.error=``;row.failureStage=``;if(accepted){removeReadyReceipt(row);row.retained=false;rowsById.delete(row.clientId);queueItems.value=queueItems.value.filter(candidate=>candidate.clientId!==row.clientId);settleWaiter(row,receipt,waiter);return receipt}row.phase=`ready`;settleWaiter(row,receipt,waiter);return receipt}catch(error){if(row.activeHandoffToken!==token||!row.retained||row.phase===`cancelled`){await cleanupReceipt(row.sessionId,receipt);settleWaiter(row,null,waiter);return null}row.activeHandoffToken=null;removeReadyReceipt(row);failRow(row,`handoff`,error,t(`jskit.assistant.attachments.error.unusable`));settleWaiter(row,null,waiter);return null}}async function finishUploadAttempt(attempt,uploaded,uploadError=null){activeAttempts.delete(attempt.token);activeUploadCount.value=activeAttempts.size;pumpQueue();const{row}=attempt;const isCurrentAttempt=row.activeToken===attempt.token;const uploadSucceeded=Boolean(!uploadError&&uploaded&&uploaded.ok!==false&&String(uploaded.attachmentId||``).trim());if(!isCurrentAttempt||!row.retained||disposed){if(uploadSucceeded)await cleanupReceipt(attempt.sessionId,uploaded);settleWaiter(row,null,attempt.waiter);pumpQueue();return}row.activeToken=null;if(uploadSucceeded){const receipt=attachmentReceipt(row,uploaded);row.receipt=receipt;row.attachmentId=receipt.attachmentId;row.path=String(receipt.path||``);row.bytesSent=row.totalBytes;row.progress=100;row.error=``;row.failureStage=``;await handOffUploadedAttachment(row,receipt,attempt.waiter)}else{failRow(row,`upload`,uploadError||new Error(attachmentUploadError(uploaded)||t(`jskit.assistant.attachments.error.uploadFailed`)),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null,attempt.waiter)}pumpQueue()}function startUpload(row){const token=Symbol(row.clientId);const abortController=new AbortController;const attempt={abortController,cancel:null,row,sessionId:row.sessionId,settled:null,token,waiter:row.waiter};row.activeToken=token;row.phase=`uploading`;row.error=``;activeAttempts.set(token,attempt);activeUploadCount.value=activeAttempts.size;try{const transport=attachmentUploadResult(uploadAttachment(row.sessionId,row.file,{onProgress:(progress,total)=>updateRowProgress(row,progress,total),signal:abortController.signal}));attempt.cancel=transport.cancel;attempt.settled=transport.promise.then(uploaded=>finishUploadAttempt(attempt,uploaded),error=>finishUploadAttempt(attempt,null,error))}catch(error){attempt.settled=finishUploadAttempt(attempt,null,error)}}function pumpQueue(){if(disposed)return;while(activeAttempts.size<uploadConcurrency&&uploadQueue.length>0){const row=uploadQueue.shift();if(!row?.retained||row.phase!==`queued`)continue;startUpload(row)}}function cancelAttachment(attachment={}){const row=canonicalRow(attachment);if(!row||!row.retained||![`preparing`,`queued`,`uploading`].includes(row.phase))return false;const token=row.activeToken;row.activeToken=null;row.activeHandoffToken=null;row.phase=`cancelled`;row.error=``;const receipt=row.receipt;removeReadyReceipt(row);if(receipt)cleanupReceipt(row.sessionId,receipt);row.receipt=null;row.failureStage=``;settleWaiter(row,null);const attempt=token?activeAttempts.get(token):null;try{row.producerAbortController?.abort();attempt?.abortController.abort();attempt?.cancel?.()}catch{}row.producerAbortController=null;row.producerToken=null;pumpQueue();return true}function retryAttachment(attachment={}){const row=canonicalRow(attachment);if(!row||!row.retained||![`failed`,`cancelled`].includes(row.phase)||row.sessionId!==assistantAttachmentSessionId(sessionId)||!assistantAttachmentUploadAllowed(canUpload))return Promise.resolve(null);if(row.phase===`cancelled`&&retainedItemCount.value>=maxItems){reportAttachmentError(tooMany());return Promise.resolve(null)}if(row.failureStage===`handoff`&&row.receipt){row.error=``;row.phase=`uploading`;const waiter=createWaiter(row);handOffUploadedAttachment(row,row.receipt,waiter);return waiter.promise}if(row.producer&&!row.file){const waiter=createWaiter(row);startAttachmentProducer(row);return waiter.promise}if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));return Promise.resolve(null)}row.bytesSent=0;row.progress=null;row.error=``;row.failureStage=``;row.phase=`queued`;const waiter=createWaiter(row);uploadQueue.push(row);pumpQueue();return waiter.promise}function detachRow(row){if([`preparing`,`queued`,`uploading`].includes(row.phase))cancelAttachment(row);row.retained=false;rowsById.delete(row.clientId);settleWaiter(row,null)}function removeAttachment(attachment={}){const row=canonicalRow(attachment);if(!row)return[];const removedReceipts=removeReadyReceipt(row);const removed=removedReceipts.length>0?removedReceipts:[row];const receiptToClean=removedReceipts[0]||row.receipt;detachRow(row);queueItems.value=queueItems.value.filter(candidate=>candidate.clientId!==row.clientId);if(receiptToClean)cleanupReceipt(row.sessionId,receiptToClean);return removed}function clearAttachments({accepted=true,attachmentIds=null}={}){if(!accepted)return abandonAttachments();const selectedIds=Array.isArray(attachmentIds)?new Set(attachmentIds):null;const cleared=attachments.value.filter(attachment=>!selectedIds||selectedIds.has(attachment.attachmentId));const readyIds=new Set(cleared.map(attachment=>attachment.clientId));const remaining=[];for(const row of[...queueItems.value]){if(selectedIds&&!readyIds.has(row.clientId)){remaining.push(row);continue}if(readyIds.has(row.clientId)){row.retained=false;rowsById.delete(row.clientId);continue}detachRow(row);if(row.receipt)cleanupReceipt(row.sessionId,row.receipt)}attachments.value=attachments.value.filter(attachment=>!readyIds.has(attachment.clientId));queueItems.value=remaining;return cleared}async function abandonAttachments({onlySessionId=``}={}){const normalizedSessionId=String(onlySessionId||``).trim();const rows=queueItems.value.filter(row=>!normalizedSessionId||row.sessionId===normalizedSessionId);const rowIds=new Set(rows.map(row=>row.clientId));const readyReceipts=rows.map(row=>row.receipt).filter(Boolean);const attempts=[...activeAttempts.values()].filter(attempt=>rowIds.has(attempt.row.clientId));for(const row of rows)detachRow(row);queueItems.value=queueItems.value.filter(row=>!rowIds.has(row.clientId));attachments.value=attachments.value.filter(attachment=>!rowIds.has(attachment.clientId));const readyCleanup=readyReceipts.map(attachment=>cleanupReceipt(attachment.sessionId,attachment));await Promise.allSettled([...readyCleanup,...attempts.map(attempt=>attempt.settled).filter(Boolean)]);await waitForAttachmentCleanup();return rows}async function disposeAttachments(){if(disposed){await waitForAttachmentCleanup();return[]}disposed=true;stopSessionWatch();return abandonAttachments()}function createQueueRow(options){const row=buildQueueRow(options);rowsById.set(row.clientId,row);queueItems.value.push(row);createWaiter(row);return row}function queuePreparedFile(row,file,waiter=row.waiter){const preparedFile=assistantAttachmentFiles([file])[0];if(!preparedFile)throw Object.assign(new Error(`The prepared attachment did not produce a file.`),{messageCode:`assistant.attachments.error.noFile`,messageParams:{}});row.file=preparedFile;row.fileName=attachmentFileName(preparedFile);row.size=Number(preparedFile.size)||0;row.totalBytes=row.size;if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null,waiter);return false}row.phase=`queued`;uploadQueue.push(row);pumpQueue();return true}function startAttachmentProducer(row){const token=Symbol(`${row.clientId}-producer`);const waiter=row.waiter;const abortController=new AbortController;row.file=null;row.producerAbortController=abortController;row.producerToken=token;row.phase=`preparing`;row.error=``;row.failureStage=``;row.producerSettled=Promise.resolve().then(()=>row.producer({signal:abortController.signal})).then(file=>{if(row.producerToken!==token||!row.retained||disposed){settleWaiter(row,null,waiter);return null}row.producerAbortController=null;row.producerToken=null;try{queuePreparedFile(row,file,waiter)}catch(error){failRow(row,`preparing`,error,t(`jskit.assistant.attachments.error.preparationFailed`));settleWaiter(row,null,waiter)}return file},error=>{if(row.producerToken!==token||!row.retained||disposed){settleWaiter(row,null,waiter);return null}row.producerAbortController=null;row.producerToken=null;if(error?.name===`AbortError`){row.phase=`cancelled`;row.error=``}else failRow(row,`preparing`,error,t(`jskit.assistant.attachments.error.preparationFailed`));settleWaiter(row,null,waiter);return null})}function uploadFileProducer({fileName=t(`jskit.assistant.attachments.preparingName`),produce}={}){const currentSessionId=assistantAttachmentSessionId(sessionId);if(!canAddFiles.value||typeof produce!==`function`){if(atCapacity.value)reportAttachmentError(tooMany());return Promise.resolve(null)}status.value=``;const row=createQueueRow({currentSessionId,fileName,phase:`preparing`,producer:produce});const waiter=row.waiter;startAttachmentProducer(row);return waiter.promise}async function uploadFiles(files=[]){const uploadableFiles=assistantAttachmentFiles(files);const currentSessionId=assistantAttachmentSessionId(sessionId);if(uploadableFiles.length<1||!currentSessionId||disposed||!assistantAttachmentUploadAllowed(canUpload))return[];status.value=``;const availableSlots=Math.max(0,maxItems-retainedItemCount.value);const acceptedFiles=uploadableFiles.slice(0,availableSlots);if(acceptedFiles.length<uploadableFiles.length)reportAttachmentError(tooMany());const waiters=[];for(const file of acceptedFiles){const row=createQueueRow({currentSessionId,file});const waiter=row.waiter;waiters.push(waiter.promise);if(row.size>maxBytes){failRow(row,`validation`,tooLarge(row),t(`jskit.assistant.attachments.error.uploadFailed`));settleWaiter(row,null)}else uploadQueue.push(row)}pumpQueue();return(await Promise.all(waiters)).filter(attachment=>attachment&&attachments.value.some(candidate=>candidate.clientId===attachment.clientId))}const stopSessionWatch=watch(()=>assistantAttachmentSessionId(sessionId),(nextSessionId,previousSessionId)=>{if(nextSessionId!==previousSessionId&&previousSessionId)abandonAttachments({onlySessionId:previousSessionId})},{flush:`sync`});if(getCurrentScope())onScopeDispose(()=>{disposeAttachments()});return{maxBytes,maxItems,abandonAttachments,aggregateProgress,attachments,atCapacity,canAddFiles,cancelAttachment,canSubmit,clearAttachments,clearStatus,disposeAttachments,dragActive,hasUnresolved,handleDragEnter,handleDragLeave,handleDragOver,handleDrop,handlePaste,queueItems,removeAttachment,resetDragState,retryAttachment,status,uploading,uploadFiles,uploadFileProducer,waitForAttachmentCleanup}}export{en_default as a,attachmentSizeText as i,assistantAttachmentFilesFromDropEvent as n,assistantAttachmentFilesFromPasteEvent as r,useAssistantAttachments as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Et as unref,gt as reactive,ht as proxyRefs,it as watch,u as computed}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as useShellWebErrorRuntime}from"./error-BQ7r64JO.js";import{N as useQueryClient,a as ensureAccessModeCompatibility,c as normalizePermissions,d as resolveEnabled,f as resolvePermissionAccess,i as emptyRecord,l as resolveAccessModeEnabled,m as resolveEnabledRef,n as useOperationRealtime,o as normalizeAccessMode,p as resolveQueryKey,r as asPlainObject,s as normalizeOwnershipFilter,t as useEndpointResource,u as resolveApiSuffix}from"./useEndpointResource-DZTjr9gg.js";import{o as normalizeLowerText,u as normalizeText}from"./normalize-BD25VwNK.js";import{n as validateSchemaPayload}from"./validators-HqYRjxEO.js";import{c as normalizePermissionList,n as getHttpWebClient,r as buildValidationFailure,s as hasPermission}from"./httpClient-Bwitq9Xf.js";import{n as resolveScopedRouteBase}from"./surface-CBlx7sF_.js";import{r as useJskitText}from"./i18n-BuXRXGaO.js";import{n as ROUTE_VISIBILITY_WORKSPACE}from"./visibility-Cq31Xy7I.js";import"./i18n-DQPYjuW7.js";import{r as toUiFieldErrors}from"./errorMessageHelpers-B49LyMJi.js";import{m as useWebPlacementContext,r as resolveSurfaceDefinitionFromPlacementContext}from"./placement-1lT0lW3-.js";import{n as useSurfaceRouteContext,t as usePaths}from"./usePaths-CvUbx5-V.js";import{t as useUiFeedback}from"./useUiFeedback-BU4NyMq8.js";var{t:t$4,text:text$1}=useJskitText();var SILENT_FIELD_BAG=Object.freeze({apply(){}});var SILENT_FEEDBACK=Object.freeze({error(){}});function validateOperationInput({input,rawPayload={},fieldBag=SILENT_FIELD_BAG,feedback=SILENT_FEEDBACK,validationMessage=``}){if(!input)return{ok:true,parsedInput:rawPayload};try{return{ok:true,parsedInput:validateSchemaPayload(input,rawPayload,{phase:`input`,context:`operation input`})}}catch(error){if(!error?.fieldErrors||typeof error.fieldErrors!==`object`)throw error;const fieldErrorCodes=error.fieldErrorCodes||error.details?.fieldErrorCodes;const failure={...buildValidationFailure({error:text$1(validationMessage)||t$4(`jskit.http.feedback.validationFailed`),code:`validation_failed`,fieldErrors:error?.fieldErrors}),...fieldErrorCodes?{fieldErrorCodes}:{}};fieldBag.apply(toUiFieldErrors(failure));feedback.error(failure,failure.error);return{ok:false,failure,parsedInput:null}}}var{t:t$3,text}=useJskitText();function useCommandCore({model,resource,writeMethod=`POST`,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions=emptyRecord,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={}}){const queryClient=useQueryClient();const sendsParsedInput=String(writeMethod||`POST`).trim().toUpperCase()!==`DELETE`||Boolean(input)||buildRawPayload!==void 0;const readRawPayload=buildRawPayload??emptyRecord;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=readRawPayload(model,{queryClient,resource,context});const validationResult=validateOperationInput({input,rawPayload,fieldBag,feedback,validationMessage:text(messages.validation)||t$3(`jskit.http.feedback.validationFailed`)});if(!validationResult.ok)return null;const{parsedInput}=validationResult;const payload=typeof buildCommandPayload===`function`?buildCommandPayload(parsedInput,{rawPayload,queryClient,resource,context}):sendsParsedInput?parsedInput:void 0;const options=buildCommandOptions(parsedInput,{rawPayload,queryClient,resource,context});try{const response=await resource.save(payload,options);if(onRunSuccess)await onRunSuccess(response,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});if(!suppressSuccessMessage)feedback.success(text(messages.success)||t$3(`jskit.http.feedback.completed`));return response}catch(error){fieldBag.apply(toUiFieldErrors(error));if(onRunError)await onRunError(error,{parsed:parsedInput,rawPayload,payload,options,queryClient,resource,context});feedback.error(error,text(messages.error)||t$3(`jskit.http.feedback.actionFailed`));throw error}}return{running,fieldErrors,message,messageType,run}}var{t:t$2}=useJskitText();function asPermissionList(value){if(Array.isArray(value))return value;if(value===void 0||value===null||value===``)return[];return[value]}function useAccess({enabled=true,access=`always`,hasPermissionRequirements=false}={}){const normalizedAccessMode=normalizeAccessMode(access);const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements:hasPermissionRequirements===true});const{context:placementContext}=useWebPlacementContext();const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&accessRequired);const hasPlacementPermissions=computed(()=>{const source=placementContext.value;if(!source||typeof source!==`object`)return false;return Object.hasOwn(source,`permissions`)});const placementPermissions=computed(()=>normalizePermissionList(placementContext.value?.permissions));const permissions=computed(()=>{if(!queryEnabled.value||!hasPlacementPermissions.value)return[];return placementPermissions.value});const permissionsUnavailableError=computed(()=>{if(!queryEnabled.value||hasPlacementPermissions.value)return``;return t$2(`jskit.http.access.permissionsUnavailable`)});const awaitingPlacementPermissions=computed(()=>queryEnabled.value&&!hasPlacementPermissions.value);function can(permission){return hasPermission(permissions.value,permission)}function canAny(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(can(entry))return true;return false}function canAll(requiredPermissions){const list=asPermissionList(requiredPermissions);if(list.length<1)return true;for(const entry of list)if(!can(entry))return false;return true}return{accessMode:normalizedAccessMode,accessRequired,permissions,permissionsUnavailableError,awaitingPlacementPermissions,can,canAny,canAll}}function toRouteParamValue(value){if(Array.isArray(value))return toRouteParamValue(value[0]);if(value==null)return``;return String(value).trim()}function extractRouteParamNames(pathTemplate=``){const normalizedTemplate=String(pathTemplate||``).trim();if(!normalizedTemplate)return[];const names=[];const seen=new Set;const pattern=/:([A-Za-z][A-Za-z0-9_]*)/g;let match=null;while((match=pattern.exec(normalizedTemplate))!=null){const name=String(match[1]||``).trim();if(!name||seen.has(name))continue;seen.add(name);names.push(name)}return names}var{t:t$1}=useJskitText();function resolveScopedRouteParamNames(placementContext=null,surfaceId=``){const routeBase=resolveSurfaceDefinitionFromPlacementContext(placementContext,surfaceId)?.routeBase||`/`;return extractRouteParamNames(resolveScopedRouteBase(routeBase))}function useScopeRuntime({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,accessMode=`auto`,hasPermissionRequirements=false}={}){const normalizedOwnershipFilter=normalizeOwnershipFilter(ownershipFilter);const normalizedAccessMode=ensureAccessModeCompatibility({accessMode,hasPermissionRequirements,caller:`useScopeRuntime`});const accessRequired=resolveAccessModeEnabled(normalizedAccessMode,{hasPermissionRequirements});const routeContext=useSurfaceRouteContext();const paths=usePaths({routeContext});const resolvedSurfaceId=computed(()=>{const explicitSurfaceId=normalizeLowerText(surfaceId);if(explicitSurfaceId)return explicitSurfaceId;return normalizeLowerText(routeContext.currentSurfaceId.value)});const scopedRouteParamNames=computed(()=>resolveScopedRouteParamNames(routeContext.placementContext.value,resolvedSurfaceId.value));const routeScopeParams=computed(()=>{const source=paths.routeParams.value;const next={};for(const paramName of scopedRouteParamNames.value){const paramValue=toRouteParamValue(source[paramName]);if(paramValue)next[paramName]=paramValue}return Object.freeze(next)});const missingScopedRouteParamNames=computed(()=>scopedRouteParamNames.value.filter(paramName=>!routeScopeParams.value[paramName]));const requiresScopedRouteParams=computed(()=>scopedRouteParamNames.value.length>0);const hasRequiredRouteScope=computed(()=>missingScopedRouteParamNames.value.length<1);const scopeParamValue=computed(()=>{const[primaryScopeParamName=``]=scopedRouteParamNames.value;return primaryScopeParamName?routeScopeParams.value[primaryScopeParamName]||``:``});const routeScopeError=computed(()=>{if(!requiresScopedRouteParams.value||hasRequiredRouteScope.value)return``;const missingParams=missingScopedRouteParamNames.value.join(`, `);return t$1(`jskit.http.access.routeParamsRequired`,{params:missingParams,surface:resolvedSurfaceId.value||`<unknown>`})});const accessRuntime=useAccess({enabled:computed(()=>accessRequired&&hasRequiredRouteScope.value),access:normalizedAccessMode,hasPermissionRequirements});function resolveApiPath(apiSuffix=``,context={}){if(routeScopeError.value)return``;const suffix=resolveApiSuffix(apiSuffix,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,...asPlainObject(context)});return paths.api(suffix,{surface:resolvedSurfaceId.value,params:routeScopeParams.value})}function requireRouteScope(caller=`useScopeRuntime`){if(routeScopeError.value)throw new Error(`${caller}: ${routeScopeError.value}`)}return{normalizedOwnershipFilter,requiresScopedRouteParams:requiresScopedRouteParams.value,resolvedSurfaceId,accessMode:normalizedAccessMode,accessRequired,routeContext,scopedRouteParamNames,routeScopeParams,scopeParamValue,hasRequiredRouteScope,routeScopeError,access:accessRuntime,resolveApiPath,requireRouteScope}}function normalizePermissionSets(permissionSets={}){const source=permissionSets&&typeof permissionSets===`object`&&!Array.isArray(permissionSets)?permissionSets:{};const normalized={};for(const[key,value]of Object.entries(source))normalized[key]=normalizePermissions(value);return normalized}function hasAnyPermissions(permissionSets={}){for(const list of Object.values(permissionSets))if(Array.isArray(list)&&list.length>0)return true;return false}function useOperationScope({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,model,readEnabled=true,queryKeyFactory,permissionSets={},realtime}){const normalizedPermissionSets=normalizePermissionSets(permissionSets);const scopeRuntime=useScopeRuntime({ownershipFilter,surfaceId,accessMode:access,hasPermissionRequirements:hasAnyPermissions(normalizedPermissionSets)});const normalizedOwnershipFilter=scopeRuntime.normalizedOwnershipFilter;const routeContext=scopeRuntime.routeContext;const scopeParamValue=scopeRuntime.scopeParamValue;const hasRequiredRouteScope=scopeRuntime.hasRequiredRouteScope;const accessRuntime=scopeRuntime.access;const apiPath=computed(()=>scopeRuntime.resolveApiPath(apiSuffix,{model}));const queryEnabled=computed(()=>resolveEnabled(readEnabled,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter,model}));const queryKey=computed(()=>resolveQueryKey(queryKeyFactory,{surfaceId:routeContext.currentSurfaceId.value,scopeParamValue:scopeParamValue.value,ownershipFilter:normalizedOwnershipFilter}));const realtimeBinding=useOperationRealtime({realtime,queryKey:typeof queryKeyFactory===`function`?queryKey:null,enabled:computed(()=>hasRequiredRouteScope.value&&Boolean(apiPath.value))});function queryCanRun(accessGate=true){return computed(()=>queryEnabled.value&&hasRequiredRouteScope.value&&Boolean(apiPath.value)&&Boolean(unref(accessGate)))}function permissionGate(key=``){const list=normalizedPermissionSets[String(key||``)]||[];return computed(()=>resolvePermissionAccess(accessRuntime,list))}function loadError(baseError=``){return computed(()=>{if(scopeRuntime.routeScopeError.value)return scopeRuntime.routeScopeError.value;const permissionsError=String(accessRuntime.permissionsUnavailableError.value||``).trim();if(permissionsError)return permissionsError;if(baseError===void 0||baseError===null||baseError===``)return``;return String(unref(baseError)||``).trim()})}function isLoading(baseLoading=false){return computed(()=>Boolean(unref(baseLoading))||accessRuntime.awaitingPlacementPermissions.value)}return{scopeRuntime,routeContext,normalizedOwnershipFilter,scopeParamValue,hasRequiredRouteScope,access:accessRuntime,apiPath,queryEnabled,queryKey,queryCanRun,realtime:realtimeBinding,permissionGate,loadError,isLoading}}function normalizeFieldErrorKeys(keys){return Array.isArray(keys)?keys.map(entry=>String(entry||``).trim()).filter(Boolean):[]}function useFieldErrorBag(keys=[]){const normalizedKeys=normalizeFieldErrorKeys(keys);const hasFixedKeys=normalizedKeys.length>0;const errors=reactive(Object.fromEntries(normalizedKeys.map(key=>[key,``])));function clear(){const keysToClear=hasFixedKeys?normalizedKeys:Object.keys(errors);for(const key of keysToClear)errors[key]=``}function apply(source={}){const fieldErrorMap=source&&typeof source===`object`?source:{};if(hasFixedKeys){for(const key of normalizedKeys)errors[key]=String(fieldErrorMap[key]||``);return}clear();for(const[field,message]of Object.entries(fieldErrorMap)){const key=String(field||``).trim();if(!key)continue;errors[key]=String(message||``)}}function set(field,message){const key=String(field||``).trim();if(!key)return;if(hasFixedKeys&&!(key in errors))return;errors[key]=String(message||``)}return{errors,clear,apply,set}}var{t}=useJskitText();function normalizeMessage(value){return String(value||``).trim()}function noRetryAction(){return null}function setupOperationErrorReporting({enabled=true,source=`http-web.operation`,loadError=null,notFoundError=null,loadActionFactory=noRetryAction,notFoundActionFactory=noRetryAction,loadChannel=``,notFoundChannel=``,loadSeverity=`error`,notFoundSeverity=`warning`,dedupeWindowMs=2e3}={}){if(!enabled)return;const runtime=useShellWebErrorRuntime();const normalizedSource=normalizeMessage(source)||`http-web.operation`;function watchMessage(value,{kind=`load`,channel=``,intent=`resource-load`,severity=`error`,actionFactory=noRetryAction}={}){let lastMessage=``;let lastPresentationId=``;watch(()=>normalizeMessage(value.value),nextMessage=>{if(!nextMessage){lastMessage=``;if(lastPresentationId){runtime.dismiss(lastPresentationId);lastPresentationId=``}return}if(nextMessage===lastMessage)return;lastMessage=nextMessage;const action=actionFactory({message:nextMessage,kind});const reportResult=runtime.report({source:normalizedSource,message:nextMessage,intent,severity,channel,action,dedupeKey:`${normalizedSource}:${kind}:${nextMessage}`,dedupeWindowMs});const nextPresentationId=String(reportResult?.presentationId||``).trim();if(nextPresentationId){if(lastPresentationId&&lastPresentationId!==nextPresentationId)runtime.dismiss(lastPresentationId);lastPresentationId=nextPresentationId}},{immediate:true})}if(loadError)watchMessage(loadError,{kind:`load`,channel:loadChannel,intent:`resource-load`,severity:loadSeverity,actionFactory:loadActionFactory});if(notFoundError)watchMessage(notFoundError,{kind:`not-found`,channel:notFoundChannel,intent:`resource-load`,severity:notFoundSeverity,actionFactory:notFoundActionFactory})}function setupRouteChangeCleanup({enabled=true,route,feedback,onClear}){if(!enabled)return;watch(()=>route?.fullPath,()=>{feedback.clear();onClear()})}var CRUD_API_ACCESS_AUTHENTICATED=`authenticated`;var CRUD_API_ACCESS_PUBLIC=`public`;var CRUD_API_ACCESS_VALUES=Object.freeze([CRUD_API_ACCESS_AUTHENTICATED,CRUD_API_ACCESS_PUBLIC]);var publicCrudClients=new WeakSet;function normalizeCrudApiAccess(value=``){const normalized=normalizeText(value).toLowerCase()||`authenticated`;if(CRUD_API_ACCESS_VALUES.includes(normalized))return normalized;throw new TypeError(`CRUD resource apiAccess must be one of: ${CRUD_API_ACCESS_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveCrudHttpClient(resource=null,{client=getHttpWebClient()}={}){if(normalizeCrudApiAccess(resource?.apiAccess)!==`public`)return client;if(publicCrudClients.has(client))return client;const publicClient=Object.freeze({request(url,options={}){const requestOptions=options&&typeof options===`object`&&!Array.isArray(options)?options:{};return client.request(url,{...requestOptions,csrf:false})}});publicCrudClients.add(publicClient);return publicClient}function useCommand({ownershipFilter=ROUTE_VISIBILITY_WORKSPACE,surfaceId=``,access=`auto`,apiSuffix=``,runPermissions=[],writeMethod=`POST`,client,resource:commandResource=null,transport,placementSource=`http-web.command`,fallbackRunError=`jskit.http.feedback.actionFailed`,fieldErrorKeys,clearOnRouteChange=true,model,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage=false,messages={},realtime}){const operationScope=useOperationScope({ownershipFilter,surfaceId,access,apiSuffix,model,readEnabled:false,permissionSets:{run:runPermissions},realtime});const routeContext=operationScope.routeContext;const canRun=operationScope.permissionGate(`run`);const endpointResource=useEndpointResource({path:operationScope.apiPath,enabled:false,client:resolveCrudHttpClient(commandResource,{client}),writeMethod,transport,fallbackSaveError:fallbackRunError});const feedback=useUiFeedback({source:`${placementSource}.feedback`});const fieldBag=useFieldErrorBag(fieldErrorKeys);const command=useCommandCore({model,resource:endpointResource,writeMethod,canRun,fieldBag,feedback,input,buildRawPayload,buildCommandPayload,buildCommandOptions,onRunSuccess,onRunError,suppressSuccessMessage:Boolean(suppressSuccessMessage),messages:{validation:`jskit.http.feedback.fixInvalidValues`,success:`jskit.http.feedback.completed`,error:String(fallbackRunError||`jskit.http.feedback.actionFailed`),...messages&&typeof messages===`object`?messages:{}}});setupRouteChangeCleanup({enabled:clearOnRouteChange,route:routeContext.route,feedback,onClear:fieldBag.clear});const loadError=operationScope.loadError();const isLoading=operationScope.isLoading();setupOperationErrorReporting({source:`${placementSource}.load`,loadError});return proxyRefs({canRun,isLoading,loadError,isRunning:command.running,fieldErrors:command.fieldErrors,message:command.message,messageType:command.messageType,run:command.run,resource:endpointResource})}export{useCommand as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as hasInjectionContext,Et as unref,N as nextTick,O as inject,Tt as toValue,_t as readonly,bt as shallowReadonly,ft as isRef,gt as reactive,it as watch,mt as onScopeDispose,u as computed,wt as toRefs,yt as shallowReactive}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{u as normalizeText}from"./normalize-BD25VwNK.js";import{n as getHttpWebClient}from"./httpClient-Bwitq9Xf.js";import{n as ROUTE_VISIBILITY_WORKSPACE,r as ROUTE_VISIBILITY_WORKSPACE_USER,t as ROUTE_VISIBILITY_TOKENS}from"./visibility-Cq31Xy7I.js";import{r as useRealtimeEvent}from"./useRealtimeEvent-B4oRg9Dt.js";import{a as mergeQueryMeta,i as hasResolvedQueryData,o as mergeRequestRecoveryQueryMeta,t as toQueryErrorMessage}from"./errorMessageHelpers-B49LyMJi.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&¶m==null)break;result=await fetchPage(result,param);currentPage++}while(currentPage<remainingPages)}return result};if(context.options.persister)context.fetchFn=()=>{return context.options.persister?.(fetchFn,{client:context.client,queryKey:context.queryKey,meta:context.options.meta,signal:context.signal},query)};else context.fetchFn=fetchFn}}}function getNextPageParam(options,{pages,pageParams}){const lastIndex=pages.length-1;return pages.length>0?options.getNextPageParam(pages[lastIndex],pages,pageParams[lastIndex],pageParams):void 0}function getPreviousPageParam(options,{pages,pageParams}){return pages.length>0?options.getPreviousPageParam?.(pages[0],pages,pageParams[0],pageParams):void 0}var Query=class extends Removable{#queryType;#initialState;#revertState;#cache;#client;#retryer;#defaultOptions;#abortSignalConsumed;constructor(config){super();this.#abortSignalConsumed=false;this.#defaultOptions=config.defaultOptions;this.setOptions(config.options);this.observers=[];this.#client=config.client;this.#cache=this.#client.getQueryCache();this.queryKey=config.queryKey;this.queryHash=config.queryHash;this.#initialState=getDefaultState$1(this.options);this.state=config.state??this.#initialState;this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#queryType}get promise(){return this.#retryer?.promise}setOptions(options){this.options={...this.#defaultOptions,...options};if(options?._type)this.#queryType=options._type;this.updateGcTime(this.options.gcTime);if(this.state&&this.state.data===void 0){const defaultState=getDefaultState$1(this.options);if(defaultState.data!==void 0){this.setState(successState(defaultState.data,defaultState.dataUpdatedAt));this.#initialState=defaultState}}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus===`idle`)this.#cache.remove(this)}setData(newData,options){const data=replaceData(this.state.data,newData,this.options);this.#dispatch({data,type:`success`,dataUpdatedAt:options?.updatedAt,manual:options?.manual});return data}setState(state){this.#dispatch({type:`setState`,state})}cancel(options){const promise=this.#retryer?.promise;this.#retryer?.cancel(options);return promise?promise.then(noop).catch(noop):Promise.resolve()}destroy(){super.destroy();this.cancel({silent:true})}get resetState(){return this.#initialState}reset(){this.destroy();this.setState(this.resetState)}isActive(){return this.observers.some(observer=>resolveQueryValue(observer.options.enabled,this)!==false)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===skipToken||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){if(this.getObserversCount()>0)return this.observers.some(observer=>resolveQueryValue(observer.options.staleTime,this)===`static`);return false}isStale(){if(this.getObserversCount()>0)return this.observers.some(observer=>observer.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(staleTime=0){if(this.state.data===void 0)return true;if(staleTime===`static`)return false;if(this.state.isInvalidated)return true;return!timeUntilStale(this.state.dataUpdatedAt,staleTime)}onFocus(){this.observers.find(x=>x.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:false});this.#retryer?.continue()}onOnline(){this.observers.find(x=>x.shouldFetchOnReconnect())?.refetch({cancelRefetch:false});this.#retryer?.continue()}addObserver(observer){if(!this.observers.includes(observer)){this.observers.push(observer);this.clearGcTimeout();this.#cache.notify({type:`observerAdded`,query:this,observer})}}removeObserver(observer){const index=this.observers.indexOf(observer);if(index!==-1){this.observers.splice(index,1);if(!this.observers.length){if(this.#retryer){if(this.#abortSignalConsumed||this.state.fetchStatus===`paused`&&this.state.status===`pending`)this.#retryer.cancel({revert:true});else this.#retryer.cancelRetry()}this.scheduleGc()}this.#cache.notify({type:`observerRemoved`,query:this,observer})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#dispatch({type:`invalidate`})}async fetch(options,fetchOptions){if(this.state.fetchStatus!==`idle`&&this.#retryer?.status()!==`rejected`){if(this.state.data!==void 0&&fetchOptions?.cancelRefetch)this.cancel({silent:true});else if(this.#retryer){this.#retryer.continueRetry();return this.#retryer.promise}}if(options)this.setOptions(options);if(!this.options.queryFn){const observer=this.observers.find(x=>x.options.queryFn);if(observer)this.setOptions(observer.options)}const abortController=new AbortController;const addSignalProperty=object=>{Object.defineProperty(object,"signal",{enumerable:true,get:()=>{this.#abortSignalConsumed=true;return abortController.signal}})};const fetchFn=()=>{const queryFn=ensureQueryFn(this.options,fetchOptions);const createQueryFnContext=()=>{const queryFnContext={client:this.#client,queryKey:this.queryKey,meta:this.meta};addSignalProperty(queryFnContext);return queryFnContext};const queryFnContext=createQueryFnContext();this.#abortSignalConsumed=false;if(this.options.persister)return this.options.persister(queryFn,queryFnContext,this);return queryFn(queryFnContext)};const createFetchContext=()=>{const context={fetchOptions,options:this.options,queryKey:this.queryKey,client:this.#client,state:this.state,fetchFn};addSignalProperty(context);return context};const context=createFetchContext();(this.#queryType===`infinite`?infiniteQueryBehavior(this.options.pages):this.options.behavior)?.onFetch(context,this);this.#revertState=this.state;if(this.state.fetchStatus===`idle`||this.state.fetchMeta!==context.fetchOptions?.meta)this.#dispatch({type:`fetch`,meta:context.fetchOptions?.meta});const retryer=this.#retryer=createRetryer({initialPromise:fetchOptions?.initialPromise,fn:context.fetchFn,onCancel:error=>{if(error instanceof CancelledError&&error.revert)this.setState({...this.#revertState,fetchStatus:`idle`});abortController.abort()},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue:()=>{this.#dispatch({type:`continue`})},retry:context.options.retry,retryDelay:context.options.retryDelay,networkMode:context.options.networkMode,canRun:()=>true});try{const data=await retryer.start();if(data===void 0)throw new Error(`${this.queryHash} data is undefined`);this.setData(data);this.#cache.config.onSuccess?.(data,this);this.#cache.config.onSettled?.(data,this.state.error,this);return data}catch(error){if(error instanceof CancelledError){if(error.silent)return this.#retryer.promise;else if(error.revert){if(this.state.data===void 0)throw error;return this.state.data}}this.#dispatch({type:`error`,error});this.#cache.config.onError?.(error,this);this.#cache.config.onSettled?.(this.state.data,error,this);throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.scheduleGc()}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,fetchFailureCount:action.failureCount,fetchFailureReason:action.error};case`pause`:return{...state,fetchStatus:`paused`};case`continue`:return{...state,fetchStatus:`fetching`};case`fetch`:return{...state,...fetchState(state.data,this.options),fetchMeta:action.meta??null};case`success`:const newState={...state,...successState(action.data,action.dataUpdatedAt),dataUpdateCount:state.dataUpdateCount+1,...!action.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};this.#revertState=action.manual?newState:void 0;return newState;case`error`:const error=action.error;return{...state,error,errorUpdateCount:state.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:state.fetchFailureCount+1,fetchFailureReason:error,fetchStatus:`idle`,status:`error`,isInvalidated:true};case`invalidate`:return{...state,isInvalidated:true};case`setState`:return{...state,...action.state}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.observers.slice().forEach(observer=>{observer.onQueryUpdate()});this.#cache.notify({query:this,type:`updated`,action})})}};function fetchState(data,options){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:canFetch(options.networkMode)?`fetching`:`paused`,...data===void 0&&{error:null,status:`pending`}}}function successState(data,dataUpdatedAt){return{data,dataUpdatedAt:dataUpdatedAt??Date.now(),error:null,isInvalidated:false,status:`success`}}function getDefaultState$1(options){const data=typeof options.initialData===`function`?options.initialData():options.initialData;const hasData=data!==void 0;const initialDataUpdatedAt=hasData?typeof options.initialDataUpdatedAt===`function`?options.initialDataUpdatedAt():options.initialDataUpdatedAt:0;return{data,dataUpdateCount:0,dataUpdatedAt:hasData?initialDataUpdatedAt??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:false,status:hasData?`success`:`pending`,fetchStatus:`idle`}}var QueryObserver=class extends Subscribable{#client;#currentQuery=void 0;#currentQueryInitialState=void 0;#currentResult=void 0;#currentResultState;#currentResultOptions;#selectError;#selectFn;#selectResult;#lastQueryWithDefinedData;#staleTimeoutId;#refetchIntervalId;#currentRefetchInterval;#trackedProps=new Set;constructor(client,options){super();this.options=options;this.#client=client;this.#selectError=null;this.bindMethods();this.setOptions(options)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){if(this.listeners.size===1){this.#currentQuery.addObserver(this);if(shouldFetchOnMount(this.#currentQuery,this.options))this.#executeFetch();else this.updateResult();this.#updateTimers()}}onUnsubscribe(){if(!this.hasListeners())this.destroy()}shouldFetchOnReconnect(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return shouldFetchOn(this.#currentQuery,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set;this.#clearStaleTimeout();this.#clearRefetchInterval();this.#currentQuery.removeObserver(this)}setOptions(options){const prevOptions=this.options;const prevQuery=this.#currentQuery;this.options=this.#client.defaultQueryOptions(options);if(this.options.enabled!==void 0&&typeof this.options.enabled!==`boolean`&&typeof this.options.enabled!==`function`&&typeof resolveQueryValue(this.options.enabled,this.#currentQuery)!==`boolean`)throw new Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#updateQuery();this.#currentQuery.setOptions(this.options);if(prevOptions._defaulted&&!shallowEqualObjects(this.options,prevOptions))this.#client.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#currentQuery,observer:this});const mounted=this.hasListeners();if(mounted&&shouldFetchOptionally(this.#currentQuery,prevQuery,this.options,prevOptions))this.#executeFetch();this.updateResult();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||resolveQueryValue(this.options.staleTime,this.#currentQuery)!==resolveQueryValue(prevOptions.staleTime,this.#currentQuery)))this.#updateStaleTimeout();const nextRefetchInterval=this.#computeRefetchInterval();if(mounted&&(this.#currentQuery!==prevQuery||resolveQueryValue(this.options.enabled,this.#currentQuery)!==resolveQueryValue(prevOptions.enabled,this.#currentQuery)||nextRefetchInterval!==this.#currentRefetchInterval))this.#updateRefetchInterval(nextRefetchInterval)}getOptimisticResult(options){const query=this.#client.getQueryCache().build(this.#client,options);const result=this.createResult(query,options);if(!shallowEqualObjects(this.getCurrentResult(),result)){this.#currentResult=result;this.#currentResultOptions=this.options;this.#currentResultState=this.#currentQuery.state}return result}getCurrentResult(){return this.#currentResult}trackResult(result,onPropTracked){return new Proxy(result,{get:(target,key)=>{this.trackProp(key);onPropTracked?.(key);return Reflect.get(target,key)}})}trackProp(key){this.#trackedProps.add(key)}getCurrentQuery(){return this.#currentQuery}refetch({...options}={}){return this.fetch({...options})}fetchOptimistic(options){const defaultedOptions=this.#client.defaultQueryOptions(options);const query=this.#client.getQueryCache().build(this.#client,defaultedOptions);let unsubscribe=()=>{};let resolveEarly;const cachePromise=new Promise(resolve=>{resolveEarly=resolve;unsubscribe=this.#client.getQueryCache().subscribe(event=>{if(event.type===`updated`&&event.query.queryHash===query.queryHash&&query.state.data!==void 0){unsubscribe();resolve(this.createResult(query,defaultedOptions))}})});return Promise.race([query.fetch().then(()=>{const result=this.createResult(query,defaultedOptions);resolveEarly?.(result);return result}).finally(()=>{unsubscribe()}),cachePromise])}fetch(fetchOptions){return this.#executeFetch({...fetchOptions,cancelRefetch:fetchOptions.cancelRefetch??true}).then(()=>{this.updateResult();return this.#currentResult})}#executeFetch(fetchOptions){this.#updateQuery();let promise=this.#currentQuery.fetch(this.options,fetchOptions);if(!fetchOptions?.throwOnError)promise=promise.catch(noop);return promise}#shouldScheduleTimer(timeout){return!isServer()&&resolveQueryValue(this.options.enabled,this.#currentQuery)!==false&&isValidTimeout(timeout)}#updateStaleTimeout(){this.#clearStaleTimeout();const staleTime=resolveQueryValue(this.options.staleTime,this.#currentQuery);if(this.#currentResult.isStale||!this.#shouldScheduleTimer(staleTime))return;const timeout=timeUntilStale(this.#currentResult.dataUpdatedAt,staleTime)+1;this.#staleTimeoutId=timeoutManager.setTimeout(()=>{if(!this.#currentResult.isStale)this.updateResult()},timeout)}#computeRefetchInterval(){return resolveQueryValue(this.options.refetchInterval,this.#currentQuery)??false}#updateRefetchInterval(nextInterval){this.#clearRefetchInterval();this.#currentRefetchInterval=nextInterval;if(this.#currentRefetchInterval===0||!this.#shouldScheduleTimer(this.#currentRefetchInterval))return;this.#refetchIntervalId=timeoutManager.setInterval(()=>{if(this.options.refetchIntervalInBackground||focusManager.isFocused())this.#executeFetch()},this.#currentRefetchInterval)}#updateTimers(){this.#updateStaleTimeout();this.#updateRefetchInterval(this.#computeRefetchInterval())}#clearStaleTimeout(){if(this.#staleTimeoutId!==void 0){timeoutManager.clearTimeout(this.#staleTimeoutId);this.#staleTimeoutId=void 0}}#clearRefetchInterval(){if(this.#refetchIntervalId!==void 0){timeoutManager.clearInterval(this.#refetchIntervalId);this.#refetchIntervalId=void 0}}createResult(query,options){const prevQuery=this.#currentQuery;const prevOptions=this.options;const prevResult=this.#currentResult;const prevResultState=this.#currentResultState;const prevResultOptions=this.#currentResultOptions;const queryInitialState=query!==prevQuery?query.state:this.#currentQueryInitialState;const{state}=query;let newState={...state};let isPlaceholderData=false;let data;if(options._optimisticResults){const mounted=this.hasListeners();const fetchOnMount=!mounted&&shouldFetchOnMount(query,options);const fetchOptionally=mounted&&shouldFetchOptionally(query,prevQuery,options,prevOptions);if(fetchOnMount||fetchOptionally)newState={...newState,...fetchState(state.data,query.options)};if(options._optimisticResults===`isRestoring`)newState.fetchStatus=`idle`}let{error,errorUpdatedAt,status}=newState;data=newState.data;let skipSelect=false;if(options.placeholderData!==void 0&&data===void 0&&status===`pending`){let placeholderData;if(prevResult?.isPlaceholderData&&options.placeholderData===prevResultOptions?.placeholderData){placeholderData=prevResult.data;skipSelect=true}else placeholderData=typeof options.placeholderData===`function`?options.placeholderData(this.#lastQueryWithDefinedData?.state.data,this.#lastQueryWithDefinedData):options.placeholderData;if(placeholderData!==void 0){status=`success`;data=replaceData(prevResult?.data,placeholderData,options);isPlaceholderData=true}}if(options.select&&data!==void 0&&!skipSelect){if(prevResult&&data===prevResultState?.data&&options.select===this.#selectFn)data=this.#selectResult;else try{this.#selectFn=options.select;data=options.select(data);data=replaceData(prevResult?.data,data,options);this.#selectResult=data;this.#selectError=null}catch(selectError){this.#selectError=selectError}}else if(data===void 0)this.#selectError=null;if(this.#selectError){error=this.#selectError;data=this.#selectResult;errorUpdatedAt=Date.now();status=`error`;isPlaceholderData=false}const isFetching=newState.fetchStatus===`fetching`;const isPending=status===`pending`;const isError=status===`error`;const isLoading=isPending&&isFetching;const hasData=data!==void 0;return{status,fetchStatus:newState.fetchStatus,isPending,isSuccess:status===`success`,isError,isInitialLoading:isLoading,isLoading,data,dataUpdatedAt:newState.dataUpdatedAt,error,errorUpdatedAt,failureCount:newState.fetchFailureCount,failureReason:newState.fetchFailureReason,errorUpdateCount:newState.errorUpdateCount,isFetched:query.isFetched(),isFetchedAfterMount:newState.dataUpdateCount>queryInitialState.dataUpdateCount||newState.errorUpdateCount>queryInitialState.errorUpdateCount,isFetching,isRefetching:isFetching&&!isPending,isLoadingError:isError&&!hasData,isPaused:newState.fetchStatus===`paused`,isPlaceholderData,isRefetchError:isError&&hasData,isStale:isStale(query,options),refetch:this.refetch,isEnabled:resolveQueryValue(options.enabled,query)!==false}}updateResult(){const prevResult=this.#currentResult;const nextResult=this.createResult(this.#currentQuery,this.options);this.#currentResultState=this.#currentQuery.state;this.#currentResultOptions=this.options;if(this.#currentResultState.data!==void 0)this.#lastQueryWithDefinedData=this.#currentQuery;if(shallowEqualObjects(nextResult,prevResult))return;this.#currentResult=nextResult;const shouldNotifyListeners=()=>{if(!prevResult)return true;const{notifyOnChangeProps}=this.options;const notifyOnChangePropsValue=typeof notifyOnChangeProps===`function`?notifyOnChangeProps():notifyOnChangeProps;if(notifyOnChangePropsValue===`all`||!notifyOnChangePropsValue&&!this.#trackedProps.size)return true;const includedProps=new Set(notifyOnChangePropsValue??this.#trackedProps);if(this.options.throwOnError)includedProps.add(`error`);return Object.keys(this.#currentResult).some(key=>{const typedKey=key;return this.#currentResult[typedKey]!==prevResult[typedKey]&&includedProps.has(typedKey)})};const notifyListeners=shouldNotifyListeners();notifyManager.batch(()=>{if(notifyListeners)this.listeners.forEach(listener=>{listener(this.#currentResult)});this.#client.getQueryCache().notify({query:this.#currentQuery,type:`observerResultsUpdated`})})}#updateQuery(){const query=this.#client.getQueryCache().build(this.#client,this.options);if(query===this.#currentQuery)return;const prevQuery=this.#currentQuery;this.#currentQuery=query;this.#currentQueryInitialState=query.state;if(this.hasListeners()){prevQuery?.removeObserver(this);query.addObserver(this)}}onQueryUpdate(){this.updateResult();if(this.hasListeners())this.#updateTimers()}};function shouldLoadOnMount(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.state.data===void 0&&!(query.state.status===`error`&&resolveQueryValue(options.retryOnMount,query)===false)}function shouldFetchOnMount(query,options){return shouldLoadOnMount(query,options)||query.state.data!==void 0&&shouldFetchOn(query,options,options.refetchOnMount)}function shouldFetchOn(query,options,field){if(resolveQueryValue(options.enabled,query)!==false&&resolveQueryValue(options.staleTime,query)!==`static`){const value=resolveQueryValue(field,query);return value===`always`||value!==false&&isStale(query,options)}return false}function shouldFetchOptionally(query,prevQuery,options,prevOptions){return(query!==prevQuery||resolveQueryValue(prevOptions.enabled,query)===false)&&(!options.suspense||query.state.status!==`error`)&&isStale(query,options)}function isStale(query,options){return resolveQueryValue(options.enabled,query)!==false&&query.isStaleByTime(resolveQueryValue(options.staleTime,query))}var Mutation=class extends Removable{#client;#observers;#mutationCache;#retryer;constructor(config){super();this.#client=config.client;this.mutationId=config.mutationId;this.#mutationCache=config.mutationCache;this.#observers=[];this.state=config.state||getDefaultState();this.setOptions(config.options);this.scheduleGc()}setOptions(options){this.options=options;this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(observer){if(!this.#observers.includes(observer)){this.#observers.push(observer);this.clearGcTimeout();this.#mutationCache.notify({type:`observerAdded`,mutation:this,observer})}}removeObserver(observer){this.#observers=this.#observers.filter(x=>x!==observer);this.scheduleGc();this.#mutationCache.notify({type:`observerRemoved`,mutation:this,observer})}optionalRemove(){if(!this.#observers.length){if(this.state.status===`pending`)this.scheduleGc();else this.#mutationCache.remove(this)}}continue(){return this.#retryer?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(variables){const onContinue=()=>{this.#dispatch({type:`continue`})};const mutationFnContext={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};const retryer=this.#retryer=createRetryer({fn:()=>{if(!this.options.mutationFn)return Promise.reject(new Error(`No mutationFn found`));return this.options.mutationFn(variables,mutationFnContext)},onFail:(failureCount,error)=>{this.#dispatch({type:`failed`,failureCount,error})},onPause:()=>{this.#dispatch({type:`pause`})},onContinue,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#mutationCache.canRun(this)});const restored=this.state.status===`pending`;const isPaused=!retryer.canStart();try{if(restored)onContinue();else{this.#dispatch({type:`pending`,variables,isPaused});if(this.#mutationCache.config.onMutate)await this.#mutationCache.config.onMutate(variables,this,mutationFnContext);const context=await this.options.onMutate?.(variables,mutationFnContext);if(context!==this.state.context)this.#dispatch({type:`pending`,context,variables,isPaused})}const data=await retryer.start();await this.#mutationCache.config.onSuccess?.(data,variables,this.state.context,this,mutationFnContext);await this.options.onSuccess?.(data,variables,this.state.context,mutationFnContext);await this.#mutationCache.config.onSettled?.(data,null,this.state.variables,this.state.context,this,mutationFnContext);await this.options.onSettled?.(data,null,variables,this.state.context,mutationFnContext);this.#dispatch({type:`success`,data});return data}catch(error){try{await this.#mutationCache.config.onError?.(error,variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onError?.(error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.#mutationCache.config.onSettled?.(void 0,error,this.state.variables,this.state.context,this,mutationFnContext)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,error,variables,this.state.context,mutationFnContext)}catch(e){Promise.reject(e)}this.#dispatch({type:`error`,error});throw error}finally{if(this.#retryer===retryer)this.#retryer=void 0;this.#mutationCache.runNext(this)}}#dispatch(action){const reducer=state=>{switch(action.type){case`failed`:return{...state,failureCount:action.failureCount,failureReason:action.error};case`pause`:return{...state,isPaused:true};case`continue`:return{...state,isPaused:false};case`pending`:return{...state,context:action.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:action.isPaused,status:`pending`,variables:action.variables,submittedAt:Date.now()};case`success`:return{...state,data:action.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:false};case`error`:return{...state,data:void 0,error:action.error,failureCount:state.failureCount+1,failureReason:action.error,isPaused:false,status:`error`}}};this.state=reducer(this.state);notifyManager.batch(()=>{this.#observers.forEach(observer=>{observer.onMutationUpdate(action)});this.#mutationCache.notify({mutation:this,type:`updated`,action})})}};function getDefaultState(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:false,status:`idle`,variables:void 0,submittedAt:0}}var MutationObserver=class extends Subscribable{#client;#currentResult=void 0;#currentMutation;#mutateOptions;constructor(client,options){super();this.#client=client;this.setOptions(options);this.bindMethods();this.#updateResult()}bindMethods(){this.mutate=this.mutate.bind(this);this.reset=this.reset.bind(this)}setOptions(options){const prevOptions=this.options;this.options=this.#client.defaultMutationOptions(options);if(!shallowEqualObjects(this.options,prevOptions))this.#client.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#currentMutation,observer:this});if(prevOptions?.mutationKey&&this.options.mutationKey&&hashKey(prevOptions.mutationKey)!==hashKey(this.options.mutationKey))this.reset();else if(this.#currentMutation?.state.status===`pending`)this.#currentMutation.setOptions(this.options)}onSubscribe(){if(this.listeners.size===1&&this.#currentMutation){this.#currentMutation.addObserver(this);this.#updateResult()}}onUnsubscribe(){if(!this.hasListeners())this.#currentMutation?.removeObserver(this)}onMutationUpdate(action){this.#updateResult();this.#notify(action)}getCurrentResult(){return this.#currentResult}reset(){this.#currentMutation?.removeObserver(this);this.#currentMutation=void 0;this.#updateResult();this.#notify()}mutate(variables,options){this.#mutateOptions=options;this.#currentMutation?.removeObserver(this);this.#currentMutation=this.#client.getMutationCache().build(this.#client,this.options);this.#currentMutation.addObserver(this);return this.#currentMutation.execute(variables)}#updateResult(){const state=this.#currentMutation?.state??getDefaultState();this.#currentResult={...state,isPending:state.status===`pending`,isSuccess:state.status===`success`,isError:state.status===`error`,isIdle:state.status===`idle`,mutate:this.mutate,reset:this.reset}}#notify(action){notifyManager.batch(()=>{if(this.#mutateOptions&&this.hasListeners()){const variables=this.#currentResult.variables;const onMutateResult=this.#currentResult.context;const context={client:this.#client,meta:this.options.meta,mutationKey:this.options.mutationKey};if(action?.type===`success`){try{this.#mutateOptions.onSuccess?.(action.data,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(action.data,null,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}else if(action?.type===`error`){try{this.#mutateOptions.onError?.(action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}try{this.#mutateOptions.onSettled?.(void 0,action.error,variables,onMutateResult,context)}catch(e){Promise.reject(e)}}}this.listeners.forEach(listener=>{listener(this.#currentResult)})})}};function useBaseQuery(Observer,options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{let resolvedOptions=options;if(typeof resolvedOptions===`function`)resolvedOptions=resolvedOptions();const clonedOptions=cloneDeepUnref(resolvedOptions);if(typeof clonedOptions.enabled===`function`)clonedOptions.enabled=clonedOptions.enabled();const defaulted=client.defaultQueryOptions(clonedOptions);defaulted._optimisticResults=client.isRestoring?.value?`isRestoring`:`optimistic`;return defaulted});const observer=new Observer(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());let unsubscribe=()=>{};if(client.isRestoring)watch(client.isRestoring,isRestoring=>{if(!isRestoring){unsubscribe();unsubscribe=observer.subscribe(result=>{updateState(state,result)})}},{immediate:true});const updater=()=>{observer.setOptions(defaultedOptions.value);updateState(state,observer.getCurrentResult())};watch(defaultedOptions,updater);onScopeDispose(()=>{unsubscribe()});const refetch=(...args)=>{updater();return state.refetch(...args)};const suspense=()=>{return new Promise((resolve,reject)=>{let stopWatch=()=>{};const run=()=>{if(defaultedOptions.value.enabled!==false){observer.setOptions(defaultedOptions.value);const optimisticResult=observer.getOptimisticResult(defaultedOptions.value);if(optimisticResult.isStale){stopWatch();observer.fetchOptimistic(defaultedOptions.value).then(resolve,error=>{if(shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))reject(error);else resolve(observer.getCurrentResult())})}else{stopWatch();resolve(optimisticResult)}}};run();stopWatch=watch(defaultedOptions,run)})};watch(()=>state.error,error=>{if(state.isError&&!state.isFetching&&shouldThrowError(defaultedOptions.value.throwOnError,[error,observer.getCurrentQuery()]))throw error});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const object=toRefs(readonlyState);for(const key in state)if(typeof state[key]===`function`)object[key]=state[key];object.suspense=suspense;object.refetch=refetch;return object}function useQuery(options,queryClient){return useBaseQuery(QueryObserver,options,queryClient)}function useMutation(options,queryClient){const client=queryClient||useQueryClient();const defaultedOptions=computed(()=>{const resolvedOptions=typeof options===`function`?options():options;return client.defaultMutationOptions(cloneDeepUnref(resolvedOptions))});const observer=new MutationObserver(client,defaultedOptions.value);const state=defaultedOptions.value.shallow?shallowReactive(observer.getCurrentResult()):reactive(observer.getCurrentResult());const unsubscribe=observer.subscribe(result=>{updateState(state,result)});const mutate=(...args)=>{observer.mutate(args[0],args[1]).catch(()=>{})};watch(defaultedOptions,()=>{observer.setOptions(defaultedOptions.value)});onScopeDispose(()=>{unsubscribe()});const readonlyState=defaultedOptions.value.shallow?shallowReadonly(state):readonly(state);const resultRefs=toRefs(readonlyState);watch(()=>state.error,error=>{if(error&&shouldThrowError(defaultedOptions.value.throwOnError,[error]))throw error});return{...resultRefs,mutate,mutateAsync:state.mutate,reset:state.reset}}function resolveEnabledRef(value){if(value===void 0)return true;return Boolean(toValue(value))}function resolveTextRef(value){return String(unref(value)||``).trim()}var OWNERSHIP_FILTER_VALUES=ROUTE_VISIBILITY_TOKENS;var SCOPED_OWNERSHIP_FILTER_SET=new Set([ROUTE_VISIBILITY_WORKSPACE,ROUTE_VISIBILITY_WORKSPACE_USER]);var ACCESS_MODE_VALUES=Object.freeze([`auto`,`always`,`never`]);function asPlainObject(value){if(!value||typeof value!==`object`||Array.isArray(value))return{};return value}function emptyRecord(){return{}}function normalizePermissions(value){if(Array.isArray(value))return value.map(entry=>String(entry||``).trim()).filter(Boolean);const one=String(value||``).trim();return one?[one]:[]}function resolvePermissionAccess(access,normalizedPermissions=[]){if(normalizedPermissions.length<1)return true;return access.canAny(normalizedPermissions)}function normalizeAccessMode(value=`auto`){const normalized=String(value||`auto`).trim().toLowerCase();if(ACCESS_MODE_VALUES.includes(normalized))return normalized;throw new TypeError(`access must be one of: ${ACCESS_MODE_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function resolveAccessModeEnabled(accessMode=`auto`,{hasPermissionRequirements=false}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`always`)return true;if(normalizedMode===`never`)return false;return hasPermissionRequirements===true}function ensureAccessModeCompatibility({accessMode=`auto`,hasPermissionRequirements=false,caller=`http-web`}={}){const normalizedMode=normalizeAccessMode(accessMode);if(normalizedMode===`never`&&hasPermissionRequirements)throw new TypeError(`${caller} cannot use access:\"never\" when permission requirements are configured.`);return normalizedMode}function resolveApiSuffix(apiSuffix,context={}){if(typeof apiSuffix===`function`)return resolveTextRef(apiSuffix(context));return resolveTextRef(apiSuffix)}function resolveEnabled(value,context={}){if(typeof value===`function`)return Boolean(value(context));return resolveEnabledRef(value)}function normalizeOwnershipFilter(value=ROUTE_VISIBILITY_WORKSPACE){const normalized=String(value||`workspace`).trim().toLowerCase();if(OWNERSHIP_FILTER_VALUES.includes(normalized))return normalized;throw new TypeError(`ownershipFilter must be one of: ${OWNERSHIP_FILTER_VALUES.join(`, `)}. Received: ${String(value||``)||`(empty)`}`)}function isScopedOwnershipFilter(ownershipFilter){return SCOPED_OWNERSHIP_FILTER_SET.has(ownershipFilter)}function resolveQueryKey(queryKeyFactory,{surfaceId=``,scopeParamValue=``,ownershipFilter=ROUTE_VISIBILITY_WORKSPACE}={}){if(isScopedOwnershipFilter(ownershipFilter))return queryKeyFactory(surfaceId,scopeParamValue,ownershipFilter);return queryKeyFactory(surfaceId,ownershipFilter)}function normalizeRealtimeOptions(value={}){if(value===null||value===void 0||value===false)return{};if(typeof value!==`object`||Array.isArray(value))throw new TypeError(`realtime must be an object when configured.`);return value}function toQueryKeyList(value){const resolved=toValue(value);if(!Array.isArray(resolved)||resolved.length<1)return[];if(Array.isArray(resolved[0]))return resolved.filter(entry=>Array.isArray(entry)&&entry.length>0).map(entry=>Object.freeze([...entry]));return[Object.freeze([...resolved])]}var followUpReads=new WeakMap;function refetchAfterCurrentRead(queryClient,query){if(followUpReads.has(query))return followUpReads.get(query);const read=()=>queryClient.refetchQueries({queryKey:query.queryKey,exact:true},{cancelRefetch:false});if(query.state.fetchStatus!==`fetching`)return read();const followUp=read().then(()=>{followUpReads.delete(query);return read()});followUpReads.set(query,followUp);return followUp}async function refreshQueriesWithoutCancelling(queryClient,queryKey){await queryClient.invalidateQueries({queryKey,refetchType:`none`});await nextTick();await Promise.all(queryClient.getQueryCache().findAll({queryKey,type:`active`}).map(query=>refetchAfterCurrentRead(queryClient,query)))}function useRealtimeQueryInvalidation({event=``,enabled=true,matches,queryKey=null,onEvent}){const queryClient=useQueryClient();const normalizedEvent=computed(()=>normalizeText(unref(event)));const active=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedEvent.value));return{active:useRealtimeEvent({event:normalizedEvent,enabled:active,matches,onEvent:async context=>{if(onEvent)await onEvent(context);const keys=toQueryKeyList(queryKey);for(const key of keys)await refreshQueriesWithoutCancelling(queryClient,key)}}).active}}function useOperationRealtime({realtime=null,queryKey=null,enabled=true}={}){const source=normalizeRealtimeOptions(realtime);const eventList=[];if(Object.hasOwn(source,`event`)){const normalizedEvent=normalizeText(source.event);if(normalizedEvent)eventList.push(normalizedEvent)}if(Object.hasOwn(source,`events`)){if(!Array.isArray(source.events))throw new TypeError(`realtime.events must be an array when configured.`);for(const entry of source.events){const normalizedEvent=normalizeText(entry);if(!normalizedEvent||eventList.includes(normalizedEvent))continue;eventList.push(normalizedEvent)}}if(eventList.length<1)return null;const{matches,onEvent}=source;const resolvedQueryKey=Object.hasOwn(source,`queryKey`)?source.queryKey:queryKey;const active=computed(()=>{const sourceEnabled=Object.hasOwn(source,`enabled`)?source.enabled:true;return resolveEnabledRef(enabled)&&resolveEnabledRef(sourceEnabled)});const bindings=eventList.map(event=>useRealtimeQueryInvalidation({event,enabled:active,matches,queryKey:resolvedQueryKey,onEvent}));return{active:computed(()=>bindings.some(binding=>Boolean(binding.active.value)))}}function buildEndpointReadRequestOptions({method=`GET`,query=null,transport=null}={}){const requestOptions={method:String(method||`GET`).toUpperCase()};const normalizedQuery=resolveRequestQuery(query);if(normalizedQuery)requestOptions.query=normalizedQuery;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function resolveRequestQuery(value=null){const source=unref(value);if(!source||typeof source!==`object`||Array.isArray(source))return null;return source}function buildEndpointWriteRequestOptions({method=`PATCH`,body=void 0,options=null,transport=null}={}){const requestOptions={method:String(method||`PATCH`).toUpperCase(),...asPlainObject(options)};if(body!==void 0)requestOptions.body=body;if(transport&&typeof transport===`object`)requestOptions.transport=transport;return requestOptions}function useEndpointResource({queryKey,path=``,enabled=true,client=getHttpWebClient(),readMethod=`GET`,writeMethod=`PATCH`,readQuery,transport,refreshOnPull=false,realtime,queryOptions=null,mutationOptions=null,requestRecovery=null,requestRecoveryLabel=``,fallbackLoadError=`jskit.http.resource.loadFailed`,fallbackSaveError=`jskit.http.resource.saveFailed`}){const normalizedPath=computed(()=>resolveTextRef(path));const queryEnabled=computed(()=>resolveEnabledRef(enabled)&&Boolean(normalizedPath.value));const query=useQuery({queryKey,queryFn:({signal})=>{const requestPath=normalizedPath.value;if(!requestPath)throw new Error(`Resource path is required.`);return client.request(requestPath,{...buildEndpointReadRequestOptions({method:readMethod,query:readQuery,transport}),signal})},enabled:queryEnabled,...mergeRequestRecoveryQueryMeta(refreshOnPull?mergeQueryMeta(asPlainObject(queryOptions),{jskit:{refreshOnPull:true}}):asPlainObject(queryOptions),requestRecovery,{label:requestRecoveryLabel,method:readMethod})});const realtimeBinding=useOperationRealtime({realtime,queryKey,enabled:queryEnabled});const mutation=useMutation({mutationFn:async(request={})=>{const options=asPlainObject(request);const requestPath=resolveTextRef(options.path||normalizedPath.value);if(!requestPath)throw new Error(`Resource path is required.`);const method=String(options.method||writeMethod||`PATCH`).toUpperCase();const body=Object.hasOwn(options,`body`)?options.body:options.payload;return client.request(requestPath,buildEndpointWriteRequestOptions({method,body,options:options.options,transport}))},...asPlainObject(mutationOptions)});const data=computed(()=>query.data.value);const hasResolvedData=computed(()=>hasResolvedQueryData({query,data}));const isInitialLoading=computed(()=>Boolean(queryEnabled.value&&query.isPending.value&&!hasResolvedData.value));const isFetching=computed(()=>Boolean(queryEnabled.value&&query.isFetching.value));const isRefetching=computed(()=>Boolean(isFetching.value&&!isInitialLoading.value));const isLoading=computed(()=>Boolean(isInitialLoading.value||isFetching.value));const isSaving=computed(()=>Boolean(mutation.isPending.value));const loadError=computed(()=>toQueryErrorMessage(query.error.value,fallbackLoadError));const saveError=computed(()=>toQueryErrorMessage(mutation.error.value,fallbackSaveError));async function reload(){return query.refetch()}async function save(payload,options={}){return mutation.mutateAsync({...asPlainObject(options),payload})}return{query,mutation,data,isInitialLoading,isFetching,isRefetching,isLoading,isSaving,loadError,saveError,realtime:realtimeBinding,reload,save}}export{partialMatchKey as A,environmentManager as C,matchMutation as D,hashQueryKeyByOptions as E,getClientKey as F,skipToken as M,useQueryClient as N,matchQuery as O,cloneDeepUnref as P,Subscribable as S,hashKey as T,Mutation as _,ensureAccessModeCompatibility as a,notifyManager as b,normalizePermissions as c,resolveEnabled as d,resolvePermissionAccess as f,useQuery as g,useMutation as h,emptyRecord as i,resolveQueryValue as j,noop as k,resolveAccessModeEnabled as l,resolveEnabledRef as m,useOperationRealtime as n,normalizeAccessMode as o,resolveQueryKey as p,asPlainObject as r,normalizeOwnershipFilter as s,useEndpointResource as t,resolveApiSuffix as u,Query as v,functionalUpdate as w,focusManager as x,onlineManager as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{vt as ref}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as useShellWebErrorRuntime}from"./error-BQ7r64JO.js";import{n as toUiErrorMessage}from"./errorMessageHelpers-B49LyMJi.js";function useUiFeedback({initialType=`success`,source=`http-web.ui-feedback`,successChannel=``,warningChannel=``,errorChannel=``,dedupeWindowMs=2e3}={}){const message=ref(``);const messageType=ref(String(initialType||`success`));const errorRuntime=useShellWebErrorRuntime();const normalizedSource=String(source||``).trim()||`http-web.ui-feedback`;let lastErrorPresentation=null;function rememberErrorPresentation(reportResult=null){const presentationId=String(reportResult?.presentationId||``).trim();const presenterId=String(reportResult?.decision?.presenterId||``).trim();if(!presentationId||!presenterId)return;lastErrorPresentation=Object.freeze({presentationId,presenterId})}function dismissLastErrorPresentation(){if(!lastErrorPresentation)return;errorRuntime.dismiss(lastErrorPresentation.presentationId,{presenterId:lastErrorPresentation.presenterId});lastErrorPresentation=null}function clear(){message.value=``}function reportDone(severity,channel,nextMessage){messageType.value=severity;const normalizedMessage=String(nextMessage||``).trim();message.value=normalizedMessage;dismissLastErrorPresentation();if(!normalizedMessage)return;errorRuntime.report({source:normalizedSource,message:normalizedMessage,intent:`action-feedback`,severity,channel,dedupeKey:`${normalizedSource}:${severity}:${normalizedMessage}`,dedupeWindowMs})}function success(nextMessage=``){reportDone(`success`,successChannel,nextMessage)}function warning(nextMessage=``){reportDone(`warning`,warningChannel,nextMessage)}function error(errorValue,fallbackMessage=``){messageType.value=`error`;message.value=toUiErrorMessage(errorValue,fallbackMessage);if(!message.value)return;const reportResult=errorRuntime.report({source:normalizedSource,message:message.value,cause:errorValue||null,intent:`action-feedback`,severity:`error`,channel:errorChannel,dedupeKey:`${normalizedSource}:error:${message.value}`,dedupeWindowMs});if(!reportResult?.skipped)rememberErrorPresentation(reportResult)}return{message,messageType,clear,success,warning,error}}export{useUiFeedback as t};
|
package/dist/assets/{useVibe64ConversationLog-Ch0ZbnCG.js → useVibe64ConversationLog-BADhWyNY.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/english-definitions-
|
|
2
|
-
import{it as watch,mt as onScopeDispose,u as computed,vt as ref,xt as shallowRef}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as isRecord,s as normalizeObject}from"./normalize-BD25VwNK.js";import{t as __vitePreload}from"./preload-helper-BvdcsxN9.js";import{n as getHttpWebClient}from"./httpClient-Bwitq9Xf.js";import{r as useRealtimeEvent}from"./useRealtimeEvent-B4oRg9Dt.js";import{t as usePaths}from"./usePaths-CvUbx5-V.js";import{t as readRefOrGetterValue}from"./vueRefOrGetterValue-y-4f_In7.js";import{I as vibe64SessionEventMatchesScope,L as vibe64SessionPath,o as VIBE64_SESSIONS_API_SUFFIX,s as VIBE64_SESSION_CHANGED_EVENT}from"./vibe64SessionRequestConfig-DVRCRAex.js";import{o as normalizeVibe64ConversationAttachments}from"./shared-B6plZPQ_.js";import{n as normalizeConversationTurn$1}from"./conversation-D7T_us2O.js";import{N as useVibe64ProjectSlug}from"./index-DAareKn3.js";var CONVERSATION_LOG_REALTIME_REASONS=new Set([`project-message-changed`,`conversation-rewound`,`session-assistant-selection-updated`,`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 normalizeConversationTurn(turn={},index=0){const normalized=normalizeConversationTurn$1(turn,index,{normalizeAttachments:normalizeVibe64ConversationAttachments});return normalized&&{...normalized,...isRecord(turn.integrationSetup)?{integrationSetup:turn.integrationSetup}:{}}}function normalizeConversationLog(payload,options={}){const log=normalizeObject(payload).conversationLog;return conversationTurnsWithPending((Array.isArray(log)?log:[]).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 sessionAgentTurnActive(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!reason||CONVERSATION_LOG_REALTIME_REASONS.has(reason)}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.`);const{connectorDefinitions}=await __vitePreload(async()=>{const{connectorDefinitions}=await import(`./english-definitions-CwCZ8VJ-.js`).then(n=>n.n);return{connectorDefinitions}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102]));if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;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,session,conversation}){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`}));const turns=computed(()=>conversationTurnsWithPending(conversation.turns.value,sessionAgentTurnActive(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}),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{integrationConnections:integrationActions.integrationConnections,connectIntegrationRequest:integrationActions.connectIntegrationRequest,checkIntegrationRequest:integrationActions.checkIntegrationRequest,cancelIntegrationRequest:integrationActions.cancelIntegrationRequest,integrationActionPending:integrationActions.integrationActionPending,integrationActionError:integrationActions.integrationActionError,skipIntegrationRequest:integrationActions.skipIntegrationRequest,resumeIntegrationRequest:integrationActions.resumeIntegrationRequest,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))}}export{useVibe64ConversationLog as n,normalizeConversationLog as t};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/english-definitions-BtX8KA5g.js","assets/placement-B2V88UDJ.js","assets/placement-1lT0lW3-.js","assets/runtime-core.esm-bundler-Bi1P1jMa.js","assets/returnToPath-CILshEkc.js","assets/normalize-BD25VwNK.js","assets/linkPath-BsiibCNd.js","assets/surface-CBlx7sF_.js","assets/vibe64GithubProject-CJneIo5O.js","assets/vibe64SessionToolDefinitions-BijEEwqu.js","assets/vibe64ProjectScope.local-B9ZpdYlf.js","assets/deepFreeze-BgoYkoTa.js","assets/validators-HqYRjxEO.js","assets/i18n-DpzQwXg6.js","assets/index-JBqyg0mr.js","assets/VChip-tORFnf7z.js","assets/VChip-4Nj-0ztL.css","assets/error-BQ7r64JO.js","assets/i18n-BuXRXGaO.js","assets/i18n-Dm74yE_M.js","assets/useEndpointResource-DZTjr9gg.js","assets/httpClient-Bwitq9Xf.js","assets/queryPath-yKLyWw8V.js","assets/visibility-Cq31Xy7I.js","assets/useRealtimeEvent-B4oRg9Dt.js","assets/errorMessageHelpers-B49LyMJi.js","assets/i18n-DQPYjuW7.js","assets/useApi-BPuI6ZR9-rsYWyW6m.js","assets/devtools-CN5uWJaH-_xug6686.js","assets/preload-helper-BvdcsxN9.js","assets/VSelect-gYJ6qrBP.js","assets/VOverlay-CrfaXCOL.js","assets/lazy-mtFmsnct.js","assets/VOverlay-DG-PukqI.css","assets/VMenu-CO6B6LWk.js","assets/VMenu-DCU7zd0B.css","assets/VTextField-DP6b7Qaf.js","assets/VTextField-F6unyhrS.css","assets/VCheckboxBtn-8g4R-c2w.js","assets/VCheckboxBtn-o1O5Bixh.css","assets/VSheet-_Grtwpfz.js","assets/VSheet-BbLSwuzR.css","assets/VSelect-yFA6_y4G.css","assets/VSkeletonLoader-CQXCEJsR.js","assets/VBtn-Com1gNEe.js","assets/VBtn-C1plz3b1.css","assets/VSkeletonLoader-DXZarZ9m.css","assets/useVibe64Learning-CbsI-XHB.js","assets/vibe64AssistantHost-CyWUOG-F.js","assets/asyncModuleRecovery-BALhPqsY.js","assets/VDialog-CapFiCqp.js","assets/VDialog-DP-kc9Gx.css","assets/_plugin-vue_export-helper-DNW4j-dv.js","assets/browser-D8z6v6Ge.js","assets/StudioErrorNotice-vDR4qneB.js","assets/StudioErrorNotice-CQfeUEOD.css","assets/browserLocalStorage-B4C7rHrs.js","assets/clipboard-CZs9aH3L.js","assets/useVibe64Learning-B9b7aUr-.css","assets/layout-DMZV-nbg.js","assets/errors-D17nJYne.js","assets/studioUrls-k_pQIuPs.js","assets/client-CevjVK2b.js","assets/VAutocomplete-NpBcbYkR.js","assets/VAutocomplete-D48FgPMA.css","assets/VCheckbox-CkezAf4Z.js","assets/VCheckbox-ChRKi1kj.css","assets/VCard-DY_DdI8Z.js","assets/VCard-dv-Dc592.css","assets/VRow-DHETsEMn.js","assets/VRow-BdVn5u8X.css","assets/VSpacer-VLYDmg7o.js","assets/VSpacer-DfbUir7X.css","assets/VExpansionPanels-B6U2XdWH.js","assets/VExpansionPanels-cvCWEkWz.css","assets/VRadioGroup-BrPW6foD.js","assets/VRadioGroup-C9f4tbih.css","assets/VSwitch-ffi-Y2TU.js","assets/VSwitch-DAlld-JI.css","assets/useCommand-D-MIMmhp.js","assets/usePaths-CvUbx5-V.js","assets/pathname-JHQIKk21.js","assets/useUiFeedback-BU4NyMq8.js","assets/shared-B6plZPQ_.js","assets/assistantRouting-B9cub38g.js","assets/shared-DjZEYqzW.js","assets/vibe64ApiResponses-DuJ9mfus.js","assets/studioGateApi-UqmdV50W.js","assets/client-CM6TGZc9.css","assets/client-4uCr4dYG.js","assets/VTextarea-7mdIF4I0.js","assets/VTextarea--uW4w6nq.css","assets/useAssistantAttachments-DqlNFiha.js","assets/conversation-OkWbkHjm.js","assets/thinkingText-mMYz6e03.js","assets/conversation-DReMq0MF.css","assets/SelectField-Dezd0B3y.js","assets/vueRefOrGetterValue-y-4f_In7.js","assets/vibe64BrowserTabOrigin-vIN_87mi.js","assets/vibe64SessionRequestConfig-DVRCRAex.js","assets/conversation-D7T_us2O.js","assets/windowSizeClass-DQekxFgV.js","assets/index-DSyb-mRJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{it as watch,mt as onScopeDispose,u as computed,vt as ref,xt as shallowRef}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as isRecord,s as normalizeObject}from"./normalize-BD25VwNK.js";import{t as __vitePreload}from"./preload-helper-BvdcsxN9.js";import{n as getHttpWebClient}from"./httpClient-Bwitq9Xf.js";import{r as useRealtimeEvent}from"./useRealtimeEvent-B4oRg9Dt.js";import{t as usePaths}from"./usePaths-CvUbx5-V.js";import{t as readRefOrGetterValue}from"./vueRefOrGetterValue-y-4f_In7.js";import{I as vibe64SessionEventMatchesScope,L as vibe64SessionPath,o as VIBE64_SESSIONS_API_SUFFIX,s as VIBE64_SESSION_CHANGED_EVENT}from"./vibe64SessionRequestConfig-DVRCRAex.js";import{o as normalizeVibe64ConversationAttachments}from"./shared-B6plZPQ_.js";import{n as normalizeConversationTurn$1}from"./conversation-D7T_us2O.js";import{N as useVibe64ProjectSlug}from"./index-JBqyg0mr.js";var CONVERSATION_LOG_REALTIME_REASONS=new Set([`project-message-changed`,`conversation-rewound`,`session-assistant-selection-updated`,`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 normalizeConversationTurn(turn={},index=0){const normalized=normalizeConversationTurn$1(turn,index,{normalizeAttachments:normalizeVibe64ConversationAttachments});return normalized&&{...normalized,...isRecord(turn.integrationSetup)?{integrationSetup:turn.integrationSetup}:{}}}function normalizeConversationLog(payload,options={}){const log=normalizeObject(payload).conversationLog;return conversationTurnsWithPending((Array.isArray(log)?log:[]).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 sessionAgentTurnActive(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!reason||CONVERSATION_LOG_REALTIME_REASONS.has(reason)}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.`);const{connectorDefinitions}=await __vitePreload(async()=>{const{connectorDefinitions}=await import(`./english-definitions-BtX8KA5g.js`).then(n=>n.n);return{connectorDefinitions}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102]));if(integrationActionPending.value!==selection||sessionId.value!==selection.sessionId)return false;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,session,conversation}){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`}));const turns=computed(()=>conversationTurnsWithPending(conversation.turns.value,sessionAgentTurnActive(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}),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{integrationConnections:integrationActions.integrationConnections,connectIntegrationRequest:integrationActions.connectIntegrationRequest,checkIntegrationRequest:integrationActions.checkIntegrationRequest,cancelIntegrationRequest:integrationActions.cancelIntegrationRequest,integrationActionPending:integrationActions.integrationActionPending,integrationActionError:integrationActions.integrationActionError,skipIntegrationRequest:integrationActions.skipIntegrationRequest,resumeIntegrationRequest:integrationActions.resumeIntegrationRequest,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))}}export{useVibe64ConversationLog as n,normalizeConversationLog as t};
|