vibe64 0.1.65 → 0.1.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/bin/run.js +823 -820
  2. package/bin/server.js +200 -197
  3. package/bin/upgrade-state.js +4181 -4054
  4. package/dist/assets/{GithubBrowserTabs-D21Nl3QI.js → GithubBrowserTabs-Bf5z_PiF.js} +1 -1
  5. package/dist/assets/{LocalDatabaseServer-POxY1K1U.js → LocalDatabaseServer-CcfGbn7H.js} +1 -1
  6. package/dist/assets/{SelectField-Dezd0B3y.js → SelectField-Df50ZFLj.js} +1 -1
  7. package/dist/assets/{ShellOutlet-DfF9vsWA.js → ShellOutlet-DPyl05um.js} +1 -1
  8. package/dist/assets/{Vibe64AuthSettingsButton-I3ufyScN.js → Vibe64AuthSettingsButton-CxJoeOhz.js} +1 -1
  9. package/dist/assets/{Vibe64ConversationLog-C04oOQ2g.js → Vibe64ConversationLog-jDb_ZvIF.js} +1 -1
  10. package/dist/assets/{Vibe64DashboardShell-BbrOUmRD.js → Vibe64DashboardShell-Ce1PNB37.js} +1 -1
  11. package/dist/assets/{Vibe64DatabaseWorkspace-VPEM2o1v.js → Vibe64DatabaseWorkspace-DiZDKEpx.js} +1 -1
  12. package/dist/assets/{Vibe64FileArea-C_nC2bPk.js → Vibe64FileArea-uRnIJ0Vp.js} +1 -1
  13. package/dist/assets/{Vibe64OutputControls-DTO3Fw3x.js → Vibe64OutputControls-BF5kh2_h.js} +1 -1
  14. package/dist/assets/{Vibe64RepositoryWorkspace-B8xcCOvL.js → Vibe64RepositoryWorkspace-D6uJCype.js} +1 -1
  15. package/dist/assets/{Vibe64SessionFiles-Cb9Mxsyq.js → Vibe64SessionFiles-CxgPB8RR.js} +1 -1
  16. package/dist/assets/{Vibe64SessionSourceEditor-CVQ3NRjh.js → Vibe64SessionSourceEditor-yaVu279S.js} +1 -1
  17. package/dist/assets/{Vibe64UiStoryboardView-BV4JFgcZ.js → Vibe64UiStoryboardView-DhbHkz8K.js} +1 -1
  18. package/dist/assets/{Vibe64UnavailableSessions-DGQAxYE-.js → Vibe64UnavailableSessions-MmPF-Db1.js} +1 -1
  19. package/dist/assets/{_pageId_-CkG15vv4.js → _pageId_-Zif-veil.js} +1 -1
  20. package/dist/assets/{_sessionId_-Bka3RUmK.js → _sessionId_-DOge-7SB.js} +1 -1
  21. package/dist/assets/_slug_-C71iAiR0.js +14 -0
  22. package/dist/assets/_slug_-CF1TPDUv.css +1 -0
  23. package/dist/assets/{access-Xo3unxGO.js → access-DQcblrWN.js} +1 -1
  24. package/dist/assets/{app-B0spNegd.js → app-CzApKPmq.js} +1 -1
  25. package/dist/assets/assistantRouting-CqIiQy21.js +3 -0
  26. package/dist/assets/{changes-DFv4tuoO.js → changes-cmlEyHug.js} +1 -1
  27. package/dist/assets/{client-CVuXqm4b.js → client-13v_yX07.js} +1 -1
  28. package/dist/assets/{client-BjMjS6lX.js → client-5JUUGxRd.js} +2 -2
  29. package/dist/assets/{client-4uCr4dYG.js → client-BJBzomgt.js} +1 -1
  30. package/dist/assets/{client-DR0w56e8.js → client-C8ZjqGdQ.js} +2 -2
  31. package/dist/assets/{client-Dlg1kjjO.js → client-Dl6I6IVb.js} +1 -1
  32. package/dist/assets/{client-CevjVK2b.js → client-Dv4scw6i.js} +1 -1
  33. package/dist/assets/{conversation-OkWbkHjm.js → conversation-CFJRkeTj.js} +3 -3
  34. package/dist/assets/{conversation-DReMq0MF.css → conversation-COcuIkcD.css} +1 -1
  35. package/dist/assets/conversation-CexAK3Qk.js +1 -0
  36. package/dist/assets/{dashboard-CAca9MQn.js → dashboard-Dm_xwwqU.js} +1 -1
  37. package/dist/assets/{english-definitions-BtX8KA5g.js → english-definitions-DwTf_alg.js} +1 -1
  38. package/dist/assets/{env-DrNyBVkB.js → env-B7wB5nBn.js} +1 -1
  39. package/dist/assets/{error-BQ7r64JO.js → error-CtOws2EC.js} +1 -1
  40. package/dist/assets/{error-BqMxhgpB.js → error-HfzrYwkQ.js} +1 -1
  41. package/dist/assets/{errorMessageHelpers-B49LyMJi.js → errorMessageHelpers-G32Hjqfm.js} +1 -1
  42. package/dist/assets/{health-B5yTW5Tt.js → health-DIkOkzPe.js} +1 -1
  43. package/dist/assets/{history-S3anp6xg.js → history-Ch597NiY.js} +1 -1
  44. package/dist/assets/{httpClient-Bwitq9Xf.js → httpClient-C71X5grL.js} +1 -1
  45. package/dist/assets/{i18n-BuXRXGaO.js → i18n-5EHeMSvt.js} +1 -1
  46. package/dist/assets/{i18n-DQPYjuW7.js → i18n-BSfPKqM3.js} +1 -1
  47. package/dist/assets/{i18n-Dm74yE_M.js → i18n-DcNQE3tT.js} +1 -1
  48. package/dist/assets/index-C-6c5Af1.css +1 -0
  49. package/dist/assets/{index-JBqyg0mr.js → index-DcKFCaBZ.js} +4 -4
  50. package/dist/assets/{integrations-C7dj7el_.js → integrations-CoNhnGvq.js} +1 -1
  51. package/dist/assets/{issues-OkV4v4GX.js → issues-Cem4Yt47.js} +1 -1
  52. package/dist/assets/{learning-lW9nBGjT.js → learning-CU2QyHrj.js} +1 -1
  53. package/dist/assets/{pages-shOT9IVe.js → pages-BzA58NoR.js} +1 -1
  54. package/dist/assets/{project-files-D_K1N0JF.js → project-files-BBKjl3wZ.js} +1 -1
  55. package/dist/assets/{publish-Bxe4ZCqe.js → publish-UFjblZA3.js} +1 -1
  56. package/dist/assets/{pull-requests-CQvk0TeH.js → pull-requests-DibGk1GB.js} +1 -1
  57. package/dist/assets/{repository-CI2CqDwF.js → repository-0EKOcyTL.js} +1 -1
  58. package/dist/assets/{settings-DIVrFrs4.js → settings-BjOnPYwD.js} +1 -1
  59. package/dist/assets/{studioGateApi-UqmdV50W.js → studioGateApi-B9EUTtMx.js} +1 -1
  60. package/dist/assets/{studioUrls-k_pQIuPs.js → studioUrls-BR4ZL-TN.js} +1 -1
  61. package/dist/assets/{useArchivedVibe64Sessions-BkWrTOzg.js → useArchivedVibe64Sessions-CXKRFR2f.js} +1 -1
  62. package/dist/assets/useAssistantAttachments-C9kAnWqw.js +2 -0
  63. package/dist/assets/useCommand-yOr3U8KF.js +1 -0
  64. package/dist/assets/{useEndpointResource-DZTjr9gg.js → useEndpointResource-BwGXpV2u.js} +1 -1
  65. package/dist/assets/{useUiFeedback-BU4NyMq8.js → useUiFeedback--0dLsslR.js} +1 -1
  66. package/dist/assets/{useVibe64ConversationLog-BADhWyNY.js → useVibe64ConversationLog-BB5tVtkt.js} +2 -2
  67. package/dist/assets/{useVibe64Learning-CbsI-XHB.js → useVibe64Learning-iAAH83uG.js} +1 -1
  68. package/dist/assets/{useVibe64SessionData-DvFvAJC-.js → useVibe64SessionData-BSYF_TgH.js} +1 -1
  69. package/dist/assets/{useVibe64SessionSelection-BukDTAxb.js → useVibe64SessionSelection-CxZ3uEAf.js} +1 -1
  70. package/dist/assets/{vibe64FileUpload-BDkcaUyk.js → vibe64FileUpload-D_rOa1R8.js} +1 -1
  71. package/dist/assets/{vibe64RepositoryRealtime-DX2DEqIz.js → vibe64RepositoryRealtime-CVGNqwxz.js} +1 -1
  72. package/dist/assets/{vibe64SessionFocus-CzuP3qPT.js → vibe64SessionFocus-DGSVXipO.js} +1 -1
  73. package/dist/index.html +23 -23
  74. package/docs/colleague-usage/ai-tasks.md +2 -1
  75. package/docs/colleague-usage/auto-workflow.md +6 -3
  76. package/docs/colleague-usage/coding-agent-goal-pause.md +34 -12
  77. package/docs/colleague-usage/coding-agent-goals.md +33 -16
  78. package/docs/colleague-usage/coding-agent-questions.md +7 -0
  79. package/docs/colleague-usage/connected-repositories.md +4 -1
  80. package/docs/colleague-usage/github-work.md +36 -3
  81. package/docs/colleague-usage/passes.md +86 -0
  82. package/docs/colleague-usage/ui-pass.md +4 -0
  83. package/docs/colleague-usage/workspace-preparation.md +51 -0
  84. package/node_modules/@jskit-ai/assistant-core/CHANGELOG.md +8 -0
  85. package/node_modules/@jskit-ai/assistant-core/locales/en.json +2 -0
  86. package/node_modules/@jskit-ai/assistant-core/package.json +1 -1
  87. package/node_modules/@jskit-ai/assistant-runtime/CHANGELOG.md +2 -0
  88. package/node_modules/@jskit-ai/assistant-runtime/package.json +1 -1
  89. package/node_modules/@jskit-ai/assistant-voice/package.json +1 -1
  90. package/node_modules/@jskit-ai/connector-google-calendar/package.json +1 -1
  91. package/node_modules/@jskit-ai/connectors-catalog/package.json +1 -1
  92. package/node_modules/@jskit-ai/connectors-core/package.json +1 -1
  93. package/node_modules/@jskit-ai/http-runtime/CHANGELOG.md +1 -0
  94. package/node_modules/@jskit-ai/http-runtime/package.json +1 -1
  95. package/node_modules/@jskit-ai/kernel/CHANGELOG.md +5 -0
  96. package/node_modules/@jskit-ai/kernel/package.json +1 -1
  97. package/node_modules/@jskit-ai/payments-core/package.json +1 -1
  98. package/node_modules/@jskit-ai/realtime/package.json +1 -1
  99. package/node_modules/@jskit-ai/resource-core/package.json +1 -1
  100. package/node_modules/@jskit-ai/uploads-runtime/package.json +1 -1
  101. package/node_modules/@local/vibe64-genesis/bin/vibe64-genesis-host-context +914 -773
  102. package/node_modules/@local/vibe64-genesis/src/server/agentSpecs.js +69 -63
  103. package/node_modules/@local/vibe64-genesis/src/server/index.js +450 -440
  104. package/node_modules/@local/vibe64-genesis/src/server/packaging.js +27 -28
  105. package/node_modules/@local/vibe64-genesis/src/server/promptContext.js +63 -55
  106. package/node_modules/@local/vibe64-runtime/src/server/codexAppServerProcess.js +1044 -901
  107. package/node_modules/@local/vibe64-terminals/src/server/opencodeSessionEnvironmentPlugin.js +560 -420
  108. package/node_modules/@local/vibe64-terminals/src/server/sessionWorkOperationCommand.js +453 -450
  109. package/package.json +15 -15
  110. package/server.bundle.mjs +42018 -41710
  111. package/dist/assets/_slug_-7Oo7pGKn.js +0 -14
  112. package/dist/assets/_slug_-BaxjtsgP.css +0 -1
  113. package/dist/assets/assistantRouting-B9cub38g.js +0 -3
  114. package/dist/assets/conversation-D7T_us2O.js +0 -1
  115. package/dist/assets/index-DSyb-mRJ.css +0 -1
  116. package/dist/assets/useAssistantAttachments-DqlNFiha.js +0 -2
  117. package/dist/assets/useCommand-D-MIMmhp.js +0 -1
@@ -1,2 +0,0 @@
1
- import{Tt as toValue,gt as reactive,it as watch,mt as onScopeDispose,u as computed,ut as getCurrentScope,vt as ref}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import"./client-4uCr4dYG.js";import{r as useJskitText,t as registerJskitMessages}from"./i18n-BuXRXGaO.js";var jskit=JSON.parse(`{"assistant":{"api":{"requestFailed":"Assistant request failed."},"attachments":{"announcement":{"cancelled":"{count} attachment cancelled. | {count} attachments cancelled.","inProgress":"{count} attachment is in progress. | {count} attachments are in progress.","needAttention":"{count} attachment needs attention. | {count} attachments need attention.","ready":"{count} attachment ready. | {count} attachments ready."},"attached":"Attached files","bytes":"{sent} / {size}","bytesPercent":"{sent} / {size} · {percent}%","cancelItem":"Cancel {name}","close":"Close","download":"Download","error":{"cleanupFailed":"Attachment cleanup failed.","localFilePaste":"Copied local files cannot be pasted from this browser. Drop the file or use Attach files.","noFile":"The prepared attachment did not produce a file.","preparationFailed":"Attachment preparation failed.","tooLarge":"{fileName} is larger than the {limit} attachment limit.","tooMany":"A message can keep at most {count} attachments.","unusable":"Uploaded attachment could not be used.","uploadFailed":"Attachment upload failed."},"limit":"{count} / {max}","preparingName":"Preparing attachment…","previewUnavailable":"Preview is unavailable for this file. You can download it below.","queue":"Message attachments","removeItem":"Remove {name}","retryItem":"Retry {name}","sizeBytes":"{size} B","sizeKilobytes":"{size} KB","sizeMebibytes":"{size} MiB","sizeMegabytes":"{size} MB","status":{"cancelled":"Cancelled","delivering":"Sending to Codex","preparationFailed":"Preparation failed","preparing":"Preparing","queued":"Queued","ready":"Ready","sendingFailed":"Sending failed","uploadFailed":"Upload failed","uploading":"Uploading"},"summary":{"cancelled":"{completed} ready · {cancelled} cancelled","inProgress":"{completed} of {total} ready · in progress","needAttention":"{completed} of {total} ready · {count} needs attention | {completed} of {total} ready · {count} need attention","percent":"{completed} of {total} ready · {percent}%","ready":"{completed} of {total} ready"},"unnamed":"attachment","uploadProgress":"Upload progress for {name}"},"chat":{"attachFiles":"Attach files","avatar":"Conversation avatar","discardUnsent":"Discard unsent message","editUnsent":"Edit unsent message","label":"Assistant conversation","messageAssistant":"Message AI assistant","minimiseAvatar":"Minimise avatar","reviewAttachedFiles":"Please review the attached files.","sendingToAssistant":"Sending to assistant…","showAvatar":"Show avatar","working":"Assistant is working…"},"composer":{"cannotSendYet":"Your words are in the chat box, but this conversation cannot send yet.","chatChanged":"The chat changed before sending. Review the draft before sending.","notReady":"The chat composer is not ready yet.","send":"Send","sendMessage":"Send message","sending":"Sending…","stop":"Stop","stopping":"Stopping…","suggestedPrompts":"Suggested prompts","suggestionsAvailable":"{count} suggested prompts are available before the message controls.","thinkingOfIdeas":"Thinking of a few ideas","thinkingOfIdeasStatus":"Thinking of a few ideas.","useSuggestion":"Use suggestion: {prompt}"},"delivery":{"cancelling":"Cancelling…","cancelUnreachable":"Couldn't reach the server — Cancel again","checkBeforeResend":"Check delivery before resending.","checkPrevious":"Check the previous message's delivery before sending again.","checking":"Checking…","notConfirmed":"Message delivery is not confirmed.","notSent":"Message could not be sent.","retry":"Retry","retryCheck":"Retry delivery check","unconfirmed":"Delivery could not be confirmed.","unconfirmedShort":"Delivery unconfirmed."},"goal":{"blocked":"Goal blocked","budgetLimited":"Goal budget reached","cancel":"Cancel goal","cancelInterruptsTurn":"Cancel stops the current turn and clears the goal.","cancelRemovesGoal":"Cancel removes this goal. Use Stop to interrupt a turn already running.","cancelling":"Cancelling…","complete":"Goal complete","elapsed":"{label}: {elapsed}","goal":"Goal","loading":"Loading goal…","notRunning":"Goal not running","notRunningHint":"Nothing is working on this goal right now. Your next message continues it.","objective":"Goal objective","outOfCredit":"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};
@@ -1 +0,0 @@
1
- import{Et as unref,gt as reactive,ht as proxyRefs,it as watch,u as computed}from"./runtime-core.esm-bundler-Bi1P1jMa.js";import{r as useShellWebErrorRuntime}from"./error-BQ7r64JO.js";import{N as useQueryClient,a as ensureAccessModeCompatibility,c as normalizePermissions,d as resolveEnabled,f as resolvePermissionAccess,i as emptyRecord,l as resolveAccessModeEnabled,m as resolveEnabledRef,n as useOperationRealtime,o as normalizeAccessMode,p as resolveQueryKey,r as asPlainObject,s as normalizeOwnershipFilter,t as useEndpointResource,u as resolveApiSuffix}from"./useEndpointResource-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};