@kortix/sdk 0.13.57 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +108 -15
- package/dist/browser/cache/idb-sync-cache.d.ts.map +1 -1
- package/dist/browser/cache/idb-sync-cache.js +19 -5
- package/dist/browser/cache/idb-sync-cache.js.map +1 -1
- package/dist/browser/session-sync/server-transcript-mirror.d.ts +26 -7
- package/dist/browser/session-sync/server-transcript-mirror.d.ts.map +1 -1
- package/dist/browser/session-sync/server-transcript-mirror.js +51 -44
- package/dist/browser/session-sync/server-transcript-mirror.js.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.d.ts +8 -0
- package/dist/browser/session-sync/session-sync-registry.d.ts.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.js +59 -2
- package/dist/browser/session-sync/session-sync-registry.js.map +1 -1
- package/dist/browser/stores/sync-store/keep-unchanged.d.ts +17 -0
- package/dist/browser/stores/sync-store/keep-unchanged.d.ts.map +1 -0
- package/dist/browser/stores/sync-store/keep-unchanged.js +47 -0
- package/dist/browser/stores/sync-store/keep-unchanged.js.map +1 -0
- package/dist/browser/stores/sync-store.d.ts +6 -0
- package/dist/browser/stores/sync-store.d.ts.map +1 -1
- package/dist/browser/stores/sync-store.js +115 -17
- package/dist/browser/stores/sync-store.js.map +1 -1
- package/dist/core/attachments/prompt-attachments.d.ts +11 -0
- package/dist/core/attachments/prompt-attachments.d.ts.map +1 -1
- package/dist/core/attachments/prompt-attachments.js +34 -0
- package/dist/core/attachments/prompt-attachments.js.map +1 -1
- package/dist/core/capture/rules.d.ts +44 -0
- package/dist/core/capture/rules.d.ts.map +1 -0
- package/dist/core/capture/rules.js +55 -0
- package/dist/core/capture/rules.js.map +1 -0
- package/dist/core/client/capture.d.ts +122 -0
- package/dist/core/client/capture.d.ts.map +1 -0
- package/dist/core/client/capture.js +62 -0
- package/dist/core/client/capture.js.map +1 -0
- package/dist/core/client/facade-commerce.d.ts +10 -1
- package/dist/core/client/facade-commerce.d.ts.map +1 -1
- package/dist/core/client/facade-commerce.js +10 -1
- package/dist/core/client/facade-commerce.js.map +1 -1
- package/dist/core/client/kortix.d.ts +87 -5
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/kortix.js +3 -0
- package/dist/core/client/kortix.js.map +1 -1
- package/dist/core/client/project-access-resources.d.ts +4 -2
- package/dist/core/client/project-access-resources.d.ts.map +1 -1
- package/dist/core/client/project-access-resources.js +2 -2
- package/dist/core/client/project-access-resources.js.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/client/project-operations-admin.d.ts +4 -4
- package/dist/core/client/project-operations-review.d.ts +4 -3
- package/dist/core/client/project-operations-review.d.ts.map +1 -1
- package/dist/core/client/project-operations-review.js +3 -0
- package/dist/core/client/project-operations-review.js.map +1 -1
- package/dist/core/client/project-operations-workspace.d.ts +5 -4
- package/dist/core/client/project-operations-workspace.d.ts.map +1 -1
- package/dist/core/client/project-operations-workspace.js +2 -1
- package/dist/core/client/project-operations-workspace.js.map +1 -1
- package/dist/core/client/project-operations.d.ts +4 -4
- package/dist/core/client/session-handle.d.ts +9 -0
- package/dist/core/client/session-handle.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-resources.d.ts +13 -0
- package/dist/core/client/session-lifecycle-resources.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-resources.js +8 -0
- package/dist/core/client/session-lifecycle-resources.js.map +1 -1
- package/dist/core/http/api-client.d.ts +17 -0
- package/dist/core/http/api-client.d.ts.map +1 -1
- package/dist/core/http/api-client.js +17 -0
- package/dist/core/http/api-client.js.map +1 -1
- package/dist/core/http/response-error.d.ts.map +1 -1
- package/dist/core/http/response-error.js +31 -2
- package/dist/core/http/response-error.js.map +1 -1
- package/dist/core/models/composer-model.d.ts +35 -0
- package/dist/core/models/composer-model.d.ts.map +1 -1
- package/dist/core/models/composer-model.js +41 -1
- package/dist/core/models/composer-model.js.map +1 -1
- package/dist/core/rest/platform-client/capture.d.ts +507 -0
- package/dist/core/rest/platform-client/capture.d.ts.map +1 -0
- package/dist/core/rest/platform-client/capture.js +178 -0
- package/dist/core/rest/platform-client/capture.js.map +1 -0
- package/dist/core/rest/platform-client/index.d.ts +1 -0
- package/dist/core/rest/platform-client/index.d.ts.map +1 -1
- package/dist/core/rest/platform-client/index.js +1 -0
- package/dist/core/rest/platform-client/index.js.map +1 -1
- package/dist/core/rest/platform-client/lifecycle.d.ts +14 -4
- package/dist/core/rest/platform-client/lifecycle.d.ts.map +1 -1
- package/dist/core/rest/platform-client/lifecycle.js +32 -16
- package/dist/core/rest/platform-client/lifecycle.js.map +1 -1
- package/dist/core/rest/platform-client/shared.d.ts +22 -0
- package/dist/core/rest/platform-client/shared.d.ts.map +1 -1
- package/dist/core/rest/platform-client/shared.js +35 -0
- package/dist/core/rest/platform-client/shared.js.map +1 -1
- package/dist/core/rest/projects-client/account-secret-resources.d.ts +5 -1
- package/dist/core/rest/projects-client/account-secret-resources.d.ts.map +1 -1
- package/dist/core/rest/projects-client/account-secret-resources.js.map +1 -1
- package/dist/core/rest/projects-client/agent-config.d.ts +15 -8
- package/dist/core/rest/projects-client/agent-config.d.ts.map +1 -1
- package/dist/core/rest/projects-client/agent-config.js +1 -1
- package/dist/core/rest/projects-client/agent-config.js.map +1 -1
- package/dist/core/rest/projects-client/apps-fleet.d.ts +14 -3
- package/dist/core/rest/projects-client/apps-fleet.d.ts.map +1 -1
- package/dist/core/rest/projects-client/apps-fleet.js +8 -4
- package/dist/core/rest/projects-client/apps-fleet.js.map +1 -1
- package/dist/core/rest/projects-client/apps.d.ts +13 -1
- package/dist/core/rest/projects-client/apps.d.ts.map +1 -1
- package/dist/core/rest/projects-client/apps.js.map +1 -1
- package/dist/core/rest/projects-client/billing.d.ts +227 -55
- package/dist/core/rest/projects-client/billing.d.ts.map +1 -1
- package/dist/core/rest/projects-client/billing.js +80 -33
- package/dist/core/rest/projects-client/billing.js.map +1 -1
- package/dist/core/rest/projects-client/change-requests.d.ts +10 -2
- package/dist/core/rest/projects-client/change-requests.d.ts.map +1 -1
- package/dist/core/rest/projects-client/change-requests.js +8 -0
- package/dist/core/rest/projects-client/change-requests.js.map +1 -1
- package/dist/core/rest/projects-client/connector-run.d.ts +1 -1
- package/dist/core/rest/projects-client/connector-run.js +1 -1
- package/dist/core/rest/projects-client/connectors.d.ts +12 -0
- package/dist/core/rest/projects-client/connectors.d.ts.map +1 -1
- package/dist/core/rest/projects-client/connectors.js +3 -0
- package/dist/core/rest/projects-client/connectors.js.map +1 -1
- package/dist/core/rest/projects-client/gateway.d.ts +19 -0
- package/dist/core/rest/projects-client/gateway.d.ts.map +1 -1
- package/dist/core/rest/projects-client/gateway.js.map +1 -1
- package/dist/core/rest/projects-client/iam-actions.d.ts +2 -2
- package/dist/core/rest/projects-client/iam-actions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/iam-actions.js +5 -3
- package/dist/core/rest/projects-client/iam-actions.js.map +1 -1
- package/dist/core/rest/projects-client/iam-enterprise.d.ts +2 -0
- package/dist/core/rest/projects-client/iam-enterprise.d.ts.map +1 -1
- package/dist/core/rest/projects-client/iam-enterprise.js +11 -9
- package/dist/core/rest/projects-client/iam-enterprise.js.map +1 -1
- package/dist/core/rest/projects-client/notifications.d.ts +3 -2
- package/dist/core/rest/projects-client/notifications.d.ts.map +1 -1
- package/dist/core/rest/projects-client/notifications.js +4 -0
- package/dist/core/rest/projects-client/notifications.js.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +22 -13
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +2 -3
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/rest/projects-client/review-items.d.ts +7 -0
- package/dist/core/rest/projects-client/review-items.d.ts.map +1 -1
- package/dist/core/rest/projects-client/review-items.js +6 -0
- package/dist/core/rest/projects-client/review-items.js.map +1 -1
- package/dist/core/rest/projects-client/review.d.ts +52 -3
- package/dist/core/rest/projects-client/review.d.ts.map +1 -1
- package/dist/core/rest/projects-client/review.js +27 -0
- package/dist/core/rest/projects-client/review.js.map +1 -1
- package/dist/core/rest/projects-client/secrets.d.ts +17 -2
- package/dist/core/rest/projects-client/secrets.d.ts.map +1 -1
- package/dist/core/rest/projects-client/secrets.js.map +1 -1
- package/dist/core/rest/projects-client/sessions.d.ts +96 -14
- package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.js +60 -10
- package/dist/core/rest/projects-client/sessions.js.map +1 -1
- package/dist/core/runtime/runtime-types.d.ts +5 -0
- package/dist/core/runtime/runtime-types.d.ts.map +1 -1
- package/dist/core/session/open-bundle.d.ts +28 -34
- package/dist/core/session/open-bundle.d.ts.map +1 -1
- package/dist/core/session/open-bundle.js +57 -80
- package/dist/core/session/open-bundle.js.map +1 -1
- package/dist/core/session/turn-end-watch.d.ts +112 -0
- package/dist/core/session/turn-end-watch.d.ts.map +1 -0
- package/dist/core/session/turn-end-watch.js +196 -0
- package/dist/core/session/turn-end-watch.js.map +1 -0
- package/dist/core/session-log/index.d.ts +1 -0
- package/dist/core/session-log/index.d.ts.map +1 -1
- package/dist/core/session-log/index.js +2 -0
- package/dist/core/session-log/index.js.map +1 -1
- package/dist/core/session-log/tool-call.d.ts +12 -1
- package/dist/core/session-log/tool-call.d.ts.map +1 -1
- package/dist/core/session-log/tool-call.js +26 -1
- package/dist/core/session-log/tool-call.js.map +1 -1
- package/dist/core/session-log/turns/blocks.d.ts +5 -1
- package/dist/core/session-log/turns/blocks.d.ts.map +1 -1
- package/dist/core/session-log/turns/blocks.js +20 -2
- package/dist/core/session-log/turns/blocks.js.map +1 -1
- package/dist/core/session-log/turns/history.d.ts +92 -0
- package/dist/core/session-log/turns/history.d.ts.map +1 -0
- package/dist/core/session-log/turns/history.js +145 -0
- package/dist/core/session-log/turns/history.js.map +1 -0
- package/dist/core/session-log/turns/index.d.ts +8 -3
- package/dist/core/session-log/turns/index.d.ts.map +1 -1
- package/dist/core/session-log/turns/index.js +7 -2
- package/dist/core/session-log/turns/index.js.map +1 -1
- package/dist/core/session-log/turns/turn.d.ts +24 -4
- package/dist/core/session-log/turns/turn.d.ts.map +1 -1
- package/dist/core/session-log/turns/turn.js +64 -5
- package/dist/core/session-log/turns/turn.js.map +1 -1
- package/dist/core/session-log/types.d.ts +4 -4
- package/dist/core/session-log/types.js +2 -2
- package/dist/core/session-log/v1-view.d.ts +13 -9
- package/dist/core/session-log/v1-view.d.ts.map +1 -1
- package/dist/core/session-log/v1-view.js +49 -24
- package/dist/core/session-log/v1-view.js.map +1 -1
- package/dist/core/session-log/v1.d.ts +2 -0
- package/dist/core/session-log/v1.d.ts.map +1 -1
- package/dist/core/session-log/v1.js +12 -1
- package/dist/core/session-log/v1.js.map +1 -1
- package/dist/core/session-sync/saved-transcript.d.ts +57 -1
- package/dist/core/session-sync/saved-transcript.d.ts.map +1 -1
- package/dist/core/session-sync/saved-transcript.js +93 -0
- package/dist/core/session-sync/saved-transcript.js.map +1 -1
- package/dist/core/session-sync/session-sync-controller.d.ts +2 -1
- package/dist/core/session-sync/session-sync-controller.d.ts.map +1 -1
- package/dist/core/session-sync/session-sync-controller.js +9 -0
- package/dist/core/session-sync/session-sync-controller.js.map +1 -1
- package/dist/core/stream/event-stream.d.ts.map +1 -1
- package/dist/core/stream/event-stream.js +4 -1
- package/dist/core/stream/event-stream.js.map +1 -1
- package/dist/core/turns/classify.d.ts.map +1 -1
- package/dist/core/turns/classify.js +6 -3
- package/dist/core/turns/classify.js.map +1 -1
- package/dist/core/turns/edit-blocks.d.ts +8 -0
- package/dist/core/turns/edit-blocks.d.ts.map +1 -0
- package/dist/core/turns/edit-blocks.js +22 -0
- package/dist/core/turns/edit-blocks.js.map +1 -0
- package/dist/core/turns/segments/burst-summary.d.ts +10 -0
- package/dist/core/turns/segments/burst-summary.d.ts.map +1 -1
- package/dist/core/turns/segments/burst-summary.js +33 -0
- package/dist/core/turns/segments/burst-summary.js.map +1 -1
- package/dist/core/turns/segments/narration.d.ts +1 -1
- package/dist/core/turns/segments/narration.d.ts.map +1 -1
- package/dist/core/turns/segments/narration.js +9 -0
- package/dist/core/turns/segments/narration.js.map +1 -1
- package/dist/core/turns/state.d.ts +5 -4
- package/dist/core/turns/state.d.ts.map +1 -1
- package/dist/core/turns/state.js +5 -4
- package/dist/core/turns/state.js.map +1 -1
- package/dist/core/turns/tool-kind.d.ts +6 -4
- package/dist/core/turns/tool-kind.d.ts.map +1 -1
- package/dist/core/turns/tool-kind.js +13 -5
- package/dist/core/turns/tool-kind.js.map +1 -1
- package/dist/core/turns/tool-registry.d.ts.map +1 -1
- package/dist/core/turns/tool-registry.js +1 -0
- package/dist/core/turns/tool-registry.js.map +1 -1
- package/dist/core/turns/view-model.d.ts.map +1 -1
- package/dist/core/turns/view-model.js +1 -14
- package/dist/core/turns/view-model.js.map +1 -1
- package/dist/genui/catalog.d.ts +40 -0
- package/dist/genui/catalog.d.ts.map +1 -0
- package/dist/genui/catalog.js +420 -0
- package/dist/genui/catalog.js.map +1 -0
- package/dist/genui/expansion.d.ts +19 -0
- package/dist/genui/expansion.d.ts.map +1 -0
- package/dist/genui/expansion.js +344 -0
- package/dist/genui/expansion.js.map +1 -0
- package/dist/genui/fence-entry.d.ts +3 -0
- package/dist/genui/fence-entry.d.ts.map +1 -0
- package/dist/genui/fence-entry.js +4 -0
- package/dist/genui/fence-entry.js.map +1 -0
- package/dist/genui/fence.d.ts +53 -0
- package/dist/genui/fence.d.ts.map +1 -0
- package/dist/genui/fence.js +170 -0
- package/dist/genui/fence.js.map +1 -0
- package/dist/genui/index.d.ts +7 -0
- package/dist/genui/index.d.ts.map +1 -0
- package/dist/genui/index.js +7 -0
- package/dist/genui/index.js.map +1 -0
- package/dist/genui/markdown.d.ts +33 -0
- package/dist/genui/markdown.d.ts.map +1 -0
- package/dist/genui/markdown.js +133 -0
- package/dist/genui/markdown.js.map +1 -0
- package/dist/genui/parse.d.ts +12 -0
- package/dist/genui/parse.d.ts.map +1 -0
- package/dist/genui/parse.js +83 -0
- package/dist/genui/parse.js.map +1 -0
- package/dist/genui/prompt.d.ts +5 -0
- package/dist/genui/prompt.d.ts.map +1 -0
- package/dist/genui/prompt.js +209 -0
- package/dist/genui/prompt.js.map +1 -0
- package/dist/genui/react/default-components.d.ts +3 -0
- package/dist/genui/react/default-components.d.ts.map +1 -0
- package/dist/genui/react/default-components.js +81 -0
- package/dist/genui/react/default-components.js.map +1 -0
- package/dist/genui/react/genui-block.d.ts +46 -0
- package/dist/genui/react/genui-block.d.ts.map +1 -0
- package/dist/genui/react/genui-block.js +106 -0
- package/dist/genui/react/genui-block.js.map +1 -0
- package/dist/genui/react/index.d.ts +3 -0
- package/dist/genui/react/index.d.ts.map +1 -0
- package/dist/genui/react/index.js +3 -0
- package/dist/genui/react/index.js.map +1 -0
- package/dist/genui/share.d.ts +11 -0
- package/dist/genui/share.d.ts.map +1 -0
- package/dist/genui/share.js +36 -0
- package/dist/genui/share.js.map +1 -0
- package/dist/genui/types.d.ts +51 -0
- package/dist/genui/types.d.ts.map +1 -0
- package/dist/genui/types.js +3 -0
- package/dist/genui/types.js.map +1 -0
- package/dist/genui/urls.d.ts +7 -0
- package/dist/genui/urls.d.ts.map +1 -0
- package/dist/genui/urls.js +24 -0
- package/dist/genui/urls.js.map +1 -0
- package/dist/genui/validate.d.ts +25 -0
- package/dist/genui/validate.d.ts.map +1 -0
- package/dist/genui/validate.js +139 -0
- package/dist/genui/validate.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/kortix.esm.min.js +38 -36
- package/dist/kortix.global.js +38 -36
- package/dist/platform/ui.d.ts +20 -2
- package/dist/platform/ui.d.ts.map +1 -1
- package/dist/platform/ui.js +31 -4
- package/dist/platform/ui.js.map +1 -1
- package/dist/react/hold-live-start.js +1 -1
- package/dist/react/hold-live-start.js.map +1 -1
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +5 -0
- package/dist/react/index.js.map +1 -1
- package/dist/react/opencode.d.ts +1 -1
- package/dist/react/opencode.d.ts.map +1 -1
- package/dist/react/opencode.js +1 -1
- package/dist/react/opencode.js.map +1 -1
- package/dist/react/query-contracts.d.ts +10 -0
- package/dist/react/query-contracts.d.ts.map +1 -1
- package/dist/react/query-contracts.js +10 -0
- package/dist/react/query-contracts.js.map +1 -1
- package/dist/react/query-keys.d.ts +29 -1
- package/dist/react/query-keys.d.ts.map +1 -1
- package/dist/react/query-keys.js +37 -2
- package/dist/react/query-keys.js.map +1 -1
- package/dist/react/reset-identity-state.d.ts +2 -1
- package/dist/react/reset-identity-state.d.ts.map +1 -1
- package/dist/react/reset-identity-state.js +4 -1
- package/dist/react/reset-identity-state.js.map +1 -1
- package/dist/react/session-cache-write.d.ts +2 -0
- package/dist/react/session-cache-write.d.ts.map +1 -1
- package/dist/react/session-cache-write.js +24 -1
- package/dist/react/session-cache-write.js.map +1 -1
- package/dist/react/sign-in-with-kortix.d.ts +5 -5
- package/dist/react/turn-end-handoff.d.ts +24 -0
- package/dist/react/turn-end-handoff.d.ts.map +1 -0
- package/dist/react/turn-end-handoff.js +131 -0
- package/dist/react/turn-end-handoff.js.map +1 -0
- package/dist/react/use-admin-accounts.d.ts +124 -39
- package/dist/react/use-admin-accounts.d.ts.map +1 -1
- package/dist/react/use-admin-accounts.js +96 -41
- package/dist/react/use-admin-accounts.js.map +1 -1
- package/dist/react/use-billing-plan.d.ts +38 -0
- package/dist/react/use-billing-plan.d.ts.map +1 -0
- package/dist/react/use-billing-plan.js +64 -0
- package/dist/react/use-billing-plan.js.map +1 -0
- package/dist/react/use-capture.d.ts +77 -0
- package/dist/react/use-capture.d.ts.map +1 -0
- package/dist/react/use-capture.js +210 -0
- package/dist/react/use-capture.js.map +1 -0
- package/dist/react/use-feature-flag.d.ts +3 -3
- package/dist/react/use-feature-flag.d.ts.map +1 -1
- package/dist/react/use-feature-flag.js +4 -3
- package/dist/react/use-feature-flag.js.map +1 -1
- package/dist/react/use-opencode-events/handle-interaction-event.d.ts.map +1 -1
- package/dist/react/use-opencode-events/handle-interaction-event.js +5 -3
- package/dist/react/use-opencode-events/handle-interaction-event.js.map +1 -1
- package/dist/react/use-opencode-events/handle-session-event.d.ts.map +1 -1
- package/dist/react/use-opencode-events/handle-session-event.js +19 -8
- package/dist/react/use-opencode-events/handle-session-event.js.map +1 -1
- package/dist/react/use-opencode-events/handler-context.d.ts +2 -0
- package/dist/react/use-opencode-events/handler-context.d.ts.map +1 -1
- package/dist/react/use-opencode-events/helpers.d.ts +11 -0
- package/dist/react/use-opencode-events/helpers.d.ts.map +1 -1
- package/dist/react/use-opencode-events/helpers.js +21 -1
- package/dist/react/use-opencode-events/helpers.js.map +1 -1
- package/dist/react/use-opencode-local.d.ts +12 -1
- package/dist/react/use-opencode-local.d.ts.map +1 -1
- package/dist/react/use-opencode-local.js +23 -3
- package/dist/react/use-opencode-local.js.map +1 -1
- package/dist/react/use-opencode-sessions/commands.d.ts +20 -1
- package/dist/react/use-opencode-sessions/commands.d.ts.map +1 -1
- package/dist/react/use-opencode-sessions/commands.js +29 -1
- package/dist/react/use-opencode-sessions/commands.js.map +1 -1
- package/dist/react/use-opencode-sessions/permissions.d.ts.map +1 -1
- package/dist/react/use-opencode-sessions/permissions.js +46 -1
- package/dist/react/use-opencode-sessions/permissions.js.map +1 -1
- package/dist/react/use-project-sessions.d.ts +1 -1
- package/dist/react/use-project-sessions.d.ts.map +1 -1
- package/dist/react/use-project-sessions.js +3 -2
- package/dist/react/use-project-sessions.js.map +1 -1
- package/dist/react/use-prompt-attachments.d.ts.map +1 -1
- package/dist/react/use-prompt-attachments.js +1 -0
- package/dist/react/use-prompt-attachments.js.map +1 -1
- package/dist/react/use-review-summary.d.ts +29 -0
- package/dist/react/use-review-summary.d.ts.map +1 -0
- package/dist/react/use-review-summary.js +48 -0
- package/dist/react/use-review-summary.js.map +1 -0
- package/dist/react/use-runtime-reconnect.js +2 -2
- package/dist/react/use-runtime-reconnect.js.map +1 -1
- package/dist/react/use-session-list-state.d.ts +14 -0
- package/dist/react/use-session-list-state.d.ts.map +1 -0
- package/dist/react/use-session-list-state.js +43 -0
- package/dist/react/use-session-list-state.js.map +1 -0
- package/dist/react/use-session-log.d.ts +19 -10
- package/dist/react/use-session-log.d.ts.map +1 -1
- package/dist/react/use-session-log.js +29 -24
- package/dist/react/use-session-log.js.map +1 -1
- package/dist/react/use-session-stream.d.ts.map +1 -1
- package/dist/react/use-session-stream.js +16 -1
- package/dist/react/use-session-stream.js.map +1 -1
- package/dist/react/use-session-sync.d.ts +10 -2
- package/dist/react/use-session-sync.d.ts.map +1 -1
- package/dist/react/use-session-sync.js +14 -8
- package/dist/react/use-session-sync.js.map +1 -1
- package/dist/react/use-session-transcript-history.d.ts +1 -0
- package/dist/react/use-session-transcript-history.d.ts.map +1 -1
- package/dist/react/use-session-transcript-history.js +5 -16
- package/dist/react/use-session-transcript-history.js.map +1 -1
- package/dist/react/use-session-working.d.ts +11 -0
- package/dist/react/use-session-working.d.ts.map +1 -1
- package/dist/react/use-session-working.js +16 -0
- package/dist/react/use-session-working.js.map +1 -1
- package/dist/react/use-session.d.ts +28 -1
- package/dist/react/use-session.d.ts.map +1 -1
- package/dist/react/use-session.js +76 -12
- package/dist/react/use-session.js.map +1 -1
- package/package.json +33 -6
package/dist/kortix.global.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var Kortix=(()=>{var ei=Object.defineProperty;var OS=Object.getOwnPropertyDescriptor;var DS=Object.getOwnPropertyNames;var jS=Object.prototype.hasOwnProperty;var $S=(e,t)=>{for(var n in t)ei(e,n,{get:t[n],enumerable:!0})},LS=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of DS(t))!jS.call(e,s)&&s!==n&&ei(e,s,{get:()=>t[s],enumerable:!(r=OS(t,s))||r.enumerable});return e};var US=e=>LS(ei({},"__esModule",{value:!0}),e);var yU={};$S(yU,{ABORT_REASONS:()=>EP,ABORT_REASONS_NOT_YET_EMITTED:()=>_j,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>pi,ACTIVE_INSTANCE_COOKIE:()=>Or,ANALYTICS_UNAVAILABLE_CODE:()=>ui,ATTACHMENT_PART_REF_PREFIX:()=>XP,ApiError:()=>_,AuthError:()=>oe,BillingError:()=>et,CONNECTION_FAULT_GRACE_MS:()=>ix,CONNECTOR_POLL_FIRST_DELAY_MS:()=>HP,CONNECTOR_POLL_INTERVAL_MS:()=>YP,CONNECTOR_POLL_WINDOW_MS:()=>zP,CONTEXT_TOOLS:()=>U_,COST_MARKUP:()=>pf,ConnectorApprovalPendingError:()=>fs,ConnectorCallError:()=>jn,ConnectorPageLimitError:()=>ys,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>F_,DEFAULT_NOTIFICATION_PREFERENCES:()=>DR,DEFAULT_TRANSCRIPT_OPTIONS:()=>Cm,DESTRUCTIVE_PHASES:()=>KP,FEATURE_DISABLED_CODE:()=>Yr,FEATURE_FLAG_KEYS:()=>fw,FEATURE_NOT_SUPPORTED_CODE:()=>ai,FILE_VERBS:()=>gt,FileExistsError:()=>sn,HeadlessAuthError:()=>Jt,HostBoundaryError:()=>$r,IMPERSONATION_HEADER:()=>ey,INBOX_NOTIFICATION_KINDS:()=>OR,INBOX_OBSERVATION_MAX_MS:()=>Ko,INITIAL_SETTLED_CONNECTION:()=>SL,INSTANCE_SCOPED_ROUTES:()=>MP,KNOWN_TOOL_KINDS:()=>ky,KORTIX_TRANSCRIPT_SCHEMA:()=>Ee,KortixMemberError:()=>ft,MAX_PROMPT_ATTACHMENTS_BYTES:()=>lk,MAX_PROMPT_ATTACHMENT_BYTES:()=>tl,MAX_PROMPT_ATTACHMENT_FILES:()=>by,MEMORY_VERBS:()=>MD,MODEL_NOT_SERVABLE_CODE:()=>ci,NO_GROUP_ACTIVITY_TOOLS:()=>wh,OPTIMISTIC_ABORT_MAX_MS:()=>Bo,OPTIMISTIC_COMPACTION_MAX_MS:()=>jL,OPTIMISTIC_RECEIPT_MAX_MS:()=>Fo,PERSISTED_QUERY_CACHE_VERSION:()=>hY,PLUMBING_TOOLS:()=>Z_,PREVIEW_PROBE_TIMEOUT_MS:()=>gL,PROJECT_ACTIONS:()=>X,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>Vk,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>Wk,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>Ly,PROVISION_IN_FLIGHT_CODE:()=>li,PublicSessionShareError:()=>Cs,REVIEW_CONTROL_ACTIONS:()=>JA,RUNTIME_NOT_READY_MARKERS:()=>Ej,RUNTIME_PERMISSION_CAPABILITIES:()=>UR,RUNTIME_PERMISSION_REPLIES:()=>LR,RequestTooLargeError:()=>_t,RuntimeNotReadyError:()=>nn,SANDBOX_FS_ROOTS:()=>fo,SANDBOX_PORTS:()=>Ye,SERVER_COMPACTION_REVALIDATE_MS:()=>ux,SERVER_OBSERVATION_MAX_MS:()=>No,SESSION_LIST_STATUS:()=>zL,SESSION_LOG_MINOR:()=>Pe,SESSION_LOG_SCHEMA:()=>ue,SESSION_NOTICE:()=>XL,STANDALONE_TOOLS:()=>kh,STREAM_OBSERVATION_MAX_MS:()=>bn,SandboxNotReadyError:()=>Dr,SessionNotReadyError:()=>Ct,SessionStartError:()=>ks,TRIGGER_CONTROL_ACTIONS:()=>YA,TURN_END_LEDGER_LAG_MS:()=>TL,TURN_ERROR_CODES:()=>lh,WAKE_ESCALATION_COOLDOWN_MS:()=>KL,WAKE_MAX_RESTARTS:()=>NL,WAKE_NO_PROGRESS_MS:()=>FL,WIRE_ID_BACKDATE_MS:()=>io,WIRE_ID_CLOCK_TOLERANCE:()=>at,WIRE_ID_TIME_MASK:()=>ze,WIRE_ID_TIME_SCALE:()=>Zt,WIRE_MESSAGE_ID:()=>Hh,__getConfigResolver:()=>KS,__setConfigResolver:()=>NS,abortErrorReason:()=>Pj,acceptAccountInvite:()=>rs,acceptAccountInviteAndLand:()=>Ui,acceptInvite:()=>Xj,accountInviteLanding:()=>py,actReviewItem:()=>sd,activateConnection:()=>uc,addComputerToProject:()=>gc,addGroupMembers:()=>Mp,addMarketplaceSource:()=>Ud,advanceWakeEscalation:()=>GL,allDescendantIds:()=>z_,appendPreviewToken:()=>kf,approveProjectAccessRequest:()=>ya,approveTask:()=>VT,archiveProject:()=>Dn,assignTicket:()=>eC,attachGroupToProject:()=>va,authMfa:()=>no,authUser:()=>Zs,authenticatedFetch:()=>$,authenticatedRequest:()=>Ln,authorizePreviewUrl:()=>dL,backendApi:()=>l,bindSlackIdentity:()=>xA,bindTeamsIdentity:()=>SA,brokerProjectSecretRequest:()=>Ua,browserKeyValueStorage:()=>sL,buildInstancePath:()=>DP,buildPresentationTemplateImageUrl:()=>hL,buildPresentationTemplatePdfUrl:()=>yL,buildPreviewAuthEndpoint:()=>wf,buildPublicTemplateUrl:()=>q$,buildRuntimePresentationConversionUrl:()=>ox,buildSandboxTemplate:()=>Hc,buildScrapeFailureResults:()=>nP,buildStaticFileHealthPreviewUrl:()=>JI,buildStaticFileLocalUrl:()=>zI,buildStaticFilePreviewUrl:()=>YI,buildStaticFileServicePath:()=>Lb,buildTunnelEventStreamUrl:()=>N0,buildWebProxyUrl:()=>tE,bulkActReviewItems:()=>od,bulkDeletePolicies:()=>iv,bulkImportPolicies:()=>av,burstSummary:()=>zm,burstSummaryLabel:()=>sO,callConnector:()=>wt,canManageBilling:()=>Hy,canOfferTopup:()=>pA,cancelAccountDeletion:()=>Vv,cancelAccountInvite:()=>Di,cancelSandbox:()=>Vj,cancelSandboxUpdate:()=>d$,cancelScheduledChange:()=>Du,cancelSubscription:()=>Eu,changeRequestControlsFrom:()=>th,checkAccessEmail:()=>A$,childMapByParent:()=>VM,claimComputer:()=>h$,claimNext:()=>l_,claimPerSeatBilling:()=>yA,claimWarmProjectSession:()=>Dl,classifyPart:()=>Bm,classifyPreviewProbeStatus:()=>sx,classifyPtyClose:()=>nb,classifySessionLogMessage:()=>qx,classifyTurn:()=>Ro,cleanErrorMessage:()=>ZM,cleanResultSnippet:()=>cO,cleanWorkerOutput:()=>vD,clearImpersonationSession:()=>fi,clearKortixAppViewerCache:()=>eS,clearModelDefault:()=>yu,clearSessionFresh:()=>wk,closeChangeRequest:()=>fl,closeMilestone:()=>TC,collectTurnParts:()=>BM,commentTicket:()=>nC,commitSessionChanges:()=>bl,compactionExpiryAtMs:()=>LL,compactionTurnInfo:()=>oO,compareMessagesForDisplay:()=>LM,compareSemver:()=>uE,completeInFlight:()=>u_,completeSlackInstall:()=>Vu,completeTeamsInstall:()=>Hu,composerSelectableAgents:()=>Ff,computeStatusFromPart:()=>cf,configureAutoTopup:()=>Uu,configureKortix:()=>Gr,confirmCheckoutSession:()=>Cu,connectEmail:()=>tp,connectSlack:()=>Gu,connectionFromHealth:()=>xL,connectionIsFaulted:()=>PL,connectionSharedWithEveryone:()=>Fw,connectorConnect:()=>fy,connectorFinalize:()=>yy,connectorHeadline:()=>z$,contextLabelForTool:()=>hO,contextToolSummary:()=>KE,contextToolTrigger:()=>BE,convertPresentationToGoogleSlides:()=>rR,convertRuntimePresentation:()=>bL,copyFile:()=>gr,costExportUrl:()=>Nu,countLiveInboxPrompts:()=>IL,countReviewItemsBySegment:()=>$A,createAccount:()=>wi,createAccountAuditWebhook:()=>Rd,createAccountSecretResource:()=>Ha,createAccountToken:()=>fd,createApp:()=>Kd,createAppAccessSession:()=>zd,createAppDeployment:()=>Qd,createAppToken:()=>Gd,createAppVolume:()=>mg,createAppVolumeSnapshot:()=>bg,createArtifactKind:()=>FO,createAssignment:()=>Xp,createAuditWebhook:()=>Lv,createBackup:()=>t$,createCheckoutSession:()=>Tu,createConnector:()=>Rc,createConnectorLinkInfoCache:()=>V$,createFile:()=>dr,createGatewayKey:()=>_p,createGroup:()=>Tp,createHttpSessionSyncController:()=>Jx,createInstance:()=>m$,createKortix:()=>o_,createKortixPty:()=>um,createKortixSession:()=>so,createMarketplaceInstallSession:()=>uR,createMilestone:()=>vC,createModelVisibility:()=>RS,createOAuthClient:()=>Hp,createPerSeatCheckout:()=>fA,createPersistedQueryCache:()=>rL,createPolicy:()=>rv,createPortalSession:()=>Iu,createProject:()=>Yi,createProjectAgent:()=>dC,createProjectCliToken:()=>Pd,createProjectRepo:()=>zi,createProjectResourceGrant:()=>Ia,createProjectSession:()=>vt,createProjectSkill:()=>ta,createProjectTrigger:()=>su,createPromptAttachmentController:()=>Rm,createRole:()=>Fp,createSSEStream:()=>K0,createSandbox:()=>Fj,createSandboxShare:()=>ad,createSandboxTemplate:()=>Gc,createSavedCopyStore:()=>Kk,createScimToken:()=>pv,createServiceAccountApi:()=>Ov,createSessionPrompt:()=>Gn,createSessionPublicShare:()=>El,createSessionQueue:()=>a_,createSessionReminder:()=>ud,createSsoGroupMapping:()=>kv,createTask:()=>qT,createTicket:()=>QT,createTunnelEventStream:()=>B0,createWarmSessionPool:()=>M0,currentSavedCopyStore:()=>wl,declineAccountInvite:()=>Fi,declineInvite:()=>Zj,deleteAccountImmediately:()=>Hv,deleteAccountSecretResource:()=>Ja,deleteApp:()=>qd,deleteAppDeployment:()=>rg,deleteAuditWebhook:()=>Fv,deleteBackup:()=>r$,deleteConnector:()=>Cc,deleteConnectorCredential:()=>jc,deleteCredential:()=>jC,deleteDriveFile:()=>TR,deleteEnv:()=>am,deleteFile:()=>Ot,deleteGatewayBudget:()=>hp,deleteGitHubInstallation:()=>da,deleteGroup:()=>Ip,deleteInstance:()=>f$,deleteKortixProject:()=>xC,deleteMilestone:()=>IC,deleteOAuthClient:()=>Jp,deletePersonalProjectSecret:()=>Ga,deletePolicy:()=>ov,deleteProjectAgent:()=>mC,deleteProjectProviderOAuth:()=>Na,deleteProjectResourceGrant:()=>Ea,deleteProjectSecret:()=>Ba,deleteProjectSession:()=>Hl,deleteProjectTrigger:()=>iu,deletePromptAttachment:()=>Gt,deleteRole:()=>Bp,deleteSandboxTemplate:()=>Vc,deleteServiceAccountApi:()=>jv,deleteSessionPrompt:()=>Kl,deleteSessionReminder:()=>Es,deleteSessionReminders:()=>dd,deleteSsoGroupMapping:()=>Av,deleteSsoProvider:()=>Sv,deleteTask:()=>HT,deleteTicket:()=>rC,describeAccountInvite:()=>Li,describeConnectorTool:()=>us,destroyAppMachine:()=>ug,destroyAppVolume:()=>yg,detachGroupFromProject:()=>Ta,detectLocalhostUrls:()=>Ob,directSubsessions:()=>e0,disableServiceAccountApi:()=>Dv,disconnectEmail:()=>np,disconnectGitHubApp:()=>eL,disconnectSlack:()=>zu,discoverConnectionOAuth2:()=>qw,discoverConnectionOAuth2Resource:()=>Gw,discoverConnectorAuth:()=>Tc,discoverLocalSandbox:()=>qj,dismissDriveConflict:()=>xR,downloadAccountAudit:()=>K$,downloadDriveFile:()=>wR,dropClientForUrl:()=>WC,dropPublicClientForUrl:()=>YC,editQueued:()=>m_,editSessionPrompt:()=>Bl,enqueue:()=>c_,ensurePmSession:()=>uC,ensurePreviewSessionCookie:()=>rx,ensureProjectConnectorConnection:()=>Nw,ensureSandbox:()=>NP,ensureWarmProjectSession:()=>Ol,env:()=>eb,exchangeCode:()=>Js,execInApp:()=>dg,exportAccountAudit:()=>Ad,extractGatewayErrorDetails:()=>Se,extractInstanceRoute:()=>yn,extractSkillBaseDir:()=>AP,extractSkillContent:()=>FD,extractSkillFiles:()=>kP,extractWorkerPreview:()=>TD,failInFlight:()=>p_,fallbackBusyRowAfterTurnId:()=>iD,familyForTool:()=>Oo,featureDisabledKey:()=>si,featureFlags:()=>zg,fetchAccountStateWithToken:()=>dA,fetchAccountsWithToken:()=>mw,fetchAttachmentPart:()=>oL,fetchCostExportCsv:()=>PA,fetchKortixAppViewer:()=>jf,fetchProjectArchive:()=>Zc,fetchProjectFileRaw:()=>ck,fetchProjectsForAccountWithToken:()=>kw,fetchSessionAttachment:()=>Hg,fileDownloadRequest:()=>yb,filePhase:()=>ED,fileVerb:()=>ID,files:()=>wb,finalizeAppArtifact:()=>Ds,finalizeConnectorSetupLink:()=>M$,findActiveTranscriptShare:()=>Yk,findFiles:()=>ur,findLastTextPart:()=>qM,findSessionAttachments:()=>_T,findText:()=>pr,fireProjectTrigger:()=>cu,fixSandboxWithAgent:()=>qc,flattenModels:()=>kS,flattenThought:()=>VO,forkAppVolume:()=>Pg,formatBillingErrorForUI:()=>ii,formatCost:()=>bD,formatDuration:()=>uf,formatJsonFailureOutput:()=>eO,formatMessageDay:()=>XO,formatMessageExact:()=>ZO,formatOpenCodeRuntimeError:()=>jj,formatRawOutput:()=>aO,formatRuntimeError:()=>FP,formatTokens:()=>_D,formatTranscript:()=>y_,freshSendHint:()=>uD,generateSessionId:()=>i_,getAccount:()=>ki,getAccountBranding:()=>vi,getAccountDeletionStatus:()=>Gv,getAccountState:()=>xu,getAccountStateMinimal:()=>Su,getActiveInstanceIdFromCookie:()=>$P,getAdminProviderAnalytics:()=>Xv,getAdminProviderDistribution:()=>zv,getAdminProviderFallback:()=>eR,getAdminRole:()=>Yv,getAgentCardLabel:()=>B_,getAgentConfig:()=>iA,getAgentPersona:()=>fC,getAllVersions:()=>l$,getAnsweredQuestionParts:()=>WM,getApp:()=>Ms,getAppAccess:()=>Vd,getAppAuthEnv:()=>Wd,getAppDeployment:()=>Zd,getAppDeploymentLogs:()=>eg,getApprovalLink:()=>lR,getAuthToken:()=>Bt,getAuthTokenWithRetry:()=>Dw,getAutoTopupSettings:()=>Lu,getAutoTopupSetupStatus:()=>mA,getBillingCreditBreakdown:()=>Au,getBillingTierConfigurations:()=>Ru,getBillingTransactionsSummary:()=>ku,getBillingUsageHistory:()=>vu,getChangeRequest:()=>ul,getChangeRequestDiff:()=>pl,getChangeRequestMergePreview:()=>dl,getChildSessionError:()=>nM,getChildSessionId:()=>kr,getChildSessionToolParts:()=>rM,getClient:()=>lt,getClientForUrl:()=>Me,getConnectStatus:()=>Oc,getConnectionOAuth2Application:()=>Bw,getConnectionOAuth2Status:()=>zw,getConnectionPolicies:()=>Jw,getConnectorCatalog:()=>qt,getConnectorConfig:()=>kc,getConnectorPolicies:()=>Sc,getConnectorSetupLink:()=>I$,getCostSummary:()=>_A,getCurrentInstanceIdFromPathname:()=>jP,getCurrentInstanceIdFromWindow:()=>wj,getCurrentProject:()=>bm,getDefaultAccountState:()=>Pu,getDiagnostics:()=>aM,getDirectory:()=>K_,getDiscoverConnector:()=>ms,getDiscoverIntegration:()=>nk,getDriveFileUrl:()=>xg,getEmailInstallation:()=>Zu,getEmailMode:()=>ep,getEnterpriseDemo:()=>Kv,getFileStatus:()=>lr,getFileWithDir:()=>$m,getFilename:()=>N_,getFolderAccess:()=>yR,getFullChangelog:()=>BP,getGatewayBreakdown:()=>dp,getGatewayBudgets:()=>fp,getGatewayErrors:()=>mp,getGatewayKeys:()=>bp,getGatewayLog:()=>lp,getGatewayOverview:()=>up,getGatewayRoutingPolicy:()=>sp,getGatewaySeries:()=>pp,getGatewaySessions:()=>gp,getGitHubAppStatus:()=>J$,getGitHubInstallation:()=>sa,getGoogleAuthUrl:()=>nR,getGroup:()=>Rp,getHiddenToolParts:()=>QE,getImpersonationSession:()=>ry,getInvite:()=>Qj,getJustavpsServerTypes:()=>g$,getKortixProject:()=>bC,getKortixProjectBySession:()=>_C,getKortixPtyWebSocketUrl:()=>gm,getLatestSandboxVersion:()=>c$,getMaintenanceConfig:()=>L$,getManagedGitBackend:()=>ga,getManagedGitStatus:()=>Pw,getMarketplaceCatalogItem:()=>jd,getMarketplaceCatalogItemFile:()=>$d,getMfaRequired:()=>gv,getMilestone:()=>kC,getMobileClientPolicy:()=>Tm,getModelDefaults:()=>mu,getNotificationPreferences:()=>vg,getOAuthClient:()=>Vp,getOAuthConsentRequest:()=>T$,getOpenCodeConfigInvalidError:()=>Tj,getPartText:()=>YE,getPatPolicy:()=>Iv,getPermissionForTool:()=>cM,getProject:()=>Cn,getProjectActivity:()=>yC,getProjectCommit:()=>ol,getProjectCommitDiff:()=>il,getProjectDetail:()=>In,getProjectDrive:()=>fR,getProjectFileHistory:()=>al,getProjectGitToken:()=>Hi,getProjectLlmCatalog:()=>En,getProjectLlmCatalogProviders:()=>hw,getProjectModelAccess:()=>zn,getProjectModelPicker:()=>Mn,getProjectSandboxHealth:()=>$n,getProjectSandboxProviderTransition:()=>xw,getProjectSession:()=>qn,getProjectSessionConfigState:()=>Yl,getProjectSessionScope:()=>Ql,getProrationPreview:()=>ju,getProviders:()=>Lj,getProxyBaseUrl:()=>QI,getPublicClientForUrl:()=>HC,getPublicMarketplaceItem:()=>w$,getPublicMarketplaceItemFile:()=>k$,getPublicSessionShare:()=>sR,getPublicSessionShareMessages:()=>oR,getPublicShareByToken:()=>j$,getPublicTemplate:()=>G$,getQuestionForTool:()=>lM,getReferralCode:()=>IA,getReferralStats:()=>OA,getRetryInfo:()=>PD,getRetryMessage:()=>xD,getReviewItem:()=>nd,getRolePermissions:()=>Lp,getRoleUsage:()=>Up,getRuntimeConfigInvalidError:()=>Uo,getSSHConnection:()=>o$,getSandbox:()=>Uj,getSandboxById:()=>Nj,getSandboxPortUrl:()=>$j,getSandboxProvisionStatus:()=>b$,getSandboxProvisionStreamUrl:()=>_$,getSandboxUpdateStatus:()=>a$,getSandboxUrl:()=>_f,getSandboxUrlForExternalId:()=>Ce,getSecretSetupLink:()=>O$,getServerHealth:()=>yo,getServiceLogs:()=>NC,getSessionAudit:()=>jl,getSessionCost:()=>hD,getSessionCostRecord:()=>Yn,getSessionDrives:()=>ah,getSessionHealth:()=>Sm,getSessionLogPage:()=>Ul,getSessionMessageAuthors:()=>tu,getSessionModelUsage:()=>nu,getSessionOpenBundle:()=>zk,getSessionOversight:()=>yv,getSessionParticipants:()=>vl,getSessionPolicy:()=>vv,getSessionPreviewCandidates:()=>Cl,getSessionProviderSecretPool:()=>ec,getSessionTranscript:()=>$l,getSessionTranscriptSync:()=>Ll,getSessionTurn:()=>Fl,getSessionWatch:()=>Rl,getShellModePart:()=>AD,getSlackChannelFile:()=>Ju,getSlackInstallation:()=>qu,getSlackManifest:()=>Yu,getSlackMode:()=>Wu,getSsoProvider:()=>bv,getStaticFileHealthPath:()=>Ub,getSupabaseAccessToken:()=>is,getSupabaseAccessTokenWithRetry:()=>my,getTask:()=>NT,getTaskStatus:()=>BT,getTemplate:()=>pR,getTicket:()=>zT,getToolInfo:()=>sM,getToolPrimaryArg:()=>So,getTranscriptFilename:()=>h_,getTurnCost:()=>Lo,getTurnError:()=>mD,getTurnErrorDetails:()=>yD,getTurnErrorRawText:()=>fD,getTurnStatus:()=>lf,getUsageRollup:()=>Fu,getUserRolesWithToken:()=>F$,getVersionDiff:()=>cl,getWebPushPublicKey:()=>Tg,getWorkingState:()=>dD,grantAccountSecretResource:()=>Qa,grantSandboxProjectAccess:()=>zj,grantSecretToAgent:()=>cA,groupMessagesIntoTurns:()=>FM,groupShowSegments:()=>rf,groupSteps:()=>ef,hasDiffs:()=>SD,hasLocalhostUrls:()=>WI,hasPreviewTarget:()=>$b,hasRetryingAssistantTurn:()=>Wm,heartbeatGapEvent:()=>ab,holdSessionPrompts:()=>Wl,humanizeReviewActionPath:()=>Ap,humanizeSearchQuery:()=>_r,humanizeToolName:()=>Fm,impersonationHeaders:()=>yi,importSsoProviderFromMetadata:()=>Pv,inboxObservationSupersedes:()=>CL,initialWakeEscalationState:()=>vf,inputPath:()=>Xe,installTemplate:()=>dR,interruptSessionPrompt:()=>ql,invalidateTokenCache:()=>as,inviteAccountMember:()=>Mi,inviteProjectMember:()=>xa,inviteRepoCollaborator:()=>Wi,isAbortError:()=>Mr,isAdminBypassEnabled:()=>ay,isAgentPart:()=>qE,isAppRouteUrl:()=>Mb,isAttachment:()=>zE,isAttachmentPartRef:()=>ZP,isAuthFailure:()=>Ut,isBillingError:()=>oi,isCompactionPart:()=>GE,isConfigured:()=>Wr,isContextTool:()=>NE,isDestructivePhase:()=>i$,isEmptyConversation:()=>Xx,isEmptyShowPart:()=>Bs,isErrorOutput:()=>YM,isExternalUrl:()=>sE,isFeatureDisabledError:()=>ri,isFilePart:()=>Lm,isImpersonationSessionLive:()=>ty,isInstanceDetailPath:()=>xj,isInstanceScopedAppPath:()=>OP,isInternalLocalhostUrl:()=>eE,isInvisibleActivityPart:()=>Kg,isInviteSent:()=>Rw,isLastUserMessage:()=>pD,isLegacyMigratedSession:()=>px,isManagedGithubProject:()=>yw,isNoGroupActivityTool:()=>Ng,isOfferedModel:()=>Xo,isOpenCodeConfigInvalidError:()=>Cj,isPaintableSavedCopy:()=>My,isPatchPart:()=>VE,isPersistableQueryKey:()=>nL,isPreviewUrl:()=>ZI,isProxiableLocalhostUrl:()=>Fb,isQuestionTool:()=>Fg,isReasoningPart:()=>ke,isRetryableTurnError:()=>J_,isRuntimeConfigInvalidError:()=>LP,isRuntimeNotReadyResponse:()=>UP,isRuntimeReady:()=>xm,isRuntimeStartingError:()=>Dj,isSandboxNotReadyError:()=>hn,isSelectableAgent:()=>Gs,isServerReachable:()=>_m,isSessionAttachmentRef:()=>dT,isSessionFresh:()=>Pl,isSessionStartError:()=>tA,isShellActivityTool:()=>aT,isShellMode:()=>xP,isShortOutput:()=>RD,isShowContentUnavailable:()=>jR,isShowPayloadEmpty:()=>Qn,isSnapshotPart:()=>WE,isStandaloneActivityTool:()=>Bg,isStepPart:()=>HE,isSubdomainPreviewUrl:()=>Lr,isTextPart:()=>Oe,isToolPart:()=>re,isToolPartHidden:()=>XE,isTurnErrorCode:()=>Mg,isUnderSandboxRoot:()=>ym,isWebProxyUrl:()=>rE,isWireIdAheadOf:()=>zh,kortixAppViewerToken:()=>tS,kortixBinding:()=>nS,kortixPty:()=>ob,kortixToken:()=>$f,leaveAccount:()=>Bi,linkGitHubInstallation:()=>ua,linkRepository:()=>na,listAccountAudit:()=>wd,listAccountAuditWebhooks:()=>vd,listAccountInvites:()=>Oi,listAccountMembers:()=>Ei,listAccountResourceGrants:()=>tv,listAccountSecretResources:()=>Va,listAccountSessions:()=>Tv,listAccountTokens:()=>md,listAccounts:()=>Si,listActions:()=>cv,listAdminSandboxes:()=>Jv,listAgentIdentities:()=>jp,listAllConnections:()=>oc,listAppAgents:()=>Hd,listAppDeployments:()=>Xd,listAppMachines:()=>og,listAppVolumeSnapshots:()=>hg,listAppVolumes:()=>gg,listApps:()=>Nd,listAssignments:()=>Qp,listAuditEvents:()=>Nv,listAuditWebhooks:()=>$v,listBackups:()=>e$,listBillingTransactions:()=>wu,listChangeRequests:()=>ll,listChannelBindings:()=>RA,listColumns:()=>sC,listConnectSections:()=>ek,listConnectToolkits:()=>Zw,listConnections:()=>sc,listConnectorAccounts:()=>ps,listConnectorTools:()=>ls,listConnectors:()=>hc,listCostByProject:()=>bA,listCredentialEvents:()=>MC,listCredentials:()=>EC,listDiscoverConnectors:()=>gs,listDiscoverIntegrations:()=>tk,listDiscoverSections:()=>Mc,listDriveConflicts:()=>PR,listDriveFiles:()=>SR,listDriveFolder:()=>ih,listDriveVersions:()=>CR,listEnv:()=>om,listFeaturedMarketplaces:()=>Dd,listFields:()=>iC,listFiles:()=>cn,listFolderPrincipals:()=>_R,listGatewayLogs:()=>cp,listGitHubInstallations:()=>oa,listGitHubRepositories:()=>aa,listGitHubRepositoryBranches:()=>ca,listGroupMembers:()=>Ep,listGroupProjectGrants:()=>XA,listGroups:()=>vp,listKortixProjectSessions:()=>PC,listKortixProjects:()=>hC,listKortixPty:()=>lm,listLinkableGitHubInstallations:()=>ia,listManagedGitRepositories:()=>ma,listMarketplaceCatalogItems:()=>Md,listMarketplaceSources:()=>Ld,listMarketplaces:()=>Od,listMemberGroups:()=>ZA,listMemberProjectAccess:()=>ev,listMilestoneEvents:()=>AC,listMilestones:()=>wC,listMyAccountInvites:()=>$i,listNotifications:()=>kg,listOAuthClients:()=>Wp,listOAuthGrants:()=>hd,listPendingApprovals:()=>Ma,listPendingProjectInvites:()=>Sa,listPermissions:()=>ed,listPipedreamApps:()=>Ic,listPipedreamSections:()=>Ec,listPolicies:()=>nv,listProjectAccess:()=>ba,listProjectAccessRequests:()=>fa,listProjectAgentIdentities:()=>$p,listProjectAgents:()=>pC,listProjectAudit:()=>kd,listProjectBranches:()=>rl,listProjectCliTokens:()=>_d,listProjectCommits:()=>sl,listProjectDirectory:()=>Jc,listProjectFiles:()=>zc,listProjectGroupGrants:()=>Aa,listProjectPolicies:()=>Uc,listProjectProviderOAuth:()=>Fa,listProjectReminders:()=>gd,listProjectResourceGrants:()=>Ca,listProjectSandboxTemplates:()=>Nc,listProjectSandboxes:()=>Yc,listProjectSecrets:()=>ja,listProjectSessions:()=>At,listProjectSessionsPage:()=>kl,listProjectSnapshots:()=>Kc,listProjectTriggerEventApps:()=>uu,listProjectTriggerEventTypes:()=>lu,listProjectTriggers:()=>ru,listProjects:()=>St,listProjectsForAccount:()=>Gi,listPublicMarketplaceItems:()=>x$,listPublicMarketplaces:()=>S$,listReferrals:()=>DA,listReviewItems:()=>td,listRoles:()=>Dp,listSandboxProjectMembers:()=>Yj,listSandboxShares:()=>id,listSandboxes:()=>Bj,listScimTokens:()=>uv,listServiceAccountsApi:()=>Mv,listServiceTemplates:()=>FC,listServices:()=>UC,listSessionConnectRequests:()=>Xw,listSessionCosts:()=>Bu,listSessionDrives:()=>MR,listSessionPrompts:()=>Nl,listSessionProviderSecretPools:()=>tc,listSessionPublicShares:()=>Il,listSessionReminders:()=>ld,listSessionsNeedingInput:()=>Oa,listSignedInDevices:()=>aR,listSsoGroupMappings:()=>wv,listTaskEvents:()=>KT,listTasks:()=>FT,listTemplates:()=>cC,listTicketEvents:()=>JT,listTickets:()=>YT,loadHttpSessionHistory:()=>zx,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>Vm,looksLikeHtml:()=>dO,looksLikeJsonPayload:()=>iO,makeDriveFolder:()=>vR,mapApiReviewItem:()=>HA,markInstanceError:()=>y$,markNotificationsRead:()=>Ag,markSessionFresh:()=>Kn,maxWireIdClock:()=>tm,memoryRelPath:()=>OD,mergeBurstSteps:()=>tf,mergeChangeRequest:()=>ml,messageCreatedAt:()=>HO,messageTime:()=>dP,migrateAdminSandboxProvider:()=>Zv,mintWireMessageId:()=>ao,mintWireMessageIdAbove:()=>nm,mkdir:()=>dn,modelInDefaultView:()=>TS,modelRefToKey:()=>pS,moveDriveFile:()=>RR,narrateFailedStep:()=>Zm,narrateStep:()=>Xm,narrationToolName:()=>Cr,narrowChatEvent:()=>cb,newestWireIdClock:()=>Jh,nextConnectorPollDelay:()=>Y$,normalizeActivityToolName:()=>ye,normalizeAppPathname:()=>vj,normalizeExternalInput:()=>oE,normalizeName:()=>ee,normalizeToolName:()=>Um,notifyHostSignal:()=>gx,openChangeRequest:()=>gl,openEventStream:()=>po,openStressTestStream:()=>B$,paginateConnector:()=>Lc,parseBillingError:()=>Rn,parseEmbeddedFailure:()=>lO,parseFlagOverride:()=>xT,parseJsonFailure:()=>X_,parseLocalhostUrl:()=>hr,parseMemoryView:()=>DD,parseOpenCodeErrorPayload:()=>Rj,parsePresentationOutput:()=>LD,parseProxyHop:()=>Pm,parseQuestionAnswersFromOutput:()=>mf,parseReadOutput:()=>UD,parseRuntimeErrorPayload:()=>bf,parseScrapeInputUrls:()=>tP,parseScrapeOutput:()=>rP,parseSubdomainUrl:()=>km,parseTaskRows:()=>CD,parseWebProxyUrl:()=>nE,parseWebSearchOutput:()=>Jm,partOutcome:()=>Hm,patchKortixProject:()=>SC,patchVerb:()=>$D,pickerProviderList:()=>wS,pipedreamConnect:()=>vc,pipedreamConnectConnection:()=>fc,pipedreamFinalize:()=>$c,pipedreamFinalizeConnection:()=>yc,platformConfig:()=>v,pollConnectionOAuth2DeviceAuthorization:()=>Yw,pollProjectProviderOAuth:()=>os,previewGatewayRoute:()=>ap,previewMfaRequired:()=>mv,previewSlackIdentity:()=>wA,previewTeamsIdentity:()=>kA,probeEffectivePermission:()=>qp,probeEffectivePermissions:()=>Gp,probePreviewPort:()=>mL,projectArchiveRequest:()=>el,projectCompacting:()=>$L,projectConfigAgentsToOpenCodeAgents:()=>lS,projectConfigAgentsToRuntimeAgents:()=>Uf,projectSessionConnection:()=>_L,projectSessionForRuntimeId:()=>t0,projectSessionStartSeed:()=>du,projectWorking:()=>EL,provisionProject:()=>Ji,provisionProjectStream:()=>_w,provisionProjectWithToken:()=>Aw,proxyLocalhostUrl:()=>wm,proxyUrlToInternal:()=>XI,purchaseCredits:()=>$u,putConnectionOAuth2Application:()=>Kw,rawErrorText:()=>br,reactivateSandbox:()=>Hj,reactivateSubscription:()=>Mu,readBlob:()=>un,readDriveFile:()=>kR,readFile:()=>ln,readKortixMember:()=>zo,readProjectFile:()=>Xc,reasoningIsRunning:()=>Do,rebuildProjectSnapshot:()=>Bc,reconcileConnection:()=>ic,reconcileMemberConnection:()=>ac,reconcileServices:()=>BC,recordPlatformLogout:()=>R$,recoverLinkResults:()=>Io,refreshReferralCode:()=>EA,refreshSession:()=>Qt,registerAppArtifact:()=>Os,registerConnectionOAuth2Client:()=>Ww,registerDeviceToken:()=>Sg,registerService:()=>qC,registerWebPushSubscription:()=>Cg,rejectProjectAccessRequest:()=>ha,relativizePath:()=>iM,reloadProjectSessionConfig:()=>zl,reloadProjectSessionConfigStream:()=>Jl,removeAccountAuditWebhook:()=>Cd,removeAccountBrandingAsset:()=>Ci,removeAccountMember:()=>Ni,removeGroupMember:()=>Op,removeKortixPty:()=>dm,removeMarketplaceSource:()=>Fd,removeQueued:()=>g_,renameConnection:()=>dc,renameFile:()=>fr,renameSandbox:()=>Kj,reopenChangeRequest:()=>yl,reopenMilestone:()=>CC,reorderQueued:()=>f_,replaceColumns:()=>oC,replaceFields:()=>aC,replaceProjectRepository:()=>ra,replaceTemplates:()=>lC,requestAccountDeletion:()=>Wv,requestChangesOnChangeRequest:()=>hl,requestProjectAccess:()=>vw,requestProjectConnector:()=>Ed,requestProjectSecret:()=>Id,requestTopUp:()=>gA,requireKortixMember:()=>oS,resendAccountInvite:()=>ji,resendPendingProjectInvite:()=>ka,resetAccountBranding:()=>Ii,resetClient:()=>VC,resetGatewayRoutingPolicy:()=>ip,resetPassword:()=>Qs,resetPublicClient:()=>zC,resetSandboxUpdateStatus:()=>p$,resolveApproval:()=>Da,resolveComposerAgent:()=>cS,resolveComposerModel:()=>ES,resolveConnectorStart:()=>H$,resolveModelDefault:()=>IS,resolvePublicShareUrl:()=>Hk,resolveScrapeResults:()=>gO,resolveWorkingTurn:()=>af,resolvedPlan:()=>uA,restartAppMachine:()=>lg,restartProjectSession:()=>Wn,restartSandbox:()=>Gj,restoreAppVolume:()=>_g,restoreBackup:()=>n$,restoreDriveVersion:()=>IR,retryAccountSecretResource:()=>za,retryFailed:()=>d_,retrySessionPrompt:()=>Gl,revealCredential:()=>DC,reviewItemTarget:()=>kp,reviewSegmentForStatus:()=>eh,reviewVerdictAllowed:()=>QA,reviewVerdictForStatus:()=>LA,revokeAccountSecretResourceGrant:()=>Xa,revokeAccountSession:()=>Cv,revokeAccountToken:()=>yd,revokeAssignment:()=>Zp,revokeConnection:()=>lc,revokeGatewayKey:()=>Pp,revokeOAuthGrant:()=>bd,revokePendingProjectInvite:()=>wa,revokeProjectAccess:()=>Pa,revokeProjectCliToken:()=>xd,revokeSandboxProjectAccess:()=>Jj,revokeSandboxShare:()=>cd,revokeScimToken:()=>dv,revokeSessionPublicShare:()=>Ml,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>sg,rootRuntimeSession:()=>dx,rotateAccountSecretResource:()=>Ya,rotateOAuthClientSecret:()=>zp,runConnector:()=>hs,runGatewayPlayground:()=>xp,runProjectProviderOAuthFlow:()=>Ew,runtimeSessionsOf:()=>qo,runtimeSupports:()=>Rb,sanitizePtyChunk:()=>sb,saveGitHubInstallation:()=>la,savedCopyEmptyRoot:()=>Qx,scaleApp:()=>pg,scheduleDowngrade:()=>Ou,searchConnectorTools:()=>rc,searchProjectFiles:()=>Qc,segmentTurn:()=>nf,selectableProjectAgents:()=>wT,sendMagicLink:()=>Hs,sendReferralEmails:()=>jA,serverCompactionRevalidateAtMs:()=>UL,serviceAction:()=>KC,sessionConnectionLabel:()=>QL,sessionListStatus:()=>JL,sessionLogActivityText:()=>Lx,sessionLogAnsweredQuestionCall:()=>Bx,sessionLogBurstRunning:()=>Fx,sessionLogBurstSteps:()=>$x,sessionLogBurstSummary:()=>Ux,sessionLogCallStatus:()=>Ex,sessionLogOfV1Rows:()=>wx,sessionLogOpenCall:()=>Nx,sessionLogPromptMessage:()=>Mx,sessionLogRetrying:()=>Mf,sessionLogShowGroupCall:()=>Kx,sessionLogThreadMetrics:()=>Gx,sessionLogTurnSegments:()=>Dx,sessionLogTurns:()=>Vo,sessionModelPin:()=>eu,sessionParentId:()=>Gk,sessionPromptActions:()=>Xk,sessionStartKey:()=>rA,setAccountSecretResourceAccess:()=>Za,setActiveInstanceCookie:()=>kj,setAdminBypass:()=>iy,setAdminProviderDistribution:()=>Qv,setAdminProviderFallback:()=>tR,setAgentScope:()=>hu,setBootstrapAuthToken:()=>Ow,setCachedAuthToken:()=>Mw,setConnectionPolicies:()=>Qw,setConnectorAuthorizationStrategy:()=>Pc,setConnectorCredential:()=>Dc,setConnectorCredentialMode:()=>_c,setConnectorName:()=>Ac,setConnectorPolicies:()=>wc,setConnectorSecretBinding:()=>rk,setConnectorSensitive:()=>xc,setDefaultConnection:()=>pc,setEnterpriseDemo:()=>Bv,setEnv:()=>im,setGatewayBudget:()=>yp,setGatewayRoutingPolicy:()=>op,setGitHubAppFromExisting:()=>X$,setGitHubAppPat:()=>Z$,setImpersonationSession:()=>XS,setMaintenanceConfig:()=>U$,setMemberSuperAdmin:()=>lv,setMfaRequired:()=>fv,setModelDefault:()=>fu,setPersonalProjectSecret:()=>qa,setProjectModelAccess:()=>Jn,setProjectModelEnablement:()=>sA,setProjectOnboardingComplete:()=>ea,setProjectOnboardingProfile:()=>ww,setProjectPolicies:()=>Fc,setProjectSecretStrategy:()=>La,setProjectSessionModel:()=>Zl,setProjectSessionScope:()=>Xl,setProjectSessionSharing:()=>Al,setProjectTriggersActivation:()=>au,setSavedCopyStore:()=>Bk,setSessionOversight:()=>hv,setSessionProviderSecretPool:()=>nc,setSessionWatch:()=>Tl,settleSessionConnection:()=>wL,setupSSH:()=>s$,shareConnection:()=>mc,shareFolder:()=>hR,shellActivityGroupLabel:()=>cT,shellExitCode:()=>yf,shouldAttachImpersonation:()=>sy,shouldHideResponsePart:()=>gD,shouldShowToolPart:()=>wo,shouldSuppressWorkingTurnBusy:()=>sD,showGroupItems:()=>sf,showTurnBusyIndicator:()=>of,signInWithPassword:()=>Vs,signInWithProvider:()=>zs,signInWithSso:()=>to,signOut:()=>ro,signOutDevice:()=>cR,signUp:()=>Ws,skillDocumentPath:()=>WD,skillInputDir:()=>BD,sortSessions:()=>HM,splitSessionLogTurnWork:()=>jx,splitTurnWork:()=>gf,splitUserParts:()=>JE,startApp:()=>tg,startAppMachine:()=>ag,startConnectionOAuth2Authorization:()=>Vw,startConnectionOAuth2DeviceAuthorization:()=>Hw,startConnectorSetupLink:()=>E$,startGitHubAppManifest:()=>Q$,startProjectProviderOAuth:()=>ss,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>gu,startSessionWithToken:()=>$$,startTask:()=>WT,stepLabel:()=>vr,stopApp:()=>ng,stopAppMachine:()=>cg,stopProjectSession:()=>Vn,stopSandbox:()=>Wj,storeGitHubUserToken:()=>pa,stripAnsi:()=>pM,stripInstancePrefix:()=>Sj,stripTrailingSlashes:()=>de,submitAccessRequest:()=>v$,submitDemoRequest:()=>N$,submitOAuthConsent:()=>C$,submitReviewItem:()=>rd,submitSecretSetupLink:()=>D$,subscribeToImpersonation:()=>ZS,supabaseClient:()=>dw,syncConnectors:()=>bc,syncSubscription:()=>hA,systemReload:()=>QC,toDaemonPath:()=>pt,toInstanceAwarePath:()=>Aj,toInternalUrl:()=>Nb,toSandboxAbsolutePath:()=>an,toToolView:()=>Km,toWorkspaceRelative:()=>hm,toolCallBlock:()=>Zn,toolCallMetadata:()=>Sh,toolInfo:()=>ko,toolKind:()=>le,toolViewModel:()=>CP,triggerControlsFrom:()=>zA,triggerSandboxUpdate:()=>u$,triggersRequest:()=>tb,turnEndCause:()=>lx,turnEndNotice:()=>DL,turnHasSteps:()=>GM,turnIsConfirmedActive:()=>aD,turnRendersQueued:()=>cD,turnRetryLabel:()=>ZL,unassignTicket:()=>tC,unregisterDeviceToken:()=>wg,unregisterWebPushSubscription:()=>Ig,unshareFolder:()=>bR,unwrapError:()=>he,updateAccountAuditWebhook:()=>Td,updateAccountBranding:()=>Ri,updateAccountMemberRole:()=>Ki,updateAccountName:()=>Ai,updateAgentConfig:()=>aA,updateApp:()=>Bd,updateAppAccess:()=>Yd,updateAppVolume:()=>fg,updateAuditWebhook:()=>Uv,updateChangeRequest:()=>_l,updateChannelBinding:()=>TA,updateConnectionCredential:()=>cc,updateEmailPolicy:()=>rp,updateExperimentalFeature:()=>Xi,updateFeatureFlag:()=>Qi,updateGroup:()=>Cp,updateKortixPty:()=>pm,updateMilestone:()=>RC,updateNotificationPreferences:()=>Rg,updateOAuthClient:()=>Yp,updatePassword:()=>Xs,updatePatPolicy:()=>Ev,updatePolicy:()=>sv,updateProject:()=>On,updateProjectAccess:()=>_a,updateProjectAgent:()=>gC,updateProjectDefaultAgent:()=>_u,updateProjectGroupGrant:()=>Ra,updateProjectSandboxProvider:()=>Zi,updateProjectSession:()=>Vl,updateProjectTrigger:()=>ou,updateRole:()=>Np,updateRolePermissions:()=>Kp,updateSandboxTemplate:()=>Wc,updateSessionPolicy:()=>Rv,updateSessionReminder:()=>Is,updateSessionReminders:()=>pd,updateTask:()=>GT,updateTemplateWarmPool:()=>Sw,updateTicket:()=>XT,updateTicketStatus:()=>ZT,updateUserMetadata:()=>eo,uploadAccountBrandingAsset:()=>Ti,uploadAppArtifactArchive:()=>Jd,uploadConnectorAttachment:()=>ds,uploadDriveFile:()=>AR,uploadFile:()=>pn,uploadNativeFile:()=>bb,uploadPromptAttachment:()=>Nn,uploadSessionAttachment:()=>Vg,uploadSlackChannelFile:()=>Qu,uploadTimeoutMsForBytes:()=>rn,upsertCredential:()=>OC,upsertProjectGitCredential:()=>Ka,upsertProjectSecret:()=>$a,upsertSsoProvider:()=>_v,validateProjectManifest:()=>Vi,validateReferralCode:()=>MA,validateToken:()=>qi,verifyGatewayProvider:()=>CA,verifyKortixToken:()=>aS,verifyOtp:()=>Ys,verifySsoDomain:()=>xv,wakeEscalationAttemptSummary:()=>YL,wakeEscalationNote:()=>VL,wakeProgressFingerprint:()=>BL,wireIdClock:()=>Et,wireIdClockAt:()=>en,wireIdClockDelta:()=>Mt,workedForLabel:()=>kD,workingExpiryAtMs:()=>ML,workingTurnDrawsBusyRow:()=>lD,writeActivityGroupLabel:()=>lT,writeFile:()=>mr,wsDomain:()=>Mo,wsFavicon:()=>pO,wsRootDomain:()=>uO});var FS={backendUrl:"",getToken:async()=>null},ti=null,qr=null;function NS(e){qr=e}function KS(){return qr}function Gr(e,t){t?.global!==!1&&(ti=e)}function v(){return qr?.()??ti??FS}function Wr(){return ti!==null||qr?.()!==void 0}function BS(e){return new Promise(t=>setTimeout(t,e))}async function Vr(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await BS(s)),i=await e(),i)return i;return i}var ni=12e4;function qS(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function zf(e,t,n=ni){let r=e instanceof Request?e.signal:t?.signal;if(qS(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function Hr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var _=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends _{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends _{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},_t=class extends _{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},GS="ENDPOINT_RETIRED";function K(e,t){let n=t?` ${t}`:"";return new _(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:GS})}var Yr="feature_disabled";function Jf(e){if(!(e instanceof _)||e.status!==403||e.code!==Yr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function ri(e){let t=Jf(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function si(e){let t=Jf(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Rn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new et(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function oi(e){return e instanceof et}function Ut(e){if(e instanceof oe)return!0;let t=e?.status;return t===401||t===403}function ii(e){if(!(e instanceof et))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Ae(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ve(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Ae())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function zr(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Ae())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Qf="request_deadline",WS=/^Request exceeded the \d+s server processing deadline$/,Xf=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Qf||WS.test(n),VS="git_mirror_unavailable",HS=/^git mirror is temporarily unavailable$/,YS=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===VS||HS.test(n);async function zS(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ve(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Ae();return{message:n,data:r}}function JS(e,t,n){return Xf(e,t,n)||YS(e,t,n)||e===501&&t?.code===ai||e===409&&(t?.code===ci||t?.code===li)||e===503&&(t?.code===ui||t?.code===pi)}async function Zf(e,t,n,r){let{message:s,data:o}=await zS(e,t),i=new _(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Xf(e.status,o,s)?Qf:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=Rn(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{v().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new _t(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!JS(e.status,o,s)&&v().onError?.(i,r),{error:i,success:!1}}var ey="X-Kortix-Impersonate",gi="kortix.impersonation",Pt=null,Jr=!1,di=new Set;function mi(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function ty(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function QS(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function ny(){for(let e of di)try{e()}catch{}}function ry(){return Jr||(Jr=!0,Pt=QS(mi()?.getItem(gi)??null)),Pt&&!ty(Pt)?(fi(),null):Pt}function XS(e){if(Jr=!0,!e){fi();return}Pt=e;try{mi()?.setItem(gi,JSON.stringify(e))}catch{}ny()}function fi(){Jr=!0;let e=Pt!==null;Pt=null;try{mi()?.removeItem(gi)}catch{}e&&ny()}function ZS(e){return di.add(e),()=>{di.delete(e)}}var ew=/(^|\/)admin\/(api|analytics)(\/|$)/;function sy(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!ew.test(t)}function yi(e){if(e!==void 0&&!sy(e))return{};let t=ry();return t?{[ey]:t.grantId}:{}}var _i=!1;function iy(e){_i=e}function ay(){return _i}function tw(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Qr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Ft(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function Xr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(tw))Ft(n,s,o);return n}function bi(e,t,n){let r={...t},s=v().clientVersion?.trim();s&&!Qr(r,"x-kortix-client-version")&&Ft(r,"X-Kortix-Client-Version",s),_i&&Ft(r,"x-kortix-admin-bypass","1");for(let[i,a]of Object.entries(yi(e)))Ft(r,i,a);let o=v().credentialHeader?.trim();return o?Qr(r,o)||Ft(r,o,n):Qr(r,"authorization")||Ft(r,"Authorization",`Bearer ${n}`),r}async function es(e,t){let n=await Zr();if(!n)throw new oe;return{headers:new Headers(bi(e,Xr(e,{headers:t}),n)),rejected:()=>Tn(n)}}function nw(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function oy(e,t,n,r,s){if(t instanceof Request){let c=new Headers(bi(t.url,Xr(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=bi(o,Xr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var cy=null;async function Pi(e){let t=await Vr(()=>v().getToken(),e);return t&&(cy=t),t}var Zr=Pi;function Tn(e=cy){e&&v().getToken.invalidate?.(e)}var hi=new Map;function rw(e){let t=hi.get(e);if(t)return t;let n=(async()=>(Tn(e),Zr({attempts:2,baseDelayMs:200})))().finally(()=>hi.delete(e));return hi.set(e,n),n}async function xt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=ni}=n,o=n.fetch??v().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:zf(e,t,s);if(i?.aborted)throw Ae();let a=await(i?ve(Zr(),i):Zr());if(!a)throw new oe;let c=r&&!nw(t)&&!Qr(Xr(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await oy(o,e,t,a,i);if(d.status!==401||!c)return d;let m=await rw(a);return!m||m===a?d:oy(o,p,t,m,i)}async function Fe(e,t,n,r){let s=await xt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new _(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var ly=()=>v().backendUrl||"",sw=new Set([502,503,504]),ow=e=>sw.has(e),uy=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},iw=e=>uy(e)||(e??"GET").toUpperCase()==="DELETE",aw=2,ts=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Ne(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await cw(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function cw(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Ae();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await uw(e,t,c,s,o,i,a);if(p instanceof oe)return{error:p,success:!1};if(!p.ok)return await Zf(p,a.activeController.signal,n,r);let d,m=p.headers.get("content-type");return m?.includes("application/json")?d=await ve(p.json(),a.activeController.signal):m?.includes("text/")?d=await ve(p.text(),a.activeController.signal):d=await ve(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return pw(c,e,t.method,n,r,s,a)}finally{ns(a)}}function ns(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function lw(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(ts(r))throw r}finally{ns(n)}}async function uw(e,t,n,r,s,o,i){let a=uy(t.method),c=iw(t.method),p=c?aw+1:1,d;for(let m=0;m<p;m++){m>0&&await zr(250*2**(m-1),t.signal??void 0);let g=m===0?o:new AbortController;i.activeController=g,t.signal?.aborted&&g.abort(),m>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,g.abort()},r));try{d=await ve(xt(e,{...t,headers:n,signal:g.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),g.signal)}catch(y){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),y instanceof oe)return new oe;if(i.didTimeout&&ts(y)&&!t.signal?.aborted&&c&&m<p-1){i.didTimeout=!1;continue}if(ts(y)||m===p-1)throw y;continue}if(!a||!ow(d.status)||m===p-1)return s||ns(i),d;await lw(d,g.signal,i)}return d}function pw(e,t,n,r,s,o,i){ns(i);let a=ts(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new _("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(ly(),"")||t;c=new _(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new _(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(ly(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&v().onError?.(c,s)):(c=new _(String(e)),r&&v().onError?.(c,s));return{error:c,success:!1}}var Ke=()=>v().backendUrl||"",ai="feature_not_supported",ci="model_not_servable",li="provision_in_flight",ui="analytics_unavailable",pi="accounts_list_unavailable",dw={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new _(r.message||"Database error",{code:r.code,details:r});return v().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new _(n.message,{name:n.name||"ApiError",stack:n.stack}):new _(String(n));return v().onError?.(r,t),{error:r,success:!1}}}};async function gw(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await xt(`${Ke()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof oe)return Hr();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Ne(`${Ke()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Ne(`${Ke()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Ne(`${Ke()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Ne(`${Ke()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Ne(`${Ke()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Ne(`${Ke()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${Ke()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${Ke()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:gw};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function xi(e){return e.replace(/\/v1\/?$/,"")}async function Nt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=xi(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Si(){return u(await l.get("/accounts"))}async function wi(e){return u(await l.post("/accounts",e))}async function ki(e){return u(await l.get(`/accounts/${e}`))}async function Ai(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function vi(e){return u(await l.get(`/accounts/${e}/branding`))}async function Ri(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Ti(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Ci(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function Ii(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Ei(e){return u(await l.get(`/accounts/${e}/members`))}async function Mi(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Oi(e){return u(await l.get(`/accounts/${e}/invites`))}async function Di(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function ji(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function $i(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function Li(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function rs(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function py(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Ui(e,t){let n=await rs(e);return{accepted:n,landing:py(n,t)}}async function Fi(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function Ni(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Ki(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Bi(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function mw(e){return Nt(e,"/v1/accounts")}async function qi(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var fw=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","volumes","stateless_sessions","drives","ephemeral_sandboxes","session_log"];async function St(){return u(await l.get("/projects"))}async function Gi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function Cn(e,t){return u(await l.get(`/projects/${e}`,t))}async function Wi(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Vi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Hi(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function yw(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function In(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function En(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Mn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function hw(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Yi(e){return u(await l.post("/projects",e))}async function zi(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function Ji(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var dy=200;function bw(e){let t=e.split(`
|
|
1
|
+
"use strict";var Kortix=(()=>{var yi=Object.defineProperty;var ck=Object.getOwnPropertyDescriptor;var lk=Object.getOwnPropertyNames;var uk=Object.prototype.hasOwnProperty;var pk=(e,t)=>{for(var n in t)yi(e,n,{get:t[n],enumerable:!0})},dk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lk(t))!uk.call(e,s)&&s!==n&&yi(e,s,{get:()=>t[s],enumerable:!(r=ck(t,s))||r.enumerable});return e};var gk=e=>dk(yi({},"__esModule",{value:!0}),e);var _N={};pk(_N,{ABORT_REASONS:()=>FS,ABORT_REASONS_NOT_YET_EMITTED:()=>a$,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Ci,ACTIVE_INSTANCE_COOKIE:()=>Kr,ANALYTICS_UNAVAILABLE_CODE:()=>Ri,ATTACHMENT_PART_REF_PREFIX:()=>iP,ApiError:()=>S,AuthError:()=>ie,BillingError:()=>rt,CAPTURE_DEVICE_DEFAULTS:()=>VM,CAPTURE_EXCLUSION_GROUPS:()=>KM,CAPTURE_FRAME_INTERVALS_MS:()=>GM,CAPTURE_LAYERS:()=>BM,CAPTURE_MAX_HEIGHTS:()=>WM,CAPTURE_RETENTION_LIMITS:()=>qM,CONNECTION_FAULT_GRACE_MS:()=>mP,CONNECTOR_POLL_FIRST_DELAY_MS:()=>tP,CONNECTOR_POLL_INTERVAL_MS:()=>nP,CONNECTOR_POLL_WINDOW_MS:()=>rP,CONTEXT_TOOLS:()=>Gx,COST_MARKUP:()=>iy,ConnectorApprovalPendingError:()=>vs,ConnectorCallError:()=>Nn,ConnectorPageLimitError:()=>As,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>Wx,DEFAULT_NOTIFICATION_PREFERENCES:()=>dT,DEFAULT_TRANSCRIPT_OPTIONS:()=>Rf,DESTRUCTIVE_PHASES:()=>YS,FEATURE_DISABLED_CODE:()=>ss,FEATURE_FLAG_KEYS:()=>Vk,FEATURE_NOT_SUPPORTED_CODE:()=>wi,FILE_VERBS:()=>yt,FileExistsError:()=>cn,HeadlessAuthError:()=>Zt,HostBoundaryError:()=>Wr,IMPERSONATION_HEADER:()=>Zy,INBOX_NOTIFICATION_KINDS:()=>pT,INBOX_OBSERVATION_MAX_MS:()=>ti,INITIAL_SETTLED_CONNECTION:()=>uU,INSTANCE_SCOPED_ROUTES:()=>NS,KNOWN_TOOL_KINDS:()=>wh,KORTIX_TRANSCRIPT_SCHEMA:()=>Ae,KortixMemberError:()=>_t,MAX_PROMPT_ATTACHMENTS_BYTES:()=>Bv,MAX_PROMPT_ATTACHMENT_BYTES:()=>_l,MAX_PROMPT_ATTACHMENT_FILES:()=>hh,MEMORY_VERBS:()=>SL,MODEL_NOT_SERVABLE_CODE:()=>ki,NO_GROUP_ACTIVITY_TOOLS:()=>R_,OPTIMISTIC_ABORT_MAX_MS:()=>ni,OPTIMISTIC_COMPACTION_MAX_MS:()=>wU,OPTIMISTIC_RECEIPT_MAX_MS:()=>Zo,PERSISTED_QUERY_CACHE_VERSION:()=>I2,PLUMBING_TOOLS:()=>gS,PREVIEW_PROBE_TIMEOUT_MS:()=>tU,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>kA,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>wA,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>Lh,PROVISION_IN_FLIGHT_CODE:()=>vi,PublicSessionShareError:()=>Ns,REVIEW_CONTROL_ACTIONS:()=>CR,RUNTIME_NOT_READY_MARKERS:()=>b$,RUNTIME_PERMISSION_CAPABILITIES:()=>yT,RUNTIME_PERMISSION_REPLIES:()=>fT,RequestTooLargeError:()=>Pt,RuntimeNotReadyError:()=>on,SANDBOX_FS_ROOTS:()=>Co,SANDBOX_PORTS:()=>Ye,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>Ai,SERVER_COMPACTION_REVALIDATE_MS:()=>_P,SERVER_OBSERVATION_MAX_MS:()=>ei,SESSION_LIST_STATUS:()=>$U,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ai,SESSION_LOG_MINOR:()=>Se,SESSION_LOG_SCHEMA:()=>pe,SESSION_NOTICE:()=>NU,STANDALONE_TOOLS:()=>C_,STREAM_OBSERVATION_MAX_MS:()=>vn,SandboxNotReadyError:()=>qr,SessionNotReadyError:()=>Mt,SessionStartError:()=>Ds,TRIGGER_CONTROL_ACTIONS:()=>AR,TURN_END_LEDGER_LAG_MS:()=>yU,TURN_ERROR_CODES:()=>c_,WAKE_ESCALATION_COOLDOWN_MS:()=>TU,WAKE_MAX_RESTARTS:()=>CU,WAKE_NO_PROGRESS_MS:()=>RU,WIRE_ID_BACKDATE_MS:()=>xo,WIRE_ID_CLOCK_TOLERANCE:()=>ut,WIRE_ID_TIME_MASK:()=>Je,WIRE_ID_TIME_SCALE:()=>nn,WIRE_MESSAGE_ID:()=>Q_,__getConfigResolver:()=>yk,__setConfigResolver:()=>fk,abortErrorReason:()=>c$,acceptAccountInvite:()=>gs,acceptAccountInviteAndLand:()=>ta,acceptEnterpriseOffer:()=>op,acceptInvite:()=>N$,accountInviteLanding:()=>uh,actReviewItem:()=>Rd,activateConnection:()=>Rc,addComputerToProject:()=>Ic,addGroupMembers:()=>ed,addMarketplaceSource:()=>ag,advanceWakeEscalation:()=>MU,allDescendantIds:()=>nS,appendPreviewToken:()=>by,approveCaptureDeviceGrant:()=>bf,approveCaptureEnrollment:()=>af,approveProjectAccessRequest:()=>Oa,approveTask:()=>vI,archiveProject:()=>Fn,assignTicket:()=>OI,attachGroupToProject:()=>qa,authMfa:()=>yo,authUser:()=>go,authenticatedFetch:()=>L,authenticatedRequest:()=>Kn,authorizePreviewUrl:()=>eU,backendApi:()=>l,bindSlackIdentity:()=>ZA,bindTeamsIdentity:()=>eR,brokerProjectSecretRequest:()=>tc,browserKeyValueStorage:()=>V0,buildInstancePath:()=>KS,buildPresentationTemplateImageUrl:()=>oU,buildPresentationTemplatePdfUrl:()=>sU,buildPreviewAuthEndpoint:()=>_y,buildPublicTemplateUrl:()=>E0,buildRuntimePresentationConversionUrl:()=>gP,buildSandboxTemplate:()=>ul,buildScrapeFailureResults:()=>cS,buildStaticFileHealthPreviewUrl:()=>TM,buildStaticFileLocalUrl:()=>CM,buildStaticFilePreviewUrl:()=>RM,buildStaticFileServicePath:()=>Bb,buildTunnelEventStreamUrl:()=>BF,buildWebProxyUrl:()=>DM,bulkActReviewItems:()=>Cd,bulkDeletePolicies:()=>UR,bulkImportPolicies:()=>FR,burstSummary:()=>Ho,burstSummaryLabel:()=>mS,burstWorkLabel:()=>Yf,callConnector:()=>Rt,canManageBilling:()=>Vh,canOfferTopup:()=>qA,cancelAccountDeletion:()=>kC,cancelAccountInvite:()=>Qi,cancelSandbox:()=>D$,cancelSandboxUpdate:()=>e0,cancelScheduledChange:()=>Xu,cancelSubscription:()=>Yu,captureHealthBucket:()=>JM,changeRequestControlsFrom:()=>e_,checkAccessEmail:()=>g0,checkMcpServerSignIn:()=>Iv,childMapByParent:()=>LD,claimComputer:()=>o0,claimNext:()=>fx,claimPerSeatBilling:()=>zA,claimWarmProjectSession:()=>Zl,classifyPart:()=>Nf,classifyPreviewProbeStatus:()=>dP,classifyPtyClose:()=>ib,classifySessionLogMessage:()=>tw,classifyTurn:()=>No,cleanErrorMessage:()=>qD,cleanResultSnippet:()=>HD,cleanWorkerOutput:()=>fL,clearImpersonationSession:()=>Mi,clearKortixAppViewerCache:()=>Cw,clearModelDefault:()=>Du,clearSessionFresh:()=>tA,closeChangeRequest:()=>Ml,closeMilestone:()=>aE,collectTurnParts:()=>MD,commentTicket:()=>jI,commitSessionChanges:()=>jl,compactionExpiryAtMs:()=>vU,compactionTurnInfo:()=>Ij,compareMessagesForDisplay:()=>RD,compareSemver:()=>eO,completeInFlight:()=>yx,completeSlackInstall:()=>mp,completeTeamsInstall:()=>fp,composerSelectableAgents:()=>Uy,computeStatusFromPart:()=>ry,configureAutoTopup:()=>np,configureKortix:()=>es,confirmCheckoutSession:()=>Hu,connectEmail:()=>wp,connectSlack:()=>dp,connectionFromHealth:()=>lU,connectionIsFaulted:()=>cU,connectionSharedWithEveryone:()=>yv,connectorConnect:()=>mh,connectorFinalize:()=>fh,connectorHeadline:()=>$0,contactEnterpriseSales:()=>ip,contextLabelForTool:()=>nj,contextToolSummary:()=>EO,contextToolTrigger:()=>MO,convertPresentationToGoogleSlides:()=>jC,convertRuntimePresentation:()=>iU,copyFile:()=>Pr,costExportUrl:()=>cp,countLiveInboxPrompts:()=>_U,countReviewItemsBySegment:()=>mR,createAccount:()=>Ni,createAccountAuditWebhook:()=>Jd,createAccountSecretResource:()=>uc,createAccountToken:()=>Ud,createApp:()=>ug,createAppAccessSession:()=>_g,createAppDeployment:()=>xg,createAppToken:()=>gg,createAppVolume:()=>$g,createAppVolumeSnapshot:()=>Bg,createArtifactKind:()=>kj,createAssignment:()=>xd,createAuditWebhook:()=>fC,createBackup:()=>q$,createCaptureEnrollmentToken:()=>rf,createCheckoutSession:()=>Vu,createConnector:()=>Gc,createConnectorLinkInfoCache:()=>D0,createFile:()=>Sr,createGatewayKey:()=>Bp,createGroup:()=>Jp,createHttpSessionSyncController:()=>bw,createInstance:()=>n0,createKortix:()=>px,createKortixPty:()=>Om,createKortixSession:()=>_o,createMarketplaceInstallSession:()=>KC,createMilestone:()=>oE,createModelVisibility:()=>ek,createOAuthClient:()=>fd,createPerSeatCheckout:()=>HA,createPersistedQueryCache:()=>W0,createPolicy:()=>jR,createPortalSession:()=>zu,createProject:()=>pa,createProjectAgent:()=>WI,createProjectCliToken:()=>qd,createProjectRepo:()=>da,createProjectResourceGrant:()=>Ha,createProjectSession:()=>It,createProjectSkill:()=>_a,createProjectTrigger:()=>Pu,createPromptAttachmentController:()=>Qm,createRole:()=>ad,createSSEStream:()=>KF,createSandbox:()=>R$,createSandboxShare:()=>Id,createSandboxTemplate:()=>al,createSavedCopyStore:()=>bA,createScimToken:()=>qR,createServiceAccountApi:()=>pC,createSessionPrompt:()=>Qn,createSessionPublicShare:()=>Jl,createSessionQueue:()=>gx,createSessionReminder:()=>Od,createSsoGroupMapping:()=>nC,createTask:()=>PI,createTicket:()=>II,createTunnelEventStream:()=>qF,createWarmSessionPool:()=>CF,currentSavedCopyStore:()=>Nl,declineAccountInvite:()=>na,declineInvite:()=>B$,deleteAccountImmediately:()=>vC,deleteAccountSecretResource:()=>gc,deleteApp:()=>dg,deleteAppDeployment:()=>Ag,deleteAuditWebhook:()=>hC,deleteBackup:()=>W$,deleteConnector:()=>Vc,deleteConnectorCredential:()=>Xc,deleteCredential:()=>mE,deleteDriveFile:()=>iT,deleteEnv:()=>Im,deleteFile:()=>Lt,deleteGatewayBudget:()=>Fp,deleteGitHubInstallation:()=>Ta,deleteGroup:()=>Xp,deleteInstance:()=>r0,deleteKortixProject:()=>eE,deleteMilestone:()=>lE,deleteOAuthClient:()=>_d,deletePersonalProjectSecret:()=>ac,deletePolicy:()=>$R,deleteProjectAgent:()=>HI,deleteProjectProviderOAuth:()=>rc,deleteProjectResourceGrant:()=>za,deleteProjectSecret:()=>oc,deleteProjectSession:()=>uu,deleteProjectTrigger:()=>ku,deletePromptAttachment:()=>Ht,deleteRole:()=>ud,deleteSandboxTemplate:()=>ll,deleteServiceAccountApi:()=>gC,deleteSessionPrompt:()=>su,deleteSessionReminder:()=>Ks,deleteSessionReminders:()=>jd,deleteSsoGroupMapping:()=>rC,deleteSsoProvider:()=>eC,deleteTask:()=>AI,deleteTicket:()=>LI,denyCaptureDeviceGrant:()=>xf,denyCaptureEnrollment:()=>cf,describeAccountInvite:()=>ea,describeConnectorTool:()=>xs,destroyAppMachine:()=>Og,destroyAppVolume:()=>Fg,detachGroupFromProject:()=>Wa,detectLocalhostUrls:()=>$b,directSubsessions:()=>KU,disableServiceAccountApi:()=>dC,disconnectEmail:()=>kp,disconnectGitHubApp:()=>K0,disconnectSlack:()=>hp,discoverConnectionOAuth2:()=>xv,discoverConnectionOAuth2Resource:()=>Sv,discoverConnectorAuth:()=>Wc,discoverLocalSandbox:()=>E$,dismissDriveConflict:()=>ZC,downloadAccountAudit:()=>T0,downloadDriveFile:()=>tT,dropClientForUrl:()=>kE,dropPublicClientForUrl:()=>RE,editQueued:()=>xx,editSessionPrompt:()=>ou,enqueue:()=>mx,ensurePmSession:()=>qI,ensurePreviewSessionCookie:()=>pP,ensureProjectConnectorConnection:()=>hv,ensureSandbox:()=>zS,ensureWarmProjectSession:()=>Xl,env:()=>sb,exchangeCode:()=>lo,execInApp:()=>jg,exportAccountAudit:()=>zd,extractGatewayErrorDetails:()=>we,extractInstanceRoute:()=>wn,extractSkillBaseDir:()=>OS,extractSkillContent:()=>CL,extractSkillFiles:()=>MS,extractWorkerPreview:()=>hL,failInFlight:()=>hx,fallbackBusyRowAfterTurnId:()=>Yj,familyForTool:()=>xn,featureDisabledKey:()=>xi,featureFlags:()=>_m,fetchAccountStateWithToken:()=>GA,fetchAccountsWithToken:()=>Wk,fetchAttachmentPart:()=>H0,fetchCostExportCsv:()=>XA,fetchKortixAppViewer:()=>Dy,fetchProjectArchive:()=>yl,fetchProjectFileRaw:()=>Nv,fetchProjectsForAccountWithToken:()=>tv,fetchSessionAttachment:()=>ym,fileDownloadRequest:()=>xb,filePhase:()=>xL,fileVerb:()=>bL,files:()=>Rb,finalizeAppArtifact:()=>Ws,finalizeConnectorSetupLink:()=>x0,findActiveTranscriptShare:()=>AA,findFiles:()=>br,findLastTextPart:()=>OD,findSessionAttachments:()=>XT,findText:()=>xr,fireProjectTrigger:()=>Au,fixSandboxWithAgent:()=>il,flattenModels:()=>Qw,flattenThought:()=>jj,forkAppVolume:()=>qg,formatBillingErrorForUI:()=>Pi,formatCost:()=>aL,formatDuration:()=>oy,formatJsonFailureOutput:()=>GD,formatMessageDay:()=>Bj,formatMessageExact:()=>Kj,formatOpenCodeRuntimeError:()=>w$,formatRawOutput:()=>VD,formatRuntimeError:()=>HS,formatTokens:()=>cL,formatTranscript:()=>Px,freshSendHint:()=>Zj,generateSessionId:()=>dx,getAccount:()=>Bi,getAccountBranding:()=>qi,getAccountDeletionStatus:()=>PC,getAccountState:()=>Fu,getAccountStateMinimal:()=>Nu,getActiveInstanceIdFromCookie:()=>GS,getAdminProviderAnalytics:()=>IC,getAdminProviderDistribution:()=>RC,getAdminProviderFallback:()=>MC,getAdminRole:()=>AC,getAgentCardLabel:()=>zx,getAgentConfig:()=>UA,getAgentPersona:()=>zI,getAllVersions:()=>Q$,getAnsweredQuestionParts:()=>jD,getApp:()=>qs,getAppAccess:()=>fg,getAppAuthEnv:()=>mg,getAppDeployment:()=>Pg,getAppDeploymentLogs:()=>wg,getApprovalLink:()=>BC,getAuthToken:()=>Wt,getAuthTokenWithRetry:()=>pv,getAutoTopupSettings:()=>tp,getAutoTopupSetupStatus:()=>VA,getBillingCreditBreakdown:()=>qu,getBillingTierConfigurations:()=>Wu,getBillingTransactionsSummary:()=>Ku,getBillingUsageHistory:()=>Gu,getCaptureAssetUrl:()=>hf,getCaptureChunkMedia:()=>yf,getCaptureDays:()=>gf,getCaptureDeviceGrant:()=>_f,getCaptureFrame:()=>ff,getCapturePolicy:()=>lf,getCaptureTimeline:()=>pf,getCaptureTimelineItems:()=>df,getCaptureWorkspace:()=>Sf,getChangeRequest:()=>Rl,getChangeRequestDiff:()=>Cl,getChangeRequestMergePreview:()=>Tl,getChildSessionError:()=>VO,getChildSessionId:()=>Or,getChildSessionToolParts:()=>HO,getClient:()=>dt,getClientForUrl:()=>Oe,getConnectStatus:()=>Jc,getConnectionOAuth2Application:()=>bv,getConnectionOAuth2Status:()=>Av,getConnectionPolicies:()=>Rv,getConnectorCatalog:()=>Vt,getConnectorConfig:()=>Bc,getConnectorPolicies:()=>Fc,getConnectorSetupLink:()=>_0,getCostSummary:()=>QA,getCurrentInstanceIdFromPathname:()=>qS,getCurrentInstanceIdFromWindow:()=>p$,getCurrentProject:()=>Bm,getDefaultAccountState:()=>Uu,getDiagnostics:()=>QO,getDirectory:()=>Hx,getDiscoverConnector:()=>ks,getDiscoverIntegration:()=>Dv,getDriveFileUrl:()=>Gg,getEmailInstallation:()=>Sp,getEmailMode:()=>Pp,getEnterpriseDemo:()=>bC,getFileStatus:()=>_r,getFileWithDir:()=>Df,getFilename:()=>Vx,getFolderAccess:()=>zC,getFullChangelog:()=>JS,getGatewayBreakdown:()=>Dp,getGatewayBudgets:()=>$p,getGatewayErrors:()=>Lp,getGatewayKeys:()=>Np,getGatewayLog:()=>Ep,getGatewayOverview:()=>Mp,getGatewayRoutingPolicy:()=>Ap,getGatewaySeries:()=>Op,getGatewaySessions:()=>jp,getGitHubAppStatus:()=>U0,getGitHubInstallation:()=>Sa,getGoogleAuthUrl:()=>DC,getGroup:()=>Yp,getHiddenToolParts:()=>BO,getImpersonationSession:()=>nh,getInvite:()=>F$,getJustavpsServerTypes:()=>t0,getKortixProject:()=>QI,getKortixProjectBySession:()=>XI,getKortixPtyWebSocketUrl:()=>Lm,getLatestSandboxVersion:()=>J$,getMaintenanceConfig:()=>v0,getManagedGitBackend:()=>Ia,getManagedGitStatus:()=>Qk,getMarketplaceCatalogItem:()=>sg,getMarketplaceCatalogItemFile:()=>og,getMfaRequired:()=>WR,getMilestone:()=>rE,getMobileClientPolicy:()=>Af,getModelDefaults:()=>Mu,getMyCaptureFrame:()=>vf,getMyCaptureTimeline:()=>kf,getNotificationPreferences:()=>Yg,getOAuthClient:()=>md,getOAuthConsentRequest:()=>y0,getOpenCodeConfigInvalidError:()=>y$,getPartText:()=>UO,getPatPolicy:()=>cC,getPermissionForTool:()=>XO,getProject:()=>At,getProjectActivity:()=>YI,getProjectCommit:()=>Pl,getProjectCommitDiff:()=>wl,getProjectDetail:()=>jn,getProjectDrive:()=>HC,getProjectFileHistory:()=>kl,getProjectGitToken:()=>ua,getProjectLlmCatalog:()=>Ln,getProjectLlmCatalogProviders:()=>zk,getProjectModelAccess:()=>rr,getProjectModelPicker:()=>$n,getProjectSandboxHealth:()=>Bn,getProjectSandboxProviderTransition:()=>Xk,getProjectSession:()=>zn,getProjectSessionConfigState:()=>gu,getProjectSessionScope:()=>yu,getProrationPreview:()=>Zu,getProviders:()=>v$,getProxyBaseUrl:()=>IM,getPublicClientForUrl:()=>AE,getPublicMarketplaceItem:()=>p0,getPublicMarketplaceItemFile:()=>d0,getPublicSessionShare:()=>LC,getPublicSessionShareMessages:()=>$C,getPublicShareByToken:()=>w0,getPublicTemplate:()=>M0,getQuestionForTool:()=>ZO,getReferralCode:()=>cR,getReferralStats:()=>pR,getRetryInfo:()=>lL,getRetryMessage:()=>uL,getReviewItem:()=>vd,getReviewSummary:()=>kd,getRolePermissions:()=>od,getRoleUsage:()=>id,getRuntimeConfigInvalidError:()=>Xo,getSSHConnection:()=>H$,getSandbox:()=>A$,getSandboxById:()=>C$,getSandboxPortUrl:()=>k$,getSandboxProvisionStatus:()=>i0,getSandboxProvisionStreamUrl:()=>a0,getSandboxUpdateStatus:()=>Y$,getSandboxUrl:()=>my,getSandboxUrlForExternalId:()=>Ee,getSecretSetupLink:()=>S0,getServerHealth:()=>To,getServiceLogs:()=>bE,getSessionAudit:()=>eu,getSessionCost:()=>iL,getSessionCostRecord:()=>nr,getSessionDrives:()=>i_,getSessionHealth:()=>Wm,getSessionLogPage:()=>nu,getSessionMessageAuthors:()=>bu,getSessionModelUsage:()=>xu,getSessionOpenBundle:()=>RA,getSessionOversight:()=>zR,getSessionParticipants:()=>ql,getSessionPolicy:()=>sC,getSessionPreviewCandidates:()=>zl,getSessionProviderSecretPool:()=>hc,getSessionTranscript:()=>tu,getSessionTranscriptSync:()=>Yn,getSessionTurn:()=>Jn,getSessionWatch:()=>Gl,getShellModePart:()=>mL,getSlackChannelFile:()=>_p,getSlackInstallation:()=>pp,getSlackManifest:()=>yp,getSlackMode:()=>gp,getSsoProvider:()=>JR,getStaticFileHealthPath:()=>Kb,getSupabaseAccessToken:()=>ys,getSupabaseAccessTokenWithRetry:()=>gh,getTask:()=>bI,getTaskStatus:()=>SI,getTemplate:()=>qC,getTicket:()=>CI,getToolInfo:()=>zO,getToolPrimaryArg:()=>jo,getTranscriptFilename:()=>wx,getTurnCost:()=>Qo,getTurnError:()=>rL,getTurnErrorDetails:()=>oL,getTurnErrorRawText:()=>sL,getTurnStatus:()=>sy,getUsageRollup:()=>ap,getUserRolesWithToken:()=>R0,getVersionDiff:()=>vl,getWebPushPublicKey:()=>Qg,getWorkingState:()=>tL,grantAccountSecretResource:()=>mc,grantSandboxProjectAccess:()=>$$,grantSecretToAgent:()=>NA,groupMessagesIntoTurns:()=>TD,groupShowSegments:()=>Zf,groupSteps:()=>Jf,hasDiffs:()=>pL,hasLocalhostUrls:()=>kM,hasPreviewTarget:()=>Nb,hasRetryingAssistantTurn:()=>qf,heartbeatGapEvent:()=>pb,holdSessionPrompts:()=>cu,humanizeReviewActionPath:()=>Hp,humanizeSearchQuery:()=>Cr,humanizeToolName:()=>$f,impersonationHeaders:()=>Oi,importSsoProviderFromMetadata:()=>XR,inboxObservationSupersedes:()=>hU,initialWakeEscalationState:()=>Sy,inputPath:()=>et,installTemplate:()=>GC,interruptSessionPrompt:()=>iu,invalidateTokenCache:()=>hs,inviteAccountMember:()=>Yi,inviteProjectMember:()=>Ua,inviteRepoCollaborator:()=>ca,isAbortError:()=>Br,isAdminBypassEnabled:()=>ih,isAgentPart:()=>OO,isAppRouteUrl:()=>Lb,isAttachment:()=>FO,isAttachmentPartRef:()=>aP,isAuthFailure:()=>Bt,isBillingError:()=>Si,isCompactionPart:()=>DO,isConfigured:()=>ts,isContextTool:()=>IO,isDestructivePhase:()=>z$,isEmptyConversation:()=>Oy,isEmptyShowPart:()=>Zs,isErrorOutput:()=>UD,isExternalUrl:()=>$M,isFeatureDisabledError:()=>bi,isFilePart:()=>jf,isImpersonationSessionLive:()=>eh,isInstanceDetailPath:()=>l$,isInstanceScopedAppPath:()=>BS,isInternalLocalhostUrl:()=>OM,isInvisibleActivityPart:()=>um,isInviteSent:()=>sv,isLastUserMessage:()=>eL,isLegacyMigratedSession:()=>bP,isManagedGithubProject:()=>Hk,isNoGroupActivityTool:()=>lm,isOfferedModel:()=>mi,isOpenCodeConfigInvalidError:()=>h$,isPaintableSavedCopy:()=>Eh,isPatchPart:()=>LO,isPersistableQueryKey:()=>G0,isPreviewUrl:()=>MM,isProxiableLocalhostUrl:()=>qb,isQuestionTool:()=>cm,isReasoningPart:()=>ve,isRetryableTurnError:()=>rS,isRuntimeConfigInvalidError:()=>WS,isRuntimeNotReadyResponse:()=>VS,isRuntimeReady:()=>Gm,isRuntimeStartingError:()=>P$,isSandboxNotReadyError:()=>kn,isSelectableAgent:()=>to,isServerReachable:()=>Km,isSessionAttachmentRef:()=>WT,isSessionFresh:()=>$l,isSessionLogRestoreNote:()=>ow,isSessionStartError:()=>OA,isShellActivityTool:()=>NT,isShellMode:()=>TS,isShortOutput:()=>yL,isShowContentUnavailable:()=>gT,isShowPayloadEmpty:()=>or,isSnapshotPart:()=>jO,isStandaloneActivityTool:()=>pm,isStepPart:()=>$O,isSubdomainPreviewUrl:()=>Vr,isTextPart:()=>De,isToolPart:()=>te,isToolPartHidden:()=>KO,isTurnErrorCode:()=>tm,isUnderSandboxRoot:()=>Fm,isWebProxyUrl:()=>LM,isWireIdAheadOf:()=>Z_,kortixAppViewerToken:()=>Tw,kortixBinding:()=>Iw,kortixPty:()=>lb,kortixToken:()=>jy,latestPromptModel:()=>sk,leaveAccount:()=>oa,linkCaptureDevice:()=>tf,linkGitHubInstallation:()=>Ra,linkRepository:()=>ba,listAccountAudit:()=>Vd,listAccountAuditWebhooks:()=>Yd,listAccountInvites:()=>Ji,listAccountMembers:()=>zi,listAccountResourceGrants:()=>OR,listAccountSecretResources:()=>lc,listAccountSessions:()=>iC,listAccountTokens:()=>$d,listAccounts:()=>Fi,listActions:()=>NR,listAdminSandboxes:()=>CC,listAgentIdentities:()=>rd,listAllConnections:()=>Pc,listAppAgents:()=>yg,listAppDeployments:()=>Sg,listAppMachines:()=>Cg,listAppVolumeSnapshots:()=>Ng,listAppVolumes:()=>Lg,listApps:()=>lg,listAssignments:()=>bd,listAuditEvents:()=>_C,listAuditWebhooks:()=>mC,listBackups:()=>K$,listBillingTransactions:()=>Bu,listCaptureDevices:()=>Zm,listCaptureEnrollmentTokens:()=>nf,listCaptureEnrollments:()=>of,listChangeRequests:()=>Al,listChannelBindings:()=>oR,listColumns:()=>$I,listConnectSections:()=>Mv,listConnectToolkits:()=>Ev,listConnections:()=>Sc,listConnectorAccounts:()=>Ss,listConnectorTools:()=>bs,listConnectors:()=>Dc,listCostByProject:()=>JA,listCredentialEvents:()=>pE,listCredentials:()=>uE,listDiscoverConnectors:()=>ws,listDiscoverIntegrations:()=>Ov,listDiscoverSections:()=>Yc,listDriveConflicts:()=>XC,listDriveFiles:()=>eT,listDriveFolder:()=>o_,listDriveVersions:()=>aT,listEnv:()=>Cm,listFeaturedMarketplaces:()=>rg,listFields:()=>FI,listFiles:()=>pn,listFolderPrincipals:()=>QC,listGatewayLogs:()=>Ip,listGitHubInstallations:()=>Pa,listGitHubRepositories:()=>ka,listGitHubRepositoryBranches:()=>va,listGroupMembers:()=>Zp,listGroupProjectGrants:()=>IR,listGroups:()=>zp,listKortixProjectSessions:()=>ZI,listKortixProjects:()=>JI,listKortixPty:()=>Mm,listLinkableGitHubInstallations:()=>wa,listManagedGitRepositories:()=>Ea,listMarketplaceCatalogItems:()=>tg,listMarketplaceSources:()=>ig,listMarketplaces:()=>ng,listMemberGroups:()=>ER,listMemberProjectAccess:()=>MR,listMilestoneEvents:()=>sE,listMilestones:()=>nE,listMyAccountInvites:()=>Zi,listNotifications:()=>Hg,listOAuthClients:()=>gd,listOAuthGrants:()=>Nd,listPendingApprovals:()=>Ya,listPendingProjectInvites:()=>Fa,listPermissions:()=>Pd,listPipedreamApps:()=>Hc,listPipedreamSections:()=>zc,listPolicies:()=>DR,listProjectAccess:()=>ja,listProjectAccessRequests:()=>Ma,listProjectAgentIdentities:()=>sd,listProjectAgents:()=>GI,listProjectAudit:()=>Hd,listProjectBranches:()=>xl,listProjectCliTokens:()=>Kd,listProjectCommits:()=>Sl,listProjectDirectory:()=>gl,listProjectFiles:()=>dl,listProjectGroupGrants:()=>Ka,listProjectPolicies:()=>tl,listProjectProviderOAuth:()=>nc,listProjectReminders:()=>Ld,listProjectResourceGrants:()=>Va,listProjectSandboxTemplates:()=>rl,listProjectSandboxes:()=>pl,listProjectSecrets:()=>Xa,listProjectSessions:()=>Tt,listProjectSessionsPage:()=>Bl,listProjectSnapshots:()=>sl,listProjectTriggerEventApps:()=>Cu,listProjectTriggerEventTypes:()=>Ru,listProjectTriggers:()=>Su,listProjects:()=>vt,listProjectsForAccount:()=>aa,listPublicMarketplaceItems:()=>l0,listPublicMarketplaces:()=>u0,listReferrals:()=>dR,listReviewItems:()=>wd,listRoles:()=>nd,listSandboxProjectMembers:()=>L$,listSandboxShares:()=>Td,listSandboxes:()=>I$,listScimTokens:()=>KR,listServiceAccountsApi:()=>uC,listServiceTemplates:()=>_E,listServices:()=>hE,listSessionConnectRequests:()=>Tv,listSessionCosts:()=>up,listSessionDrives:()=>uT,listSessionPrompts:()=>ru,listSessionProviderSecretPools:()=>_c,listSessionPublicShares:()=>Yl,listSessionReminders:()=>Md,listSessionsNeedingInput:()=>Ja,listSignedInDevices:()=>FC,listSsoGroupMappings:()=>tC,listTaskEvents:()=>xI,listTasks:()=>_I,listTemplates:()=>BI,listTicketEvents:()=>TI,listTickets:()=>RI,loadHttpSessionHistory:()=>_w,loadPreviewUrlTemplate:()=>lt,looksLikeError:()=>Gf,looksLikeHtml:()=>QD,looksLikeJsonPayload:()=>WD,makeDriveFolder:()=>sT,mapApiReviewItem:()=>vR,markInstanceError:()=>s0,markNotificationsRead:()=>zg,markSessionFresh:()=>Vn,maxWireIdClock:()=>km,memoryRelPath:()=>PL,mergeBurstSteps:()=>Qf,mergeChangeRequest:()=>El,messageCreatedAt:()=>Lj,messageTime:()=>xS,migrateAdminSandboxProvider:()=>EC,mintWireMessageId:()=>So,mintWireMessageIdAbove:()=>vm,mkdir:()=>fn,modelInDefaultView:()=>tk,modelRefToKey:()=>pi,moveDriveFile:()=>oT,narrateFailedStep:()=>Hf,narrateStep:()=>Ur,narrationToolName:()=>$r,narrowChatEvent:()=>db,newestWireIdClock:()=>eb,nextConnectorPollDelay:()=>L0,normalizeActivityToolName:()=>he,normalizeAppPathname:()=>m$,normalizeCaptureAppId:()=>YM,normalizeCaptureDomain:()=>zM,normalizeExternalInput:()=>UM,normalizeName:()=>ee,normalizeToolName:()=>Lf,notifyHostSignal:()=>SP,openChangeRequest:()=>Il,openEventStream:()=>vo,openStressTestStream:()=>I0,paginateConnector:()=>el,parseBillingError:()=>On,parseEmbeddedFailure:()=>zD,parseFlagOverride:()=>eI,parseJsonFailure:()=>oS,parseLocalhostUrl:()=>Ar,parseMemoryView:()=>wL,parseOpenCodeErrorPayload:()=>f$,parsePresentationOutput:()=>AL,parseProxyHop:()=>qm,parseQuestionAnswersFromOutput:()=>ly,parseReadOutput:()=>RL,parseRuntimeErrorPayload:()=>gy,parseScrapeInputUrls:()=>aS,parseScrapeOutput:()=>lS,parseSubdomainUrl:()=>Hm,parseTaskRows:()=>_L,parseWebProxyUrl:()=>jM,parseWebSearchOutput:()=>Wf,partOutcome:()=>qo,patchKortixProject:()=>tE,patchVerb:()=>vL,pickerProviderList:()=>Jw,pipedreamConnect:()=>qc,pipedreamConnectConnection:()=>Mc,pipedreamFinalize:()=>Zc,pipedreamFinalizeConnection:()=>Oc,platformConfig:()=>C,pollConnectionOAuth2DeviceAuthorization:()=>vv,pollProjectProviderOAuth:()=>fs,previewBillingPlan:()=>rp,previewGatewayRoute:()=>Tp,previewMfaRequired:()=>VR,previewSlackIdentity:()=>tR,previewTeamsIdentity:()=>nR,probeEffectivePermission:()=>pd,probeEffectivePermissions:()=>dd,probePreviewPort:()=>nU,projectArchiveRequest:()=>hl,projectCompacting:()=>kU,projectConfigAgentsToOpenCodeAgents:()=>$w,projectConfigAgentsToRuntimeAgents:()=>$y,projectSessionConnection:()=>aU,projectSessionForRuntimeId:()=>qU,projectSessionStartSeed:()=>Iu,projectWorking:()=>bU,provisionProject:()=>ga,provisionProjectStream:()=>Jk,provisionProjectWithToken:()=>nv,proxyLocalhostUrl:()=>Vm,proxyUrlToInternal:()=>EM,purchaseCredits:()=>ep,putConnectionOAuth2Application:()=>_v,rawErrorText:()=>Rr,reactivateSandbox:()=>j$,reactivateSubscription:()=>Ju,readBlob:()=>gn,readDriveFile:()=>nT,readFile:()=>dn,readKortixMember:()=>ui,readProjectFile:()=>fl,readSavedSessionCopy:()=>Aw,reasoningIsRunning:()=>zo,rebuildProjectSnapshot:()=>ol,reconcileConnection:()=>wc,reconcileMemberConnection:()=>kc,reconcileServices:()=>SE,recordPlatformLogout:()=>f0,recoverLinkResults:()=>Go,recoverProjectSession:()=>pu,refreshReferralCode:()=>lR,refreshSession:()=>en,registerAppArtifact:()=>Gs,registerConnectionOAuth2Client:()=>Pv,registerDeviceToken:()=>Wg,registerService:()=>PE,registerWebPushSubscription:()=>Xg,rejectProjectAccessRequest:()=>Da,relativizePath:()=>JO,reloadProjectSessionConfig:()=>mu,reloadProjectSessionConfigStream:()=>fu,removeAccountAuditWebhook:()=>Xd,removeAccountBrandingAsset:()=>Vi,removeAccountMember:()=>ra,removeGroupMember:()=>td,removeKortixPty:()=>jm,removeMarketplaceSource:()=>cg,removeQueued:()=>bx,renameConnection:()=>Tc,renameFile:()=>kr,renameSandbox:()=>T$,reopenChangeRequest:()=>Ol,reopenMilestone:()=>cE,reorderQueued:()=>Sx,replaceColumns:()=>UI,replaceFields:()=>NI,replaceProjectRepository:()=>xa,replaceTemplates:()=>KI,requestAccountDeletion:()=>wC,requestChangesOnChangeRequest:()=>Dl,requestProjectAccess:()=>rv,requestProjectConnector:()=>eg,requestProjectSecret:()=>Zd,requestTopUp:()=>WA,requireKortixMember:()=>Ow,resendAccountInvite:()=>Xi,resendPendingProjectInvite:()=>Ba,resetAccountBranding:()=>Hi,resetClient:()=>vE,resetGatewayRoutingPolicy:()=>Cp,resetPassword:()=>uo,resetPublicClient:()=>CE,resetSandboxUpdateStatus:()=>Z$,resolveApproval:()=>Qa,resolveComposerAgent:()=>Lw,resolveComposerModel:()=>ik,resolveConnectorStart:()=>j0,resolveModelDefault:()=>rk,resolvePublicShareUrl:()=>vA,resolveScrapeResults:()=>XD,resolveWorkingTurn:()=>ny,resolvedPlan:()=>KA,restartAppMachine:()=>Mg,restartProjectSession:()=>Xn,restartSandbox:()=>M$,restoreAppVolume:()=>Kg,restoreBackup:()=>G$,restoreDriveVersion:()=>cT,restoreProjectSession:()=>du,retryAccountSecretResource:()=>dc,retryFailed:()=>_x,retrySessionPrompt:()=>au,revealCredential:()=>gE,reviewItemTarget:()=>Vp,reviewSegmentForStatus:()=>Zh,reviewVerdictAllowed:()=>TR,reviewVerdictForStatus:()=>fR,revokeAccountSecretResourceGrant:()=>fc,revokeAccountSession:()=>aC,revokeAccountToken:()=>Fd,revokeAssignment:()=>Sd,revokeCaptureDevice:()=>ef,revokeCaptureEnrollmentToken:()=>sf,revokeConnection:()=>Ac,revokeGatewayKey:()=>Kp,revokeOAuthGrant:()=>Bd,revokePendingProjectInvite:()=>Na,revokeProjectAccess:()=>$a,revokeProjectCliToken:()=>Gd,revokeSandboxProjectAccess:()=>U$,revokeSandboxShare:()=>Ed,revokeScimToken:()=>GR,revokeSessionPublicShare:()=>Ql,rewriteLocalhostUrl:()=>ft,rollbackApp:()=>Rg,rootRuntimeSession:()=>xP,rotateAccountSecretResource:()=>pc,rotateOAuthClientSecret:()=>hd,runConnector:()=>Rs,runGatewayPlayground:()=>qp,runProjectProviderOAuthFlow:()=>cv,runtimeSessionsOf:()=>ri,runtimeSupports:()=>Eb,sanitizePtyChunk:()=>cb,saveGitHubInstallation:()=>Aa,savedCopyEmptyRoot:()=>My,scaleApp:()=>Dg,scheduleDowngrade:()=>Qu,searchCapture:()=>mf,searchConnectorTools:()=>xc,searchMyCapture:()=>wf,searchProjectFiles:()=>ml,segmentTurn:()=>Xf,selectableProjectAgents:()=>nI,sendMagicLink:()=>io,sendReferralEmails:()=>gR,serverCompactionRevalidateAtMs:()=>AU,serviceAction:()=>xE,sessionConnectionLabel:()=>FU,sessionListStatus:()=>UU,sessionLogActivityText:()=>zP,sessionLogAnsweredQuestionCall:()=>ew,sessionLogBurstRunning:()=>QP,sessionLogBurstSteps:()=>HP,sessionLogBurstSummary:()=>YP,sessionLogBurstWorkLabel:()=>JP,sessionLogCallStatus:()=>NP,sessionLogFullTextAction:()=>pw,sessionLogFullTextPlan:()=>dw,sessionLogHarnessSwitches:()=>iw,sessionLogOfV1Rows:()=>EP,sessionLogOpenCall:()=>XP,sessionLogPromptMessage:()=>BP,sessionLogReferencedTexts:()=>lw,sessionLogRestoreNotice:()=>aw,sessionLogRetrying:()=>Cy,sessionLogShowGroupCall:()=>ZP,sessionLogThreadMetrics:()=>rw,sessionLogTurnSegments:()=>WP,sessionLogTurns:()=>ii,sessionLogWithFullTexts:()=>gw,sessionModelCandidates:()=>ok,sessionModelPin:()=>er,sessionParentId:()=>PA,sessionPromptActions:()=>IA,sessionStartKey:()=>jA,setAccountSecretResourceAccess:()=>yc,setActiveInstanceCookie:()=>d$,setAdminBypass:()=>oh,setAdminProviderDistribution:()=>TC,setAdminProviderFallback:()=>OC,setAgentScope:()=>ju,setBillingPlan:()=>sp,setBootstrapAuthToken:()=>uv,setCachedAuthToken:()=>lv,setCaptureEnabled:()=>Pf,setCapturePolicy:()=>uf,setConnectionPolicies:()=>Cv,setConnectorAuthorizationStrategy:()=>$c,setConnectorCredential:()=>Qc,setConnectorCredentialMode:()=>Lc,setConnectorName:()=>Kc,setConnectorPolicies:()=>Nc,setConnectorSecretBinding:()=>jv,setConnectorSensitive:()=>Uc,setDefaultConnection:()=>Cc,setEnterpriseDemo:()=>xC,setEnv:()=>Tm,setGatewayBudget:()=>Up,setGatewayRoutingPolicy:()=>Rp,setGitHubAppFromExisting:()=>N0,setGitHubAppPat:()=>B0,setImpersonationSession:()=>Tk,setMaintenanceConfig:()=>A0,setMemberSuperAdmin:()=>BR,setMfaRequired:()=>HR,setModelDefault:()=>Ou,setPersonalProjectSecret:()=>ic,setProjectModelAccess:()=>sr,setProjectModelEnablement:()=>LA,setProjectOnboardingComplete:()=>ha,setProjectOnboardingProfile:()=>ev,setProjectPolicies:()=>nl,setProjectSecretStrategy:()=>ec,setProjectSessionModel:()=>_u,setProjectSessionScope:()=>hu,setProjectSessionSharing:()=>Kl,setProjectTriggersActivation:()=>vu,setSavedCopyStore:()=>xA,setSessionArchived:()=>Hl,setSessionOversight:()=>YR,setSessionPinned:()=>Vl,setSessionProviderSecretPool:()=>bc,setSessionWatch:()=>Wl,settleSessionConnection:()=>pU,setupSSH:()=>V$,shareConnection:()=>Ec,shareFolder:()=>YC,shellActivityGroupLabel:()=>BT,shellExitCode:()=>py,shouldAttachImpersonation:()=>rh,shouldHideResponsePart:()=>nL,shouldShowToolPart:()=>_n,shouldSuppressWorkingTurnBusy:()=>Hj,showGroupItems:()=>ey,showTurnBusyIndicator:()=>ty,signInWithPassword:()=>oo,signInWithProvider:()=>co,signInWithSso:()=>fo,signOut:()=>ho,signOutDevice:()=>NC,signUp:()=>so,skillDocumentPath:()=>DL,skillInputDir:()=>EL,sortSessions:()=>$D,splitSessionLogTurnWork:()=>VP,splitTurnWork:()=>cy,splitUserParts:()=>NO,startApp:()=>kg,startAppMachine:()=>Ig,startConnectionOAuth2Authorization:()=>wv,startConnectionOAuth2DeviceAuthorization:()=>kv,startConnectorSetupLink:()=>b0,startGitHubAppManifest:()=>F0,startProjectProviderOAuth:()=>ms,startProjectSession:()=>ot,startProjectSessionOrThrow:()=>Eu,startSessionWithToken:()=>k0,startTask:()=>kI,stepLabel:()=>Sn,stopApp:()=>vg,stopAppMachine:()=>Eg,stopProjectSession:()=>Zn,stopSandbox:()=>O$,storeGitHubUserToken:()=>Ca,stripAnsi:()=>tD,stripInstancePrefix:()=>u$,stripTrailingSlashes:()=>de,subAgentCalls:()=>nw,submitAccessRequest:()=>m0,submitDemoRequest:()=>C0,submitOAuthConsent:()=>h0,submitReviewItem:()=>Ad,submitSecretSetupLink:()=>P0,subscribeToImpersonation:()=>Ik,supabaseClient:()=>qk,syncConnectors:()=>jc,syncSubscription:()=>YA,systemReload:()=>IE,toDaemonPath:()=>mt,toInstanceAwarePath:()=>g$,toInternalUrl:()=>Gb,toSandboxAbsolutePath:()=>un,toToolView:()=>Ff,toWorkspaceRelative:()=>Nm,toolCallBlock:()=>ar,toolCallError:()=>A_,toolCallMetadata:()=>P_,toolCallRawOutput:()=>v_,toolCallStatus:()=>k_,toolInfo:()=>$o,toolKind:()=>ue,toolViewModel:()=>$S,triggerControlsFrom:()=>RR,triggerSandboxUpdate:()=>X$,triggersRequest:()=>ob,turnEndCause:()=>hP,turnEndNotice:()=>PU,turnHasSteps:()=>DD,turnIsConfirmedActive:()=>Jj,turnRendersQueued:()=>Qj,turnRetryLabel:()=>BU,unassignTicket:()=>DI,unregisterDeviceToken:()=>Vg,unregisterWebPushSubscription:()=>Zg,unshareFolder:()=>JC,unwrapError:()=>_e,updateAccountAuditWebhook:()=>Qd,updateAccountBranding:()=>Gi,updateAccountMemberRole:()=>sa,updateAccountName:()=>Ki,updateAgentConfig:()=>FA,updateApp:()=>pg,updateAppAccess:()=>hg,updateAppVolume:()=>Ug,updateAuditWebhook:()=>yC,updateChangeRequest:()=>Ll,updateChannelBinding:()=>iR,updateConnectionCredential:()=>vc,updateEmailPolicy:()=>vp,updateExperimentalFeature:()=>fa,updateFeatureFlag:()=>ma,updateGroup:()=>Qp,updateKortixPty:()=>Dm,updateMilestone:()=>iE,updateNotificationPreferences:()=>Jg,updateOAuthClient:()=>yd,updatePassword:()=>po,updatePatPolicy:()=>lC,updatePolicy:()=>LR,updateProject:()=>Un,updateProjectAccess:()=>La,updateProjectAgent:()=>VI,updateProjectDefaultAgent:()=>$u,updateProjectGroupGrant:()=>Ga,updateProjectSandboxProvider:()=>ya,updateProjectSession:()=>lu,updateProjectTrigger:()=>wu,updateRole:()=>cd,updateRolePermissions:()=>ld,updateSandboxTemplate:()=>cl,updateSessionPolicy:()=>oC,updateSessionReminder:()=>Bs,updateSessionReminders:()=>Dd,updateTask:()=>wI,updateTemplateWarmPool:()=>Zk,updateTicket:()=>EI,updateTicketStatus:()=>MI,updateUserMetadata:()=>mo,uploadAccountBrandingAsset:()=>Wi,uploadAppArtifactArchive:()=>bg,uploadConnectorAttachment:()=>Ps,uploadDriveFile:()=>rT,uploadFile:()=>mn,uploadNativeFile:()=>Pb,uploadPromptAttachment:()=>Wn,uploadSessionAttachment:()=>fm,uploadSlackChannelFile:()=>bp,uploadTimeoutMsForBytes:()=>an,upsertCredential:()=>dE,upsertProjectGitCredential:()=>sc,upsertProjectSecret:()=>Za,upsertSsoProvider:()=>QR,validateProjectManifest:()=>la,validateReferralCode:()=>uR,validateToken:()=>ia,verifyGatewayProvider:()=>aR,verifyKortixToken:()=>jw,verifyOtp:()=>ao,verifySsoDomain:()=>ZR,wakeEscalationAttemptSummary:()=>LU,wakeEscalationNote:()=>DU,wakeProgressFingerprint:()=>IU,wireIdClock:()=>Dt,wireIdClockAt:()=>rn,wireIdClockDelta:()=>jt,workedForLabel:()=>gL,workingExpiryAtMs:()=>xU,workingTurnDrawsBusyRow:()=>Xj,writeActivityGroupLabel:()=>KT,writeFile:()=>wr,wsDomain:()=>Vo,wsFavicon:()=>JD,wsRootDomain:()=>YD});var mk={backendUrl:"",getToken:async()=>null},hi=null,Zr=null;function fk(e){Zr=e}function yk(){return Zr}function es(e,t){t?.global!==!1&&(hi=e)}function C(){return Zr?.()??hi??mk}function ts(){return hi!==null||Zr?.()!==void 0}function hk(e){return new Promise(t=>setTimeout(t,e))}async function ns(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await hk(s)),i=await e(),i)return i;return i}var _i=12e4;function _k(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function zy(e,t,n=_i){let r=e instanceof Request?e.signal:t?.signal;if(_k(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function rs(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var S=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},rt=class extends S{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},Pt=class extends S{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},bk="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new S(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:bk})}var ss="feature_disabled";function Yy(e){if(!(e instanceof S)||e.status!==403||e.code!==ss)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function bi(e){let t=Yy(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function xi(e){let t=Yy(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function On(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new rt(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function Si(e){return e instanceof rt}function Bt(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Pi(e){if(!(e instanceof rt))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Re(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Ce(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Re())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function os(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Re())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Jy="request_deadline",xk=/^Request exceeded the \d+s server processing deadline$/,Qy=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Jy||xk.test(n),Sk="git_mirror_unavailable",Pk=/^git mirror is temporarily unavailable$/,wk=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Sk||Pk.test(n),kk="connectors_provider_unavailable",vk=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===kk;async function Ak(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Ce(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Re();return{message:n,data:r}}function Rk(e,t,n){return Qy(e,t,n)||wk(e,t,n)||vk(e,t)||e===501&&t?.code===wi||e===409&&(t?.code===ki||t?.code===vi||t?.code===Ai)||e===503&&(t?.code===Ri||t?.code===Ci)}async function Xy(e,t,n,r){let{message:s,data:o}=await Ak(e,t),i=new S(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Qy(e.status,o,s)?Jy:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=On(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{C().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new Pt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!Rk(e.status,o,s)&&C().onError?.(i,r),{error:i,success:!1}}var Zy="X-Kortix-Impersonate",Ii="kortix.impersonation",wt=null,is=!1,Ti=new Set;function Ei(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function eh(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function Ck(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function th(){for(let e of Ti)try{e()}catch{}}function nh(){return is||(is=!0,wt=Ck(Ei()?.getItem(Ii)??null)),wt&&!eh(wt)?(Mi(),null):wt}function Tk(e){if(is=!0,!e){Mi();return}wt=e;try{Ei()?.setItem(Ii,JSON.stringify(e))}catch{}th()}function Mi(){is=!0;let e=wt!==null;wt=null;try{Ei()?.removeItem(Ii)}catch{}e&&th()}function Ik(e){return Ti.add(e),()=>{Ti.delete(e)}}var Ek=/(^|\/)admin\/(api|analytics)(\/|$)/;function rh(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Ek.test(t)}function Oi(e){if(e!==void 0&&!rh(e))return{};let t=nh();return t?{[Zy]:t.grantId}:{}}var Li=!1;function oh(e){Li=e}function ih(){return Li}function Mk(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function as(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Kt(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function cs(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Mk))Kt(n,s,o);return n}function ji(e,t,n){let r={...t},s=C().clientVersion?.trim();s&&!as(r,"x-kortix-client-version")&&Kt(r,"X-Kortix-Client-Version",s),Li&&Kt(r,"x-kortix-admin-bypass","1");for(let[i,a]of Object.entries(Oi(e)))Kt(r,i,a);let o=C().credentialHeader?.trim();return o?as(r,o)||Kt(r,o,n):as(r,"authorization")||Kt(r,"Authorization",`Bearer ${n}`),r}async function us(e,t){let n=await ls();if(!n)throw new ie;return{headers:new Headers(ji(e,cs(e,{headers:t}),n)),rejected:()=>Dn(n)}}function Ok(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function sh(e,t,n,r,s){if(t instanceof Request){let c=new Headers(ji(t.url,cs(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=ji(o,cs(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var ah=null;async function $i(e){let t=await ns(()=>C().getToken(),e);return t&&(ah=t),t}var ls=$i;function Dn(e=ah){e&&C().getToken.invalidate?.(e)}var Di=new Map;function Dk(e){let t=Di.get(e);if(t)return t;let n=(async()=>(Dn(e),ls({attempts:2,baseDelayMs:200})))().finally(()=>Di.delete(e));return Di.set(e,n),n}async function kt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=_i}=n,o=n.fetch??C().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:zy(e,t,s);if(i?.aborted)throw Re();let a=await(i?Ce(ls(),i):ls());if(!a)throw new ie;let c=r&&!Ok(t)&&!as(cs(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await sh(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await Dk(a);return!g||g===a?d:sh(o,p,t,g,i)}async function Ne(e,t,n,r){let s=await kt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new S(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var ch=()=>C().backendUrl||"",jk=new Set([502,503,504]),Lk=e=>jk.has(e),lh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},$k=e=>lh(e)||(e??"GET").toUpperCase()==="DELETE",Uk=2,ps=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Be(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Fk(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Fk(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Re();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Bk(e,t,c,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Xy(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Ce(p.json(),a.activeController.signal):g?.includes("text/")?d=await Ce(p.text(),a.activeController.signal):d=await Ce(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Kk(c,e,t.method,n,r,s,a)}finally{ds(a)}}function ds(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Nk(e,t,n){try{await Ce(e.arrayBuffer(),t)}catch(r){if(ps(r))throw r}finally{ds(n)}}async function Bk(e,t,n,r,s,o,i){let a=lh(t.method),c=$k(t.method),p=c?Uk+1:1,d;for(let g=0;g<p;g++){g>0&&await os(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Ce(kt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof ie)return new ie;if(i.didTimeout&&ps(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(ps(f)||g===p-1)throw f;continue}if(!a||!Lk(d.status)||g===p-1)return s||ds(i),d;await Nk(d,m.signal,i)}return d}function Kk(e,t,n,r,s,o,i){ds(i);let a=ps(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(ch(),"")||t;c=new S(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new S(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(ch(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&C().onError?.(c,s)):(c=new S(String(e)),r&&C().onError?.(c,s));return{error:c,success:!1}}var Ke=()=>C().backendUrl||"",wi="feature_not_supported",ki="model_not_servable",vi="provision_in_flight",Ai="sandbox_state_change_in_progress",Ri="analytics_unavailable",Ci="accounts_list_unavailable",qk={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new S(r.message||"Database error",{code:r.code,details:r});return C().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return C().onError?.(r,t),{error:r,success:!1}}}};async function Gk(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await kt(`${Ke()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof ie)return rs();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Be(`${Ke()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Be(`${Ke()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Be(`${Ke()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Be(`${Ke()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Be(`${Ke()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Be(`${Ke()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Be(`${Ke()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Be(`${Ke()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Gk};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Ui(e){return e.replace(/\/v1\/?$/,"")}async function qt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Ui(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Fi(){return u(await l.get("/accounts"))}async function Ni(e){return u(await l.post("/accounts",e))}async function Bi(e){return u(await l.get(`/accounts/${e}`))}async function Ki(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function qi(e){return u(await l.get(`/accounts/${e}/branding`))}async function Gi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Wi(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Vi(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function Hi(e){return u(await l.delete(`/accounts/${e}/branding`))}async function zi(e){return u(await l.get(`/accounts/${e}/members`))}async function Yi(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Ji(e){return u(await l.get(`/accounts/${e}/invites`))}async function Qi(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Xi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Zi(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function ea(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function gs(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function uh(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function ta(e,t){let n=await gs(e);return{accepted:n,landing:uh(n,t)}}async function na(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function ra(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function sa(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function oa(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function Wk(e){return qt(e,"/v1/accounts")}async function ia(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Vk=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore"];async function vt(){return u(await l.get("/projects"))}async function aa(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function At(e,t){return u(await l.get(`/projects/${e}`,t))}async function ca(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function la(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ua(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Hk(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function jn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function Ln(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function $n(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function zk(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function pa(e){return u(await l.post("/projects",e))}async function da(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ga(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var ph=200;function Yk(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let s=n.length>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>ph?`${n.slice(0,ph)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function Jk(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new S(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await s.read();if(c)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
|
|
4
4
|
|
|
5
|
-
`);for(;d!==-1;){let
|
|
5
|
+
`);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
|
|
6
6
|
|
|
7
|
-
`);let g=bw(m);if(g){if(t(g),g.type==="error")throw new _(g.error,{status:g.status,code:g.code});g.type==="done"&&(a=g.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function Pw(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function On(e,t){return u(await l.patch(`/projects/${e}`,t))}async function Qi(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Xi(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Zi(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function xw(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Sw(e,t){throw K("updateTemplateWarmPool")}async function ea(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function ww(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Dn(e){return u(await l.delete(`/projects/${e}`))}async function kw(e,t){return Nt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function Aw(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=xi(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ta(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function na(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function ra(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function sa(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function oa(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ia(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function aa(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ca(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function la(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function ua(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function pa(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function da(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function ga(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function ma(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function vw(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function fa(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function ya(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function ha(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function ba(e){return u(await l.get(`/projects/${e}/access`))}async function _a(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Pa(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function Rw(e){return"status"in e&&e.status==="invited"}async function xa(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Sa(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function wa(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ka(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Aa(e){return u(await l.get(`/projects/${e}/group-grants`))}async function va(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ra(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Ta(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Ca(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Ia(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Ea(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Ma(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Oa(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Da(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function ja(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function $a(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function La(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Ua(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Fa(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function ss(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function os(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Na(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Tw=2e3,Cw=3e3,Iw=10*6e4;async function Ew(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=g=>new Promise(y=>setTimeout(y,g)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await ss(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Tw,p.interval_ms||Cw),m=p.expires_at||a()+Iw;for(;!c()&&a()<m;){if(await i(d),c())return{status:"cancelled"};let g;try{g=await os(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(g.status==="success")return{status:"success",credential:g.credential};if(g.status==="failed")return{status:"failed",error:g.error};if(g.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Ka(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ba(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function qa(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ga(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Wa=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Kt=(e,t)=>`${Wa(e)}/${encodeURIComponent(t)}`,gy=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Va(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${Wa(e)}${n}`))}async function Ha(e,t){return u(await l.post(Wa(e),t))}async function Ya(e,t,n){return u(await l.put(`${Kt(e,t)}/value`,{value:n}))}async function za(e,t){return u(await l.post(`${Kt(e,t)}/retry`))}async function Ja(e,t){return u(await l.delete(Kt(e,t)))}async function Qa(e,t,n,r){return u(await l.put(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Xa(e,t,n,r){return u(await l.delete(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Za(e,t,n,r){return u(await l.put(`${Kt(e,t)}/access`,{mode:n,user_ids:r}))}async function ec(e,t,n){return u(await l.get(gy(e,t,n)))}async function tc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function nc(e,t,n,r){return u(await l.put(gy(e,t,n),{secret_ids:r}))}async function is(){return Pi()}async function my(e){return Vr(()=>v().getToken(),e,as)}function as(){Tn()}function Mw(e){e===null&&Tn()}function Ow(e){}async function Bt(){return is()}async function Dw(e){return my(e)}async function $(e,t,n){try{return await xt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof oe)return Hr();throw r}}function cs(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function qt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${cs(e,"catalog")}${r}`)).connectors??[]}async function ls(e){let t=[];for(let n of await qt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function rc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await ls(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function us(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await qt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function jw(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var $w=9e4;async function wt(e,t,n={},r={}){let{connector:s,action:o}=jw(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(cs(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??$w,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function ps(e,t){let n=await l.get(cs(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Lw(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function Uw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function ds(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=Uw(v().backendUrl),a=cs(e,"attachments"),c=await $(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new _(Lw(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function Fw(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function sc(e){return u(await l.get(`/projects/${e}/connections`))}async function oc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function ic(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function ac(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function cc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Be(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Nw(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function Kw(e,t,n){return u(await l.put(Be(e,t,"application"),n))}async function Bw(e,t){return u(await l.get(Be(e,t,"application")))}async function qw(e,t,n){return u(await l.post(Be(e,t,"discover"),n))}async function Gw(e,t,n={}){return u(await l.post(Be(e,t,"discover-resource"),n))}async function Ww(e,t,n){return u(await l.post(Be(e,t,"register"),n))}async function Vw(e,t,n){return u(await l.post(Be(e,t,"authorize"),n))}async function Hw(e,t,n){return u(await l.post(Be(e,t,"device"),n))}async function Yw(e,t,n){return u(await l.post(Be(e,t,`device/${encodeURIComponent(n)}`),{}))}async function zw(e,t){return u(await l.get(Be(e,t,"status")))}async function lc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function uc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function pc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function dc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function gc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function mc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function fc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function yc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function hc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function bc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function _c(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Pc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function xc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Sc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function wc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function Jw(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Qw(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function kc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Ac(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function fy(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var vc=fy;async function Xw(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Rc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Tc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Cc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Ic(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function Ec(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function Zw(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function ek(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function gs(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Mc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ms(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var tk=gs,nk=ms;async function Oc(){return u(await l.get("/connectors/connect-status"))}async function Dc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function jc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function rk(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function yy(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var $c=yy;var jn=class extends _{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:m,requestedAccount:g,...y}=n;super(t,{...y,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=m??[],this.requestedAccount=g??null}},fs=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},ys=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Re=e=>typeof e=="string"&&e?e:null;function hy(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function sk(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function ok(e,t,n){if(!(e instanceof _)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Re(r.reason)??Re(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new jn(Re(r.message)??Re(r.hint)??s,{status:e.status,code:i===null?hy(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Re(r.connector)??t,action:Re(r.action)??n,binding:Re(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:sk(e.response),connectUrl:Re(r.connect_url),hint:Re(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Re(r.requested_account)})}function ik(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function hs(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await wt(e,`${o}.${i}`,r,s)}catch(c){throw ok(c,o,i)}if(a.status==="pending_approval")throw new fs(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new jn(c,{status:200,code:a.upstream_error?"upstream_error":hy(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return ik(a)}async function*Lc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new ys(t,n,i,c);let d=await hs(e,t,n,c,a);yield d,c=o(d,c)}}async function Uc(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Fc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Nc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Kc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function $n(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Bc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function qc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Gc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Wc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Vc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Hc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Yc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Ln(e){let t=new URL(v().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await es(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function zc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Jc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Qc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function Xc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var ak=10*6e4;async function Zc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${v().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Fe(o,{method:"GET"},{timeoutMs:ak},"Failed to download")).blob()}async function el(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Ln(`${v().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function ck(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${v().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Fe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var tl=52428800,lk=104857600,by=20;var _s=e=>`/projects/${encodeURIComponent(e)}/attachments`,Ps={showErrors:!1,deadlineCoversBody:!0},_y=3e4,uk=12e4,pk=6e4,dk=5*6e4,gk=6e4,mk=6e4;function bs(){return new _("Request aborted",{name:"AbortError",code:"ABORTED"})}function Un(e){if(e?.aborted)throw bs()}function fk(e){return!(e instanceof _)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Fn(e,t,n=!1){let r;for(let s=0;;s++){Un(t);try{return await e()}catch(o){let i=n&&o instanceof _&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(fk(o)||i))throw o;r??=Date.now()+(n?dk:pk);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await zr(a,t)}catch{throw Un(t),o}}}}function yk(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function nl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&yk(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function Py(e,t,n,r){return u(await l.post(_s(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Ps,signal:n,timeout:_y}),"Failed to start attachment upload")}async function xy(e,t,n,r){let s=nl({...await Fn(()=>Py(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Sy(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new _(r,{status:e,details:n,code:String(n?.statusCode??e)})}function hk(e){if(!(e instanceof _))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function bk(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=y=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",g),y?o(y):s())},m=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new _("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},gk)},g=()=>{d(bs()),i.abort()};i.open(t.method,t.url);for(let[y,h]of Object.entries(t.headers))i.setRequestHeader(y,h);i.upload.onprogress=y=>{m(),a=Math.min(y.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Sy(i.status,i.responseText))},i.onerror=()=>d(new _("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(bs()),r.signal?.addEventListener("abort",g,{once:!0}),m(),i.send(n)})}async function _k(e,t,n){let r=v().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?bs():new _(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Sy(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function Pk(e,t,n){Un(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?bk(r,e,t,n):_k(e,t,n)}async function xk(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Fn(()=>Pk(i,t,r),r.signal)}catch(a){let c=hk(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await xy(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return wy(e,t,s,r)}async function wy(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${_s(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Un(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Fn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...Ps,signal:r.signal,timeout:_y}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function Nn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");Un(n.signal);let r=n.resume?nl({...n.resume},t):nl({...await Fn(()=>Py(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<mk&&(r=await xy(e,t,r,n)),r=r.upload.kind==="direct"?await xk(e,t,r,n):await wy(e,t,r,n)),n.onProcessing?.();let s=`${_s(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Fn(async()=>u(await l.post(`${s}/complete`,{},{...Ps,signal:n.signal,timeout:uk}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof _&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Gt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${_s(e)}/${encodeURIComponent(t)}`,{...Ps,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function rl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function sl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function ol(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function il(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function al(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function cl(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function ll(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function ul(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function pl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function dl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function gl(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function ml(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function fl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function yl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function hl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function bl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function _l(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var Wt=new Set,Sk=500;function Kn(e){e&&(Wt.add(e),Wt.size>Sk&&Wt.delete(Wt.values().next().value))}function Pl(e){return!!e&&Wt.has(e)}function wk(e){e&&Wt.delete(e)}var ue="kortix.session/2",Pe=1,ky=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Y=e=>typeof e=="string",Te=e=>Y(e)&&e.length>0,Ge=e=>e===null||Y(e),J=(e,t)=>e===void 0||t(e),qe=(...e)=>t=>e.includes(t),Bn=e=>Number.isInteger(e)&&e>=0,Vt=e=>typeof e=="number",Ry=e=>e.schema===ue&&Bn(e.v),kt=e=>J(e,Y),xl=e=>e===void 0||ie(e)&&Object.values(e).every(t=>ie(t)&&Y(t.version)),Ty=e=>e===null||ie(e)&&Y(e.provider)&&Y(e.model)&&kt(e.variant),kk=e=>e===null||ie(e)&&Vt(e.input)&&Vt(e.output)&&Vt(e.cache_read)&&Vt(e.cache_write)&&J(e.reasoning,Vt)&&J(e.cost,Vt),Ay=e=>ie(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),Ak=e=>ie(e)&&Array.isArray(e.content)&&e.content.every(Ay)&&J(e.model_content,t=>Array.isArray(t)&&t.every(Ay))&&typeof e.is_error=="boolean",vy={text:e=>Y(e.text)&&J(e.bytes,Bn)&&kt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&&kt(e.ref)&&J(e.bytes,Bn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Te(e.kind)&&qe("pending","running","complete","error")(e.status)&&J(e.result,Ak),compaction:e=>Ge(e.summary)&&Ge(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>qe("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function vk(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!ie(r)||!Te(r.id)||n.has(r.id)||!Object.hasOwn(vy,r.type)||!vy[r.type](r)||!xl(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Rk(e){return ie(e)&&Ry(e)&&Te(e.message_id)&&Te(e.thread_id)&&Number.isInteger(e.seq)&&qe("user","assistant","system")(e.role)&&qe("turn","compaction","context")(e.kind)&&qe("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,qe("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,qe("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Ge)&&J(e.reply_to,Ge)&&J(e.parent_message_id,Ge)&&kt(e.native_agent_id)&&kt(e.context_ref)&&Ty(e.model)&&kk(e.usage)&&qe("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||ie(e.error)&&Te(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&Ge(e.completed_at)&&ie(e.producer)&&Te(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&xl(e.ext)&&vk(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Tk(e){return ie(e)&&Ry(e)&&Te(e.thread_id)&&Ge(e.parent_thread_id)&&(e.spawned_by===null||ie(e.spawned_by))&&Y(e.created_at)}function Ck(e){return ie(e)&&J(e.schema,t=>t===ue)&&J(e.v,Bn)&&kt(e.session_id)&&J(e.title,Ge)&&kt(e.created_at)&&J(e.restore_grade,qe("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>ie(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>ie(t)&&J(t.agent,Ge)&&Ty(t.model??null))&&J(e.harness,t=>ie(t)&&Y(t.current)&&Array.isArray(t.history))&&xl(e.ext)}function xs(e){return ie(e)&&Bn(e.generation)&&typeof e.has_more=="boolean"&&Ck(e.session)&&Array.isArray(e.threads)&&e.threads.every(Tk)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Rk(t)&&t.thread_id===e.thread_id)}var Ik=e=>xs(e)&&e.messages.length>0;function Ek(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var Cy={paintable:Ik,fit:Ek,capturedAt:()=>0},Mk=new WeakMap;function Iy(e,t,n){Mk.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function My(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Ss=1,Ok=12,Dk=15e5,jk=3e5,$k=336*60*60*1e3,Oy="kortix.saved-copy";function Sl(e){return!!e&&typeof e.then=="function"}function Lk(e,t){return Sl(e)?e.then(t):t(e)}function Uk(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function Fk(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Nk={paintable:My,fit:Uk,capturedAt:Fk};function Kk(e){let t=Ey(e,Nk),n=Ey({...e,namespace:`${e.namespace??Oy}.log`},Cy),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Iy(r,n,t.remove),r}function Ey(e,t){let{storage:n,userId:r,maxSessions:s=Ok,maxBytes:o=Dk,maxEnvelopeBytes:i=jk,maxAgeMs:a=$k,namespace:c=Oy,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,m=`${d}index`,g=(w,S)=>`${d}${w}/${S}`,y=w=>{try{let S=n.getItem(w);return Sl(S)?S.catch(()=>null):S}catch{return null}},h=w=>{try{let S=n.removeItem(w);Sl(S)&&S.catch(()=>{})}catch{}},P=async w=>{try{await n.removeItem(w)}catch{}},C=w=>{if(!w)return[];try{let S=JSON.parse(w);return S?.v===Ss&&Array.isArray(S.entries)?S.entries:[]}catch{return[]}},M=Promise.resolve(),L=w=>{let S=M.then(w,w);return M=S.catch(()=>{}),S},f=async w=>{try{await n.setItem(m,JSON.stringify({v:Ss,entries:w}))}catch{}},b=async()=>C(await y(m)),x=async(w,S)=>{let I=[...w].sort((U,j)=>U.u-j.u),k=I.reduce((U,j)=>U+j.b,0);for(;I.length>s||k>o;){let U=I.findIndex(D=>D.s!==S);if(U===-1)break;let[j]=I.splice(U,1);k-=j.b,await P(`${d}${j.s}`)}return I},R=w=>{L(async()=>{let S=await b(),I=S.find(k=>k.s===w);I&&(I.u=p(),await f(S))})},T=w=>L(async()=>{await P(`${d}${w}`);let S=await b(),I=S.filter(k=>k.s!==w);I.length!==S.length&&await f(I)});return{keyFor:g,read(w,S){let I=`${w}/${S}`;return Lk(y(g(w,S)),k=>{if(!k)return null;let U;try{U=JSON.parse(k)}catch{return h(g(w,S)),T(I),null}return!U||U.v!==Ss||U.user!==r||p()-U.at>a||!t.paintable(U.e)?(h(g(w,S)),T(I),null):(R(I),U.e)})},write(w,S,I){let k=`${w}/${S}`;if(!t.paintable(I))return T(k);let U={v:Ss,user:r,at:p(),e:I},j=t.fit(U,i);if(j===null)return T(k);let D=t.capturedAt(I);return L(async()=>{let q=await b(),Q=q.find($e=>$e.s===k);if(Q&&D>0&&Q.c>D)return;let W=q.filter($e=>$e.s!==k),An={s:k,b:j.length,u:p(),c:D},je=await x([...W,An],k),vn=g(w,S);try{await n.setItem(vn,j)}catch{let $e=je.filter(ne=>ne.s!==k).sort((ne,yt)=>ne.u-yt.u)[0];$e&&(await P(`${d}${$e.s}`),je=je.filter(ne=>ne.s!==$e.s));try{await n.setItem(vn,j)}catch{await P(vn),je=je.filter(ne=>ne.s!==k)}}await f(je)})},remove(w,S){return T(`${w}/${S}`)},clear(){return L(async()=>{let w=await b();for(let S of w)await P(`${d}${S.s}`);await P(m)})}}}var Dy=null;function Bk(e){Dy=e}function wl(){return Dy}var qk=new Set;function jy(e){for(let t of qk)try{t(e)}catch{}}var $y=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await l.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data};function Gk(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var Wk=50,Ly=200,Vk=Ly;function Uy(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function kl(e,t){let n=await l.get(`/projects/${e}/sessions${Uy(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function At(e,t){return u(await l.get(`/projects/${e}/sessions${Uy(t)}`))}async function Al(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function vl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Rl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Tl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function Hk(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function Yk(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Cl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Il(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function El(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Ml(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function vt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Kn(n?.session_id),n}async function Ol(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Kn(r.session.session_id),r}async function Dl(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Kn(n.session_id),n}async function qn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function jl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function $l(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Ll(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Ul(e,t,n={},r){let s;try{s=await $y(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!xs(s))throw new Error("The response is not a session log page");return s}async function Fl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function zk(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function Jk(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Gn(e,t,n){let r=n.placement??Jk(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Nl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Kl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Bl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function ql(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Gl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Wl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Vl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Hl(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return wl()?.remove(e,t),n}async function Wn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function Vn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return jy(t),n}async function Yl(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Qk(e){let t=e.split(`
|
|
7
|
+
`);let m=Yk(g);if(m){if(t(m),m.type==="error")throw new S(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function Qk(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Un(e,t){return u(await l.patch(`/projects/${e}`,t))}async function ma(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function fa(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ya(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Xk(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Zk(e,t){throw F("updateTemplateWarmPool")}async function ha(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function ev(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Fn(e){return u(await l.delete(`/projects/${e}`))}async function tv(e,t){return qt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function nv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Ui(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function _a(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ba(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function xa(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Sa(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Pa(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function wa(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function ka(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function va(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Aa(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Ra(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Ca(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ta(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Ia(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Ea(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function rv(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Ma(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function Oa(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Da(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function ja(e){return u(await l.get(`/projects/${e}/access`))}async function La(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function $a(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function sv(e){return"status"in e&&e.status==="invited"}async function Ua(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Fa(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Na(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ba(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ka(e){return u(await l.get(`/projects/${e}/group-grants`))}async function qa(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ga(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Wa(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Va(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Ha(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function za(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Ya(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ja(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Qa(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Xa(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Za(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function ec(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function tc(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function nc(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function ms(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function fs(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function rc(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var ov=2e3,iv=3e3,av=10*6e4;async function cv(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await ms(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(ov,p.interval_ms||iv),g=p.expires_at||a()+av;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await fs(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function sc(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function oc(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function ic(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function ac(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var cc=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Gt=(e,t)=>`${cc(e)}/${encodeURIComponent(t)}`,dh=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function lc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${cc(e)}${n}`))}async function uc(e,t){return u(await l.post(cc(e),t))}async function pc(e,t,n){return u(await l.put(`${Gt(e,t)}/value`,{value:n}))}async function dc(e,t){return u(await l.post(`${Gt(e,t)}/retry`))}async function gc(e,t){return u(await l.delete(Gt(e,t)))}async function mc(e,t,n,r){return u(await l.put(`${Gt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function fc(e,t,n,r){return u(await l.delete(`${Gt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function yc(e,t,n,r){return u(await l.put(`${Gt(e,t)}/access`,{mode:n,user_ids:r}))}async function hc(e,t,n){return u(await l.get(dh(e,t,n)))}async function _c(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function bc(e,t,n,r){return u(await l.put(dh(e,t,n),{secret_ids:r}))}async function ys(){return $i()}async function gh(e){return ns(()=>C().getToken(),e,hs)}function hs(){Dn()}function lv(e){e===null&&Dn()}function uv(e){}async function Wt(){return ys()}async function pv(e){return gh(e)}async function L(e,t,n){try{return await kt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return rs();throw r}}function _s(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Vt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${_s(e,"catalog")}${r}`)).connectors??[]}async function bs(e){let t=[];for(let n of await Vt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function xc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await bs(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function xs(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Vt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function dv(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var gv=9e4;async function Rt(e,t,n={},r={}){let{connector:s,action:o}=dv(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(_s(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??gv,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function Ss(e,t){let n=await l.get(_s(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function mv(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function fv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function Ps(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=fv(C().backendUrl),a=_s(e,"attachments"),c=await L(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new S(mv(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function yv(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function Sc(e){return u(await l.get(`/projects/${e}/connections`))}async function Pc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function wc(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function kc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function vc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function qe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function hv(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function _v(e,t,n){return u(await l.put(qe(e,t,"application"),n))}async function bv(e,t){return u(await l.get(qe(e,t,"application")))}async function xv(e,t,n){return u(await l.post(qe(e,t,"discover"),n))}async function Sv(e,t,n={}){return u(await l.post(qe(e,t,"discover-resource"),n))}async function Pv(e,t,n){return u(await l.post(qe(e,t,"register"),n))}async function wv(e,t,n){return u(await l.post(qe(e,t,"authorize"),n))}async function kv(e,t,n){return u(await l.post(qe(e,t,"device"),n))}async function vv(e,t,n){return u(await l.post(qe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Av(e,t){return u(await l.get(qe(e,t,"status")))}async function Ac(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Rc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Cc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Tc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Ic(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Ec(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Mc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Oc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Dc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function jc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Lc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function $c(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Uc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Fc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Nc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function Rv(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Cv(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Bc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function mh(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var qc=mh;async function Tv(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Gc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Wc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Iv(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Vc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Hc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function zc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function Ev(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function Mv(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ws(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Yc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ks(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var Ov=ws,Dv=ks;async function Jc(){return u(await l.get("/connectors/connect-status"))}async function Qc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Xc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function jv(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function fh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Zc=fh;var Nn=class extends S{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},vs=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},As=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Te=e=>typeof e=="string"&&e?e:null;function yh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Lv(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function $v(e,t,n){if(!(e instanceof S)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Te(r.reason)??Te(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new Nn(Te(r.message)??Te(r.hint)??s,{status:e.status,code:i===null?yh(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Te(r.connector)??t,action:Te(r.action)??n,binding:Te(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Lv(e.response),connectUrl:Te(r.connect_url),hint:Te(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Te(r.requested_account)})}function Uv(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function Rs(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await Rt(e,`${o}.${i}`,r,s)}catch(c){throw $v(c,o,i)}if(a.status==="pending_approval")throw new vs(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Nn(c,{status:200,code:a.upstream_error?"upstream_error":yh(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return Uv(a)}async function*el(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new As(t,n,i,c);let d=await Rs(e,t,n,c,a);yield d,c=o(d,c)}}async function tl(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function nl(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function rl(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function sl(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Bn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function ol(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function il(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function al(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function cl(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ll(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function ul(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function pl(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Kn(e){let t=new URL(C().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await us(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function dl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function gl(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function ml(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function fl(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Fv=10*6e4;async function yl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${C().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Ne(o,{method:"GET"},{timeoutMs:Fv},"Failed to download")).blob()}async function hl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Kn(`${C().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function Nv(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${C().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Ne(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var _l=52428800,Bv=104857600,hh=20;var Ts=e=>`/projects/${encodeURIComponent(e)}/attachments`,Is={showErrors:!1,deadlineCoversBody:!0},_h=3e4,Kv=12e4,qv=6e4,Gv=5*6e4,Wv=6e4,Vv=6e4;function Cs(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function qn(e){if(e?.aborted)throw Cs()}function Hv(e){return!(e instanceof S)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Gn(e,t,n=!1){let r;for(let s=0;;s++){qn(t);try{return await e()}catch(o){let i=n&&o instanceof S&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(Hv(o)||i))throw o;r??=Date.now()+(n?Gv:qv);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await os(a,t)}catch{throw qn(t),o}}}}function zv(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function bl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&zv(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function bh(e,t,n,r){return u(await l.post(Ts(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Is,signal:n,timeout:_h}),"Failed to start attachment upload")}async function xh(e,t,n,r){let s=bl({...await Gn(()=>bh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Sh(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function Yv(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function Jv(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new S("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},Wv)},m=()=>{d(Cs()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Sh(i.status,i.responseText))},i.onerror=()=>d(new S("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Cs()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function Qv(e,t,n){let r=C().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?Cs():new S(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Sh(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function Xv(e,t,n){qn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?Jv(r,e,t,n):Qv(e,t,n)}async function Zv(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Gn(()=>Xv(i,t,r),r.signal)}catch(a){let c=Yv(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await xh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Ph(e,t,s,r)}async function Ph(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Ts(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){qn(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Gn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...Is,signal:r.signal,timeout:_h}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function Wn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");qn(n.signal);let r=n.resume?bl({...n.resume},t):bl({...await Gn(()=>bh(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<Vv&&(r=await xh(e,t,r,n)),r=r.upload.kind==="direct"?await Zv(e,t,r,n):await Ph(e,t,r,n)),n.onProcessing?.();let s=`${Ts(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Gn(async()=>u(await l.post(`${s}/complete`,{},{...Is,signal:n.signal,timeout:Kv}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof S&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Ht(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${Ts(e)}/${encodeURIComponent(t)}`,{...Is,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function xl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function Sl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function Pl(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function wl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function kl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function vl(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function Al(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function Rl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function Cl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function Tl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Il(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function El(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Ml(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Ol(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Dl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function jl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Ll(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var zt=new Set,eA=500;function Vn(e){e&&(zt.add(e),zt.size>eA&&zt.delete(zt.values().next().value))}function $l(e){return!!e&&zt.has(e)}function tA(e){e&&zt.delete(e)}var pe="kortix.session/2",Se=1,wh=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Y=e=>typeof e=="string",Ie=e=>Y(e)&&e.length>0,We=e=>e===null||Y(e),J=(e,t)=>e===void 0||t(e),Ge=(...e)=>t=>e.includes(t),Hn=e=>Number.isInteger(e)&&e>=0,Yt=e=>typeof e=="number",Ah=e=>e.schema===pe&&Hn(e.v),Ct=e=>J(e,Y),Ul=e=>e===void 0||ae(e)&&Object.values(e).every(t=>ae(t)&&Y(t.version)),Rh=e=>e===null||ae(e)&&Y(e.provider)&&Y(e.model)&&Ct(e.variant),nA=e=>e===null||ae(e)&&Yt(e.input)&&Yt(e.output)&&Yt(e.cache_read)&&Yt(e.cache_write)&&J(e.reasoning,Yt)&&J(e.cost,Yt),kh=e=>ae(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),rA=e=>ae(e)&&Array.isArray(e.content)&&e.content.every(kh)&&J(e.model_content,t=>Array.isArray(t)&&t.every(kh))&&typeof e.is_error=="boolean",vh={text:e=>Y(e.text)&&J(e.bytes,Hn)&&Ct(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&&Ct(e.ref)&&J(e.bytes,Hn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Ie(e.kind)&&Ge("pending","running","complete","error")(e.status)&&J(e.result,rA),compaction:e=>We(e.summary)&&We(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>Ge("start","finish")(e.phase),harness:e=>Ie(e.harness)&&Ie(e.kind)&&typeof e.model_visible=="boolean"};function sA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!ae(r)||!Ie(r.id)||n.has(r.id)||!Object.hasOwn(vh,r.type)||!vh[r.type](r)||!Ul(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function oA(e){return ae(e)&&Ah(e)&&Ie(e.message_id)&&Ie(e.thread_id)&&Number.isInteger(e.seq)&&Ge("user","assistant","system")(e.role)&&Ge("turn","compaction","context")(e.kind)&&Ge("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,Ge("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,Ge("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,We)&&J(e.reply_to,We)&&J(e.parent_message_id,We)&&Ct(e.native_agent_id)&&Ct(e.context_ref)&&Rh(e.model)&&nA(e.usage)&&Ge("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||ae(e.error)&&Ie(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&We(e.completed_at)&&ae(e.producer)&&Ie(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&Ul(e.ext)&&sA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function iA(e){return ae(e)&&Ah(e)&&Ie(e.thread_id)&&We(e.parent_thread_id)&&(e.spawned_by===null||ae(e.spawned_by))&&Y(e.created_at)}function aA(e){return ae(e)&&J(e.schema,t=>t===pe)&&J(e.v,Hn)&&Ct(e.session_id)&&J(e.title,We)&&Ct(e.created_at)&&J(e.restore_grade,Ge("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>ae(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>ae(t)&&J(t.agent,We)&&Rh(t.model??null))&&J(e.harness,t=>ae(t)&&Y(t.current)&&Array.isArray(t.history))&&Ul(e.ext)}function Es(e){return ae(e)&&Hn(e.generation)&&typeof e.has_more=="boolean"&&aA(e.session)&&Array.isArray(e.threads)&&e.threads.every(iA)&&(e.thread_id===null||Ie(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>oA(t)&&t.thread_id===e.thread_id)}var cA=e=>Es(e)&&e.messages.length>0;function lA(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var Ch={paintable:cA,fit:lA,capturedAt:()=>0},uA=new WeakMap;function Th(e,t,n){uA.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function Eh(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Ms=1,pA=12,dA=15e5,gA=3e5,mA=336*60*60*1e3,Mh="kortix.saved-copy";function Fl(e){return!!e&&typeof e.then=="function"}function fA(e,t){return Fl(e)?e.then(t):t(e)}function yA(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function hA(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var _A={paintable:Eh,fit:yA,capturedAt:hA};function bA(e){let t=Ih(e,_A),n=Ih({...e,namespace:`${e.namespace??Mh}.log`},Ch),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Th(r,n,t.remove),r}function Ih(e,t){let{storage:n,userId:r,maxSessions:s=pA,maxBytes:o=dA,maxEnvelopeBytes:i=gA,maxAgeMs:a=mA,namespace:c=Mh,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(x,P)=>`${d}${x}/${P}`,f=x=>{try{let P=n.getItem(x);return Fl(P)?P.catch(()=>null):P}catch{return null}},h=x=>{try{let P=n.removeItem(x);Fl(P)&&P.catch(()=>{})}catch{}},_=async x=>{try{await n.removeItem(x)}catch{}},I=x=>{if(!x)return[];try{let P=JSON.parse(x);return P?.v===Ms&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},j=Promise.resolve(),D=x=>{let P=j.then(x,x);return j=P.catch(()=>{}),P},w=async x=>{try{await n.setItem(g,JSON.stringify({v:Ms,entries:x}))}catch{}},y=async()=>I(await f(g)),b=async(x,P)=>{let O=[...x].sort(($,K)=>$.u-K.u),v=O.reduce(($,K)=>$+K.b,0);for(;O.length>s||v>o;){let $=O.findIndex(T=>T.s!==P);if($===-1)break;let[K]=O.splice($,1);v-=K.b,await _(`${d}${K.s}`)}return O},R=x=>{D(async()=>{let P=await y(),O=P.find(v=>v.s===x);O&&(O.u=p(),await w(P))})},k=x=>D(async()=>{await _(`${d}${x}`);let P=await y(),O=P.filter(v=>v.s!==x);O.length!==P.length&&await w(O)});return{keyFor:m,read(x,P){let O=`${x}/${P}`;return fA(f(m(x,P)),v=>{if(!v)return null;let $;try{$=JSON.parse(v)}catch{return h(m(x,P)),k(O),null}return!$||$.v!==Ms||$.user!==r||p()-$.at>a||!t.paintable($.e)?(h(m(x,P)),k(O),null):(R(O),$.e)})},write(x,P,O){let v=`${x}/${P}`;if(!t.paintable(O))return k(v);let $={v:Ms,user:r,at:p(),e:O},K=t.fit($,i);if(K===null)return k(v);let T=t.capturedAt(O);return D(async()=>{let q=await y(),G=q.find($e=>$e.s===v);if(G&&T>0&&G.c>T)return;let V=q.filter($e=>$e.s!==v),En={s:v,b:K.length,u:p(),c:T},Le=await b([...V,En],v),Mn=m(x,P);try{await n.setItem(Mn,K)}catch{let $e=Le.filter(re=>re.s!==v).sort((re,bt)=>re.u-bt.u)[0];$e&&(await _(`${d}${$e.s}`),Le=Le.filter(re=>re.s!==$e.s));try{await n.setItem(Mn,K)}catch{await _(Mn),Le=Le.filter(re=>re.s!==v)}}await w(Le)})},remove(x,P){return k(`${x}/${P}`)},clear(){return D(async()=>{let x=await y();for(let P of x)await _(`${d}${P.s}`);await _(g)})}}}var Oh=null;function xA(e){Oh=e}function Nl(){return Oh}var SA=new Set;function Dh(e){for(let t of SA)try{t(e)}catch{}}var jh=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await l.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data};function PA(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var wA=50,Lh=200,kA=Lh;function $h(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Bl(e,t){let n=await l.get(`/projects/${e}/sessions${$h(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Tt(e,t){return u(await l.get(`/projects/${e}/sessions${$h(t)}`))}async function Kl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function ql(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Gl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Wl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Vl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Hl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function vA(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function AA(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function zl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Yl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Jl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Ql(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function It(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Vn(n?.session_id),n}async function Xl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Vn(r.session.session_id),r}async function Zl(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Vn(n.session_id),n}async function zn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function eu(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function tu(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Yn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function nu(e,t,n={},r){let s;try{s=await jh(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Es(s))throw new Error("The response is not a session log page");return s}async function Jn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function RA(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function CA(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Qn(e,t,n){let r=n.placement??CA(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function ru(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function su(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function ou(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function iu(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function au(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function cu(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function lu(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function uu(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Nl()?.remove(e,t),n}async function pu(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function du(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Xn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Zn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return Dh(t),n}async function gu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function TA(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function mu(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function fu(e,t,n,r,s={}){let o=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new S(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
|
|
10
10
|
|
|
11
|
-
`);for(;
|
|
11
|
+
`);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let h=Qk(y);if(h){if(r(h),h.type==="error")throw new _(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function Ql(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function Xl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Zl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function eu(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function tu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function nu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function Xk(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function ru(e){return u(await l.get(`/projects/${e}/triggers`))}async function su(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function ou(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function iu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function au(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function cu(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function lu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function uu(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function pu(e,t){return`${e}::${t}`}function Fy(e,t){tt.delete(e),tt.set(e,t)}function Ny(e,t){let n=pu(e,t),r=tt.get(n);return r&&Fy(n,r),r}function ws(e,t,n){let r=pu(e,t);if(!tt.has(r)&&tt.size>=512){let s=tt.keys().next().value;s!==void 0&&tt.delete(s)}Fy(r,n)}function Ky(e,t){tt.delete(pu(e,t))}function Zk(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Hn(){return Zk(v().backendUrl||"http://localhost:8008/v1")}function By(){let e=v().sandboxId;return e?`${Hn()}/p/${e}/8000`:""}function eA(e,t=8e3){return`${Hn()}/p/${e}/${t}`}function Ce(e,t=8e3){return eA(e,t)}function du(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var ks=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function tA(e){return e instanceof Error&&e.name==="SessionStartError"}function nA(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new ks(s,{status:n,code:r,terminal:!0}):null}function qy(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function nt(e,t,n){let r=await qy(e,t,n);if(!r.success||!r.data){let s=nA(r.error);if(s&&!(s.status===404&&Pl(t)))throw s;return null}return Gy(e,t,r.data)}async function gu(e,t,n){let r=await qy(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Gy(e,t,r.data)}function Gy(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&ws(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ce(r),sandboxId:r}),n}function rA(e,t){return["session-start",e,t]}async function mu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function fu(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function yu(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function sA(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Wy(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function oA(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function As(e){let t=e.connectors_required?Wy(e.connectors_required):void 0,n=e.connectors_personal?Wy(e.connectors_personal):void 0;if(t&&n&&!oA(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function hu(e,t,n){let r=As(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function iA(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?bu(n.block):null}}async function aA(e,t,n){let r=bu(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?bu(s.block):null}}function bu(e,t=!1){let n=As(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function cA(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function _u(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Vy="Use createPerSeatCheckout().";function Pu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function lA(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function uA(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??Pu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:lA(r),label:s,sublabel:null,isGrandfathered:!1}}function Hy(e){return!!e&&e.can_manage_billing!==!1}function pA(e){return e?.subscription?.can_purchase_credits===!0&&Hy(e)}async function Yy(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Pu():t.data}function zy(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function xu(e){return Yy(`/billing/account-state${zy(e)}`)}async function Su(e){return Yy(`/billing/account-state/minimal${zy(e)}`)}async function wu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Au(){return u(await l.get("/billing/credit-breakdown"))}async function vu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Ru(){return u(await l.get("/billing/tier-configurations"))}async function dA(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Nt(e,`/v1/billing/account-state${t}`)}async function Tu(e){throw K("createCheckoutSession",Vy)}async function Cu(e,t){throw K("confirmCheckoutSession",Vy)}async function Iu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Eu(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Mu(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Ou(e,t,n){throw K("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Du(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function ju(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function $u(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Lu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function gA(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Uu(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function mA(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function fA(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function yA(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function hA(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Fu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Ku(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function vs(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Rs(e){return e.size>0?`?${e}`:""}async function Bu(e={}){let t=new URLSearchParams;return Ku(t,e),e.ownerId&&t.set("owner_id",e.ownerId),vs(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Rs(t)}`))}async function Yn(e,t={}){let n=new URLSearchParams;return Ku(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Rs(n)}`))}async function bA(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),vs(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Rs(t)}`))}async function _A(e={}){let t=new URLSearchParams;return Ku(t,e),e.sessionId&&t.set("session_id",e.sessionId),vs(t,e),u(await l.get(`/usage/cost-summary${Rs(t)}`))}function Nu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}vs(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${v().backendUrl||""}${r}?${n}`}async function PA(e,t={}){let n=Nu(e==="projects"?"projects":"sessions",t),r=await Fe(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Jy(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function xA(e){return Jy("slack",e)}function SA(e){return Jy("teams",e)}async function Qy(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function wA(e){return Qy("slack",e)}function kA(e){return Qy("teams",e)}async function qu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Gu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var AA={oauth_available:!1,install_url:null};async function Wu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?AA:t.data}async function Xy(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function Vu(e,t){return Xy("slack",e,t)}function Hu(e,t){return Xy("teams",e,t)}async function Yu(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function zu(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Ju(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function Qu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function Xu(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var vA={provider:"agentmail",managed_available:!1};async function Zu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?Xu(r.data):null}async function ep(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?vA:t.data}async function tp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Xu(n)}async function np(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function rp(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return Xu(r)}async function RA(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function TA(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function sp(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function op(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function ip(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function ap(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function cp(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function lp(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function up(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function pp(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function dp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function gp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function mp(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function fp(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function yp(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function hp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function bp(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function _p(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Pp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function xp(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function CA(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function IA(){throw K("getReferralCode")}async function EA(){throw K("refreshReferralCode")}async function MA(e){throw K("validateReferralCode")}async function OA(){throw K("getReferralStats")}async function DA(e={}){throw K("listReferrals")}async function jA(e){throw K("sendReferralEmails")}var Sp="call:";function kp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Sp)&&e.length>Sp.length?{type:"connector_call",executionId:e.slice(Sp.length)}:{type:"review_item",reviewItemId:e}}function eh(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function $A(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[eh(n.status)]+=1;return t}function LA(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function wp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ap(e){let t=e.indexOf(".");return t<=0?wp(e):`(${wp(e.slice(0,t))}) ${wp(e.slice(t+1))}`}function UA(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Ts=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},N=e=>typeof e=="string"&&e?e:void 0,Ie=e=>Array.isArray(e)?e:void 0,Zy=e=>typeof e=="number"?e:0,FA=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function NA(e,t){let n=Ts(e.advanced),r=N(e.description),s=Ie(e.whatChanged)??(r?FA(r):t.summary?[t.summary]:[]);return{crId:N(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:N(e.impact)??"",verification:Ie(e.verification)??[],previewUrl:N(e.previewUrl)??N(e.preview_url),conflicts:Ie(e.conflicts),requestedChanges:Ie(e.requested_changes)??[],advanced:{headRef:N(n.headRef)??N(e.head_ref)??"",baseRef:N(n.baseRef)??N(e.base_ref)??"",headSha:N(n.headSha)??N(e.head_sha)??N(e.head_commit_sha)??"",baseSha:N(n.baseSha)??N(e.base_sha)??"",additions:Zy(n.additions),deletions:Zy(n.deletions),files:Ie(n.files)??[],mergeMode:N(n.mergeMode)??"merge"}}}function KA(e,t){let n=Ie(e.actions);if(n)return{actions:n.map((c,p)=>({id:N(c.id)??`${t.review_item_id}-${p}`,title:N(c.title)??"Action",connector:N(c.connector)??"",action:N(c.action)??"",consequence:N(c.consequence)??"",risk:N(c.risk)??t.risk,icon:N(c.icon)??"generic",argsPreview:Ie(c.argsPreview)??[],policySource:N(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=N(e.action_path)??"",{connector:s,action:o}=UA(r),i=Ts(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:N(e.execution_id)??t.review_item_id,title:r?Ap(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:N(e.approval_context),connectorRisk:N(e.risk)??null,policySource:"Requires approval"}]}}function BA(e,t){return{artifactKind:N(e.artifactKind)??"document",artifactLabel:N(e.artifactLabel)??"Output",previewUrl:N(e.previewUrl)??N(e.preview_url),preview:N(e.preview),files:Ie(e.files),note:N(e.note)??t.summary??""}}function qA(e,t){return{question:N(e.question)??t.title??"",context:N(e.context),options:Ie(e.options)??[]}}function GA(e,t){return{note:N(e.note)??t.summary??"",children:Ie(e.children)??[]}}function WA(e){let t=Ts(e.detail);switch(e.kind){case"change":return NA(t,e);case"approval":return KA(t,e);case"output":return BA(t,e);case"decision":return qA(t,e);case"batch":return GA(t,e)}}function VA(e,t){let n=typeof e.number=="number"?e.number:void 0,r=N(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function HA(e,t={}){let n=Ts(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?N(n.action_path):void 0,i=e.kind==="change"?VA(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Ap(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:WA(e)}}var X={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},YA=[X.PROJECT_WRITE,X.PROJECT_TRIGGER_CREATE,X.PROJECT_TRIGGER_FIRE,X.PROJECT_TRIGGER_UPDATE,X.PROJECT_TRIGGER_DELETE];function zA(e){let t=r=>e[r]?.allowed===!0,n=t(X.PROJECT_WRITE);return{canCreate:n&&t(X.PROJECT_TRIGGER_CREATE),canFire:t(X.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(X.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(X.PROJECT_TRIGGER_DELETE)}}var JA=[X.PROJECT_WRITE,X.PROJECT_GITOPS_PUSH,X.PROJECT_GITOPS_MERGE,X.PROJECT_REVIEW_ACT];function th(e){let t=r=>e[r]?.allowed===!0,n=t(X.PROJECT_WRITE);return{canOpen:n&&t(X.PROJECT_GITOPS_PUSH),canMerge:n&&t(X.PROJECT_GITOPS_MERGE),canClose:n}}function QA(e,t,n){let r=kp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return th(n).canMerge}return n[X.PROJECT_WRITE]?.allowed===!0&&n[X.PROJECT_REVIEW_ACT]?.allowed===!0}function F(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function vp(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Rp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Tp(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Cp(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Ip(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Ep(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Mp(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function XA(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Op(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function ZA(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function ev(e,t){let n=A(await F(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function rt(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function tv(e,t={}){let n=rt({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await F(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function nv(e,t={}){let n=rt({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await F(`/accounts/${e}/iam/policies${n}`)).policies}async function rv(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function sv(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function ov(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function iv(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function av(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Dp(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function jp(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function $p(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Lp(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function cv(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function Up(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function Fp(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Np(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Kp(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Bp(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function lv(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function uv(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function pv(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function dv(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function gv(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function mv(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function fv(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function yv(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function hv(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function bv(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function _v(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function Pv(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function xv(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function Sv(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function wv(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function kv(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function Av(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function vv(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function Rv(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function Tv(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function Cv(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function Iv(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function Ev(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function Mv(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Ov(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function Dv(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function jv(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function $v(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function Lv(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function Uv(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Fv(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Nv(e,t={}){let n=rt({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await F(`/accounts/${e}/audit${n}`))}async function qp(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await F(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Gp(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function Kv(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function Bv(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Wp(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Vp(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Hp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Yp(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function zp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Jp(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function qv(e){return rt({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function Qp(e,t){return u(await F(`/accounts/${e}/iam/assignments${qv(t)}`)).assignments}async function Xp(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function Zp(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function ed(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function Gv(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function Wv(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function Vv(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Hv(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function Yv(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function zv(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function Jv(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function Qv(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function Xv(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function Zv(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function eR(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function tR(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var nh="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function nR(e){throw K("getGoogleAuthUrl",nh)}async function rR(e,t){throw K("convertPresentationToGoogleSlides",nh)}async function td(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function nd(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function rd(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function sd(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function od(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function id(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function ad(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function cd(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Cs=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function rh(e,t=""){return`${Hn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function sh(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Cs(s,t.status)}return r}async function sR(e){return sh(rh(e))}async function oR(e){return sh(rh(e,"/messages"))}async function ld(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function ud(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Is(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Es(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var iR=4;async function oh(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(iR,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function pd(e,t,n){return oh(t,r=>Is(e,r.sessionId,r.reminderId,n))}function dd(e,t){return oh(t,n=>Es(e,n.sessionId,n.reminderId))}async function gd(e){return u(await l.get(`/projects/${e}/reminders`))}async function md(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function fd(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function yd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function hd(){return u(await l.get("/oauth/grants")).grants}async function bd(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function aR(){return u(await l.get("/accounts/me/devices")).devices}async function cR(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function _d(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Pd(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function xd(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Ht(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function Sd(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function wd(e,t){let n=Ht(Sd(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function kd(e,t){let n=Ht(Sd({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Ad(e,t){let n=Ht(Sd(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function vd(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Rd(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Td(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Cd(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Id(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Ed(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function lR(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Md(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function Od(){return u(await l.get("/marketplace/marketplaces"))}async function Dd(){return u(await l.get("/marketplace/marketplaces/featured"))}async function jd(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function $d(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Ld(){return u(await l.get("/marketplace/sources"))}async function Ud(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Fd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function uR(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function pR(e){throw K("getTemplate")}async function dR(e,t){throw K("installTemplate")}async function Nd(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Kd(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Ms(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Bd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function qd(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Gd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Wd(e,t){let n=await Ms(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function Vd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Hd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Yd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function zd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Os(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Ds(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function gR(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function mR(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function Jd(e,t,n={}){let r=await gR(t),s=n.mediaType??"application/gzip",o=await Os(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Ds(e,o.artifact.artifact_id,{sha256:await mR(r),size_bytes:r.byteLength})}async function Qd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Xd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Zd(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function eg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function tg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function ng(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function rg(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function sg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var xe=(e,t)=>`/projects/${e}/apps/${t}`;async function og(e,t){return u(await l.get(`${xe(e,t)}/machines`),"Failed to list machines").machines}async function ig(e,t,n,r){return u(await l.post(`${xe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ag=(e,t,n)=>ig(e,t,n,"start"),cg=(e,t,n)=>ig(e,t,n,"stop"),lg=(e,t,n)=>ig(e,t,n,"restart");async function ug(e,t,n){return u(await l.delete(`${xe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function pg(e,t,n){return u(await l.put(`${xe(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function dg(e,t,n){return u(await l.post(`${xe(e,t)}/exec`,n),"Failed to run the command")}async function gg(e,t){return u(await l.get(`${xe(e,t)}/volumes`),"Failed to list volumes").volumes}async function mg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes`,n),"Failed to create the volume")}async function fg(e,t,n,r){return u(await l.patch(`${xe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function yg(e,t,n,r){u(await l.delete(`${xe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function hg(e,t,n){return u(await l.get(`${xe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function bg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function _g(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Pg(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var me=e=>`/drives/${encodeURIComponent(e)}`;async function fR(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new _("Files not found",{status:404});return t[0]}async function yR(e,t){return u(await l.get(`${me(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function hR(e,t){return u(await l.put(`${me(e)}/access`,t),"Failed to share folder")}async function bR(e,t){let n=u(await l.delete(`${me(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function _R(e){return u(await l.get(`${me(e)}/principals`),"Failed to load people")}async function PR(e){return u(await l.get(`${me(e)}/conflicts`),"Failed to load conflicts").conflicts}async function xR(e,t){u(await l.post(`${me(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function SR(e,t="/"){return(await ih(e,t)).entries}async function ih(e,t="/"){return u(await l.get(`${me(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function xg(e,t,n){let r=de(v().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${me(e)}/files/content?${new URLSearchParams(s)}`}async function wR(e,t,n){let r=await $(xg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function kR(e,t,n){let r=await $(xg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function AR(e,t,n,r){return u(await l.putRaw(`${me(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function vR(e,t){return u(await l.post(`${me(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function RR(e,t,n){return u(await l.post(`${me(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function TR(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${me(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function CR(e){return u(await l.get(`${me(e)}/versions`),"Failed to load versions").versions}async function IR(e,t){u(await l.post(`${me(e)}/restore`,{versionId:t}),"Failed to restore version")}var ER=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function MR(e,t){return(await ah(e,t)).drives}async function ah(e,t){return u(await l.get(ER(e,t)),"Failed to load session files")}async function Sg(e){return u(await l.post("/notifications/device-token",e))}async function wg(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var OR=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function kg(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Ag(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var DR={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1}};async function vg(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Rg(e){return u(await l.put("/notifications/preferences",e))}async function Tg(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Cg(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Ig(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function zn(e){return u(await l.get(`/projects/${e}/model-access`))}async function Jn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function jR(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Eg(e){return typeof e=="string"&&e.trim().length>0}function ch(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Eg(t)||Eg(n)||Eg(r)}function $R(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Qn(e){if(!e)return!0;let t=$R(e.items);return t?!t.some(ch):!ch(e)}var Ee="kortix.transcript.v1",lh=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Mg(e){return typeof e=="string"&&lh.includes(e)}var LR=["once","always","reject"],UR=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var dh="kortix-v1-import",FR={harness:dh,harness_version:Ee,adapter_version:"1"},Og={schema:ue,v:1},NR={opencode:"[Tool execution was interrupted]",pi:"No result provided"},KR="[Old tool result content cleared]",BR="The following tool was executed by the user",qR=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),GR=e=>qR.get(e)??(e.includes("_")?"mcp":"other"),WR=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),VR=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Z=e=>typeof e=="string"?e:void 0,We=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Us=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,gh=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Yt=e=>We(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,zt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Dg(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Dg(r,t[s]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>Dg(e[r],Us(t,r)))}function $s(e,t){if(Dg(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=$s(Us(e,r),Us(t,r));s&&gh(n,r,s)}return{sub:n}}function Ls(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Ls(Us(n,r),s);o===void 0?delete n[r]:gh(n,r,o)}return n}var Xn=e=>Object.values(e??{}).find(t=>t.version===Ee),Fs=(e,t)=>({[e]:{version:Ee,...t}}),mh=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},uh=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),HR=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID});function YR(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=zt(e.started_at)??t.created,i=zt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:uh(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,m)=>d.type==="attachment"?[{...n,id:`${e.id}-a${m}`,type:"file",mime:d.mime,...mh(d,t)}]:[]),p=zt(r?.cleared_at);return{status:"completed",...s,output:uh(r?.content),title:e.title??"",metadata:a,time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function fh(e,t){let n=HR(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...mh(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:YR(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function zR(e){return Mg(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function yh(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:VR.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:zt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:zR(e.error)},...n}}function hh(e,t){return e.role==="assistant"?yh(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function bh(e,t,n){let r=`${e.message_id}-summary`;return{info:yh({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function JR(e,t,n){let r=n||e.producer.harness===dh;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=Xn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:zt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let m=fh(d,i);return m===void 0?[]:[Ls(m,Xn(d.ext)?.data)]}),c=[{runtime_session_id:o,info:Ls(hh(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Ls(bh(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var jg=e=>We(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,js=e=>String(B(e.info)?e.info.id:""),_h=(e,t)=>jg(e)-jg(t)||(js(e)<js(t)?-1:js(e)>js(t)?1:0),ph=e=>{let t=Xn(e.ext);return t?t.native_id??null:e.thread_id};function Ns(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>JR(a,ph(i),Xn(i.ext)!==void 0))),s=Xn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?ph(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(_h)}}function QR(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=Z(t.p),r=Z(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Z(t.v)!==void 0&&{variant:t.v}}}function XR(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:We(t.input)??0,output:We(t.output)??0,cache_read:We(n.read)??0,cache_write:We(n.write)??0,...We(t.reasoning)!==void 0&&{reasoning:t.reasoning},...We(e.cost)!==void 0&&{cost:e.cost}}}var ZR=e=>({code:Z(e.code)||Z(e.name)||"UnknownError",message:Z(B(e.data)?e.data.message:void 0)??""});function Ph(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Z(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Z(e.url)!==void 0&&{url:e.url}}}function eT(e,t,n,r){let s=e.state,o=B(s.time)?s.time:{};B(s.input)||r.tool_input++;let i=B(s.metadata)&&We(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let g=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(h=>{let{bytes:P,...C}=Ph(h,n,r);return{type:"attachment",...C}}),y=Yt(o.compacted);a="complete",c={content:[...Z(s.output)!==void 0?[{type:"text",text:s.output}]:[],...g],is_error:!1,...i,...y&&{model_content:[{type:"text",text:KR}],cleared_at:y}}}else if(s.status==="error"){let g=Z(s.error);a="error",c={content:g!==void 0?[{type:"text",text:g}]:[],is_error:!0,...g!==void 0&&{error:{message:g}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&Z(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let g=NR[n.h];a="error",c={content:[{type:"text",text:g}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:g}}}let d=Yt(o.start),m=Yt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:GR(e.tool),input:p,status:a,...c&&{result:c},...Z(s.title)&&{title:s.title},...d&&{started_at:d},...m&&{ended_at:m}}}function tT(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:BR}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...Ph(e,s,o),...Z(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?eT(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:Z(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Z(e.type)||"unknown")}}function nT(e){let t=e.map((s,o)=>B(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function rT(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(k=>B(k)&&k.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",m=c?p:d==="assistant"?i:void 0,g=m&&B(m.error)?m.error:void 0,y=g?.name==="MessageAbortedError",h=m&&B(m.time)?Yt(m.time.completed):null,P=o.live?"streaming":"interrupted",C=m?g?y?"aborted":"error":h?"complete":P:c?P:"complete",M=Yt(B(i.time)?i.time.created:void 0)??"",L=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(k=>B(k)&&k.type==="text"&&typeof k.text=="string"?[k.text]:[]).join(""):null,f={tool_input:0,cut_point:0,attachment:0},b=nT(a),x=a.map((k,U)=>tT(k,b[U],c,L,o,f)),R=x.some(k=>k.type==="text"||k.type==="attachment"||k.type==="tool_call"||k.type==="harness"&&k.model_visible),T=!s&&d!=="system"&&(c?C==="complete":!g||y&&R),w=o.live&&T&&C!=="streaming"&&x.some(k=>k.type==="tool_call"&&(k.status==="pending"||k.status==="running"))?"streaming":C,S=s?"superseded":T||!g?void 0:y?"aborted":"failed_attempt";return c&&B(c)&&Z(c.tail_start_id)===void 0&&f.cut_point++,{m:{...Og,message_id:Z(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:w,in_context:T,...S&&{hidden_reason:S},agent:Z(i.agent)??null,...d==="assistant"&&{reply_to:Z(i.parentID)??null},model:QR(i),usage:m?XR(m):null,finish:!m||c?null:y?"aborted":g?"error":WR.get(i.finish)??null,error:g?ZR(g):null,created_at:M,completed_at:m||c?h:M||null,producer:FR,blocks:x},lost:f}}function sT(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:zt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let m=$s(t.parts[d],fh(p,i));m&&(p.ext=Fs(s,{data:m}))}):o.parts=t.parts;let a=$s(t.info,hh(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=$s({info:n.info,parts:n.parts},bh(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Fs(s,{data:o}))}function oT(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!B(o)||o.type!=="tool"||!B(o.state))&&(r?B(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Ks(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(_h),s=new Map;for(let f of r){let b=s.get(f.runtime_session_id);b?b.push(f):s.set(f.runtime_session_id,[f])}let o=e.root_id,i=s.has(o),a=new Map,c=f=>a.get(f)??(a.set(f,JSON.stringify(f)),a.get(f)),p=new Map;for(let f of s.keys()){let b=i&&f===o?void 0:oT(r,f,c);b&&p.set(f,b)}let d=[...r].reverse().find(f=>f.runtime_session_id===null||!p.has(f.runtime_session_id)),m=i||!d?o:d.runtime_session_id;s.has(m)||s.set(m,[]);let g=m||e.session_id,y=f=>f!==null&&p.has(f)?f:g,h=Yt(r.map(jg).find(Number.isFinite))??"",P=[];for(let[f,b]of s){if(f!==m&&(f===null||!p.has(f)))continue;let x=f===m,R=x?r.filter(D=>D.runtime_session_id!==m&&y(D.runtime_session_id)===g):[],T=[...R,...b],w=new Set(R),S=new Map,I=new Set;for(let D of T){let q=B(D.info)?D.info:{};if(q.role!=="user"||!Array.isArray(D.parts)||!D.parts.some(W=>B(W)&&W.type==="compaction"))continue;let Q=T.find(W=>!I.has(W)&&W.runtime_session_id===D.runtime_session_id&&B(W.info)&&W.info.role==="assistant"&&W.info.summary===!0&&W.info.parentID===q.id);Q&&(S.set(D,Q),I.add(Q))}let k=[];for(let D of T){if(I.has(D))continue;let q=S.get(D),{m:Q,lost:W}=rT(D,q,x?g:f,k.length+1,w.has(D),n);if(sT(Q,D,q,f,n.h),Q.in_context)for(let An of["tool_input","cut_point","attachment"])n.counts[An]+=W[An];k.push(Q)}let U=f===null?void 0:p.get(f),j=k.find(D=>D.role==="user"&&D.kind==="turn");P.push({...Og,thread_id:x?g:f,parent_thread_id:U?y(U.row.runtime_session_id):null,spawned_by:U&&typeof U.part.callID=="string"?{message_id:Z(U.row.info?.id)??"",call_id:U.part.callID}:null,agent:j?.agent??null,title:null,created_at:k[0]?.created_at||h,messages:k,ext:Fs(n.h,f===null?{}:{native_id:f})})}P.sort((f,b)=>f.parent_thread_id===null?-1:b.parent_thread_id===null?1:L(f)-L(b));let C=P[0]?.messages.filter(f=>f.role==="user"&&f.kind==="turn").at(-1),M=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Og,session_id:e.session_id,title:null,created_at:h,restore_grade:M?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:C?.agent??null,model:C?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:P,...m!==o&&{ext:Fs(n.h,{data:{root_id:o}})}};function L(f){return r.findIndex(b=>b.runtime_session_id===f.thread_id)}}var $g={schema:ue,v:1},iT=Object.freeze({}),xh=new WeakMap;function Zn(e){let t=xh.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Ks({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return xh.set(e,{state:e.state,block:o}),o}var Lg=new WeakMap;function Ug(e){if(Lg.has(e))return Lg.get(e);let t={...$g,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Ee}},messages:[{...$g,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Ns({...$g,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Lg.set(e,r),r}function ae(e){return Ug(e)}var fe=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ve=e=>fe(e)?ae(e):e;function Sh(e){let t=ae(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:iT}function ye(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function aT(e){return ye(e)==="bash"}function Fg(e){let t=ye(e);return t==="question"||t==="ask"}function cT(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var wh=new Set(["show","show_user"]);function Ng(e){return wh.has(ye(e))}function lT(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Kg(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Bs(e))}function Bs(e){let t=fe(e)?ae(e):e,n=ye(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:Qn(t.state?.input)}var kh=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Bg(e){return kh.has(ye(e))}var uT=50*1024*1024,qg="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",pT=new RegExp(`^kortix-attachment://(${qg})/(${qg})/(${qg})$`);function Wg(e){if(typeof e!="string")return null;let t=pT.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function dT(e){return Wg(e)!==null}var Gg=new WeakMap;async function Vg(e,t,n,r={}){if(n.size>uT)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Gg.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=Gg.get(n)??new Map;c.set(s,i),Gg.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Hg(e,t){let n=Wg(e);if(!n)throw new Error("Invalid attachment reference");let r=v().backendUrl.replace(/\/$/,""),s=await $(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new _("Could not load attachment",{status:s.status});return s.blob()}var gT=new Set(["show","show_user"]);function mT(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var He=e=>!!e&&typeof e=="object"&&!Array.isArray(e),er=e=>typeof e=="string"&&e.length>0?e:null,Ah=e=>typeof e=="string"?er(e.split("/").pop()):null;function qs(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function fT(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function yT(e){let t=e.blocks.filter(He).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&He(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function hT(e,t){for(let n of mT(e))t(qs(n,"attachment"),qs(n,"filename")??Ah(qs(n,"path")),qs(n,"mime"))}function bT(e,t){for(let n of[e,...fT(e.items)])He(n)&&t(n.attachment,Ah(n.path),null)}function _T(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=He(r)&&Array.isArray(r.blocks)?yT(r):r;if(!He(s)||!He(s.info)||!Array.isArray(s.parts))continue;let o=er(s.info.id);if(!o)continue;let i=er(s.info.role)??"unknown",a=(c,p,d)=>{let m=Wg(c);!m||n.has(c)||(n.add(c),t.push({url:c,attachment_id:m.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)He(c)&&(c.type==="file"?a(c.url,er(c.filename),er(c.mime)):c.type==="text"&&typeof c.text=="string"?hT(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&gT.has(ye(c.tool))&&He(c.state)&&He(c.state.input)&&bT(c.state.input,a))}return t}function st(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function PT(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function xT(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function Yg(e,t,n){return e!==void 0?e:PT(st(t),n)}var zg={get disableMobileAdvertising(){return Yg(v().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Yg(v().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Yg(v().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var ST=new Set(["project-manager"]);function Gs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:zg.enableProjects||!ST.has(e.name)}function wT(e){let t=e.agents.filter(Gs),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function vh(){return{projects:{list:St,listForAccount:Gi,get:Cn,detail:In,create:Yi,createRepo:zi,provision:Ji,update:On,archive:Dn,llmCatalog:En,modelPicker:Mn,modelAccess:zn,setModelAccess:Jn,sandboxHealth:$n,sandboxTemplates:Nc,sessions:At,createSession:vt},github:{linkRepository:na,replaceProjectRepository:ra,getInstallation:sa,listInstallations:oa,listLinkableInstallations:ia,listRepositories:aa,listRepositoryBranches:ca,linkInstallation:ua,saveInstallation:la,deleteInstallation:da,storeUserToken:pa},gitBackend:{get:ga,repositories:ma},connectStatus:Oc,marketplace:{items:o=>Md(o),item:o=>jd(o),itemFile:(o,i)=>$d(o,i),marketplaces:()=>Od(),featured:()=>Dd(),sources:{list:()=>Ld(),add:o=>Ud(o),remove:o=>Fd(o)}}}}function Rh(){return{billing:{accountState:xu,accountStateMinimal:Su,transactions:wu,transactionsSummary:ku,creditBreakdown:Au,usageHistory:vu,usageRollup:Fu,sessionCosts:{list:Bu,get:Yn},tierConfigurations:Ru,checkout:{createSession:n=>Tu(n),confirmSession:(n,r)=>Cu(n,r)},subscription:{createPortalSession:(n,r)=>Iu(n,r),cancel:(n,r)=>Eu(n,r),reactivate:n=>Mu(n),scheduleDowngrade:(n,r,s)=>Ou(n,r,s),cancelScheduledChange:n=>Du(n),prorationPreview:(n,r)=>ju(n,r)},credits:{purchase:n=>$u(n),autoTopupSettings:n=>Lu(n),configureAutoTopup:n=>Uu(n)}},sandboxShares:{list:id,create:ad,revoke:cd}}}var Ye={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function ot(){let e=st("BACKEND_URL")||v().backendUrl;return e||"http://localhost:8008/v1"}function Rt(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function tr(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=tr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return tr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function kT(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Jg(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${ot()}/p/${n.external_id}/${Ye.KORTIX_MASTER}`:""),status:kT(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function Qg(){let e=await St(),t=[];for(let n of e){let r=await At(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Jg(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Tt(e){let t=await Qg();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Jt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ce(e,t,n){let r=n?.fetch??v().fetch??((p,d)=>fetch(p,d)),s=de(n?.backendUrl??v().backendUrl??"");if(!s)throw new Jt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${Rt(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Jt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function Ws(e,t){return ce("/auth/signup",{body:e},t)}function Vs(e,t){return ce("/auth/sign-in/password",{body:e},t)}function Hs(e,t){return ce("/auth/sign-in/magic-link",{body:e},t)}function Ys(e,t){return ce("/auth/verify-otp",{body:e},t)}function zs(e,t){return ce("/auth/sign-in/oauth",{body:e},t)}function Js(e,t){return ce("/auth/oauth/exchange",{body:e},t)}function Qt(e,t){return ce("/auth/refresh",{body:e},t)}function Qs(e,t){return ce("/auth/password/reset",{body:e},t)}function Xs(e,t,n){return ce("/auth/password/update",{body:e,bearer:t},n)}function Zs(e,t){return ce("/auth/user",{bearer:e},t)}function eo(e,t,n){return ce("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function to(e,t){return ce("/auth/sign-in/sso",{body:e},t)}var no={enroll:(e,t,n)=>ce("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function ro(e,t={},n){return ce("/auth/sign-out",{body:t,bearer:e},n)}function so(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=0,p=new Set,d=P=>(P.expires_at??0)*1e3,m=P=>d(P)-t*1e3<=n();async function g(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let P of[...p])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function y(){if(o)return r;if(!i){let P=c,C=(async()=>{let M=await e.storage.get();if(P===c&&M)try{let L=JSON.parse(M);L.session?.access_token&&L.session?.refresh_token&&(r=L.session,s=L.user??null)}catch{r=null}return o=!0,r})();i=C,C.then(()=>{i===C&&(i=null)},()=>{i===C&&(i=null)})}return i}async function h(){if(await y(),!r)return null;if(!a){let P=r.refresh_token,C=c,M=Qt({refresh_token:P},e.request).then(async L=>(C!==c||(r=L.session,L.user&&(s=L.user),await g()),r)).catch(async L=>{if(C!==c)return r;let f=L&&typeof L=="object"&&"status"in L?L.status:0;if(f>=400&&f<500)return r=null,s=null,await g(),null;throw L}).finally(()=>{a===M&&(a=null)});a=M}return a}return{subscribe(P){return p.add(P),()=>{p.delete(P)}},current:()=>r,user:()=>s,load:y,async set(P,C){await y(),c+=1,a=null,r=P,C!==void 0&&(s=C),P||(s=null),await g()},async getToken(){return await y(),r?m(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,s=null,o=!0,await g()}}}function Th(){return{list:Si,get:ki,create:wi,secretResources:{list:Va,create:Ha,rotate:Ya,retry:za,remove:Ja,grant:Qa,revoke:Xa,setAccess:Za},updateName:Ai,branding:{get:vi,update:Ri,uploadAsset:Ti,removeAsset:Ci,reset:Ii},leave:Bi,members:Ei,invite:Mi,removeMember:Ni,updateMemberRole:Ki,invites:Oi,cancelInvite:Di,resendInvite:ji,tokens:{list:md,create:fd,revoke:yd},connectedApps:{list:hd,revoke:bd},audit:{log:wd,export:Ad,webhooks:{list:vd,create:Rd,update:Td,remove:Cd}}}}function Ch(){return{assignments:{list:Qp,create:Xp,revoke:Zp},permissions:{list:ed,forRole:Lp},roles:{list:Dp,create:Fp,update:Np,setPermissions:Kp,remove:Bp,usage:Up},groups:{list:vp,get:Rp,create:Tp,update:Cp,remove:Ip,members:{list:Ep,add:Mp,remove:Op}},agentIdentities:jp,oauthClients:{list:Wp,get:Vp,create:Hp,update:Yp,rotateSecret:zp,remove:Jp},can:qp,canBatch:Gp}}function Ih(){let e={signUp:Ws,signInWithPassword:Vs,sendMagicLink:Hs,verifyOtp:Ys,signInWithProvider:zs,exchangeCode:Js,refresh:Qt,resetPassword:Qs,updatePassword:Xs,updateUserMetadata:eo,signInWithSso:to,mfa:no,user:Zs,signOut:ro,session:so},t=Th(),n=Ch();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:$i,describe:Li,accept:rs,acceptAndLand:Ui,decline:Fi}}}var nr=new Map,Xg=new Map;function Zg(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Eh(e){return nr.get(Zg(e))??null}function Mh(){return[...nr.values()].filter(e=>typeof e=="string")}function Oh(e){return nr.has(Zg(e))}async function it(e){let t=Zg(e),n=nr.get(t);if(n!==void 0)return n;let r=Xg.get(t);if(r)return r;let s=(async()=>{try{let o=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return nr.set(t,i),i}catch{return null}finally{Xg.delete(t)}})();return Xg.set(t,s),s}function Dh(e){let{apiBaseUrl:t}=e;return Oh(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Eh(t)}}function jh(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new _(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=v().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),Dh({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function $h(e,t){let n=null;async function r(){n||(n=qn(e,t,{showErrors:!1}).then(s=>{let o=eu(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Xt={url:null,sandboxId:null,dbSandboxId:null,version:0},vT=new Set;function oo(e,t=null,n=null){if(!(Xt.url===e&&Xt.sandboxId===t&&Xt.dbSandboxId===n)){Xt={url:e,sandboxId:t,dbSandboxId:n,version:Xt.version+1};for(let r of vT)r()}}function Lh(){return Xt.url}var rr=new Map;function Uh(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ct=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function Fh(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await nt(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await nt(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new _(Uh(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new _("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ce(c);return oo(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function Nh(e,t,n){let r=null;function s(){if(r)return r;let p=Ny(e,t);return p&&(r=p),r}let o=Fh(e,t);async function i(p){let d=s();if(d)return d;let m=p?.readyTimeoutMs??18e4,g=it(v().backendUrl??n.backendUrl).catch(()=>null),y=p?.session?.session_id===t?du(p.session):null,h=y?.sandbox?.external_id,P=y?.runtime_session_id;if(h&&P){let f=Ce(h);return oo(f,h),r={runtimeSessionId:P,opencodeSessionId:P,runtimeUrl:f,sandboxId:h},ws(e,t,r),await g,r}let C=`${e}
|
|
15
|
-
${t}`,
|
|
13
|
+
`);let h=TA(f);if(h){if(r(h),h.type==="error")throw new S(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function yu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function hu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function _u(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function er(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function bu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function xu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function IA(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function Su(e){return u(await l.get(`/projects/${e}/triggers`))}async function Pu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function wu(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function ku(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function vu(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Au(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function Ru(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function Cu(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var st=new Map;function Tu(e,t){return`${e}::${t}`}function Uh(e,t){st.delete(e),st.set(e,t)}function Fh(e,t){let n=Tu(e,t),r=st.get(n);return r&&Uh(n,r),r}function Os(e,t,n){let r=Tu(e,t);if(!st.has(r)&&st.size>=512){let s=st.keys().next().value;s!==void 0&&st.delete(s)}Uh(r,n)}function Nh(e,t){st.delete(Tu(e,t))}function EA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tr(){return EA(C().backendUrl||"http://localhost:8008/v1")}function Bh(){let e=C().sandboxId;return e?`${tr()}/p/${e}/8000`:""}function MA(e,t=8e3){return`${tr()}/p/${e}/${t}`}function Ee(e,t=8e3){return MA(e,t)}function Iu(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Ds=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function OA(e){return e instanceof Error&&e.name==="SessionStartError"}function DA(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Ds(s,{status:n,code:r,terminal:!0}):null}function Kh(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function ot(e,t,n){let r=await Kh(e,t,n);if(!r.success||!r.data){let s=DA(r.error);if(s&&!(s.status===404&&$l(t)))throw s;return null}return qh(e,t,r.data)}async function Eu(e,t,n){let r=await Kh(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return qh(e,t,r.data)}function qh(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Os(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ee(r),sandboxId:r}),n}function jA(e,t){return["session-start",e,t]}async function Mu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Ou(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Du(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function LA(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Gh(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function $A(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function js(e){let t=e.connectors_required?Gh(e.connectors_required):void 0,n=e.connectors_personal?Gh(e.connectors_personal):void 0;if(t&&n&&!$A(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function ju(e,t,n){let r=js(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function UA(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Lu(n.block):null}}async function FA(e,t,n){let r=Lu(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Lu(s.block):null}}function Lu(e,t=!1){let n=js(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function NA(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function $u(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Ls="Use setBillingPlan().",Wh="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Uu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",monthly_usd:null,status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function BA(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function KA(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Uu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:BA(r),label:s,sublabel:null,monthlyUsd:null}}function Vh(e){return!!e&&e.can_manage_billing!==!1}function qA(e){return e?.subscription?.can_purchase_credits===!0&&Vh(e)}async function Hh(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Uu():t.data}function zh(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function Fu(e){return Hh(`/billing/account-state${zh(e)}`)}async function Nu(e){return Hh(`/billing/account-state/minimal${zh(e)}`)}async function Bu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function Ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function qu(){return u(await l.get("/billing/credit-breakdown"))}async function Gu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Wu(){return u(await l.get("/billing/tier-configurations"))}async function GA(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return qt(e,`/v1/billing/account-state${t}`)}async function Vu(e){throw F("createCheckoutSession",Ls)}async function Hu(e,t){throw F("confirmCheckoutSession",Ls)}async function zu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Yu(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Ju(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Qu(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Xu(e){throw F("cancelScheduledChange",Wh)}async function Zu(e,t){throw F("getProrationPreview",Wh)}async function ep(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function tp(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function WA(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function np(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function VA(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function rp(e){return u(await l.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function sp(e){return u(await l.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function op(e){return u(await l.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function ip(e={}){return u(await l.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function HA(e){throw F("createPerSeatCheckout",Ls)}async function zA(e){throw F("claimPerSeatBilling",Ls)}async function YA(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function ap(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function lp(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function $s(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Us(e){return e.size>0?`?${e}`:""}async function up(e={}){let t=new URLSearchParams;return lp(t,e),e.ownerId&&t.set("owner_id",e.ownerId),$s(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Us(t)}`))}async function nr(e,t={}){let n=new URLSearchParams;return lp(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Us(n)}`))}async function JA(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),$s(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Us(t)}`))}async function QA(e={}){let t=new URLSearchParams;return lp(t,e),e.sessionId&&t.set("session_id",e.sessionId),$s(t,e),u(await l.get(`/usage/cost-summary${Us(t)}`))}function cp(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}$s(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${C().backendUrl||""}${r}?${n}`}async function XA(e,t={}){let n=cp(e==="projects"?"projects":"sessions",t),r=await Ne(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Yh(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function ZA(e){return Yh("slack",e)}function eR(e){return Yh("teams",e)}async function Jh(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function tR(e){return Jh("slack",e)}function nR(e){return Jh("teams",e)}async function pp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function dp(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var rR={oauth_available:!1,install_url:null};async function gp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?rR:t.data}async function Qh(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function mp(e,t){return Qh("slack",e,t)}function fp(e,t){return Qh("teams",e,t)}async function yp(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function hp(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function _p(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function bp(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function xp(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var sR={provider:"agentmail",managed_available:!1};async function Sp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?xp(r.data):null}async function Pp(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?sR:t.data}async function wp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return xp(n)}async function kp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function vp(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return xp(r)}async function oR(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function iR(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function Ap(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Rp(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Cp(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Tp(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Ip(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Ep(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Mp(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Op(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Dp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function jp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Lp(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function $p(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Up(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Fp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Np(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Bp(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Kp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function qp(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function aR(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function cR(){throw F("getReferralCode")}async function lR(){throw F("refreshReferralCode")}async function uR(e){throw F("validateReferralCode")}async function pR(){throw F("getReferralStats")}async function dR(e={}){throw F("listReferrals")}async function gR(e){throw F("sendReferralEmails")}var Gp="call:";function Vp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Gp)&&e.length>Gp.length?{type:"connector_call",executionId:e.slice(Gp.length)}:{type:"review_item",reviewItemId:e}}function Zh(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function mR(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Zh(n.status)]+=1;return t}function fR(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function Wp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Hp(e){let t=e.indexOf(".");return t<=0?Wp(e):`(${Wp(e.slice(0,t))}) ${Wp(e.slice(t+1))}`}function yR(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Fs=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},N=e=>typeof e=="string"&&e?e:void 0,Me=e=>Array.isArray(e)?e:void 0,Xh=e=>typeof e=="number"?e:0,hR=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function _R(e,t){let n=Fs(e.advanced),r=N(e.description),s=Me(e.whatChanged)??(r?hR(r):t.summary?[t.summary]:[]);return{crId:N(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:N(e.impact)??"",verification:Me(e.verification)??[],previewUrl:N(e.previewUrl)??N(e.preview_url),conflicts:Me(e.conflicts),requestedChanges:Me(e.requested_changes)??[],advanced:{headRef:N(n.headRef)??N(e.head_ref)??"",baseRef:N(n.baseRef)??N(e.base_ref)??"",headSha:N(n.headSha)??N(e.head_sha)??N(e.head_commit_sha)??"",baseSha:N(n.baseSha)??N(e.base_sha)??"",additions:Xh(n.additions),deletions:Xh(n.deletions),files:Me(n.files)??[],mergeMode:N(n.mergeMode)??"merge"}}}function bR(e,t){let n=Me(e.actions);if(n)return{actions:n.map((c,p)=>({id:N(c.id)??`${t.review_item_id}-${p}`,title:N(c.title)??"Action",connector:N(c.connector)??"",action:N(c.action)??"",consequence:N(c.consequence)??"",risk:N(c.risk)??t.risk,icon:N(c.icon)??"generic",argsPreview:Me(c.argsPreview)??[],policySource:N(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=N(e.action_path)??"",{connector:s,action:o}=yR(r),i=Fs(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:N(e.execution_id)??t.review_item_id,title:r?Hp(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:N(e.approval_context),connectorRisk:N(e.risk)??null,policySource:"Requires approval"}]}}function xR(e,t){return{artifactKind:N(e.artifactKind)??"document",artifactLabel:N(e.artifactLabel)??"Output",previewUrl:N(e.previewUrl)??N(e.preview_url),preview:N(e.preview),files:Me(e.files),note:N(e.note)??t.summary??""}}function SR(e,t){return{question:N(e.question)??t.title??"",context:N(e.context),options:Me(e.options)??[]}}function PR(e,t){return{note:N(e.note)??t.summary??"",children:Me(e.children)??[]}}function wR(e){let t=Fs(e.detail);switch(e.kind){case"change":return _R(t,e);case"approval":return bR(t,e);case"output":return xR(t,e);case"decision":return SR(t,e);case"batch":return PR(t,e)}}function kR(e,t){let n=typeof e.number=="number"?e.number:void 0,r=N(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function vR(e,t={}){let n=Fs(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?N(n.action_path):void 0,i=e.kind==="change"?kR(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Hp(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:wR(e)}}var Q={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},AR=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function RR(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canCreate:n&&t(Q.PROJECT_TRIGGER_CREATE),canFire:t(Q.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Q.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Q.PROJECT_TRIGGER_DELETE)}}var CR=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function e_(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canOpen:n&&t(Q.PROJECT_GITOPS_PUSH),canMerge:n&&t(Q.PROJECT_GITOPS_MERGE),canClose:n}}function TR(e,t,n){let r=Vp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return e_(n).canMerge}return n[Q.PROJECT_WRITE]?.allowed===!0&&n[Q.PROJECT_REVIEW_ACT]?.allowed===!0}function U(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function zp(e){return A(await U(`/accounts/${e}/iam/groups`)).groups}async function Yp(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}`))}async function Jp(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Qp(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Xp(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Zp(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/members`)).members}async function ed(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function IR(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function td(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function ER(e,t){return A(await U(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function MR(e,t){let n=A(await U(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function it(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function OR(e,t={}){let n=it({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await U(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function DR(e,t={}){let n=it({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await U(`/accounts/${e}/iam/policies${n}`)).policies}async function jR(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function LR(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function $R(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function UR(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function FR(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function nd(e){return A(await U(`/accounts/${e}/iam/roles`)).roles}async function rd(e){return A(await U(`/accounts/${e}/iam/agent-identities`)).agents}async function sd(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function od(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/permissions`))}async function NR(e){return A(await U(`/accounts/${e}/iam/actions`)).actions}async function id(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/usage`))}async function ad(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function cd(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function ld(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function ud(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function BR(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function KR(e){return A(await U(`/accounts/${e}/iam/scim/tokens`)).tokens}async function qR(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function GR(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function WR(e){return A(await U(`/accounts/${e}/iam/mfa-required`))}async function VR(e){return A(await U(`/accounts/${e}/iam/mfa-required/preview`))}async function HR(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function zR(e){return A(await U(`/accounts/${e}/iam/session-oversight`))}async function YR(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function JR(e){return A(await U(`/accounts/${e}/iam/sso/provider`)).provider}async function QR(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function XR(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function ZR(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function eC(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function tC(e){return A(await U(`/accounts/${e}/iam/sso/mappings`)).mappings}async function nC(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function rC(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function sC(e){return A(await U(`/accounts/${e}/iam/session-policy`))}async function oC(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function iC(e){return A(await U(`/accounts/${e}/iam/sessions`)).sessions}async function aC(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function cC(e){return A(await U(`/accounts/${e}/iam/pat-policy`))}async function lC(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function uC(e){return A(await U(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function pC(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function dC(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function gC(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function mC(e){return A(await U(`/accounts/${e}/audit/webhooks`)).webhooks}async function fC(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function yC(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function hC(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function _C(e,t={}){let n=it({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await U(`/accounts/${e}/audit${n}`))}async function pd(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await U(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function dd(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function bC(e){return A(await U(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function xC(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function gd(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function md(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function fd(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function yd(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function hd(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function _d(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function SC(e){return it({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function bd(e,t){return u(await U(`/accounts/${e}/iam/assignments${SC(t)}`)).assignments}async function xd(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function Sd(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Pd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await U(`/accounts/${e}/iam/permissions${n}`)).permissions}async function PC(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function wC(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function kC(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function vC(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function AC(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function RC(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function CC(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function TC(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function IC(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function EC(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function MC(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function OC(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var t_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function DC(e){throw F("getGoogleAuthUrl",t_)}async function jC(e,t){throw F("convertPresentationToGoogleSlides",t_)}async function wd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function kd(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function vd(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Ad(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function Rd(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function Cd(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function Td(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Id(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Ed(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Ns=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function n_(e,t=""){return`${tr()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function r_(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Ns(s,t.status)}return r}async function LC(e){return r_(n_(e))}async function $C(e){return r_(n_(e,"/messages"))}async function Md(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Od(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Bs(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Ks(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var UC=4;async function s_(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(UC,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function Dd(e,t,n){return s_(t,r=>Bs(e,r.sessionId,r.reminderId,n))}function jd(e,t){return s_(t,n=>Ks(e,n.sessionId,n.reminderId))}async function Ld(e){return u(await l.get(`/projects/${e}/reminders`))}async function $d(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function Ud(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Fd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Nd(){return u(await l.get("/oauth/grants")).grants}async function Bd(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function FC(){return u(await l.get("/accounts/me/devices")).devices}async function NC(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Kd(e){return u(await l.get(`/projects/${e}/cli-token`))}async function qd(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Gd(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Jt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function Wd(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function Vd(e,t){let n=Jt(Wd(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Hd(e,t){let n=Jt(Wd({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function zd(e,t){let n=Jt(Wd(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Yd(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Jd(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Qd(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Xd(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Zd(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function eg(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function BC(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function tg(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function ng(){return u(await l.get("/marketplace/marketplaces"))}async function rg(){return u(await l.get("/marketplace/marketplaces/featured"))}async function sg(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function og(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function ig(){return u(await l.get("/marketplace/sources"))}async function ag(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function cg(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function KC(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function qC(e){throw F("getTemplate")}async function GC(e,t){throw F("installTemplate")}async function lg(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function ug(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function qs(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function pg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function dg(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function gg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function mg(e,t){let n=await qs(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function fg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function yg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function hg(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function _g(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Gs(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Ws(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function WC(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function VC(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function bg(e,t,n={}){let r=await WC(t),s=n.mediaType??"application/gzip",o=await Gs(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Ws(e,o.artifact.artifact_id,{sha256:await VC(r),size_bytes:r.byteLength})}async function xg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Sg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Pg(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function wg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function kg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function vg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Ag(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Rg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var Pe=(e,t)=>`/projects/${e}/apps/${t}`;async function Cg(e,t){return u(await l.get(`${Pe(e,t)}/machines`),"Failed to list machines").machines}async function Tg(e,t,n,r){return u(await l.post(`${Pe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Ig=(e,t,n)=>Tg(e,t,n,"start"),Eg=(e,t,n)=>Tg(e,t,n,"stop"),Mg=(e,t,n)=>Tg(e,t,n,"restart");async function Og(e,t,n){return u(await l.delete(`${Pe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Dg(e,t,n,r={}){return u(await l.put(`${Pe(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function jg(e,t,n){return u(await l.post(`${Pe(e,t)}/exec`,n),"Failed to run the command")}async function Lg(e,t){return u(await l.get(`${Pe(e,t)}/volumes`),"Failed to list volumes").volumes}async function $g(e,t,n){return u(await l.post(`${Pe(e,t)}/volumes`,n),"Failed to create the volume")}async function Ug(e,t,n,r){return u(await l.patch(`${Pe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Fg(e,t,n,r){u(await l.delete(`${Pe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Ng(e,t,n){return u(await l.get(`${Pe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Bg(e,t,n){return u(await l.post(`${Pe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Kg(e,t,n,r){return u(await l.post(`${Pe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function qg(e,t,n,r){return u(await l.post(`${Pe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var fe=e=>`/drives/${encodeURIComponent(e)}`;async function HC(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new S("Files not found",{status:404});return t[0]}async function zC(e,t){return u(await l.get(`${fe(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function YC(e,t){return u(await l.put(`${fe(e)}/access`,t),"Failed to share folder")}async function JC(e,t){let n=u(await l.delete(`${fe(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function QC(e){return u(await l.get(`${fe(e)}/principals`),"Failed to load people")}async function XC(e){return u(await l.get(`${fe(e)}/conflicts`),"Failed to load conflicts").conflicts}async function ZC(e,t){u(await l.post(`${fe(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function eT(e,t="/"){return(await o_(e,t)).entries}async function o_(e,t="/"){return u(await l.get(`${fe(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Gg(e,t,n){let r=de(C().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${fe(e)}/files/content?${new URLSearchParams(s)}`}async function tT(e,t,n){let r=await L(Gg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function nT(e,t,n){let r=await L(Gg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function rT(e,t,n,r){return u(await l.putRaw(`${fe(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function sT(e,t){return u(await l.post(`${fe(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function oT(e,t,n){return u(await l.post(`${fe(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function iT(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${fe(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function aT(e){return u(await l.get(`${fe(e)}/versions`),"Failed to load versions").versions}async function cT(e,t){u(await l.post(`${fe(e)}/restore`,{versionId:t}),"Failed to restore version")}var lT=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function uT(e,t){return(await i_(e,t)).drives}async function i_(e,t){return u(await l.get(lT(e,t)),"Failed to load session files")}async function Wg(e){return u(await l.post("/notifications/device-token",e))}async function Vg(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var pT=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function Hg(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function zg(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var dT={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1}};async function Yg(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Jg(e){return u(await l.put("/notifications/preferences",e))}async function Qg(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Xg(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Zg(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function rr(e){return u(await l.get(`/projects/${e}/model-access`))}async function sr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function gT(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function em(e){return typeof e=="string"&&e.trim().length>0}function a_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return em(t)||em(n)||em(r)}function mT(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function or(e){if(!e)return!0;let t=mT(e.items);return t?!t.some(a_):!a_(e)}var Ae="kortix.transcript.v1",c_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function tm(e){return typeof e=="string"&&c_.includes(e)}var fT=["once","always","reject"],yT=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var p_="kortix-v1-import",hT={harness:p_,harness_version:Ae,adapter_version:"1"},nm={schema:pe,v:1},_T={opencode:"[Tool execution was interrupted]",pi:"No result provided"},bT="[Old tool result content cleared]",xT="The following tool was executed by the user",ST=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),PT=e=>ST.get(e)??(e.includes("_")?"mcp":"other"),wT=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),kT=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ve=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ys=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,d_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Qt=e=>Ve(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Xt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function rm(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>rm(r,t[s]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>rm(e[r],Ys(t,r)))}function Hs(e,t){if(rm(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=Hs(Ys(e,r),Ys(t,r));s&&d_(n,r,s)}return{sub:n}}function zs(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=zs(Ys(n,r),s);o===void 0?delete n[r]:d_(n,r,o)}return n}var ir=e=>Object.values(e??{}).find(t=>t.version===Ae),Js=(e,t)=>({[e]:{version:Ae,...t}}),g_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},l_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),vT=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),AT=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Ae&&B(n.data?.details));return t?t.data.details:{}};function RT(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Xt(e.started_at)??t.created,i=Xt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:l_(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...g_(d,t)}]:[]),p=Xt(r?.cleared_at);return{status:"completed",...s,output:l_(r?.content),title:e.title??"",metadata:{...AT(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function m_(e,t){let n=vT(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...g_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:RT(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function CT(e){return tm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function f_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:kT.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Xt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:CT(e.error)},...n}}function y_(e,t){return e.role==="assistant"?f_(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function h_(e,t,n){let r=`${e.message_id}-summary`;return{info:f_({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function TT(e,t,n){let r=n||e.producer.harness===p_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=ir(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Xt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=m_(d,i);return g===void 0?[]:[zs(g,ir(d.ext)?.data)]}),c=[{runtime_session_id:o,info:zs(y_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=zs(h_(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var sm=e=>Ve(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,Vs=e=>String(B(e.info)?e.info.id:""),__=(e,t)=>sm(e)-sm(t)||(Vs(e)<Vs(t)?-1:Vs(e)>Vs(t)?1:0),u_=e=>{let t=ir(e.ext);return t?t.native_id??null:e.thread_id};function Qs(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>TT(a,u_(i),ir(i.ext)!==void 0))),s=ir(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?u_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(__)}}function IT(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=X(t.p),r=X(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...X(t.v)!==void 0&&{variant:t.v}}}function ET(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Ve(t.input)??0,output:Ve(t.output)??0,cache_read:Ve(n.read)??0,cache_write:Ve(n.write)??0,...Ve(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ve(e.cost)!==void 0&&{cost:e.cost}}}var MT=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(B(e.data)?e.data.message:void 0)??""});function b_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:X(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...X(e.url)!==void 0&&{url:e.url}}}function OT(e,t,n,r){let s=e.state,o=B(s.time)?s.time:{};B(s.input)||r.tool_input++;let i=B(s.metadata)&&Ve(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(h=>{let{bytes:_,...I}=b_(h,n,r);return{type:"attachment",...I}}),f=Qt(o.compacted);a="complete",c={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:bT}],cleared_at:f}}}else if(s.status==="error"){let m=X(s.error);a="error",c={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&X(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=_T[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Qt(o.start),g=Qt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:PT(e.tool),input:p,status:a,...c&&{result:c},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function DT(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:xT}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...b_(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?OT(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:X(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(X(e.type)||"unknown")}}function jT(e){let t=e.map((s,o)=>B(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function LT(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(v=>B(v)&&v.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=c?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&B(g.time)?Qt(g.time.completed):null,_=o.live?"streaming":"interrupted",I=g?m?f?"aborted":"error":h?"complete":_:c?_:"complete",j=Qt(B(i.time)?i.time.created:void 0)??"",D=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(v=>B(v)&&v.type==="text"&&typeof v.text=="string"?[v.text]:[]).join(""):null,w={tool_input:0,cut_point:0,attachment:0},y=jT(a),b=a.map((v,$)=>DT(v,y[$],c,D,o,w)),R=b.some(v=>v.type==="text"||v.type==="attachment"||v.type==="tool_call"||v.type==="harness"&&v.model_visible),k=!s&&d!=="system"&&(c?I==="complete":!m||f&&R),x=o.live&&k&&I!=="streaming"&&b.some(v=>v.type==="tool_call"&&(v.status==="pending"||v.status==="running"))?"streaming":I,P=s?"superseded":k||!m?void 0:f?"aborted":"failed_attempt";return c&&B(c)&&X(c.tail_start_id)===void 0&&w.cut_point++,{m:{...nm,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:x,in_context:k,...P&&{hidden_reason:P},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:IT(i),usage:g?ET(g):null,finish:!g||c?null:f?"aborted":m?"error":wT.get(i.finish)??null,error:m?MT(m):null,created_at:j,completed_at:g||c?h:j||null,producer:hT,blocks:b},lost:w}}function $T(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Xt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Hs(t.parts[d],m_(p,i));g&&(p.ext=Js(s,{data:g}))}):o.parts=t.parts;let a=Hs(t.info,y_(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=Hs({info:n.info,parts:n.parts},h_(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Js(s,{data:o}))}function UT(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!B(o)||o.type!=="tool"||!B(o.state))&&(r?B(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Xs(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(__),s=new Map;for(let w of r){let y=s.get(w.runtime_session_id);y?y.push(w):s.set(w.runtime_session_id,[w])}let o=e.root_id,i=s.has(o),a=new Map,c=w=>a.get(w)??(a.set(w,JSON.stringify(w)),a.get(w)),p=new Map;for(let w of s.keys()){let y=i&&w===o?void 0:UT(r,w,c);y&&p.set(w,y)}let d=[...r].reverse().find(w=>w.runtime_session_id===null||!p.has(w.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=w=>w!==null&&p.has(w)?w:m,h=Qt(r.map(sm).find(Number.isFinite))??"",_=[];for(let[w,y]of s){if(w!==g&&(w===null||!p.has(w)))continue;let b=w===g,R=b?r.filter(T=>T.runtime_session_id!==g&&f(T.runtime_session_id)===m):[],k=[...R,...y],x=new Set(R),P=new Map,O=new Set;for(let T of k){let q=B(T.info)?T.info:{};if(q.role!=="user"||!Array.isArray(T.parts)||!T.parts.some(V=>B(V)&&V.type==="compaction"))continue;let G=k.find(V=>!O.has(V)&&V.runtime_session_id===T.runtime_session_id&&B(V.info)&&V.info.role==="assistant"&&V.info.summary===!0&&V.info.parentID===q.id);G&&(P.set(T,G),O.add(G))}let v=[];for(let T of k){if(O.has(T))continue;let q=P.get(T),{m:G,lost:V}=LT(T,q,b?m:w,v.length+1,x.has(T),n);if($T(G,T,q,w,n.h),G.in_context)for(let En of["tool_input","cut_point","attachment"])n.counts[En]+=V[En];v.push(G)}let $=w===null?void 0:p.get(w),K=v.find(T=>T.role==="user"&&T.kind==="turn");_.push({...nm,thread_id:b?m:w,parent_thread_id:$?f($.row.runtime_session_id):null,spawned_by:$&&typeof $.part.callID=="string"?{message_id:X($.row.info?.id)??"",call_id:$.part.callID}:null,agent:K?.agent??null,title:null,created_at:v[0]?.created_at||h,messages:v,ext:Js(n.h,w===null?{}:{native_id:w})})}_.sort((w,y)=>w.parent_thread_id===null?-1:y.parent_thread_id===null?1:D(w)-D(y));let I=_[0]?.messages.filter(w=>w.role==="user"&&w.kind==="turn").at(-1),j=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...nm,session_id:e.session_id,title:null,created_at:h,restore_grade:j?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:I?.agent??null,model:I?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:_,...g!==o&&{ext:Js(n.h,{data:{root_id:o}})}};function D(w){return r.findIndex(y=>y.runtime_session_id===w.thread_id)}}var om={schema:pe,v:1},FT=Object.freeze({}),x_=new WeakMap;function ar(e){let t=x_.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Xs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return x_.set(e,{state:e.state,block:o}),o}var im=new WeakMap;function am(e){if(im.has(e))return im.get(e);let t={...om,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Ae}},messages:[{...om,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Qs({...om,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return im.set(e,r),r}function ce(e){return am(e)}var ye=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",He=e=>ye(e)?ce(e):e;function P_(e){let t=ce(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:FT}var w_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function k_(e){return e.status==="complete"?"completed":e.status}var S_=new WeakMap;function v_(e){if(e.status!=="complete")return"";let t=S_.get(e);return t===void 0&&S_.set(e,t=w_(e)),t}function A_(e){return e.status==="error"?e.result?.error?.message||w_(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function NT(e){return he(e)==="bash"}function cm(e){let t=he(e);return t==="question"||t==="ask"}function BT(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var R_=new Set(["show","show_user"]);function lm(e){return R_.has(he(e))}function KT(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function um(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Zs(e))}function Zs(e){let t=ye(e)?ce(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:or(t.state?.input)}var C_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function pm(e){return C_.has(he(e))}var qT=50*1024*1024,dm="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",GT=new RegExp(`^kortix-attachment://(${dm})/(${dm})/(${dm})$`);function mm(e){if(typeof e!="string")return null;let t=GT.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function WT(e){return mm(e)!==null}var gm=new WeakMap;async function fm(e,t,n,r={}){if(n.size>qT)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:gm.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=gm.get(n)??new Map;c.set(s,i),gm.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function ym(e,t){let n=mm(e);if(!n)throw new Error("Invalid attachment reference");let r=C().backendUrl.replace(/\/$/,""),s=await L(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new S("Could not load attachment",{status:s.status});return s.blob()}var VT=new Set(["show","show_user"]);function HT(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cr=e=>typeof e=="string"&&e.length>0?e:null,T_=e=>typeof e=="string"?cr(e.split("/").pop()):null;function eo(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function zT(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function YT(e){let t=e.blocks.filter(ze).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&ze(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function JT(e,t){for(let n of HT(e))t(eo(n,"attachment"),eo(n,"filename")??T_(eo(n,"path")),eo(n,"mime"))}function QT(e,t){for(let n of[e,...zT(e.items)])ze(n)&&t(n.attachment,T_(n.path),null)}function XT(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=ze(r)&&Array.isArray(r.blocks)?YT(r):r;if(!ze(s)||!ze(s.info)||!Array.isArray(s.parts))continue;let o=cr(s.info.id);if(!o)continue;let i=cr(s.info.role)??"unknown",a=(c,p,d)=>{let g=mm(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)ze(c)&&(c.type==="file"?a(c.url,cr(c.filename),cr(c.mime)):c.type==="text"&&typeof c.text=="string"?JT(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&VT.has(he(c.tool))&&ze(c.state)&&ze(c.state.input)&&QT(c.state.input,a))}return t}function at(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function ZT(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function eI(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function hm(e,t,n){return e!==void 0?e:ZT(at(t),n)}var _m={get disableMobileAdvertising(){return hm(C().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return hm(C().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return hm(C().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var tI=new Set(["project-manager"]);function to(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:_m.enableProjects||!tI.has(e.name)}function nI(e){let t=e.agents.filter(to),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function I_(){return{projects:{list:vt,listForAccount:aa,get:At,detail:jn,create:pa,createRepo:da,provision:ga,update:Un,archive:Fn,llmCatalog:Ln,modelPicker:$n,modelAccess:rr,setModelAccess:sr,sandboxHealth:Bn,sandboxTemplates:rl,sessions:Tt,createSession:It},github:{linkRepository:ba,replaceProjectRepository:xa,getInstallation:Sa,listInstallations:Pa,listLinkableInstallations:wa,listRepositories:ka,listRepositoryBranches:va,linkInstallation:Ra,saveInstallation:Aa,deleteInstallation:Ta,storeUserToken:Ca},gitBackend:{get:Ia,repositories:Ea},connectStatus:Jc,marketplace:{items:o=>tg(o),item:o=>sg(o),itemFile:(o,i)=>og(o,i),marketplaces:()=>ng(),featured:()=>rg(),sources:{list:()=>ig(),add:o=>ag(o),remove:o=>cg(o)}}}}function E_(){return{billing:{accountState:Fu,accountStateMinimal:Nu,transactions:Bu,transactionsSummary:Ku,creditBreakdown:qu,usageHistory:Gu,usageRollup:ap,sessionCosts:{list:up,get:nr},tierConfigurations:Wu,setPlan:sp,previewPlan:rp,acceptEnterpriseOffer:op,contactSales:ip,checkout:{createSession:n=>Vu(n),confirmSession:(n,r)=>Hu(n,r)},subscription:{createPortalSession:(n,r)=>zu(n,r),cancel:(n,r)=>Yu(n,r),reactivate:n=>Ju(n),scheduleDowngrade:(n,r,s)=>Qu(n,r,s),cancelScheduledChange:n=>Xu(n),prorationPreview:(n,r)=>Zu(n,r)},credits:{purchase:n=>ep(n),autoTopupSettings:n=>tp(n),configureAutoTopup:n=>np(n)}},sandboxShares:{list:Td,create:Id,revoke:Ed}}}var Ye={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function ct(){let e=at("BACKEND_URL")||C().backendUrl;return e||"http://localhost:8008/v1"}function Et(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function lr(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=lr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return lr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function rI(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function no(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${ct()}/p/${n.external_id}/${Ye.KORTIX_MASTER}`:""),status:rI(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function bm(){let e=await vt(),t=[];for(let n of e){let r=await Tt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:no(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function xm(e){let t=await l.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function ro(e){let t=await xm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await ur(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function ur(e){let t=await bm();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Zt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function le(e,t,n){let r=n?.fetch??C().fetch??((p,d)=>fetch(p,d)),s=de(n?.backendUrl??C().backendUrl??"");if(!s)throw new Zt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${Et(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Zt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function so(e,t){return le("/auth/signup",{body:e},t)}function oo(e,t){return le("/auth/sign-in/password",{body:e},t)}function io(e,t){return le("/auth/sign-in/magic-link",{body:e},t)}function ao(e,t){return le("/auth/verify-otp",{body:e},t)}function co(e,t){return le("/auth/sign-in/oauth",{body:e},t)}function lo(e,t){return le("/auth/oauth/exchange",{body:e},t)}function en(e,t){return le("/auth/refresh",{body:e},t)}function uo(e,t){return le("/auth/password/reset",{body:e},t)}function po(e,t,n){return le("/auth/password/update",{body:e,bearer:t},n)}function go(e,t){return le("/auth/user",{bearer:e},t)}function mo(e,t,n){return le("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function fo(e,t){return le("/auth/sign-in/sso",{body:e},t)}var yo={enroll:(e,t,n)=>le("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>le(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>le(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>le(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function ho(e,t={},n){return le("/auth/sign-out",{body:t,bearer:e},n)}function _o(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=0,p=new Set,d=_=>(_.expires_at??0)*1e3,g=_=>d(_)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let _ of[...p])try{_(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let _=c,I=(async()=>{let j=await e.storage.get();if(_===c&&j)try{let D=JSON.parse(j);D.session?.access_token&&D.session?.refresh_token&&(r=D.session,s=D.user??null)}catch{r=null}return o=!0,r})();i=I,I.then(()=>{i===I&&(i=null)},()=>{i===I&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let _=r.refresh_token,I=c,j=en({refresh_token:_},e.request).then(async D=>(I!==c||(r=D.session,D.user&&(s=D.user),await m()),r)).catch(async D=>{if(I!==c)return r;let w=D&&typeof D=="object"&&"status"in D?D.status:0;if(w>=400&&w<500)return r=null,s=null,await m(),null;throw D}).finally(()=>{a===j&&(a=null)});a=j}return a}return{subscribe(_){return p.add(_),()=>{p.delete(_)}},current:()=>r,user:()=>s,load:f,async set(_,I){await f(),c+=1,a=null,r=_,I!==void 0&&(s=I),_||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function M_(){return{list:Fi,get:Bi,create:Ni,secretResources:{list:lc,create:uc,rotate:pc,retry:dc,remove:gc,grant:mc,revoke:fc,setAccess:yc},updateName:Ki,branding:{get:qi,update:Gi,uploadAsset:Wi,removeAsset:Vi,reset:Hi},leave:oa,members:zi,invite:Yi,removeMember:ra,updateMemberRole:sa,invites:Ji,cancelInvite:Qi,resendInvite:Xi,tokens:{list:$d,create:Ud,revoke:Fd},connectedApps:{list:Nd,revoke:Bd},audit:{log:Vd,export:zd,webhooks:{list:Yd,create:Jd,update:Qd,remove:Xd}}}}function O_(){return{assignments:{list:bd,create:xd,revoke:Sd},permissions:{list:Pd,forRole:od},roles:{list:nd,create:ad,update:cd,setPermissions:ld,remove:ud,usage:id},groups:{list:zp,get:Yp,create:Jp,update:Qp,remove:Xp,members:{list:Zp,add:ed,remove:td}},agentIdentities:rd,oauthClients:{list:gd,get:md,create:fd,update:yd,rotateSecret:hd,remove:_d},can:pd,canBatch:dd}}function D_(){let e={signUp:so,signInWithPassword:oo,sendMagicLink:io,verifyOtp:ao,signInWithProvider:co,exchangeCode:lo,refresh:en,resetPassword:uo,updatePassword:po,updateUserMetadata:mo,signInWithSso:fo,mfa:yo,user:go,signOut:ho,session:_o},t=M_(),n=O_();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Zi,describe:ea,accept:gs,acceptAndLand:ta,decline:na}}}var pr=new Map,Sm=new Map;function Pm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function j_(e){return pr.get(Pm(e))??null}function L_(){return[...pr.values()].filter(e=>typeof e=="string")}function $_(e){return pr.has(Pm(e))}async function lt(e){let t=Pm(e),n=pr.get(t);if(n!==void 0)return n;let r=Sm.get(t);if(r)return r;let s=(async()=>{try{let o=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Sm.delete(t)}})();return Sm.set(t,s),s}function U_(e){let{apiBaseUrl:t}=e;return $_(t)||lt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:j_(t)}}function F_(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=C().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),U_({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function N_(e,t){let n=null;async function r(){n||(n=zn(e,t,{showErrors:!1}).then(s=>{let o=er(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var tn={url:null,sandboxId:null,dbSandboxId:null,version:0},oI=new Set;function bo(e,t=null,n=null){if(!(tn.url===e&&tn.sandboxId===t&&tn.dbSandboxId===n)){tn={url:e,sandboxId:t,dbSandboxId:n,version:tn.version+1};for(let r of oI)r()}}function B_(){return tn.url}var dr=new Map;function K_(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Mt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function q_(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await ot(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await ot(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new S(K_(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ee(c);return bo(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function G_(e,t,n){let r=null;function s(){if(r)return r;let p=Fh(e,t);return p&&(r=p),r}let o=q_(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=lt(C().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Iu(p.session):null,h=f?.sandbox?.external_id,_=f?.runtime_session_id;if(h&&_){let w=Ee(h);return bo(w,h),r={runtimeSessionId:_,opencodeSessionId:_,runtimeUrl:w,sandboxId:h},Os(e,t,r),await m,r}let I=`${e}
|
|
15
|
+
${t}`,j=dr.get(I);if(j)return r=await j,await m,r;let D=o(g);dr.set(I,D);try{return r=await D,await m,r}finally{dr.get(I)===D&&dr.delete(I)}}function a(p){let d=s();if(!d)throw new Mt(p);return d}function c(){r=null,Nh(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var W=["directory","workspace"],W_=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=W,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),iI={"session.list":E("GET","/session",[...W,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",W,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",W,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...W,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",W,W_),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",W,W_),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",W,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",W,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",W,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":E("POST","/session/{sessionID}/share"),"session.unshare":E("DELETE","/session/{sessionID}/share"),"session.fork":E("POST","/session/{sessionID}/fork",W,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...W,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",W,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",W,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",W,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...W,"path"]),"file.read":E("GET","/file/content",[...W,"path"]),"find.files":E("GET","/find/file",[...W,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...W,"mode","context"]),"global.health":E("GET","/global/health",[]),"global.dispose":E("POST","/global/dispose",[]),"global.config.get":E("GET","/global/config",[]),"global.config.update":E("PATCH","/global/config",[],[],"config"),"provider.list":E("GET","/provider"),"provider.auth":E("GET","/provider/auth"),"provider.oauth.authorize":E("POST","/provider/{providerID}/oauth/authorize",W,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",W,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",W,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...W,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",W,["name","config"]),"mcp.connect":E("POST","/mcp/{name}/connect"),"mcp.disconnect":E("POST","/mcp/{name}/disconnect"),"mcp.auth.start":E("POST","/mcp/{name}/auth"),"mcp.auth.callback":E("POST","/mcp/{name}/auth/callback",W,["code"]),"mcp.auth.remove":E("DELETE","/mcp/{name}/auth"),"project.list":E("GET","/project"),"project.current":E("GET","/project/current"),"path.get":E("GET","/path")};function aI(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function cI(e,t,n={},r={}){let s=iI[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${aI(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function lI(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function uI(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=lI(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function wm(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await o.read();if(c)break;a=(a+p).replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
17
|
`);let d=a.split(`
|
|
18
18
|
|
|
19
|
-
`);a=d.pop()??"";for(let
|
|
20
|
-
`))if(h.startsWith("data:"))
|
|
21
|
-
`)),yield g}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*MT(e,t,n){let r=e.eventTransport??em(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function sr(e){let t=s=>(o,i)=>ET(e,CT(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:MT(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var Bh=200;async function OT(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function It(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new _(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function qh(e){let t=e.runtimeUrl.replace(/\/$/,""),n=sr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let m=`/messages/${s}${d.size?`?${d}`:""}`,g=P=>e.fetch(new Request(`${t}${P}${m}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),y=await g("/kortix/runtime");if((y.status===404||(y.headers.get("content-type")??"").startsWith("text/html"))&&(y=await g("/kortix/opencode")),!y.ok)throw new _(`Reading the session transcript failed: ${await OT(y)}`,{status:y.status,response:y});let h=await y.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,Bh),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,Bh),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>It(i,"Reading the session status failed")),n.permission.list().then(i=>It(i,"Reading permission requests failed")),n.question.list().then(i=>It(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{It(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){It(await n.question.reject({requestID:r}),"Dismissing the question failed");return}It(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new _("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return It(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function Gh(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return qh({runtimeUrl:r,rootId:n,fetch:$})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function Wh(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await Zl(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Zt=BigInt(4096),ze=BigInt(0xffffffffffff),Vh=ze+BigInt(1),DT=Vh/BigInt(2),at=BigInt(3600*1e3)*Zt,io=120*1e3,Hh=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,jT=/^msg_([0-9a-f]{12})/,Yh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Et(e){let t=jT.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function en(e){return BigInt(Math.trunc(e))*Zt&ze}function Mt(e,t){let n=e-t&ze;return n>=DT&&(n-=Vh),n}function tm(e){let t=null;for(let n of e)n!=null&&(t===null||Mt(n,t)>BigInt(0))&&(t=n);return t}function zh(e,t){let n=Et(e);return n===null?!1:Mt(n,en(t))>at}function Jh(e,t){let n=t===void 0?null:en(t);return Qh(e,r=>n===null||Mt(r,n)<=at)}function Qh(e,t){let n=[];for(let r of e){let s=Et(r);s!==null&&t(s)&&n.push(s)}return tm(n)}function $T(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Yh[n%62])}return e}function nm(e){let t=e.random,n=en(e.nowMs-(e.backdateMs??io)),r=e.newestKnownTime??null;if(r!==null){let o=Mt(r,n);o>=BigInt(0)&&o<=at&&(n=r+BigInt(1)&ze)}let s="";if(t)for(let o=0;o<14;o++)s+=Yh[Math.min(61,Math.floor(t()*62))];else s=$T();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function ao(e={}){let t=e.nowMs??Date.now(),n=en(t-io),r=Qh(e.after??[],s=>{let o=Mt(s,n);return o>=BigInt(0)&&o<=at});return nm({nowMs:t,newestKnownTime:r}).id}function Xh(e){return{scope:()=>Ql(e.projectId,e.sessionId),providerSecretPool:{list:()=>tc(e.projectId,e.sessionId),get:t=>ec(e.projectId,e.sessionId,t),set:(t,n)=>nc(e.projectId,e.sessionId,t,n)},rescope:t=>Xl(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,c=ao(),p=await Gn(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new _("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Zh=async function*(e){let t=v().eventStreamTransport;if(!t){yield*em(((s,o)=>$(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await es(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Je(){let e=Lh();return e||(v().billingEnabled??!1?"":By())}async function rm(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function sm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function om(e){let t=sm(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await rm(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function im(e,t,n){let r=sm(e),s=await $(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await rm(s,"Failed to save secret"))}async function am(e,t){let n=sm(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await rm(r,"Failed to delete secret"))}var eb={list:om,set:im,delete:am};async function tb(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await $(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function co(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function or(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function lm(e){let t=or(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await co(n,"Failed to list terminals"));return n.json()}async function um(e,t){let n=or(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await co(r,"Failed to create terminal"));return r.json()}async function pm(e,t,n){let r=or(e),s=await $(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await co(s,"Failed to update terminal"));return s.json()}async function dm(e,t){let n=or(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await co(r,"Failed to remove terminal"))}async function gm(e,t,n){let r=or(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Bt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function nb(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var ct="\x1B",rb="\x07",LT="\0",cm=`(?:${rb}|${ct}\\\\)`,UT=[new RegExp(`${ct}\\]697;[^${rb}${ct}]*${cm}`,"g"),new RegExp(`${LT}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${ct}\\][0-9]+;rgb:[0-9a-fA-F/]+${cm}`,"g"),new RegExp(`${ct}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${cm}`,"g"),new RegExp(`${ct}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${ct}\\[\\d+;\\d+R`,"g"),new RegExp(`${ct}\\[\\?[0-9;]*c`,"g")];function sb(e){let t=e;for(let n of UT)t=t.replace(n,"");return t}var ob={list:lm,create:um,update:pm,remove:dm,webSocketUrl:gm};async function O(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await $(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function FT(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return O(e,`/kortix/tasks${r}`)}async function NT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function KT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function BT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function qT(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function GT(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function WT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function VT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function HT(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function YT(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function zT(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function JT(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function QT(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function XT(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function ZT(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function eC(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function tC(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function nC(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function rC(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function sC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function oC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function iC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function aC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function cC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function lC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function uC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function pC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function dC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function gC(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function mC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function fC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function yC(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function hC(e){return O(e,"/kortix/projects")}async function bC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function _C(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function PC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function xC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function SC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function wC(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function kC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function AC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function vC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function RC(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function TC(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function CC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function IC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function EC(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function MC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function OC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function DC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function jC(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var $C=1e4,LC={retryOnAuthError:!1};function tn(e,t,n){return O(e,t,{signal:AbortSignal.timeout($C),...n},LC)}async function UC(e,t=!1){return(await tn(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function FC(e){return(await tn(e,"/kortix/services/templates")).templates??[]}async function NC(e,t){return(await tn(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function KC(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return tn(e,s,{method:r?"DELETE":"POST"})}async function BC(e,t){return tn(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function qC(e,t){return tn(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Qe=new Map,GC=256,nn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function lt(){let e=Je();if(!e)throw new nn;return Me(e)}function Me(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Qe.get(e);if(t)return Qe.delete(e),Qe.set(e,t),t;if(!Wr())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=sr({baseUrl:e,fetch:$,eventTransport:Zh});return Qe.set(e,n),Qe.size>GC&&Qe.delete(Qe.keys().next().value),n}function WC(e){Qe.delete(e)}function VC(){Qe.clear()}var lo=new Map;function HC(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=lo.get(e);if(t)return t;let n=sr({baseUrl:e,fetch});return lo.set(e,n),n}function YC(e){lo.delete(e)}function zC(){lo.clear()}async function JC(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function QC(e){let t=Je();if(!t)throw new _("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await $(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new _(`System reload failed (${r.status}): ${await JC(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new _(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new _(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var ib="frontend";function uo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${ib}] ${t}`,...n?[n]:[]);try{lt().app.log({service:ib,level:e,message:t,extra:n})}catch{}}var ut={debug:(e,t)=>uo("debug",e,t),info:(e,t)=>uo("info",e,t),warn:(e,t)=>uo("warn",e,t),error:(e,t)=>uo("error",e,t)};function ab(e){return{type:"heartbeat-gap",gapMs:e}}function cb(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var XC={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},ZC=16,eI=8,tI=6e4,nI=5e3,rI=250,sI=1e3,oI=3e4,iI=5,aI=1e4,cI=4,lI=.5,uI=3e3,pI=3e4,dI=2e4,gI=2e3,mI=8;function fI(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function yI(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function lb(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var ir=new WeakMap;function hI(e,t,n){let r=t.timers??XC,s=t.connectTimeoutMs??dI,o=t.heartbeatTimeoutMs??tI,i=t.maxConsecutiveHardFailures??mI,a=new AbortController;function c(b,...x){for(let R of n){let T=b(R);if(T)try{T(...x)}catch(w){console.warn("[opencode-events] subscriber handler threw, skipping",w)}}}let p=null,d=!1,m=b=>{p!==b&&(p=b,b&&c(x=>x.onConnectionChange,b))},g=r.now(),y=null,h=[],P,C=0,M=new Map,L=()=>{if(P&&r.clearTimeout(P),P=void 0,h.length===0)return;let b=h;h=[],M.clear(),C=r.now(),g=r.now();for(let x of b)x&&c(R=>R.onEvent,x.event)},f=()=>{if(P)return;let b=r.now()-C;P=r.setTimeout(L,Math.max(0,ZC-b))};return(async()=>{let b=0,x=0,R=0;for(;!a.signal.aborted;){let T=!1,w=!1,S,I,k=null,U=r.now(),j=new AbortController;m("connecting");let D=lb(a.signal);D.promise.then(()=>j.abort());try{let ne=await new Promise(($t,bt)=>{let ge=!1;I=r.setTimeout(()=>{ge||(ge=!0,ut.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),j.abort(),bt(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:j.signal,sseDefaultRetryDelay:uI,sseMaxRetryDelay:pI,sseMaxRetryAttempts:1}).then(Le=>{ge||(ge=!0,r.clearTimeout(I),$t(Le))},Le=>{ge||(ge=!0,r.clearTimeout(I),bt(Le))})}),{stream:yt}=ne;if(y){let $t=r.now()-y.lastActivityAt,bt=y.eventful;y=null,(bt||$t>nI)&&c(ge=>ge.onGapRehydrate,$t)}g=r.now();let ht=()=>{r.clearTimeout(S),S=r.setTimeout(()=>{ut.warn("SSE heartbeat timeout, forcing reconnect"),j.abort()},o)};ht();let Br=r.now(),MS=yt[Symbol.asyncIterator]();for(;!j.signal.aborted;){let $t=MS.next().then(Ue=>({kind:"next",result:Ue}),Ue=>({kind:"error",error:Ue})),bt=lb(j.signal),ge=await Promise.race([$t,bt.promise.then(()=>({kind:"aborted"}))]);if(bt.cleanup(),ge.kind==="aborted")break;if(ge.kind==="error")throw ge.error;if(ge.result.done)break;m("open"),ht();let Le=ge.result.value,Lt=Le&&typeof Le=="object"&&"payload"in Le?Le.payload:Le;if(!Lt?.type)continue;Lt.type!=="server.connected"&&(T=!0);let Zo=yI(h[h.length-1]?.event,Lt);if(Zo)h[h.length-1]={type:Zo.type,event:Zo};else{let Ue=fI(Lt);if(Ue){let Yf=M.get(Ue);Yf!==void 0&&(h[Yf]=void 0),M.set(Ue,h.length)}h.push({type:Lt.type,event:Lt})}f(),!(r.now()-Br<eI)&&(Br=r.now(),await new Promise(Ue=>r.setTimeout(Ue,0)))}w=T}catch(ne){if(a.signal.aborted)break;k=ne;let yt=String(ne),ht=Ut(ne)||Ut(ne?.cause);if(ut.error("SSE event stream error",{error:yt,retryCount:b,isAuthError:ht}),ht)try{as(),await is(),ut.info("SSE: refreshed auth token after auth error")}catch(Br){ut.error("SSE: failed to refresh auth token",{error:String(Br)})}}finally{r.clearTimeout(S),r.clearTimeout(I),j.abort(),D.cleanup(),L()}if(a.signal.aborted)break;let q=r.now()-U,Q=k?.cause?.status;if(x=!T&&(typeof Q=="number"&&Q>=400||q<gI)?x+1:0,x>=i){ut.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:x,lastError:String(k)}),p=null,d=!0,c(ne=>ne.onParked,{consecutiveFailures:x,lastError:k});break}m("lost"),y={lastActivityAt:g,eventful:(y?.eventful??!1)||T},R=w&&q<aI?R+1:0;let je=w&&R<=cI;je?b=0:(b++,b>1&&ut.warn("SSE event stream reconnecting",{retryCount:b}));let vn=je?rI:Math.min(sI*2**Math.min(b-1,iI),oI),$e=Math.round(vn*(1+lI*(r.random?.()??0)));await new Promise(ne=>{let yt=r.setTimeout(ne,$e),ht=()=>{r.clearTimeout(yt),ne()};a.signal.addEventListener("abort",ht,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),P&&r.clearTimeout(P)}}}function po(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},c=ir.get(i);if(c?.isParked()&&(ir.delete(i),c=void 0),!c)c=hI(i,e,new Set([a])),ir.set(i,c);else{c.subscribers.add(a);let y=c.connectionState();y&&s?.(y)}let p=c,d=!1,m=()=>{d||(d=!0,o&&o.removeEventListener("abort",g),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),ir.get(i)===p&&ir.delete(i)))},g=()=>m();return o&&(o.aborted?m():o.addEventListener("abort",g,{once:!0})),{close:m}}function ub(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return po({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function mb(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new _(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function on(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function se(e){let t=(e??Je()).trim();if(!t)throw new nn;return t}async function mo(e,t){let n=await $(`${se(t)}${e}`);if(!n.ok)throw new _(await on(n),{status:n.status,response:n});return n.json()}var fo=["/workspace","/tmp","/home","/opt"],bI=fo.filter(e=>e!=="/workspace");function ym(e){return fo.some(t=>e===t||e.startsWith(`${t}/`))}function an(e){return ym(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(bI.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var hm=pt;async function cn(e,t){let n=se(t),r=pt(e)||".";return(await mo(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function ln(e,t){let n=se(t),r=pt(e),s=await $(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new _(await on(s),{status:s.status,response:s});return s.json()}async function _I(e,t,n){let r=se(n),s=pt(e),o=await $(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new _(await on(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new _("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var PI=8,go=0,fb=[];async function xI(){if(go<PI){go++;return}await new Promise(e=>fb.push(e)),go++}function SI(){go--,fb.shift()?.()}function yb(e,t){let n=se(t);return Ln(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function un(e,t){await xI();try{let n=se(t);try{return await _I(e,void 0,n)}catch{}let r=await ln(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{SI()}}async function lr(e){return mo("/file/status",se(e))}async function ur(e,t,n){let r=se(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),mo(`/find/file?${s.toString()}`,r)}async function pr(e,t){let n=se(t);return(await mo(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var ar=[400,1200],wI=e=>e===408||e===429||e===502||e===503||e===504,pb=e=>new Promise(t=>setTimeout(t,e));function kI(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var mm=3e4,hb=15*6e4,AI=256;function rn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return mm;let t=mm+e/AI;return Math.min(hb,Math.max(mm,Math.round(t)))}async function vI(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function cr(e,t){let n;for(let s=0;s<=ar.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,kI(a)||s===ar.length)break;await pb(ar[s]);continue}if(o.ok)return o.json();let i=await vI(o);if(n=new _(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!wI(o.status)||s===ar.length)throw n;await pb(ar[s])}if(n instanceof _)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new _(`Upload failed: ${r}`)}var fm=8*1024*1024;function RI(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new _(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function db(e,t){try{e?.onProgress?.(t)}catch{}}function gb(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function TI(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function pn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=se(o),c=rn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=fm){let y=await cr(()=>gb(e,t,p),h=>$(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return RI(y[0],e.size),db(i,{loadedBytes:e.size,totalBytes:e.size}),y}let m=(await cr(()=>gb(new Blob([],{type:e.type}),t,p),y=>$(`${a}/file/upload`,{method:"POST",body:y},{timeoutMs:rn(0)})))[0]?.path;if(!m)throw new _("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let g=TI(m);if(!g.name)throw new _(`Upload reservation returned an invalid file path: ${m}`,{code:"UPLOAD_INVALID_PATH"});try{for(let y=0;y<e.size;y+=fm){let h=Math.min(e.size,y+fm),P=e.slice(y,h,e.type),C=await cr(()=>{let M=new FormData;return g.parent&&M.append("path",g.parent),M.append("filename",g.name),M.append("first",y===0?"true":"false"),M.append("offset",String(y)),M.append("file",P,g.name),M},M=>$(`${a}/file/append`,{method:"POST",body:M},{timeoutMs:rn(P.size)}));if(C.path!==m||C.size!==h)throw new _(`Upload verification failed for ${m}: expected ${h} bytes, received ${C.size}`,{code:"UPLOAD_SIZE_MISMATCH"});db(i,{loadedBytes:h,totalBytes:e.size})}}catch(y){throw await Ot(m,a).catch(()=>{}),y}return[{path:m,size:e.size}]}function bb(e,t,n){let r=se(n);return cr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>$(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:CI}))}var CI=hb;function II(e,t,n){let r=se(n),s=rn(t.size);return cr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>$(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var sn=class extends _{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function dr(e,t){let n=se(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=an(`${a}/${i}`),p=[];try{p=await cn(_b(c),n)}catch(m){if(!(m instanceof _&&m.status===404))throw m}if(p.some(m=>m.name===Pb(c)))throw new sn(c);let d=await xb(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function gr(e,t,n){let r=se(n);return II(t,await un(e,r),r)}function EI(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function _b(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Pb(e){return e.slice(e.lastIndexOf("/")+1)}function MI(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function mr(e,t,n){let r=se(n),s=an(EI(e.trim()));return xb(s,t,r,{overwrite:!0})}async function xb(e,t,n,r){let s=Pb(e);if(!s)throw new _(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=_b(e);await dn(o,n).catch(()=>{});let i=MI(),a=await pn(t,o,`.${s}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new _(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=an(c);try{await Sb(p,e,n,r.overwrite)}catch(m){throw await Ot(p,n).catch(()=>{}),!r.overwrite&&m instanceof _&&m.status===409?new sn(e):m}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Ot(e,t){let n=await $(`${se(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new _(`Delete failed (${n.status}): ${await on(n)}`,{status:n.status,response:n});return n.json()}async function dn(e,t){let n=await $(`${se(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new _(`Mkdir failed (${n.status}): ${await on(n)}`,{status:n.status,response:n});return n.json()}async function fr(e,t,n){return Sb(e,t,se(n),!0)}async function Sb(e,t,n,r){let s=await $(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!s.ok)throw new _(`Rename failed (${s.status}): ${await on(s)}`,{status:s.status,response:s});return s.json()}async function bm(){return mb(await lt().project.current())}async function yo(){return mb(await lt().global.health())}async function _m(){try{return(await yo()).healthy===!0}catch{return!1}}var wb={list:cn,read:ln,readBlob:un,status:lr,findFiles:ur,findText:pr,upload:pn,write:mr,create:dr,copy:gr,remove:Ot,mkdir:dn,rename:fr,currentProject:bm,health:yo,isReachable:_m,toDaemonPath:pt,toSandboxAbsolutePath:an,toWorkspaceRelative:hm};function kb(e){return{list:async t=>cn(t,(await e()).runtimeUrl),read:async t=>ln(t,(await e()).runtimeUrl),readBlob:async t=>un(t,(await e()).runtimeUrl),status:async()=>lr((await e()).runtimeUrl),findFiles:async(t,n)=>ur(t,n,(await e()).runtimeUrl),findText:async t=>pr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>pn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>mr(t,n,(await e()).runtimeUrl),create:async t=>dr(t,(await e()).runtimeUrl),copy:async(t,n)=>gr(t,n,(await e()).runtimeUrl),remove:async t=>Ot(t,(await e()).runtimeUrl),mkdir:async t=>dn(t,(await e()).runtimeUrl),rename:async(t,n)=>fr(t,n,(await e()).runtimeUrl)}}function Ab(e){return{get:t=>qn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Yn(e.sessionId,{projectId:e.projectId}),update:t=>Vl(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Hl(e.projectId,e.sessionId)),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>gu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Wn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Vn(e.projectId,e.sessionId)),configState:()=>Yl(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),zl(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Jl(e.projectId,e.sessionId,...t)),setSharing:t=>Al(e.projectId,e.sessionId,t),previews:()=>Cl(e.projectId,e.sessionId),participants:()=>vl(e.projectId,e.sessionId),watch:()=>Rl(e.projectId,e.sessionId),setWatch:t=>Tl(e.projectId,e.sessionId,t),commit:t=>bl(e.projectId,e.sessionId,t),publicShares:{list:()=>Il(e.projectId,e.sessionId),create:(...t)=>El(e.projectId,e.sessionId,...t),revoke:(...t)=>Ml(e.projectId,e.sessionId,...t)}}}function vb(e){return{reminders:{list:()=>ld(e.projectId,e.sessionId),create:t=>ud(e.projectId,e.sessionId,t),update:(t,n)=>Is(e.projectId,e.sessionId,t,n),remove:t=>Es(e.projectId,e.sessionId,t)},audit:(t,n)=>jl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Vg(e.projectId,e.sessionId,t,n),read:(t,n)=>Hg(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>$l(e.projectId,e.sessionId,t),messageAuthors:()=>tu(e.projectId,e.sessionId),modelUsage:()=>nu(e.projectId,e.sessionId),transcriptSync:t=>Ll(e.projectId,e.sessionId,t),log:t=>Ul(e.projectId,e.sessionId,t),turn:()=>Fl(e.projectId,e.sessionId),prompts:{create:t=>Gn(e.projectId,e.sessionId,t),list:()=>Nl(e.projectId,e.sessionId),remove:t=>Kl(e.projectId,e.sessionId,t),retry:t=>Gl(e.projectId,e.sessionId,t),edit:(t,n)=>Bl(e.projectId,e.sessionId,t,n),interrupt:t=>ql(e.projectId,e.sessionId,t),hold:t=>Wl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Rb(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var DI=["control_plane","provider_ingress","daemon","upstream_port"];function Pm(e){return typeof e=="string"&&DI.includes(e)?e:null}function xm(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function Sm(e,t){let n=(e===void 0?Je():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await $(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=Pm(r.headers.get("X-Kortix-Proxy-Hop"))??Pm(o?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var Tb=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Cb=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Ib=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Eb=new Set([22,4096,parseInt(Ye.KORTIX_MASTER,10)]);function jI(e){return Cb.test(e)}function ho(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function $I(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var LI=new Set(["'",'"',"`","<","(","["]),UI=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function FI(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&LI.has(e[t]);)t++;for(;n>t&&UI.has(e[n-1]);)n--;return e.slice(t,n)}function NI(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var KI=/^\/proxy\/(\d{1,5})(\/.*)?$/,BI=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function Mb(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:BI.test(t.pathname)}catch{return!1}}function hr(e){if(!e)return null;let t=FI($I(e.trim())),n=km(t);if(n){let r=ho(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ye.KORTIX_MASTER,10);if(s===i){let c=r.pathname.match(KI);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=ho(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=ho(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=NI(e);return r&&r!==e?hr(r):null}}function qI(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function GI(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Ob(e){let t=[],n=new Set,r=qI(e);Tb.lastIndex=0;let s;for(;(s=Tb.exec(e))!==null;){let o=hr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||Eb.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:GI(s.index,r)}))}return t}function WI(e){return Ob(e).length>0}function VI(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Db(e){return e.trim().toLowerCase().split("_").join("-")}function jb(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function HI(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(Db(n.sandboxId));return`${jb(s)}${t}`}function $b(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=ho(t);if(!$b(n))return Nb(e,r);let s=HI(e,r,n);return s||(VI(n.apiBaseUrl)?`http://p${e}-${Db(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${jb(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function YI(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return dt(3211,`/open?path=/workspace/${r}`,t)}function Lb(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function zI(e){return`http://localhost:3211${Lb(e)}`}function Ub(){return"/health"}function JI(e){return dt(3211,Ub(),e)}function QI(e,t){return dt(e,"/",t)}function Fb(e){let t=hr(e);return!(!t||Eb.has(t.port)||Mb(e))}function wm(e,t){if(!e)return e;let n=hr(e);return n?Fb(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function Nb(e,t="/"){return`http://localhost:${e}${t}`}var Kb=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function km(e){let t=e.match(Cb);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(Ib);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(Kb);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function XI(e){try{let t=km(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function ZI(e){return jI(e)||Ib.test(e)||Kb.test(e)}function eE(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var yr="/web-proxy/";function tE(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${yr}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Ye.KORTIX_MASTER,10);return`${dt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function nE(e){try{let t=new URL(e),n=t.pathname.indexOf(yr);if(n===-1)return null;let s=t.pathname.slice(n+yr.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function rE(e){try{return new URL(e).pathname.includes(yr)}catch{return e.includes(yr)}}function sE(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function oE(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function Bb(e){return{health:t=>Sm(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>wm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ce(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Am(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=$h(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:m}=Nh(e,t,n),g={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:m,resolvePreviewOptsForSandbox:r,get model(){return s},set model(y){s=y},get agent(){return o},set agent(y){o=y},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Ab(g),...vb(g),...Bb(g),...Wh(g),...Xh(g),...ub(g),files:kb(c),...Gh(g),get runtime(){return Me(d("runtime").runtimeUrl)}}}function qb(e){return{apps:{list:()=>Nd(e),create:t=>Kd(e,t),get:t=>Ms(e,t),update:(...t)=>Bd(e,...t),access:{get:(...t)=>Vd(e,...t),update:(...t)=>Yd(e,...t),session:(...t)=>zd(e,...t),agents:t=>Hd(e,t)},remove:t=>qd(e,t),token:t=>Gd(e,t),authEnv:t=>Wd(e,t),artifacts:{register:t=>Os(e,t),uploadArchive:(...t)=>Jd(e,...t),finalize:(...t)=>Ds(e,...t)},deployments:{create:(...t)=>Qd(e,...t),list:t=>Xd(e,t),get:(...t)=>Zd(e,...t),logs:(...t)=>eg(e,...t),remove:(...t)=>rg(e,...t)},start:t=>tg(e,t),stop:t=>ng(e,t),rollback:(...t)=>sg(e,...t),machines:{list:t=>og(e,t),start:(t,n)=>ag(e,t,n),stop:(t,n)=>cg(e,t,n),restart:(t,n)=>lg(e,t,n),destroy:(t,n)=>ug(e,t,n)},scale:(t,n)=>pg(e,t,n),exec:(...t)=>dg(e,...t),volumes:{list:t=>gg(e,t),create:(...t)=>mg(e,...t),update:(...t)=>fg(e,...t),destroy:(...t)=>yg(e,...t),snapshots:(...t)=>hg(e,...t),snapshot:(...t)=>bg(e,...t),restore:(...t)=>_g(e,...t),fork:(...t)=>Pg(e,...t)}}}}function Gb(e){return{list:()=>ba(e),invite:(...t)=>xa(e,...t),update:(...t)=>_a(e,...t),revoke:t=>Pa(e,t),pendingInvites:()=>Sa(e),resendInvite:(...t)=>ka(e,...t),revokeInvite:(...t)=>wa(e,...t),requests:()=>fa(e),approveRequest:(...t)=>ya(e,...t),rejectRequest:(...t)=>ha(e,...t),groupGrants:()=>Aa(e),attachGroupGrant:(...t)=>va(e,...t),updateGroupGrant:(...t)=>Ra(e,...t),detachGroupGrant:t=>Ta(e,t),resourceGrants:{list:()=>Ca(e),create:t=>Ia(e,t),remove:t=>Ea(e,t)}}}function Wb(e){return{tokens:{list:()=>_d(e),create:t=>Pd(e,t),revoke:t=>xd(e,t)},setupLinks:{requestSecret:t=>Id(e,t),requestConnector:t=>Ed(e,t)},validateManifest:t=>Vi(e,t),gitToken:()=>Hi(e),agentIdentities:()=>$p(e),secrets:{list:()=>ja(e),upsert:t=>$a(e,t),setStrategy:(...t)=>La(e,...t),broker:(...t)=>Ua(e,...t),remove:t=>Ba(e,t),setPersonal:(...t)=>qa(e,...t),removePersonal:t=>Ga(e,t),setGitCredential:t=>Ka(e,t),listProviderOAuth:()=>Fa(e),startProviderOAuth:(...t)=>ss(e,...t),pollProviderOAuth:(...t)=>os(e,...t),removeProviderOAuth:t=>Na(e,t)},access:Gb(e)}}function Vb(e){return{list:()=>sc(e),listAll:()=>oc(e),reconcile:(...t)=>ic(e,...t),reconcileMember:(...t)=>ac(e,...t),updateCredential:(...t)=>cc(e,...t),revoke:(...t)=>lc(e,...t),activate:(...t)=>uc(e,...t),setDefault:(...t)=>pc(e,...t),rename:(...t)=>dc(e,...t),share:(...t)=>mc(e,...t),addComputer:(...t)=>gc(e,...t),pipedreamConnect:(...t)=>fc(e,...t),pipedreamFinalize:(...t)=>yc(e,...t)}}function bo(e){return{catalog:t=>qt(e,t),tools:()=>ls(e),search:(...t)=>rc(e,...t),describe:(...t)=>us(e,...t),call:(...t)=>wt(e,...t),callAction:(t,n,r,s)=>wt(e,`${t}.${n}`,r,s),accounts:(...t)=>ps(e,...t),uploadAttachment:(...t)=>ds(e,...t)}}function vm(e,t){return{slug:t,run:(r,s,o)=>hs(e,t,r,s,o),call:(r,s,o)=>wt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?us(e,`${t}.${r}`):(await qt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>ps(e,t),paginate:(r,s,o)=>Lc(e,t,r,s,o),uploadAttachment:(r,s)=>ds(e,r,{...s,connector:t})}}var iE=100,aE=0,cE=new Set(["attachment_size_mismatch","attachment_failed"]),Hb=()=>new _("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Yb(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function Rm(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(f=>!f.handedOff);function m(f,b){f.removalDeleted||(f.removalDeleted=!0,Gt(e,b).catch(()=>{}))}function g(){c&&clearTimeout(c);let f=d().map(({item:x})=>x);(f.length!==p.attachments.length||f.some((x,R)=>x!==p.attachments[R]))&&(p={attachments:f});let b=Math.min(...f.filter(x=>x.status==="ready").map(x=>Date.parse(x.attachment.expires_at)));Number.isFinite(b)&&!a&&(c=setTimeout(()=>{for(let x of d())x.item.status==="ready"&&Date.parse(x.item.attachment.expires_at)<=Date.now()&&(x.item={...x.item,status:"error",error:Hb()});g()},Math.min(2147483647,Math.max(0,b-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let x of s)x();for(let x of[...o])x()}function y(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(f){y();let b=d();if(b.length+f.length>20)throw new Error("A message can contain up to 20 attachments");if(f.some(R=>!Number.isSafeInteger(R)||R<=0||R>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(b.reduce((R,T)=>R+T.item.size,0)+f.reduce((R,T)=>R+T,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function P(){for(let f of r.values()){if(i>=n)break;if(f.item.status!=="pending"||!f.item.file||a&&!f.handedOff)continue;let b=f.item.file;i++;let x=++f.generation,R=new AbortController;f.abort=R,f.item={...f.item,status:"uploading",error:void 0};let T=()=>(!a||f.handedOff===!0)&&r.get(f.item.id)===f&&f.generation===x,w,S=0,I,k=()=>{I=void 0,!(!T()||f.item.status!=="uploading"||w===void 0)&&(f.item={...f.item,receivedBytes:w},w=void 0,S=Date.now(),g())},U=j=>Math.floor(j*100/f.item.size);Nn(e,b,{resume:f.upload,signal:R.signal,onUpload:j=>{f.upload=j,f.removed&&(R.abort(),m(f,j.attachment_id))},onProgress:j=>{if(!T()||U(j)===U(f.item.receivedBytes)||(w=j,I))return;let D=S+iE-Date.now();if(D<=0)return k();I=setTimeout(k,D),typeof I=="object"&&"unref"in I&&I.unref()},onProcessing:()=>{I&&clearTimeout(I),I=void 0,w=void 0,T()&&(f.item={...f.item,status:"processing",receivedBytes:f.item.size},g())}}).then(j=>{T()&&(f.item={...f.item,status:"ready",attachment:Yb(j),receivedBytes:j.size})}).catch(j=>{j instanceof _&&cE.has(j.code??"")&&(f.upload=void 0),T()&&(f.item={...f.item,status:j instanceof _&&j.code==="ABORTED"?"aborted":"error",error:j instanceof Error?j:new Error(String(j))})}).finally(()=>{i--,I&&clearTimeout(I),f.abort===R&&(f.abort=void 0),g(),P()})}g()}function C(f){h(f.map(x=>x.size));let b=f.map(x=>{let R=`attachment-${++aE}`;return r.set(R,{generation:0,item:{id:R,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),R});return g(),P(),b}function M(f){let b=r.get(f);!b||b.item.status==="ready"||(b.generation++,b.abort?.abort(),b.item={...b.item,status:"aborted",error:new Error("Attachment upload cancelled")},g())}function L(f,{signal:b}={}){let x=[...f];return new Promise((R,T)=>{let w=()=>{o.delete(k),b?.removeEventListener("abort",I)},S=U=>{w(),T(U)},I=()=>S(Ae()),k=()=>{let U=!1;for(let D of x){let q=r.get(D);if(!q)return S(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return S(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return S(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&(U=!0)}if(U)return;let j;try{j=x.map(D=>{let q=Yb(r.get(D).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(D){return S(D instanceof Error?D:new Error(String(D)))}w(),R(j)};if(b?.aborted)return I();o.add(k),b?.addEventListener("abort",I,{once:!0}),k()})}return{add:f=>C([f])[0],addMany:C,retry(f){let b=r.get(f);if(b?.handedOff||y(),!(!b||b.item.status==="ready"||b.item.status==="uploading"||b.item.status==="processing"||b.item.status==="pending")){if(!b.item.file||b.upload&&Date.parse(b.upload.expires_at)<=Date.now())throw Hb();b.item={...b.item,status:"pending",error:void 0},P()}},async remove(f){let b=r.get(f);if(!b)return;b.removed=!0,b.generation++,r.delete(f);let x=b.upload?.attachment_id??b.item.attachment?.attachment_id;x&&b.abort?.abort(),g(),P(),x&&m(b,x)},abort:M,submit(f){if(!a){for(let b of f){let x=r.get(b);x&&(x.handedOff=!0)}g()}},reclaim(f){if(!a){for(let b of f){let x=r.get(b);x&&(x.handedOff=!1)}g()}},whenReady:L,forget(f=d().map(b=>b.item.id)){for(let b of f){let x=r.get(b);x&&(x.generation++,x.abort?.abort(),r.delete(b))}g(),P()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let f of r.values()){if(f.handedOff)continue;f.generation++,f.abort?.abort();let b=f.upload?.attachment_id??f.item.attachment?.attachment_id;b&&e&&Gt(e,b).catch(()=>{})}s.clear(),g()}},getSnapshot:()=>p,subscribe(f){return s.add(f),()=>{s.delete(f)}}}}function zb(e){return{attachments:{upload:(...t)=>Nn(e,...t),delete:(...t)=>Gt(e,...t),createController:t=>Rm(e,t)},get:t=>Cn(e,t),detail:()=>In(e),skills:{create:(...t)=>ta(e,...t)},audit:t=>kd(e,t),update:t=>On(e,t),archive:()=>Dn(e),llmCatalog:()=>En(e),modelPicker:()=>Mn(e),modelAccess:()=>zn(e),setModelAccess:t=>Jn(e,t),sandboxHealth:()=>$n(e),onboardingComplete:(...t)=>ea(e,...t)}}function Jb(e){return{sessions:{list:t=>At(e,t),listPage:t=>kl(e,t),create:t=>vt(e,t),ensureWarm:()=>Ol(e),claimWarm:t=>Dl(e,t)},review:{list:t=>td(e,t),get:t=>nd(e,t),submit:t=>rd(e,t),act:(...t)=>sd(e,...t),bulkAct:t=>od(e,t)},approvals:{list:t=>Ma(e,t),resolve:(...t)=>Da(e,...t),sessionsNeedingInput:t=>Oa(e,t)}}}function Qb(e){return{files:{list:t=>zc(e,t),listDirectory:t=>Jc(e,t),read:(t,n)=>Xc(e,t,n),search:(...t)=>Qc(e,...t),archive:(...t)=>Zc(e,...t),archiveRequest:(...t)=>el(e,...t),history:(...t)=>al(e,...t)},git:{commits:()=>sl(e),commit:t=>ol(e,t),commitDiff:t=>il(e,t),branches:()=>rl(e),versionDiff:(...t)=>cl(e,...t),inviteCollaborator:(...t)=>Wi(e,...t)},changeRequests:{list:()=>ll(e),get:t=>ul(e,t),update:(...t)=>_l(e,...t),diff:t=>pl(e,t),mergePreview:t=>dl(e,t),open:(...t)=>gl(e,...t),merge:(...t)=>ml(e,...t),close:(...t)=>fl(e,...t),reopen:(...t)=>yl(e,...t),requestChanges:(...t)=>hl(e,...t)},...Jb(e)}}function Xb(e){return{policies:{list:()=>Uc(e),set:(...t)=>Fc(e,...t)},reminders:{list:()=>gd(e),updateMany:(...t)=>pd(e,...t),removeMany:(...t)=>dd(e,...t)},triggers:{list:()=>ru(e),eventApps:()=>uu(e),eventTypes:(...t)=>lu(e,...t),create:(...t)=>su(e,...t),update:(...t)=>ou(e,...t),remove:(...t)=>iu(e,...t),fire:(...t)=>cu(e,...t),setActivation:(...t)=>au(e,...t)},...Qb(e)}}function Zb(e,t){return{connectors:{...bo(e),list:()=>hc(e),config:(...n)=>kc(e,...n),create:(...n)=>Rc(e,...n),remove:(...n)=>Cc(e,...n),sync:()=>bc(e),auth:{discover:(...n)=>Tc(e,...n)},setName:(...n)=>Ac(e,...n),setCredentialMode:(...n)=>_c(e,...n),setAuthorizationStrategy:(...n)=>Pc(e,...n),setCredential:(...n)=>Dc(e,...n),deleteCredential:(...n)=>jc(e,...n),setSensitive:(...n)=>xc(e,...n),connections:t,policies:{get:(...n)=>Sc(e,...n),set:(...n)=>wc(e,...n)},pipedream:{listApps:(...n)=>Ic(e,...n),listSections:(...n)=>Ec(e,...n),connect:(...n)=>vc(e,...n),finalize:(...n)=>$c(e,...n)},discover:{list:(...n)=>gs(e,...n),sections:(...n)=>Mc(e,...n),detail:(...n)=>ms(e,...n)}},...Xb(e)}}function e_(e){return{gateway:{logs:t=>cp(e,t),log:t=>lp(e,t),overview:t=>up(e,t),series:t=>pp(e,t),breakdown:t=>dp(e,t),sessions:t=>gp(e,t),errors:t=>mp(e,t),budgets:()=>fp(e),setBudget:t=>yp(e,t),deleteBudget:t=>hp(e,t),keys:()=>bp(e),createKey:t=>_p(e,t),revokeKey:t=>Pp(e,t),routing:{get:()=>sp(e),set:t=>op(e,t),reset:()=>ip(e),preview:t=>ap(e,t)},playground:(t,n,r)=>xp(e,t,n,r)}}}function t_(e){return{modelDefaults:{get:()=>mu(e),set:t=>fu(e,t),clear:t=>yu(e,t)},setDefaultAgent:t=>_u(e,t),sandbox:{list:()=>Yc(e),snapshots:()=>Kc(e),rebuildSnapshot:t=>Bc(e,t),fixWithAgent:()=>qc(e),createTemplate:t=>Gc(e,t),updateTemplate:(...t)=>Wc(e,...t),removeTemplate:t=>Vc(e,t),buildTemplate:t=>Hc(e,t),setProvider:t=>Zi(e,t)},setAgentScope:(...t)=>hu(e,...t)}}function n_(e){return{channels:{slack:{installation:()=>qu(e),connect:t=>Gu(e,t),mode:()=>Wu(e),completeInstall:t=>Vu(e,t),manifest:()=>Yu(e),disconnect:()=>zu(e),getFile:t=>Ju(e,t),uploadFile:t=>Qu(e,t)},teams:{completeInstall:t=>Hu(e,t)},email:{installation:t=>Zu(e,t),mode:()=>ep(e),connect:t=>tp(e,t),disconnect:t=>np(e,t),updatePolicy:(...t)=>rp(e,...t)}},updateFeatureFlag:(...t)=>Qi(e,...t),updateExperimentalFeature:(...t)=>Xi(e,...t),...t_(e)}}async function Tm(e){let t=e?.fetch??v().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??v().backendUrl,r=await t(`${Rt(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new _(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var lE=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function uE(e,t){let n=o=>{let i=lE.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function pE(){return lt()}var r_=null,s_=!1;function dE(e){let t=r_;r_=e,!(s_||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(s_=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function o_(e,t){t?.global!==!1&&dE(e),Gr(e,t);let n=jh(e),{auth:r,accounts:s,iam:o,accountInvites:i}=Ih(),{billing:a,sandboxShares:c}=Rh(),{projects:p,github:d,gitBackend:m,connectStatus:g,marketplace:y}=vh();function h(P){let C=Vb(P);return{...zb(P),...qb(P),...Wb(P),...Zb(P,C),...e_(P),...n_(P),connector:M=>vm(P,M),session:M=>Am(P,M,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:bo(),connector:P=>vm(void 0,P),project:h,session:(P,C)=>Am(P,C,e,n),github:d,gitBackend:m,billing:a,sandboxShares:c,connectStatus:g,marketplace:y,notifications:{registerDeviceToken:Sg,unregisterDeviceToken:wg,list:kg,markRead:Ag,preferences:vg,updatePreferences:Rg,webPushPublicKey:Tg,registerWebPushSubscription:Cg,unregisterWebPushSubscription:Ig},mobileClientPolicy:Tm,validateToken:qi,runtime:pE}}function i_(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function a_(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function gn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function c_(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function l_(e){if(gn(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function u_(e){let t=gn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function p_(e,t){let n=gn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function d_(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function g_(e,t){return gn(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function m_(e,t,n){return gn(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function f_(e,t,n){let r=gn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var Cm={thinking:!1,toolDetails:!0,assistantMetadata:!0};function gE(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function mE(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function fE(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
19
|
+
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
|
|
20
|
+
`))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let _=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(_)||(m.retry=_)}f.length&&(m.data=f.join(`
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*pI(e,t,n){let r=e.eventTransport??wm(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=s=>(o,i)=>uI(e,cI(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:pI(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var V_=200;async function dI(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function Ot(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new S(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function H_(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=_=>e.fetch(new Request(`${t}${_}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new S(`Reading the session transcript failed: ${await dI(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,V_),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,V_),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>Ot(i,"Reading the session status failed")),n.permission.list().then(i=>Ot(i,"Reading permission requests failed")),n.question.list().then(i=>Ot(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{Ot(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){Ot(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Ot(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new S("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Ot(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function z_(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return H_({runtimeUrl:r,rootId:n,fetch:L})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function Y_(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await _u(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var nn=BigInt(4096),Je=BigInt(0xffffffffffff),J_=Je+BigInt(1),gI=J_/BigInt(2),ut=BigInt(3600*1e3)*nn,xo=120*1e3,Q_=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,mI=/^msg_([0-9a-f]{12})/,X_="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Dt(e){let t=mI.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function rn(e){return BigInt(Math.trunc(e))*nn&Je}function jt(e,t){let n=e-t&Je;return n>=gI&&(n-=J_),n}function km(e){let t=null;for(let n of e)n!=null&&(t===null||jt(n,t)>BigInt(0))&&(t=n);return t}function Z_(e,t){let n=Dt(e);return n===null?!1:jt(n,rn(t))>ut}function eb(e,t){let n=t===void 0?null:rn(t);return tb(e,r=>n===null||jt(r,n)<=ut)}function tb(e,t){let n=[];for(let r of e){let s=Dt(r);s!==null&&t(s)&&n.push(s)}return km(n)}function fI(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=X_[n%62])}return e}function vm(e){let t=e.random,n=rn(e.nowMs-(e.backdateMs??xo)),r=e.newestKnownTime??null;if(r!==null){let o=jt(r,n);o>=BigInt(0)&&o<=ut&&(n=r+BigInt(1)&Je)}let s="";if(t)for(let o=0;o<14;o++)s+=X_[Math.min(61,Math.floor(t()*62))];else s=fI();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function So(e={}){let t=e.nowMs??Date.now(),n=rn(t-xo),r=tb(e.after??[],s=>{let o=jt(s,n);return o>=BigInt(0)&&o<=ut});return vm({nowMs:t,newestKnownTime:r}).id}function nb(e){return{scope:()=>yu(e.projectId,e.sessionId),providerSecretPool:{list:()=>_c(e.projectId,e.sessionId),get:t=>hc(e.projectId,e.sessionId,t),set:(t,n)=>bc(e.projectId,e.sessionId,t,n)},rescope:t=>hu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,c=So(),p=await Qn(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new S("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var rb=async function*(e){let t=C().eventStreamTransport;if(!t){yield*wm(((s,o)=>L(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await us(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Qe(){let e=B_();return e||(C().billingEnabled??!1?"":Bh())}async function Am(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Rm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Cm(e){let t=Rm(e),n=await L(`${t}/env`);if(!n.ok)throw new Error(await Am(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Tm(e,t,n){let r=Rm(e),s=await L(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Am(s,"Failed to save secret"))}async function Im(e,t){let n=Rm(e),r=await L(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Am(r,"Failed to delete secret"))}var sb={list:Cm,set:Tm,delete:Im};async function ob(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await L(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function Po(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function Mm(e){let t=mr(e),n=await L(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Po(n,"Failed to list terminals"));return n.json()}async function Om(e,t){let n=mr(e),r=await L(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Po(r,"Failed to create terminal"));return r.json()}async function Dm(e,t,n){let r=mr(e),s=await L(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await Po(s,"Failed to update terminal"));return s.json()}async function jm(e,t){let n=mr(e),r=await L(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Po(r,"Failed to remove terminal"))}async function Lm(e,t,n){let r=mr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Wt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function ib(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var pt="\x1B",ab="\x07",yI="\0",Em=`(?:${ab}|${pt}\\\\)`,hI=[new RegExp(`${pt}\\]697;[^${ab}${pt}]*${Em}`,"g"),new RegExp(`${yI}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${pt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Em}`,"g"),new RegExp(`${pt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Em}`,"g"),new RegExp(`${pt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${pt}\\[\\d+;\\d+R`,"g"),new RegExp(`${pt}\\[\\?[0-9;]*c`,"g")];function cb(e){let t=e;for(let n of hI)t=t.replace(n,"");return t}var lb={list:Mm,create:Om,update:Dm,remove:jm,webSocketUrl:Lm};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await L(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function _I(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/kortix/tasks${r}`)}async function bI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function xI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function SI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function PI(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function wI(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function kI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function vI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function AI(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function RI(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function CI(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function TI(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function II(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function EI(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function MI(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function OI(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function DI(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function jI(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function LI(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function $I(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function UI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function FI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function NI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function BI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function KI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function qI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function GI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function WI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function VI(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function HI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function zI(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function YI(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function JI(e){return M(e,"/kortix/projects")}async function QI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function XI(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function ZI(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function eE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function tE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function nE(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function rE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function sE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function oE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function iE(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function aE(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function cE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function lE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function uE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function pE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function dE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function gE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function mE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var fE=1e4,yE={retryOnAuthError:!1};function sn(e,t,n){return M(e,t,{signal:AbortSignal.timeout(fE),...n},yE)}async function hE(e,t=!1){return(await sn(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function _E(e){return(await sn(e,"/kortix/services/templates")).templates??[]}async function bE(e,t){return(await sn(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function xE(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return sn(e,s,{method:r?"DELETE":"POST"})}async function SE(e,t){return sn(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function PE(e,t){return sn(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Xe=new Map,wE=256,on=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function dt(){let e=Qe();if(!e)throw new on;return Oe(e)}function Oe(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Xe.get(e);if(t)return Xe.delete(e),Xe.set(e,t),t;if(!ts())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:L,eventTransport:rb});return Xe.set(e,n),Xe.size>wE&&Xe.delete(Xe.keys().next().value),n}function kE(e){Xe.delete(e)}function vE(){Xe.clear()}var wo=new Map;function AE(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=wo.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return wo.set(e,n),n}function RE(e){wo.delete(e)}function CE(){wo.clear()}async function TE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function IE(e){let t=Qe();if(!t)throw new S("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await L(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await TE(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new S(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new S(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var ub="frontend";function ko(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${ub}] ${t}`,...n?[n]:[]);try{dt().app.log({service:ub,level:e,message:t,extra:n})}catch{}}var gt={debug:(e,t)=>ko("debug",e,t),info:(e,t)=>ko("info",e,t),warn:(e,t)=>ko("warn",e,t),error:(e,t)=>ko("error",e,t)};function pb(e){return{type:"heartbeat-gap",gapMs:e}}function db(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var EE={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},ME=16,OE=8,DE=6e4,jE=5e3,LE=250,$E=1e3,UE=3e4,FE=5,NE=1e4,BE=4,KE=.5,qE=3e3,GE=3e4,WE=2e4,VE=2e3,HE=8;function zE(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function YE(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function gb(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var fr=new WeakMap;function JE(e,t,n){let r=t.timers??EE,s=t.connectTimeoutMs??WE,o=t.heartbeatTimeoutMs??DE,i=t.maxConsecutiveHardFailures??HE,a=new AbortController;function c(y,...b){for(let R of n){let k=y(R);if(k)try{k(...b)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=!1,g=y=>{p!==y&&(p=y,y&&c(b=>b.onConnectionChange,y))},m=r.now(),f=null,h=[],_,I=0,j=new Map,D=()=>{if(_&&r.clearTimeout(_),_=void 0,h.length===0)return;let y=h;h=[],j.clear(),I=r.now(),m=r.now();for(let b of y)b&&c(R=>R.onEvent,b.event)},w=()=>{if(_)return;let y=r.now()-I;_=r.setTimeout(D,Math.max(0,ME-y))};return(async()=>{let y=0,b=0,R=0;for(;!a.signal.aborted;){let k=!1,x=!1,P,O,v=null,$=r.now(),K=new AbortController;g("connecting");let T=gb(a.signal);T.promise.then(()=>K.abort());try{let re=await new Promise((Ft,St)=>{let me=!1;O=r.setTimeout(()=>{me||(me=!0,gt.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),K.abort(),St(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:K.signal,sseDefaultRetryDelay:qE,sseMaxRetryDelay:GE,sseMaxRetryAttempts:1}).then(Ue=>{me||(me=!0,r.clearTimeout(O),Ft(Ue))},Ue=>{me||(me=!0,r.clearTimeout(O),St(Ue))})}),{stream:bt}=re;if(f){let Ft=r.now()-f.lastActivityAt,St=f.eventful;f=null,(St||Ft>jE)&&c(me=>me.onGapRehydrate,Ft)}m=r.now();let xt=()=>{r.clearTimeout(P),P=r.setTimeout(()=>{gt.warn("SSE heartbeat timeout, forcing reconnect"),K.abort()},o)};xt();let Xr=r.now(),ak=bt[Symbol.asyncIterator]();for(;!K.signal.aborted;){let Ft=ak.next().then(Fe=>({kind:"next",result:Fe}),Fe=>({kind:"error",error:Fe})),St=gb(K.signal),me=await Promise.race([Ft,St.promise.then(()=>({kind:"aborted"}))]);if(St.cleanup(),me.kind==="aborted")break;if(me.kind==="error")throw me.error;if(me.result.done)break;g("open"),xt();let Ue=me.result.value,Nt=Ue&&typeof Ue=="object"&&"payload"in Ue?Ue.payload:Ue;if(!Nt?.type)continue;Nt.type!=="server.connected"&&(k=!0);let fi=YE(h[h.length-1]?.event,Nt);if(fi)h[h.length-1]={type:fi.type,event:fi};else{let Fe=zE(Nt);if(Fe){let Hy=j.get(Fe);Hy!==void 0&&(h[Hy]=void 0),j.set(Fe,h.length)}h.push({type:Nt.type,event:Nt})}w(),!(r.now()-Xr<OE)&&(await new Promise(Fe=>r.setTimeout(Fe,0)),Xr=r.now())}x=k}catch(re){if(a.signal.aborted)break;v=re;let bt=String(re),xt=Bt(re)||Bt(re?.cause);if(gt.error("SSE event stream error",{error:bt,retryCount:y,isAuthError:xt}),xt)try{hs(),await ys(),gt.info("SSE: refreshed auth token after auth error")}catch(Xr){gt.error("SSE: failed to refresh auth token",{error:String(Xr)})}}finally{r.clearTimeout(P),r.clearTimeout(O),K.abort(),T.cleanup(),D()}if(a.signal.aborted)break;let q=r.now()-$,G=v?.cause?.status;if(b=!k&&(typeof G=="number"&&G>=400||q<VE)?b+1:0,b>=i){gt.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:b,lastError:String(v)}),p=null,d=!0,c(re=>re.onParked,{consecutiveFailures:b,lastError:v});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||k},R=x&&q<NE?R+1:0;let Le=x&&R<=BE;Le?y=0:(y++,y>1&>.warn("SSE event stream reconnecting",{retryCount:y}));let Mn=Le?LE:Math.min($E*2**Math.min(y-1,FE),UE),$e=Math.round(Mn*(1+KE*(r.random?.()??0)));await new Promise(re=>{let bt=r.setTimeout(re,$e),xt=()=>{r.clearTimeout(bt),re()};a.signal.addEventListener("abort",xt,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_&&r.clearTimeout(_)}}}function vo(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Oe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},c=fr.get(i);if(c?.isParked()&&(fr.delete(i),c=void 0),!c)c=JE(i,e,new Set([a])),fr.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function mb(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Oe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return vo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function _b(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function ln(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function oe(e){let t=(e??Qe()).trim();if(!t)throw new on;return t}async function Ro(e,t){let n=await L(`${oe(t)}${e}`);if(!n.ok)throw new S(await ln(n),{status:n.status,response:n});return n.json()}var Co=["/workspace","/tmp","/home","/opt"],QE=Co.filter(e=>e!=="/workspace");function Fm(e){return Co.some(t=>e===t||e.startsWith(`${t}/`))}function un(e){return Fm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function mt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(QE.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Nm=mt;async function pn(e,t){let n=oe(t),r=mt(e)||".";return(await Ro(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function dn(e,t){let n=oe(t),r=mt(e),s=await L(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new S(await ln(s),{status:s.status,response:s});return s.json()}async function XE(e,t,n){let r=oe(n),s=mt(e),o=await L(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new S(await ln(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new S("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var ZE=8,Ao=0,bb=[];async function eM(){if(Ao<ZE){Ao++;return}await new Promise(e=>bb.push(e)),Ao++}function tM(){Ao--,bb.shift()?.()}function xb(e,t){let n=oe(t);return Kn(`${n}/file/raw?path=${encodeURIComponent(mt(e))}`)}async function gn(e,t){await eM();try{let n=oe(t);try{return await XE(e,void 0,n)}catch{}let r=await dn(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{tM()}}async function _r(e){return Ro("/file/status",oe(e))}async function br(e,t,n){let r=oe(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),Ro(`/find/file?${s.toString()}`,r)}async function xr(e,t){let n=oe(t);return(await Ro(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var yr=[400,1200],nM=e=>e===408||e===429||e===502||e===503||e===504,fb=e=>new Promise(t=>setTimeout(t,e));function rM(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var $m=3e4,Sb=15*6e4,sM=256;function an(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return $m;let t=$m+e/sM;return Math.min(Sb,Math.max($m,Math.round(t)))}async function oM(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let s=0;s<=yr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,rM(a)||s===yr.length)break;await fb(yr[s]);continue}if(o.ok)return o.json();let i=await oM(o);if(n=new S(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!nM(o.status)||s===yr.length)throw n;await fb(yr[s])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Um=8*1024*1024;function iM(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new S(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function yb(e,t){try{e?.onProgress?.(t)}catch{}}function hb(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function aM(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function mn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=oe(o),c=an(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Um){let f=await hr(()=>hb(e,t,p),h=>L(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return iM(f[0],e.size),yb(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await hr(()=>hb(new Blob([],{type:e.type}),t,p),f=>L(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:an(0)})))[0]?.path;if(!g)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=aM(g);if(!m.name)throw new S(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=Um){let h=Math.min(e.size,f+Um),_=e.slice(f,h,e.type),I=await hr(()=>{let j=new FormData;return m.parent&&j.append("path",m.parent),j.append("filename",m.name),j.append("first",f===0?"true":"false"),j.append("offset",String(f)),j.append("file",_,m.name),j},j=>L(`${a}/file/append`,{method:"POST",body:j},{timeoutMs:an(_.size)}));if(I.path!==g||I.size!==h)throw new S(`Upload verification failed for ${g}: expected ${h} bytes, received ${I.size}`,{code:"UPLOAD_SIZE_MISMATCH"});yb(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await Lt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Pb(e,t,n){let r=oe(n);return hr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>L(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:cM}))}var cM=Sb;function lM(e,t,n){let r=oe(n),s=an(t.size);return hr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>L(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var cn=class extends S{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Sr(e,t){let n=oe(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=un(`${a}/${i}`),p=[];try{p=await pn(wb(c),n)}catch(g){if(!(g instanceof S&&g.status===404))throw g}if(p.some(g=>g.name===kb(c)))throw new cn(c);let d=await vb(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function Pr(e,t,n){let r=oe(n);return lM(t,await gn(e,r),r)}function uM(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function wb(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function kb(e){return e.slice(e.lastIndexOf("/")+1)}function pM(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function wr(e,t,n){let r=oe(n),s=un(uM(e.trim()));return vb(s,t,r,{overwrite:!0})}async function vb(e,t,n,r){let s=kb(e);if(!s)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=wb(e);await fn(o,n).catch(()=>{});let i=pM(),a=await mn(t,o,`.${s}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new S(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=un(c);try{await Ab(p,e,n,r.overwrite)}catch(g){throw await Lt(p,n).catch(()=>{}),!r.overwrite&&g instanceof S&&g.status===409?new cn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Lt(e,t){let n=await L(`${oe(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Delete failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function fn(e,t){let n=await L(`${oe(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Mkdir failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function kr(e,t,n){return Ab(e,t,oe(n),!0)}async function Ab(e,t,n,r){let s=await L(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!s.ok)throw new S(`Rename failed (${s.status}): ${await ln(s)}`,{status:s.status,response:s});return s.json()}async function Bm(){return _b(await dt().project.current())}async function To(){return _b(await dt().global.health())}async function Km(){try{return(await To()).healthy===!0}catch{return!1}}var Rb={list:pn,read:dn,readBlob:gn,status:_r,findFiles:br,findText:xr,upload:mn,write:wr,create:Sr,copy:Pr,remove:Lt,mkdir:fn,rename:kr,currentProject:Bm,health:To,isReachable:Km,toDaemonPath:mt,toSandboxAbsolutePath:un,toWorkspaceRelative:Nm};function Cb(e){return{list:async t=>pn(t,(await e()).runtimeUrl),read:async t=>dn(t,(await e()).runtimeUrl),readBlob:async t=>gn(t,(await e()).runtimeUrl),status:async()=>_r((await e()).runtimeUrl),findFiles:async(t,n)=>br(t,n,(await e()).runtimeUrl),findText:async t=>xr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>mn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>wr(t,n,(await e()).runtimeUrl),create:async t=>Sr(t,(await e()).runtimeUrl),copy:async(t,n)=>Pr(t,n,(await e()).runtimeUrl),remove:async t=>Lt(t,(await e()).runtimeUrl),mkdir:async t=>fn(t,(await e()).runtimeUrl),rename:async(t,n)=>kr(t,n,(await e()).runtimeUrl)}}function Tb(e){return{get:t=>zn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>nr(e.sessionId,{projectId:e.projectId}),update:t=>lu(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),uu(e.projectId,e.sessionId)),restore:()=>du(e.projectId,e.sessionId),recover:()=>pu(e.projectId,e.sessionId),start:(...t)=>ot(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Eu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Xn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Zn(e.projectId,e.sessionId)),configState:()=>gu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),mu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),fu(e.projectId,e.sessionId,...t)),setSharing:t=>Kl(e.projectId,e.sessionId,t),previews:()=>zl(e.projectId,e.sessionId),participants:()=>ql(e.projectId,e.sessionId),watch:()=>Gl(e.projectId,e.sessionId),setWatch:t=>Wl(e.projectId,e.sessionId,t),setPinned:t=>Vl(e.projectId,e.sessionId,t),setArchived:t=>Hl(e.projectId,e.sessionId,t),commit:t=>jl(e.projectId,e.sessionId,t),publicShares:{list:()=>Yl(e.projectId,e.sessionId),create:(...t)=>Jl(e.projectId,e.sessionId,...t),revoke:(...t)=>Ql(e.projectId,e.sessionId,...t)}}}function Ib(e){return{reminders:{list:()=>Md(e.projectId,e.sessionId),create:t=>Od(e.projectId,e.sessionId,t),update:(t,n)=>Bs(e.projectId,e.sessionId,t,n),remove:t=>Ks(e.projectId,e.sessionId,t)},audit:(t,n)=>eu(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>fm(e.projectId,e.sessionId,t,n),read:(t,n)=>ym(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>tu(e.projectId,e.sessionId,t),messageAuthors:()=>bu(e.projectId,e.sessionId),modelUsage:()=>xu(e.projectId,e.sessionId),transcriptSync:t=>Yn(e.projectId,e.sessionId,t),log:t=>nu(e.projectId,e.sessionId,t),turn:()=>Jn(e.projectId,e.sessionId),prompts:{create:t=>Qn(e.projectId,e.sessionId,t),list:()=>ru(e.projectId,e.sessionId),remove:t=>su(e.projectId,e.sessionId,t),retry:t=>au(e.projectId,e.sessionId,t),edit:(t,n)=>ou(e.projectId,e.sessionId,t,n),interrupt:t=>iu(e.projectId,e.sessionId,t),hold:t=>cu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Eb(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var gM=["control_plane","provider_ingress","daemon","upstream_port"];function qm(e){return typeof e=="string"&&gM.includes(e)?e:null}function Gm(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function Wm(e,t){let n=(e===void 0?Qe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await L(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=qm(r.headers.get("X-Kortix-Proxy-Hop"))??qm(o?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var Mb=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Ob=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Db=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,jb=new Set([22,4096,parseInt(Ye.KORTIX_MASTER,10)]);function mM(e){return Ob.test(e)}function Io(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function fM(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var yM=new Set(["'",'"',"`","<","(","["]),hM=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function _M(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&yM.has(e[t]);)t++;for(;n>t&&hM.has(e[n-1]);)n--;return e.slice(t,n)}function bM(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var xM=/^\/proxy\/(\d{1,5})(\/.*)?$/,SM=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function Lb(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:SM.test(t.pathname)}catch{return!1}}function Ar(e){if(!e)return null;let t=_M(fM(e.trim())),n=Hm(t);if(n){let r=Io(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ye.KORTIX_MASTER,10);if(s===i){let c=r.pathname.match(xM);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=Io(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Io(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=bM(e);return r&&r!==e?Ar(r):null}}function PM(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function wM(e,t){return t.some(([n,r])=>e>=n&&e<r)}function $b(e){let t=[],n=new Set,r=PM(e);Mb.lastIndex=0;let s;for(;(s=Mb.exec(e))!==null;){let o=Ar(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||jb.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:wM(s.index,r)}))}return t}function kM(e){return $b(e).length>0}function vM(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Ub(e){return e.trim().toLowerCase().split("_").join("-")}function Fb(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function AM(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(Ub(n.sandboxId));return`${Fb(s)}${t}`}function Nb(e){return e.sandboxId.trim().length>0}function ft(e,t,n){let r=Io(t);if(!Nb(n))return Gb(e,r);let s=AM(e,r,n);return s||(vM(n.apiBaseUrl)?`http://p${e}-${Ub(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${Fb(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function RM(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return ft(3211,`/open?path=/workspace/${r}`,t)}function Bb(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function CM(e){return`http://localhost:3211${Bb(e)}`}function Kb(){return"/health"}function TM(e){return ft(3211,Kb(),e)}function IM(e,t){return ft(e,"/",t)}function qb(e){let t=Ar(e);return!(!t||jb.has(t.port)||Lb(e))}function Vm(e,t){if(!e)return e;let n=Ar(e);return n?qb(n.originalUrl)?ft(n.port,n.path,t):n.originalUrl:e}function Gb(e,t="/"){return`http://localhost:${e}${t}`}var Wb=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Hm(e){let t=e.match(Ob);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(Db);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(Wb);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function EM(e){try{let t=Hm(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function MM(e){return mM(e)||Db.test(e)||Wb.test(e)}function OM(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var vr="/web-proxy/";function DM(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${vr}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Ye.KORTIX_MASTER,10);return`${ft(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function jM(e){try{let t=new URL(e),n=t.pathname.indexOf(vr);if(n===-1)return null;let s=t.pathname.slice(n+vr.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function LM(e){try{return new URL(e).pathname.includes(vr)}catch{return e.includes(vr)}}function $M(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function UM(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function Vb(e){return{health:t=>Wm(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>ft(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Vm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ee(e.requireReady("sandboxPortUrl").sandboxId,t)}}function zm(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=N_(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=G_(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Tb(m),...Ib(m),...Vb(m),...Y_(m),...nb(m),...mb(m),files:Cb(c),...z_(m),get runtime(){return Oe(d("runtime").runtimeUrl)}}}function Hb(e){return{apps:{list:()=>lg(e),create:t=>ug(e,t),get:t=>qs(e,t),update:(...t)=>pg(e,...t),access:{get:(...t)=>fg(e,...t),update:(...t)=>hg(e,...t),session:(...t)=>_g(e,...t),agents:t=>yg(e,t)},remove:t=>dg(e,t),token:t=>gg(e,t),authEnv:t=>mg(e,t),artifacts:{register:t=>Gs(e,t),uploadArchive:(...t)=>bg(e,...t),finalize:(...t)=>Ws(e,...t)},deployments:{create:(...t)=>xg(e,...t),list:t=>Sg(e,t),get:(...t)=>Pg(e,...t),logs:(...t)=>wg(e,...t),remove:(...t)=>Ag(e,...t)},start:t=>kg(e,t),stop:t=>vg(e,t),rollback:(...t)=>Rg(e,...t),machines:{list:t=>Cg(e,t),start:(t,n)=>Ig(e,t,n),stop:(t,n)=>Eg(e,t,n),restart:(t,n)=>Mg(e,t,n),destroy:(t,n)=>Og(e,t,n)},scale:(...t)=>Dg(e,...t),exec:(...t)=>jg(e,...t),volumes:{list:t=>Lg(e,t),create:(...t)=>$g(e,...t),update:(...t)=>Ug(e,...t),destroy:(...t)=>Fg(e,...t),snapshots:(...t)=>Ng(e,...t),snapshot:(...t)=>Bg(e,...t),restore:(...t)=>Kg(e,...t),fork:(...t)=>qg(e,...t)}}}}function zb(e){return{list:()=>ja(e),invite:(...t)=>Ua(e,...t),update:(...t)=>La(e,...t),revoke:t=>$a(e,t),pendingInvites:()=>Fa(e),resendInvite:(...t)=>Ba(e,...t),revokeInvite:(...t)=>Na(e,...t),requests:()=>Ma(e),approveRequest:(...t)=>Oa(e,...t),rejectRequest:(...t)=>Da(e,...t),groupGrants:()=>Ka(e),attachGroupGrant:(...t)=>qa(e,...t),updateGroupGrant:(...t)=>Ga(e,...t),detachGroupGrant:t=>Wa(e,t),resourceGrants:{list:()=>Va(e),create:t=>Ha(e,t),remove:t=>za(e,t)}}}function Yb(e){return{tokens:{list:()=>Kd(e),create:t=>qd(e,t),revoke:t=>Gd(e,t)},setupLinks:{requestSecret:t=>Zd(e,t),requestConnector:t=>eg(e,t)},validateManifest:t=>la(e,t),gitToken:()=>ua(e),agentIdentities:()=>sd(e),secrets:{list:()=>Xa(e),upsert:t=>Za(e,t),setStrategy:(...t)=>ec(e,...t),broker:(...t)=>tc(e,...t),remove:t=>oc(e,t),setPersonal:(...t)=>ic(e,...t),removePersonal:t=>ac(e,t),setGitCredential:t=>sc(e,t),listProviderOAuth:()=>nc(e),startProviderOAuth:(...t)=>ms(e,...t),pollProviderOAuth:(...t)=>fs(e,...t),removeProviderOAuth:t=>rc(e,t)},access:zb(e)}}function Jb(e){return{list:()=>Sc(e),listAll:()=>Pc(e),reconcile:(...t)=>wc(e,...t),reconcileMember:(...t)=>kc(e,...t),updateCredential:(...t)=>vc(e,...t),revoke:(...t)=>Ac(e,...t),activate:(...t)=>Rc(e,...t),setDefault:(...t)=>Cc(e,...t),rename:(...t)=>Tc(e,...t),share:(...t)=>Ec(e,...t),addComputer:(...t)=>Ic(e,...t),pipedreamConnect:(...t)=>Mc(e,...t),pipedreamFinalize:(...t)=>Oc(e,...t)}}function Eo(e){return{catalog:t=>Vt(e,t),tools:()=>bs(e),search:(...t)=>xc(e,...t),describe:(...t)=>xs(e,...t),call:(...t)=>Rt(e,...t),callAction:(t,n,r,s)=>Rt(e,`${t}.${n}`,r,s),accounts:(...t)=>Ss(e,...t),uploadAttachment:(...t)=>Ps(e,...t)}}function Ym(e,t){return{slug:t,run:(r,s,o)=>Rs(e,t,r,s,o),call:(r,s,o)=>Rt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?xs(e,`${t}.${r}`):(await Vt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>Ss(e,t),paginate:(r,s,o)=>el(e,t,r,s,o),uploadAttachment:(r,s)=>Ps(e,r,{...s,connector:t})}}var FM=100,Qb=0,NM=new Set(["attachment_size_mismatch","attachment_failed"]),Xb=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Jm(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function Qm(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,b){y.removalDeleted||(y.removalDeleted=!0,Ht(e,b).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:R})=>R);(y.length!==p.attachments.length||y.some((R,k)=>R!==p.attachments[k]))&&(p={attachments:y});let b=Math.min(...y.filter(R=>R.status==="ready").map(R=>Date.parse(R.attachment.expires_at)));Number.isFinite(b)&&!a&&(c=setTimeout(()=>{for(let R of d())R.item.status==="ready"&&Date.parse(R.item.attachment.expires_at)<=Date.now()&&(R.item={...R.item,status:"error",error:Xb()});m()},Math.min(2147483647,Math.max(0,b-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let R of s)R();for(let R of[...o])R()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let b=d();if(b.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(b.reduce((k,x)=>k+x.item.size,0)+y.reduce((k,x)=>k+x,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function _(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let b=y.item.file;i++;let R=++y.generation,k=new AbortController;y.abort=k,y.item={...y.item,status:"uploading",error:void 0};let x=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===R,P,O=0,v,$=()=>{v=void 0,!(!x()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,O=Date.now(),m())},K=T=>Math.floor(T*100/y.item.size);Wn(e,b,{resume:y.upload,signal:k.signal,onUpload:T=>{y.upload=T,y.removed&&(k.abort(),g(y,T.attachment_id))},onProgress:T=>{if(!x()||K(T)===K(y.item.receivedBytes)||(P=T,v))return;let q=O+FM-Date.now();if(q<=0)return $();v=setTimeout($,q),typeof v=="object"&&"unref"in v&&v.unref()},onProcessing:()=>{v&&clearTimeout(v),v=void 0,P=void 0,x()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(T=>{x()&&(y.item={...y.item,status:"ready",attachment:Jm(T),receivedBytes:T.size})}).catch(T=>{T instanceof S&&NM.has(T.code??"")&&(y.upload=void 0),x()&&(y.item={...y.item,status:T instanceof S&&T.code==="ABORTED"?"aborted":"error",error:T instanceof Error?T:new Error(String(T))})}).finally(()=>{i--,v&&clearTimeout(v),y.abort===k&&(y.abort=void 0),m(),_()})}m()}function I(y){h(y.map(R=>R.size));let b=y.map(R=>{let k=`attachment-${++Qb}`;return r.set(k,{generation:0,item:{id:k,file:R,filename:R.name,mime:R.type||"application/octet-stream",size:R.size,status:"pending",receivedBytes:0}}),k});return m(),_(),b}function j(y){let b=y.map(({attachment:k,file:x})=>{try{return{attachment:Jm(k),file:x}}catch{return}});h(b.flatMap(k=>k?[k.attachment.size]:[]));let R=b.map(k=>{if(!k)return;let x=`attachment-${++Qb}`,{attachment:P,file:O}=k;return r.set(x,{generation:0,item:{id:x,...O?{file:O}:{},filename:P.filename,mime:P.mime,size:P.size,status:"ready",receivedBytes:P.size,attachment:P}}),x});return m(),R}function D(y){let b=r.get(y);!b||b.item.status==="ready"||(b.generation++,b.abort?.abort(),b.item={...b.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function w(y,{signal:b}={}){let R=[...y];return new Promise((k,x)=>{let P=()=>{o.delete($),b?.removeEventListener("abort",v)},O=K=>{P(),x(K)},v=()=>O(Re()),$=()=>{let K=!1;for(let q of R){let G=r.get(q);if(!G)return O(new Error("Attachment was removed before it was sent"));if(a&&!G.handedOff)return O(new Error("Attachment controller is disposed"));if(G.item.status==="error"||G.item.status==="aborted")return O(G.item.error??new Error("Attachment upload failed"));G.item.status!=="ready"&&(K=!0)}if(K)return;let T;try{T=R.map(q=>{let G=Jm(r.get(q).item.attachment);return{type:"file",attachment_id:G.attachment_id,filename:G.filename,mime:G.mime}})}catch(q){return O(q instanceof Error?q:new Error(String(q)))}P(),k(T)};if(b?.aborted)return v();o.add($),b?.addEventListener("abort",v,{once:!0}),$()})}return{add:y=>I([y])[0],addMany:I,restore:j,retry(y){let b=r.get(y);if(b?.handedOff||f(),!(!b||b.item.status==="ready"||b.item.status==="uploading"||b.item.status==="processing"||b.item.status==="pending")){if(!b.item.file||b.upload&&Date.parse(b.upload.expires_at)<=Date.now())throw Xb();b.item={...b.item,status:"pending",error:void 0},_()}},async remove(y){let b=r.get(y);if(!b)return;b.removed=!0,b.generation++,r.delete(y);let R=b.upload?.attachment_id??b.item.attachment?.attachment_id;R&&b.abort?.abort(),m(),_(),R&&g(b,R)},abort:D,submit(y){if(!a){for(let b of y){let R=r.get(b);R&&(R.handedOff=!0)}m()}},reclaim(y){if(!a){for(let b of y){let R=r.get(b);R&&(R.handedOff=!1)}m()}},whenReady:w,forget(y=d().map(b=>b.item.id)){for(let b of y){let R=r.get(b);R&&(R.generation++,R.abort?.abort(),r.delete(b))}m(),_()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let b=y.upload?.attachment_id??y.item.attachment?.attachment_id;b&&e&&Ht(e,b).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function Zb(e){return{attachments:{upload:(...t)=>Wn(e,...t),delete:(...t)=>Ht(e,...t),createController:t=>Qm(e,t)},get:t=>At(e,t),detail:()=>jn(e),skills:{create:(...t)=>_a(e,...t)},audit:t=>Hd(e,t),update:t=>Un(e,t),archive:()=>Fn(e),llmCatalog:()=>Ln(e),modelPicker:()=>$n(e),modelAccess:()=>rr(e),setModelAccess:t=>sr(e,t),sandboxHealth:()=>Bn(e),onboardingComplete:(...t)=>ha(e,...t)}}function ex(e){return{sessions:{list:t=>Tt(e,t),listPage:t=>Bl(e,t),create:t=>It(e,t),ensureWarm:()=>Xl(e),claimWarm:t=>Zl(e,t)},review:{list:t=>wd(e,t),summary:()=>kd(e),get:t=>vd(e,t),submit:t=>Ad(e,t),act:(...t)=>Rd(e,...t),bulkAct:t=>Cd(e,t)},approvals:{list:t=>Ya(e,t),resolve:(...t)=>Qa(e,...t),sessionsNeedingInput:t=>Ja(e,t)}}}function tx(e){return{files:{list:t=>dl(e,t),listDirectory:t=>gl(e,t),read:(t,n)=>fl(e,t,n),search:(...t)=>ml(e,...t),archive:(...t)=>yl(e,...t),archiveRequest:(...t)=>hl(e,...t),history:(...t)=>kl(e,...t)},git:{commits:()=>Sl(e),commit:t=>Pl(e,t),commitDiff:t=>wl(e,t),branches:()=>xl(e),versionDiff:(...t)=>vl(e,...t),inviteCollaborator:(...t)=>ca(e,...t)},changeRequests:{list:(...t)=>Al(e,...t),get:t=>Rl(e,t),update:(...t)=>Ll(e,...t),diff:t=>Cl(e,t),mergePreview:t=>Tl(e,t),open:(...t)=>Il(e,...t),merge:(...t)=>El(e,...t),close:(...t)=>Ml(e,...t),reopen:(...t)=>Ol(e,...t),requestChanges:(...t)=>Dl(e,...t)},...ex(e)}}function nx(e){return{policies:{list:()=>tl(e),set:(...t)=>nl(e,...t)},reminders:{list:()=>Ld(e),updateMany:(...t)=>Dd(e,...t),removeMany:(...t)=>jd(e,...t)},triggers:{list:()=>Su(e),eventApps:()=>Cu(e),eventTypes:(...t)=>Ru(e,...t),create:(...t)=>Pu(e,...t),update:(...t)=>wu(e,...t),remove:(...t)=>ku(e,...t),fire:(...t)=>Au(e,...t),setActivation:(...t)=>vu(e,...t)},...tx(e)}}function rx(e,t){return{connectors:{...Eo(e),list:()=>Dc(e),config:(...n)=>Bc(e,...n),create:(...n)=>Gc(e,...n),remove:(...n)=>Vc(e,...n),sync:()=>jc(e),auth:{discover:(...n)=>Wc(e,...n)},setName:(...n)=>Kc(e,...n),setCredentialMode:(...n)=>Lc(e,...n),setAuthorizationStrategy:(...n)=>$c(e,...n),setCredential:(...n)=>Qc(e,...n),deleteCredential:(...n)=>Xc(e,...n),setSensitive:(...n)=>Uc(e,...n),connections:t,policies:{get:(...n)=>Fc(e,...n),set:(...n)=>Nc(e,...n)},pipedream:{listApps:(...n)=>Hc(e,...n),listSections:(...n)=>zc(e,...n),connect:(...n)=>qc(e,...n),finalize:(...n)=>Zc(e,...n)},discover:{list:(...n)=>ws(e,...n),sections:(...n)=>Yc(e,...n),detail:(...n)=>ks(e,...n)}},...nx(e)}}function sx(e){return{gateway:{logs:t=>Ip(e,t),log:t=>Ep(e,t),overview:t=>Mp(e,t),series:t=>Op(e,t),breakdown:t=>Dp(e,t),sessions:t=>jp(e,t),errors:t=>Lp(e,t),budgets:()=>$p(e),setBudget:t=>Up(e,t),deleteBudget:t=>Fp(e,t),keys:()=>Np(e),createKey:t=>Bp(e,t),revokeKey:t=>Kp(e,t),routing:{get:()=>Ap(e),set:t=>Rp(e,t),reset:()=>Cp(e),preview:t=>Tp(e,t)},playground:(t,n,r)=>qp(e,t,n,r)}}}function ox(e){return{modelDefaults:{get:()=>Mu(e),set:t=>Ou(e,t),clear:t=>Du(e,t)},setDefaultAgent:t=>$u(e,t),sandbox:{list:()=>pl(e),snapshots:()=>sl(e),rebuildSnapshot:t=>ol(e,t),fixWithAgent:()=>il(e),createTemplate:t=>al(e,t),updateTemplate:(...t)=>cl(e,...t),removeTemplate:t=>ll(e,t),buildTemplate:t=>ul(e,t),setProvider:t=>ya(e,t)},setAgentScope:(...t)=>ju(e,...t)}}function ix(e){return{channels:{slack:{installation:()=>pp(e),connect:t=>dp(e,t),mode:()=>gp(e),completeInstall:t=>mp(e,t),manifest:()=>yp(e),disconnect:()=>hp(e),getFile:t=>_p(e,t),uploadFile:t=>bp(e,t)},teams:{completeInstall:t=>fp(e,t)},email:{installation:t=>Sp(e,t),mode:()=>Pp(e),connect:t=>wp(e,t),disconnect:t=>kp(e,t),updatePolicy:(...t)=>vp(e,...t)}},updateFeatureFlag:(...t)=>ma(e,...t),updateExperimentalFeature:(...t)=>fa(e,...t),...ox(e)}}var BM=["screen","actions","audio"],KM=["password_managers","messaging","banking"],qM={localHours:8760,remoteDays:3650},GM=[500,1e3,2e3,5e3,1e4],WM=[720,1080,1440,2160],VM={intervalMs:2e3,maxHeight:1440},HM=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function zM(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),HM.test(n)?n:null}function YM(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||/\s/.test(t)&&!t.toLowerCase().endsWith(".exe")?null:t}function JM(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Z=e=>`/accounts/${e}/capture`;function Ze(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var ax=e=>Ze({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Xm=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function Zm(e,t={}){return u(await l.get(`${Z(e)}/devices${Ze({user_id:t.userId,scope:t.scope})}`))}async function ef(e,t){return u(await l.delete(`${Z(e)}/devices/${t}`))}async function tf(e,t,n){return u(await l.put(`${Z(e)}/devices/${t}/link`,{user_id:n}))}async function nf(e){return u(await l.get(`${Z(e)}/enrollment-tokens`))}async function rf(e,t){return u(await l.post(`${Z(e)}/enrollment-tokens`,t))}async function sf(e,t){return u(await l.delete(`${Z(e)}/enrollment-tokens/${t}`))}async function of(e,t={}){return u(await l.get(`${Z(e)}/enrollments${Ze({status:t.status})}`))}async function af(e,t,n){return u(await l.post(`${Z(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function cf(e,t){return u(await l.post(`${Z(e)}/enrollments/${t}/deny`,{}))}async function lf(e){return u(await l.get(`${Z(e)}/policy`))}async function uf(e,t){return u(await l.put(`${Z(e)}/policy`,{policy:t}))}async function pf(e,t={}){return u(await l.get(`${Z(e)}/timeline${Ze(Xm(t))}`))}async function df(e,t={}){return u(await l.get(`${Z(e)}/timeline/items${Ze(Xm(t))}`))}async function gf(e,t={}){return u(await l.get(`${Z(e)}/days${Ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function mf(e,t){return u(await l.get(`${Z(e)}/search${ax(t)}`))}async function ff(e,t,n={}){return u(await l.get(`${Z(e)}/frames/${t}${Ze({user_id:n.userId})}`))}async function yf(e,t,n={}){return u(await l.get(`${Z(e)}/chunks/${t}/media${Ze({user_id:n.userId})}`))}async function hf(e,t,n){return u(await l.get(`${Z(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function _f(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function bf(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function xf(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Sf(e){return u(await l.get(Z(e)))}async function Pf(e,t){return u(await l.patch(Z(e),{enabled:t}))}async function wf(e){return u(await l.get(`/capture/me/search${ax(e)}`))}async function kf(e={}){return u(await l.get(`/capture/me/timeline${Ze(Xm(e))}`))}async function vf(e){return u(await l.get(`/capture/me/frames/${e}`))}function XM(e){return{workspace:{get:()=>Sf(e),setEnabled:t=>Pf(e,t)},devices:{list:t=>Zm(e,t),revoke:t=>ef(e,t),link:(t,n)=>tf(e,t,n),assetUrl:(t,n)=>hf(e,t,n)},enrollment:{tokens:{list:()=>nf(e),create:t=>rf(e,t),revoke:t=>sf(e,t)},list:t=>of(e,t),approve:(t,n)=>af(e,t,n),deny:t=>cf(e,t)},policy:{get:()=>lf(e),set:t=>uf(e,t)},timeline:{get:t=>pf(e,t),items:t=>df(e,t),days:t=>gf(e,t)},search:t=>mf(e,t),frame:(t,n)=>ff(e,t,n),media:(t,n)=>yf(e,t,n)}}var cx={account:e=>XM(e),deviceGrant:_f,approveDevice:bf,denyDevice:xf,me:{search:wf,timeline:kf,frame:vf}};async function Af(e){let t=e?.fetch??C().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??C().backendUrl,r=await t(`${Et(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new S(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var ZM=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function eO(e,t){let n=o=>{let i=ZM.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function tO(){return dt()}var lx=null,ux=!1;function nO(e){let t=lx;lx=e,!(ux||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(ux=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function px(e,t){t?.global!==!1&&nO(e),es(e,t);let n=F_(e),{auth:r,accounts:s,iam:o,accountInvites:i}=D_(),{billing:a,sandboxShares:c}=E_(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=I_();function h(_){let I=Jb(_);return{...Zb(_),...Hb(_),...Yb(_),...rx(_,I),...sx(_),...ix(_),connector:j=>Ym(_,j),session:j=>zm(_,j,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:Eo(),connector:_=>Ym(void 0,_),project:h,session:(_,I)=>zm(_,I,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,capture:cx,notifications:{registerDeviceToken:Wg,unregisterDeviceToken:Vg,list:Hg,markRead:zg,preferences:Yg,updatePreferences:Jg,webPushPublicKey:Qg,registerWebPushSubscription:Xg,unregisterWebPushSubscription:Zg},mobileClientPolicy:Af,validateToken:ia,runtime:tO}}function dx(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function gx(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function yn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function mx(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function fx(e){if(yn(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function yx(e){let t=yn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function hx(e,t){let n=yn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function _x(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function bx(e,t){return yn(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function xx(e,t,n){return yn(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function Sx(e,t,n){let r=yn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var Rf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function rO(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function sO(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function oO(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${s}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function iO(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?rO(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=sO(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function aO(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=iO(e,n.assistantMetadata);for(let s of t)r+=oO(s,n);return r}function Px(e,t,n=Rf){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,30 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let s of t)r+=
|
|
70
|
+
`;for(let s of t)r+=aO(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function wx(e,t){return`session-${e}.md`}var Cf="An error occurred";var cO=["message","error","detail","error_description","msg","errors","data"];function Tf(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function hn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function lO(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=hn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function uO(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=pO(e,t);if(n)return n;let r=gO(e,t);return r?r.slice(0,200):void 0}function Rx(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function kx(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function pO(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!Rx(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var dO=["script","style"];function gO(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=dO.find(i=>t.startsWith(`<${i}`,s)&&Rx(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:kx(e,i);continue}r=kx(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function mO(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function fO(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function vx(e,t,n){if(typeof e=="string")return Mo(e,t,n);if(e&&typeof e=="object")return Oo(e,t,n)}function Mo(e,t,n=new WeakSet){let r=Tf(e);if(!r)return;if(t>=4)return r;let s=mO(r);if(s)return s;let o=hn(r);if(o!==void 0)return typeof o=="string"?Mo(o,t+1,n):o&&typeof o=="object"?Oo(o,t+1,n):String(o);let i=Cx(r);if(i){let a=hn(i);if(a&&typeof a=="object"){let c=Oo(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=lO(r);if(a)return Mo(a,t+1,n)??a}return uO(r)??r}function Oo(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=vx(i,t,n);if(a)return a}return}let r=e;for(let i of cO){let a=vx(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return fO(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function _e(e){return e?typeof e=="string"?Mo(e,0)??Cf:typeof e=="object"?Oo(e,0)??Cf:String(e):Cf}function Rr(e){let t=yO(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||Tf(t)===n))return t}function yO(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function
|
|
75
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Cx(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function hO(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function _O(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function Ax(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=_O(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||hO(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function we(e){if(e==null)return;if(typeof e=="string"){let a=Tf(e),c=hn(a)??hn(Cx(a));return c!==void 0?we(c):void 0}if(typeof e!="object")return;let t=e,n=Ax(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Ax(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=hn(o.responseBody);if(a!==void 0){let c=we(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=we(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=we(a);if(c)return c}}return n}var Tx={};function z(e,t){for(let n of t)Tx[n]=e}z("read",["read"]);z("list",["list","ls"]);z("glob",["glob"]);z("grep",["grep"]);z("write",["write"]);z("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);z("apply_patch",["apply_patch","patch"]);z("bash",["bash"]);z("script",["codemode"]);z("web_search",["web_search","websearch","image_search"]);z("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);z("media",["image_gen","video_gen"]);z("show",["show","show_user","presentation_gen"]);z("task",["task"]);z("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);z("todowrite",["todowrite","todo_write","todoread"]);z("question",["question","ask"]);z("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);z("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);z("automations",["triggers"]);z("skill",["skill"]);z("context",["prune","distill","compress","context_info"]);z("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var bO=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ue(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Tx[t];if(n)return n;for(let[r,s]of bO)if(t.startsWith(r))return s;return"other"}function et(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var xO=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function SO(){return new RegExp(`(^|\\s)([-+]?)(${xO.join("|")}):("[^"]*"|\\S+)`,"gi")}function PO(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function wO(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function kO(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function vO(e){return kO(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Ix(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Cr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(SO(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=vO(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(PO(),"$1").replace(wO(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Ix(n)}`:r:n.length>0?Ix(n):t}var AO=/\s/,RO=/\w/;function be(e){return e!==void 0&&AO.test(e)}function Tr(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function If(e){return e!==void 0&&RO.test(e)}function $t(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(CO(n.charCodeAt(0))):n;return t}function CO(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function tt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function Ex(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return tt(e.slice(t))}function Ir(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function Ef(e,t){let n=Ir(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
|
|
76
76
|
`)&&(n=n.slice(1)),n.endsWith(`
|
|
77
|
-
`)&&(n=n.slice(0,-1)),n)}function Dm(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function v_(e,t){let n=Dm(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function R_(e,t){let n=Dm(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function T_(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Dm(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function C_(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Sr(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&be(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function I_(e,t,n){let r=Dt(t),s=Dt(n);for(let o of Dt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function E_(e,t){let n=Dt(e),r=t.map(Dt),s=e.length,o=c=>{let p=c;for(;p<s&&be(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Pr(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let m=o(d+1);if(m<s){let g=m;for(;g<s&&!Pr(e[g]);)g++;for(;g>m+1&&be(e[g-1]);)g--;return e.slice(m,g)}for(let g=s-1;g>d;g--)if(!Pr(e[g]))return e[g];return null}}a=i(c)}return null}function M_(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=be(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!be(e[a-1]))continue;let c=a+1;if(be(e[c])){for(;c<t&&be(e[c]);)c++;Mm(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Pr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;be(e[c]);)c++;let p=c;for(;p<t&&Mm(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&be(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let m=r[d+2]??-1;if(m!==-1){let g=Math.max(d+1,n[m]);if(o(d,g))return{id:e.slice(a+2,c),title:e.slice(d,g),status:i(m)}}}if(d<t&&r[d]===d){for(let m=d-2;m>=p+1;m--)if(!Pr(e[m]))return{id:e.slice(a+2,c),title:e[m],status:i(d)}}}}return null}function O_(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&be(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&be(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Mm(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&be(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function D_(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function j_(e){return D_(e,!0)}function $_(e){return D_(e,!1)}function FE(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function L_(e,t){let n=Dt(e),r=Dt(t),s=e.length,o=i=>{let a=i;for(;a<s&&be(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let c=o(a+1);for(let p=c;p<s;){if(!be(e[p])){p++;continue}let d=o(p);if(FE(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var U_=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function NE(e){return U_.has(le(e))}function KE(e){let t=0,n=0,r=0;for(let s of e){let o=le(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function jm(e){if(!e)return"";let t=Ze(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function xo(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function So(e){let t=Ve(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=r.filePath??r.file_path??r.path;return i?jm(String(i)):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${xo(String(i),40)}" in ${jm(String(a))}`:i?`"${xo(String(i),60)}"`:""}case"list":return r.path?jm(String(r.path)):"";case"bash":return xo(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return xo(i==="query"&&_r(a)||a,60)}return""}var F_={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function BE(e,t={}){let n=fe(e)?ae(e):e,r={...F_,...t},s=ee(n.tool),o=So(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function Oe(e){return e.type==="text"}function ke(e){return e.type==="reasoning"}function re(e){return e.type==="tool"}function Lm(e){return e.type==="file"}function qE(e){return e.type==="agent"}function GE(e){return e.type==="compaction"}function WE(e){return e.type==="snapshot"}function VE(e){return e.type==="patch"}function HE(e){return e.type==="step-start"||e.type==="step-finish"}function YE(e){if(Oe(e)||ke(e))return e.text}function zE(e){if(!Lm(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function JE(e){let t=[],n=[];for(let r of e)Lm(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function QE(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function XE(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var ZE=new Set(["todoread","context_info"]);function wo(e){return!ZE.has(fe(e)?e.name:e.tool)}var eM=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function kr(e){let t=fe(e)?ae(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=le(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return tM(n,t.state)}function tM(e,t){let n=ee(e);if(eM.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function nM(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return he(n.error)}}function rM(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)re(r)&&wo(r)&&t.push(r);return t}function sM(e,t={}){switch(ee(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:B_(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return oM(e,t)}}function oM(e,t){switch(le(e)){case"read":return{icon:"glasses",title:"Read",subtitle:N_(Xe(t))};case"list":return{icon:"list",title:"List",subtitle:K_(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:$m(Xe(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:$m(Xe(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function N_(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function $m(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function K_(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function iM(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function wr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
-
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function
|
|
79
|
-
`)
|
|
80
|
-
|
|
81
|
-
`)}var Z_=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),tO={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function nO(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&_r(t)||t}function rO(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return nO(r,s.trim())}}function vr(e){let t=fe(e)?ae(e):e;if(ke(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!re(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=ye(t.tool),r=tO[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:rO(s,r.objectKeys),tier:Z_.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function zm(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(vr(o).tier==="plumbing"){r=!0;continue}if(ke(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,re(o)&&Hm(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Ym(e){return`${e} ${e===1?"step":"steps"}`}function sO(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Ym(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Ym(n)}`:s===0?`${Ym(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function oO(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function iO(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function aO(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function cO(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=j_(n),n=$_(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function lO(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Sr(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function Rr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Io(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(Rr(i[1]),Rr(i[2]),i[3]?Rr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(Rr(i[2]),Rr(i[1])),n.length>=t)return n}return n}function eP(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Eo(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Jm(e){if(!e)return[];let t=eP(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let s of t.results)typeof s.query=="string"&&r.push({query:s.query,answer:s.answer||void 0,sources:Array.isArray(s.results)?Eo(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Eo(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Eo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Eo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let s of n){let o=s.match(/^Title:\s*(.+)/m),i=s.match(/^URL:\s*(.+)/m),a=s.match(/^Author:\s*(.+)/m),c=s.match(/^Published Date:\s*(.+)/m),p=s.match(/^Text:\s*([\s\S]*?)$/m);o&&i&&r.push({title:o[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Io(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function Mo(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function uO(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Mo(e)}}function pO(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function dO(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function tP(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function nP(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=L_(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function gO(e,t){let n=rP(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?nP(r,tP(t)):[]}function rP(e){if(!e)return null;let t=eP(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Io(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function mO(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var fO={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Oo(e){return fO[le(e)]}function Cr(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var yO={run:"Terminal",memory:"Memory"};function hO(e){let t=Oo(e);return(t==="hidden"?void 0:yO[t])??Cr(e)}function Tr(e,t,n){return e===1?t:n}function Qm(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function iP(e){return e.length?So(e[0]):""}function De(e){return(e.state??{}).input??{}}var bO={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function _O(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(De(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return bO[t]??"message"}function sP(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function PO(e){let t=ee(e.tool);if(t==="triggers"){let r=De(e).action||"list";return sP(r)}let n=t.match(/^trigger_(.+)$/);return sP(n?n[1]:"list")}var xO={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function SO(e){return xO[ee(e.tool)]??"read"}var wO={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function kO(e){return wO[ee(e.tool)]??"open"}function fn(e){return e.every(t=>t===e[0])}var AO={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function vO(e){if(ee(e.tool)!=="memory")return"read";let n=De(e).command;return n&&AO[n]||"unknown"}var RO={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},TO={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function CO(e){let t=Ze(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function IO(e){let t=De(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return EO(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return CO(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=mO(o);return i?Mo(i):"a link"}return""}function EO(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function MO(e){let t=De(e).action;return t&&RO[t]||"Worked on an image"}function OO(e){let t=De(e).action;return t&&TO[t]||"Worked on a presentation"}function DO(e){return e.slice(0,e.indexOf(":"))}var jO={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},$O={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function LO(e){let t=ee(e.tool);if(t==="image_gen"){let n=De(e).action;return n&&jO[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=De(e).action;return n&&$O[n]||"presentation:unknown"}return"shown:result"}var UO=new Set(["create_slide","export_pdf","export_pptx"]);function FO(e){let t=Ve(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=De(t).action;return r?UO.has(r)?"presentation":null:"presentation"}return null}var NO={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},oP={image:"image",video:"video",presentation:"presentation",shown:"result"};function KO(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[DO(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Tr(s,oP[r],`${oP[r]}s`)}`)}),`Worked on ${Qm(n)}`}function Xm(e,t){let n=t.map(Ve),r=n.length,s=iP(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Tr(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>Xe(De(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Tr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Tr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let m of Jm(d).flatMap(g=>g.sources))m.url&&a.add(m.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let c=a.size||r;return`Searched and read ${c} ${Tr(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return MO(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return OO(i);let c=IO(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(LO);return fn(o)?NO[o[0]](r):KO(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(_O);if(fn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(vO);if(fn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(SO);if(fn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(PO);if(fn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(kO);if(fn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${Cr(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Cr(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${Qm(o)}`}}}function Zm(e,t){let n=t.map(Ve),r=iP(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>Cr(a.tool))));return`Couldn't finish using ${Qm(i)}`}}}function BO(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function qO(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function aP(e,t){let n=t.map(Ve),r=BO(n);return{id:n[0].callID,family:e,label:r==="error"?Zm(e,n):Xm(e,n),parts:t,status:r,durationMs:r==="running"?void 0:qO(n)}}function ef(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(aP(n,r)),n=null,r=[]};for(let o of e){let i=Ve(o),a=Oo(i.tool);if(a!=="hidden"&&!Bs(i)){if(Ng(i.tool)){s(),t.push(aP(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Do(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function tf(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of ef(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(ke(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Do(a);continue}if(o(),re(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var GO=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function WO(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function VO(e){let t=e.flatMap(s=>{let o=WO(s);return o?[o]:[]}).join(" ").trim();return t?GO.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function dP(e){return e?.info?.time??{}}function HO(e){let t=dP(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var jo=6e4,YO=10080*jo,cP=1440;function lP(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function zO(e,t){let n=t.getTime()-e.getTime(),r=n/jo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<cP)return s(Math.round(r/60),"hour");let o=(n-(lP(t)-lP(e)))/jo;return s(Math.round(o/cP),"day")}function gP(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var uP=new Map;function JO(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=uP.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),uP.set(r,s)),s}function $o(e,t,n){return JO(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?QO(r.value,n):r.value).join("")}function QO(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function pP(e,t){return $o(e,{year:"numeric"},t)}function XO(e,t,n={}){let r=gP(e);if(!r)return"";let s=i=>$o(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<jo?"just now":o<YO?zO(r,new Date(t)):s(pP(r,n)!==pP(new Date(t),n))}function ZO(e,t={}){let n=gP(e);if(!n)return"";let r=$o(n,{month:"long",day:"numeric",year:"numeric"},t),s=$o(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function nf(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Kg(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(re(o)&&(Bg(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function eD(e){let t=ye(e);return t==="show"||t==="show_user"}function rf(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&eD(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var tD=["title","description","path","url","content","language","aspect_ratio","attachment"];function mP(e,t){if(!t||typeof t!="object")return null;let n=t;if(Qn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of tD){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function nD(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function sf(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=nD(s.items),i=o?o.map(a=>mP(n.callID,a)).filter(a=>!!a):[mP(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function of(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Ir=e=>"id"in e?e.id:e.userMessage.info.id,fP=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,rD=e=>e.time?.completed;function sD(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function oD(e,t){let n=Ir(e);return t.pendingTurnIds.has(n)||fP(e)===0&&t.pendingPromptIds.has(n)}function iD(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Ir(r)));if(t)return Ir(t);let n=e.turns.findIndex(r=>oD(r,e));return n<=0?null:Ir(e.turns[n-1])}function aD(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function cD(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function lD(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:of({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function uD(e,t){for(let n=e.length-1;n>=0;n--){let r=Ir(e[n]);if(t(r))return fP(e[n])===0?r:null}return null}function af(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!rD(c.info)&&!c.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function pD(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function dD(e,t){return!t||!e?!1:e.type!=="idle"}function gD(e,t){return!e&&!!t}function mD(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)?.message||he(n.error)}}function fD(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return br(n.error)}}function yD(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)}}function cf(e){if(e){if(re(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(ke(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Oe(e))return"Gathering thoughts..."}}function lf(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=re(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=cf(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let o=cf(r);if(o)return o}return"Figuring out what\u2019s next..."}function uf(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var pf=1.2;function yP(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,m)=>m.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,s>0&&(p+=s/1e6*(c.cacheReadPer1M??c.inputPer1M)),o>0&&(p+=o/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function df(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function hP(e,t,n,r){if(df(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?yP(e.tokens,o):0}function bP(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Lo(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let m=p,{providerID:g,modelID:y}=bP(d.info);n+=hP(m,g,y,t),r+=m.tokens?.input||0,s+=m.tokens?.output||0,o+=m.tokens?.reasoning||0,i+=m.tokens?.cache?.read||0,a+=m.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let m=d.info;if(p.has(m.id))continue;p.add(m.id);let g=_P(m,t),y=m.tokens&&df(m.providerID,m.modelID);if(g<=0&&!y)continue;c=!0,n+=g;let h=m.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*pf,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function _P(e,t){if(df(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?yP({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function hD(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=bP(s),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=hP(p,o,i,t));c||(a+=_P(s,t)),n+=a}return n*pf}function bD(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function _D(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function PD(e){if(!e||e.type!=="retry")return;let t=e,n=he(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:Se(t.message)}}function xD(e){if(!(!e||e.type!=="retry"))return he(e.message)}function SD(e){return(e.info.summary?.diffs?.length??0)>0}function PP(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=ye(e.part.tool);return t==="show"||t==="show_user"}function wD(e){return e.kind==="text"&&!e.part.text?.trim()}function gf(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(PP(o)||wD(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):PP(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function kD(e){let t=e==null?"":uf(e);return t?`Worked for ${t}`:"Worked"}function xP(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Oe(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return re(s)&&s.tool==="bash"}function AD(e){if(xP(e))return e.assistantMessages[0].parts[0]}function vD(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=T_(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function RD(e){return e?e.split(`
|
|
82
|
-
|
|
83
|
-
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function CD(e){if(!e)return[];let t=[],n=e.split(`
|
|
84
|
-
`).filter(
|
|
85
|
-
`)
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Mf(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function Mx(e,t){let n=Mf(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Ox(e,t){let n=Mf(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function Dx(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Mf(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function jx(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Er(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&be(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Lx(e,t,n){let r=$t(t),s=$t(n);for(let o of $t(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function $x(e,t){let n=$t(e),r=t.map($t),s=e.length,o=c=>{let p=c;for(;p<s&&be(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Tr(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Tr(e[m]);)m++;for(;m>g+1&&be(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Tr(e[m]))return e[m];return null}}a=i(c)}return null}function Ux(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=be(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!be(e[a-1]))continue;let c=a+1;if(be(e[c])){for(;c<t&&be(e[c]);)c++;If(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Tr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;be(e[c]);)c++;let p=c;for(;p<t&&If(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&be(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Tr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function Fx(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&be(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&be(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!If(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&be(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function Nx(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function Bx(e){return Nx(e,!0)}function Kx(e){return Nx(e,!1)}function TO(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function qx(e,t){let n=$t(e),r=$t(t),s=e.length,o=i=>{let a=i;for(;a<s&&be(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let c=o(a+1);for(let p=c;p<s;){if(!be(e[p])){p++;continue}let d=o(p);if(TO(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var Gx=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function IO(e){return Gx.has(ue(e))}function EO(e){let t=0,n=0,r=0;for(let s of e){let o=ue(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Of(e){if(!e)return"";let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Do(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function jo(e){let t=He(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=r.filePath??r.file_path??r.path;return i?Of(String(i)):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${Do(String(i),40)}" in ${Of(String(a))}`:i?`"${Do(String(i),60)}"`:""}case"list":return r.path?Of(String(r.path)):"";case"bash":return Do(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return Do(i==="query"&&Cr(a)||a,60)}return""}var Wx={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function MO(e,t={}){let n=ye(e)?ce(e):e,r={...Wx,...t},s=ee(n.tool),o=jo(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function De(e){return e.type==="text"}function ve(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function jf(e){return e.type==="file"}function OO(e){return e.type==="agent"}function DO(e){return e.type==="compaction"}function jO(e){return e.type==="snapshot"}function LO(e){return e.type==="patch"}function $O(e){return e.type==="step-start"||e.type==="step-finish"}function UO(e){if(De(e)||ve(e))return e.text}function FO(e){if(!jf(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function NO(e){let t=[],n=[];for(let r of e)jf(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function BO(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function KO(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var qO=new Set(["todoread","context_info"]);function _n(e){return!qO.has(ye(e)?e.name:e.tool)}var GO=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=ye(e)?ce(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ue(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return WO(n,t.state)}function WO(e,t){let n=ee(e);if(GO.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function VO(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function HO(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&_n(r)&&t.push(r);return t}function zO(e,t={}){switch(ee(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:zx(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return YO(e,t)}}function YO(e,t){switch(ue(e)){case"read":return{icon:"glasses",title:"Read",subtitle:Vx(et(t))};case"list":return{icon:"list",title:"List",subtitle:Hx(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Df(et(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Df(et(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function Vx(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Df(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function Hx(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function JO(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
+
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function zx(e){let t=Mr(e.description);if(t)return t;let n=Mr(e.title,80);if(n)return n;let r=Mr(e.message);if(r)return r;let s=Mr(e.prompt);if(s)return s;let o=Mr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function QO(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function XO(e,t){return e.find(n=>n.tool?.callID===t)}function ZO(e,t){return e.find(n=>n.tool?.callID===t)}var eD=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function tD(e){return e?e.replace(eD,""):""}function Lo(e){let t=Yx(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?Yx(r):void 0;return s?[s]:[]})}function Yx(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var nD={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},rD={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function sD(e){return e.replace(/^oc[-_]/,"")}function Lf(e){return sD(e).replace(/-/g,"_")}function $f(e){return Lf(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function $o(e){return{label:nD[Lf(e)]??$f(e),category:rD[ue(e)]}}var oD=256*1024;function iD(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function aD(e){if(e===void 0)return{};if(e.length>oD)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function cD(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?_e(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var ge=e=>typeof e=="string"?e:void 0,Uo=e=>typeof e=="number"?e:void 0,Fo=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Uf(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var lD=new Set(["add","update","delete","move"]);function uD(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Fo(d),m=g&&(ge(g.relativePath)||ge(g.filePath));if(!g||!m)return[];let f=ge(g.type);return[Uf({path:m,type:f&&lD.has(f)?f:void 0,before:ge(g.before),after:ge(g.after),patch:ge(g.patch)??ge(g.diff),additions:Uo(g.additions),deletions:Uo(g.deletions),movePath:ge(g.movePath)})]});return p.length?p:void 0}let r=et(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Uf({path:r,after:ge(t.content)})];if(e!=="edit")return;let s=Fo(n.filediff),o=s?void 0:ge(n.patch),i=o?pD(o):void 0,a=s||o?[]:Lo(t);return[Uf({path:r,before:ge(s?.before)??(a.length?a.map(([c])=>c).join(`
|
|
79
|
+
`):void 0),after:ge(s?.after)??(a.length?a.map(([,c])=>c).join(`
|
|
80
|
+
`):ge(t.new_source)),patch:o,additions:Uo(s?.additions)??i?.additions,deletions:Uo(s?.deletions)??i?.deletions})]}function pD(e){let t=0,n=0;for(let r of e.split(`
|
|
81
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function dD(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Jx(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=aD(r),i=iD(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=cD(s);m&&(i="error",a=m)}let c=ue(e),p=t.input??{},d="metadata"in t&&Fo(t.metadata)||{},g=Fo(d.diagnostics);return{name:e,kind:c,title:n||$o(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:uD(c,p,d),diff:ge(d.patch)??ge(d.diff),diagnostics:g,answers:c==="question"?dD(d):void 0,childSessionId:Or({tool:e,state:t})}}function Ff(e){let t=ye(e)?ce(e):e;return Jx(t.tool,t.state)}function gD(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function mD(e){return{kind:"reasoning",id:e.id,text:e.text}}function fD(e){return{kind:"tool",id:e.id,tool:Jx(e.tool,e.state)}}function yD(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function hD(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function _D(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function bD(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function xD(e){return{kind:"agent",id:e.id,name:e.name}}function SD(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function PD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function wD(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function kD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Nf(e){switch(e.type){case"text":return gD(e);case"reasoning":return mD(e);case"tool":return fD(e);case"file":return yD(e);case"subtask":return hD(e);case"patch":return _D(e);case"snapshot":return bD(e);case"agent":return xD(e);case"retry":return SD(e);case"compaction":return PD(e);case"step-start":return wD(e);case"step-finish":return kD(e);default:return{kind:"unknown",raw:e}}}function vD(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=we(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function AD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function No(e){let t=e.parts.map(Nf),n=e.info.role==="assistant"?e.info.error:void 0,r=vD(n),s=!r&&!t.some(AD);return{parts:t,error:r,isEmpty:s}}var Bf=Je+BigInt(1),Qx=Bf/BigInt(2);function Bo(e){return BigInt(Math.trunc(e))*nn}function Kf(e,t){let r=t-(t&Je)+e;return r-t>Qx?r-=Bf:t-r>Qx&&(r+=Bf),r}function Xx(e,t){let n=Dt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Kf(n,t);let s=Bo(r),o=Kf(n,s);return(o>s?o-s:s-o)<=ut?o:s}function Zx(e){return Dt(e)===null?1:0}function eS(e,t){return e<t?-1:e>t?1:0}function RD(e,t){return tS(e,t,Bo(Date.now()))}function CD(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Bo(t??Date.now())}function tS(e,t,n){let r=Zx(e.info.id),s=Zx(t.info.id);if(r!==s)return r-s;if(r===0){let a=Xx(e,n),c=Xx(t,n);return a!==c?a<c?-1:1:eS(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:eS(e.info.id,t.info.id)}function TD(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=CD(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:tS(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:ED(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...o]:o}var Dr=new Map,ID=256;function ED(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Dr.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Dr.size>=ID){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(s,i),i}function MD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function OD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(De(n)&&n.text?.trim())return n}}function DD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function jD(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!te(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function LD(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function $D(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function nS(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...nS(e,s));return r}function rS(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function qf(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&rS(n.error)}return!1}function Ko(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gf(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function UD(e){return!!e&&(Gf(e)||oS(e)!==null)}function qo(e){let t=ye(e)?ce(e):e,n=sS.get(t);if(n&&n.state===t.state)return n.outcome;let r=FD(t);return sS.set(t,{state:t.state,outcome:r}),r}var sS=new WeakMap;function FD(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(Gf(n))return"failed";let r=ND(n);return r===void 0?"ok":BD(r)?"failed":KD(r)}function ND(e){try{return JSON.parse(e)}catch{return}}function BD(e){return Ko(e)&&e.success===!1&&typeof e.error=="string"}function KD(e){let t=Ko(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function oS(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Ko(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=Er(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function qD(e){return Fx(e).replace(/\s+/g," ").trim()||e.trim()}function GD(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Ko(n))return null;let r=n.success,s=n.error,o=n.hint;if(r!==!1||typeof s!="string")return null;let i=[];i.push(s.trim());let a=Er(s);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof o=="string"&&o.trim()&&i.push(`Hint: ${o.trim()}`),i.join(`
|
|
82
|
+
|
|
83
|
+
`)}function WD(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function VD(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function HD(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Bx(n),n=Kx(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function zD(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Er(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function jr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Go(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(jr(i[1]),jr(i[2]),i[3]?jr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(jr(i[2]),jr(i[1])),n.length>=t)return n}return n}function iS(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Wo(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Wf(e){if(!e)return[];let t=iS(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let s of t.results)typeof s.query=="string"&&r.push({query:s.query,answer:s.answer||void 0,sources:Array.isArray(s.results)?Wo(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Wo(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Wo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Wo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let s of n){let o=s.match(/^Title:\s*(.+)/m),i=s.match(/^URL:\s*(.+)/m),a=s.match(/^Author:\s*(.+)/m),c=s.match(/^Published Date:\s*(.+)/m),p=s.match(/^Text:\s*([\s\S]*?)$/m);o&&i&&r.push({title:o[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Go(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function Vo(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function YD(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Vo(e)}}function JD(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function QD(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function aS(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function cS(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=qx(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function XD(e,t){let n=lS(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?cS(r,aS(t)):[]}function lS(e){if(!e)return null;let t=iS(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Go(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function ZD(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var ej={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function xn(e){return ej[ue(e)]}function $r(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var tj={run:"Terminal",memory:"Memory"};function nj(e){let t=xn(e);return(t==="hidden"?void 0:tj[t])??$r(e)}function Lr(e,t,n){return e===1?t:n}function Vf(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function dS(e){return e.length?jo(e[0]):""}function je(e){return(e.state??{}).input??{}}var rj={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function sj(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(je(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return rj[t]??"message"}function uS(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function oj(e){let t=ee(e.tool);if(t==="triggers"){let r=je(e).action||"list";return uS(r)}let n=t.match(/^trigger_(.+)$/);return uS(n?n[1]:"list")}var ij={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function aj(e){return ij[ee(e.tool)]??"read"}var cj={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function lj(e){return cj[ee(e.tool)]??"open"}function bn(e){return e.every(t=>t===e[0])}var uj={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function pj(e){if(ee(e.tool)!=="memory")return"read";let n=je(e).command;return n&&uj[n]||"unknown"}var dj={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},gj={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function mj(e){let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function fj(e){let t=je(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return yj(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return mj(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=ZD(o);return i?Vo(i):"a link"}return""}function yj(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function hj(e){let t=je(e).action;return t&&dj[t]||"Worked on an image"}function _j(e){let t=je(e).action;return t&&gj[t]||"Worked on a presentation"}function bj(e){return e.slice(0,e.indexOf(":"))}var xj={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},Sj={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function Pj(e){let t=ee(e.tool);if(t==="image_gen"){let n=je(e).action;return n&&xj[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=je(e).action;return n&&Sj[n]||"presentation:unknown"}return"shown:result"}var wj=new Set(["create_slide","export_pdf","export_pptx"]);function kj(e){let t=He(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=je(t).action;return r?wj.has(r)?"presentation":null:"presentation"}return null}var vj={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},pS={image:"image",video:"video",presentation:"presentation",shown:"result"};function Aj(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[bj(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Lr(s,pS[r],`${pS[r]}s`)}`)}),`Worked on ${Vf(n)}`}function Ur(e,t){let n=t.map(He),r=n.length,s=dS(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Lr(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>et(je(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Lr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Lr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Wf(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let c=a.size||r;return`Searched and read ${c} ${Lr(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return hj(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return _j(i);let c=fj(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(Pj);return bn(o)?vj[o[0]](r):Aj(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(sj);if(bn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(pj);if(bn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(aj);if(bn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(oj);if(bn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(lj);if(bn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$r(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>$r(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${Vf(o)}`}}}function Hf(e,t){let n=t.map(He),r=dS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>$r(a.tool))));return`Couldn't finish using ${Vf(i)}`}}}var gS=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),Rj={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function Cj(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Cr(t)||t}function Tj(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return Cj(r,s.trim())}}function Sn(e){let t=ye(e)?ce(e):e;if(ve(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=he(t.tool),r=Rj[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:Tj(s,r.objectKeys),tier:gS.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Ho(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(Sn(o).tier==="plumbing"){r=!0;continue}if(ve(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,te(o)&&qo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function zf(e){return`${e} ${e===1?"step":"steps"}`}function mS(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${zf(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${zf(n)}`:s===0?`${zf(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Yf(e){let t=new Map,n=0;for(let s of e){if(!te(s)||Sn(s).tier==="plumbing")continue;let o=xn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),qo(s)!=="ok"&&(n+=1))}if(t.size===0)return mS(Ho(e),!1);let r=[...t].map(([s,o],i)=>{let a=Ur(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function Ij(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function Ej(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function Mj(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function fS(e,t){let n=t.map(He),r=Ej(n);return{id:n[0].callID,family:e,label:r==="error"?Hf(e,n):Ur(e,n),parts:t,status:r,durationMs:r==="running"?void 0:Mj(n)}}function Jf(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(fS(n,r)),n=null,r=[]};for(let o of e){let i=He(o),a=xn(i.tool);if(a!=="hidden"&&!Zs(i)){if(lm(i.tool)){s(),t.push(fS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function zo(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function Qf(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Jf(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(ve(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=zo(a);continue}if(o(),te(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var Oj=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function Dj(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function jj(e){let t=e.flatMap(s=>{let o=Dj(s);return o?[o]:[]}).join(" ").trim();return t?Oj.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function xS(e){return e?.info?.time??{}}function Lj(e){let t=xS(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Yo=6e4,$j=10080*Yo,yS=1440;function hS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function Uj(e,t){let n=t.getTime()-e.getTime(),r=n/Yo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<yS)return s(Math.round(r/60),"hour");let o=(n-(hS(t)-hS(e)))/Yo;return s(Math.round(o/yS),"day")}function SS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var _S=new Map;function Fj(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=_S.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),_S.set(r,s)),s}function Jo(e,t,n){return Fj(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?Nj(r.value,n):r.value).join("")}function Nj(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function bS(e,t){return Jo(e,{year:"numeric"},t)}function Bj(e,t,n={}){let r=SS(e);if(!r)return"";let s=i=>Jo(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Yo?"just now":o<$j?Uj(r,new Date(t)):s(bS(r,n)!==bS(new Date(t),n))}function Kj(e,t={}){let n=SS(e);if(!n)return"";let r=Jo(n,{month:"long",day:"numeric",year:"numeric"},t),s=Jo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Xf(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!um(o)){if(De(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(pm(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function qj(e){let t=he(e);return t==="show"||t==="show_user"}function Zf(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&qj(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var Gj=["title","description","path","url","content","language","aspect_ratio","attachment"];function PS(e,t){if(!t||typeof t!="object")return null;let n=t;if(or(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of Gj){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function Wj(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function ey(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=Wj(s.items),i=o?o.map(a=>PS(n.callID,a)).filter(a=>!!a):[PS(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function ty(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Fr=e=>"id"in e?e.id:e.userMessage.info.id,wS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,Vj=e=>e.time?.completed;function Hj(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function zj(e,t){let n=Fr(e);return t.pendingTurnIds.has(n)||wS(e)===0&&t.pendingPromptIds.has(n)}function Yj(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Fr(r)));if(t)return Fr(t);let n=e.turns.findIndex(r=>zj(r,e));return n<=0?null:Fr(e.turns[n-1])}function Jj(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function Qj(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function Xj(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:ty({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function Zj(e,t){for(let n=e.length-1;n>=0;n--){let r=Fr(e[n]);if(t(r))return wS(e[n])===0?r:null}return null}function ny(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!Vj(c.info)&&!c.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function eL(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function tL(e,t){return!t||!e?!1:e.type!=="idle"}function nL(e,t){return!e&&!!t}function rL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)?.message||_e(n.error)}}function sL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Rr(n.error)}}function oL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)}}function ry(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(ve(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(De(e))return"Gathering thoughts..."}}function sy(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=te(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=ry(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let o=ry(r);if(o)return o}return"Figuring out what\u2019s next..."}function oy(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var iy=1.055;function kS(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,s>0&&(p+=s/1e6*(c.cacheReadPer1M??c.inputPer1M)),o>0&&(p+=o/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ay(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function vS(e,t,n,r){if(ay(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?kS(e.tokens,o):0}function AS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Qo(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=AS(d.info);n+=vS(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=RS(g,t),f=g.tokens&&ay(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*iy,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function RS(e,t){if(ay(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?kS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function iL(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=AS(s),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=vS(p,o,i,t));c||(a+=RS(s,t)),n+=a}return n*iy}function aL(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function cL(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function lL(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:we(t.message)}}function uL(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function pL(e){return(e.info.summary?.diffs?.length??0)>0}function CS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function dL(e){return e.kind==="text"&&!e.part.text?.trim()}function cy(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(CS(o)||dL(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):CS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function gL(e){let t=e==null?"":oy(e);return t?`Worked for ${t}`:"Worked"}function TS(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>De(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return te(s)&&s.tool==="bash"}function mL(e){if(TS(e))return e.assistantMessages[0].parts[0]}function fL(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=Dx(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function yL(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function hL(e){if(!e)return null;let n=e.split(`
|
|
85
|
+
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function _L(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=Ux(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var yt={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function bL(e,t){let n=yt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function xL(e,t){return t?"failed":e?"running":"done"}var SL={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function PL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function wL(e,t){if(!e)return null;let n=e.indexOf(`
|
|
87
|
+
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(Lx(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
86
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
87
89
|
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
88
|
-
`)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var
|
|
90
|
+
`)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var kL={add:{...yt.write,icon:"create"},delete:{...yt.delete,icon:"delete"},move:{...yt.rename,icon:"edit"},update:{...yt.edit,icon:"edit"}},IS={...yt.change,icon:"edit"};function vL(e){if(e.length===0)return IS;let t=ES(e[0]);for(let n=1;n<e.length;n++)if(ES(e[n])!==t)return IS;return kL[t]}function ES(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function AL(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function ly(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function RL(e){if(!e)return null;let t=Ir(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Ef(e,"content");if(r!==null){let o=r.split(`
|
|
89
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
90
|
-
`);return{path:n,type:"file",content:o}}let s=
|
|
91
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function
|
|
92
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=Ef(e,"entries");if(s!==null){let o=s.split(`
|
|
93
|
+
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function CL(e){let t=Ox(e,"skill_content");return t!==null?t.trim():e}function MS(e){let t=Ir(e,"<skill_files>","</skill_files>");return t===null?[]:jx(t,"<file>","</file>").map(n=>n.trim())}function TL(e){let t=Mx(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function IL(e){return $x(e,["Base directory","Directory","Skill directory"])?.trim()??""}function OS(e){return tt(TL(e)||IL(e))}function EL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return tt(n.trim())}return""}var ML="skills";function OL(e){let t=Ex(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${ML}/${r}`:""}function DL(e,t,n){let s=tt(t?.trim()??"")||OS(e)||OL(n),o=MS(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var jL=4e3;function Nr(e,t=jL){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function DS(e){if(e!==void 0)try{return Nr(JSON.stringify(e,null,2))}catch{return}}function se(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function LL(e){let t=se(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Pn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=Pn(o)??{};return{title:se(i.title)??"",url:se(i.url,i.link)??"",snippet:se(i.snippet,i.description,i.source)}});return{kind:"web-search",query:se(n.query)??t,results:s.length>0?s:void 0,answer:se(n.answer)}}var $L=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function py(e){let t=e.match($L);return t?Number(t[1]):void 0}function UL(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var FL=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function NL(e){let t=-1;for(let n of FL){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var BL=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function KL(e){return e.replace(BL,"")}function qL(e){let t=se(e.input?.command)??"",n=e.output??"",r=py(n),o=KL(NL(UL(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function dy(e){return se(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function GL(e){let t=e.status==="error"?e.error:e.output&&Nr(e.output)||void 0;return{kind:"file-read",path:dy(e),preview:t}}function WL(e){let t=se(e.input?.content),n=e.status==="error"?e.error:Nr(t??e.output??"")||void 0;return{kind:"file-write",path:dy(e),preview:n}}var VL=256*1024;function HL(e,t){if(e.length+t.length>VL)return;let n=e.split(`
|
|
93
95
|
`),r=t.split(`
|
|
94
|
-
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function
|
|
95
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function uj(e){let t=H(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=TP.test(e.output.trim())?cj(e.output):lj(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function pj(e){let t=H(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=H(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function ff(e){let t=jt(e)??{};return{content:H(t.content)??"",status:H(t.status)??"pending",priority:H(t.priority)}}function dj(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(ff)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(ff)};let n=jt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(ff)}:{kind:"todo",items:[]}}function gj(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=jt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=jt(a),p=c&&H(c.label);return p?[{label:p,description:c?H(c.description):void 0}]:[]});return{question:H(s.question)??"",header:H(s.header),options:i}})}}function mj(e){let n=e.input&&Object.keys(e.input).length>0?vP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Er(e.outputParsed):vP(e.outputParsed):e.outputText!==void 0?r=Er(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function CP(e){switch(le(e.name)){case"web_search":return HD(e);case"bash":return ej(e);case"read":return tj(e);case"write":return nj(e);case"edit":return ij(e);case"grep":case"glob":return uj(e);case"task":return pj(e);case"todowrite":return dj(e);case"question":return gj(e);default:return mj(e)}}var fj=new Set(["AbortError","MessageAbortedError"]),yj=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],hj=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function IP(e){let t=e.toLowerCase();return hj.some(n=>t.includes(n))?!1:yj.some(n=>t.includes(n))}function bj(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Mr(e){if(typeof e=="string")return IP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&fj.has(n))return!0;let r=bj(t);return typeof r=="string"?IP(r):!1}var EP=["user","runtime-disposed","orphan-finalized","wake"],_j=["orphan-finalized","wake"];function Pj(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return EP.includes(n)?n:void 0}var Or="kortix-active-instance",MP=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function OP(e){return MP.some(t=>e===t||e.startsWith(`${t}/`))}function yn(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function xj(e){let t=yn(e);return!!t&&t.innerPath===""}function Sj(e){let t=yn(e);return!t||!t.innerPath?e:t.innerPath}function DP(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=yn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return OP(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function jP(e){return e?yn(e)?.instanceId??null:null}function wj(){return typeof window>"u"?null:jP(window.location.pathname)||$P()}function $P(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Or}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function kj(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Or}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Or}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Or}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function Aj(e,t){return t?DP(t,e):e}function vj(e){let t=yn(e);return t?t.innerPath||"/dashboard":e}function jr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function bf(e){let t=jr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var Rj=bf;function Uo(e){let t=bf(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var Tj=Uo;function LP(e){return Uo(e)!==null}var Cj=LP,Ij=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],Ej=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],Mj=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function UP(e){return Mj.test(jr(e))}function hn(e){let t=jr(e);return t?UP(t)||Ij.some(n=>n.test(t)):!1}var Oj=/server url not ready|sandbox is still loading/i;function Dj(e){return Oj.test(jr(e))||hn(e)}var Dr=class extends Error{constructor(t){let n=t?.trim();super(n&&hn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function FP(e){let t=Uo(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=jr(e);return hn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var jj=FP;function _f(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${ot()}/p/${e.external_id}/${Ye.KORTIX_MASTER}`}function $j(e,t){return e.external_id?`${ot()}/p/${e.external_id}/${t}`:null}async function Lj(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function NP(e){let t=await Tt();if(t)return{sandbox:t.sandbox,created:!1};let r=(await St())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await vt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await nt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Jg(r,s,o),created:!0}}async function Uj(){return(await Tt().catch(()=>null))?.sandbox??null}async function Fj(e){return{sandbox:(await NP(e)).sandbox}}async function Nj(e){let t=tr(e);return t?(await Tt(t).catch(()=>null))?.sandbox??null:null}async function Kj(e,t){throw await Tt(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function Bj(e){let t=tr(e);return(await Qg().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function qj(){return null}async function Gj(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Tt(e);if(!t)throw new Error("Project session sandbox not found");await Wn(t.project.project_id,t.session.session_id)}async function Wj(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Tt(e);if(!t)throw new Error("Project session sandbox not found");await Vn(t.project.project_id,t.session.session_id)}async function Vj(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function Hj(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Pf(e,t,n){let r=_f(e),s=await $(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function Yj(e,t){return Pf(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function zj(e,t,n,r="member"){await Pf(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function Jj(e,t,n){await Pf(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var xf="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function Qj(e){throw K("getInvite",xf)}async function Xj(e){throw K("acceptInvite",xf)}async function Zj(e){throw K("declineInvite",xf)}async function e$(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function t$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function n$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function r$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function s$(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function o$(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var KP=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function i$(e){return KP.includes(e)}async function a$(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function c$(e){let t=e?`?channel=${e}`:"",r=await(await Fe(`${ot()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await BP(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function BP(e){let t=e?`?channel=${e}`:"";return(await(await Fe(`${ot()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function l$(){return(await Fe(`${ot()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function u$(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function p$(e){}async function d$(e){}async function g$(e){return{serverTypes:[],location:e||"hel1"}}async function m$(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function f$(e){throw K("deleteInstance")}async function y$(e,t){}async function h$(){throw K("claimComputer")}async function b$(e){return null}function _$(e,t){throw K("getSandboxProvisionStreamUrl")}var $r=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function qP(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function GP(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function WP(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function te(e,t,n){let r=n?.body!==void 0,s=await fetch(`${Rt(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:qP(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await GP(s);if(!s.ok)throw new $r(WP(s,o),s.status,o);return o}function P$(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function x$(e,t){return te(`/marketplace/items${P$(t)}`,e)}function S$(e){return te("/marketplace/marketplaces",e)}function w$(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function k$(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function A$(e,t){return te("/access/check-email",t,{method:"POST",body:{email:e}})}function v$(e,t){return te("/access/request-access",t,{method:"POST",body:e})}function R$(e){return te("/auth/logout",e,{method:"POST",body:{}})}function T$(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function C$(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function I$(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function E$(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function M$(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function O$(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function D$(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function j$(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function $$(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function L$(e){return te("/system/maintenance",e)}function U$(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function F$(e){return te("/user-roles",e)}function N$(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function K$(e,t,n){let r=await fetch(`${Rt(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ht(t)}`,{headers:qP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await GP(r);throw new $r(WP(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function B$(e,t){throw K("openStressTestStream")}function q$(e,t){throw K("buildPublicTemplateUrl")}async function G$(e,t,n){throw K("getPublicTemplate")}var W$="kortix:connect-link:";function Sf(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${W$}${t.toString(36)}${n.toString(36)}`}function V$(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Sf(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Sf(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Sf(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var VP="Could not start the connect flow.";async function H$(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:VP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:VP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var HP=3e3,YP=5e3,zP=5*6e4;function Y$(e,t){let n=e===0?HP:YP;return t+n>zP?null:n}function z$(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function J$(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function Q$(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function X$(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function Z$(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function eL(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var hY="1";var tL="kortix.query-cache";function QP(e){return!!e&&typeof e.then=="function"}function JP(e){return QP(e)?e:Promise.resolve()}function nL(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function rL(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=tL,now:p=()=>Date.now()}=e,d=`${c}:${n}`,m=null,g=!1,y=null,h=Promise.resolve(),P=()=>{try{return JP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},C=(T,w)=>{if(!w)return 0;let S;try{S=JSON.parse(w)}catch{return P(),0}if(!S||S.v!==s||S.user!==n||!Array.isArray(S.queries)||p()-S.at>o)return P(),0;let I=0;for(let k of S.queries){if(!k||!Array.isArray(k.k)||k.d===void 0||typeof k.t!="number"||p()-k.t>o||!r(k.k))continue;let U=T.getQueryState(k.k);U&&U.data!==void 0&&U.dataUpdatedAt>=k.t||(T.setQueryData(k.k,k.d,{updatedAt:k.t}),T.invalidateQueries?.({queryKey:k.k,exact:!0,refetchType:"none"}),I+=1)}return I},M=T=>T.getQueryCache().getAll().filter(w=>w.state.data!==void 0&&r(w.queryKey)).map(w=>({k:w.queryKey,d:w.state.data,t:w.state.dataUpdatedAt})).sort((w,S)=>S.t-w.t),L=(T,w)=>{let S=[],I=0;for(let k of T){let U=JSON.stringify(k).length+1;I+U>w||(S.push(k),I+=U)}return S},f=async T=>{let w=L(M(T),i);for(;;){let S={v:s,user:n,at:p(),queries:w};try{await JP(t.setItem(d,JSON.stringify(S)));return}catch{if(w.length===0)return;w=w.slice(0,Math.floor(w.length/2))}}},b=()=>{y!==null&&(clearTimeout(y),y=null)},x=()=>{b();let T=m;return!T||!g||(g=!1,h=h.then(()=>f(T)).catch(()=>{})),h},R=()=>{g=!0,y===null&&(y=setTimeout(()=>{y=null,x()},a))};return{storageKey:d,restore(T){let w;try{w=t.getItem(d)}catch{return 0}return QP(w)?w.then(S=>C(T,S)).catch(()=>0):C(T,w)},persist(T){m=T,g=!0;let w=T.getQueryCache().subscribe(S=>{S.type!=="updated"&&S.type!=="removed"&&S.type!=="added"||r(S.query.queryKey)&&R()});return()=>{w(),m===T&&(m=null,b())}},flush(){return x()},async clear(){b(),m=null,g=!1,await h,await P()}}}function sL(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var XP="/kortix/part/";function ZP(e){return typeof e=="string"&&e.startsWith(XP)}async function oL(e){if(!ZP(e))throw new Error(`not an attachment part reference: ${e}`);let t=Je();if(!t)throw new Error("runtime url not bound");let n=await $(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function ex(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function iL(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function wf(e,t){return iL(e,t)?(t?ex(t):null)??ex(e):null}function Lr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function kf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var aL=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function cL(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lL(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(cL).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function uL(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function tx(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function pL(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:aL.test(n.hostname)?t.backendUrls.some(r=>{let s=uL(r);return s!==null&&tx(s)===tx(n)}):t.templates.some(r=>lL(n.origin,r))}async function nx(e,t={}){if(!Lr(e))return!1;let n=v().backendUrl;n&&await it(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return pL(e,{templates:Mh(),backendUrls:r})}async function rx(e,t={}){let n=wf(e,t.serverUrl||v().backendUrl||void 0);if(!n)return!1;let r=await Bt();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function dL(e,t={}){if(Lr(e)){if(!await nx(e,t))return e;let n=await Bt();return n?kf(e,n):e}return await rx(e,t),e}var gL=3e3;function sx(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function mL(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return sx(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function fL(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function yL(e,t){throw K("buildPresentationTemplatePdfUrl")}function hL(e,t){throw K("buildPresentationTemplateImageUrl")}function ox(e,t){return`${fL(e)}/presentation/convert-to-${t}`}async function bL(e,t,n,r){let s=ox(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,P)=>{let C=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(C),P(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let g=await p.text().catch(()=>""),y=p.statusText;try{let h=JSON.parse(g);y=String(h.error||h.detail||h.message||y)}catch{g&&(y=g)}throw new Error(`Failed to download ${e.toUpperCase()}: ${y} (HTTP ${p.status})`)}}function _L(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function PL(e){return e==="unreachable"}function xL(e){return!e||e.status===0?"unknown":e.ok&&xm(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var ix=1e4,SL={connection:"unknown",faultSinceMs:null};function wL(e,t,n,r=ix){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function ax({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Fo,c=!!t&&i-t.atMs<Bo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=No,streamFresh:!!s&&i-s.atMs<=bn,inboxFresh:!!n&&i-n.atMs<=Ko,activityFresh:!!o&&i-o.atMs<=bn}}function _n(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Af(e,t,n){if(!t)return!1;let r=_n(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=_n(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function kL(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!Af(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function AL(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(m=>!Af(m,n,s)):[],p=c.find(m=>m.state==="active")??c[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:_n(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function vL(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:m,abortLive:g}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?m:null,since:r.atMs,serverOpenTurnToken:n};let y=r?.drainedAtMs;return i&&r.pending===0&&y!=null&&!g&&!(p&&s.atMs>=y)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:y,serverOpenTurnToken:n}:null}function RL(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:m,abortFloor:g,receiptLive:y,receiptTurnId:h}=t,P=c&&!n&&s.atMs>=p,C=d&&o.atMs>=m&&(o.type==="idle"||o.atMs>=g);if(P&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:_n(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(C)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(y)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let M=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:M.source,turnId:null,since:M.atMs,serverOpenTurnToken:r}}function cx(e){let t=ax(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=kL(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=AL(e,t,s,o);return a??vL(e,t,o)??RL(e,t,c,o)}var Fo=6e4,No=45e3,bn=45e3,Ko=1e4,TL=3e3,Bo=15e3;function CL(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function IL(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function EL(e){return cx(e)}function ML(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+Fo:null,n?n.atMs+Bo:null,r?r.atMs+Ko:null,s?s.atMs+No:null,o?o.atMs+bn:null,i?i.atMs+bn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function lx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Mr({name:s.name??void 0,message:s.message})?null:s}var OL="SandboxMemoryGuard";function DL(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=lx(e,t);if(r?.message){if(r.name!==OL)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var jL=6e4;function $L(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function LL(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var ux=9e4;function UL(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+ux}var FL=75e3,NL=2,KL=2e4;function vf(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function BL(e){return e.filter(t=>t!=null).join("|")}function qL(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function GL(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...vf(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...vf(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),m={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...m,status:"exhausted"};let g=!a&&!c&&d>=r;if(!t.serverGaveUp&&!g||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return m;let y=qL(e.attempts,s);return y?{...m,status:"escalating",dispatch:y,attempts:[...e.attempts,{step:y,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...m,status:"exhausted"}}var WL={"retry-start":"retrying",restart:"restarting"};function VL(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${WL[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function HL(e){return e===1?"once":e===2?"twice":`${e} times`}function YL(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${HL(t)}`),`Tried: ${r.join(", then ")}.`}var zL={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function px(e){return!!(e.metadata??{}).legacy_migration}function JL(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return px(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function QL(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var XL={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function ZL(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function qo(e){return e.runtime_sessions??e.opencode_sessions??[]}function dx(e){let t=qo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function e0(e){let t=dx(e);return t?qo(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function t0(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>qo(r).some(s=>s.id===t))??null)}var n0=new Set;function gx(e){for(let t of[...n0])try{t(e)}catch{}}var bx={schema:ue,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var _x=e=>Object.values(e.ext??{}).find(t=>t.version===Ee),Px=e=>!!e&&_x(e)!==void 0,r0=e=>{let t=_x(e);return t?t.native_id??null:e.thread_id},mx=new WeakMap;function xx(e,t){let n=r0(e),r=mx.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Ns({...bx,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return mx.set(t,{native:n,rows:o}),o}var Rf=e=>e.info.time?.created;var s0=(e,t)=>(Rf(e)??-1/0)-(Rf(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var fx=new WeakMap,yx=new WeakMap,Sx=e=>typeof e=="object"&&e!==null,o0=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,i0=e=>e.info.role==="user"&&e.parts.some(t=>Sx(t)&&t.type==="compaction"),a0=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},hx=new WeakMap;function c0(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!Sx(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,m=hx.get(p);return m&&m.key===d?(o=!0,m.block):(hx.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function l0(e,t,n,r,s){let o=fx.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Ks({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),c=c0(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return fx.set(n,p),p}function wx(e,t,n){let r=yx.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(s0),o=new Map,i=new Set;for(let g of s){if(!i0(g))continue;let y=s.find(h=>!i.has(h)&&a0(h,g));y&&(o.set(g,y),i.add(y))}let a={tool_input:0,cut_point:0,attachment:0},c=[];for(let g of s){if(i.has(g))continue;let y=l0(e,t,g,o.get(g),c.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=y.lost[h];c.push(y.message)}let p=o0(s.map(Rf).find(g=>typeof g=="number"&&Number.isFinite(g)))??"",d=c.filter(g=>g.role==="user"&&g.kind==="turn"),m={...bx,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ue,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:c[0]?.created_at||p,messages:c,ext:{opencode:{version:Ee,native_id:t}}}]};return yx.set(n,{sessionId:e,native:t,log:m}),m}var Tf=new WeakMap,Pn=new WeakMap,kx=new WeakMap;function Go(e){let t,n=Pn.get(e);return n&&(t=u0(n).get(e.id)),t?(Tf.set(t,e),t):(e.type!=="harness"?t=Ug(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=kx.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},kx.set(e,t)),t&&Tf.set(t,e),t)}var Ur=e=>Tf.get(e),xn=e=>e.flatMap(t=>Go(t)??[]),Ax=new WeakMap;function u0(e){let t=Ax.get(e);return t||Ax.set(e,t=new Map(mt(e)[0]?.parts.map(n=>[n.id,n]))),t}var vx=new Map;function mt(e){let t=vx.get(e.thread_id);return t||(t={schema:ue,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},vx.set(e.thread_id,t)),xx(t,e)}var p0="kortix-v1-import",Ix={schema:ue,v:1};function Wo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Cf=e=>e.type==="tool_call",d0=e=>e.status==="pending"||e.status==="running",If=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function Ex(e,t){let n=If(e);return!d0(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var Rx=new WeakMap;function Mx(e,t){let n=Rx.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...Ix,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return Rx.set(e,s),s}var Tx=new WeakMap;function g0(e){let t=Tx.get(e);return t||(t={...Ix,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},Tx.set(e,t)),t}var m0=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function f0(e,t){let n=[],r=new Map;for(let a of e){if(a.role!=="user"||a.kind==="context"||r.has(a.message_id))continue;let c={user:a,assistant:[],partial:!1};r.set(a.message_id,c),n.push(c)}let s=[],o=[],i=null;for(let a of e){if(a.role==="user"){let m=r.get(a.message_id);m&&!t.has(a.message_id)&&(i=m);continue}if(a.role!=="assistant"||m0(a))continue;let p=(a.reply_to?r.get(a.reply_to):void 0)??i;if(p){p.assistant.push(a);continue}if(!a.reply_to){o.push(a);continue}let d=s[s.length-1];d&&d.user.message_id===a.reply_to?d.assistant.push(a):s.push({user:g0(a),assistant:[a],partial:!0})}if(o.length){let a=n[0]??s[0];a?a.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}return[...s,...n.filter(a=>!t.has(a.user.message_id)),...[...t].flatMap(a=>r.get(a)??[])]}function y0(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=mt(n)[0]?.info?.error??n.error.message,s=Se(r),o=br(r);return{code:n.error.code,message:s?.message||he(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function h0(e,t,n){return e.length&&e.every(t)?Lo(e.flatMap(r=>mt(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Ef(e,n)}function Ef(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return Lo(n,t)??null}function b0(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function _0(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&Cf(n)&&n.name==="bash"?n:null}function P0(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:Cf(i)?kr(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var x0=e=>e.assistant.some(t=>t.blocks.some(n=>Cf(n)&&le(n.name)==="todowrite"&&wo(n))),Cx=new WeakMap,S0=[];function Mf(e){let t=Wo(e.messages,n=>n.role==="assistant");return!!t&&Wm(mt(t))}function Vo(e,t={}){let n=new Set(t.held??S0),r=f0(e.messages,n),s=Wo(e.messages,g=>g.role==="assistant"),o=Mf(e),i=af({turns:r.map(g=>({userMessage:{info:{id:g.user.message_id}},assistantMessages:g.assistant.map(y=>({info:{time:y.status==="streaming"?{}:{completed:1},error:y.error??void 0}}))})),hintMessageId:t.liveMessageId,unrunTurnIds:n}),a=Wo(r,x0)??r[r.length-1],c=Px(e),p=g=>c||g.producer.harness===p0,d=t.threads??[],m=new Set(d.map(g=>g.thread_id));return r.map(g=>{let y=t.busy===!0&&i.workingTurnId===g.user.message_id,h=i.pendingTurnIds.includes(g.user.message_id),P=o&&g.assistant.includes(s),C=`${g.partial}|${y}|${h}|${g===a}|${P}`,M=Cx.get(g.user);if(M&&M.key===C&&M.pricing===t.pricing&&M.heads===t.threads&&M.assistant.length===g.assistant.length&&M.assistant.every((R,T)=>R===g.assistant[T]))return M.turn;let L=g.assistant.flatMap(R=>R.blocks);for(let R of g.assistant)for(let T of R.blocks)Pn.set(T,R);let f=P0(g,L,d,m),b=g.assistant[g.assistant.length-1],x={id:g.user.message_id,user:g.user,assistant:g.assistant,partial:g.partial,blocks:L,status:P?"streaming":b?b.status:g.user.kind==="compaction"?g.user.status:"pending",error:y0(g),cost:h0([g.user,...g.assistant],p,t.pricing),compaction:b0(g.user),threads:f,plan:g===a,shell:_0(g),response:Wo(L,R=>R.type==="text"&&!!R.text.trim())??null,attachments:g.user.blocks.filter(R=>R.type==="attachment"&&(R.mime.startsWith("image/")||R.mime==="application/pdf")),live:y,queued:h,retrying:P};return Cx.set(g.user,{assistant:g.assistant,key:C,pricing:t.pricing,heads:t.threads,turn:x}),x})}var Of=e=>Ur(e);function Dx(e,t={}){return rf(nf(xn(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Ur)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Of)}:n.kind==="text"?{kind:n.kind,block:Ur(n.part)}:{kind:n.kind,block:Of(n.part)})}var w0=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:xn(e.blocks)}:{kind:e.kind,part:Go(e.block)};function jx(e,t){let n=new Map(e.map(o=>[w0(o),o])),r=gf([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function k0(e){if(!re(e)||!Fg(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=Km(e);return(n.answers??mf(n.outputText??"",t.length)??[]).length>0}function $x(e){return tf(xn(e),n=>vr(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(k0)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Ur(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Of),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Pn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function Lx(e,t){return lf(xn(e.blocks).map(n=>({part:n})),t?.flatMap(mt))}function Ux(e){return zm(xn(e))}function Fx(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Go(n),s=Pn.get(n);return!!r&&ke(r)&&Do(r)&&(!s||s.status==="streaming")}):!1}var Ox=new WeakMap;function Nx(e){if(!If(e))return e;let t=Ox.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Ox.set(e,t)}return t}function A0(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Kx(e){let t=e.map(ae),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=sf(t).map(A0);return Zn({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Bx(e,t,n){let r=ae(e),s=r.state;return Zn({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function qx(e){let t=mt(e).map(r=>Ro(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}function Gx(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of Vo(e)){let s=Ef([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}function v0(e){return e==="TIMEOUT"||e==="request_deadline"}function R0(e){let t=Vx(e)?e.code:void 0;return typeof t=="string"?t:void 0}var Vx=e=>typeof e=="object"&&e!==null;function Wx(e){let t=e?.metadata;return!!Vx(t)&&t.warm===!0}var T0=5,C0=2e3,I0=e=>new Promise(t=>setTimeout(t,e));async function E0(e,{attempts:t=T0,delayMs:n=C0,sleep:r=I0}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function M0(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let m=i,g=(async()=>{let y=null;try{let h=await e.ensure(c,p);if(m!==i)return;s.has(h.sessionId)?y=h.sessionId:n.set(c,h)}catch{}finally{m===i&&r.delete(c)}y&&d>0&&await a(c,y,d-1)})();return o.add(g),g.finally(()=>o.delete(g)),g};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let m=n.get(c);return m?(n.delete(c),s.add(m.sessionId),d&&a(c,m.sessionId,1),t.fits(m,p)?m:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(m){return v0(R0(m))?E0(async()=>!Wx(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(Wx(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var O0=12e4,Ho=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},D0=1e3,j0=15e3,Hx=100,$0=50,L0=10;function Yx(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new Dr(`session ${c.status}`):new _(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function zx(e){return U0(Yx(e))}function Jx(e){return new Df({...e,loadPage:Yx(e)})}async function U0(e){let t=[],n=new Set,r;do{let i=await e({limit:Hx,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var F0={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Df=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??F0,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??O0,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Ho;if(!r&&Mr(n))return;if(r||this.update({freshness:hn(n)?"loading":"error"}),n instanceof _&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(D0*2**this.retryAttempt,j0);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?$0:Hx,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((c,p)=>{o=this.startTimer(()=>{let d=new Ho(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let m of t.messages)m.info.role==="user"&&a.add(m.info.id);for(;p&&d<L0&&i.some(m=>m.info.role==="assistant"&&!!m.info.parentID&&!a.has(m.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let m;try{m=await this.loadPage(n,r,p)}catch(g){throw o?.({messages:[...i],nextCursor:p}),g}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...m.messages);for(let g of m.messages)g.info.role==="user"&&a.add(g.info.id);p=m.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function Qx(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function Xx(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function N0(e){throw K("buildTunnelEventStreamUrl")}function K0(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,m=null,g=!1,y="";function h(f,b){o?.(f,b);let x=d.get(f);if(x)for(let R of x)try{R(b)}catch{}}async function P(){if(g)return;let f=new AbortController;m=f,p&&(p.aborted?f.abort():p.addEventListener("abort",()=>f.abort(),{once:!0}));let b=f.signal;try{let x={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(x["Content-Type"]="application/json"),y&&(x["Last-Event-ID"]=y);let R=await fetch(t,{method:r,headers:x,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:b,credentials:"include"});if(!R.ok)throw new Error(`SSE connection failed: ${R.status} ${R.statusText}`);if(!R.body)throw new Error("SSE response has no body");i?.();let T=R.body.getReader(),w=new TextDecoder,S="",I="message",k=[],U=D=>{if(D===""){k.length>0&&h(I,k.join(`
|
|
96
|
-
`)),I="message",k=[];return}if(D.startsWith(":"))return;let q=D.indexOf(":"),Q=q===-1?D:D.slice(0,q),W=q===-1?"":D.slice(q+1);W.startsWith(" ")&&(W=W.slice(1)),Q==="event"?I=W.trim()||"message":Q==="data"?k.push(W):Q==="id"&&!W.includes("\0")&&(y=W)},j=D=>{let q="";!D&&S.endsWith("\r")&&(q="\r",S=S.slice(0,-1));let Q=S.split(/\r\n|\n|\r/);S=(Q.pop()??"")+q;for(let W of Q)U(W)};for(;!g;){let{done:D,value:q}=await T.read();if(D)break;S+=w.decode(q,{stream:!0}),j(!1)}g||(S+=w.decode(),j(!0),c?.())}catch(x){if(g||x instanceof DOMException&&x.name==="AbortError")return;a?.(x instanceof Error?x:new Error(String(x)))}}function C(){g=!0,m?.abort(),m=null,d.clear()}function M(f,b){let x=d.get(f)??new Set;x.add(b),d.set(f,x)}function L(f,b){d.get(f)?.delete(b)}return{connect:P,close:C,addEventListener:M,removeEventListener:L}}function B0(e,t){throw K("createTunnelEventStream")}var Zx="/_kortix/viewer",Yo=6e4,Sn=new Map;function eS(){Sn.clear(),Fr.clear()}async function q0(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function jf(e={}){let t=e.path??Zx,n=e.fetch??((o,i)=>fetch(o,i)),r=Sn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=q0(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Yo:Date.now()+Yo;return Sn.set(t,{session:o,expiresAt:a}),o});return Sn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function tS(e={}){let t=e.path??Zx;return Object.assign(async()=>(await jf(e))?.access_token??null,{invalidate:n=>{let r=Sn.get(t);r&&!r.inflight&&r.session?.access_token===n&&Sn.delete(t)}})}var Fr=new Map;async function G0(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Fr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Yo:Date.now()+Yo}),r.token}catch{return null}}function $f(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Fr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=G0(n,r).then(a=>(a===null&&Fr.delete(n),a));return Fr.set(n,i),i}}function nS(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${de(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:$f({audience:e,fetch:t.fetch})}}var ft=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},we=e=>typeof e=="string"&&e.length>0?e:null;function rS(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function zo(e){if(!e||typeof e!="object")return null;let t=e,n=we(t.sub)??we(t.subject)??we(t.user_id)??we(t.userId);return n?{userId:n,email:we(t.email),name:we(t.name),picture:we(t.picture)??we(t.pictureUrl),groups:rS(t.groups),groupIds:rS(t.group_ids??t.groupIds),role:we(t.role),accountId:we(t.account_id)??we(t.accountId),projectId:we(t.project_id)??we(t.projectId)}:null}function oS(e,t={}){let n=zo(e);if(!n)throw new ft("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new ft("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new ft("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var W0=60,Lf=new Map;function iS(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function sS(e){return JSON.parse(new TextDecoder().decode(iS(e)))}async function V0(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=Lf.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Lf.delete(e)),Lf.set(e,n)),n}return JSON.parse(e)}async function aS(e,t={}){let n=f=>{throw new ft("unauthenticated",`Kortix sign-in token refused: ${f}.`)},r=t.jwks??st("KORTIX_AUTH_JWKS"),s=t.issuer??st("KORTIX_AUTH_ISSUER"),o=t.audience??st("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,m;try{d=sS(a),m=sS(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let g;try{g=await V0(r,t.fetch??((f,b)=>fetch(f,b)))}catch{return n("key set unavailable")}let y=(g.keys??[]).filter(f=>f.kty==="EC"&&(d.kid===void 0||f.kid===d.kid));if(y.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),P;try{P=iS(p)}catch{return n("malformed")}let C=!1;for(let f of y)try{let{kid:b,alg:x,use:R,key_ops:T,...w}=f,S=await crypto.subtle.importKey("jwk",w,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},S,P,h)){C=!0;break}}catch{}if(!C)return n("bad signature");let M=Math.floor(Date.now()/1e3);if(typeof m.exp!="number"||m.exp+W0<M)return n("expired");if(s&&m.iss!==s)return n("wrong issuer");if(o){let f=m.aud;if(!(f===o||Array.isArray(f)&&f.includes(o)))return n("wrong audience")}let L=zo(m);return L||n("no subject")}function Uf(e){let t=e.agents.map(H0),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function H0(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function Ff(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Gs(n?{...r,mode:null}:r))}function cS(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=Ff(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var lS=Uf;function uS(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Nf(e){return{providerID:"kortix",modelID:e}}function pS(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Nf(n)}var Kf=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Bf(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function z0(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function dS(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function _e(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function gS(e){return e.reduce((t,n)=>{let r=Bf(n)??0,s=Bf(t)??0;return r!==s?r>s?n:t:_e(n.id)>_e(t.id)?n:t})}function qf(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of dS(e,z0)){let a=[...dS(o,p=>p.family||p.id).values()].map(gS),c=a.filter(p=>{let d=Bf(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[gS(a)])s.add(p.id)}return s}function Jo(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>_e(r.id)>0)?n.filter(r=>_e(r.id)>0):n}function Nr(e){let t;for(let n of Jo(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&_e(n.id)>_e(t.id))&&(t=n)}return t}var J0={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function mS(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var Q0=(()=>{let e=new Map;for(let{id:n,env:r}of Kf)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>mS(o)===n)??s[0])}return t})();function fS(e){let t=J0[e.id];if(t)return t;let n=e.env??[],r=n.length===1?Q0.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[mS(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Wf(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var X0=["low","medium","high"];function yS(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...X0]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var hS=Kf;var Gf={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Qo=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...Gf,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...Gf,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...Gf,max_price:{prompt:3.3,completion:16.5}}}],v2=new Map(Qo.map(e=>[e.id,e]));var bS=Qo.map(e=>e.id),_S=(Qo.find(e=>e.tier==="flagship")??Qo[0]).id,PS="deepseek-v4.1-flash";var SS=hS.map(e=>({id:e.id,authRequirement:fS(e)})),Kr=new Set(["kortix"]),Vf=new Set(["kortix"]);function wn(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function Z0(e){if(!e)return!1;let t=wn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function eU(e){let t=wn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!Vf.has(s.id)),connected:r.filter(s=>!Vf.has(s))}}function tU(e,t,n){let r=wn(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&Wf(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var nU=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function rU(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var Hf="opencode";function sU(e){return e.cost?.input===0&&e.cost?.output===0}function xS(e){return e===Hf?Number.MAX_SAFE_INTEGER:nU.get(e)??Number.MAX_SAFE_INTEGER-1}function oU(e,t){let n=aU(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Hf&&!n.has(Hf)?{...o,models:i.filter(sU),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!Vf.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>xS(o.id)-xS(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||_e(p.id)-_e(c.id)),a=Nr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=rU(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function iU(e,t){if(!e)return t;if(!t)return e;let n=wn(e),r=wn(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,m]of Object.entries(n.default??{})){let g=s.get(d);(!g||g.models&&m in g.models)&&(p[d]=m)}return{...r,all:o,connected:a,default:p}}function aU(e){let t=new Set;for(let n of SS)Wf(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function cU(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=yS({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function lU(e,t){return eU(tU(wn(e),t,SS))}function wS(e){if(e.gatewayEnabled)return e.modelPicker?cU(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?lU(e.runtimeProviders,t):void 0;return iU(e.llmCatalogProviders?oU(e.llmCatalogProviders,t):void 0,Z0(n)?n:void 0)}function uU(e){return"capabilities"in e&&e.capabilities!=null}function Xo(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function kS(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!Kr.has(i.id):Kr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(uU(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:uS({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function AS(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var pU=new Set([_S]),dU="kortix",vS="codex",gU=new Set(bS);function mU(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function kn(e){return pU.has(e.modelID)}function fU(e){return qf(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function RS(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=fU(e.catalogModels),s=AS(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===dU){let d=mU(i.modelID,i.provider),m=d===vS?t?.has(vS)??!1:t?.has(d)??!1;if(gU.has(i.modelID))return!n||i.modelID===PS;if(!m)return!1;if(c==="show"||r.has(a))return!0;let g=s.get(a);if(!g?.releaseDate)return kn(i);try{let y=new Date(g.releaseDate);if(Number.isNaN(y.getTime()))return kn(i)}catch{return kn(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return kn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return kn(i)}catch{return kn(i)}return!1}}function TS(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function CS(e,t){if(!e||Kr.has(e.providerID)||_e(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>_e(i.modelID)>0))return e;let r=i=>_e(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Nr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function IS(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Nf(n):void 0}function ES(e){let{models:t,providers:n}=e,r=c=>Xo(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,m=d.join("/");if(r({providerID:p,modelID:m}))return{providerID:p,modelID:m}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],m=p.filter(g=>d.includes(g.id));for(let g of m){let y=c[g.id];if(y){let h={providerID:g.id,modelID:y};if(r(h))return h}for(let h of Jo(Object.keys(g.models).map(P=>({id:P})))){let P={providerID:g.id,modelID:h.id};if(r(P))return P}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:CS(a,t),explicit:i,fallback:o}}return US(yU);})();
|
|
96
|
+
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function zL(e){let t=Lo(e.input),n=t.map(([s,o])=>HL(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:dy(e),diff:r}}var LS=/^Found\s+(\d+)\s+match/i,YL=/^(\/[^:]+?):\s*/,jS=/Line\s+(\d+):/g;function JL(e){let t=e.trim(),n=t.match(LS),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(YL);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(jS.lastIndex=0;(g=jS.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function QL(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function XL(e){let t=se(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=LS.test(e.output.trim())?JL(e.output):QL(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function ZL(e){let t=se(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=se(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function uy(e){let t=Pn(e)??{};return{content:se(t.content)??"",status:se(t.status)??"pending",priority:se(t.priority)}}function e$(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(uy)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(uy)};let n=Pn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(uy)}:{kind:"todo",items:[]}}function t$(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Pn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=Pn(a),p=c&&se(c.label);return p?[{label:p,description:c?se(c.description):void 0}]:[]});return{question:se(s.question)??"",header:se(s.header),options:i}})}}function n$(e){let n=e.input&&Object.keys(e.input).length>0?DS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Nr(e.outputParsed):DS(e.outputParsed):e.outputText!==void 0?r=Nr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function $S(e){switch(ue(e.name)){case"web_search":return LL(e);case"bash":return qL(e);case"read":return GL(e);case"write":return WL(e);case"edit":return zL(e);case"grep":case"glob":return XL(e);case"task":return ZL(e);case"todowrite":return e$(e);case"question":return t$(e);default:return n$(e)}}var r$=new Set(["AbortError","MessageAbortedError"]),s$=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],o$=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function US(e){let t=e.toLowerCase();return o$.some(n=>t.includes(n))?!1:s$.some(n=>t.includes(n))}function i$(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Br(e){if(typeof e=="string")return US(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&r$.has(n))return!0;let r=i$(t);return typeof r=="string"?US(r):!1}var FS=["user","runtime-disposed","orphan-finalized","wake"],a$=["orphan-finalized","wake"];function c$(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return FS.includes(n)?n:void 0}var Kr="kortix-active-instance",NS=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function BS(e){return NS.some(t=>e===t||e.startsWith(`${t}/`))}function wn(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function l$(e){let t=wn(e);return!!t&&t.innerPath===""}function u$(e){let t=wn(e);return!t||!t.innerPath?e:t.innerPath}function KS(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=wn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return BS(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function qS(e){return e?wn(e)?.instanceId??null:null}function p$(){return typeof window>"u"?null:qS(window.location.pathname)||GS()}function GS(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Kr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function d$(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Kr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function g$(e,t){return t?KS(t,e):e}function m$(e){let t=wn(e);return t?t.innerPath||"/dashboard":e}function Gr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function gy(e){let t=Gr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var f$=gy;function Xo(e){let t=gy(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var y$=Xo;function WS(e){return Xo(e)!==null}var h$=WS,_$=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],b$=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],x$=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function VS(e){return x$.test(Gr(e))}function kn(e){let t=Gr(e);return t?VS(t)||_$.some(n=>n.test(t)):!1}var S$=/server url not ready|sandbox is still loading/i;function P$(e){return S$.test(Gr(e))||kn(e)}var qr=class extends Error{constructor(t){let n=t?.trim();super(n&&kn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function HS(e){let t=Xo(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Gr(e);return kn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var w$=HS;function my(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${ct()}/p/${e.external_id}/${Ye.KORTIX_MASTER}`}function k$(e,t){return e.external_id?`${ct()}/p/${e.external_id}/${t}`:null}async function v$(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function zS(e){let t=await ur();if(t)return{sandbox:t.sandbox,created:!1};let r=(await vt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await It(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await ot(r.project_id,s.session_id))?.sandbox??null;return{sandbox:no(r,s,o),created:!0}}async function A$(){return(await ur().catch(()=>null))?.sandbox??null}async function R$(e){return{sandbox:(await zS(e)).sandbox}}async function C$(e){let t=lr(e);if(!t)return null;try{let n=await xm(t);return n?no(await At(n.project_id),n,null):(await ur(t))?.sandbox??null}catch{return null}}async function T$(e,t){throw await ro(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function I$(e){let t=lr(e);return(await bm().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function E$(){return null}async function M$(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ro(e);if(!t)throw new Error("Project session sandbox not found");await Xn(t.projectId,t.sessionId)}async function O$(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ro(e);if(!t)throw new Error("Project session sandbox not found");await Zn(t.projectId,t.sessionId)}async function D$(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function j$(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function fy(e,t,n){let r=my(e),s=await L(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function L$(e,t){return fy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function $$(e,t,n,r="member"){await fy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function U$(e,t,n){await fy(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var yy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function F$(e){throw F("getInvite",yy)}async function N$(e){throw F("acceptInvite",yy)}async function B$(e){throw F("declineInvite",yy)}async function K$(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function q$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function G$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function W$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function V$(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function H$(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var YS=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function z$(e){return YS.includes(e)}async function Y$(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function J$(e){let t=e?`?channel=${e}`:"",r=await(await Ne(`${ct()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await JS(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function JS(e){let t=e?`?channel=${e}`:"";return(await(await Ne(`${ct()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function Q$(){return(await Ne(`${ct()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function X$(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function Z$(e){}async function e0(e){}async function t0(e){return{serverTypes:[],location:e||"hel1"}}async function n0(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function r0(e){throw F("deleteInstance")}async function s0(e,t){}async function o0(){throw F("claimComputer")}async function i0(e){return null}function a0(e,t){throw F("getSandboxProvisionStreamUrl")}var Wr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function QS(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function XS(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function ZS(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function ne(e,t,n){let r=n?.body!==void 0,s=await fetch(`${Et(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:QS(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await XS(s);if(!s.ok)throw new Wr(ZS(s,o),s.status,o);return o}function c0(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function l0(e,t){return ne(`/marketplace/items${c0(t)}`,e)}function u0(e){return ne("/marketplace/marketplaces",e)}function p0(e,t){return ne(`/marketplace/items/${encodeURIComponent(e)}`,t)}function d0(e,t,n){return ne(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function g0(e,t){return ne("/access/check-email",t,{method:"POST",body:{email:e}})}function m0(e,t){return ne("/access/request-access",t,{method:"POST",body:e})}function f0(e){return ne("/auth/logout",e,{method:"POST",body:{}})}function y0(e,t){return ne(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function h0(e,t){return ne("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function _0(e,t){return ne(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function b0(e,t){return ne(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function x0(e,t,n={}){return ne(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function S0(e,t){return ne(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function P0(e,t,n,r){return ne(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function w0(e,t){return ne(`/p/public-share/${encodeURIComponent(e)}`,t)}function k0(e,t,n){return ne(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function v0(e){return ne("/system/maintenance",e)}function A0(e,t){return ne("/system/maintenance",t,{method:"PUT",body:e})}function R0(e){return ne("/user-roles",e)}function C0(e,t){return ne("/system/demo-request",t,{method:"POST",body:e})}async function T0(e,t,n){let r=await fetch(`${Et(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Jt(t)}`,{headers:QS(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await XS(r);throw new Wr(ZS(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function I0(e,t){throw F("openStressTestStream")}function E0(e,t){throw F("buildPublicTemplateUrl")}async function M0(e,t,n){throw F("getPublicTemplate")}var O0="kortix:connect-link:";function hy(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${O0}${t.toString(36)}${n.toString(36)}`}function D0(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(hy(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(hy(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(hy(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var eP="Could not start the connect flow.";async function j0(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:eP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:eP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var tP=3e3,nP=5e3,rP=5*6e4;function L0(e,t){let n=e===0?tP:nP;return t+n>rP?null:n}function $0(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function U0(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function F0(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function N0(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function B0(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function K0(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var I2="1";var q0="kortix.query-cache";function oP(e){return!!e&&typeof e.then=="function"}function sP(e){return oP(e)?e:Promise.resolve()}function G0(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function W0(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=q0,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),_=()=>{try{return sP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},I=(k,x)=>{if(!x)return 0;let P;try{P=JSON.parse(x)}catch{return _(),0}if(!P||P.v!==s||P.user!==n||!Array.isArray(P.queries)||p()-P.at>o)return _(),0;let O=0;for(let v of P.queries){if(!v||!Array.isArray(v.k)||v.d===void 0||typeof v.t!="number"||p()-v.t>o||!r(v.k))continue;let $=k.getQueryState(v.k);$&&$.data!==void 0&&$.dataUpdatedAt>=v.t||(k.setQueryData(v.k,v.d,{updatedAt:v.t}),k.invalidateQueries?.({queryKey:v.k,exact:!0,refetchType:"none"}),O+=1)}return O},j=k=>k.getQueryCache().getAll().filter(x=>x.state.data!==void 0&&r(x.queryKey)).map(x=>({k:x.queryKey,d:x.state.data,t:x.state.dataUpdatedAt})).sort((x,P)=>P.t-x.t),D=(k,x)=>{let P=[],O=0;for(let v of k){let $=JSON.stringify(v).length+1;O+$>x||(P.push(v),O+=$)}return P},w=async k=>{let x=D(j(k),i);for(;;){let P={v:s,user:n,at:p(),queries:x};try{await sP(t.setItem(d,JSON.stringify(P)));return}catch{if(x.length===0)return;x=x.slice(0,Math.floor(x.length/2))}}},y=()=>{f!==null&&(clearTimeout(f),f=null)},b=()=>{y();let k=g;return!k||!m||(m=!1,h=h.then(()=>w(k)).catch(()=>{})),h},R=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,b()},a))};return{storageKey:d,restore(k){let x;try{x=t.getItem(d)}catch{return 0}return oP(x)?x.then(P=>I(k,P)).catch(()=>0):I(k,x)},persist(k){g=k,m=!0;let x=k.getQueryCache().subscribe(P=>{P.type!=="updated"&&P.type!=="removed"&&P.type!=="added"||r(P.query.queryKey)&&R()});return()=>{x(),g===k&&(g=null,y())}},flush(){return b()},async clear(){y(),g=null,m=!1,await h,await _()}}}function V0(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var iP="/kortix/part/";function aP(e){return typeof e=="string"&&e.startsWith(iP)}async function H0(e){if(!aP(e))throw new Error(`not an attachment part reference: ${e}`);let t=Qe();if(!t)throw new Error("runtime url not bound");let n=await L(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function cP(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function z0(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function _y(e,t){return z0(e,t)?(t?cP(t):null)??cP(e):null}function Vr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function by(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var Y0=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function J0(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Q0(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(J0).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function X0(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function lP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function Z0(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:Y0.test(n.hostname)?t.backendUrls.some(r=>{let s=X0(r);return s!==null&&lP(s)===lP(n)}):t.templates.some(r=>Q0(n.origin,r))}async function uP(e,t={}){if(!Vr(e))return!1;let n=C().backendUrl;n&&await lt(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return Z0(e,{templates:L_(),backendUrls:r})}async function pP(e,t={}){let n=_y(e,t.serverUrl||C().backendUrl||void 0);if(!n)return!1;let r=await Wt();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function eU(e,t={}){if(Vr(e)){if(!await uP(e,t))return e;let n=await Wt();return n?by(e,n):e}return await pP(e,t),e}var tU=3e3;function dP(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function nU(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return dP(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function rU(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function sU(e,t){throw F("buildPresentationTemplatePdfUrl")}function oU(e,t){throw F("buildPresentationTemplateImageUrl")}function gP(e,t){return`${rU(e)}/presentation/convert-to-${t}`}async function iU(e,t,n,r){let s=gP(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,_)=>{let I=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(I),_(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function aU(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function cU(e){return e==="unreachable"}function lU(e){return!e||e.status===0?"unknown":e.ok&&Gm(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var mP=1e4,uU={connection:"unknown",faultSinceMs:null};function pU(e,t,n,r=mP){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function fP({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Zo,c=!!t&&i-t.atMs<ni;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=ei,streamFresh:!!s&&i-s.atMs<=vn,inboxFresh:!!n&&i-n.atMs<=ti,activityFresh:!!o&&i-o.atMs<=vn}}function An(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function xy(e,t,n){if(!t)return!1;let r=An(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=An(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function dU(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!xy(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function gU(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!xy(g,n,s)):[],p=c.find(g=>g.state==="active")??c[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:An(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function mU(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function fU(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,_=c&&!n&&s.atMs>=p,I=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(_&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:An(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(I)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let j=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:j.source,turnId:null,since:j.atMs,serverOpenTurnToken:r}}function yP(e){let t=fP(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=dU(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=gU(e,t,s,o);return a??mU(e,t,o)??fU(e,t,c,o)}var Zo=6e4,ei=45e3,vn=45e3,ti=1e4,yU=3e3,ni=15e3;function hU(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function _U(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function bU(e){return yP(e)}function xU(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+Zo:null,n?n.atMs+ni:null,r?r.atMs+ti:null,s?s.atMs+ei:null,o?o.atMs+vn:null,i?i.atMs+vn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function hP(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Br({name:s.name??void 0,message:s.message})?null:s}var SU="SandboxMemoryGuard";function PU(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=hP(e,t);if(r?.message){if(r.name!==SU)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var wU=6e4;function kU(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function vU(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var _P=9e4;function AU(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+_P}var RU=75e3,CU=2,TU=2e4;function Sy(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function IU(e){return e.filter(t=>t!=null).join("|")}function EU(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function MU(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Sy(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Sy(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=EU(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var OU={"retry-start":"retrying",restart:"restarting"};function DU(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${OU[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function jU(e){return e===1?"once":e===2?"twice":`${e} times`}function LU(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${jU(t)}`),`Tried: ${r.join(", then ")}.`}var $U={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function bP(e){return!!(e.metadata??{}).legacy_migration}function UU(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return bP(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function FU(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var NU={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function BU(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ri(e){return e.runtime_sessions??e.opencode_sessions??[]}function xP(e){let t=ri(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function KU(e){let t=xP(e);return t?ri(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function qU(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>ri(r).some(s=>s.id===t))??null)}var GU=new Set;function SP(e){for(let t of[...GU])try{t(e)}catch{}}var AP={schema:pe,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var RP=e=>Object.values(e.ext??{}).find(t=>t.version===Ae),CP=e=>!!e&&RP(e)!==void 0,WU=e=>{let t=RP(e);return t?t.native_id??null:e.thread_id},PP=new WeakMap;function TP(e,t){let n=WU(e),r=PP.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Qs({...AP,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return PP.set(t,{native:n,rows:o}),o}var Py=e=>e.info.time?.created;var VU=(e,t)=>(Py(e)??-1/0)-(Py(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var wP=new WeakMap,kP=new WeakMap,IP=e=>typeof e=="object"&&e!==null,HU=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,zU=e=>e.info.role==="user"&&e.parts.some(t=>IP(t)&&t.type==="compaction"),YU=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},vP=new WeakMap;function JU(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!IP(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,g=vP.get(p);return g&&g.key===d?(o=!0,g.block):(vP.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function QU(e){let t=new Map,n=new Set;for(let r of e){if(!zU(r))continue;let s=e.find(o=>!n.has(o)&&YU(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function XU(e,t,n,r,s){let o=wP.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Xs({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),c=JU(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return wP.set(n,p),p}function EP(e,t,n){let r=kP.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(VU),{paired:o,used:i}=QU(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=XU(e,t,m,o.get(m),c.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];c.push(f.message)}let p=HU(s.map(Py).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...AP,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:pe,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:c[0]?.created_at||p,messages:c,ext:{opencode:{version:Ae,native_id:t}}}]};return kP.set(n,{sessionId:e,native:t,log:g}),g}var wy=new WeakMap,Rn=new WeakMap,MP=new WeakMap;function si(e){let t,n=Rn.get(e);return n&&(t=ZU(n).get(e.id)),t?(wy.set(t,e),t):(e.type!=="harness"?t=am(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=MP.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},MP.set(e,t)),t&&wy.set(t,e),t)}var Hr=e=>wy.get(e),Ut=e=>e.flatMap(t=>si(t)??[]),OP=new WeakMap;function ZU(e){let t=OP.get(e);return t||OP.set(e,t=new Map(ht(e)[0]?.parts.map(n=>[n.id,n]))),t}var DP=new Map;function ht(e){let t=DP.get(e.thread_id);return t||(t={schema:pe,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},DP.set(e.thread_id,t)),TP(t,e)}var eF="kortix-v1-import",ky={schema:pe,v:1};function oi(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var vy=e=>e.type==="tool_call",tF=e=>e.status==="pending"||e.status==="running",Ay=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function NP(e,t){let n=Ay(e);return!tF(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var jP=new WeakMap;function BP(e,t){let n=jP.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...ky,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return jP.set(e,s),s}var LP=new WeakMap;function nF(e){let t=LP.get(e);return t||(t={...ky,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},LP.set(e,t)),t}var $P=new WeakMap;function rF(e){let t=$P.get(e);return t||(t={...ky,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},$P.set(e,t)),t}var sF=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function oF(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,c=null,p=null;for(let g of e){if(g.role==="user"){let _=r.get(g.message_id);_&&!t.has(g.message_id)&&(c=_,i.has(_)||i.set(_,i.size),_.user.kind==="compaction"&&(p=_));continue}if(g.role!=="assistant"||sF(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let _=a.get(p);_||(_={user:rF(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,_)),f=_}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:nF(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function iF(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function aF(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=ht(n)[0]?.info?.error??n.error.message,s=we(r),o=Rr(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function cF(e,t,n){return e.length&&e.every(t)?Qo(e.flatMap(r=>ht(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Ry(e,n)}function Ry(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return Qo(n,t)??null}function lF(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function uF(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&vy(n)&&n.name==="bash"?n:null}function pF(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:vy(i)?Or(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var dF=e=>e.assistant.some(t=>t.blocks.some(n=>vy(n)&&ue(n.name)==="todowrite"&&_n(n))),UP=new WeakMap,gF=[];function Cy(e){let t=oi(e.messages,n=>n.role==="assistant");return!!t&&qf(ht(t))}var FP=new WeakMap;function mF(e){let t=FP.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},FP.set(e,t)}return t}function ii(e,t={}){let n=t.hideOutOfContext?mF(e):e,r=new Set(t.held??gF),s=oF(n.messages,r),o=oi(n.messages,f=>f.role==="assistant"),i=Cy(n),a=ny({turns:s.map(f=>({userMessage:{info:{id:f.user.message_id}},assistantMessages:f.assistant.map(h=>({info:{time:h.status==="streaming"?{}:{completed:1},error:h.error??void 0}}))})),hintMessageId:iF(s,t.liveMessageId),unrunTurnIds:r}),c=oi(s,dF)??s[s.length-1],p=CP(n),d=f=>p||f.producer.harness===eF,g=t.threads??[],m=new Set(g.map(f=>f.thread_id));return s.map(f=>{let h=t.busy===!0&&a.workingTurnId===f.user.message_id,_=a.pendingTurnIds.includes(f.user.message_id),I=i&&f.assistant.includes(o),j=`${f.partial}|${h}|${_}|${f===c}|${I}`,D=UP.get(f.user);if(D&&D.key===j&&D.pricing===t.pricing&&D.heads===t.threads&&D.assistant.length===f.assistant.length&&D.assistant.every((k,x)=>k===f.assistant[x]))return D.turn;let w=f.assistant.flatMap(k=>k.blocks);for(let k of f.assistant)for(let x of k.blocks)Rn.set(x,k);let y=pF(f,w,g,m),b=f.assistant[f.assistant.length-1],R={id:f.user.message_id,user:f.user,assistant:f.assistant,partial:f.partial,continues:f.continues??null,blocks:w,status:I?"streaming":b?b.status:f.user.kind==="compaction"?f.user.status:"pending",error:aF(f),cost:cF([f.user,...f.assistant],d,t.pricing),compaction:lF(f.user),threads:y,plan:f===c,shell:uF(f),response:oi(w,k=>k.type==="text"&&!!k.text.trim())??null,attachments:f.user.blocks.filter(k=>k.type==="attachment"&&(k.mime.startsWith("image/")||k.mime==="application/pdf")),live:h,queued:_,retrying:I};return UP.set(f.user,{assistant:f.assistant,key:j,pricing:t.pricing,heads:t.threads,turn:R}),R})}var Ty=e=>Hr(e);function WP(e,t={}){return Zf(Xf(Ut(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Hr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Ty)}:n.kind==="text"?{kind:n.kind,block:Hr(n.part)}:{kind:n.kind,block:Ty(n.part)})}var fF=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ut(e.blocks)}:{kind:e.kind,part:si(e.block)};function VP(e,t){let n=new Map(e.map(o=>[fF(o),o])),r=cy([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function yF(e){if(!te(e)||!cm(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=Ff(e);return(n.answers??ly(n.outputText??"",t.length)??[]).length>0}function HP(e){return Qf(Ut(e),n=>Sn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(yF)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Hr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Ty),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Rn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function zP(e,t){return sy(Ut(e.blocks).map(n=>({part:n})),t?.flatMap(ht))}function YP(e){return Ho(Ut(e))}function JP(e){return Yf(Ut(e))}function QP(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=si(n),s=Rn.get(n);return!!r&&ve(r)&&zo(r)&&(!s||s.status==="streaming")}):!1}var KP=new WeakMap;function XP(e){if(!Ay(e))return e;let t=KP.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},KP.set(e,t)}return t}function hF(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function ZP(e){let t=e.map(ce),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=ey(t).map(hF);return ar({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function ew(e,t,n){let r=ce(e),s=r.state;return ar({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function tw(e){let t=ht(e).map(r=>No(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var qP=Object.freeze([]),GP=new WeakMap;function nw(e){if(!e)return qP;let t=GP.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&_n(s)):[]);t=n.length?n:qP,GP.set(e,t)}return t}function rw(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ii(e)){let s=Ry([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var _F="prt_kortix_restore_g";function ow(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(_F))}function iw(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(c=>c.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var Iy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,bF=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function aw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Iy(t)?t.restore:void 0;if(!Iy(n))return null;let r=Iy(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:nt(r.message)},{kind:"attachment",count:nt(s?.attachment)},{kind:"text",count:nt(r.text)+nt(n.truncated)},{kind:"tool_input",count:nt(s?.tool_input)},{kind:"tool_result",count:nt(r.tool_result)},{kind:"cut_point",count:nt(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,c])=>bF.has(a)?i:i+nt(c),0)}];return{generation:nt(n.generation),missing:o.filter(i=>i.count>0)}}var cw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function lw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of cw(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var uw=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},xF=(e,t)=>e.map(n=>n.type==="text"?uw(n,t):n),sw=new WeakMap;function SF(e,t){let n=sw.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>cw(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?uw(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:xF(s.result.content,t)}}:s)}:e;return sw.set(e,{texts:t,out:r}),r}var ai=1024*1024;function pw(e){return e.reduce((t,n)=>t+n.bytes,0)>ai?"download":"inline"}function dw(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>ai)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function gw(e,t){if(t.size===0)return e;let n=e.messages.map(r=>SF(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function PF(e){return e==="TIMEOUT"||e==="request_deadline"}function wF(e){let t=fw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var fw=e=>typeof e=="object"&&e!==null;function mw(e){let t=e?.metadata;return!!fw(t)&&t.warm===!0}var kF=5,vF=2e3,AF=e=>new Promise(t=>setTimeout(t,e));async function RF(e,{attempts:t=kF,delayMs:n=vF,sleep:r=AF}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function CF(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(c,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return PF(wF(g))?RF(async()=>!mw(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(mw(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var TF=12e4,ci=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},IF=1e3,EF=15e3,yw=100,MF=50,OF=10;function hw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new qr(`session ${c.status}`):new S(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function _w(e){return DF(hw(e))}function bw(e){return new Ey({...e,loadPage:hw(e)})}async function DF(e){let t=[],n=new Set,r;do{let i=await e({limit:yw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var jF={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Ey=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??jF,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??TF,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ci;if(!r&&Br(n))return;if(r||this.update({freshness:kn(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(IF*2**this.retryAttempt,EF);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?MF:yw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((c,p)=>{o=this.startTimer(()=>{let d=new ci(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<OF&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var LF=5e3,Sw=40,CQ=5*6e4,$F=16,zr=new Map;function Pw(e,t,n,r=Date.now()){let s=ww(e,t);for(zr.delete(s),zr.set(s,{envelope:n,atMs:r});zr.size>$F;){let o=zr.keys().next().value;if(o===void 0)break;zr.delete(o)}}var xw=new Map;function ww(e,t){return`${e}/${t}`}function UF(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=LF}function kw(e,t,n=Date.now()){if(!e||!t)return null;let r=ww(e,t),s=xw.get(r);return s?UF(s,n)?s.promise:(xw.delete(r),null):null}function vw(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var FF=2e3;async function NF(e,t,n){let r=kw(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??FF,null)})]).finally(()=>clearTimeout(s)):null;return(o&&vw(o))??Yn(e,t,{limit:Sw,history:!0,signal:n.signal})}async function Aw(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s;try{s=await NF(t,n,{})}catch{return{envelope:null,empty:!1}}if(Pw(t,n,s),My(s)!==r)return{envelope:s,empty:!1};try{let o=await Jn(t,n);return{envelope:s,empty:Oy({savedEmptyRoot:r,rootSessionId:r,turnRead:!0,hasEndedTurn:o.last_ended!=null,hasOpenOrQueuedTurn:o.turns.length>0})}}catch{return{envelope:s,empty:!1}}}function My(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function Oy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function BF(e){throw F("buildTunnelEventStreamUrl")}function KF(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(w,y){o?.(w,y);let b=d.get(w);if(b)for(let R of b)try{R(y)}catch{}}async function _(){if(m)return;let w=new AbortController;g=w,p&&(p.aborted?w.abort():p.addEventListener("abort",()=>w.abort(),{once:!0}));let y=w.signal;try{let b={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(b["Content-Type"]="application/json"),f&&(b["Last-Event-ID"]=f);let R=await fetch(t,{method:r,headers:b,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:y,credentials:"include"});if(!R.ok)throw new Error(`SSE connection failed: ${R.status} ${R.statusText}`);if(!R.body)throw new Error("SSE response has no body");i?.();let k=R.body.getReader(),x=new TextDecoder,P="",O="message",v=[],$=T=>{if(T===""){v.length>0&&h(O,v.join(`
|
|
98
|
+
`)),O="message",v=[];return}if(T.startsWith(":"))return;let q=T.indexOf(":"),G=q===-1?T:T.slice(0,q),V=q===-1?"":T.slice(q+1);V.startsWith(" ")&&(V=V.slice(1)),G==="event"?O=V.trim()||"message":G==="data"?v.push(V):G==="id"&&!V.includes("\0")&&(f=V)},K=T=>{let q="";!T&&P.endsWith("\r")&&(q="\r",P=P.slice(0,-1));let G=P.split(/\r\n|\n|\r/);P=(G.pop()??"")+q;for(let V of G)$(V)};for(;!m;){let{done:T,value:q}=await k.read();if(T)break;P+=x.decode(q,{stream:!0}),K(!1)}m||(P+=x.decode(),K(!0),c?.())}catch(b){if(m||b instanceof DOMException&&b.name==="AbortError")return;a?.(b instanceof Error?b:new Error(String(b)))}}function I(){m=!0,g?.abort(),g=null,d.clear()}function j(w,y){let b=d.get(w)??new Set;b.add(y),d.set(w,b)}function D(w,y){d.get(w)?.delete(y)}return{connect:_,close:I,addEventListener:j,removeEventListener:D}}function qF(e,t){throw F("createTunnelEventStream")}var Rw="/_kortix/viewer",li=6e4,Cn=new Map;function Cw(){Cn.clear(),Yr.clear()}async function GF(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function Dy(e={}){let t=e.path??Rw,n=e.fetch??((o,i)=>fetch(o,i)),r=Cn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=GF(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-li:Date.now()+li;return Cn.set(t,{session:o,expiresAt:a}),o});return Cn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Tw(e={}){let t=e.path??Rw;return Object.assign(async()=>(await Dy(e))?.access_token??null,{invalidate:n=>{let r=Cn.get(t);r&&!r.inflight&&r.session?.access_token===n&&Cn.delete(t)}})}var Yr=new Map;async function WF(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Yr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-li:Date.now()+li}),r.token}catch{return null}}function jy(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Yr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=WF(n,r).then(a=>(a===null&&Yr.delete(n),a));return Yr.set(n,i),i}}function Iw(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${de(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:jy({audience:e,fetch:t.fetch})}}var _t=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},ke=e=>typeof e=="string"&&e.length>0?e:null;function Ew(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function ui(e){if(!e||typeof e!="object")return null;let t=e,n=ke(t.sub)??ke(t.subject)??ke(t.user_id)??ke(t.userId);return n?{userId:n,email:ke(t.email),name:ke(t.name),picture:ke(t.picture)??ke(t.pictureUrl),groups:Ew(t.groups),groupIds:Ew(t.group_ids??t.groupIds),role:ke(t.role),accountId:ke(t.account_id)??ke(t.accountId),projectId:ke(t.project_id)??ke(t.projectId)}:null}function Ow(e,t={}){let n=ui(e);if(!n)throw new _t("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new _t("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new _t("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var VF=60,Ly=new Map;function Dw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function Mw(e){return JSON.parse(new TextDecoder().decode(Dw(e)))}async function HF(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=Ly.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Ly.delete(e)),Ly.set(e,n)),n}return JSON.parse(e)}async function jw(e,t={}){let n=w=>{throw new _t("unauthenticated",`Kortix sign-in token refused: ${w}.`)},r=t.jwks??at("KORTIX_AUTH_JWKS"),s=t.issuer??at("KORTIX_AUTH_ISSUER"),o=t.audience??at("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=Mw(a),g=Mw(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await HF(r,t.fetch??((w,y)=>fetch(w,y)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(w=>w.kty==="EC"&&(d.kid===void 0||w.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),_;try{_=Dw(p)}catch{return n("malformed")}let I=!1;for(let w of f)try{let{kid:y,alg:b,use:R,key_ops:k,...x}=w,P=await crypto.subtle.importKey("jwk",x,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},P,_,h)){I=!0;break}}catch{}if(!I)return n("bad signature");let j=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+VF<j)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let w=g.aud;if(!(w===o||Array.isArray(w)&&w.includes(o)))return n("wrong audience")}let D=ui(g);return D||n("no subject")}function $y(e){let t=e.agents.map(zF),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function zF(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function Uy(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>to(n?{...r,mode:null}:r))}function Lw(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=Uy(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var $w=$y;function Uw(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Fy(e){return{providerID:"kortix",modelID:e}}function pi(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Fy(n)}var Ny=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function By(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function JF(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Fw(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function xe(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Nw(e){return e.reduce((t,n)=>{let r=By(n)??0,s=By(t)??0;return r!==s?r>s?n:t:xe(n.id)>xe(t.id)?n:t})}function Ky(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of Fw(e,JF)){let a=[...Fw(o,p=>p.family||p.id).values()].map(Nw),c=a.filter(p=>{let d=By(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[Nw(a)])s.add(p.id)}return s}function di(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>xe(r.id)>0)?n.filter(r=>xe(r.id)>0):n}function Jr(e){let t;for(let n of di(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&xe(n.id)>xe(t.id))&&(t=n)}return t}var QF={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Bw(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var XF=(()=>{let e=new Map;for(let{id:n,env:r}of Ny)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Bw(o)===n)??s[0])}return t})();function Kw(e){let t=QF[e.id];if(t)return t;let n=e.env??[],r=n.length===1?XF.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Bw(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Gy(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var ZF=["low","medium","high"];function qw(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...ZF]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Gw=Ny;var qy={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var gi=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...qy,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...qy,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...qy,max_price:{prompt:3.3,completion:16.5}}}],HQ=new Map(gi.map(e=>[e.id,e]));var Ww=gi.map(e=>e.id),Vw=(gi.find(e=>e.tier==="flagship")??gi[0]).id,Hw="deepseek-v4.1-flash";var Yw=Gw.map(e=>({id:e.id,authRequirement:Kw(e)})),Qr=new Set(["kortix"]),Wy=new Set(["kortix"]);function Tn(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function eN(e){if(!e)return!1;let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function tN(e){let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!Wy.has(s.id)),connected:r.filter(s=>!Wy.has(s))}}function nN(e,t,n){let r=Tn(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&Gy(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var rN=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function sN(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var Vy="opencode";function oN(e){return e.cost?.input===0&&e.cost?.output===0}function zw(e){return e===Vy?Number.MAX_SAFE_INTEGER:rN.get(e)??Number.MAX_SAFE_INTEGER-1}function iN(e,t){let n=cN(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Vy&&!n.has(Vy)?{...o,models:i.filter(oN),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!Wy.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>zw(o.id)-zw(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||xe(p.id)-xe(c.id)),a=Jr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=sN(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function aN(e,t){if(!e)return t;if(!t)return e;let n=Tn(e),r=Tn(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function cN(e){let t=new Set;for(let n of Yw)Gy(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function lN(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=qw({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function uN(e,t){return tN(nN(Tn(e),t,Yw))}function Jw(e){if(e.gatewayEnabled)return e.modelPicker?lN(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?uN(e.runtimeProviders,t):void 0;return aN(e.llmCatalogProviders?iN(e.llmCatalogProviders,t):void 0,eN(n)?n:void 0)}function pN(e){return"capabilities"in e&&e.capabilities!=null}function mi(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Qw(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!Qr.has(i.id):Qr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(pN(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:Uw({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function Xw(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var dN=new Set([Vw]),gN="kortix",Zw="codex",mN=new Set(Ww);function fN(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function In(e){return dN.has(e.modelID)}function yN(e){return Ky(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function ek(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=yN(e.catalogModels),s=Xw(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===gN){let d=fN(i.modelID,i.provider),g=d===Zw?t?.has(Zw)??!1:t?.has(d)??!1;if(mN.has(i.modelID))return!n||i.modelID===Hw;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return In(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return In(i)}catch{return In(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return In(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return In(i)}catch{return In(i)}return!1}}function tk(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function nk(e,t){if(!e||Qr.has(e.providerID)||xe(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>xe(i.modelID)>0))return e;let r=i=>xe(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Jr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function rk(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Fy(n):void 0}function sk(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var hN=new Set(["explicit","repointed"]);function ok(e){let t=e.session?er(e.session):null,n=t?pi(t,e.gatewayEnabled):void 0;return(hN.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function ik(e){let{models:t,providers:n}=e,r=c=>mi(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of di(Object.keys(m.models).map(_=>({id:_})))){let _={providerID:m.id,modelID:h.id};if(r(_))return _}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:nk(a,t),explicit:i,fallback:o}}return gk(_N);})();
|