@ai-development-environment/server 0.0.48 → 0.0.49
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/package.json +1 -1
- package/prisma-runtime/prisma/migrations/20260723214432_add_model_costs/migration.sql +28 -0
- package/prisma-runtime/prisma/schema.prisma +30 -0
- package/standalone/.next/BUILD_ID +1 -1
- package/standalone/.next/app-path-routes-manifest.json +1 -0
- package/standalone/.next/build-manifest.json +3 -3
- package/standalone/.next/prerender-manifest.json +3 -3
- package/standalone/.next/routes-manifest.json +8 -0
- package/standalone/.next/server/app/[locale]/actions/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/actions/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/actions-cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/actions-cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/agents/[id]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/agents/[id]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/agents/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/agents/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/analytics-events/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/analytics-events/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/build-data/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/build-data/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/builds/[buildId]/coverage/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/builds/[buildId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/builds/[buildId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/builds/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/builds/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/codebases/[codebaseId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/codebases/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/codebases/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/codebases/repositories/[repositoryId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/comments/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/comments/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/console-logs/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/console-logs/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/costs/page/app-paths-manifest.json +3 -0
- package/standalone/.next/server/app/[locale]/costs/page/build-manifest.json +16 -0
- package/standalone/.next/server/app/[locale]/costs/page/next-font-manifest.json +11 -0
- package/standalone/.next/server/app/[locale]/costs/page/react-loadable-manifest.json +1 -0
- package/standalone/.next/server/app/[locale]/costs/page/server-reference-manifest.json +4 -0
- package/standalone/.next/server/app/[locale]/costs/page.js +17 -0
- package/standalone/.next/server/app/[locale]/costs/page.js.map +5 -0
- package/standalone/.next/server/app/[locale]/costs/page.js.nft.json +1 -0
- package/standalone/.next/server/app/[locale]/costs/page_client-reference-manifest.js +3 -0
- package/standalone/.next/server/app/[locale]/credentials/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/credentials/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/devices/[id]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/devices/[id]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/devices/enroll/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/devices/enroll/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/devices/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/devices/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/drafts/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/drafts/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/jira/cache/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/jira/cache/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/jira/cache/tickets/[issueKey]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/jira/cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/jira/tickets/[issueKey]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/jira/tickets/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/jira/tickets/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/jobs/[jobId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/jobs/[jobId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/notifications/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/notifications/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/plans/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/plans/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/plans/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/plans/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/polling/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/polling/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/provisioning-profiles/[profileId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/provisioning-profiles/[profileId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/provisioning-profiles/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/provisioning-profiles/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/pull-requests/[owner]/[repository]/[number]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/pull-requests/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/pull-requests/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/push-notifications/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/push-notifications/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/runs/new/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/runs/new/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/sessions/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/sessions/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/sessions/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/sessions/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/settings/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/settings/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/skills/[skillId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/skills/[skillId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/skills/groups/[groupId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/skills/groups/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/skills/groups/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/skills/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/skills/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/skills/sync/[runId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/tools/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/tools/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/unified-events/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/unified-events/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/usage/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/usage/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/worktrees/[worktreeId]/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/[locale]/worktrees/page.js.nft.json +1 -1
- package/standalone/.next/server/app/[locale]/worktrees/page_client-reference-manifest.js +1 -1
- package/standalone/.next/server/app/_global-error.html +1 -1
- package/standalone/.next/server/app/_global-error.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.html +1 -1
- package/standalone/.next/server/app/_not-found.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js +1 -1
- package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js +1 -1
- package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/by-path/route.js +1 -1
- package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/codebases/route.js +1 -1
- package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/graphql/route.js +1 -1
- package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/apns-devices/route.js +1 -1
- package/standalone/.next/server/app/api/ios/apns-devices/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js +1 -1
- package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/ios/enrollment/start/route.js +1 -1
- package/standalone/.next/server/app/api/ios/enrollment/start/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/mcp/route.js +1 -1
- package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/openapi.json/route.js +1 -1
- package/standalone/.next/server/app/api/openapi.json/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js +1 -1
- package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/github/webhook/route.js +1 -1
- package/standalone/.next/server/app/api/public/github/webhook/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js +1 -1
- package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/public/ios/profile-response/route.js +1 -1
- package/standalone/.next/server/app/api/public/ios/profile-response/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js +1 -1
- package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/run-attachments/route.js +1 -1
- package/standalone/.next/server/app/api/run-attachments/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/analytics-events/route.js +1 -1
- package/standalone/.next/server/app/api/telemetry/analytics-events/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/console-logs/route.js +1 -1
- package/standalone/.next/server/app/api/telemetry/console-logs/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/telemetry/export/route.js +1 -1
- package/standalone/.next/server/app/api/telemetry/export/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/call/route.js +1 -1
- package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/tools/catalog/route.js +1 -1
- package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
- package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js +1 -1
- package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
- package/standalone/.next/server/app-paths-manifest.json +1 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0m6-kcg._.js → [root-of-the-server]__0-ktevp._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__06tm4sl._.js → [root-of-the-server]__0-zj-yf._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__0eili-e._.js → [root-of-the-server]__01nvzbq._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0_87b17._.js → [root-of-the-server]__03orm-i._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__039ccw_._.js → [root-of-the-server]__04_a-p8._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__045avxp._.js → [root-of-the-server]__04sca_q._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__09vpqml._.js → [root-of-the-server]__04wnjxs._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__0dvn5ie._.js → [root-of-the-server]__04xapi4._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__00kk4vq._.js → [root-of-the-server]__04xwt6o._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__00rus46._.js → [root-of-the-server]__051yqe-._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__1tw_3no._.js → [root-of-the-server]__05pgm03._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__05vesnq._.js → [root-of-the-server]__05uug8c._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__026cujx._.js → [root-of-the-server]__064xuoi._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__0hwgatq._.js → [root-of-the-server]__06bc7-t._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__05iw4b6._.js → [root-of-the-server]__06hz_5m._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__079vs-o._.js → [root-of-the-server]__06qqqz4._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__073_7pr._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__07ezodj._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0ammric._.js → [root-of-the-server]__07gz69e._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__0avv--n._.js → [root-of-the-server]__08ekn_k._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__06qq-80._.js → [root-of-the-server]__09v822g._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__0_2v0r6._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0ev57uq._.js → [root-of-the-server]__0_elwh5._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__0_uti3p._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__04iwwa-._.js → [root-of-the-server]__0av34cc._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__0be93bj._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0bzypkl._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0lfudmf._.js → [root-of-the-server]__0ccm4vp._.js} +1 -1
- package/standalone/.next/server/chunks/{[root-of-the-server]__212svca._.js → [root-of-the-server]__0cfp7rm._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__0d3jwu8._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0dqd2cd._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0e3sw2f._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0ehmsw5._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0ey9b8q._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0hxwzy5._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__00pn80i._.js → [root-of-the-server]__0i46cc8._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__1mkh-uu._.js → [root-of-the-server]__0ii54f8._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__0k5hi4x._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0lk6mxj._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__1nozyf6._.js → [root-of-the-server]__0miujba._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__0qbgbqj._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0qc5tar._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0rland0._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__1_sflnn._.js → [root-of-the-server]__0rsjbt9._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__0u67sg7._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0ubhe7w._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0ue-6s0._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0uyhbd8._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0v_qn14._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__0oef7yv._.js → [root-of-the-server]__0vgjzu_._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0t1ryja._.js → [root-of-the-server]__0vs63nv._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0ujfqqn._.js → [root-of-the-server]__0vuegxj._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__0wc19bn._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0xhhfqn._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__0xuga9u._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1-b8mhr._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1-vesoj._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__10jq5fz._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__11adyal._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__11v9z03._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__03yxfwh._.js → [root-of-the-server]__12qoy0t._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0uq2mf_._.js → [root-of-the-server]__13olq7t._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__13z4o0y._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__14flk9w._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__14p4_xo._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__1attksp._.js → [root-of-the-server]__14x4hy5._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__16yif_j._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__17_i51a._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__17fmydy._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__17uilh6._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__11hjzc0._.js → [root-of-the-server]__183_4dj._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__18p4ewi._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__190kf-7._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1_t7_qf._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1_tq9n2._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1b8ar_b._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1b_j3xv._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1cj96fo._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1dvcmqw._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1gcfshm._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1gen-el._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1gonl53._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1hst7ec._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1hvcd1x._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1kajbb_._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1kj1ln5._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1l9-hc6._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1lgant0._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1na8-n6._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1ottisz._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1shxc8n._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1tvvhzn._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__1yam92a._.js → [root-of-the-server]__1ummn4p._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__1v-dnat._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1wdw3t2._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1wdye-x._.js +3 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__1wjvdyz._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__06dbyo-._.js → [root-of-the-server]__1xnwo73._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0v0oh52._.js → [root-of-the-server]__1yi_2qs._.js} +2 -2
- package/standalone/.next/server/chunks/{[root-of-the-server]__0axi_lh._.js → [root-of-the-server]__1yim97_._.js} +1 -1
- package/standalone/.next/server/chunks/[root-of-the-server]__1zcjrka._.js +3 -0
- package/standalone/.next/server/chunks/{[root-of-the-server]__08bpdlj._.js → [root-of-the-server]__1zrp8nv._.js} +2 -2
- package/standalone/.next/server/chunks/[root-of-the-server]__2125ewz._.js +3 -0
- package/standalone/.next/server/chunks/_0151la8._.js +1 -1
- package/standalone/.next/server/chunks/_01p5vu2._.js +1 -1
- package/standalone/.next/server/chunks/_07bbzzn._.js +1 -1
- package/standalone/.next/server/chunks/_0_3-lke._.js +88 -1
- package/standalone/.next/server/chunks/_0g1xb8v._.js +1 -1
- package/standalone/.next/server/chunks/_11p_tgb._.js +1 -1
- package/standalone/.next/server/chunks/_17e45g_._.js +1 -1
- package/standalone/.next/server/chunks/_1hmzed-._.js +192 -105
- package/standalone/.next/server/chunks/_1ioi8na._.js +1 -1
- package/standalone/.next/server/chunks/_1m96-gv._.js +1 -1
- package/standalone/.next/server/chunks/_1r_e2vq._.js +1 -1
- package/standalone/.next/server/chunks/_1xr-3kb._.js +1 -1
- package/standalone/.next/server/chunks/src_services_runs_index_ts_0_l1wkt._.js +5 -5
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__03mx68i._.js +35 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__06_k1v8._.js +55 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ik85du._.js +35 -0
- package/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1wsrjus._.js → [root-of-the-server]__0lavdf4._.js} +2 -2
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0lgqolk._.js +3 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0o4j_p7._.js +3 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0usqx1k._.js +3 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__1bpbvfj._.js +3 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__1iccye4._.js +3 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__1m28j8h._.js +50 -0
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__1qatu4i._.js +55 -0
- package/standalone/.next/server/chunks/ssr/_0-zp1-t._.js +24 -0
- package/standalone/.next/server/chunks/ssr/_01gprkf._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_02ku0-d._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_04de9zy._.js +22 -0
- package/standalone/.next/server/chunks/ssr/_06iu0wl._.js +14 -0
- package/standalone/.next/server/chunks/ssr/_09fzzrw._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0_l0f-3._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0c0xiut._.js +3 -3
- package/standalone/.next/server/chunks/ssr/{_1-kqme0._.js → _0egs9gy._.js} +2 -2
- package/standalone/.next/server/chunks/ssr/_0f77vgb._.js +3 -3
- package/standalone/.next/server/chunks/ssr/_0fxzy4k._.js +25 -0
- package/standalone/.next/server/chunks/ssr/_0kp9tyy._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0mbgqw2._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0nlc7lw._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0o60joc._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0o6a-0c._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0p296dl._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0qilx29._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0qt0tus._.js +34 -0
- package/standalone/.next/server/chunks/ssr/_0vyqwim._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0xquvzm._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_0y39xwb._.js +11 -0
- package/standalone/.next/server/chunks/ssr/_0zush3e._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_12xqut4._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1337yek._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_15cf0-b._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_15p60kc._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_17dj9--._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1_z-mrp._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1btalzp._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1bxaf69._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1dwrw9s._.js +3 -0
- package/standalone/.next/server/chunks/ssr/{_0ov6iy1._.js → _1ejg55c._.js} +2 -2
- package/standalone/.next/server/chunks/ssr/_1glp2ss._.js +24 -0
- package/standalone/.next/server/chunks/ssr/_1hisxge._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1kstox-._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1m5s4f8._.js +3 -0
- package/standalone/.next/server/chunks/ssr/_1qtzca_._.js +3 -0
- package/standalone/.next/server/chunks/ssr/{_1kysa5a._.js → _1s5bp9h._.js} +2 -2
- package/standalone/.next/server/chunks/ssr/_1wb78d8._.js +34 -0
- package/standalone/.next/server/chunks/ssr/_1y5d9t8._.js +6 -0
- package/standalone/.next/server/chunks/ssr/_1zgu74l._.js +7 -7
- package/standalone/.next/server/chunks/ssr/{_1j_ku-q._.js → _20lnu8x._.js} +2 -2
- package/standalone/.next/server/chunks/ssr/{_03lk450._.js → _20wicqx._.js} +3 -3
- package/standalone/.next/server/chunks/ssr/_next-internal_server_app_[locale]_costs_page_actions_16fdpkb.js +3 -0
- package/standalone/.next/server/chunks/ssr/messages_de_json_[json]_cjs_1uig1ud._.js +1 -1
- package/standalone/.next/server/chunks/ssr/messages_en_json_[json]_cjs_206072-._.js +1 -1
- package/standalone/.next/server/chunks/ssr/messages_es_json_[json]_cjs_082yukd._.js +1 -1
- package/standalone/.next/server/chunks/ssr/messages_fr_json_[json]_cjs_0j6-w0i._.js +1 -1
- package/standalone/.next/server/chunks/ssr/node_modules_0j8c3kh._.js +3 -0
- package/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_1ghuygj._.js +3 -0
- package/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_1x2xg00._.js +3 -0
- package/standalone/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0kifgf3.js +4 -0
- package/standalone/.next/server/chunks/ssr/src_components_builds_configuration-icon_tsx_1v42ztc._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_builds_coverage-report-page_tsx_1nhwba1._.js +2 -2
- package/standalone/.next/server/chunks/ssr/src_components_notifications_notifications-page_tsx_19f4ztg._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_push-notifications_push-notifications-page_tsx_1c_b-t4._.js +2 -2
- package/standalone/.next/server/chunks/ssr/src_components_runs_attachment-picker_tsx_0netm9l._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_runs_run-detail-page_tsx_0eje87-._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_runs_runs-page_tsx_0l5-7eu._.js +1 -1
- package/standalone/.next/server/chunks/ssr/src_components_settings-page_tsx_06dxqc7._.js +5 -5
- package/standalone/.next/server/chunks/ssr/src_components_tools_tools-page_tsx_0k1jqcz._.js +2 -2
- package/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/standalone/.next/server/next-font-manifest.js +1 -1
- package/standalone/.next/server/next-font-manifest.json +4 -0
- package/standalone/.next/server/pages/404.html +1 -1
- package/standalone/.next/server/pages/500.html +1 -1
- package/standalone/.next/server/server-reference-manifest.js +1 -1
- package/standalone/.next/server/server-reference-manifest.json +1 -1
- package/standalone/.next/static/chunks/{3b8uo25m50np4.js → 00-wgagfa3jgw.js} +6 -6
- package/standalone/.next/static/chunks/{1_zvnvft13-co.js → 0269se70im5oy.js} +1 -1
- package/standalone/.next/static/chunks/06ww4smr4x1rf.js +46 -0
- package/standalone/.next/static/chunks/0ad6f15x10087.js +31 -0
- package/standalone/.next/static/chunks/{04gmuff_hq-a2.js → 0gi1rut09px9z.js} +1 -1
- package/standalone/.next/static/chunks/0hhv79fjnhx0r.js +1 -0
- package/standalone/.next/static/chunks/0koiigzfqaaxm.js +6 -0
- package/standalone/.next/static/chunks/0lz2yyevf796v.js +57 -0
- package/standalone/.next/static/chunks/{12rdpylf5_1s1.js → 0n_3nenvq-cdq.js} +1 -1
- package/standalone/.next/static/chunks/{2g3hfv0bu6-ac.js → 0nsdo6d126qko.js} +1 -1
- package/standalone/.next/static/chunks/0tydvosk1yzd3.js +9 -0
- package/standalone/.next/static/chunks/{11rdgo_6b41l1.js → 0vh2j_0-i7_4a.js} +2 -2
- package/standalone/.next/static/chunks/0x7ht_1kzfirv.js +3 -0
- package/standalone/.next/static/chunks/{2lgln0a2k277h.js → 0xge_x1_gyy-7.js} +1 -1
- package/standalone/.next/static/chunks/0y9oq83e4ty93.js +29 -0
- package/standalone/.next/static/chunks/10ugqh884daci.js +67 -0
- package/standalone/.next/static/chunks/167jr5pbpylis.js +7 -0
- package/standalone/.next/static/chunks/{2vjc_-wvtw1hf.js → 18rpe2d8mq3kd.js} +3 -3
- package/standalone/.next/static/chunks/1c285hxt_qxlx.js +46 -0
- package/standalone/.next/static/chunks/1f3ggqgs3erm7.js +41 -0
- package/standalone/.next/static/chunks/1f3hspf4q04c7.js +1 -0
- package/standalone/.next/static/chunks/1g8c1oh-w22rr.js +54 -0
- package/standalone/.next/static/chunks/1h680dhlld_lc.js +33 -0
- package/standalone/.next/static/chunks/1hymkpu62xhp8.js +33 -0
- package/standalone/.next/static/chunks/{12kemc9g02r2c.js → 1l-ift-80ao1c.js} +1 -1
- package/standalone/.next/static/chunks/1nz8ddeplq5hs.js +1 -0
- package/standalone/.next/static/chunks/1qecuivo6a47u.css +1 -0
- package/standalone/.next/static/chunks/1r9r_g25rp8ak.js +23 -0
- package/standalone/.next/static/chunks/{0x7pt5btcphku.js → 1uwz2ko2jqwtz.js} +1 -1
- package/standalone/.next/static/chunks/1v5zb8ln1rz2d.js +1 -0
- package/standalone/.next/static/chunks/{0ai0x7vc1931l.js → 1xjs526g101xh.js} +1 -1
- package/standalone/.next/static/chunks/{3369nhs1_otwi.js → 2-duyp_kl5qx9.js} +1 -1
- package/standalone/.next/static/chunks/{3roht5nbja0a_.js → 21di8-zv-5qvx.js} +18 -18
- package/standalone/.next/static/chunks/22d7hj9vwqj9p.js +1 -0
- package/standalone/.next/static/chunks/{1lnlrcypmvv5h.js → 24jkxx9dbxh1h.js} +1 -1
- package/standalone/.next/static/chunks/{3pj0v38s6yr9s.js → 28vxarecfoquo.js} +4 -4
- package/standalone/.next/static/chunks/28z95ky0z7tkb.js +10 -0
- package/standalone/.next/static/chunks/2ayopd7367rqs.js +41 -0
- package/standalone/.next/static/chunks/2azupfg2-5j-p.js +1 -0
- package/standalone/.next/static/chunks/2brlnpt__4ftd.js +1 -0
- package/standalone/.next/static/chunks/2k_pfyxmtuoy5.js +1 -0
- package/standalone/.next/static/chunks/2km-n4_gmq7cl.js +1 -0
- package/standalone/.next/static/chunks/2llvq19x9do52.js +9 -0
- package/standalone/.next/static/chunks/{1biwep24jyw3_.js → 2qedr2wefau4t.js} +1 -1
- package/standalone/.next/static/chunks/2wb15vf48-edn.js +92 -0
- package/standalone/.next/static/chunks/{0b33bs18huezl.js → 2x2_7-5jm0gme.js} +15 -15
- package/standalone/.next/static/chunks/2yjrhue4lxrng.js +1 -0
- package/standalone/.next/static/chunks/324kabhuasm-p.js +53 -0
- package/standalone/.next/static/chunks/34jvsrj9xubhb.js +1 -0
- package/standalone/.next/static/chunks/38oh9ov0j80rj.js +12 -0
- package/standalone/.next/static/chunks/{42n596b3nvu1d.js → 38z6ydb1jtugp.js} +9 -9
- package/standalone/.next/static/chunks/{06ko8c02ly6ua.js → 3b7o_8v0u__4p.js} +1 -1
- package/standalone/.next/static/chunks/3e31jo--0j7bd.js +1 -0
- package/standalone/.next/static/chunks/3llt9fqdrs6_3.js +7 -0
- package/standalone/.next/static/chunks/3m3riu0uoz_w0.js +64 -0
- package/standalone/.next/static/chunks/3s_cg15bmegsq.js +64 -0
- package/standalone/.next/static/chunks/{1il4firsh2p_o.js → 3tulld0sh2yxv.js} +1 -1
- package/standalone/.next/static/chunks/3zr5h7dm94-d3.js +1 -0
- package/standalone/.next/server/chunks/[root-of-the-server]__082mwbz._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__08rs4kl._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0ejd120._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0epw197._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0erekw9._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0l8fuzs._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0m09s9s._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0o4kf3w._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0q7pwvx._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0quwt4e._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0r2qqym._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0rafxyp._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0rxa3sz._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0sxnukz._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0tck2gw._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0upntz8._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0w7u33h._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0wccpuq._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0wq5_-0._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0x8p1h0._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0yq7gle._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0yvl0kj._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__0yyj4bs._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1-q8hnm._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__11i-u3m._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__11wdfkm._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__13-bmbg._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__14sr2n9._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__15zrchx._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__17im3wm._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__17j6ax7._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__19bpnrg._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__19y6-lp._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1_8gar4._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1_m78-y._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1_osj_0._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1_xtyhp._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1ba1y6w._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1d-p62y._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1e2tfpn._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1fw5scf._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1g0rhrl._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1h6a01c._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1i54hfr._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1ismp8w._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1kgh2tn._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1l0a05x._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1levtv0._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1mk80rh._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1n58dbx._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1nxvyuj._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1o4ho5v._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1osqj7h._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1oxgsjg._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1r9m70u._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1t1-ozx._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1tj3th9._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1v_176-._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1wnx190._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1wsm3gj._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__1ygwh5f._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__205s18n._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__20m339t._.js +0 -3
- package/standalone/.next/server/chunks/[root-of-the-server]__216tiae._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0__ku3o._.js +0 -35
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0f7usu6._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0fa4g67._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ybu1dj._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ywelz9._.js +0 -55
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__114998b._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__144jx4y._.js +0 -35
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__17mewsc._.js +0 -3
- package/standalone/.next/server/chunks/ssr/[root-of-the-server]__1lx9kov._.js +0 -50
- package/standalone/.next/server/chunks/ssr/_03edwuc._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_03mo_w3._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_065924f._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0a8xyjk._.js +0 -34
- package/standalone/.next/server/chunks/ssr/_0dsosms._.js +0 -34
- package/standalone/.next/server/chunks/ssr/_0kx9ux4._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0la2zju._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0mcyq3z._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0ocxapn._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0p03tt8._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0qi9ubx._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0s55i9k._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_0w5dl6y._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1-3kr_6._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1-h8fzh._.js +0 -24
- package/standalone/.next/server/chunks/ssr/_15_tlq_._.js +0 -6
- package/standalone/.next/server/chunks/ssr/_1_-b2as._.js +0 -24
- package/standalone/.next/server/chunks/ssr/_1ax0n4o._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1bedv0f._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1cg5e7d._.js +0 -55
- package/standalone/.next/server/chunks/ssr/_1dre7jj._.js +0 -9
- package/standalone/.next/server/chunks/ssr/_1h8h0mh._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1j6x49s._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1m3mq_d._.js +0 -42
- package/standalone/.next/server/chunks/ssr/_1q7k2_j._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1qanfz-._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1qu6yg5._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1rgxkh5._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1rqv83r._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1sn2hfw._.js +0 -14
- package/standalone/.next/server/chunks/ssr/_1w9iqqu._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1y1-frz._.js +0 -22
- package/standalone/.next/server/chunks/ssr/_1zfs9qf._.js +0 -3
- package/standalone/.next/server/chunks/ssr/_1zxg4ba._.js +0 -3
- package/standalone/.next/server/chunks/ssr/node_modules_lucide-react_dist_esm_icons_0qgkxbt._.js +0 -3
- package/standalone/.next/static/chunks/08q6vr-p-cstj.js +0 -29
- package/standalone/.next/static/chunks/0_zeonk2mtnf-.js +0 -1
- package/standalone/.next/static/chunks/0buuj5lld90he.css +0 -1
- package/standalone/.next/static/chunks/0bviczmoov5a2.js +0 -1
- package/standalone/.next/static/chunks/0ff5gudlpx2v5.js +0 -1
- package/standalone/.next/static/chunks/0piy74xklzjfr.js +0 -62
- package/standalone/.next/static/chunks/1-eifwvqj9be1.js +0 -1
- package/standalone/.next/static/chunks/11jwq4xw0a435.js +0 -64
- package/standalone/.next/static/chunks/17uchsfglg1ck.js +0 -73
- package/standalone/.next/static/chunks/1_82pgfh8i49s.js +0 -1
- package/standalone/.next/static/chunks/1t3vla-ambxbp.js +0 -6
- package/standalone/.next/static/chunks/1uc144yy_2oye.js +0 -3
- package/standalone/.next/static/chunks/2358pwl17z6qf.js +0 -41
- package/standalone/.next/static/chunks/25ugyd34t2mrk.js +0 -1
- package/standalone/.next/static/chunks/28lukaj4hpvlk.js +0 -63
- package/standalone/.next/static/chunks/2efb8ggk_k58p.js +0 -53
- package/standalone/.next/static/chunks/2eidepo22ts0u.js +0 -1
- package/standalone/.next/static/chunks/2hd3kczfekev9.js +0 -12
- package/standalone/.next/static/chunks/2k1pvryqz_c4u.js +0 -1
- package/standalone/.next/static/chunks/2nzg7au4ezqgc.js +0 -109
- package/standalone/.next/static/chunks/2ub8d_20l7ahg.js +0 -54
- package/standalone/.next/static/chunks/2v3vffkcv30_q.js +0 -8
- package/standalone/.next/static/chunks/2y3inehs64srx.js +0 -39
- package/standalone/.next/static/chunks/2z2vm371tkfeo.js +0 -39
- package/standalone/.next/static/chunks/3-8aipql92ik4.js +0 -46
- package/standalone/.next/static/chunks/3-doerwkk9tw0.js +0 -57
- package/standalone/.next/static/chunks/300j0k53l2xf4.js +0 -7
- package/standalone/.next/static/chunks/38cr_upvs02u3.js +0 -10
- package/standalone/.next/static/chunks/3ev0nt_zzxoc6.js +0 -1
- package/standalone/.next/static/chunks/3he_se7z8qr9v.js +0 -1
- package/standalone/.next/static/chunks/3w11s4sn96-rw.js +0 -1
- package/standalone/.next/static/chunks/3ylqdy-23qzuz.js +0 -54
- package/standalone/.next/static/chunks/3yvgowlcy4bok.js +0 -7
- package/standalone/.next/static/chunks/43-yobagq1112.js +0 -1
- package/standalone/.next/static/chunks/44v5iw1qe3el2.js +0 -9
- /package/standalone/.next/static/{OS8UYgZ5MOMdBZuXMlpNG → fqOmtAGSGlY51xUvvOKyW}/_buildManifest.js +0 -0
- /package/standalone/.next/static/{OS8UYgZ5MOMdBZuXMlpNG → fqOmtAGSGlY51xUvvOKyW}/_clientMiddlewareManifest.js +0 -0
- /package/standalone/.next/static/{OS8UYgZ5MOMdBZuXMlpNG → fqOmtAGSGlY51xUvvOKyW}/_ssgManifest.js +0 -0
|
@@ -425,6 +425,6 @@ ${n}`,d++}else ef(e,r,a)?p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,i)||void 0:g(e
|
|
|
425
425
|
`,r),a=-1;if(-1!==t&&-1!==i?a=t<i?t:i:-1!==t?a=t===e.length-1?-1:t:-1!==i&&(a=i),-1===a)break;g(e,r,a),r=a+1,13===e.charCodeAt(r-1)&&10===e.charCodeAt(r)&&r++}return e.slice(r)}function g(e,r,i){if(r===i)return void(d>0&&t({id:c,event:p,data:u}),c=void 0,u="",d=0,p=void 0);let n=e.charCodeAt(r);if(em(e,r,n)){let t=32===e.charCodeAt(r+5)?r+6:r+5,a=e.slice(t,i);u=0===d?a:`${u}
|
|
426
426
|
${a}`,d++;return}if(ef(e,r,n)){p=e.slice(32===e.charCodeAt(r+6)?r+7:r+6,i)||void 0;return}if(105===n&&100===e.charCodeAt(r+1)&&58===e.charCodeAt(r+2)){let t=e.slice(32===e.charCodeAt(r+3)?r+4:r+3,i);c=t.includes("\0")?void 0:t;return}if(58===n){a&&a(e.slice(r,i).slice(32===e.charCodeAt(r+1)?2:1));return}let s=e.slice(r,i),o=s.indexOf(":");if(-1===o)return void y(s,"",s);let l=s.slice(0,o),h=32===s.charCodeAt(o+1)?2:1;y(l,s.slice(o+h),s)}function y(e,t,a){switch(e){case"event":p=t||void 0;break;case"data":u=0===d?t:`${u}
|
|
427
427
|
${t}`,d++;break;case"id":c=t.includes("\0")?void 0:t;break;case"retry":/^\d+$/.test(t)?i(parseInt(t,10)):r(new ed(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:a}));break;default:r(new ed(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:"unknown-field",field:e,value:t,line:a}))}}return{feed:function(e){if(h)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){let t=f(e);""!==t&&(s.push(t),o=t.length),m();return}if(-1===e.indexOf(`
|
|
428
|
-
`)&&-1===e.indexOf("\r")){s.push(e),o+=e.length,m();return}s.push(e);let t=s.join("");s.length=0,o=0;let r=f(t);""!==r&&(s.push(r),o=r.length),m()},reset:function(e={}){if(e.consume&&s.length>0){let e=s.join("");g(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,s.length=0,o=0,h=!1}}}function em(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function ef(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class eg extends Event{constructor(e,t){var r,i;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(i=null==t?void 0:t.message)?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(ey(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(ey(this),t)}}function ey(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ev,eb,ew,ex,ek,eS,eI,eA,e_,eE,eC,eT,eD,e$,eR,eN,eP,eO,ej,eB,eU,eq,eL,eM=e=>{throw TypeError(e)},eF=(e,t,r)=>t.has(e)||eM("Cannot "+r),eV=(e,t,r)=>(eF(e,t,"read from private field"),r?r.call(e):t.get(e)),eK=(e,t,r)=>t.has(e)?eM("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),eH=(e,t,r,i)=>(eF(e,t,"write to private field"),t.set(e,r),r),ez=(e,t,r)=>(eF(e,t,"access private method"),r);class eG extends EventTarget{constructor(e,t){var r,i;super(),eK(this,e$),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eK(this,ev),eK(this,eb),eK(this,ew),eK(this,ex),eK(this,ek),eK(this,eS),eK(this,eI),eK(this,eA,null),eK(this,e_),eK(this,eE),eK(this,eC,null),eK(this,eT,null),eK(this,eD,null),eK(this,eN,async e=>{var t;eV(this,eE).reset();let{body:r,redirected:i,status:a,headers:n}=e;if(204===a){ez(this,e$,eU).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(i?eH(this,ew,new URL(e.url)):eH(this,ew,void 0),200!==a)return void ez(this,e$,eU).call(this,`Non-200 status code (${a})`,a);if(!(n.get("content-type")||"").startsWith("text/event-stream"))return void ez(this,e$,eU).call(this,'Invalid content type, expected "text/event-stream"',a);if(eV(this,ev)===this.CLOSED)return;eH(this,ev,this.OPEN);let s=new Event("open");if(null==(t=eV(this,eD))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r)){ez(this,e$,eU).call(this,"Invalid response body, expected a web ReadableStream",a),this.close();return}let o=new TextDecoder,l=r.getReader(),c=!0;do{let{done:e,value:t}=await l.read();t&&eV(this,eE).feed(o.decode(t,{stream:!e})),e&&(c=!1,eV(this,eE).reset(),ez(this,e$,eq).call(this))}while(c)}),eK(this,eP,e=>{eH(this,e_,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&ez(this,e$,eq).call(this,function e(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(e).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${e(t.cause)}`:t.message:`${t}`}(e))}),eK(this,ej,e=>{"string"==typeof e.id&&eH(this,eA,e.id);let t=new MessageEvent(e.event||"message",{data:e.data,origin:eV(this,ew)?eV(this,ew).origin:eV(this,eb).origin,lastEventId:e.id||""});eV(this,eT)&&(!e.event||"message"===e.event)&&eV(this,eT).call(this,t),this.dispatchEvent(t)}),eK(this,eB,e=>{eH(this,eS,e)}),eK(this,eL,()=>{eH(this,eI,void 0),eV(this,ev)===this.CONNECTING&&ez(this,e$,eR).call(this)});try{if(e instanceof URL)eH(this,eb,e);else if("string"==typeof e)eH(this,eb,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}eH(this,eE,eh({onEvent:eV(this,ej),onRetry:eV(this,eB)})),eH(this,ev,this.CONNECTING),eH(this,eS,3e3),eH(this,ek,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),eH(this,ex,null!=(i=null==t?void 0:t.withCredentials)&&i),ez(this,e$,eR).call(this)}get readyState(){return eV(this,ev)}get url(){return eV(this,eb).href}get withCredentials(){return eV(this,ex)}get onerror(){return eV(this,eC)}set onerror(e){eH(this,eC,e)}get onmessage(){return eV(this,eT)}set onmessage(e){eH(this,eT,e)}get onopen(){return eV(this,eD)}set onopen(e){eH(this,eD,e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){eV(this,eI)&&clearTimeout(eV(this,eI)),eV(this,ev)!==this.CLOSED&&(eV(this,e_)&&eV(this,e_).abort(),eH(this,ev,this.CLOSED),eH(this,e_,void 0))}}function eJ(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function eW(e=fetch,t){return t?async(r,i)=>e(r,{...t,...i,headers:i?.headers?{...eJ(t.headers),...eJ(i.headers)}:t.headers}):e}async function eZ(e){return(await t).getRandomValues(new Uint8Array(e))}async function eY(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=256-256%t.length,i="";for(;i.length<e;)for(let a of(await eZ(e-i.length)))a<r&&(i+=t[a%t.length]);return i}async function eQ(e){return await eY(e)}async function eX(e){return btoa(String.fromCharCode(...new Uint8Array(await (await t).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function e0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await eQ(e),r=await eX(t);return{code_verifier:t,code_challenge:r}}ev=new WeakMap,eb=new WeakMap,ew=new WeakMap,ex=new WeakMap,ek=new WeakMap,eS=new WeakMap,eI=new WeakMap,eA=new WeakMap,e_=new WeakMap,eE=new WeakMap,eC=new WeakMap,eT=new WeakMap,eD=new WeakMap,e$=new WeakSet,eR=function(){eH(this,ev,this.CONNECTING),eH(this,e_,new AbortController),eV(this,ek)(eV(this,eb),ez(this,e$,eO).call(this)).then(eV(this,eN)).catch(eV(this,eP))},eN=new WeakMap,eP=new WeakMap,eO=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eV(this,eA)?{"Last-Event-ID":eV(this,eA)}:void 0},cache:"no-store",signal:null==(e=eV(this,e_))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ej=new WeakMap,eB=new WeakMap,eU=function(e,t){var r;eV(this,ev)!==this.CLOSED&&eH(this,ev,this.CLOSED);let i=new eg("error",{code:t,message:e});null==(r=eV(this,eC))||r.call(this,i),this.dispatchEvent(i)},eq=function(e,t){var r;if(eV(this,ev)===this.CLOSED)return;eH(this,ev,this.CONNECTING);let i=new eg("error",{code:t,message:e});null==(r=eV(this,eC))||r.call(this,i),this.dispatchEvent(i),eH(this,eI,setTimeout(eV(this,eL),eV(this,eS)))},eL=new WeakMap,eG.CONNECTING=0,eG.OPEN=1,eG.CLOSED=2,t=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);var e1=e.i(907855),e2=e.i(733137),e3=e.i(127438),e4=e.i(334512),e4=e4;let e6=e1.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:e2.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),e3.NEVER}).refine(e=>{let t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),e8=e1.looseObject({resource:e1.string().url(),authorization_servers:e1.array(e6).optional(),jwks_uri:e1.string().url().optional(),scopes_supported:e1.array(e1.string()).optional(),bearer_methods_supported:e1.array(e1.string()).optional(),resource_signing_alg_values_supported:e1.array(e1.string()).optional(),resource_name:e1.string().optional(),resource_documentation:e1.string().optional(),resource_policy_uri:e1.string().url().optional(),resource_tos_uri:e1.string().url().optional(),tls_client_certificate_bound_access_tokens:e1.boolean().optional(),authorization_details_types_supported:e1.array(e1.string()).optional(),dpop_signing_alg_values_supported:e1.array(e1.string()).optional(),dpop_bound_access_tokens_required:e1.boolean().optional()}),e5=e1.looseObject({issuer:e1.string(),authorization_endpoint:e6,token_endpoint:e6,registration_endpoint:e6.optional(),scopes_supported:e1.array(e1.string()).optional(),response_types_supported:e1.array(e1.string()),response_modes_supported:e1.array(e1.string()).optional(),grant_types_supported:e1.array(e1.string()).optional(),token_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),service_documentation:e6.optional(),revocation_endpoint:e6.optional(),revocation_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),introspection_endpoint:e1.string().optional(),introspection_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),code_challenge_methods_supported:e1.array(e1.string()).optional(),client_id_metadata_document_supported:e1.boolean().optional()}),e9=e1.looseObject({issuer:e1.string(),authorization_endpoint:e6,token_endpoint:e6,userinfo_endpoint:e6.optional(),jwks_uri:e6,registration_endpoint:e6.optional(),scopes_supported:e1.array(e1.string()).optional(),response_types_supported:e1.array(e1.string()),response_modes_supported:e1.array(e1.string()).optional(),grant_types_supported:e1.array(e1.string()).optional(),acr_values_supported:e1.array(e1.string()).optional(),subject_types_supported:e1.array(e1.string()),id_token_signing_alg_values_supported:e1.array(e1.string()),id_token_encryption_alg_values_supported:e1.array(e1.string()).optional(),id_token_encryption_enc_values_supported:e1.array(e1.string()).optional(),userinfo_signing_alg_values_supported:e1.array(e1.string()).optional(),userinfo_encryption_alg_values_supported:e1.array(e1.string()).optional(),userinfo_encryption_enc_values_supported:e1.array(e1.string()).optional(),request_object_signing_alg_values_supported:e1.array(e1.string()).optional(),request_object_encryption_alg_values_supported:e1.array(e1.string()).optional(),request_object_encryption_enc_values_supported:e1.array(e1.string()).optional(),token_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),display_values_supported:e1.array(e1.string()).optional(),claim_types_supported:e1.array(e1.string()).optional(),claims_supported:e1.array(e1.string()).optional(),service_documentation:e1.string().optional(),claims_locales_supported:e1.array(e1.string()).optional(),ui_locales_supported:e1.array(e1.string()).optional(),claims_parameter_supported:e1.boolean().optional(),request_parameter_supported:e1.boolean().optional(),request_uri_parameter_supported:e1.boolean().optional(),require_request_uri_registration:e1.boolean().optional(),op_policy_uri:e6.optional(),op_tos_uri:e6.optional(),client_id_metadata_document_supported:e1.boolean().optional()}),e7=e1.object({...e9.shape,...e5.pick({code_challenge_methods_supported:!0}).shape}),te=e1.object({access_token:e1.string(),id_token:e1.string().optional(),token_type:e1.string(),expires_in:e4.number().optional(),scope:e1.string().optional(),refresh_token:e1.string().optional()}).strip(),tt=e1.object({error:e1.string(),error_description:e1.string().optional(),error_uri:e1.string().optional()}),tr=e6.optional().or(e1.literal("").transform(()=>void 0)),ti=e1.object({redirect_uris:e1.array(e6),token_endpoint_auth_method:e1.string().optional(),grant_types:e1.array(e1.string()).optional(),response_types:e1.array(e1.string()).optional(),client_name:e1.string().optional(),client_uri:e6.optional(),logo_uri:tr,scope:e1.string().optional(),contacts:e1.array(e1.string()).optional(),tos_uri:tr,policy_uri:e1.string().optional(),jwks_uri:e6.optional(),jwks:e1.any().optional(),software_id:e1.string().optional(),software_version:e1.string().optional(),software_statement:e1.string().optional()}).strip(),ta=e1.object({client_id:e1.string(),client_secret:e1.string().optional(),client_id_issued_at:e1.number().optional(),client_secret_expires_at:e1.number().optional()}).strip(),tn=ti.merge(ta);e1.object({error:e1.string(),error_description:e1.string().optional()}).strip(),e1.object({token:e1.string(),token_type_hint:e1.string().optional()}).strip();class ts extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class to extends ts{}to.errorCode="invalid_request";class tl extends ts{}tl.errorCode="invalid_client";class tc extends ts{}tc.errorCode="invalid_grant";class tu extends ts{}tu.errorCode="unauthorized_client";class td extends ts{}td.errorCode="unsupported_grant_type";class tp extends ts{}tp.errorCode="invalid_scope";class th extends ts{}th.errorCode="access_denied";class tm extends ts{}tm.errorCode="server_error";class tf extends ts{}tf.errorCode="temporarily_unavailable";class tg extends ts{}tg.errorCode="unsupported_response_type";class ty extends ts{}ty.errorCode="unsupported_token_type";class tv extends ts{}tv.errorCode="invalid_token";class tb extends ts{}tb.errorCode="method_not_allowed";class tw extends ts{}tw.errorCode="too_many_requests";class tx extends ts{}tx.errorCode="invalid_client_metadata";class tk extends ts{}tk.errorCode="insufficient_scope";class tS extends ts{}tS.errorCode="invalid_target";let tI={[to.errorCode]:to,[tl.errorCode]:tl,[tc.errorCode]:tc,[tu.errorCode]:tu,[td.errorCode]:td,[tp.errorCode]:tp,[th.errorCode]:th,[tm.errorCode]:tm,[tf.errorCode]:tf,[tg.errorCode]:tg,[ty.errorCode]:ty,[tv.errorCode]:tv,[tb.errorCode]:tb,[tw.errorCode]:tw,[tx.errorCode]:tx,[tk.errorCode]:tk,[tS.errorCode]:tS};class tA extends Error{constructor(e){super(e??"Unauthorized")}}let t_="code",tE="S256";async function tC(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=tt.parse(JSON.parse(r));return new(tI[e]||tm)(t||"",i)}catch(e){return new tm(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function tT(e,t){try{return await tD(e,t)}catch(r){if(r instanceof tl||r instanceof tu)return await e.invalidateCredentials?.("all"),await tD(e,t);if(r instanceof tc)return await e.invalidateCredentials?.("tokens"),await tD(e,t);throw r}}async function tD(e,{serverUrl:t,authorizationCode:r,scope:i,resourceMetadataUrl:a,fetchFn:n}){let s,o,l,c=await e.discoveryState?.(),u=a;if(!u&&c?.resourceMetadataUrl&&(u=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(o=c.authorizationServerUrl,s=c.resourceMetadata,l=c.authorizationServerMetadata??await tU(o,{fetchFn:n}),!s)try{s=await tP(t,{resourceMetadataUrl:u},n)}catch{}(l!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let r=await tq(t,{resourceMetadataUrl:u,fetchFn:n});o=r.authorizationServerUrl,l=r.authorizationServerMetadata,s=r.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await t$(t,e,s),p=i||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation());if(!h){if(void 0!==r)throw Error("Existing OAuth client information is required when exchanging an authorization code");let t=l?.client_id_metadata_document_supported===!0,i=e.clientMetadataUrl;if(i&&!function(e){if(!e)return!1;try{let t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(i))throw new tx(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${i}`);if(t&&i)h={client_id:i},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let t=await tK(o,{metadata:l,clientMetadata:e.clientMetadata,scope:p,fetchFn:n});await e.saveClientInformation(t),h=t}}let m=!e.redirectUrl;if(void 0!==r||m){let t=await tV(e,o,{metadata:l,resource:d,authorizationCode:r,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}let f=await e.tokens();if(f?.refresh_token)try{let t=await tF(o,{metadata:l,clientInformation:h,refreshToken:f.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(!(e instanceof ts)||e instanceof tm);else throw e}let g=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:v}=await tL(o,{metadata:l,clientInformation:h,state:g,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(y),"REDIRECT"}async function t$(e,t,r){let i,a=((i=new URL("string"==typeof e?e:e.href)).hash="",i);if(t.validateResourceURL)return await t.validateResourceURL(a,r?.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){let r=new URL("string"==typeof e?e:e.href),i=new URL("string"==typeof t?t:t.href);if(r.origin!==i.origin||r.pathname.length<i.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return a.startsWith(n)}({requestedResource:a,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function tR(e){let t,r=e.headers.get("WWW-Authenticate");if(!r)return{};let[i,a]=r.split(" ");if("bearer"!==i.toLowerCase()||!a)return{};let n=tN(e,"resource_metadata")||void 0;if(n)try{t=new URL(n)}catch{}return{resourceMetadataUrl:t,scope:tN(e,"scope")||void 0,error:tN(e,"error")||void 0}}function tN(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let i=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(i);return a?a[1]||a[2]:null}async function tP(e,t,r=fetch){let i=await tB(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||404===i.status)throw await i?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw await i.body?.cancel(),Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return e8.parse(await i.json())}async function tO(e,t,r=fetch){try{return await r(e,{headers:t})}catch(i){if(i instanceof TypeError)if(t)return tO(e,void 0,r);else return;throw i}}async function tj(e,t,r=fetch){return await tO(e,{"MCP-Protocol-Version":t},r)}async function tB(e,t,r,i){var a,n;let s,o=new URL(e),l=i?.protocolVersion??v.LATEST_PROTOCOL_VERSION;i?.metadataUrl?s=new URL(i.metadataUrl):(s=new URL(function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,o.pathname),i?.metadataServerUrl??o)).search=o.search;let c=await tj(s,l,r);if(!i?.metadataUrl&&(a=c,n=o.pathname,!a||a.status>=400&&a.status<500&&"/"!==n)){let e=new URL(`/.well-known/${t}`,o);c=await tj(e,l,r)}return c}async function tU(e,{fetchFn:t=fetch,protocolVersion:r=v.LATEST_PROTOCOL_VERSION}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"};for(let{url:r,type:a}of function(e){let t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,i=[];if(!r)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}(e)){let e=await tO(r,i,t);if(e){if(!e.ok){if(await e.body?.cancel(),e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===a?"OAuth":"OpenID provider"} metadata from ${r}`)}if("oauth"===a)return e5.parse(await e.json());return e7.parse(await e.json())}}}async function tq(e,t){let r,i;try{(r=await tP(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn)).authorization_servers&&r.authorization_servers.length>0&&(i=r.authorization_servers[0])}catch{}i||(i=String(new URL("/",e)));let a=await tU(i,{fetchFn:t?.fetchFn});return{authorizationServerUrl:i,authorizationServerMetadata:a,resourceMetadata:r}}async function tL(e,{metadata:t,clientInformation:r,redirectUrl:i,scope:a,state:n,resource:s}){let o;if(t){if(o=new URL(t.authorization_endpoint),!t.response_types_supported.includes(t_))throw Error(`Incompatible auth server: does not support response type ${t_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(tE))throw Error(`Incompatible auth server: does not support code challenge method ${tE}`)}else o=new URL("/authorize",e);let l=await e0(),c=l.code_verifier,u=l.code_challenge;return o.searchParams.set("response_type",t_),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",u),o.searchParams.set("code_challenge_method",tE),o.searchParams.set("redirect_uri",String(i)),n&&o.searchParams.set("state",n),a&&o.searchParams.set("scope",a),a?.includes("offline_access")&&o.searchParams.append("prompt","consent"),s&&o.searchParams.set("resource",s.href),{authorizationUrl:o,codeVerifier:c}}async function tM(e,{metadata:t,tokenRequestParams:r,clientInformation:i,addClientAuthentication:a,resource:n,fetchFn:s}){var o,l;let c,u=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});n&&r.set("resource",n.href),a?await a(d,r,u,t):i&&function(e,t,r,i){let{client_id:a,client_secret:n}=t;switch(e){case"client_secret_basic":var s,o,l,c,u=a,d=n,p=r;if(!d)throw Error("client_secret_basic authentication requires a client_secret");let h=btoa(`${u}:${d}`);p.set("Authorization",`Basic ${h}`);return;case"client_secret_post":s=a,o=n,(l=i).set("client_id",s),o&&l.set("client_secret",o);return;case"none":c=a,i.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}((o=i,l=t?.token_endpoint_auth_methods_supported??[],c=void 0!==o.client_secret,"token_endpoint_auth_method"in o&&o.token_endpoint_auth_method&&["client_secret_basic","client_secret_post","none"].includes(o.token_endpoint_auth_method)&&(0===l.length||l.includes(o.token_endpoint_auth_method))?o.token_endpoint_auth_method:0===l.length?c?"client_secret_basic":"none":c&&l.includes("client_secret_basic")?"client_secret_basic":c&&l.includes("client_secret_post")?"client_secret_post":l.includes("none")?"none":c?"client_secret_post":"none"),i,d,r);let p=await (s??fetch)(u,{method:"POST",headers:d,body:r});if(!p.ok)throw await tC(p);return te.parse(await p.json())}async function tF(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:n,fetchFn:s}){let o=new URLSearchParams({grant_type:"refresh_token",refresh_token:i});return{refresh_token:i,...await tM(e,{metadata:t,tokenRequestParams:o,clientInformation:r,addClientAuthentication:n,resource:a,fetchFn:s})}}async function tV(e,t,{metadata:r,resource:i,authorizationCode:a,fetchFn:n}={}){let s,o=e.clientMetadata.scope;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!a)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");s=new URLSearchParams({grant_type:"authorization_code",code:a,code_verifier:await e.codeVerifier(),redirect_uri:String(e.redirectUrl)})}return tM(t,{metadata:r,tokenRequestParams:s,clientInformation:await e.clientInformation()??void 0,addClientAuthentication:e.addClientAuthentication,resource:i,fetchFn:n})}async function tK(e,{metadata:t,clientMetadata:r,scope:i,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let s=await (a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...void 0!==i?{scope:i}:{}})});if(!s.ok)throw await tC(s);return tn.parse(await s.json())}class tH extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class tz{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eW(t?.fetch,t?.requestInit)}async _authThenStart(){let e;if(!this._authProvider)throw new tA("No auth provider");try{e=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tA;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eJ(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new eG(this._url.href,{...this._eventSourceInit,fetch:async(t,r)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(t,{...r,headers:i});if(401===a.status&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=tR(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(401===e.code&&this._authProvider)return void this._authThenStart().then(t,r);let i=new tH(e.code,e.message,e);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",e=>{try{if(this._endpoint=new URL(e.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t;try{t=v.JSONRPCMessageSchema.parse(JSON.parse(e.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(t)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new tA("No auth provider");if("AUTHORIZED"!==await tT(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tA("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error("Not connected");try{let t=await this._commonHeaders();t.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},i=await (this._fetch??fetch)(this._endpoint,r);if(!i.ok){let t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r}=tR(i);this._resourceMetadataUrl=t,this._scope=r;let a=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==a)throw new tA;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${t}`)}await i.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tG extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:i}={}){let a;super({start(n){a=eh({onEvent:e=>{n.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&n.error(t)},onRetry:t,onComment:r,maxBufferSize:i})},transform(e){a.feed(e)}})}}let tJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tW extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class tZ{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eW(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??tJ}async _authThenStart(){let e;if(!this._authProvider)throw new tA("No auth provider");try{e=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tA;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eJ(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);let i=await (this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new tW(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){return void 0!==this._serverRetryMs?this._serverRetryMs:Math.min(this._reconnectionOptions.initialReconnectionDelay*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`));let i=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,r){let i;if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,s=!1,o=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tG({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(i=e.id,s=!0,a?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=v.JSONRPCMessageSchema.parse(JSON.parse(e.data));(0,v.isJSONRPCResultResponse)(t)&&(o=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tA("No auth provider");if("AUTHORIZED"!==await tT(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tA("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r)return void this._startOrAuthSse({resumptionToken:r,replayMessageId:(0,v.isJSONRPCRequest)(e)?e.id:void 0}).catch(e=>this.onerror?.(e));let a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");let n={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await (this._fetch??fetch)(this._url,n),o=s.headers.get("mcp-session-id");if(o&&(this._sessionId=o),!s.ok){let t=await s.text().catch(()=>null);if(401===s.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tW(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:t,scope:r}=tR(s);this._resourceMetadataUrl=t,this._scope=r;let i=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==i)throw new tA;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===s.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r,error:i}=tR(s);if("insufficient_scope"===i){let i=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===i)throw new tW(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=i??void 0;let a=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==a)throw new tA;return this.send(e)}}throw new tW(s.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===s.status){await s.body?.cancel(),(0,v.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,c=s.headers.get("content-type");if(l)if(c?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(c?.includes("application/json")){let e=await s.json();for(let t of Array.isArray(e)?e.map(e=>v.JSONRPCMessageSchema.parse(e)):[v.JSONRPCMessageSchema.parse(e)])this.onmessage?.(t)}else throw await s.body?.cancel(),new tW(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await (this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&405!==r.status)throw new tW(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}var tY=e.i(243783);e.i(582482);var tQ=e.i(91022),tX=e.i(318905),t0=e.i(971619);function t1(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}function t2(e){return e instanceof Date?e.toISOString():"string"==typeof e&&Number.isFinite(Date.parse(e))?new Date(e).toISOString():null}function t3(e){let t;return{id:String(e.id),name:String(e.name),hostname:String(e.hostname),version:String(e.version),osVersion:String(e.osVersion),architecture:String(e.architecture),cpuModel:"string"==typeof e.cpuModel?e.cpuModel:null,memoryTotalBytes:"number"==typeof e.memoryTotalBytes?e.memoryTotalBytes:null,memoryFreeBytes:"number"==typeof e.memoryFreeBytes?e.memoryFreeBytes:null,diskTotalBytes:"number"==typeof e.diskTotalBytes?e.diskTotalBytes:null,diskFreeBytes:"number"==typeof e.diskFreeBytes?e.diskFreeBytes:null,capabilities:Array.isArray(e.capabilities)?e.capabilities:t1(e.capabilitiesJson)??[],baseRepoDirectory:"string"==typeof e.baseRepoDirectory?e.baseRepoDirectory:null,derivedDataLocationMode:String(e.derivedDataLocationMode),derivedDataPath:"string"==typeof e.derivedDataPath?e.derivedDataPath:null,buildsDirectory:"string"==typeof e.buildsDirectory?e.buildsDirectory:null,defaultBuildsDirectory:"string"==typeof e.defaultBuildsDirectory?e.defaultBuildsDirectory:null,effectiveBuildsDirectory:(0,t0.effectiveBuildsDirectory)(e),connectionStatus:null!==(t=t2(e.lastSeenAt))&&Date.now()-Date.parse(t)<=(0,a.agentOnlineWindowMs)(e)&&!e.disconnectedAt?"ONLINE":"OFFLINE",ipAddress:"string"==typeof e.ipAddress?e.ipAddress:null,lastSeenAt:t2(e.lastSeenAt),disconnectedAt:t2(e.disconnectedAt),createdAt:t2(e.createdAt),updatedAt:t2(e.updatedAt)}}function t4(e){let t=t3(e);return{agentId:t.id,baseRepoDirectory:t.baseRepoDirectory,buildsDirectory:t.buildsDirectory,defaultBuildsDirectory:t.defaultBuildsDirectory,effectiveBuildsDirectory:t.effectiveBuildsDirectory,derivedDataLocationMode:t.derivedDataLocationMode,derivedDataPath:t.derivedDataPath,updatedAt:t.updatedAt}}function t6(e){return{id:String(e.id),agentId:String(e.agentId),worktreeId:"string"==typeof e.worktreeId?e.worktreeId:null,codebaseId:"string"==typeof e.codebaseId?e.codebaseId:null,kind:String(e.kind),payload:t1(e.payload??e.payloadJson),status:String(e.status),idempotencyKey:String(e.idempotencyKey),result:t1(e.result??e.resultJson),error:"string"==typeof e.error?e.error:null,timeoutSeconds:Number(e.timeoutSeconds),createdAt:t2(e.createdAt),startedAt:t2(e.startedAt),finishedAt:t2(e.finishedAt),updatedAt:t2(e.updatedAt)}}let t8=e1.object({}),t5=e1.object({id:e1.string(),name:e1.string(),hostname:e1.string(),version:e1.string(),osVersion:e1.string(),architecture:e1.string(),cpuModel:e1.string().nullable(),memoryTotalBytes:e1.number().nullable(),memoryFreeBytes:e1.number().nullable(),diskTotalBytes:e1.number().nullable(),diskFreeBytes:e1.number().nullable(),capabilities:e1.array(e1.string()),baseRepoDirectory:e1.string().nullable(),derivedDataLocationMode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e1.string().nullable(),buildsDirectory:e1.string().nullable(),defaultBuildsDirectory:e1.string().nullable(),effectiveBuildsDirectory:e1.string().nullable(),connectionStatus:e1.enum(["ONLINE","OFFLINE"]),ipAddress:e1.string().nullable(),lastSeenAt:e1.string().nullable(),disconnectedAt:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),t9=e1.object({agentId:e1.string(),baseRepoDirectory:e1.string().nullable(),buildsDirectory:e1.string().nullable(),defaultBuildsDirectory:e1.string().nullable(),effectiveBuildsDirectory:e1.string().nullable(),derivedDataLocationMode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e1.string().nullable(),updatedAt:e1.string()}),t7=e1.object({id:e1.string(),agentId:e1.string(),worktreeId:e1.string().nullable(),codebaseId:e1.string().nullable(),kind:e1.string(),payload:e1.unknown(),status:e1.string(),idempotencyKey:e1.string(),result:e1.unknown().nullable(),error:e1.string().nullable(),timeoutSeconds:e1.number().int(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable(),updatedAt:e1.string()}),re=e1.object({id:e1.string(),jobId:e1.string(),sequence:e1.number().int(),stream:e1.string(),message:e1.string(),createdAt:e1.string()}),rt=e1.object({agentId:e1.string().min(1)});var rr=e.i(190714),ri=e.i(184015);let ra=e1.object({}),rn=e1.object({settings:e1.object({refreshIntervalSeconds:e1.number().int(),fetchIntervalSeconds:e1.number().int(),defaultJiraBranchRegex:e1.string(),updatedAt:e1.string()})}),rs=e1.object({agentId:e1.string().min(1),path:e1.string().nullable().default(null),requestId:e1.string().min(1)}),ro=e1.object({listing:e1.unknown()}),rl=e1.object({agentId:e1.string().min(1),folder:e1.string().min(1),requestId:e1.string().min(1)}),rc=e1.object({inspection:e1.unknown()}),ru=e1.object({codebaseIds:e1.array(e1.string().min(1)).min(1).max(500),requestId:e1.string().min(1)}),rd=e1.object({jobs:e1.array(e1.unknown()),skipped:e1.array(e1.object({codebaseId:e1.string(),reason:e1.string()}))}),rp=e1.object({codebaseId:e1.string().min(1),requestId:e1.string().min(1)}),rh=e1.object({state:e1.unknown()}),rm=e1.object({codebaseId:e1.string().min(1),stashOid:e1.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i),requestId:e1.string().min(1)}),rf=e1.object({diff:e1.unknown()});e.i(282790);var rg=e.i(474170);function ry(e){return e instanceof Date?e.toISOString():null}function rv(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}let rb=e1.object({id:e1.string(),clientRegistrationId:e1.string(),tokenMasked:e1.string(),topic:e1.string(),environment:e1.string(),supportedPushTypes:e1.array(e1.string()),displayName:e1.string(),deviceModel:e1.string().nullable(),osVersion:e1.string().nullable(),appVersion:e1.string().nullable(),appBuild:e1.string().nullable(),locale:e1.string().nullable(),pushMagicConfigured:e1.boolean(),status:e1.string(),invalidatedAt:e1.string().nullable(),lastFailureReason:e1.string().nullable(),lastFailureAt:e1.string().nullable(),lastRegisteredAt:e1.string(),lastSentAt:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),rw=e1.object({id:e1.string(),name:e1.string(),topic:e1.string(),environment:e1.string(),fingerprint:e1.string(),expiresAt:e1.string().nullable(),lastTestedAt:e1.string().nullable(),lastError:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),rx=e1.object({tokenConfigured:e1.boolean(),tokenTeamId:e1.string().nullable(),tokenKeyId:e1.string().nullable(),tokenPrivateKeyFingerprint:e1.string().nullable(),tokenConfiguredAt:e1.string().nullable(),tokenLastUsedAt:e1.string().nullable(),tokenLastError:e1.string().nullable(),certificates:e1.array(rw),updatedAt:e1.string()}),rk=e1.object({id:e1.string(),channelId:e1.string(),bundleId:e1.string(),environment:e1.string(),storagePolicy:e1.string(),createdAt:e1.string(),updatedAt:e1.string()}),rS=e1.object({id:e1.string(),name:e1.string(),editor:e1.unknown(),createdAt:e1.string(),updatedAt:e1.string()}),rI=e1.object({id:e1.string(),registrationId:e1.string().nullable(),topic:e1.string(),environment:e1.string(),status:e1.string(),apnsId:e1.string().nullable(),responseCode:e1.number().int().nullable(),reason:e1.string().nullable(),responseTimestamp:e1.string().nullable(),attempts:e1.number().int(),durationMs:e1.number().int().nullable(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable()}),rA=e1.object({id:e1.string(),requestId:e1.string(),status:e1.string(),editor:e1.unknown(),payload:e1.unknown(),headers:e1.unknown(),targetMode:e1.string(),channelId:e1.string().nullable(),recipientCount:e1.number().int(),successCount:e1.number().int(),failureCount:e1.number().int(),error:e1.string().nullable(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable(),updatedAt:e1.string(),deliveries:e1.array(rI)});function r_(e){return{id:String(e.id),requestId:String(e.requestId),status:String(e.status),editor:rv(e.editor??e.editorJson),payload:rv(e.payload??e.payloadJson),headers:rv(e.headers??e.headersJson),targetMode:String(e.targetMode),channelId:"string"==typeof e.channelId?e.channelId:null,recipientCount:Number(e.recipientCount),successCount:Number(e.successCount),failureCount:Number(e.failureCount),error:"string"==typeof e.error?e.error:null,createdAt:ry(e.createdAt),startedAt:ry(e.startedAt),finishedAt:ry(e.finishedAt),updatedAt:ry(e.updatedAt),deliveries:Array.isArray(e.deliveries)?e.deliveries.map(e=>({id:String(e.id),registrationId:"string"==typeof e.registrationId?e.registrationId:null,topic:String(e.topic),environment:String(e.environment),status:String(e.status),apnsId:"string"==typeof e.apnsId?e.apnsId:null,responseCode:"number"==typeof e.responseCode?e.responseCode:null,reason:"string"==typeof e.reason?e.reason:null,responseTimestamp:ry(e.responseTimestamp),attempts:Number(e.attempts),durationMs:"number"==typeof e.durationMs?e.durationMs:null,createdAt:ry(e.createdAt),startedAt:ry(e.startedAt),finishedAt:ry(e.finishedAt)})):[]}}let rE={requestId:e1.string().min(1),editor:e1.record(e1.string(),e1.unknown())},rC={requestId:e1.string().min(1),presetId:e1.string().min(1)},rT=e1.discriminatedUnion("targetMode",[e1.object({...rE,targetMode:e1.literal("DEVICES"),registrationIds:e1.array(e1.string().min(1)).min(1)}),e1.object({...rE,targetMode:e1.literal("ALL")}),e1.object({...rE,targetMode:e1.literal("BROADCAST"),channelId:e1.string().min(1)}),e1.object({...rE,targetMode:e1.literal("DIRECT"),directToken:e1.string().min(1),directTokenEncoding:e1.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e1.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]),rD=e1.discriminatedUnion("targetMode",[e1.object({...rC,targetMode:e1.literal("DEVICES"),registrationIds:e1.array(e1.string().min(1)).min(1)}),e1.object({...rC,targetMode:e1.literal("ALL")}),e1.object({...rC,targetMode:e1.literal("BROADCAST"),channelId:e1.string().min(1)}),e1.object({...rC,targetMode:e1.literal("DIRECT"),directToken:e1.string().min(1),directTokenEncoding:e1.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e1.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]);function r$(e){return{requestId:e.requestId,editor:e.editor,targetMode:e.targetMode,registrationIds:"DEVICES"===e.targetMode?e.registrationIds:void 0,channelId:"BROADCAST"===e.targetMode?e.channelId:void 0,directToken:"DIRECT"===e.targetMode?e.directToken:void 0,directTokenEncoding:"DIRECT"===e.targetMode?e.directTokenEncoding:void 0,directEnvironment:"DIRECT"===e.targetMode?e.directEnvironment:void 0}}let rR=e1.object({id:e1.string(),entryType:e1.enum(["CONSOLE","ANALYTICS","SEPARATOR"]),clientTime:e1.string(),receivedAt:e1.string(),deviceIp:e1.string().nullable(),message:e1.string().nullable(),level:e1.string().nullable(),category:e1.string().nullable(),eventName:e1.string().nullable(),eventKind:e1.string().nullable(),screenName:e1.string().nullable(),buildId:e1.string().nullable(),sessionId:e1.string().nullable(),attributes:e1.record(e1.string(),e1.unknown()),defaultParameters:e1.record(e1.string(),e1.unknown()),additionalParameters:e1.record(e1.string(),e1.unknown()),highlightColor:e1.string().nullable(),separatorKind:e1.string().nullable(),separatorName:e1.string().nullable()}),rN=e1.object({items:e1.array(rR),nextCursor:e1.string().nullable(),matchingCount:e1.number().int().nonnegative(),totalCount:e1.number().int().nonnegative()}),rP=rN.extend({separator:rR.nullable()}),rO=e1.object({first:e1.number().int().min(1).max(500).default(200),after:e1.string().nullable().default(null)}),rj=e1.object({field:e1.string().min(1),operator:e1.enum(["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"]),value:e1.string().nullable().optional(),caseSensitive:e1.boolean().default(!1),sources:e1.array(e1.enum(["CONSOLE","ANALYTICS"])).optional()}),rB=e1.object({mode:e1.enum(["ALL","ANY"]),conditions:e1.array(rj).min(1).max(100)}),rU={search:e1.string().min(1).nullable().optional(),searchMode:e1.enum(["TEXT","GLOB","REGEX"]).default("TEXT"),caseSensitive:e1.boolean().default(!1),quickFilters:e1.record(e1.string(),e1.array(e1.string()).max(500)).nullable().optional(),advancedFilter:rB.nullable().optional()},rq=rO.extend(rU).refine(rV,{message:"At least one telemetry search filter is required"}),rL=rO.extend(rU),rM=e1.object({scope:e1.literal("MATCHING"),...rU}).refine(rV,{message:"At least one telemetry search filter is required"}),rF=e1.union([e1.object({scope:e1.literal("IDS"),ids:e1.array(e1.string().min(1)).min(1).max(1e3)}),rM,e1.object({scope:e1.literal("ALL"),includeSeparators:e1.boolean().default(!1)}),e1.object({scope:e1.literal("BEFORE_LATEST_SEPARATOR"),includeSeparators:e1.boolean().default(!1)})]);function rV(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function rK(e,t){return{view:e,first:t.first,after:t.after,search:t.search,searchMode:t.searchMode??"TEXT",caseSensitive:t.caseSensitive??!1,quickFilters:t.quickFilters,advancedFilter:t.advancedFilter}}function rH(e,t,r){return[rW({name:`get_${r.plural}`,title:`Get ${r.label}`,description:`Fetch the newest ${r.label.toLocaleLowerCase()} with cursor pagination.`,inputSchema:rO,outputSchema:rN,annotations:rz,handler:r=>e.timeline(rK(t,r))}),rW({name:`get_${r.singular}`,title:`Get ${r.singular.replaceAll("_"," ")}`,description:`Fetch one ${r.label.toLocaleLowerCase()} item by ID.`,inputSchema:e1.object({id:e1.string().min(1)}),outputSchema:e1.object({entry:rR.nullable()}),annotations:rz,handler:async({id:r})=>({entry:await e.entry(r,t)})}),rW({name:`search_${r.plural}`,title:`Search ${r.label}`,description:"Search with text, glob, regex, quick facets, or advanced filter conditions.",inputSchema:rq,outputSchema:rN,annotations:rz,handler:r=>e.timeline(rK(t,r))}),rW({name:`get_${r.plural}_since_latest_separator`,title:`Get ${r.label} since latest separator`,description:"Fetch entries strictly newer than the latest global telemetry separator.",inputSchema:rL,outputSchema:rP,annotations:rz,handler:r=>e.timelineSinceLatestSeparator(rK(t,r))}),rW({name:`get_${r.singular}_search_metadata`,title:`Get ${r.label} search metadata`,description:"Get searchable fields and current facet values.",inputSchema:e1.object({}),outputSchema:e1.object({fields:e1.array(e1.string()),facets:e1.record(e1.string(),e1.array(e1.string()))}),annotations:rz,handler:async()=>{let[r,i]=await Promise.all([e.fields(t),e.facets(t)]);return{fields:r,facets:i}}}),rW({name:`clear_${r.plural}`,title:`Clear ${r.label}`,description:"Clear explicit IDs, matching entries, all entries, or entries before the latest separator.",inputSchema:rF,outputSchema:e1.object({view:e1.enum(["CONSOLE","ANALYTICS","UNIFIED"]),scope:e1.enum(["IDS","MATCHING","ALL","BEFORE_LATEST_SEPARATOR"]),deletedCount:e1.number().int().nonnegative()}),annotations:rJ,handler:async r=>{let i="MATCHING"===r.scope?r:null,a=await e.clearScoped({view:t,scope:r.scope,ids:"IDS"===r.scope?r.ids:null,includeSeparators:("ALL"===r.scope||"BEFORE_LATEST_SEPARATOR"===r.scope)&&r.includeSeparators,query:i?{search:i.search,searchMode:i.searchMode,caseSensitive:i.caseSensitive,quickFilters:i.quickFilters,advancedFilter:i.advancedFilter}:null});return{view:t,scope:r.scope,deletedCount:a}}})]}let rz={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},rG={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},rJ={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function rW(e){return{name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,annotations:e.annotations??rz,invoke:async t=>{let r=e.inputSchema.parse(t);return e.outputSchema.parse(await e.handler(r))}}}function rZ(e){return{id:e.id,name:e.name,source:"BUILTIN",transport:null,url:null,error:null,tools:e.tools.map(e=>({name:e.name,title:e.title,description:e.description,inputSchema:w.toJSONSchema(e.inputSchema),outputSchema:w.toJSONSchema(e.outputSchema)})),children:e.children.map(rZ)}}function rY(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Built-in tool output must be a JSON object");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}class rQ{groups;indexed;byName;groupIds;constructor(e){this.groups=e,this.indexed=function e(t){return t.flatMap(t=>[...t.tools.map(e=>({groupId:t.id,definition:e})),...e(t.children)])}(e),this.byName=new Map,this.groupIds=new Set;const t=e=>{if(this.groupIds.has(e.id))throw Error(`Duplicate built-in tool group id: ${e.id}`);this.groupIds.add(e.id),e.children.forEach(t)};for(const r of(e.forEach(t),this.indexed)){if(this.byName.has(r.definition.name))throw Error(`Duplicate built-in MCP tool name: ${r.definition.name}`);this.byName.set(r.definition.name,r)}}definitions(){return this.indexed.map(({definition:e})=>e)}catalog(){return this.groups.map(rZ)}hasGroup(e){return this.groupIds.has(e)}async call(e,t,r){let i=this.byName.get(t);if(!i||i.groupId!==e)throw Error(`Unknown built-in tool: ${t}`);return rY(await i.definition.invoke(r))}async callByName(e,t){let r=this.byName.get(e);if(!r)throw Error(`Unknown built-in tool: ${e}`);return rY(await r.definition.invoke(t))}}let rX="external:",r0=new Set(["accept","connection","content-length","content-type","host","last-event-id","mcp-protocol-version","mcp-session-id","transfer-encoding"]);function r1(e){if("STREAMABLE_HTTP"===e||"SSE"===e)return e;throw Error(`Unsupported MCP transport: ${e}`)}function r2(e,t){return{id:e.id,name:e.name,url:e.url,transport:r1(e.transport),toolNamePrefix:e.toolNamePrefix,headers:[...e.headers].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({id:e.id,name:e.name,valueConfigured:t})),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}class r3{credentials;builtInTools;constructor(e,t,r={},i=new tQ.CredentialService){this.credentials=i,this.builtInTools=function(e){var t,r,i,a,n,s;let o,l,u,d=[(t=e.codebaseTools,r=e.codebases,o=[rW({name:"get_codebases",title:"Get codebases",description:"List every registered codebase checkout.",inputSchema:c.GetCodebasesInputSchema,outputSchema:c.GetCodebasesOutputSchema,annotations:rz,handler:async()=>({codebases:await t.list()})}),rW({name:"get_codebase",title:"Get codebase",description:"Get one registered codebase by ID or exact folder path.",inputSchema:c.GetCodebaseInputSchema,outputSchema:c.GetCodebaseOutputSchema,annotations:rz,handler:async e=>({codebase:"id"in e?await t.getById(e.id):e.agentId?await t.getByPath(e.path,e.agentId):await t.getByPath(e.path)})})],r&&(o.splice(1,0,rW({name:"search_codebases",title:"Search codebases",description:"Search registered codebases by text, agent, repository, branch, availability, or sync state.",inputSchema:c.SearchCodebasesInputSchema,outputSchema:c.SearchCodebasesOutputSchema,annotations:rz,handler:e=>t.search(e)})),o.push(rW({name:"get_codebase_repositories",title:"Get codebase repositories",description:"List canonical repositories and their checkout counts.",inputSchema:ra,outputSchema:c.GetCodebaseRepositoriesOutputSchema,annotations:rz,handler:async()=>({repositories:await t.repositories()})}),rW({name:"get_codebase_repository",title:"Get codebase repository",description:"Get a canonical repository and all of its registered checkouts.",inputSchema:c.GetCodebaseRepositoryInputSchema,outputSchema:c.GetCodebaseRepositoryOutputSchema,annotations:rz,handler:async({id:e})=>({repository:await t.repository(e)})}),rW({name:"get_codebase_settings",title:"Get codebase settings",description:"Get global codebase refresh, fetch, and branch settings.",inputSchema:ra,outputSchema:rn,annotations:rz,handler:async()=>{let e=await r.settings();return{settings:{refreshIntervalSeconds:e.refreshIntervalSeconds,fetchIntervalSeconds:e.fetchIntervalSeconds,defaultJiraBranchRegex:e.defaultJiraBranchRegex,updatedAt:e.updatedAt.toISOString()}}}}),rW({name:"browse_agent_directory",title:"Browse agent directory",description:"List candidate repository folders on an enrolled agent.",inputSchema:rs,outputSchema:ro,annotations:rz,handler:async({agentId:e,path:t,requestId:i})=>({listing:await r.browse(e,t,i)})}),rW({name:"inspect_agent_codebase",title:"Inspect agent codebase",description:"Inspect a repository folder without registering or changing it.",inputSchema:rl,outputSchema:rc,annotations:rz,handler:async({agentId:e,folder:t,requestId:i})=>({inspection:JSON.parse(JSON.stringify(await r.inspect(e,t,i)))})}),rW({name:"refresh_codebases",title:"Refresh codebases",description:"Queue local metadata refreshes for registered codebases.",inputSchema:ru,outputSchema:rd,annotations:rG,handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(ri.CODEBASE_REFRESH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t6(e)),skipped:i.skipped}}}),rW({name:"fetch_codebases",title:"Fetch codebases",description:"Queue remote Git fetches and configured base-branch updates.",inputSchema:ru,outputSchema:rd,annotations:{...rG,openWorldHint:!0},handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(ri.CODEBASE_FETCH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t6(e)),skipped:i.skipped}}}),rW({name:"inspect_codebase_git_state",title:"Inspect codebase Git state",description:"Inspect branches, checkout locations, and stashes.",inputSchema:rp,outputSchema:rh,annotations:rz,handler:async({codebaseId:e,requestId:t})=>({state:await r.inspectGitState(e,t)})}),rW({name:"inspect_codebase_stash",title:"Inspect codebase stash",description:"Read a bounded textual patch for a Git stash.",inputSchema:rm,outputSchema:rf,annotations:rz,handler:async({codebaseId:e,stashOid:t,requestId:i})=>({diff:await r.inspectStash(e,t,i)})}))),{id:"builtin:codebases",name:"Codebases",tools:o,children:[]})];return e.builds&&d.push((i=e.builds,{id:"builtin:builds",name:"Builds",children:[],tools:[rW({name:"get_builds",title:"Get builds",description:"List immutable iOS build records.",inputSchema:rr.GetBuildsInputSchema,outputSchema:rr.GetBuildsOutputSchema,annotations:rz,handler:async e=>{let t=await i.builds(e);return{builds:t.items,nextCursor:t.nextCursor}}}),rW({name:"get_build",title:"Get build",description:"Get a build with sanitized logs.",inputSchema:rr.GetBuildInputSchema,outputSchema:rr.GetBuildOutputSchema,annotations:rz,handler:async({buildId:e,afterLogId:t,logLimit:r})=>{let a=await i.getBuild(e);if(!a)throw Error("Build not found");return{build:a,logs:await i.logs(e,t,r)}}}),rW({name:"get_build_configurations",title:"Get build configurations",description:"List build configurations for a worktree.",inputSchema:rr.GetBuildConfigurationsInputSchema,outputSchema:rr.GetBuildConfigurationsOutputSchema,annotations:rz,handler:async({worktreeId:e})=>({project:await i.projectForWorktree(e)})}),rW({name:"get_build_destinations",title:"Get build destinations",description:"Inspect compatible build destinations.",inputSchema:rr.GetBuildDestinationsInputSchema,outputSchema:rr.GetBuildDestinationsOutputSchema,annotations:rz,handler:async e=>({destinations:"buildId"in e?await i.destinationsForBuild(e.buildId,e.requestId):await i.destinations(e)})}),rW({name:"start_build",title:"Start build",description:"Queue an iOS build.",inputSchema:rr.StartBuildToolInputSchema,outputSchema:rr.StartBuildToolOutputSchema,annotations:rG,handler:async e=>({build:await i.startBuild(e)})}),rW({name:"cancel_build",title:"Cancel build",description:"Cancel an active build.",inputSchema:rr.CancelBuildToolInputSchema,outputSchema:rr.CancelBuildToolOutputSchema,annotations:rJ,handler:async({buildId:e})=>({build:await i.cancelBuild(e)})}),rW({name:"run_build",title:"Run build",description:"Install and launch without rebuilding.",inputSchema:rr.RunBuildToolInputSchema,outputSchema:rr.RunBuildToolOutputSchema,annotations:rG,handler:async e=>({deployments:await i.runBuild(e)})}),rW({name:"export_build_archive",title:"Export build archive",description:"Export an archive to a local IPA folder.",inputSchema:rr.ExportBuildToolInputSchema,outputSchema:rr.ExportBuildToolOutputSchema,annotations:rG,handler:async e=>({export:await i.exportArchive(e)})})]})),e.telemetry&&e.pushNotifications&&d.push((a=e.telemetry,n=e.pushNotifications,(l=rH(a,"UNIFIED",{plural:"unified_events",singular:"unified_event",label:"Unified Events"})).push(rW({name:"get_telemetry_separators",title:"Get telemetry separators",description:"List global manual and build separators with optional filters.",inputSchema:e1.object({first:e1.number().int().min(1).max(500).default(100),after:e1.string().nullable().default(null),kind:e1.string().min(1).nullable().optional(),name:e1.string().min(1).nullable().optional(),buildId:e1.string().min(1).nullable().optional()}),outputSchema:e1.object({items:e1.array(rR),nextCursor:e1.string().nullable()}),annotations:rz,handler:e=>a.separators(e)}),rW({name:"add_telemetry_separator",title:"Add telemetry separator",description:"Add a global manual separator to all telemetry views.",inputSchema:e1.object({name:e1.string().max(100).nullable().default(null)}),outputSchema:e1.object({separator:rR}),annotations:{...rG,idempotentHint:!1},handler:async({name:e})=>({separator:await a.addSeparator(e)})}),rW({name:"get_telemetry_settings",title:"Get telemetry settings",description:"Get telemetry collection state and effective ingestion URLs.",inputSchema:e1.object({}),outputSchema:e1.object({settings:e1.object({localBaseUrlOverride:e1.string().nullable(),remoteBaseUrlOverride:e1.string().nullable(),consoleCollectionEnabled:e1.boolean(),analyticsCollectionEnabled:e1.boolean(),detectedLocalBaseUrl:e1.string(),detectedRemoteBaseUrl:e1.string(),effectiveLocalBaseUrl:e1.string(),effectiveRemoteBaseUrl:e1.string(),updatedAt:e1.string()})}),annotations:rz,handler:async()=>({settings:await a.settings()})})),{id:"builtin:debugging",name:"Debugging",tools:l,children:[{id:"builtin:debugging:console-logs",name:"Console Logs",tools:rH(a,"CONSOLE",{plural:"console_logs",singular:"console_log",label:"Console Logs"}),children:[]},{id:"builtin:debugging:analytics-events",name:"Analytics Events",tools:rH(a,"ANALYTICS",{plural:"analytics_events",singular:"analytics_event",label:"Analytics Events"}),children:[]},(u={...rG,openWorldHint:!0},{id:"builtin:debugging:push-notifications",name:"Push Notifications",children:[],tools:[rW({name:"get_push_notification_registrations",title:"Get push notification registrations",description:"List registered APNs devices with masked tokens.",inputSchema:e1.object({}),outputSchema:e1.object({registrations:e1.array(rb)}),annotations:rz,handler:async()=>({registrations:(await n.registrations()).map(e=>{let t,r;return t=Array.isArray(e.supportedPushTypes)?e.supportedPushTypes:rv(e.pushTypesJson),r="string"==typeof e.token?e.token:"",{id:String(e.id),clientRegistrationId:String(e.clientRegistrationId),tokenMasked:"string"==typeof e.tokenMasked?e.tokenMasked:r?`${r.slice(0,8)}…${r.slice(-8)}`:"—",topic:String(e.topic),environment:String(e.environment),supportedPushTypes:Array.isArray(t)?t:[],displayName:String(e.displayName),deviceModel:"string"==typeof e.deviceModel?e.deviceModel:null,osVersion:"string"==typeof e.osVersion?e.osVersion:null,appVersion:"string"==typeof e.appVersion?e.appVersion:null,appBuild:"string"==typeof e.appBuild?e.appBuild:null,locale:"string"==typeof e.locale?e.locale:null,pushMagicConfigured:!!e.pushMagic,status:String(e.status),invalidatedAt:ry(e.invalidatedAt),lastFailureReason:"string"==typeof e.lastFailureReason?e.lastFailureReason:null,lastFailureAt:ry(e.lastFailureAt),lastRegisteredAt:ry(e.lastRegisteredAt),lastSentAt:ry(e.lastSentAt),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}})})}),rW({name:"get_push_notification_settings",title:"Get push notification settings",description:"Inspect APNs credential status without returning secrets.",inputSchema:e1.object({}),outputSchema:e1.object({settings:rx}),annotations:rz,handler:async()=>{var e;return{settings:{tokenConfigured:!!(e=await n.settings()).tokenConfigured,tokenTeamId:"string"==typeof e.tokenTeamId?e.tokenTeamId:null,tokenKeyId:"string"==typeof e.tokenKeyId?e.tokenKeyId:null,tokenPrivateKeyFingerprint:"string"==typeof e.tokenPrivateKeyFingerprint?e.tokenPrivateKeyFingerprint:null,tokenConfiguredAt:ry(e.tokenConfiguredAt),tokenLastUsedAt:ry(e.tokenLastUsedAt),tokenLastError:"string"==typeof e.tokenLastError?e.tokenLastError:null,certificates:Array.isArray(e.certificates)?e.certificates.map(e=>({id:String(e.id),name:String(e.name),topic:String(e.topic),environment:String(e.environment),fingerprint:String(e.fingerprint),expiresAt:ry(e.expiresAt),lastTestedAt:ry(e.lastTestedAt),lastError:"string"==typeof e.lastError?e.lastError:null,createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)})):[],updatedAt:ry(e.updatedAt)}}}}),rW({name:"get_push_notification_channels",title:"Get push notification channels",description:"List configured APNs broadcast channels.",inputSchema:e1.object({}),outputSchema:e1.object({channels:e1.array(rk)}),annotations:rz,handler:async()=>({channels:(await n.channels()).map(e=>({id:String(e.id),channelId:String(e.channelId),bundleId:String(e.bundleId),environment:String(e.environment),storagePolicy:String(e.storagePolicy),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}))})}),rW({name:"get_push_notification_presets",title:"Get push notification presets",description:"List saved, validated push editor presets.",inputSchema:e1.object({}),outputSchema:e1.object({presets:e1.array(rS)}),annotations:rz,handler:async()=>({presets:(await n.presets()).map(e=>({id:String(e.id),name:String(e.name),editor:rv(e.editor??e.editorJson),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}))})}),rW({name:"get_push_notification_history",title:"Get push notification history",description:"List recent push batches and per-recipient delivery results.",inputSchema:e1.object({limit:e1.number().int().min(1).max(200).default(100)}),outputSchema:e1.object({batches:e1.array(rA)}),annotations:rz,handler:async({limit:e})=>({batches:(await n.history(e)).map(e=>r_(e))})}),rW({name:"get_push_notification_history_item",title:"Get push notification history item",description:"Get one push batch and all delivery results by ID.",inputSchema:e1.object({id:e1.string().min(1)}),outputSchema:e1.object({batch:rA.nullable()}),annotations:rz,handler:async({id:e})=>{let t=await n.historyItem(e);return{batch:t?r_(t):null}}}),rW({name:"preview_push_notification",title:"Preview push notification",description:"Validate an editor and return its final payload and APNs headers.",inputSchema:e1.object({editor:e1.record(e1.string(),e1.unknown())}),outputSchema:e1.object({editor:e1.unknown(),payload:e1.unknown(),headers:e1.record(e1.string(),e1.string()),byteLength:e1.number().int().nonnegative()}),annotations:rz,handler:({editor:e})=>(0,rg.validatePushEditor)(e)}),rW({name:"send_push_notification",title:"Send push notification",description:"Validate and queue a raw APNs editor payload for delivery.",inputSchema:rT,outputSchema:e1.object({batch:rA}),annotations:u,handler:async e=>({batch:r_(await n.send(r$(e)))})}),rW({name:"send_push_notification_preset",title:"Send push notification preset",description:"Load a saved preset by ID and queue it for APNs delivery.",inputSchema:rD,outputSchema:e1.object({batch:rA}),annotations:u,handler:async e=>{let t=await n.preset(e.presetId);if(!t)throw Error("Push notification preset not found");let r={...e,editor:rv(t.editorJson)};return{batch:r_(await n.send(r$(r)))}}}),rW({name:"resend_push_notification",title:"Resend push notification",description:"Queue a historical non-draft, non-direct batch again.",inputSchema:e1.object({id:e1.string().min(1),requestId:e1.string().min(1)}),outputSchema:e1.object({batch:rA}),annotations:u,handler:async({id:e,requestId:t})=>({batch:r_(await n.resend(e,t))})})]})]})),e.agents&&d.push((s=e.agents,{id:"builtin:agents",name:"Agents",children:[],tools:[rW({name:"get_agents",title:"Get agents",description:"List enrolled agents, capabilities, resources, and status.",inputSchema:t8,outputSchema:e1.object({agents:e1.array(t5)}),annotations:rz,handler:async()=>({agents:(await s.listAgents()).map(e=>t3(e))})}),rW({name:"get_agent",title:"Get agent",description:"Get one enrolled agent by ID.",inputSchema:rt,outputSchema:e1.object({agent:t5.nullable()}),annotations:rz,handler:async({agentId:e})=>{let t=await s.getAgent(e);return{agent:t?t3(t):null}}}),rW({name:"get_agent_settings",title:"Get agent settings",description:"Get repository, build, and Derived Data paths for an agent.",inputSchema:rt,outputSchema:e1.object({settings:t9}),annotations:rz,handler:async({agentId:e})=>{let t=await s.getAgent(e);if(!t)throw Error("Agent not found");return{settings:t4(t)}}}),rW({name:"get_agent_jobs",title:"Get agent jobs",description:"List recent user-visible jobs for an agent.",inputSchema:e1.object({agentId:e1.string().min(1),limit:e1.number().int().min(1).max(200).default(50)}),outputSchema:e1.object({jobs:e1.array(t7)}),annotations:rz,handler:async({agentId:e,limit:t})=>({jobs:(await s.listJobs(e,t)).map(e=>t6(e))})}),rW({name:"get_agent_job",title:"Get agent job",description:"Get one agent job and its result by ID.",inputSchema:e1.object({jobId:e1.string().min(1)}),outputSchema:e1.object({job:t7.nullable()}),annotations:rz,handler:async({jobId:e})=>{let t=await s.getJob(e);return{job:t?t6(t):null}}}),rW({name:"get_agent_job_logs",title:"Get agent job logs",description:"Fetch ordered job logs after an optional sequence number.",inputSchema:e1.object({jobId:e1.string().min(1),afterSequence:e1.number().int().min(-1).default(-1)}),outputSchema:e1.object({logs:e1.array(re)}),annotations:rz,handler:async({jobId:e,afterSequence:t})=>({logs:(await s.listLogs(e,t)).map(e=>({id:String(e.id),jobId:String(e.jobId),sequence:Number(e.sequence),stream:String(e.stream),message:String(e.message),createdAt:t2(e.createdAt)}))})}),rW({name:"update_agent_base_repo_directory",title:"Update agent base repository directory",description:"Set or reset the absolute base repository directory.",inputSchema:e1.object({agentId:e1.string().min(1),baseRepoDirectory:e1.string().min(1).nullable()}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,baseRepoDirectory:t})=>({settings:t4(await s.updateBaseRepoDirectory(e,t))})}),rW({name:"update_agent_builds_directory",title:"Update agent builds directory",description:"Set or reset the absolute build-output directory.",inputSchema:e1.object({agentId:e1.string().min(1),buildsDirectory:e1.string().min(1).nullable()}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,buildsDirectory:t})=>({settings:t4(await s.updateBuildsDirectory(e,t))})}),rW({name:"update_agent_derived_data_settings",title:"Update agent Derived Data settings",description:"Set default, absolute, or worktree-relative Derived Data paths.",inputSchema:e1.object({agentId:e1.string().min(1),mode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),path:e1.string().min(1).nullable().default(null)}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,mode:t,path:r})=>({settings:t4(await s.updateDerivedDataSettings(e,t,r))})}),rW({name:"request_agent_codebase_reconcile",title:"Request agent codebase reconcile",description:"Ask an online agent to reconcile its registered codebases.",inputSchema:rt,outputSchema:e1.object({requested:e1.boolean()}),annotations:rG,handler:async({agentId:e})=>({requested:await s.requestCodebaseReconcile([e])===1})}),rW({name:"cancel_agent_job",title:"Cancel agent job",description:"Cancel a queued or running agent job.",inputSchema:e1.object({jobId:e1.string().min(1)}),outputSchema:e1.object({job:t7}),annotations:rJ,handler:async({jobId:e})=>({job:t6(await s.cancelJob(e))})})]})),new rQ(d)}({codebaseTools:e,builds:t,...r})}async externalServers(){let e=await (0,tY.getPrismaClient)();return Promise.all((await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}})).map(async e=>r2(e,0===e.headers.length||await this.credentials.isConfigured((0,tX.externalMcpHeadersCredential)(e.id)))))}async createExternalServer(e){return this.saveExternalServer(null,e)}async updateExternalServer(e,t){return this.saveExternalServer(e,t)}async saveExternalServer(e,t){let r=function(e){let t,r=e.name.trim();if(!r)throw Error("Server name is required");if(r.length>80)throw Error("Server name must be 80 characters or fewer");try{t=new URL(e.url.trim())}catch{throw Error("Server URL must be a valid HTTP or HTTPS URL")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Server URL must be an HTTP or HTTPS URL without embedded credentials");if("STREAMABLE_HTTP"!==e.transport&&"SSE"!==e.transport)throw Error("Transport must be Streamable HTTP or SSE");let i=e.toolNamePrefix?.trim()??"";if(i.length>64||!/^[A-Za-z0-9_.-]*$/.test(i))throw Error("Tool name prefix may contain up to 64 letters, numbers, underscores, periods, or hyphens");let a=new Set,n=e.headers.map(e=>{let t=e.name.trim();if(!t)throw Error("Header name is required");let r=t.toLowerCase();if(r0.has(r))throw Error(`${t} is managed by the MCP transport`);if(a.has(r))throw Error(`Duplicate header name: ${t}`);a.add(r);try{new Headers([[t,e.value??"validation"]])}catch{throw Error(`Invalid HTTP header: ${t}`)}return{id:e.id??null,name:t,value:e.value}});return{name:r,url:t.toString(),transport:e.transport,toolNamePrefix:i,headers:n}}(t),i=await (0,tY.getPrismaClient)();if((await i.externalMcpServer.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.name.toLocaleLowerCase()))throw Error("An MCP server with this name already exists");let a=e?await i.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}}):null;if(e&&!a)throw Error("External MCP server not found");let n=new Map(a?.headers.map(e=>[e.id,e])??[]),s=e??(0,g.randomUUID)(),o=(0,tX.externalMcpHeadersCredential)(s),l=new Map((e?await this.credentials.getJson(o)??[]:[]).map(e=>[e.id,e]));for(let e of r.headers){if(e.id&&!n.has(e.id))throw Error(`Header ${e.name} does not belong to this server`);if(!e.id&&!e.value)throw Error(`A value is required for the new ${e.name} header`)}let c=r.headers.map(e=>{let t=e.id??(0,g.randomUUID)(),r=e.value||l.get(t)?.value;if(!r)throw Error(`A value is required for ${e.name}`);return{id:t,name:e.name,value:r}}),u=async e=>{await e.externalMcpServer.upsert({where:{id:s},create:{id:s,name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix},update:{name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix}}),await e.externalMcpServerHeader.deleteMany({where:{serverId:s}}),c.length&&await e.externalMcpServerHeader.createMany({data:c.map(e=>({id:e.id,serverId:s,name:e.name}))})};return c.length?await this.credentials.setJson(o,c,u):await this.credentials.delete(o,u),r2(await i.externalMcpServer.findUniqueOrThrow({where:{id:s},include:{headers:!0}}),!0)}async deleteExternalServer(e){return await this.credentials.delete((0,tX.externalMcpHeadersCredential)(e),async t=>{await t.externalMcpServer.delete({where:{id:e}})}),{id:e}}async catalog(){let e=await (0,tY.getPrismaClient)(),t=await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}}),r=await Promise.all(t.map(async e=>{try{let t=await this.listRemoteTools(await this.externalServerWithSecrets(e.id));return{id:`${rX}${e.id}`,name:e.name,source:"EXTERNAL",transport:r1(e.transport),url:e.url,error:null,tools:t.map(t=>({...t,name:`${e.toolNamePrefix}${t.name}`})),children:[]}}catch(t){return{id:`${rX}${e.id}`,name:e.name,source:"EXTERNAL",transport:r1(e.transport),url:e.url,error:t instanceof Error?t.message:String(t),tools:[],children:[]}}}));return{groups:[...this.builtInTools.catalog(),...r]}}async callTool(e){if(this.builtInTools.hasGroup(e.groupId))return this.builtInTools.call(e.groupId,e.name,e.arguments);if(!e.groupId.startsWith(rX))throw Error("Unknown tool group");let t=e.groupId.slice(rX.length),r=await this.externalServerWithSecrets(t);if(!e.name.startsWith(r.toolNamePrefix))throw Error("Tool name does not use this server's configured prefix");let i=e.name.slice(r.toolNamePrefix.length);if(!i)throw Error("Tool name is required");return this.withClient(r,t=>t.callTool({name:i,arguments:e.arguments},void 0,{timeout:12e4,resetTimeoutOnProgress:!0}))}async externalServerWithSecrets(e){let t=await (0,tY.getPrismaClient)(),r=await t.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}});if(!r)throw Error("External MCP server not found");if(r1(r.transport),!r.headers.length)return{...r,headers:[]};let i=await this.credentials.getJson((0,tX.externalMcpHeadersCredential)(r.id));if(!i)throw Error("External MCP server headers are not configured; re-enter them in Settings");let a=new Map(i.map(e=>[e.id,e]));return{...r,headers:r.headers.map(e=>{let t=a.get(e.id);if(!t?.value)throw Error(`External MCP header ${e.name} is missing; re-enter it in Settings`);return{id:e.id,name:e.name,value:t.value}})}}async withClient(e,t){var r;let i,a=new eu({name:"ai-development-environment-tools",version:"0.1.0"}),n=(r=e,async(e,t)=>{let i=new Headers(r.headers.map(e=>[e.name,e.value]));return e instanceof Request&&e.headers.forEach((e,t)=>i.set(t,e)),new Headers(t?.headers).forEach((e,t)=>i.set(t,e)),fetch(e,{...t,headers:i})}),s="STREAMABLE_HTTP"===r1(e.transport)?new tZ(new URL(e.url),{fetch:n}):new tz(new URL(e.url),{fetch:n}),o=()=>i??=a.close().catch(()=>void 0);try{let e;try{await Promise.race([a.connect(s,{timeout:15e3}),new Promise((t,r)=>{e=setTimeout(()=>{o(),r(Error("External MCP server connection timed out after 15000ms"))},15e3)})])}finally{e&&clearTimeout(e)}return await t(a)}finally{await o()}}async listRemoteTools(e){return this.withClient(e,async e=>{let t,r=[],i=new Set,a=0;do{let n=await e.listTools(t?{cursor:t}:void 0,{timeout:15e3});a+=1,r.push(...n.tools.map(e=>({name:e.name,title:e.title??null,description:e.description??null,inputSchema:e.inputSchema,outputSchema:e.outputSchema??null})));let s=n.nextCursor;if(s){if(i.has(s))throw Error("External MCP server returned a repeated tools/list cursor");if(a>=100)throw Error("External MCP server exceeded the tools/list pagination limit of 100 pages");i.add(s)}t=s}while(t)return r})}}class r4{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},v.CreateMessageResultSchema,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.")}let a="form"===i&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},v.ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class r6 extends et{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v.LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new es,this.setRequestHandler(v.InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(v.InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(v.SetLevelRequestSchema,async(e,t)=>{let r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=e.params,a=v.LoggingLevelSchema.safeParse(i);return a.success&&this._loggingLevels.set(r,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new r4(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=ei(this._capabilities,e)}setRequestHandler(e,t){let r,i=(0,y.getObjectShape)(e),a=i?.method;if(!a)throw Error("Schema is missing a method literal");if((0,y.isZ4Schema)(a)){let e=a._zod?.def;r=e?.value??a.value}else{let e=a._def;r=e?.value??a.value}if("string"!=typeof r)throw Error("Schema method literal must be a string");if("tools/call"===r){let r=async(e,r)=>{let i=(0,y.safeParse)(v.CallToolRequestSchema,e);if(!i.success){let e=i.error instanceof Error?i.error.message:String(i.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:a}=i.data,n=await Promise.resolve(t(e,r));if(a.task){let e=(0,y.safeParse)(v.CreateTaskResultSchema,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=(0,y.safeParse)(v.CallToolResultSchema,n);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){ec(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&el(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:v.SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:v.LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},v.EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},v.CreateMessageResultWithToolsSchema,t):this.request({method:"sampling/createMessage",params:e},v.CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},v.ElicitResultSchema,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let r="form"===e.mode?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:r},v.ElicitResultSchema,t);if("accept"===i.action&&i.content&&r.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(i.content);if(!e.valid)throw new v.McpError(v.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof v.McpError)throw e;throw new v.McpError(v.ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},v.ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let r8=Symbol.for("mcp.completable");function r5(e){return!!e&&"object"==typeof e&&r8 in e}(i||(i={})).Completable="McpCompletable";let r9=/^[A-Za-z0-9._-]{1,128}$/;function r7(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!r9.test(e)){let r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var r=t.warnings;if(r.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),r))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class ie{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let i={taskSupport:"required",...t.execution};if("forbidden"===i.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,i,t._meta,r)}}class it{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new r6(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new ie(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(il(v.CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(v.ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r,i={name:e,title:t.title,description:t.description,inputSchema:(r=(0,y.normalizeObjectSchema)(t.inputSchema))?Q(r,{strictUnions:!0,pipeStrategy:"input"}):ir,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=(0,y.normalizeObjectSchema)(t.outputSchema);e&&(i.outputSchema=Q(e,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(v.CallToolRequestSchema,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new v.McpError(v.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if(("required"===a||"optional"===a)&&!n)throw new v.McpError(v.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if("required"===a&&!i)throw new v.McpError(v.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===a&&!i&&n)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,s,t);if(i)return o;return await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof v.McpError&&e.code===v.ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let i=(0,y.normalizeObjectSchema)(e.inputSchema)??e.inputSchema,a=await (0,y.safeParseAsync)(i,t);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,y.getParseErrorMessage)(e);throw new v.McpError(v.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${t}`)}return a.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new v.McpError(v.ErrorCode.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let i=(0,y.normalizeObjectSchema)(e.outputSchema),a=await (0,y.safeParseAsync)(i,t.structuredContent);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,y.getParseErrorMessage)(e);throw new v.McpError(v.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${t}`)}}async executeToolHandler(e,t,r){let i=e.handler;if("createTask"in i){if(!r.taskStore)throw Error("No task store provided.");let a={...r,taskStore:r.taskStore};return e.inputSchema?await Promise.resolve(i.createTask(t,a)):await Promise.resolve(i.createTask(a))}return e.inputSchema?await Promise.resolve(i(t,r)):await Promise.resolve(i(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},s=i?await Promise.resolve(a.createTask(i,n)):await Promise.resolve(a.createTask(n)),o=s.task.taskId,l=s.task,c=l.pollInterval??5e3;for(;"completed"!==l.status&&"failed"!==l.status&&"cancelled"!==l.status;){await new Promise(e=>setTimeout(e,c));let e=await r.taskStore.getTask(o);if(!e)throw new v.McpError(v.ErrorCode.InternalError,`Task ${o} not found during polling`);l=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(il(v.CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(v.CompleteRequestSchema,async e=>{switch(e.params.ref.type){case"ref/prompt":return(0,v.assertCompleteRequestPrompt)(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return(0,v.assertCompleteRequestResourceTemplate)(e),this.handleResourceCompletion(e,e.params.ref);default:throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r,i=this._registeredPrompts[t.name];if(!i)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!i.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!i.argsSchema)return iu;let a=(0,y.getObjectShape)(i.argsSchema),n=a?.[e.params.argument.name];if(!r5(n))return iu;let s=(r=n[r8],r?.complete);return s?ic(await s(e.params.argument.value,e.params.context)):iu}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return iu;throw new v.McpError(v.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=r.resourceTemplate.completeCallback(e.params.argument.name);return i?ic(await i(e.params.argument.value,e.params.context)):iu}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(il(v.ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(il(v.ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(v.ListResourcesRequestSchema,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),i=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let r of(await e.resourceTemplate.listCallback(t)).resources)i.push({...e.metadata,...r});return{resources:[...r,...i]}}),this.server.setRequestHandler(v.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(v.ReadResourceRequestSchema,async(e,t)=>{let r=new URL(e.params.uri),i=this._registeredResources[r.toString()];if(i){if(!i.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Resource ${r} disabled`);return i.readCallback(r,t)}for(let e of Object.values(this._registeredResourceTemplates)){let i=e.resourceTemplate.uriTemplate.match(r.toString());if(i)return e.readCallback(r,i,t)}throw new v.McpError(v.ErrorCode.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(il(v.GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(v.ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{var r;let i;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,(i=(0,y.getObjectShape)(r))?Object.entries(i).map(([e,t])=>({name:e,description:(0,y.getSchemaDescription)(t),required:!(0,y.isSchemaOptional)(t)})):[]):void 0}})})),this.server.setRequestHandler(v.GetPromptRequestSchema,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let i=(0,y.normalizeObjectSchema)(r.argsSchema),a=await (0,y.safeParseAsync)(i,e.params.arguments);if(!a.success){let t="error"in a?a.error:"Unknown error",r=(0,y.getParseErrorMessage)(t);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${r}`)}let n=a.data,s=r.callback;return await Promise.resolve(s(n,t))}{let e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let i;"object"==typeof r[0]&&(i=r.shift());let a=r[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let r=this._createRegisteredResource(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,i){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,i,a){let n={name:e,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,i,a){let n={resourceTemplate:r,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!r.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,i,a){let n={title:t,description:r,argsSchema:void 0===i?void 0:(0,y.objectFromShape)(i),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=(0,y.objectFromShape)(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,i&&Object.values(i).some(e=>r5(e instanceof e1.ZodOptional?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,i,a,n,s,o,l){r7(e);let c={title:t,description:r,inputSchema:io(i),outputSchema:io(a),annotations:n,execution:s,_meta:o,handler:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&r7(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),void 0!==t.title&&(c.title=t.title),void 0!==t.description&&(c.description=t.description),void 0!==t.paramsSchema&&(c.inputSchema=(0,y.objectFromShape)(t.paramsSchema)),void 0!==t.outputSchema&&(c.outputSchema=(0,y.objectFromShape)(t.outputSchema)),void 0!==t.callback&&(c.handler=t.callback),void 0!==t.annotations&&(c.annotations=t.annotations),void 0!==t._meta&&(c._meta=t._meta),void 0!==t.enabled&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){let r,i,a,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(r=t.shift()),t.length>1){let r=t[0];if(is(r))i=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!is(t[0])&&(n=t.shift());else if("object"==typeof r&&null!==r){if(Object.values(r).some(e=>"object"==typeof e&&null!==e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,i,a,n,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:i,description:a,inputSchema:n,outputSchema:s,annotations:o,_meta:l}=t;return this._createRegisteredTool(e,i,a,n,s,o,{taskSupport:"forbidden"},l,r)}prompt(e,...t){let r,i;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(i=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:n}=t,s=this._createRegisteredPrompt(e,i,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}let ir={type:"object",properties:{}};function ii(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function ia(e){return"_def"in e||"_zod"in e||ii(e)}function is(e){return!("object"!=typeof e||null===e||ia(e))&&(0===Object.keys(e).length||Object.values(e).some(ii))}function io(e){if(e){if(is(e))return(0,y.objectFromShape)(e);if(!ia(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function il(e){let t=(0,y.getObjectShape)(e),r=t?.method;if(!r)throw Error("Schema is missing a method literal");let i=(0,y.getLiteralValue)(r);if("string"==typeof i)return i;throw Error("Schema method literal must be a string")}function ic(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let iu={completion:{values:[],hasMore:!1}};e.s(["createBuiltInMcpServer",0,function(e){let t=new it({name:"ai-development-environment",version:"0.1.0"}),r=t.registerTool.bind(t);for(let t of e.definitions())r(t.name,{title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations},async r=>e.callByName(t.name,r));return t}],700909),e.s([],719961);var id=e.i(504173),ip=e.i(750227),ih=e.i(320058),im=e.i(661983);function ig(e,t){let r=[],i=e.includes("CLAUDE");return i&&r.push("CLAUDE"),(e.includes("CODEX")||!i&&e.length>0||"GLOBAL"===t&&e.includes("GITHUB_COPILOT"))&&r.push("AGENTS"),r}let iy="default",iv=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],ib=["SCAN","READ"],iw=[...ib,"APPLY"],ix={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},ik={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function iS(e,t){if(!e)return t;try{return JSON.parse(e)}catch{return t}}function iI(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function iA(e,t){return"AGENTS"===t?[".agents","skills"]:"CLAUDE"===t?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".copilot","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".github","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".opencode","skills"]}function i_(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?ip.win32:ip.posix}function iE(e,...t){return i_(e).join(e,...t)}function iC(e){return i_(e).dirname(e)}class iT{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(ih.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(ih.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(ih.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){im.agentEventBus.publish(im.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&im.agentEventBus.publish((0,im.skillSyncRunTopic)(e),{id:e})}subscribe(){return im.agentEventBus.iterate(im.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return im.agentEventBus.iterate((0,im.skillSyncRunTopic)(e))}async settings(){return(await (0,tY.getPrismaClient)()).skillSettings.upsert({where:{id:iy},create:{id:iy},update:{}})}async overview(e=""){let t=await (0,tY.getPrismaClient)(),r=e.trim().toLocaleLowerCase(),[i,a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:ix,orderBy:{name:"asc"}}),t.skillGroup.findMany({include:ik,orderBy:{name:"asc"}}),t.skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]}),t.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]}),this.settings(),t.codebaseRepository.findMany({orderBy:{name:"asc"}})]);return{skills:r?i.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(r))):i,groups:a,observations:n,installations:r?s.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(r))):s,settings:o,repositories:l}}async getSkill(e){return(await (0,tY.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:ix})}async saveSkill(e){let t,r=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,ih.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,ih.hashSkillFiles)(t),files:t})),i=[...new Set(e.groupIds)].slice(0,100),a=await (0,tY.getPrismaClient)();if(await a.skillGroup.count({where:{id:{in:i}}})!==i.length)throw Error("One or more skill groups were not found");let n=await a.skill.findUnique({where:{name:r.name}});if(n&&n.id!==e.id)throw Error("Skill names must be unique");let s=e.id??(0,g.randomUUID)(),o=e.id?await a.skillGroupSkill.findMany({where:{skillId:s},select:{groupId:!0}}):[];return await a.$transaction(async t=>{await t.skill.upsert({where:{id:s},create:{id:s,name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash},update:{name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:s}}),await t.skillFile.createMany({data:r.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,g.randomUUID)(),skillId:s,path:e.path,contents:t,executable:e.executable,contentHash:(0,g.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:s}}),i.length&&await t.skillGroupSkill.createMany({data:i.map(e=>({groupId:e,skillId:s}))})}),this.publish(),await this.scheduleAutoSync([...i,...o.map(e=>e.groupId)]),await this.getSkill(s)}async deleteSkill(e){let t=await (0,tY.getPrismaClient)(),r=await t.skill.findUnique({where:{id:e},include:{groups:!0}});return!!r&&(await t.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(r.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),i=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,tY.getPrismaClient)(),[n,s,o]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:i}}}),a.skillGroup.findUnique({where:{name:t}})]);if(n!==r.length)throw Error("One or more skills were not found");if(s!==i.length)throw Error("One or more repositories were not found");if(o&&o.id!==e.id)throw Error("Group names must be unique");let l=e.id??(0,g.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:l},create:{id:l,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:l}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:l}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:l,skillId:e}))}),i.length&&await e.codebaseRepositorySkillGroup.createMany({data:i.map(e=>({groupId:l,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([l]),a.skillGroup.findUniqueOrThrow({where:{id:l},include:ik})}async validateGroupIds(e){let t=[...new Set(e)].slice(0,100),r=await (0,tY.getPrismaClient)();if(await r.skillGroup.count({where:{id:{in:t}}})!==t.length)throw Error("One or more skill groups were not found");return t}async groupsForRepository(e){let t=await (0,tY.getPrismaClient)();return(await t.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillGroup.deleteMany({where:{id:e}});return r.count&&this.publish(),r.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r.count>0}async saveSettings(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSettings.upsert({where:{id:iy},create:{id:iy,...e},update:e});return this.publish(),r.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r}async setRepositoryGroups(e,t){let r=await this.validateGroupIds(t),i=await (0,tY.getPrismaClient)();await i.$transaction(async t=>{await t.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),r.length&&await t.codebaseRepositorySkillGroup.createMany({data:r.map(t=>({repositoryId:e,groupId:t}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let t of[...new Set(e)])await this.prepareSync("GROUP",t,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let t=await (0,tY.getPrismaClient)(),r=await t.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),i=new Map;for(let e of r)for(let t of(i.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))i.set(t.folder,{codebaseId:e.id,worktreeId:t.id,folder:t.folder});return[...i.values()]}async prepareSync(e,t,r=!1){let i=await (0,tY.getPrismaClient)();if(t&&!await i.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(r){let r=await i.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:iv}},orderBy:{createdAt:"desc"}});if(r)return r}let a=await i.skillSyncRun.create({data:{id:(0,g.randomUUID)(),kind:e,groupId:t??null,automatic:r,status:"PREPARING"}}),n=iI(await this.settings()),s=await i.agent.findMany({orderBy:{name:"asc"}});for(let e of s){let t=await i.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:a.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:ih.SKILL_SCAN_JOB_KIND,payload:{tools:n,targets:await this.targets(e.id),syncRunId:a.id,syncItemId:t.id},idempotencyKey:`skills:scan:${a.id}:${e.id}`,timeoutSeconds:300,visibility:r?"SYSTEM":"USER"})}return!s.length&&(await i.skillSyncRun.update({where:{id:a.id},data:{status:"READY"}}),r)?this.applyRun(a.id):(this.publish(a.id),this.getRun(a.id))}async getRun(e){return(await (0,tY.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return iS(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=iS(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),a=new Date;await i.$transaction(async i=>{for(let r of(await i.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))ih.AI_TOOLS.includes(r.tool)&&await i.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:r.tool}},create:{agentId:e.agentId,tool:r.tool,configured:r.configured,homePath:r.homePath,checkedAt:a},update:{configured:r.configured,homePath:r.homePath,checkedAt:a}});for(let r of t.installations){let t=await i.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await i.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,tY.getPrismaClient)(),t=new Set(iI(await this.settings())),r=await e.skillToolObservation.findMany({where:{configured:!0}}),i=new Map;for(let e of r){if(!t.has(e.tool))continue;let r=i.get(e.agentId)??[];r.push(e.tool),i.set(e.agentId,r)}return i}async desiredLocations(e,t=new Set){let r=await (0,tY.getPrismaClient)(),i=await this.configuredByAgent(),a=await r.skillToolObservation.findMany({where:{configured:!0}}),n=new Map;for(let e of a)n.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await r.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:ix});for(let[r,a]of i){if(t.has(r))continue;let i=n.get(r);if(i)for(let t of ig(a,"GLOBAL")){let a=iE(i,...iA("GLOBAL",t));for(let i of e)s.push({skill:i,agentId:r,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:t,folder:null,rootPath:a,targetPath:iE(a,i.name)})}}}for(let a of(await r.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:ix}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of a.repositories)for(let r of e.repository.codebases){if(t.has(r.agentId))continue;let e=ig(i.get(r.agentId)??[],"PROJECT");for(let t of[{folder:r.folder,worktreeId:null},...r.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let i of e){let e=iE(t.folder,...iA("PROJECT",i));for(let n of a.skills)s.push({skill:n.skill,agentId:r.agentId,codebaseId:r.id,worktreeId:t.worktreeId,scope:"PROJECT",rootKind:i,folder:t.folder,rootPath:e,targetPath:iE(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,t){return{present:!0,...t.size?{agentId:{notIn:[...t]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:ix}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(r,i),include:{baseline:!0}}),this.desiredLocations(r,i),"GROUP"===r.kind&&r.groupId?this.desiredLocations({...r,groupId:null},i):this.desiredLocations(r,i)]),c=new Map(a.map(e=>[e.name,e])),u=new Map(a.map(e=>[e.id,e])),d=new Map(n.map(e=>[e.name,e])),p=new Map(n.map(e=>[e.id,e])),h=new Map;for(let e of s){let t=h.get(e.skillName)??[];t.push(e.packageHash),h.set(e.skillName,t)}let m=new Set([...h].flatMap(([e,t])=>{var r;return(r=c.get(e)?.packageHash??null,new Set(t.filter(e=>null===r||e!==r)).size>1)?[e]:[]})),f=[];for(let t of o)s.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||f.push({id:(0,g.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of s){let i=r.baseline?.skillId??r.skillId,a=(i?u.get(i):void 0)??c.get(r.skillName),n=(i?p.get(i):void 0)??d.get(r.skillName),s=!!r.baseline&&!!a&&a.name!==r.skillName,h=o.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),v=l.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);a&&r.packageHash===a.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,g.randomUUID)(),installationId:r.id,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}});let b="UNCHANGED",w="COMPLETE";if(n&&r.baseline&&!r.tracked)b="DELETE_MANAGED",w="READY";else if(s)b=r.tracked?"CONFLICT":"DELETE_MANAGED",w=r.tracked?"BLOCKED":"READY";else if(v||!r.baseline||r.tracked)if(a)if(r.packageHash!==a.packageHash){var y;w="CONFLICT"===(b=m.has(r.skillName)?"CONFLICT":(y={databaseHash:a.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===y.targetHash?"UNCHANGED":y.tracked?"CONFLICT":y.baselineHash===y.databaseHash?"IMPORT":y.baselineHash===y.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!v&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&l.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(b="DELETE_REDUNDANT",w="READY");else w="CONFLICT"==(b=m.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else b="DELETE_MANAGED",w="READY";f.push({id:(0,g.randomUUID)(),runId:e,skillId:a?.id??n?.id??null,installationId:r.id,agentId:r.agentId,direction:b,status:w,sourceHash:a?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?h?.folder??null:null,skillName:r.skillName},projectGroupRequired:!a&&"PROJECT"===r.scope})})}f.length&&await t.skillSyncItem.createMany({data:f});let v=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),b=new Map;for(let e of v){if(!e.agentId||!e.installation)continue;let t=b.get(e.agentId)??[];t.push(e),b.set(e.agentId,t)}let w=iI(await this.settings());for(let[r,i]of b){let a=await t.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:e,agentId:r,direction:"READ",status:"PENDING"}}),n=await this.targets(r);await this.agentControl.createJob({agentId:r,kind:ih.SKILL_READ_JOB_KIND,payload:{tools:w,targets:n,requests:i.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?n.find(t=>t.codebaseId===e.installation.codebaseId&&t.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${r}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let a=iS(e.resultJson,{packages:[]}),n=await i.skillSyncItem.findMany({where:{runId:t,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of a.packages){let t=n.find(t=>t.installation?.skillName===e.package.name&&t.installation?.rootKind===e.rootKind&&t.installation?.scope===e.scope&&("GLOBAL"===e.scope||t.installation?.rootPath===iE(e.folder,...iA("PROJECT",e.rootKind))));if(!t)continue;let r=iS(t.candidatePackageJson,{});await i.skillSyncItem.update({where:{id:t.id},data:{candidatePackageJson:JSON.stringify({...r,package:e.package})}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE"}})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(t),this.publish(t)}}async refreshRunStatus(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncItem.findMany({where:{runId:e}});if(r.some(e=>ib.includes(e.direction)&&"PENDING"===e.status))return;let i=r.some(e=>"BLOCKED"===e.status),a=r.some(e=>"FAILED"===e.status),n=i?"NEEDS_RESOLUTION":a?"PARTIAL":"READY",s=await t.skillSyncRun.update({where:{id:e},data:{status:n}});this.publish(e),s.automatic&&"READY"===n&&await this.applyRun(e)}async skipPending(e){let t=await (0,tY.getPrismaClient)();await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});let r=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:iw},status:"PENDING",agentId:{not:null}}}),i=[];for(let a of r){if(1!==(await t.skillSyncItem.updateMany({where:{id:a.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!a.agentId)continue;i.push(a);let r=await t.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:a.agentId,idempotencyKey:`skills:${a.direction.toLowerCase()}:${e}:${a.agentId}`}}});r&&await this.agentControl.cancelJob(r.id)}if(!i.length)return this.getRun(e);let a=[...new Set(i.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];a.length&&await t.skillSyncItem.updateMany({where:{runId:e,agentId:{in:a},direction:{notIn:iw},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let n=i.filter(e=>"APPLY"===e.direction),s=n.flatMap(e=>{let{deployments:t=[]}=iS(e.candidatePackageJson,{});return t.map(e=>e.id)});return s.length&&await t.skillDeployment.updateMany({where:{id:{in:s},status:"PENDING"},data:{status:"SKIPPED"}}),i.some(e=>"SCAN"===e.direction)?await t.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):a.length&&await this.refreshRunStatus(e),n.length&&(await t.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await t.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(r.status))throw Error("Sync item cannot be resolved");let i=iS(r.candidatePackageJson,{});if("MANUAL"===e.resolution&&(i.package=(0,ih.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!i.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!r.installationId)throw Error("The client skill installation is unavailable");if(i.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await t.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");i.groupId=e.groupId}if(await t.skillSyncItem.update({where:{id:r.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":r.direction,candidatePackageJson:JSON.stringify(i),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=i.package?.name??null;if(e){let i=(await t.skillSyncItem.findMany({where:{runId:r.runId,id:{not:r.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(t=>(t.skill?.name??t.installation?.skillName)===e?[t.id]:[]);i.length&&await t.skillSyncItem.updateMany({where:{id:{in:i}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(r.runId),this.getRun(r.runId)}async importCandidates(e){let t=await (0,tY.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=iS(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:ix}),a=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:a.id}}),r.targetHash===a.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,g.randomUUID)(),installationId:r.installationId,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:ib},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),a=await this.desiredLocations(r,i),n=await t.skillInstallation.findMany({where:this.installationWhere(r,i)}),s=new Map,o=new Map,l=(e,t)=>{let r=s.get(e)??[];r.push(t),s.set(e,r)},c=(e,t)=>{let r=o.get(e)??[];r.push(t),o.set(e,r)};for(let e of a){let r=n.find(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;l(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let t=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:t}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,g.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});c(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let u=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),d=new Set(u.flatMap(e=>e.installationId?[e.installationId]:[])),p=n.filter(e=>!d.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!a.some(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skill.name===e.skillName)&&a.some(t=>t.agentId===e.agentId&&t.scope===e.scope&&("GLOBAL"===e.scope||t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)&&t.skill.name===e.skillName&&t.skill.packageHash===e.packageHash));for(let e of[...u.flatMap(e=>e.installation?[e.installation]:[]),...p]){if(!e||e.tracked)continue;let t=await this.targets(e.agentId),r="PROJECT"===e.scope?t.find(t=>t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||r)&&l(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:r,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[r,i]of s){let a=await t.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:e,agentId:r,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:o.get(r)??[]})}});await this.agentControl.createJob({agentId:r,kind:ih.SKILL_APPLY_JOB_KIND,payload:{operations:i,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${r}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:s.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)(),a=await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let n="SUCCEEDED"===e.status,{deployments:s=[]}=iS(a?.candidatePackageJson??null,{});await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:n?"COMPLETE":"FAILED",error:n?null:e.error??"Skill apply failed"}});let o=await i.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),l=iS(e.resultJson,{});if(n){let t=await this.configuredByAgent();for(let e of o){let r=s.find(t=>t.id===e.id),a=l.results?.find(t=>"WRITE"===t.kind&&t.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||a?.packageHash!==r.desiredHash)continue;let n=await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:iC(e.targetPath),skillName:e.skill.name}},create:{id:(0,g.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:iC(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await i.skillSyncBaseline.upsert({where:{installationId:n.id},create:{id:(0,g.randomUUID)(),installationId:n.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await i.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let t of l.results??[])if("DELETE"===t.kind){var c;await i.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:iC(t.path),skillName:i_(c=t.path).basename(c)},data:{present:!1,lastSeenAt:new Date}})}}else for(let t of s)await i.skillDeployment.updateMany({where:{id:t.id,agentId:e.agentId,desiredHash:t.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await i.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}e.i(464841);var iD=e.i(220629),i$=e.i(692680);e.i(493015);var iR=e.i(49172);function iN(e){if(!e)return{};let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function iP(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.valueOf())?null:t}function iO(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}class ij{agentControl;fetcher;credentials;constructor(e,t=fetch,r=new tQ.CredentialService){for(const i of(this.agentControl=e,this.fetcher=t,this.credentials=r,this.agentControl.registerCompletionHandler(i$.SIGNING_ASSETS_SCAN_JOB_KIND,e=>this.completeScan(e)),[i$.SIGNING_PROFILE_READ_JOB_KIND,i$.SIGNING_PROFILE_INSTALL_JOB_KIND,i$.SIGNING_PROFILE_DELETE_JOB_KIND,i$.SIGNING_IDENTITY_IMPORT_JOB_KIND,i$.SIGNING_IDENTITY_DELETE_JOB_KIND]))this.agentControl.registerCompletionHandler(i,e=>this.completeOperation(e))}changed(){im.agentEventBus.publish(im.SIGNING_ASSETS_CHANGED_TOPIC,{changed:!0})}deleteTransferJobSoon(e){setTimeout(()=>{(0,tY.getPrismaClient)().then(t=>t.agentJob.deleteMany({where:{id:e,visibility:"SYSTEM"}}))},3e4).unref()}subscribe(){return im.agentEventBus.iterate(im.SIGNING_ASSETS_CHANGED_TOPIC)}async completeScan(e){if("SUCCEEDED"!==e.status)return;let t=(0,i$.parseSigningAssetsScanResult)(iN(e.resultJson)),r=await (0,tY.getPrismaClient)(),i=new Date;await r.$transaction(async r=>{for(let a of(await r.signingProfileAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),await r.signingCertificateAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),t.profiles))await r.signingProfileAsset.upsert({where:{agentId_uuid:{agentId:e.agentId,uuid:a.uuid}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,uuid:a.uuid,contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:iP(a.createdAt),expiresAt:iP(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i},update:{contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:iP(a.createdAt),expiresAt:iP(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i,missingAt:null}});for(let a of t.certificates)await r.signingCertificateAsset.upsert({where:{agentId_sha1:{agentId:e.agentId,sha1:a.sha1}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,sha1:a.sha1,sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:iP(a.notBefore),expiresAt:iP(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i},update:{sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:iP(a.notBefore),expiresAt:iP(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i,missingAt:null}})}),this.deleteTransferJobSoon(e.id),this.changed()}async refreshAfterMutation(e,t){await this.agentControl.createJob({agentId:e,kind:i$.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:${t}:${e}:refresh`,timeoutSeconds:60,visibility:"SYSTEM"})}async finishOperation(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingOperationItem.findMany({where:{operationId:e}});if(r.some(e=>["WAITING","QUEUED","RUNNING"].includes(e.status)))return;let i=r.filter(e=>"SUCCEEDED"!==e.status);await t.signingOperation.update({where:{id:e},data:{status:i.length?"FAILED":"SUCCEEDED",error:i.map(e=>e.error).filter(Boolean).join("; ")||null,finishedAt:new Date}}),this.changed()}async completeOperation(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingOperationItem.findUnique({where:{jobId:e.id},include:{operation:!0}});if(r){if(await t.signingOperationItem.update({where:{id:r.id},data:{status:e.status,error:e.error,finishedAt:new Date}}),e.kind===i$.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"===e.status&&"SYNC_PROFILE"===r.operation.kind){let i=iN(e.resultJson).contentBase64;if("string"==typeof i&&i)for(let e of(await t.signingOperationItem.findMany({where:{operationId:r.operationId,status:"WAITING"}}))){let a=await this.agentControl.createJob({agentId:e.agentId,kind:i$.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:i},idempotencyKey:`signing:${r.operationId}:${e.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await t.signingOperationItem.update({where:{id:e.id},data:{jobId:a.id,status:a.status}})}else await t.signingOperation.update({where:{id:r.operationId},data:{status:"FAILED",error:"Profile read returned no content"}})}e.kind===i$.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"!==e.status&&"SYNC_PROFILE"===r.operation.kind&&await t.signingOperationItem.updateMany({where:{operationId:r.operationId,status:"WAITING"},data:{status:"FAILED",error:"Source profile could not be read",finishedAt:new Date}}),"SUCCEEDED"===e.status&&e.kind!==i$.SIGNING_PROFILE_READ_JOB_KIND&&await this.refreshAfterMutation(e.agentId,r.operationId),await this.finishOperation(r.operationId),this.deleteTransferJobSoon(e.id)}}async refresh(e){let t=await (0,tY.getPrismaClient)(),r=await t.agent.findMany({where:e?.length?{id:{in:[...new Set(e)]}}:void 0,orderBy:{name:"asc"}}),i=[];for(let e of r)iO(e.capabilitiesJson).includes(i$.SIGNING_ASSETS_SCAN_JOB_KIND)&&i.push(await this.agentControl.createJob({agentId:e.id,kind:i$.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:scan:${Date.now()}:${e.id}`,timeoutSeconds:60,visibility:"SYSTEM"}));return i}async agents(){let e=await (0,tY.getPrismaClient)();return(await e.agent.findMany({orderBy:{name:"asc"}})).map(e=>({id:e.id,name:e.name,hostname:e.hostname,supported:iO(e.capabilitiesJson).includes(i$.SIGNING_ASSETS_SCAN_JOB_KIND),lastSeenAt:e.lastSeenAt?.toISOString()??null}))}async profiles(){let e=await (0,tY.getPrismaClient)(),t=await e.signingProfileAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t){let t=`${e.uuid}:${e.contentHash}`;r.set(t,[...r.get(t)??[],e])}return[...r.values()].map(e=>{let t=e[0];return{id:`${t.uuid}:${t.contentHash}`,uuid:t.uuid,contentHash:t.contentHash,name:t.name,profileType:t.profileType,bundleId:t.bundleId,teamId:t.teamId,teamName:t.teamName,platforms:iO(t.platformsJson),deviceCount:t.deviceCount,deviceUdids:iO(t.deviceUdidsJson),certificateSha1s:iO(t.certificateSha1sJson),createdAt:t.createdAt?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,xcodeManaged:t.xcodeManaged,installedAgents:e.map(({agent:e})=>e)}})}async profile(e){return(await this.profiles()).find(t=>t.id===e)??null}async profileDevices(e){let t=new Set,r=e.filter(e=>{let r=e.toUpperCase();return!t.has(r)&&(t.add(r),!0)}),i=r.map(e=>e.toUpperCase());if(!i.length)return[];let a=await (0,tY.getPrismaClient)(),n=new Map((await a.iosDevice.findMany({where:{udid:{in:i}},select:{id:!0,udid:!0,displayName:!0,product:!0,osVersion:!0,status:!0}})).map(e=>[e.udid.toUpperCase(),e]));return r.map(e=>{let t=n.get(e.toUpperCase());return{udid:e,deviceId:t?.id??null,displayName:t?.displayName??null,product:t?.product??null,osVersion:t?.osVersion??null,status:t?.status??null}})}async certificates(){let e=await (0,tY.getPrismaClient)(),t=await e.signingCertificateAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t)r.set(e.sha1,[...r.get(e.sha1)??[],e]);return[...r.values()].map(e=>{let t=e[0];return{id:t.sha1,sha1:t.sha1,sha256:t.sha256,name:t.name,teamId:t.teamId,certificateType:t.certificateType,notBefore:t.notBefore?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,hasPrivateKey:e.some(e=>e.hasPrivateKey),installedAgents:e.map(({agent:e})=>e),privateKeyAgents:e.filter(e=>e.hasPrivateKey).map(({agent:e})=>e)}})}async operations(e=50){return(await (0,tY.getPrismaClient)()).signingOperation.findMany({include:{items:{include:{agent:{select:{id:!0,name:!0}}},orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"},take:Math.max(1,Math.min(e,200))})}async operation(e,t,r,i=null,a=[]){let n=await (0,tY.getPrismaClient)(),s=(0,g.randomUUID)();return n.signingOperation.create({data:{id:s,kind:e,assetKey:t,sourceAgentId:i,items:{create:[...new Set(r)].map(e=>({id:(0,g.randomUUID)(),agentId:e,status:a.includes(e)?"WAITING":"QUEUED"}))}},include:{items:{include:{agent:{select:{id:!0,name:!0}}}}}})}async attachJob(e,t){let r=await (0,tY.getPrismaClient)();await r.signingOperationItem.update({where:{id:e},data:{jobId:t.id,status:t.status}})}async uploadProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=(0,g.createHash)("sha256").update(Buffer.from(e,"base64")).digest("hex").toUpperCase(),i=await this.operation("INSTALL_PROFILE",r,t);for(let t of i.items){let r=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:e},idempotencyKey:`signing:${i.id}:${t.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,r)}return this.changed(),i}async downloadProfile(e,t){let r=(0,g.randomUUID)(),i=await this.agentControl.createJob({agentId:t,kind:i$.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:download:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"}),a=await (0,tY.getPrismaClient)();try{let t=Date.now()+55e3;for(;Date.now()<t;){let t=await this.agentControl.getJob(i.id);if(!t)throw Error("Profile download job was removed");if(["FAILED","CANCELLED","TIMED_OUT"].includes(t.status))throw Error(t.error||"Could not read provisioning profile");if("SUCCEEDED"===t.status){let r=iN(t.resultJson);if("string"!=typeof r.contentBase64)throw Error("Agent returned no provisioning profile content");return{uuid:e,filename:`${e}.mobileprovision`,contentBase64:r.contentBase64}}await new Promise(e=>setTimeout(e,250))}throw Error("Timed out reading provisioning profile")}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async syncProfile(e,t,r){let i=[...new Set(r)].filter(e=>e!==t);if(!i.length)throw Error("Select at least one target agent");let a=await this.operation("SYNC_PROFILE",e,[t,...i],t,i),n=a.items.find(e=>e.agentId===t),s=await this.agentControl.createJob({agentId:t,kind:i$.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${a.id}:${t}:read`,timeoutSeconds:60,visibility:"SYSTEM"});return await this.attachJob(n.id,s),this.changed(),a}async deleteProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=await this.operation("DELETE_PROFILE",e,t);for(let t of r.items){let i=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_PROFILE_DELETE_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${r.id}:${t.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,i)}return this.changed(),r}async deleteExpiredProfiles(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingProfileAsset.findMany({where:{expired:!0,missingAt:null,...e?.length?{agentId:{in:e}}:{}}}),i=new Map;for(let e of r)i.set(e.uuid,[...i.get(e.uuid)??[],e.agentId]);let a=[];for(let[e,t]of i)a.push(await this.deleteProfile(e,t));return a}async importIdentity(e){if(!e.targetAgentIds.length)throw Error("Select at least one agent");let t=Buffer.from(e.p12Base64,"base64");if(!t.length||t.length>0x1400000)throw Error("The .p12 file is empty or larger than 20 MiB");let r=[...new Set(e.targetAgentIds)],i=await (0,tY.getPrismaClient)(),n=new Map((await i.agent.findMany({where:{id:{in:r}},select:{id:!0,name:!0,capabilitiesJson:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}})).map(e=>[e.id,e])),s=Date.now(),o=r.filter(e=>{let t=n.get(e);return!t||!function(e,t=Date.now()){return null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}(t,s)||!iO(t.capabilitiesJson).includes(i$.SIGNING_IDENTITY_IMPORT_JOB_KIND)});if(o.length)throw Error(`Identity imports require online supported agents: ${o.map(e=>n.get(e)?.name??e).join(", ")}`);let l=(0,g.createHash)("sha256").update(t).digest("hex").toUpperCase(),c=await this.operation("IMPORT_IDENTITY",l,r);for(let t of c.items){let r=this.agentControl.createSigningSecretTransfer(t.agentId,{p12Base64:e.p12Base64,passphrase:e.passphrase});try{let e=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_IDENTITY_IMPORT_JOB_KIND,payload:{transferId:r,sha256:l},idempotencyKey:`signing:${c.id}:${t.agentId}:import`,timeoutSeconds:120,visibility:"SYSTEM"});await this.attachJob(t.id,e)}catch(e){throw this.agentControl.revokeSigningSecretTransfer(r),e}}return this.changed(),c}async deleteIdentity(e,t){if(!t.length)throw Error("Select at least one agent");let r=e.toUpperCase(),i=[...new Set(t)],a=await (0,tY.getPrismaClient)(),n=new Set((await a.signingCertificateAsset.findMany({where:{sha1:r,agentId:{in:i},hasPrivateKey:!0,missingAt:null},select:{agentId:!0}})).map(e=>e.agentId)),s=i.filter(e=>n.has(e));if(!s.length)throw Error("The identity has no private key on the selected agents");let o=await this.operation("DELETE_IDENTITY",r,s);for(let e of o.items){let t=await this.agentControl.createJob({agentId:e.agentId,kind:i$.SIGNING_IDENTITY_DELETE_JOB_KIND,payload:{sha1:r},idempotencyKey:`signing:${o.id}:${e.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(e.id,t)}return this.changed(),o}async appleClient(){return new iR.AppleDeveloperClient(await (0,iR.storedAppleDeveloperCredentials)(this.credentials),this.fetcher)}async portalInventory(){let e=await this.appleClient(),[t,r,i,a]=await Promise.all([e.listProfiles(),e.listCertificates(),e.listBundleIds(),e.listDevices()]);return{profiles:t,certificates:r,bundleIds:i,devices:a}}async createPortalProfile(e){let t=await (await this.appleClient()).createProfile(e);return this.changed(),t.data}async deletePortalProfile(e){return await (await this.appleClient()).deleteProfile(e),this.changed(),!0}async revokePortalCertificate(e){return await (await this.appleClient()).revokeCertificate(e),this.changed(),!0}}var iB=e.i(308810),iU=e.i(726355);let iq={IOS_BUILD_SUCCEEDED:{key:"IOS_BUILD_SUCCEEDED",category:"BUILDS",label:"iOS build succeeded",description:"An iOS build finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},IOS_BUILD_FAILED:{key:"IOS_BUILD_FAILED",category:"BUILDS",label:"iOS build failed",description:"An iOS build finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},GITHUB_ACTIONS_SUCCEEDED:{key:"GITHUB_ACTIONS_SUCCEEDED",category:"GITHUB",label:"GitHub Actions succeeded",description:"A GitHub Actions workflow finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},GITHUB_ACTIONS_FAILED:{key:"GITHUB_ACTIONS_FAILED",category:"GITHUB",label:"GitHub Actions failed",description:"A GitHub Actions workflow finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_NEEDS_ANSWER:{key:"RUN_NEEDS_ANSWER",category:"RUNS",label:"Plan or session needs an answer",description:"A managed plan or session asks for user input.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_COMPLETED:{key:"RUN_COMPLETED",category:"RUNS",label:"Plan or session completed",description:"A managed plan or session completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_FAILED:{key:"RUN_FAILED",category:"RUNS",label:"Plan or session failed",description:"A managed plan or session fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_CANCELLED:{key:"RUN_CANCELLED",category:"RUNS",label:"Plan or session cancelled",description:"A managed plan or session is cancelled.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!1,defaultWebPushEnabled:!1},RUN_RECOVERY_PAUSED:{key:"RUN_RECOVERY_PAUSED",category:"RUNS",label:"Plan or session paused after recovery",description:"A managed plan or session is paused after its agent restarts.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1}};function iL(e){return e in iq?iq[e]:null}let iM="default";function iF(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function iV(e){let t,r=iF(e,"Push endpoint",4e3);try{t=new URL(r)}catch{throw Error("Push endpoint must be a valid URL")}if("https:"!==t.protocol)throw Error("Push endpoint must use HTTPS");return r}function iK(e,t){let r=new Date(e);if(!Number.isFinite(r.getTime()))throw Error(`${t} is invalid`);return r}function iH(){let e=process.env.PUBLIC_BASE_URL?.trim();if(e)try{let t=new URL(e);if("https:"===t.protocol)return t.origin}catch{}return"mailto:notifications@ai-development-environment.local"}function iz(e){if(!e||"object"!=typeof e)return null;let t=e.statusCode;return"number"==typeof t?t:null}class iG{credentialService;vapidPreparation;constructor(e){this.credentialService=e,this.vapidPreparation=null}publish(e){im.agentEventBus.publish(im.APP_NOTIFICATIONS_CHANGED_TOPIC,{notificationsChanged:e})}subscribe(){return im.agentEventBus.iterate(im.APP_NOTIFICATIONS_CHANGED_TOPIC)}async preferences(){let e=await (0,tY.getPrismaClient)(),t=new Map((await e.notificationPreference.findMany()).map(e=>[e.typeKey,e]));return Object.values(iq).map(e=>{let r=t.get(e.key);return{...e,sidebarEnabled:r?.sidebarEnabled??e.defaultSidebarEnabled,browserEnabled:r?.browserEnabled??e.defaultBrowserEnabled,webPushEnabled:r?.webPushEnabled??e.defaultWebPushEnabled,updatedAt:r?.updatedAt??null}})}async savePreference(e){let t=iL(e.typeKey);if(!t)throw Error("Unknown notification type");let r=await (0,tY.getPrismaClient)(),i=await r.notificationPreference.upsert({where:{typeKey:t.key},create:{typeKey:t.key,sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled},update:{sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled}});return this.publish({kind:"PREFERENCES_UPDATED",notification:null,notificationId:null}),{...t,...i}}async recordInTransaction(e,t){let r=iL(t.typeKey);if(!r)throw Error("Unknown notification type");let i=await e.notificationPreference.findUnique({where:{typeKey:r.key}}),a=i?.sidebarEnabled??r.defaultSidebarEnabled,n=i?.browserEnabled??r.defaultBrowserEnabled,s=i?.webPushEnabled??r.defaultWebPushEnabled;if(!a&&!n&&!s)return null;let o=iF(t.dedupeKey,"Deduplication key",500);return await e.appNotification.findUnique({where:{dedupeKey:o}})?null:e.appNotification.create({data:{id:(0,g.randomUUID)(),dedupeKey:o,typeKey:r.key,title:iF(t.title,"Notification title",240),body:iF(t.body,"Notification body",1e3),href:function(e){let t=iF(e,"Notification link",2e3);if(!t.startsWith("/")||t.startsWith("//"))throw Error("Notification links must be same-origin paths");return t}(t.href),resourceKind:iF(t.resourceKind,"Resource kind",100),resourceId:iF(t.resourceId,"Resource ID",500),worktreeId:t.worktreeId??null,highlightColor:t.highlightColor?.trim()||null,sidebarRequested:a,browserRequested:n,webPushRequested:s}})}created(e){e&&(this.publish({kind:"CREATED",notification:e,notificationId:e.id}),e.webPushRequested&&this.deliverWebPush(e).catch(e=>{console.error("Web Push delivery failed:",e)}))}async history(e={}){let t=Math.max(1,Math.min(e.first??100,200)),r=await (0,tY.getPrismaClient)(),[i,a]=await Promise.all([r.appNotification.findMany({orderBy:[{createdAt:"desc"},{id:"desc"}],take:t+1,...e.after?{cursor:{id:e.after},skip:1}:void 0}),r.appNotification.count()]);return{items:i.slice(0,t),nextCursor:i.length>t?i[t-1].id:null,totalCount:a}}async sidebar(e=50){return(await (0,tY.getPrismaClient)()).appNotification.findMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},orderBy:[{createdAt:"desc"},{id:"desc"}],take:Math.max(1,Math.min(e,100))})}async dismiss(e){let t=await (0,tY.getPrismaClient)(),r=await t.appNotification.updateMany({where:{id:e,sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return r.count&&this.publish({kind:"DISMISSED",notification:null,notificationId:e}),r.count>0}async dismissAll(){let e=await (0,tY.getPrismaClient)(),t=await e.appNotification.updateMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return t.count&&this.publish({kind:"SIDEBAR_CLEARED",notification:null,notificationId:null}),t.count}selectionWhere(e){let t=e.excludedRanges??[],r=e.all&&0===t.length?[]:[...new Set(e.ids??[])],i=[...new Set(e.excludedIds??[])],a=e.ranges??[];if(r.length>5e3||i.length>5e3)throw Error("Notification selection is too large");if(a.length>366||t.length>366)throw Error("Notification date selection is too large");let n=t.map(e=>{let t=iK(e.start,"Excluded selection start"),r=iK(e.end,"Excluded selection end");if(t>=r)throw Error("Excluded selection range is invalid");return{createdAt:{gte:t,lt:r}}}),s={NOT:{OR:n}},o=[];if(r.length&&o.push({id:{in:r}}),e.all)o.push(n.length?s:{});else if(a.length){let e=a.map(e=>{let t=iK(e.start,"Selection start"),r=iK(e.end,"Selection end");if(t>=r)throw Error("Selection range is invalid");return{createdAt:{gte:t,lt:r}}});o.push({AND:[{OR:e},...n.length?[s]:[]]})}if(!o.length)return{id:{in:[]}};let l=1===o.length?o[0]:{OR:o};return i.length?{AND:[l,{id:{notIn:i}}]}:l}async deleteSelection(e){let t=await (0,tY.getPrismaClient)(),r=await t.appNotification.deleteMany({where:this.selectionWhere(e)});return r.count&&this.publish({kind:"DELETED",notification:null,notificationId:null}),r.count}async deleteAll(){let e=await (0,tY.getPrismaClient)(),t=await e.appNotification.deleteMany();return t.count&&this.publish({kind:"HISTORY_CLEARED",notification:null,notificationId:null}),t.count}async webPushState(){let e=await (0,tY.getPrismaClient)(),[t,r]=await Promise.all([e.webPushSettings.findUnique({where:{id:iM}}),e.webPushSubscription.count()]),i=await this.credentialService.isConfigured(tX.CREDENTIALS.webPushVapidPrivateKey);return{configured:!!(t?.vapidPublicKey&&i),publicKey:t?.vapidPublicKey??null,subscriptionCount:r}}async webPushSubscriptions(){return(await (0,tY.getPrismaClient)()).webPushSubscription.findMany({orderBy:[{lastSeenAt:"desc"},{createdAt:"desc"}],select:{id:!0,endpoint:!0,expirationTime:!0,locale:!0,userAgent:!0,lastSeenAt:!0,createdAt:!0,updatedAt:!0}})}async prepareWebPush(){return this.vapidPreparation||(this.vapidPreparation=this.prepareWebPushOnce().finally(()=>{this.vapidPreparation=null})),this.vapidPreparation}async prepareWebPushOnce(){let e=await (0,tY.getPrismaClient)(),t=await e.webPushSettings.findUnique({where:{id:iM}});if(t?.vapidPublicKey){if(!await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey))throw Error("The Web Push private key is unavailable");return{publicKey:t.vapidPublicKey}}let r=iU.default.generateVAPIDKeys();return await this.credentialService.setText(tX.CREDENTIALS.webPushVapidPrivateKey,r.privateKey,e=>e.webPushSettings.upsert({where:{id:iM},create:{id:iM,vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date},update:{vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date}}).then(()=>void 0)),{publicKey:r.publicKey}}async registerWebPush(e){let t=iV(e.endpoint),r=iF(e.p256dh,"Push p256dh key",1e3),i=iF(e.auth,"Push auth key",1e3),a=null===e.expirationTime||void 0===e.expirationTime?null:new Date(e.expirationTime);if(a&&!Number.isFinite(a.getTime()))throw Error("Push subscription expiration is invalid");return await this.prepareWebPush(),(await (0,tY.getPrismaClient)()).webPushSubscription.upsert({where:{endpoint:t},create:{id:(0,g.randomUUID)(),endpoint:t,p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null},update:{p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null,lastSeenAt:new Date}})}async unregisterWebPush(e){let t=iV(e),r=await (0,tY.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{endpoint:t}})).count>0}async deleteWebPushSubscription(e){let t=iF(e,"Push subscription",200),r=await (0,tY.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{id:t}})).count>0}async testWebPushSubscription(e){let t=iF(e,"Push subscription",200),r=await (0,tY.getPrismaClient)(),[i,a]=await Promise.all([r.webPushSettings.findUnique({where:{id:iM}}),r.webPushSubscription.findUnique({where:{id:t}})]);if(!a)throw Error("Push subscription was not found");if(!i?.vapidPublicKey)throw Error("Web Push is not configured");let n=await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey);if(!n)throw Error("The Web Push private key is unavailable");iU.default.setVapidDetails(iH(),i.vapidPublicKey,n);try{return await iU.default.sendNotification({endpoint:a.endpoint,expirationTime:a.expirationTime?.getTime()??null,keys:{p256dh:a.p256dh,auth:a.auth}},JSON.stringify({id:`test:${Date.now()}`,title:"Test notification",body:"Web Push is working for this browser.",href:"/notifications",icon:"/icon-192.png",badge:"/icon-192.png"}),{TTL:60,timeout:1e4}),!0}catch(e){if([404,410].includes(iz(e)??0))throw await r.webPushSubscription.deleteMany({where:{id:t}}),Error("The browser subscription expired and was removed");throw e}}async deliverWebPush(e){if(!e.webPushRequested)return;let t=await (0,tY.getPrismaClient)(),[r,i]=await Promise.all([t.webPushSettings.findUnique({where:{id:iM}}),t.webPushSubscription.findMany()]);if(!r?.vapidPublicKey||!i.length)return;let a=await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey);if(!a)return;iU.default.setVapidDetails(iH(),r.vapidPublicKey,a);let n=JSON.stringify({id:e.id,title:e.title,body:e.body,href:e.href,icon:"/icon-192.png",badge:"/icon-192.png"});await Promise.allSettled(i.map(async e=>{try{await iU.default.sendNotification({endpoint:e.endpoint,expirationTime:e.expirationTime?.getTime()??null,keys:{p256dh:e.p256dh,auth:e.auth}},n,{TTL:3600,timeout:1e4})}catch(r){if([404,410].includes(iz(r)??0))return void await t.webPushSubscription.deleteMany({where:{endpoint:e.endpoint}});console.error(`Web Push delivery to ${e.endpoint} failed:`,r)}}))}}var iJ=e.i(986847);let iW=e=>e?.toISOString()??null;function iZ(e,t,r,i,a){return e?t?"RUNNING":a?"ERROR":r&&!i||r&&i&&Date.now()-i.getTime()>2e3*r+5e3?"STALE":"HEALTHY":"DISABLED"}class iY{operations=new Map;register(e){let t=this.operations.get(e.id);this.operations.set(e.id,{...e,lastStartedAt:t?.lastStartedAt??null,lastCompletedAt:t?.lastCompletedAt??null,lastSucceededAt:t?.lastSucceededAt??null,nextScheduledAt:t?.nextScheduledAt??null,durationMs:t?.durationMs??null,lastError:t?.lastError??null}),this.changed(e.id)}configure(e,t){let r=this.operations.get(e);r&&(Object.assign(r,t),r.enabled||(r.nextScheduledAt=null),this.changed(e))}schedule(e,t){let r=this.operations.get(e);r&&(r.nextScheduledAt=t,this.changed(e))}async run(e,t,r){let i=this.operations.get(e);if(!i)throw Error(`Polling operation ${e} is not registered`);let a=new Date;i.lastStartedAt=a,i.lastError=null,this.changed(e);try{let e=await t(),n=new Date;return i.lastCompletedAt=n,i.lastSucceededAt=n,i.durationMs=n.getTime()-a.getTime(),i.lastError=null,r&&(i.details={...i.details,...r(e)}),e}catch(t){let e=new Date;throw i.lastCompletedAt=e,i.durationMs=e.getTime()-a.getTime(),i.lastError=t instanceof Error?t.message:String(t),t}finally{this.changed(e)}}changed(e){im.agentEventBus.publish(im.POLLING_CHANGED_TOPIC,{pollingOperationChanged:e})}subscribe(){return im.agentEventBus.iterate(im.POLLING_CHANGED_TOPIC)}serverViews(){return[...this.operations.values()].map(e=>({...e,status:iZ(e.enabled,!!(e.lastStartedAt&&(!e.lastCompletedAt||e.lastStartedAt>e.lastCompletedAt)),e.cadenceSeconds,e.lastCompletedAt,e.lastError),lastStartedAt:iW(e.lastStartedAt),lastCompletedAt:iW(e.lastCompletedAt),lastSucceededAt:iW(e.lastSucceededAt),nextScheduledAt:iW(e.nextScheduledAt)}))}async list(){let e=await (0,tY.getPrismaClient)(),[t,r,i]=await Promise.all([e.codebaseSettings.findUnique({where:{id:"default"}}),e.agent.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,lastSeenAt:!0,disconnectedAt:!0,codebaseScanIntervalSeconds:!0,jobReconciliationIntervalSeconds:!0,gitFetchIntervalSeconds:!0,heartbeatIntervalSeconds:!0,codebases:{select:{lastCheckedAt:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,lastFetchError:!0}}}}),e.agentJob.groupBy({by:["agentId","status"],where:{status:{in:["QUEUED","RUNNING"]}},_count:{_all:!0}})]),n=t?.refreshIntervalSeconds??30,s=t?.fetchIntervalSeconds??300,o=new Map;for(let e of i)o.set(e.agentId,(o.get(e.agentId)??0)+e._count._all);let l=[];for(let e of r){let t=e.heartbeatIntervalSeconds??iJ.DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS,r=e.jobReconciliationIntervalSeconds??iJ.DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,i=e.codebaseScanIntervalSeconds??n,c=e.gitFetchIntervalSeconds??s,u=null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e);l.push({id:`agent-heartbeat:${e.id}`,kind:"AGENT_HEARTBEAT",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:t,lastStartedAt:null,lastCompletedAt:iW(e.lastSeenAt),lastSucceededAt:iW(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*t).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,connection:u?"ONLINE":"OFFLINE"}}),l.push({id:`agent-job-reconciliation:${e.id}`,kind:"AGENT_JOB_RECONCILIATION",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:r,lastStartedAt:null,lastCompletedAt:iW(e.lastSeenAt),lastSucceededAt:iW(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*r).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,pendingJobs:o.get(e.id)??0}});let d=e.codebases.map(e=>e.lastCheckedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,p=e.codebases.map(e=>e.lastFetchAttemptAt??e.lastFetchedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,h=e.codebases.filter(e=>e.lastFetchError).length;l.push({id:`agent-codebase-scan:${e.id}`,kind:"CODEBASE_SCAN",runtime:"AGENT",status:iZ(e.codebases.length>0,!1,i,d,null),enabled:e.codebases.length>0,cadenceSeconds:i,lastStartedAt:null,lastCompletedAt:iW(d),lastSucceededAt:iW(d),nextScheduledAt:d?new Date(d.getTime()+1e3*i).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length}}),l.push({id:`agent-git-fetch:${e.id}`,kind:"GIT_FETCH",runtime:"AGENT",status:h>0?"ERROR":iZ(e.codebases.length>0,!1,c,p,null),enabled:e.codebases.length>0,cadenceSeconds:c,lastStartedAt:null,lastCompletedAt:iW(p),lastSucceededAt:h>0?null:iW(p),nextScheduledAt:p?new Date(p.getTime()+1e3*c).toISOString():null,durationMs:null,lastError:h>0?`${h} repositories have fetch errors`:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length,fetchErrors:h}})}return[...this.serverViews(),...l]}}e.i(648153);var iQ=e.i(594875);let iX=globalThis;e.s(["getServerServices",0,function(){let e,t,r,i,g,y,v,b,w,x,k,S,I,A,_,E,C,T,D,$,R;return iX.serverServices??(e=new f.PrismaService,t=new tQ.CredentialService,r=new a.AgentControlService,i=new n.CcusageService(r),g=new s.BuildDataService(r),y=new iD.TelemetryService,v=new ij(r,void 0,t),b=new iY,w=new iB.PushNotificationsService(void 0,t,b),x=new iG(t),(k=new iQ.RunsService(x)).startReaper(),S=new o.BuildsService(r,y,x),I=new iT(r),A=new l.CodebasesService(r,I),_=new c.CodebaseToolsService(A),E=new h.JiraService(t),C=new m.IosDevicesService(void 0,t),T=new u.GitHubActionsNotificationsService(t,x,b),D=new d.GitHubService(!0,t,b,()=>T.configurationChanged()),$=new p.CacheServerService(t),R=new id.WorktreesService(r,E,D,I),iX.serverServices={prismaService:e,credentialService:t,agentControlService:r,ccusageService:i,buildDataService:g,buildsService:S,codebasesService:A,codebaseToolsService:_,jiraService:E,iosDevicesService:C,gitHubService:D,gitHubActionsNotificationsService:T,cacheServerService:$,worktreesService:R,skillsService:I,telemetryService:y,signingAssetsService:v,pushNotificationsService:w,notificationsService:x,pollingService:b,runsService:k,toolsService:new r3(_,S,{codebases:A,telemetry:y,pushNotifications:w,agents:r},t)})}],887394)}];
|
|
428
|
+
`)&&-1===e.indexOf("\r")){s.push(e),o+=e.length,m();return}s.push(e);let t=s.join("");s.length=0,o=0;let r=f(t);""!==r&&(s.push(r),o=r.length),m()},reset:function(e={}){if(e.consume&&s.length>0){let e=s.join("");g(e,0,e.length)}l=!0,c=void 0,u="",d=0,p=void 0,s.length=0,o=0,h=!1}}}function em(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function ef(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class eg extends Event{constructor(e,t){var r,i;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(i=null==t?void 0:t.message)?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(ey(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(ey(this),t)}}function ey(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ev,eb,ew,ex,ek,eS,eI,eA,e_,eE,eC,eT,eD,e$,eR,eN,eP,eO,ej,eB,eU,eq,eL,eM=e=>{throw TypeError(e)},eF=(e,t,r)=>t.has(e)||eM("Cannot "+r),eV=(e,t,r)=>(eF(e,t,"read from private field"),r?r.call(e):t.get(e)),eK=(e,t,r)=>t.has(e)?eM("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),eH=(e,t,r,i)=>(eF(e,t,"write to private field"),t.set(e,r),r),ez=(e,t,r)=>(eF(e,t,"access private method"),r);class eG extends EventTarget{constructor(e,t){var r,i;super(),eK(this,e$),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,eK(this,ev),eK(this,eb),eK(this,ew),eK(this,ex),eK(this,ek),eK(this,eS),eK(this,eI),eK(this,eA,null),eK(this,e_),eK(this,eE),eK(this,eC,null),eK(this,eT,null),eK(this,eD,null),eK(this,eN,async e=>{var t;eV(this,eE).reset();let{body:r,redirected:i,status:a,headers:n}=e;if(204===a){ez(this,e$,eU).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(i?eH(this,ew,new URL(e.url)):eH(this,ew,void 0),200!==a)return void ez(this,e$,eU).call(this,`Non-200 status code (${a})`,a);if(!(n.get("content-type")||"").startsWith("text/event-stream"))return void ez(this,e$,eU).call(this,'Invalid content type, expected "text/event-stream"',a);if(eV(this,ev)===this.CLOSED)return;eH(this,ev,this.OPEN);let s=new Event("open");if(null==(t=eV(this,eD))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r)){ez(this,e$,eU).call(this,"Invalid response body, expected a web ReadableStream",a),this.close();return}let o=new TextDecoder,l=r.getReader(),c=!0;do{let{done:e,value:t}=await l.read();t&&eV(this,eE).feed(o.decode(t,{stream:!e})),e&&(c=!1,eV(this,eE).reset(),ez(this,e$,eq).call(this))}while(c)}),eK(this,eP,e=>{eH(this,e_,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&ez(this,e$,eq).call(this,function e(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(e).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${e(t.cause)}`:t.message:`${t}`}(e))}),eK(this,ej,e=>{"string"==typeof e.id&&eH(this,eA,e.id);let t=new MessageEvent(e.event||"message",{data:e.data,origin:eV(this,ew)?eV(this,ew).origin:eV(this,eb).origin,lastEventId:e.id||""});eV(this,eT)&&(!e.event||"message"===e.event)&&eV(this,eT).call(this,t),this.dispatchEvent(t)}),eK(this,eB,e=>{eH(this,eS,e)}),eK(this,eL,()=>{eH(this,eI,void 0),eV(this,ev)===this.CONNECTING&&ez(this,e$,eR).call(this)});try{if(e instanceof URL)eH(this,eb,e);else if("string"==typeof e)eH(this,eb,new URL(e,function(){let e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()));else throw Error("Invalid URL")}catch{throw function(e){let t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):SyntaxError(e)}("An invalid or illegal string was specified")}eH(this,eE,eh({onEvent:eV(this,ej),onRetry:eV(this,eB)})),eH(this,ev,this.CONNECTING),eH(this,eS,3e3),eH(this,ek,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),eH(this,ex,null!=(i=null==t?void 0:t.withCredentials)&&i),ez(this,e$,eR).call(this)}get readyState(){return eV(this,ev)}get url(){return eV(this,eb).href}get withCredentials(){return eV(this,ex)}get onerror(){return eV(this,eC)}set onerror(e){eH(this,eC,e)}get onmessage(){return eV(this,eT)}set onmessage(e){eH(this,eT,e)}get onopen(){return eV(this,eD)}set onopen(e){eH(this,eD,e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){eV(this,eI)&&clearTimeout(eV(this,eI)),eV(this,ev)!==this.CLOSED&&(eV(this,e_)&&eV(this,e_).abort(),eH(this,ev,this.CLOSED),eH(this,e_,void 0))}}function eJ(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function eW(e=fetch,t){return t?async(r,i)=>e(r,{...t,...i,headers:i?.headers?{...eJ(t.headers),...eJ(i.headers)}:t.headers}):e}async function eZ(e){return(await t).getRandomValues(new Uint8Array(e))}async function eY(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=256-256%t.length,i="";for(;i.length<e;)for(let a of(await eZ(e-i.length)))a<r&&(i+=t[a%t.length]);return i}async function eQ(e){return await eY(e)}async function eX(e){return btoa(String.fromCharCode(...new Uint8Array(await (await t).subtle.digest("SHA-256",new TextEncoder().encode(e))))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function e0(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await eQ(e),r=await eX(t);return{code_verifier:t,code_challenge:r}}ev=new WeakMap,eb=new WeakMap,ew=new WeakMap,ex=new WeakMap,ek=new WeakMap,eS=new WeakMap,eI=new WeakMap,eA=new WeakMap,e_=new WeakMap,eE=new WeakMap,eC=new WeakMap,eT=new WeakMap,eD=new WeakMap,e$=new WeakSet,eR=function(){eH(this,ev,this.CONNECTING),eH(this,e_,new AbortController),eV(this,ek)(eV(this,eb),ez(this,e$,eO).call(this)).then(eV(this,eN)).catch(eV(this,eP))},eN=new WeakMap,eP=new WeakMap,eO=function(){var e;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...eV(this,eA)?{"Last-Event-ID":eV(this,eA)}:void 0},cache:"no-store",signal:null==(e=eV(this,e_))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},ej=new WeakMap,eB=new WeakMap,eU=function(e,t){var r;eV(this,ev)!==this.CLOSED&&eH(this,ev,this.CLOSED);let i=new eg("error",{code:t,message:e});null==(r=eV(this,eC))||r.call(this,i),this.dispatchEvent(i)},eq=function(e,t){var r;if(eV(this,ev)===this.CLOSED)return;eH(this,ev,this.CONNECTING);let i=new eg("error",{code:t,message:e});null==(r=eV(this,eC))||r.call(this,i),this.dispatchEvent(i),eH(this,eI,setTimeout(eV(this,eL),eV(this,eS)))},eL=new WeakMap,eG.CONNECTING=0,eG.OPEN=1,eG.CLOSED=2,t=globalThis.crypto?.webcrypto??globalThis.crypto??e.A(70729).then(e=>e.webcrypto);var e1=e.i(907855),e2=e.i(733137),e3=e.i(127438),e4=e.i(334512),e4=e4;let e6=e1.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:e2.ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),e3.NEVER}).refine(e=>{let t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),e8=e1.looseObject({resource:e1.string().url(),authorization_servers:e1.array(e6).optional(),jwks_uri:e1.string().url().optional(),scopes_supported:e1.array(e1.string()).optional(),bearer_methods_supported:e1.array(e1.string()).optional(),resource_signing_alg_values_supported:e1.array(e1.string()).optional(),resource_name:e1.string().optional(),resource_documentation:e1.string().optional(),resource_policy_uri:e1.string().url().optional(),resource_tos_uri:e1.string().url().optional(),tls_client_certificate_bound_access_tokens:e1.boolean().optional(),authorization_details_types_supported:e1.array(e1.string()).optional(),dpop_signing_alg_values_supported:e1.array(e1.string()).optional(),dpop_bound_access_tokens_required:e1.boolean().optional()}),e5=e1.looseObject({issuer:e1.string(),authorization_endpoint:e6,token_endpoint:e6,registration_endpoint:e6.optional(),scopes_supported:e1.array(e1.string()).optional(),response_types_supported:e1.array(e1.string()),response_modes_supported:e1.array(e1.string()).optional(),grant_types_supported:e1.array(e1.string()).optional(),token_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),service_documentation:e6.optional(),revocation_endpoint:e6.optional(),revocation_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),introspection_endpoint:e1.string().optional(),introspection_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),code_challenge_methods_supported:e1.array(e1.string()).optional(),client_id_metadata_document_supported:e1.boolean().optional()}),e9=e1.looseObject({issuer:e1.string(),authorization_endpoint:e6,token_endpoint:e6,userinfo_endpoint:e6.optional(),jwks_uri:e6,registration_endpoint:e6.optional(),scopes_supported:e1.array(e1.string()).optional(),response_types_supported:e1.array(e1.string()),response_modes_supported:e1.array(e1.string()).optional(),grant_types_supported:e1.array(e1.string()).optional(),acr_values_supported:e1.array(e1.string()).optional(),subject_types_supported:e1.array(e1.string()),id_token_signing_alg_values_supported:e1.array(e1.string()),id_token_encryption_alg_values_supported:e1.array(e1.string()).optional(),id_token_encryption_enc_values_supported:e1.array(e1.string()).optional(),userinfo_signing_alg_values_supported:e1.array(e1.string()).optional(),userinfo_encryption_alg_values_supported:e1.array(e1.string()).optional(),userinfo_encryption_enc_values_supported:e1.array(e1.string()).optional(),request_object_signing_alg_values_supported:e1.array(e1.string()).optional(),request_object_encryption_alg_values_supported:e1.array(e1.string()).optional(),request_object_encryption_enc_values_supported:e1.array(e1.string()).optional(),token_endpoint_auth_methods_supported:e1.array(e1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:e1.array(e1.string()).optional(),display_values_supported:e1.array(e1.string()).optional(),claim_types_supported:e1.array(e1.string()).optional(),claims_supported:e1.array(e1.string()).optional(),service_documentation:e1.string().optional(),claims_locales_supported:e1.array(e1.string()).optional(),ui_locales_supported:e1.array(e1.string()).optional(),claims_parameter_supported:e1.boolean().optional(),request_parameter_supported:e1.boolean().optional(),request_uri_parameter_supported:e1.boolean().optional(),require_request_uri_registration:e1.boolean().optional(),op_policy_uri:e6.optional(),op_tos_uri:e6.optional(),client_id_metadata_document_supported:e1.boolean().optional()}),e7=e1.object({...e9.shape,...e5.pick({code_challenge_methods_supported:!0}).shape}),te=e1.object({access_token:e1.string(),id_token:e1.string().optional(),token_type:e1.string(),expires_in:e4.number().optional(),scope:e1.string().optional(),refresh_token:e1.string().optional()}).strip(),tt=e1.object({error:e1.string(),error_description:e1.string().optional(),error_uri:e1.string().optional()}),tr=e6.optional().or(e1.literal("").transform(()=>void 0)),ti=e1.object({redirect_uris:e1.array(e6),token_endpoint_auth_method:e1.string().optional(),grant_types:e1.array(e1.string()).optional(),response_types:e1.array(e1.string()).optional(),client_name:e1.string().optional(),client_uri:e6.optional(),logo_uri:tr,scope:e1.string().optional(),contacts:e1.array(e1.string()).optional(),tos_uri:tr,policy_uri:e1.string().optional(),jwks_uri:e6.optional(),jwks:e1.any().optional(),software_id:e1.string().optional(),software_version:e1.string().optional(),software_statement:e1.string().optional()}).strip(),ta=e1.object({client_id:e1.string(),client_secret:e1.string().optional(),client_id_issued_at:e1.number().optional(),client_secret_expires_at:e1.number().optional()}).strip(),tn=ti.merge(ta);e1.object({error:e1.string(),error_description:e1.string().optional()}).strip(),e1.object({token:e1.string(),token_type_hint:e1.string().optional()}).strip();class ts extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class to extends ts{}to.errorCode="invalid_request";class tl extends ts{}tl.errorCode="invalid_client";class tc extends ts{}tc.errorCode="invalid_grant";class tu extends ts{}tu.errorCode="unauthorized_client";class td extends ts{}td.errorCode="unsupported_grant_type";class tp extends ts{}tp.errorCode="invalid_scope";class th extends ts{}th.errorCode="access_denied";class tm extends ts{}tm.errorCode="server_error";class tf extends ts{}tf.errorCode="temporarily_unavailable";class tg extends ts{}tg.errorCode="unsupported_response_type";class ty extends ts{}ty.errorCode="unsupported_token_type";class tv extends ts{}tv.errorCode="invalid_token";class tb extends ts{}tb.errorCode="method_not_allowed";class tw extends ts{}tw.errorCode="too_many_requests";class tx extends ts{}tx.errorCode="invalid_client_metadata";class tk extends ts{}tk.errorCode="insufficient_scope";class tS extends ts{}tS.errorCode="invalid_target";let tI={[to.errorCode]:to,[tl.errorCode]:tl,[tc.errorCode]:tc,[tu.errorCode]:tu,[td.errorCode]:td,[tp.errorCode]:tp,[th.errorCode]:th,[tm.errorCode]:tm,[tf.errorCode]:tf,[tg.errorCode]:tg,[ty.errorCode]:ty,[tv.errorCode]:tv,[tb.errorCode]:tb,[tw.errorCode]:tw,[tx.errorCode]:tx,[tk.errorCode]:tk,[tS.errorCode]:tS};class tA extends Error{constructor(e){super(e??"Unauthorized")}}let t_="code",tE="S256";async function tC(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:i}=tt.parse(JSON.parse(r));return new(tI[e]||tm)(t||"",i)}catch(e){return new tm(`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${e}. Raw body: ${r}`)}}async function tT(e,t){try{return await tD(e,t)}catch(r){if(r instanceof tl||r instanceof tu)return await e.invalidateCredentials?.("all"),await tD(e,t);if(r instanceof tc)return await e.invalidateCredentials?.("tokens"),await tD(e,t);throw r}}async function tD(e,{serverUrl:t,authorizationCode:r,scope:i,resourceMetadataUrl:a,fetchFn:n}){let s,o,l,c=await e.discoveryState?.(),u=a;if(!u&&c?.resourceMetadataUrl&&(u=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(o=c.authorizationServerUrl,s=c.resourceMetadata,l=c.authorizationServerMetadata??await tU(o,{fetchFn:n}),!s)try{s=await tP(t,{resourceMetadataUrl:u},n)}catch{}(l!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let r=await tq(t,{resourceMetadataUrl:u,fetchFn:n});o=r.authorizationServerUrl,l=r.authorizationServerMetadata,s=r.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(o),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await t$(t,e,s),p=i||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,h=await Promise.resolve(e.clientInformation());if(!h){if(void 0!==r)throw Error("Existing OAuth client information is required when exchanging an authorization code");let t=l?.client_id_metadata_document_supported===!0,i=e.clientMetadataUrl;if(i&&!function(e){if(!e)return!1;try{let t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(i))throw new tx(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${i}`);if(t&&i)h={client_id:i},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let t=await tK(o,{metadata:l,clientMetadata:e.clientMetadata,scope:p,fetchFn:n});await e.saveClientInformation(t),h=t}}let m=!e.redirectUrl;if(void 0!==r||m){let t=await tV(e,o,{metadata:l,resource:d,authorizationCode:r,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}let f=await e.tokens();if(f?.refresh_token)try{let t=await tF(o,{metadata:l,clientInformation:h,refreshToken:f.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:n});return await e.saveTokens(t),"AUTHORIZED"}catch(e){if(!(e instanceof ts)||e instanceof tm);else throw e}let g=e.state?await e.state():void 0,{authorizationUrl:y,codeVerifier:v}=await tL(o,{metadata:l,clientInformation:h,state:g,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(v),await e.redirectToAuthorization(y),"REDIRECT"}async function t$(e,t,r){let i,a=((i=new URL("string"==typeof e?e:e.href)).hash="",i);if(t.validateResourceURL)return await t.validateResourceURL(a,r?.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){let r=new URL("string"==typeof e?e:e.href),i=new URL("string"==typeof t?t:t.href);if(r.origin!==i.origin||r.pathname.length<i.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",n=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return a.startsWith(n)}({requestedResource:a,configuredResource:r.resource}))throw Error(`Protected resource ${r.resource} does not match expected ${a} (or origin)`);return new URL(r.resource)}}function tR(e){let t,r=e.headers.get("WWW-Authenticate");if(!r)return{};let[i,a]=r.split(" ");if("bearer"!==i.toLowerCase()||!a)return{};let n=tN(e,"resource_metadata")||void 0;if(n)try{t=new URL(n)}catch{}return{resourceMetadataUrl:t,scope:tN(e,"scope")||void 0,error:tN(e,"error")||void 0}}function tN(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let i=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(i);return a?a[1]||a[2]:null}async function tP(e,t,r=fetch){let i=await tB(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!i||404===i.status)throw await i?.body?.cancel(),Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!i.ok)throw await i.body?.cancel(),Error(`HTTP ${i.status} trying to load well-known OAuth protected resource metadata.`);return e8.parse(await i.json())}async function tO(e,t,r=fetch){try{return await r(e,{headers:t})}catch(i){if(i instanceof TypeError)if(t)return tO(e,void 0,r);else return;throw i}}async function tj(e,t,r=fetch){return await tO(e,{"MCP-Protocol-Version":t},r)}async function tB(e,t,r,i){var a,n;let s,o=new URL(e),l=i?.protocolVersion??v.LATEST_PROTOCOL_VERSION;i?.metadataUrl?s=new URL(i.metadataUrl):(s=new URL(function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,o.pathname),i?.metadataServerUrl??o)).search=o.search;let c=await tj(s,l,r);if(!i?.metadataUrl&&(a=c,n=o.pathname,!a||a.status>=400&&a.status<500&&"/"!==n)){let e=new URL(`/.well-known/${t}`,o);c=await tj(e,l,r)}return c}async function tU(e,{fetchFn:t=fetch,protocolVersion:r=v.LATEST_PROTOCOL_VERSION}={}){let i={"MCP-Protocol-Version":r,Accept:"application/json"};for(let{url:r,type:a}of function(e){let t="string"==typeof e?new URL(e):e,r="/"!==t.pathname,i=[];if(!r)return i.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),i.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),i;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),i.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),i.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),i.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}(e)){let e=await tO(r,i,t);if(e){if(!e.ok){if(await e.body?.cancel(),e.status>=400&&e.status<500)continue;throw Error(`HTTP ${e.status} trying to load ${"oauth"===a?"OAuth":"OpenID provider"} metadata from ${r}`)}if("oauth"===a)return e5.parse(await e.json());return e7.parse(await e.json())}}}async function tq(e,t){let r,i;try{(r=await tP(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn)).authorization_servers&&r.authorization_servers.length>0&&(i=r.authorization_servers[0])}catch{}i||(i=String(new URL("/",e)));let a=await tU(i,{fetchFn:t?.fetchFn});return{authorizationServerUrl:i,authorizationServerMetadata:a,resourceMetadata:r}}async function tL(e,{metadata:t,clientInformation:r,redirectUrl:i,scope:a,state:n,resource:s}){let o;if(t){if(o=new URL(t.authorization_endpoint),!t.response_types_supported.includes(t_))throw Error(`Incompatible auth server: does not support response type ${t_}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(tE))throw Error(`Incompatible auth server: does not support code challenge method ${tE}`)}else o=new URL("/authorize",e);let l=await e0(),c=l.code_verifier,u=l.code_challenge;return o.searchParams.set("response_type",t_),o.searchParams.set("client_id",r.client_id),o.searchParams.set("code_challenge",u),o.searchParams.set("code_challenge_method",tE),o.searchParams.set("redirect_uri",String(i)),n&&o.searchParams.set("state",n),a&&o.searchParams.set("scope",a),a?.includes("offline_access")&&o.searchParams.append("prompt","consent"),s&&o.searchParams.set("resource",s.href),{authorizationUrl:o,codeVerifier:c}}async function tM(e,{metadata:t,tokenRequestParams:r,clientInformation:i,addClientAuthentication:a,resource:n,fetchFn:s}){var o,l;let c,u=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),d=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});n&&r.set("resource",n.href),a?await a(d,r,u,t):i&&function(e,t,r,i){let{client_id:a,client_secret:n}=t;switch(e){case"client_secret_basic":var s,o,l,c,u=a,d=n,p=r;if(!d)throw Error("client_secret_basic authentication requires a client_secret");let h=btoa(`${u}:${d}`);p.set("Authorization",`Basic ${h}`);return;case"client_secret_post":s=a,o=n,(l=i).set("client_id",s),o&&l.set("client_secret",o);return;case"none":c=a,i.set("client_id",c);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}((o=i,l=t?.token_endpoint_auth_methods_supported??[],c=void 0!==o.client_secret,"token_endpoint_auth_method"in o&&o.token_endpoint_auth_method&&["client_secret_basic","client_secret_post","none"].includes(o.token_endpoint_auth_method)&&(0===l.length||l.includes(o.token_endpoint_auth_method))?o.token_endpoint_auth_method:0===l.length?c?"client_secret_basic":"none":c&&l.includes("client_secret_basic")?"client_secret_basic":c&&l.includes("client_secret_post")?"client_secret_post":l.includes("none")?"none":c?"client_secret_post":"none"),i,d,r);let p=await (s??fetch)(u,{method:"POST",headers:d,body:r});if(!p.ok)throw await tC(p);return te.parse(await p.json())}async function tF(e,{metadata:t,clientInformation:r,refreshToken:i,resource:a,addClientAuthentication:n,fetchFn:s}){let o=new URLSearchParams({grant_type:"refresh_token",refresh_token:i});return{refresh_token:i,...await tM(e,{metadata:t,tokenRequestParams:o,clientInformation:r,addClientAuthentication:n,resource:a,fetchFn:s})}}async function tV(e,t,{metadata:r,resource:i,authorizationCode:a,fetchFn:n}={}){let s,o=e.clientMetadata.scope;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!a)throw Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw Error("redirectUrl is required for authorization_code flow");s=new URLSearchParams({grant_type:"authorization_code",code:a,code_verifier:await e.codeVerifier(),redirect_uri:String(e.redirectUrl)})}return tM(t,{metadata:r,tokenRequestParams:s,clientInformation:await e.clientInformation()??void 0,addClientAuthentication:e.addClientAuthentication,resource:i,fetchFn:n})}async function tK(e,{metadata:t,clientMetadata:r,scope:i,fetchFn:a}){let n;if(t){if(!t.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");n=new URL(t.registration_endpoint)}else n=new URL("/register",e);let s=await (a??fetch)(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...void 0!==i?{scope:i}:{}})});if(!s.ok)throw await tC(s);return tn.parse(await s.json())}class tH extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class tz{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eW(t?.fetch,t?.requestInit)}async _authThenStart(){let e;if(!this._authProvider)throw new tA("No auth provider");try{e=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tA;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eJ(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new eG(this._url.href,{...this._eventSourceInit,fetch:async(t,r)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(t,{...r,headers:i});if(401===a.status&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:e,scope:t}=tR(a);this._resourceMetadataUrl=e,this._scope=t}return a}}),this._abortController=new AbortController,this._eventSource.onerror=e=>{if(401===e.code&&this._authProvider)return void this._authThenStart().then(t,r);let i=new tH(e.code,e.message,e);r(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",e=>{try{if(this._endpoint=new URL(e.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(e){r(e),this.onerror?.(e),this.close();return}t()}),this._eventSource.onmessage=e=>{let t;try{t=v.JSONRPCMessageSchema.parse(JSON.parse(e.data))}catch(e){this.onerror?.(e);return}this.onmessage?.(t)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new tA("No auth provider");if("AUTHORIZED"!==await tT(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tA("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw Error("Not connected");try{let t=await this._commonHeaders();t.set("content-type","application/json");let r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},i=await (this._fetch??fetch)(this._endpoint,r);if(!i.ok){let t=await i.text().catch(()=>null);if(401===i.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r}=tR(i);this._resourceMetadataUrl=t,this._scope=r;let a=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==a)throw new tA;return this.send(e)}throw Error(`Error POSTing to endpoint (HTTP ${i.status}): ${t}`)}await i.body?.cancel()}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}}class tG extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:i}={}){let a;super({start(n){a=eh({onEvent:e=>{n.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&n.error(t)},onRetry:t,onComment:r,maxBufferSize:i})},transform(e){a.feed(e)}})}}let tJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class tW extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class tZ{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=eW(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??tJ}async _authThenStart(){let e;if(!this._authProvider)throw new tA("No auth provider");try{e=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if("AUTHORIZED"!==e)throw new tA;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=eJ(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);let i=await (this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!i.ok){if(await i.body?.cancel(),401===i.status&&this._authProvider)return await this._authThenStart();if(405===i.status)return;throw new tW(i.status,`Failed to open SSE stream: ${i.statusText}`)}this._handleSseStream(i.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){return void 0!==this._serverRetryMs?this._serverRetryMs:Math.min(this._reconnectionOptions.initialReconnectionDelay*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),this._reconnectionOptions.maxReconnectionDelay)}_scheduleReconnection(e,t=0){let r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(Error(`Maximum reconnection attempts (${r}) exceeded.`));let i=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},i)}_handleSseStream(e,t,r){let i;if(!e)return;let{onresumptiontoken:a,replayMessageId:n}=t,s=!1,o=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new tG({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:r}=await t.read();if(r)break;if((e.id&&(i=e.id,s=!0,a?.(e.id)),e.data)&&(!e.event||"message"===e.event))try{let t=v.JSONRPCMessageSchema.parse(JSON.parse(e.data));(0,v.isJSONRPCResultResponse)(t)&&(o=!0,void 0!==n&&(t.id=n)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(r||s)&&!o&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:n},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new tA("No auth provider");if("AUTHORIZED"!==await tT(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new tA("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:r,onresumptiontoken:i}=t||{};if(r)return void this._startOrAuthSse({resumptionToken:r,replayMessageId:(0,v.isJSONRPCRequest)(e)?e.id:void 0}).catch(e=>this.onerror?.(e));let a=await this._commonHeaders();a.set("content-type","application/json"),a.set("accept","application/json, text/event-stream");let n={...this._requestInit,method:"POST",headers:a,body:JSON.stringify(e),signal:this._abortController?.signal},s=await (this._fetch??fetch)(this._url,n),o=s.headers.get("mcp-session-id");if(o&&(this._sessionId=o),!s.ok){let t=await s.text().catch(()=>null);if(401===s.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new tW(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:t,scope:r}=tR(s);this._resourceMetadataUrl=t,this._scope=r;let i=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit});if("AUTHORIZED"!==i)throw new tA;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===s.status&&this._authProvider){let{resourceMetadataUrl:t,scope:r,error:i}=tR(s);if("insufficient_scope"===i){let i=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===i)throw new tW(403,"Server returned 403 after trying upscoping");r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=i??void 0;let a=await tT(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch});if("AUTHORIZED"!==a)throw new tA;return this.send(e)}}throw new tW(s.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===s.status){await s.body?.cancel(),(0,v.isInitializedNotification)(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let l=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,c=s.headers.get("content-type");if(l)if(c?.includes("text/event-stream"))this._handleSseStream(s.body,{onresumptiontoken:i},!1);else if(c?.includes("application/json")){let e=await s.json();for(let t of Array.isArray(e)?e.map(e=>v.JSONRPCMessageSchema.parse(e)):[v.JSONRPCMessageSchema.parse(e)])this.onmessage?.(t)}else throw await s.body?.cancel(),new tW(-1,`Unexpected content type: ${c}`);else await s.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await (this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&405!==r.status)throw new tW(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}var tY=e.i(243783);e.i(582482);var tQ=e.i(91022),tX=e.i(318905),t0=e.i(971619);function t1(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}function t2(e){return e instanceof Date?e.toISOString():"string"==typeof e&&Number.isFinite(Date.parse(e))?new Date(e).toISOString():null}function t3(e){let t;return{id:String(e.id),name:String(e.name),hostname:String(e.hostname),version:String(e.version),osVersion:String(e.osVersion),architecture:String(e.architecture),cpuModel:"string"==typeof e.cpuModel?e.cpuModel:null,memoryTotalBytes:"number"==typeof e.memoryTotalBytes?e.memoryTotalBytes:null,memoryFreeBytes:"number"==typeof e.memoryFreeBytes?e.memoryFreeBytes:null,diskTotalBytes:"number"==typeof e.diskTotalBytes?e.diskTotalBytes:null,diskFreeBytes:"number"==typeof e.diskFreeBytes?e.diskFreeBytes:null,capabilities:Array.isArray(e.capabilities)?e.capabilities:t1(e.capabilitiesJson)??[],baseRepoDirectory:"string"==typeof e.baseRepoDirectory?e.baseRepoDirectory:null,derivedDataLocationMode:String(e.derivedDataLocationMode),derivedDataPath:"string"==typeof e.derivedDataPath?e.derivedDataPath:null,buildsDirectory:"string"==typeof e.buildsDirectory?e.buildsDirectory:null,defaultBuildsDirectory:"string"==typeof e.defaultBuildsDirectory?e.defaultBuildsDirectory:null,effectiveBuildsDirectory:(0,t0.effectiveBuildsDirectory)(e),connectionStatus:null!==(t=t2(e.lastSeenAt))&&Date.now()-Date.parse(t)<=(0,a.agentOnlineWindowMs)(e)&&!e.disconnectedAt?"ONLINE":"OFFLINE",ipAddress:"string"==typeof e.ipAddress?e.ipAddress:null,lastSeenAt:t2(e.lastSeenAt),disconnectedAt:t2(e.disconnectedAt),createdAt:t2(e.createdAt),updatedAt:t2(e.updatedAt)}}function t4(e){let t=t3(e);return{agentId:t.id,baseRepoDirectory:t.baseRepoDirectory,buildsDirectory:t.buildsDirectory,defaultBuildsDirectory:t.defaultBuildsDirectory,effectiveBuildsDirectory:t.effectiveBuildsDirectory,derivedDataLocationMode:t.derivedDataLocationMode,derivedDataPath:t.derivedDataPath,updatedAt:t.updatedAt}}function t6(e){return{id:String(e.id),agentId:String(e.agentId),worktreeId:"string"==typeof e.worktreeId?e.worktreeId:null,codebaseId:"string"==typeof e.codebaseId?e.codebaseId:null,kind:String(e.kind),payload:t1(e.payload??e.payloadJson),status:String(e.status),idempotencyKey:String(e.idempotencyKey),result:t1(e.result??e.resultJson),error:"string"==typeof e.error?e.error:null,timeoutSeconds:Number(e.timeoutSeconds),createdAt:t2(e.createdAt),startedAt:t2(e.startedAt),finishedAt:t2(e.finishedAt),updatedAt:t2(e.updatedAt)}}let t8=e1.object({}),t5=e1.object({id:e1.string(),name:e1.string(),hostname:e1.string(),version:e1.string(),osVersion:e1.string(),architecture:e1.string(),cpuModel:e1.string().nullable(),memoryTotalBytes:e1.number().nullable(),memoryFreeBytes:e1.number().nullable(),diskTotalBytes:e1.number().nullable(),diskFreeBytes:e1.number().nullable(),capabilities:e1.array(e1.string()),baseRepoDirectory:e1.string().nullable(),derivedDataLocationMode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e1.string().nullable(),buildsDirectory:e1.string().nullable(),defaultBuildsDirectory:e1.string().nullable(),effectiveBuildsDirectory:e1.string().nullable(),connectionStatus:e1.enum(["ONLINE","OFFLINE"]),ipAddress:e1.string().nullable(),lastSeenAt:e1.string().nullable(),disconnectedAt:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),t9=e1.object({agentId:e1.string(),baseRepoDirectory:e1.string().nullable(),buildsDirectory:e1.string().nullable(),defaultBuildsDirectory:e1.string().nullable(),effectiveBuildsDirectory:e1.string().nullable(),derivedDataLocationMode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),derivedDataPath:e1.string().nullable(),updatedAt:e1.string()}),t7=e1.object({id:e1.string(),agentId:e1.string(),worktreeId:e1.string().nullable(),codebaseId:e1.string().nullable(),kind:e1.string(),payload:e1.unknown(),status:e1.string(),idempotencyKey:e1.string(),result:e1.unknown().nullable(),error:e1.string().nullable(),timeoutSeconds:e1.number().int(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable(),updatedAt:e1.string()}),re=e1.object({id:e1.string(),jobId:e1.string(),sequence:e1.number().int(),stream:e1.string(),message:e1.string(),createdAt:e1.string()}),rt=e1.object({agentId:e1.string().min(1)});var rr=e.i(190714),ri=e.i(184015);let ra=e1.object({}),rn=e1.object({settings:e1.object({refreshIntervalSeconds:e1.number().int(),fetchIntervalSeconds:e1.number().int(),defaultJiraBranchRegex:e1.string(),updatedAt:e1.string()})}),rs=e1.object({agentId:e1.string().min(1),path:e1.string().nullable().default(null),requestId:e1.string().min(1)}),ro=e1.object({listing:e1.unknown()}),rl=e1.object({agentId:e1.string().min(1),folder:e1.string().min(1),requestId:e1.string().min(1)}),rc=e1.object({inspection:e1.unknown()}),ru=e1.object({codebaseIds:e1.array(e1.string().min(1)).min(1).max(500),requestId:e1.string().min(1)}),rd=e1.object({jobs:e1.array(e1.unknown()),skipped:e1.array(e1.object({codebaseId:e1.string(),reason:e1.string()}))}),rp=e1.object({codebaseId:e1.string().min(1),requestId:e1.string().min(1)}),rh=e1.object({state:e1.unknown()}),rm=e1.object({codebaseId:e1.string().min(1),stashOid:e1.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i),requestId:e1.string().min(1)}),rf=e1.object({diff:e1.unknown()});e.i(282790);var rg=e.i(474170);function ry(e){return e instanceof Date?e.toISOString():null}function rv(e){if("string"!=typeof e)return e??null;try{return JSON.parse(e)}catch{return null}}let rb=e1.object({id:e1.string(),clientRegistrationId:e1.string(),tokenMasked:e1.string(),topic:e1.string(),environment:e1.string(),supportedPushTypes:e1.array(e1.string()),displayName:e1.string(),deviceModel:e1.string().nullable(),osVersion:e1.string().nullable(),appVersion:e1.string().nullable(),appBuild:e1.string().nullable(),locale:e1.string().nullable(),pushMagicConfigured:e1.boolean(),status:e1.string(),invalidatedAt:e1.string().nullable(),lastFailureReason:e1.string().nullable(),lastFailureAt:e1.string().nullable(),lastRegisteredAt:e1.string(),lastSentAt:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),rw=e1.object({id:e1.string(),name:e1.string(),topic:e1.string(),environment:e1.string(),fingerprint:e1.string(),expiresAt:e1.string().nullable(),lastTestedAt:e1.string().nullable(),lastError:e1.string().nullable(),createdAt:e1.string(),updatedAt:e1.string()}),rx=e1.object({tokenConfigured:e1.boolean(),tokenTeamId:e1.string().nullable(),tokenKeyId:e1.string().nullable(),tokenPrivateKeyFingerprint:e1.string().nullable(),tokenConfiguredAt:e1.string().nullable(),tokenLastUsedAt:e1.string().nullable(),tokenLastError:e1.string().nullable(),certificates:e1.array(rw),updatedAt:e1.string()}),rk=e1.object({id:e1.string(),channelId:e1.string(),bundleId:e1.string(),environment:e1.string(),storagePolicy:e1.string(),createdAt:e1.string(),updatedAt:e1.string()}),rS=e1.object({id:e1.string(),name:e1.string(),editor:e1.unknown(),createdAt:e1.string(),updatedAt:e1.string()}),rI=e1.object({id:e1.string(),registrationId:e1.string().nullable(),topic:e1.string(),environment:e1.string(),status:e1.string(),apnsId:e1.string().nullable(),responseCode:e1.number().int().nullable(),reason:e1.string().nullable(),responseTimestamp:e1.string().nullable(),attempts:e1.number().int(),durationMs:e1.number().int().nullable(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable()}),rA=e1.object({id:e1.string(),requestId:e1.string(),status:e1.string(),editor:e1.unknown(),payload:e1.unknown(),headers:e1.unknown(),targetMode:e1.string(),channelId:e1.string().nullable(),recipientCount:e1.number().int(),successCount:e1.number().int(),failureCount:e1.number().int(),error:e1.string().nullable(),createdAt:e1.string(),startedAt:e1.string().nullable(),finishedAt:e1.string().nullable(),updatedAt:e1.string(),deliveries:e1.array(rI)});function r_(e){return{id:String(e.id),requestId:String(e.requestId),status:String(e.status),editor:rv(e.editor??e.editorJson),payload:rv(e.payload??e.payloadJson),headers:rv(e.headers??e.headersJson),targetMode:String(e.targetMode),channelId:"string"==typeof e.channelId?e.channelId:null,recipientCount:Number(e.recipientCount),successCount:Number(e.successCount),failureCount:Number(e.failureCount),error:"string"==typeof e.error?e.error:null,createdAt:ry(e.createdAt),startedAt:ry(e.startedAt),finishedAt:ry(e.finishedAt),updatedAt:ry(e.updatedAt),deliveries:Array.isArray(e.deliveries)?e.deliveries.map(e=>({id:String(e.id),registrationId:"string"==typeof e.registrationId?e.registrationId:null,topic:String(e.topic),environment:String(e.environment),status:String(e.status),apnsId:"string"==typeof e.apnsId?e.apnsId:null,responseCode:"number"==typeof e.responseCode?e.responseCode:null,reason:"string"==typeof e.reason?e.reason:null,responseTimestamp:ry(e.responseTimestamp),attempts:Number(e.attempts),durationMs:"number"==typeof e.durationMs?e.durationMs:null,createdAt:ry(e.createdAt),startedAt:ry(e.startedAt),finishedAt:ry(e.finishedAt)})):[]}}let rE={requestId:e1.string().min(1),editor:e1.record(e1.string(),e1.unknown())},rC={requestId:e1.string().min(1),presetId:e1.string().min(1)},rT=e1.discriminatedUnion("targetMode",[e1.object({...rE,targetMode:e1.literal("DEVICES"),registrationIds:e1.array(e1.string().min(1)).min(1)}),e1.object({...rE,targetMode:e1.literal("ALL")}),e1.object({...rE,targetMode:e1.literal("BROADCAST"),channelId:e1.string().min(1)}),e1.object({...rE,targetMode:e1.literal("DIRECT"),directToken:e1.string().min(1),directTokenEncoding:e1.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e1.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]),rD=e1.discriminatedUnion("targetMode",[e1.object({...rC,targetMode:e1.literal("DEVICES"),registrationIds:e1.array(e1.string().min(1)).min(1)}),e1.object({...rC,targetMode:e1.literal("ALL")}),e1.object({...rC,targetMode:e1.literal("BROADCAST"),channelId:e1.string().min(1)}),e1.object({...rC,targetMode:e1.literal("DIRECT"),directToken:e1.string().min(1),directTokenEncoding:e1.enum(["HEX","BASE64"]).default("HEX"),directEnvironment:e1.enum(["SANDBOX","PRODUCTION"]).default("SANDBOX")})]);function r$(e){return{requestId:e.requestId,editor:e.editor,targetMode:e.targetMode,registrationIds:"DEVICES"===e.targetMode?e.registrationIds:void 0,channelId:"BROADCAST"===e.targetMode?e.channelId:void 0,directToken:"DIRECT"===e.targetMode?e.directToken:void 0,directTokenEncoding:"DIRECT"===e.targetMode?e.directTokenEncoding:void 0,directEnvironment:"DIRECT"===e.targetMode?e.directEnvironment:void 0}}let rR=e1.object({id:e1.string(),entryType:e1.enum(["CONSOLE","ANALYTICS","SEPARATOR"]),clientTime:e1.string(),receivedAt:e1.string(),deviceIp:e1.string().nullable(),message:e1.string().nullable(),level:e1.string().nullable(),category:e1.string().nullable(),eventName:e1.string().nullable(),eventKind:e1.string().nullable(),screenName:e1.string().nullable(),buildId:e1.string().nullable(),sessionId:e1.string().nullable(),attributes:e1.record(e1.string(),e1.unknown()),defaultParameters:e1.record(e1.string(),e1.unknown()),additionalParameters:e1.record(e1.string(),e1.unknown()),highlightColor:e1.string().nullable(),separatorKind:e1.string().nullable(),separatorName:e1.string().nullable()}),rN=e1.object({items:e1.array(rR),nextCursor:e1.string().nullable(),matchingCount:e1.number().int().nonnegative(),totalCount:e1.number().int().nonnegative()}),rP=rN.extend({separator:rR.nullable()}),rO=e1.object({first:e1.number().int().min(1).max(500).default(200),after:e1.string().nullable().default(null)}),rj=e1.object({field:e1.string().min(1),operator:e1.enum(["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"]),value:e1.string().nullable().optional(),caseSensitive:e1.boolean().default(!1),sources:e1.array(e1.enum(["CONSOLE","ANALYTICS"])).optional()}),rB=e1.object({mode:e1.enum(["ALL","ANY"]),conditions:e1.array(rj).min(1).max(100)}),rU={search:e1.string().min(1).nullable().optional(),searchMode:e1.enum(["TEXT","GLOB","REGEX"]).default("TEXT"),caseSensitive:e1.boolean().default(!1),quickFilters:e1.record(e1.string(),e1.array(e1.string()).max(500)).nullable().optional(),advancedFilter:rB.nullable().optional()},rq=rO.extend(rU).refine(rV,{message:"At least one telemetry search filter is required"}),rL=rO.extend(rU),rM=e1.object({scope:e1.literal("MATCHING"),...rU}).refine(rV,{message:"At least one telemetry search filter is required"}),rF=e1.union([e1.object({scope:e1.literal("IDS"),ids:e1.array(e1.string().min(1)).min(1).max(1e3)}),rM,e1.object({scope:e1.literal("ALL"),includeSeparators:e1.boolean().default(!1)}),e1.object({scope:e1.literal("BEFORE_LATEST_SEPARATOR"),includeSeparators:e1.boolean().default(!1)})]);function rV(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function rK(e,t){return{view:e,first:t.first,after:t.after,search:t.search,searchMode:t.searchMode??"TEXT",caseSensitive:t.caseSensitive??!1,quickFilters:t.quickFilters,advancedFilter:t.advancedFilter}}function rH(e,t,r){return[rW({name:`get_${r.plural}`,title:`Get ${r.label}`,description:`Fetch the newest ${r.label.toLocaleLowerCase()} with cursor pagination.`,inputSchema:rO,outputSchema:rN,annotations:rz,handler:r=>e.timeline(rK(t,r))}),rW({name:`get_${r.singular}`,title:`Get ${r.singular.replaceAll("_"," ")}`,description:`Fetch one ${r.label.toLocaleLowerCase()} item by ID.`,inputSchema:e1.object({id:e1.string().min(1)}),outputSchema:e1.object({entry:rR.nullable()}),annotations:rz,handler:async({id:r})=>({entry:await e.entry(r,t)})}),rW({name:`search_${r.plural}`,title:`Search ${r.label}`,description:"Search with text, glob, regex, quick facets, or advanced filter conditions.",inputSchema:rq,outputSchema:rN,annotations:rz,handler:r=>e.timeline(rK(t,r))}),rW({name:`get_${r.plural}_since_latest_separator`,title:`Get ${r.label} since latest separator`,description:"Fetch entries strictly newer than the latest global telemetry separator.",inputSchema:rL,outputSchema:rP,annotations:rz,handler:r=>e.timelineSinceLatestSeparator(rK(t,r))}),rW({name:`get_${r.singular}_search_metadata`,title:`Get ${r.label} search metadata`,description:"Get searchable fields and current facet values.",inputSchema:e1.object({}),outputSchema:e1.object({fields:e1.array(e1.string()),facets:e1.record(e1.string(),e1.array(e1.string()))}),annotations:rz,handler:async()=>{let[r,i]=await Promise.all([e.fields(t),e.facets(t)]);return{fields:r,facets:i}}}),rW({name:`clear_${r.plural}`,title:`Clear ${r.label}`,description:"Clear explicit IDs, matching entries, all entries, or entries before the latest separator.",inputSchema:rF,outputSchema:e1.object({view:e1.enum(["CONSOLE","ANALYTICS","UNIFIED"]),scope:e1.enum(["IDS","MATCHING","ALL","BEFORE_LATEST_SEPARATOR"]),deletedCount:e1.number().int().nonnegative()}),annotations:rJ,handler:async r=>{let i="MATCHING"===r.scope?r:null,a=await e.clearScoped({view:t,scope:r.scope,ids:"IDS"===r.scope?r.ids:null,includeSeparators:("ALL"===r.scope||"BEFORE_LATEST_SEPARATOR"===r.scope)&&r.includeSeparators,query:i?{search:i.search,searchMode:i.searchMode,caseSensitive:i.caseSensitive,quickFilters:i.quickFilters,advancedFilter:i.advancedFilter}:null});return{view:t,scope:r.scope,deletedCount:a}}})]}let rz={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},rG={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},rJ={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1};function rW(e){return{name:e.name,title:e.title,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,annotations:e.annotations??rz,invoke:async t=>{let r=e.inputSchema.parse(t);return e.outputSchema.parse(await e.handler(r))}}}function rZ(e){return{id:e.id,name:e.name,source:"BUILTIN",transport:null,url:null,error:null,tools:e.tools.map(e=>({name:e.name,title:e.title,description:e.description,inputSchema:w.toJSONSchema(e.inputSchema),outputSchema:w.toJSONSchema(e.outputSchema)})),children:e.children.map(rZ)}}function rY(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("Built-in tool output must be a JSON object");return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}class rQ{groups;indexed;byName;groupIds;constructor(e){this.groups=e,this.indexed=function e(t){return t.flatMap(t=>[...t.tools.map(e=>({groupId:t.id,definition:e})),...e(t.children)])}(e),this.byName=new Map,this.groupIds=new Set;const t=e=>{if(this.groupIds.has(e.id))throw Error(`Duplicate built-in tool group id: ${e.id}`);this.groupIds.add(e.id),e.children.forEach(t)};for(const r of(e.forEach(t),this.indexed)){if(this.byName.has(r.definition.name))throw Error(`Duplicate built-in MCP tool name: ${r.definition.name}`);this.byName.set(r.definition.name,r)}}definitions(){return this.indexed.map(({definition:e})=>e)}catalog(){return this.groups.map(rZ)}hasGroup(e){return this.groupIds.has(e)}async call(e,t,r){let i=this.byName.get(t);if(!i||i.groupId!==e)throw Error(`Unknown built-in tool: ${t}`);return rY(await i.definition.invoke(r))}async callByName(e,t){let r=this.byName.get(e);if(!r)throw Error(`Unknown built-in tool: ${e}`);return rY(await r.definition.invoke(t))}}let rX="external:",r0=new Set(["accept","connection","content-length","content-type","host","last-event-id","mcp-protocol-version","mcp-session-id","transfer-encoding"]);function r1(e){if("STREAMABLE_HTTP"===e||"SSE"===e)return e;throw Error(`Unsupported MCP transport: ${e}`)}function r2(e,t){return{id:e.id,name:e.name,url:e.url,transport:r1(e.transport),toolNamePrefix:e.toolNamePrefix,headers:[...e.headers].sort((e,t)=>e.name.localeCompare(t.name)).map(e=>({id:e.id,name:e.name,valueConfigured:t})),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}}class r3{credentials;builtInTools;constructor(e,t,r={},i=new tQ.CredentialService){this.credentials=i,this.builtInTools=function(e){var t,r,i,a,n,s;let o,l,u,d=[(t=e.codebaseTools,r=e.codebases,o=[rW({name:"get_codebases",title:"Get codebases",description:"List every registered codebase checkout.",inputSchema:c.GetCodebasesInputSchema,outputSchema:c.GetCodebasesOutputSchema,annotations:rz,handler:async()=>({codebases:await t.list()})}),rW({name:"get_codebase",title:"Get codebase",description:"Get one registered codebase by ID or exact folder path.",inputSchema:c.GetCodebaseInputSchema,outputSchema:c.GetCodebaseOutputSchema,annotations:rz,handler:async e=>({codebase:"id"in e?await t.getById(e.id):e.agentId?await t.getByPath(e.path,e.agentId):await t.getByPath(e.path)})})],r&&(o.splice(1,0,rW({name:"search_codebases",title:"Search codebases",description:"Search registered codebases by text, agent, repository, branch, availability, or sync state.",inputSchema:c.SearchCodebasesInputSchema,outputSchema:c.SearchCodebasesOutputSchema,annotations:rz,handler:e=>t.search(e)})),o.push(rW({name:"get_codebase_repositories",title:"Get codebase repositories",description:"List canonical repositories and their checkout counts.",inputSchema:ra,outputSchema:c.GetCodebaseRepositoriesOutputSchema,annotations:rz,handler:async()=>({repositories:await t.repositories()})}),rW({name:"get_codebase_repository",title:"Get codebase repository",description:"Get a canonical repository and all of its registered checkouts.",inputSchema:c.GetCodebaseRepositoryInputSchema,outputSchema:c.GetCodebaseRepositoryOutputSchema,annotations:rz,handler:async({id:e})=>({repository:await t.repository(e)})}),rW({name:"get_codebase_settings",title:"Get codebase settings",description:"Get global codebase refresh, fetch, and branch settings.",inputSchema:ra,outputSchema:rn,annotations:rz,handler:async()=>{let e=await r.settings();return{settings:{refreshIntervalSeconds:e.refreshIntervalSeconds,fetchIntervalSeconds:e.fetchIntervalSeconds,defaultJiraBranchRegex:e.defaultJiraBranchRegex,updatedAt:e.updatedAt.toISOString()}}}}),rW({name:"browse_agent_directory",title:"Browse agent directory",description:"List candidate repository folders on an enrolled agent.",inputSchema:rs,outputSchema:ro,annotations:rz,handler:async({agentId:e,path:t,requestId:i})=>({listing:await r.browse(e,t,i)})}),rW({name:"inspect_agent_codebase",title:"Inspect agent codebase",description:"Inspect a repository folder without registering or changing it.",inputSchema:rl,outputSchema:rc,annotations:rz,handler:async({agentId:e,folder:t,requestId:i})=>({inspection:JSON.parse(JSON.stringify(await r.inspect(e,t,i)))})}),rW({name:"refresh_codebases",title:"Refresh codebases",description:"Queue local metadata refreshes for registered codebases.",inputSchema:ru,outputSchema:rd,annotations:rG,handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(ri.CODEBASE_REFRESH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t6(e)),skipped:i.skipped}}}),rW({name:"fetch_codebases",title:"Fetch codebases",description:"Queue remote Git fetches and configured base-branch updates.",inputSchema:ru,outputSchema:rd,annotations:{...rG,openWorldHint:!0},handler:async({codebaseIds:e,requestId:t})=>{let i=await r.runOperation(ri.CODEBASE_FETCH_JOB_KIND,e,t);return{jobs:i.jobs.map(e=>t6(e)),skipped:i.skipped}}}),rW({name:"inspect_codebase_git_state",title:"Inspect codebase Git state",description:"Inspect branches, checkout locations, and stashes.",inputSchema:rp,outputSchema:rh,annotations:rz,handler:async({codebaseId:e,requestId:t})=>({state:await r.inspectGitState(e,t)})}),rW({name:"inspect_codebase_stash",title:"Inspect codebase stash",description:"Read a bounded textual patch for a Git stash.",inputSchema:rm,outputSchema:rf,annotations:rz,handler:async({codebaseId:e,stashOid:t,requestId:i})=>({diff:await r.inspectStash(e,t,i)})}))),{id:"builtin:codebases",name:"Codebases",tools:o,children:[]})];return e.builds&&d.push((i=e.builds,{id:"builtin:builds",name:"Builds",children:[],tools:[rW({name:"get_builds",title:"Get builds",description:"List immutable iOS build records.",inputSchema:rr.GetBuildsInputSchema,outputSchema:rr.GetBuildsOutputSchema,annotations:rz,handler:async e=>{let t=await i.builds(e);return{builds:t.items,nextCursor:t.nextCursor}}}),rW({name:"get_build",title:"Get build",description:"Get a build with sanitized logs.",inputSchema:rr.GetBuildInputSchema,outputSchema:rr.GetBuildOutputSchema,annotations:rz,handler:async({buildId:e,afterLogId:t,logLimit:r})=>{let a=await i.getBuild(e);if(!a)throw Error("Build not found");return{build:a,logs:await i.logs(e,t,r)}}}),rW({name:"get_build_configurations",title:"Get build configurations",description:"List build configurations for a worktree.",inputSchema:rr.GetBuildConfigurationsInputSchema,outputSchema:rr.GetBuildConfigurationsOutputSchema,annotations:rz,handler:async({worktreeId:e})=>({project:await i.projectForWorktree(e)})}),rW({name:"get_build_destinations",title:"Get build destinations",description:"Inspect compatible build destinations.",inputSchema:rr.GetBuildDestinationsInputSchema,outputSchema:rr.GetBuildDestinationsOutputSchema,annotations:rz,handler:async e=>({destinations:"buildId"in e?await i.destinationsForBuild(e.buildId,e.requestId):await i.destinations(e)})}),rW({name:"start_build",title:"Start build",description:"Queue an iOS build.",inputSchema:rr.StartBuildToolInputSchema,outputSchema:rr.StartBuildToolOutputSchema,annotations:rG,handler:async e=>({build:await i.startBuild(e)})}),rW({name:"cancel_build",title:"Cancel build",description:"Cancel an active build.",inputSchema:rr.CancelBuildToolInputSchema,outputSchema:rr.CancelBuildToolOutputSchema,annotations:rJ,handler:async({buildId:e})=>({build:await i.cancelBuild(e)})}),rW({name:"run_build",title:"Run build",description:"Install and launch without rebuilding.",inputSchema:rr.RunBuildToolInputSchema,outputSchema:rr.RunBuildToolOutputSchema,annotations:rG,handler:async e=>({deployments:await i.runBuild(e)})}),rW({name:"export_build_archive",title:"Export build archive",description:"Export an archive to a local IPA folder.",inputSchema:rr.ExportBuildToolInputSchema,outputSchema:rr.ExportBuildToolOutputSchema,annotations:rG,handler:async e=>({export:await i.exportArchive(e)})})]})),e.telemetry&&e.pushNotifications&&d.push((a=e.telemetry,n=e.pushNotifications,(l=rH(a,"UNIFIED",{plural:"unified_events",singular:"unified_event",label:"Unified Events"})).push(rW({name:"get_telemetry_separators",title:"Get telemetry separators",description:"List global manual and build separators with optional filters.",inputSchema:e1.object({first:e1.number().int().min(1).max(500).default(100),after:e1.string().nullable().default(null),kind:e1.string().min(1).nullable().optional(),name:e1.string().min(1).nullable().optional(),buildId:e1.string().min(1).nullable().optional()}),outputSchema:e1.object({items:e1.array(rR),nextCursor:e1.string().nullable()}),annotations:rz,handler:e=>a.separators(e)}),rW({name:"add_telemetry_separator",title:"Add telemetry separator",description:"Add a global manual separator to all telemetry views.",inputSchema:e1.object({name:e1.string().max(100).nullable().default(null)}),outputSchema:e1.object({separator:rR}),annotations:{...rG,idempotentHint:!1},handler:async({name:e})=>({separator:await a.addSeparator(e)})}),rW({name:"get_telemetry_settings",title:"Get telemetry settings",description:"Get telemetry collection state and effective ingestion URLs.",inputSchema:e1.object({}),outputSchema:e1.object({settings:e1.object({localBaseUrlOverride:e1.string().nullable(),remoteBaseUrlOverride:e1.string().nullable(),consoleCollectionEnabled:e1.boolean(),analyticsCollectionEnabled:e1.boolean(),detectedLocalBaseUrl:e1.string(),detectedRemoteBaseUrl:e1.string(),effectiveLocalBaseUrl:e1.string(),effectiveRemoteBaseUrl:e1.string(),updatedAt:e1.string()})}),annotations:rz,handler:async()=>({settings:await a.settings()})})),{id:"builtin:debugging",name:"Debugging",tools:l,children:[{id:"builtin:debugging:console-logs",name:"Console Logs",tools:rH(a,"CONSOLE",{plural:"console_logs",singular:"console_log",label:"Console Logs"}),children:[]},{id:"builtin:debugging:analytics-events",name:"Analytics Events",tools:rH(a,"ANALYTICS",{plural:"analytics_events",singular:"analytics_event",label:"Analytics Events"}),children:[]},(u={...rG,openWorldHint:!0},{id:"builtin:debugging:push-notifications",name:"Push Notifications",children:[],tools:[rW({name:"get_push_notification_registrations",title:"Get push notification registrations",description:"List registered APNs devices with masked tokens.",inputSchema:e1.object({}),outputSchema:e1.object({registrations:e1.array(rb)}),annotations:rz,handler:async()=>({registrations:(await n.registrations()).map(e=>{let t,r;return t=Array.isArray(e.supportedPushTypes)?e.supportedPushTypes:rv(e.pushTypesJson),r="string"==typeof e.token?e.token:"",{id:String(e.id),clientRegistrationId:String(e.clientRegistrationId),tokenMasked:"string"==typeof e.tokenMasked?e.tokenMasked:r?`${r.slice(0,8)}…${r.slice(-8)}`:"—",topic:String(e.topic),environment:String(e.environment),supportedPushTypes:Array.isArray(t)?t:[],displayName:String(e.displayName),deviceModel:"string"==typeof e.deviceModel?e.deviceModel:null,osVersion:"string"==typeof e.osVersion?e.osVersion:null,appVersion:"string"==typeof e.appVersion?e.appVersion:null,appBuild:"string"==typeof e.appBuild?e.appBuild:null,locale:"string"==typeof e.locale?e.locale:null,pushMagicConfigured:!!e.pushMagic,status:String(e.status),invalidatedAt:ry(e.invalidatedAt),lastFailureReason:"string"==typeof e.lastFailureReason?e.lastFailureReason:null,lastFailureAt:ry(e.lastFailureAt),lastRegisteredAt:ry(e.lastRegisteredAt),lastSentAt:ry(e.lastSentAt),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}})})}),rW({name:"get_push_notification_settings",title:"Get push notification settings",description:"Inspect APNs credential status without returning secrets.",inputSchema:e1.object({}),outputSchema:e1.object({settings:rx}),annotations:rz,handler:async()=>{var e;return{settings:{tokenConfigured:!!(e=await n.settings()).tokenConfigured,tokenTeamId:"string"==typeof e.tokenTeamId?e.tokenTeamId:null,tokenKeyId:"string"==typeof e.tokenKeyId?e.tokenKeyId:null,tokenPrivateKeyFingerprint:"string"==typeof e.tokenPrivateKeyFingerprint?e.tokenPrivateKeyFingerprint:null,tokenConfiguredAt:ry(e.tokenConfiguredAt),tokenLastUsedAt:ry(e.tokenLastUsedAt),tokenLastError:"string"==typeof e.tokenLastError?e.tokenLastError:null,certificates:Array.isArray(e.certificates)?e.certificates.map(e=>({id:String(e.id),name:String(e.name),topic:String(e.topic),environment:String(e.environment),fingerprint:String(e.fingerprint),expiresAt:ry(e.expiresAt),lastTestedAt:ry(e.lastTestedAt),lastError:"string"==typeof e.lastError?e.lastError:null,createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)})):[],updatedAt:ry(e.updatedAt)}}}}),rW({name:"get_push_notification_channels",title:"Get push notification channels",description:"List configured APNs broadcast channels.",inputSchema:e1.object({}),outputSchema:e1.object({channels:e1.array(rk)}),annotations:rz,handler:async()=>({channels:(await n.channels()).map(e=>({id:String(e.id),channelId:String(e.channelId),bundleId:String(e.bundleId),environment:String(e.environment),storagePolicy:String(e.storagePolicy),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}))})}),rW({name:"get_push_notification_presets",title:"Get push notification presets",description:"List saved, validated push editor presets.",inputSchema:e1.object({}),outputSchema:e1.object({presets:e1.array(rS)}),annotations:rz,handler:async()=>({presets:(await n.presets()).map(e=>({id:String(e.id),name:String(e.name),editor:rv(e.editor??e.editorJson),createdAt:ry(e.createdAt),updatedAt:ry(e.updatedAt)}))})}),rW({name:"get_push_notification_history",title:"Get push notification history",description:"List recent push batches and per-recipient delivery results.",inputSchema:e1.object({limit:e1.number().int().min(1).max(200).default(100)}),outputSchema:e1.object({batches:e1.array(rA)}),annotations:rz,handler:async({limit:e})=>({batches:(await n.history(e)).map(e=>r_(e))})}),rW({name:"get_push_notification_history_item",title:"Get push notification history item",description:"Get one push batch and all delivery results by ID.",inputSchema:e1.object({id:e1.string().min(1)}),outputSchema:e1.object({batch:rA.nullable()}),annotations:rz,handler:async({id:e})=>{let t=await n.historyItem(e);return{batch:t?r_(t):null}}}),rW({name:"preview_push_notification",title:"Preview push notification",description:"Validate an editor and return its final payload and APNs headers.",inputSchema:e1.object({editor:e1.record(e1.string(),e1.unknown())}),outputSchema:e1.object({editor:e1.unknown(),payload:e1.unknown(),headers:e1.record(e1.string(),e1.string()),byteLength:e1.number().int().nonnegative()}),annotations:rz,handler:({editor:e})=>(0,rg.validatePushEditor)(e)}),rW({name:"send_push_notification",title:"Send push notification",description:"Validate and queue a raw APNs editor payload for delivery.",inputSchema:rT,outputSchema:e1.object({batch:rA}),annotations:u,handler:async e=>({batch:r_(await n.send(r$(e)))})}),rW({name:"send_push_notification_preset",title:"Send push notification preset",description:"Load a saved preset by ID and queue it for APNs delivery.",inputSchema:rD,outputSchema:e1.object({batch:rA}),annotations:u,handler:async e=>{let t=await n.preset(e.presetId);if(!t)throw Error("Push notification preset not found");let r={...e,editor:rv(t.editorJson)};return{batch:r_(await n.send(r$(r)))}}}),rW({name:"resend_push_notification",title:"Resend push notification",description:"Queue a historical non-draft, non-direct batch again.",inputSchema:e1.object({id:e1.string().min(1),requestId:e1.string().min(1)}),outputSchema:e1.object({batch:rA}),annotations:u,handler:async({id:e,requestId:t})=>({batch:r_(await n.resend(e,t))})})]})]})),e.agents&&d.push((s=e.agents,{id:"builtin:agents",name:"Agents",children:[],tools:[rW({name:"get_agents",title:"Get agents",description:"List enrolled agents, capabilities, resources, and status.",inputSchema:t8,outputSchema:e1.object({agents:e1.array(t5)}),annotations:rz,handler:async()=>({agents:(await s.listAgents()).map(e=>t3(e))})}),rW({name:"get_agent",title:"Get agent",description:"Get one enrolled agent by ID.",inputSchema:rt,outputSchema:e1.object({agent:t5.nullable()}),annotations:rz,handler:async({agentId:e})=>{let t=await s.getAgent(e);return{agent:t?t3(t):null}}}),rW({name:"get_agent_settings",title:"Get agent settings",description:"Get repository, build, and Derived Data paths for an agent.",inputSchema:rt,outputSchema:e1.object({settings:t9}),annotations:rz,handler:async({agentId:e})=>{let t=await s.getAgent(e);if(!t)throw Error("Agent not found");return{settings:t4(t)}}}),rW({name:"get_agent_jobs",title:"Get agent jobs",description:"List recent user-visible jobs for an agent.",inputSchema:e1.object({agentId:e1.string().min(1),limit:e1.number().int().min(1).max(200).default(50)}),outputSchema:e1.object({jobs:e1.array(t7)}),annotations:rz,handler:async({agentId:e,limit:t})=>({jobs:(await s.listJobs(e,t)).map(e=>t6(e))})}),rW({name:"get_agent_job",title:"Get agent job",description:"Get one agent job and its result by ID.",inputSchema:e1.object({jobId:e1.string().min(1)}),outputSchema:e1.object({job:t7.nullable()}),annotations:rz,handler:async({jobId:e})=>{let t=await s.getJob(e);return{job:t?t6(t):null}}}),rW({name:"get_agent_job_logs",title:"Get agent job logs",description:"Fetch ordered job logs after an optional sequence number.",inputSchema:e1.object({jobId:e1.string().min(1),afterSequence:e1.number().int().min(-1).default(-1)}),outputSchema:e1.object({logs:e1.array(re)}),annotations:rz,handler:async({jobId:e,afterSequence:t})=>({logs:(await s.listLogs(e,t)).map(e=>({id:String(e.id),jobId:String(e.jobId),sequence:Number(e.sequence),stream:String(e.stream),message:String(e.message),createdAt:t2(e.createdAt)}))})}),rW({name:"update_agent_base_repo_directory",title:"Update agent base repository directory",description:"Set or reset the absolute base repository directory.",inputSchema:e1.object({agentId:e1.string().min(1),baseRepoDirectory:e1.string().min(1).nullable()}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,baseRepoDirectory:t})=>({settings:t4(await s.updateBaseRepoDirectory(e,t))})}),rW({name:"update_agent_builds_directory",title:"Update agent builds directory",description:"Set or reset the absolute build-output directory.",inputSchema:e1.object({agentId:e1.string().min(1),buildsDirectory:e1.string().min(1).nullable()}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,buildsDirectory:t})=>({settings:t4(await s.updateBuildsDirectory(e,t))})}),rW({name:"update_agent_derived_data_settings",title:"Update agent Derived Data settings",description:"Set default, absolute, or worktree-relative Derived Data paths.",inputSchema:e1.object({agentId:e1.string().min(1),mode:e1.enum(["DEFAULT","ABSOLUTE","RELATIVE"]),path:e1.string().min(1).nullable().default(null)}),outputSchema:e1.object({settings:t9}),annotations:rG,handler:async({agentId:e,mode:t,path:r})=>({settings:t4(await s.updateDerivedDataSettings(e,t,r))})}),rW({name:"request_agent_codebase_reconcile",title:"Request agent codebase reconcile",description:"Ask an online agent to reconcile its registered codebases.",inputSchema:rt,outputSchema:e1.object({requested:e1.boolean()}),annotations:rG,handler:async({agentId:e})=>({requested:await s.requestCodebaseReconcile([e])===1})}),rW({name:"cancel_agent_job",title:"Cancel agent job",description:"Cancel a queued or running agent job.",inputSchema:e1.object({jobId:e1.string().min(1)}),outputSchema:e1.object({job:t7}),annotations:rJ,handler:async({jobId:e})=>({job:t6(await s.cancelJob(e))})})]})),new rQ(d)}({codebaseTools:e,builds:t,...r})}async externalServers(){let e=await (0,tY.getPrismaClient)();return Promise.all((await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}})).map(async e=>r2(e,0===e.headers.length||await this.credentials.isConfigured((0,tX.externalMcpHeadersCredential)(e.id)))))}async createExternalServer(e){return this.saveExternalServer(null,e)}async updateExternalServer(e,t){return this.saveExternalServer(e,t)}async saveExternalServer(e,t){let r=function(e){let t,r=e.name.trim();if(!r)throw Error("Server name is required");if(r.length>80)throw Error("Server name must be 80 characters or fewer");try{t=new URL(e.url.trim())}catch{throw Error("Server URL must be a valid HTTP or HTTPS URL")}if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Error("Server URL must be an HTTP or HTTPS URL without embedded credentials");if("STREAMABLE_HTTP"!==e.transport&&"SSE"!==e.transport)throw Error("Transport must be Streamable HTTP or SSE");let i=e.toolNamePrefix?.trim()??"";if(i.length>64||!/^[A-Za-z0-9_.-]*$/.test(i))throw Error("Tool name prefix may contain up to 64 letters, numbers, underscores, periods, or hyphens");let a=new Set,n=e.headers.map(e=>{let t=e.name.trim();if(!t)throw Error("Header name is required");let r=t.toLowerCase();if(r0.has(r))throw Error(`${t} is managed by the MCP transport`);if(a.has(r))throw Error(`Duplicate header name: ${t}`);a.add(r);try{new Headers([[t,e.value??"validation"]])}catch{throw Error(`Invalid HTTP header: ${t}`)}return{id:e.id??null,name:t,value:e.value}});return{name:r,url:t.toString(),transport:e.transport,toolNamePrefix:i,headers:n}}(t),i=await (0,tY.getPrismaClient)();if((await i.externalMcpServer.findMany({select:{id:!0,name:!0}})).some(t=>t.id!==e&&t.name.toLocaleLowerCase()===r.name.toLocaleLowerCase()))throw Error("An MCP server with this name already exists");let a=e?await i.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}}):null;if(e&&!a)throw Error("External MCP server not found");let n=new Map(a?.headers.map(e=>[e.id,e])??[]),s=e??(0,g.randomUUID)(),o=(0,tX.externalMcpHeadersCredential)(s),l=new Map((e?await this.credentials.getJson(o)??[]:[]).map(e=>[e.id,e]));for(let e of r.headers){if(e.id&&!n.has(e.id))throw Error(`Header ${e.name} does not belong to this server`);if(!e.id&&!e.value)throw Error(`A value is required for the new ${e.name} header`)}let c=r.headers.map(e=>{let t=e.id??(0,g.randomUUID)(),r=e.value||l.get(t)?.value;if(!r)throw Error(`A value is required for ${e.name}`);return{id:t,name:e.name,value:r}}),u=async e=>{await e.externalMcpServer.upsert({where:{id:s},create:{id:s,name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix},update:{name:r.name,url:r.url,transport:r.transport,toolNamePrefix:r.toolNamePrefix}}),await e.externalMcpServerHeader.deleteMany({where:{serverId:s}}),c.length&&await e.externalMcpServerHeader.createMany({data:c.map(e=>({id:e.id,serverId:s,name:e.name}))})};return c.length?await this.credentials.setJson(o,c,u):await this.credentials.delete(o,u),r2(await i.externalMcpServer.findUniqueOrThrow({where:{id:s},include:{headers:!0}}),!0)}async deleteExternalServer(e){return await this.credentials.delete((0,tX.externalMcpHeadersCredential)(e),async t=>{await t.externalMcpServer.delete({where:{id:e}})}),{id:e}}async catalog(){let e=await (0,tY.getPrismaClient)(),t=await e.externalMcpServer.findMany({orderBy:{name:"asc"},include:{headers:!0}}),r=await Promise.all(t.map(async e=>{try{let t=await this.listRemoteTools(await this.externalServerWithSecrets(e.id));return{id:`${rX}${e.id}`,name:e.name,source:"EXTERNAL",transport:r1(e.transport),url:e.url,error:null,tools:t.map(t=>({...t,name:`${e.toolNamePrefix}${t.name}`})),children:[]}}catch(t){return{id:`${rX}${e.id}`,name:e.name,source:"EXTERNAL",transport:r1(e.transport),url:e.url,error:t instanceof Error?t.message:String(t),tools:[],children:[]}}}));return{groups:[...this.builtInTools.catalog(),...r]}}async callTool(e){if(this.builtInTools.hasGroup(e.groupId))return this.builtInTools.call(e.groupId,e.name,e.arguments);if(!e.groupId.startsWith(rX))throw Error("Unknown tool group");let t=e.groupId.slice(rX.length),r=await this.externalServerWithSecrets(t);if(!e.name.startsWith(r.toolNamePrefix))throw Error("Tool name does not use this server's configured prefix");let i=e.name.slice(r.toolNamePrefix.length);if(!i)throw Error("Tool name is required");return this.withClient(r,t=>t.callTool({name:i,arguments:e.arguments},void 0,{timeout:12e4,resetTimeoutOnProgress:!0}))}async externalServerWithSecrets(e){let t=await (0,tY.getPrismaClient)(),r=await t.externalMcpServer.findUnique({where:{id:e},include:{headers:!0}});if(!r)throw Error("External MCP server not found");if(r1(r.transport),!r.headers.length)return{...r,headers:[]};let i=await this.credentials.getJson((0,tX.externalMcpHeadersCredential)(r.id));if(!i)throw Error("External MCP server headers are not configured; re-enter them in Settings");let a=new Map(i.map(e=>[e.id,e]));return{...r,headers:r.headers.map(e=>{let t=a.get(e.id);if(!t?.value)throw Error(`External MCP header ${e.name} is missing; re-enter it in Settings`);return{id:e.id,name:e.name,value:t.value}})}}async withClient(e,t){var r;let i,a=new eu({name:"ai-development-environment-tools",version:"0.1.0"}),n=(r=e,async(e,t)=>{let i=new Headers(r.headers.map(e=>[e.name,e.value]));return e instanceof Request&&e.headers.forEach((e,t)=>i.set(t,e)),new Headers(t?.headers).forEach((e,t)=>i.set(t,e)),fetch(e,{...t,headers:i})}),s="STREAMABLE_HTTP"===r1(e.transport)?new tZ(new URL(e.url),{fetch:n}):new tz(new URL(e.url),{fetch:n}),o=()=>i??=a.close().catch(()=>void 0);try{let e;try{await Promise.race([a.connect(s,{timeout:15e3}),new Promise((t,r)=>{e=setTimeout(()=>{o(),r(Error("External MCP server connection timed out after 15000ms"))},15e3)})])}finally{e&&clearTimeout(e)}return await t(a)}finally{await o()}}async listRemoteTools(e){return this.withClient(e,async e=>{let t,r=[],i=new Set,a=0;do{let n=await e.listTools(t?{cursor:t}:void 0,{timeout:15e3});a+=1,r.push(...n.tools.map(e=>({name:e.name,title:e.title??null,description:e.description??null,inputSchema:e.inputSchema,outputSchema:e.outputSchema??null})));let s=n.nextCursor;if(s){if(i.has(s))throw Error("External MCP server returned a repeated tools/list cursor");if(a>=100)throw Error("External MCP server exceeded the tools/list pagination limit of 100 pages");i.add(s)}t=s}while(t)return r})}}class r4{constructor(e){this._server=e}requestStream(e,t,r){return this._server.requestStream(e,t,r)}createMessageStream(e,t){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},v.CreateMessageResultSchema,t)}elicitInputStream(e,t){let r=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":if(!r?.elicitation?.url)throw Error("Client does not support url elicitation.");break;case"form":if(!r?.elicitation?.form)throw Error("Client does not support form elicitation.")}let a="form"===i&&void 0===e.mode?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},v.ElicitResultSchema,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._server.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}}class r6 extends et{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(v.LoggingLevelSchema.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let r=this._loggingLevels.get(t);return!!r&&this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(r)},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new es,this.setRequestHandler(v.InitializeRequestSchema,e=>this._oninitialize(e)),this.setNotificationHandler(v.InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(v.SetLevelRequestSchema,async(e,t)=>{let r=t.sessionId||t.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=e.params,a=v.LoggingLevelSchema.safeParse(i);return a.success&&this._loggingLevels.set(r,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new r4(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=ei(this._capabilities,e)}setRequestHandler(e,t){let r,i=(0,y.getObjectShape)(e),a=i?.method;if(!a)throw Error("Schema is missing a method literal");if((0,y.isZ4Schema)(a)){let e=a._zod?.def;r=e?.value??a.value}else{let e=a._def;r=e?.value??a.value}if("string"!=typeof r)throw Error("Schema method literal must be a string");if("tools/call"===r){let r=async(e,r)=>{let i=(0,y.safeParse)(v.CallToolRequestSchema,e);if(!i.success){let e=i.error instanceof Error?i.error.message:String(i.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:a}=i.data,n=await Promise.resolve(t(e,r));if(a.task){let e=(0,y.safeParse)(v.CreateTaskResultSchema,n);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let s=(0,y.safeParse)(v.CallToolResultSchema,n);if(!s.success){let e=s.error instanceof Error?s.error.message:String(s.error);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid tools/call result: ${e}`)}return s.data};return super.setRequestHandler(e,r)}return super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){ec(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&el(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:v.SUPPORTED_PROTOCOL_VERSIONS.includes(t)?t:v.LATEST_PROTOCOL_VERSION,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},v.EmptyResultSchema)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(e.messages.length>0){let t=e.messages[e.messages.length-1],r=Array.isArray(t.content)?t.content:[t.content],i=r.some(e=>"tool_result"===e.type),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,n=a?Array.isArray(a.content)?a.content:[a.content]:[],s=n.some(e=>"tool_use"===e.type);if(i){if(r.some(e=>"tool_result"!==e.type))throw Error("The last message must contain only tool_result content if any is present");if(!s)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(s){let e=new Set(n.filter(e=>"tool_use"===e.type).map(e=>e.id)),t=new Set(r.filter(e=>"tool_result"===e.type).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},v.CreateMessageResultWithToolsSchema,t):this.request({method:"sampling/createMessage",params:e},v.CreateMessageResultSchema,t)}async elicitInput(e,t){switch(e.mode??"form"){case"url":if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");return this.request({method:"elicitation/create",params:e},v.ElicitResultSchema,t);case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let r="form"===e.mode?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:r},v.ElicitResultSchema,t);if("accept"===i.action&&i.content&&r.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(r.requestedSchema)(i.content);if(!e.valid)throw new v.McpError(v.ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){if(e instanceof v.McpError)throw e;throw new v.McpError(v.ErrorCode.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return i}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},v.ListRootsResultSchema,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}let r8=Symbol.for("mcp.completable");function r5(e){return!!e&&"object"==typeof e&&r8 in e}(i||(i={})).Completable="McpCompletable";let r9=/^[A-Za-z0-9._-]{1,128}$/;function r7(e){let t=function(e){let t=[];if(0===e.length)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!r9.test(e)){let r=e.split("").filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,r)=>r.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${r.map(e=>`"${e}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}(e);var r=t.warnings;if(r.length>0){for(let t of(console.warn(`Tool name validation warning for "${e}":`),r))console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}return t.isValid}class ie{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let i={taskSupport:"required",...t.execution};if("forbidden"===i.taskSupport)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,i,t._meta,r)}}class it{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new r6(e,t)}get experimental(){return this._experimental||(this._experimental={tasks:new ie(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListToolsRequestSchema)),this.server.assertCanSetRequestHandler(il(v.CallToolRequestSchema)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(v.ListToolsRequestSchema,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r,i={name:e,title:t.title,description:t.description,inputSchema:(r=(0,y.normalizeObjectSchema)(t.inputSchema))?Q(r,{strictUnions:!0,pipeStrategy:"input"}):ir,annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=(0,y.normalizeObjectSchema)(t.outputSchema);e&&(i.outputSchema=Q(e,{strictUnions:!0,pipeStrategy:"output"}))}return i})})),this.server.setRequestHandler(v.CallToolRequestSchema,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new v.McpError(v.ErrorCode.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if(("required"===a||"optional"===a)&&!n)throw new v.McpError(v.ErrorCode.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if("required"===a&&!i)throw new v.McpError(v.ErrorCode.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if("optional"===a&&!i&&n)return await this.handleAutomaticTaskPolling(r,e,t);let s=await this.validateToolInput(r,e.params.arguments,e.params.name),o=await this.executeToolHandler(r,s,t);if(i)return o;return await this.validateToolOutput(r,o,e.params.name),o}catch(e){if(e instanceof v.McpError&&e.code===v.ErrorCode.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(!e.inputSchema)return;let i=(0,y.normalizeObjectSchema)(e.inputSchema)??e.inputSchema,a=await (0,y.safeParseAsync)(i,t);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,y.getParseErrorMessage)(e);throw new v.McpError(v.ErrorCode.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${t}`)}return a.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new v.McpError(v.ErrorCode.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let i=(0,y.normalizeObjectSchema)(e.outputSchema),a=await (0,y.safeParseAsync)(i,t.structuredContent);if(!a.success){let e="error"in a?a.error:"Unknown error",t=(0,y.getParseErrorMessage)(e);throw new v.McpError(v.ErrorCode.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${t}`)}}async executeToolHandler(e,t,r){let i=e.handler;if("createTask"in i){if(!r.taskStore)throw Error("No task store provided.");let a={...r,taskStore:r.taskStore};return e.inputSchema?await Promise.resolve(i.createTask(t,a)):await Promise.resolve(i.createTask(a))}return e.inputSchema?await Promise.resolve(i(t,r)):await Promise.resolve(i(r))}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},s=i?await Promise.resolve(a.createTask(i,n)):await Promise.resolve(a.createTask(n)),o=s.task.taskId,l=s.task,c=l.pollInterval??5e3;for(;"completed"!==l.status&&"failed"!==l.status&&"cancelled"!==l.status;){await new Promise(e=>setTimeout(e,c));let e=await r.taskStore.getTask(o);if(!e)throw new v.McpError(v.ErrorCode.InternalError,`Task ${o} not found during polling`);l=e}return await r.taskStore.getTaskResult(o)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(il(v.CompleteRequestSchema)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(v.CompleteRequestSchema,async e=>{switch(e.params.ref.type){case"ref/prompt":return(0,v.assertCompleteRequestPrompt)(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return(0,v.assertCompleteRequestResourceTemplate)(e),this.handleResourceCompletion(e,e.params.ref);default:throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r,i=this._registeredPrompts[t.name];if(!i)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${t.name} not found`);if(!i.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${t.name} disabled`);if(!i.argsSchema)return iu;let a=(0,y.getObjectShape)(i.argsSchema),n=a?.[e.params.argument.name];if(!r5(n))return iu;let s=(r=n[r8],r?.complete);return s?ic(await s(e.params.argument.value,e.params.context)):iu}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return iu;throw new v.McpError(v.ErrorCode.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=r.resourceTemplate.completeCallback(e.params.argument.name);return i?ic(await i(e.params.argument.value,e.params.context)):iu}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListResourcesRequestSchema)),this.server.assertCanSetRequestHandler(il(v.ListResourceTemplatesRequestSchema)),this.server.assertCanSetRequestHandler(il(v.ReadResourceRequestSchema)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(v.ListResourcesRequestSchema,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),i=[];for(let e of Object.values(this._registeredResourceTemplates))if(e.resourceTemplate.listCallback)for(let r of(await e.resourceTemplate.listCallback(t)).resources)i.push({...e.metadata,...r});return{resources:[...r,...i]}}),this.server.setRequestHandler(v.ListResourceTemplatesRequestSchema,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(v.ReadResourceRequestSchema,async(e,t)=>{let r=new URL(e.params.uri),i=this._registeredResources[r.toString()];if(i){if(!i.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Resource ${r} disabled`);return i.readCallback(r,t)}for(let e of Object.values(this._registeredResourceTemplates)){let i=e.resourceTemplate.uriTemplate.match(r.toString());if(i)return e.readCallback(r,i,t)}throw new v.McpError(v.ErrorCode.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(il(v.ListPromptsRequestSchema)),this.server.assertCanSetRequestHandler(il(v.GetPromptRequestSchema)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(v.ListPromptsRequestSchema,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{var r;let i;return{name:e,title:t.title,description:t.description,arguments:t.argsSchema?(r=t.argsSchema,(i=(0,y.getObjectShape)(r))?Object.entries(i).map(([e,t])=>({name:e,description:(0,y.getSchemaDescription)(t),required:!(0,y.isSchemaOptional)(t)})):[]):void 0}})})),this.server.setRequestHandler(v.GetPromptRequestSchema,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new v.McpError(v.ErrorCode.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let i=(0,y.normalizeObjectSchema)(r.argsSchema),a=await (0,y.safeParseAsync)(i,e.params.arguments);if(!a.success){let t="error"in a?a.error:"Unknown error",r=(0,y.getParseErrorMessage)(t);throw new v.McpError(v.ErrorCode.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${r}`)}let n=a.data,s=r.callback;return await Promise.resolve(s(n,t))}{let e=r.callback;return await Promise.resolve(e(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let i;"object"==typeof r[0]&&(i=r.shift());let a=r[0];if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let r=this._createRegisteredResource(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let r=this._createRegisteredResourceTemplate(e,void 0,t,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),r}}registerResource(e,t,r,i){if("string"==typeof t){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,i,a){let n={name:e,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:e=>{void 0!==e.uri&&e.uri!==r&&(delete this._registeredResources[r],e.uri&&(this._registeredResources[e.uri]=n)),void 0!==e.name&&(n.name=e.name),void 0!==e.title&&(n.title=e.title),void 0!==e.metadata&&(n.metadata=e.metadata),void 0!==e.callback&&(n.readCallback=e.callback),void 0!==e.enabled&&(n.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,i,a){let n={resourceTemplate:r,title:t,metadata:i,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.template&&(n.resourceTemplate=t.template),void 0!==t.metadata&&(n.metadata=t.metadata),void 0!==t.callback&&(n.readCallback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let s=r.uriTemplate.variableNames;return Array.isArray(s)&&s.some(e=>!!r.completeCallback(e))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,i,a){let n={title:t,description:r,argsSchema:void 0===i?void 0:(0,y.objectFromShape)(i),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=n)),void 0!==t.title&&(n.title=t.title),void 0!==t.description&&(n.description=t.description),void 0!==t.argsSchema&&(n.argsSchema=(0,y.objectFromShape)(t.argsSchema)),void 0!==t.callback&&(n.callback=t.callback),void 0!==t.enabled&&(n.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,i&&Object.values(i).some(e=>r5(e instanceof e1.ZodOptional?e._def?.innerType:e))&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,i,a,n,s,o,l){r7(e);let c={title:t,description:r,inputSchema:io(i),outputSchema:io(a),annotations:n,execution:s,_meta:o,handler:l,enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{void 0!==t.name&&t.name!==e&&("string"==typeof t.name&&r7(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=c)),void 0!==t.title&&(c.title=t.title),void 0!==t.description&&(c.description=t.description),void 0!==t.paramsSchema&&(c.inputSchema=(0,y.objectFromShape)(t.paramsSchema)),void 0!==t.outputSchema&&(c.outputSchema=(0,y.objectFromShape)(t.outputSchema)),void 0!==t.callback&&(c.handler=t.callback),void 0!==t.annotations&&(c.annotations=t.annotations),void 0!==t._meta&&(c._meta=t._meta),void 0!==t.enabled&&(c.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=c,this.setToolRequestHandlers(),this.sendToolListChanged(),c}tool(e,...t){let r,i,a,n;if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);if("string"==typeof t[0]&&(r=t.shift()),t.length>1){let r=t[0];if(is(r))i=t.shift(),t.length>1&&"object"==typeof t[0]&&null!==t[0]&&!is(t[0])&&(n=t.shift());else if("object"==typeof r&&null!==r){if(Object.values(r).some(e=>"object"==typeof e&&null!==e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let s=t[0];return this._createRegisteredTool(e,void 0,r,i,a,n,{taskSupport:"forbidden"},void 0,s)}registerTool(e,t,r){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:i,description:a,inputSchema:n,outputSchema:s,annotations:o,_meta:l}=t;return this._createRegisteredTool(e,i,a,n,s,o,{taskSupport:"forbidden"},l,r)}prompt(e,...t){let r,i;if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);"string"==typeof t[0]&&(r=t.shift()),t.length>1&&(i=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:n}=t,s=this._createRegisteredPrompt(e,i,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return void 0!==this.server.transport}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}}let ir={type:"object",properties:{}};function ii(e){return null!==e&&"object"==typeof e&&"parse"in e&&"function"==typeof e.parse&&"safeParse"in e&&"function"==typeof e.safeParse}function ia(e){return"_def"in e||"_zod"in e||ii(e)}function is(e){return!("object"!=typeof e||null===e||ia(e))&&(0===Object.keys(e).length||Object.values(e).some(ii))}function io(e){if(e){if(is(e))return(0,y.objectFromShape)(e);if(!ia(e))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function il(e){let t=(0,y.getObjectShape)(e),r=t?.method;if(!r)throw Error("Schema is missing a method literal");let i=(0,y.getLiteralValue)(r);if("string"==typeof i)return i;throw Error("Schema method literal must be a string")}function ic(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let iu={completion:{values:[],hasMore:!1}};e.s(["createBuiltInMcpServer",0,function(e){let t=new it({name:"ai-development-environment",version:"0.1.0"}),r=t.registerTool.bind(t);for(let t of e.definitions())r(t.name,{title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations},async r=>e.callByName(t.name,r));return t}],700909),e.s([],719961);var id=e.i(504173),ip=e.i(750227),ih=e.i(320058),im=e.i(661983);function ig(e,t){let r=[],i=e.includes("CLAUDE");return i&&r.push("CLAUDE"),(e.includes("CODEX")||!i&&e.length>0||"GLOBAL"===t&&e.includes("GITHUB_COPILOT"))&&r.push("AGENTS"),r}let iy="default",iv=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],ib=["SCAN","READ"],iw=[...ib,"APPLY"],ix={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},ik={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function iS(e,t){if(!e)return t;try{return JSON.parse(e)}catch{return t}}function iI(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function iA(e,t){return"AGENTS"===t?[".agents","skills"]:"CLAUDE"===t?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".copilot","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===t?[".cursor","skills"]:"GITHUB_COPILOT"===t?[".github","skills"]:"CODEX_LEGACY"===t?[".codex","skills"]:[".opencode","skills"]}function i_(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?ip.win32:ip.posix}function iE(e,...t){return i_(e).join(e,...t)}function iC(e){return i_(e).dirname(e)}class iT{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(ih.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(ih.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(ih.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){im.agentEventBus.publish(im.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&im.agentEventBus.publish((0,im.skillSyncRunTopic)(e),{id:e})}subscribe(){return im.agentEventBus.iterate(im.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return im.agentEventBus.iterate((0,im.skillSyncRunTopic)(e))}async settings(){return(await (0,tY.getPrismaClient)()).skillSettings.upsert({where:{id:iy},create:{id:iy},update:{}})}async overview(e=""){let t=await (0,tY.getPrismaClient)(),r=e.trim().toLocaleLowerCase(),[i,a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:ix,orderBy:{name:"asc"}}),t.skillGroup.findMany({include:ik,orderBy:{name:"asc"}}),t.skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]}),t.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]}),this.settings(),t.codebaseRepository.findMany({orderBy:{name:"asc"}})]);return{skills:r?i.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(r))):i,groups:a,observations:n,installations:r?s.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(r))):s,settings:o,repositories:l}}async getSkill(e){return(await (0,tY.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:ix})}async saveSkill(e){let t,r=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,ih.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,ih.hashSkillFiles)(t),files:t})),i=[...new Set(e.groupIds)].slice(0,100),a=await (0,tY.getPrismaClient)();if(await a.skillGroup.count({where:{id:{in:i}}})!==i.length)throw Error("One or more skill groups were not found");let n=await a.skill.findUnique({where:{name:r.name}});if(n&&n.id!==e.id)throw Error("Skill names must be unique");let s=e.id??(0,g.randomUUID)(),o=e.id?await a.skillGroupSkill.findMany({where:{skillId:s},select:{groupId:!0}}):[];return await a.$transaction(async t=>{await t.skill.upsert({where:{id:s},create:{id:s,name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash},update:{name:r.name,description:r.description,syncGlobally:e.syncGlobally,packageHash:r.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:s}}),await t.skillFile.createMany({data:r.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,g.randomUUID)(),skillId:s,path:e.path,contents:t,executable:e.executable,contentHash:(0,g.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:s}}),i.length&&await t.skillGroupSkill.createMany({data:i.map(e=>({groupId:e,skillId:s}))})}),this.publish(),await this.scheduleAutoSync([...i,...o.map(e=>e.groupId)]),await this.getSkill(s)}async deleteSkill(e){let t=await (0,tY.getPrismaClient)(),r=await t.skill.findUnique({where:{id:e},include:{groups:!0}});return!!r&&(await t.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(r.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),i=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,tY.getPrismaClient)(),[n,s,o]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:i}}}),a.skillGroup.findUnique({where:{name:t}})]);if(n!==r.length)throw Error("One or more skills were not found");if(s!==i.length)throw Error("One or more repositories were not found");if(o&&o.id!==e.id)throw Error("Group names must be unique");let l=e.id??(0,g.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:l},create:{id:l,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:l}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:l}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:l,skillId:e}))}),i.length&&await e.codebaseRepositorySkillGroup.createMany({data:i.map(e=>({groupId:l,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([l]),a.skillGroup.findUniqueOrThrow({where:{id:l},include:ik})}async validateGroupIds(e){let t=[...new Set(e)].slice(0,100),r=await (0,tY.getPrismaClient)();if(await r.skillGroup.count({where:{id:{in:t}}})!==t.length)throw Error("One or more skill groups were not found");return t}async groupsForRepository(e){let t=await (0,tY.getPrismaClient)();return(await t.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillGroup.deleteMany({where:{id:e}});return r.count&&this.publish(),r.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r.count>0}async saveSettings(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSettings.upsert({where:{id:iy},create:{id:iy,...e},update:e});return this.publish(),r.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),r}async setRepositoryGroups(e,t){let r=await this.validateGroupIds(t),i=await (0,tY.getPrismaClient)();await i.$transaction(async t=>{await t.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),r.length&&await t.codebaseRepositorySkillGroup.createMany({data:r.map(t=>({repositoryId:e,groupId:t}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let t of[...new Set(e)])await this.prepareSync("GROUP",t,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let t=await (0,tY.getPrismaClient)(),r=await t.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),i=new Map;for(let e of r)for(let t of(i.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))i.set(t.folder,{codebaseId:e.id,worktreeId:t.id,folder:t.folder});return[...i.values()]}async prepareSync(e,t,r=!1){let i=await (0,tY.getPrismaClient)();if(t&&!await i.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(r){let r=await i.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:iv}},orderBy:{createdAt:"desc"}});if(r)return r}let a=await i.skillSyncRun.create({data:{id:(0,g.randomUUID)(),kind:e,groupId:t??null,automatic:r,status:"PREPARING"}}),n=iI(await this.settings()),s=await i.agent.findMany({orderBy:{name:"asc"}});for(let e of s){let t=await i.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:a.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:ih.SKILL_SCAN_JOB_KIND,payload:{tools:n,targets:await this.targets(e.id),syncRunId:a.id,syncItemId:t.id},idempotencyKey:`skills:scan:${a.id}:${e.id}`,timeoutSeconds:300,visibility:r?"SYSTEM":"USER"})}return!s.length&&(await i.skillSyncRun.update({where:{id:a.id},data:{status:"READY"}}),r)?this.applyRun(a.id):(this.publish(a.id),this.getRun(a.id))}async getRun(e){return(await (0,tY.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return iS(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=iS(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),a=new Date;await i.$transaction(async i=>{for(let r of(await i.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))ih.AI_TOOLS.includes(r.tool)&&await i.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:r.tool}},create:{agentId:e.agentId,tool:r.tool,configured:r.configured,homePath:r.homePath,checkedAt:a},update:{configured:r.configured,homePath:r.homePath,checkedAt:a}});for(let r of t.installations){let t=await i.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:a}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await i.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,tY.getPrismaClient)(),t=new Set(iI(await this.settings())),r=await e.skillToolObservation.findMany({where:{configured:!0}}),i=new Map;for(let e of r){if(!t.has(e.tool))continue;let r=i.get(e.agentId)??[];r.push(e.tool),i.set(e.agentId,r)}return i}async desiredLocations(e,t=new Set){let r=await (0,tY.getPrismaClient)(),i=await this.configuredByAgent(),a=await r.skillToolObservation.findMany({where:{configured:!0}}),n=new Map;for(let e of a)n.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await r.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:ix});for(let[r,a]of i){if(t.has(r))continue;let i=n.get(r);if(i)for(let t of ig(a,"GLOBAL")){let a=iE(i,...iA("GLOBAL",t));for(let i of e)s.push({skill:i,agentId:r,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:t,folder:null,rootPath:a,targetPath:iE(a,i.name)})}}}for(let a of(await r.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:ix}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of a.repositories)for(let r of e.repository.codebases){if(t.has(r.agentId))continue;let e=ig(i.get(r.agentId)??[],"PROJECT");for(let t of[{folder:r.folder,worktreeId:null},...r.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let i of e){let e=iE(t.folder,...iA("PROJECT",i));for(let n of a.skills)s.push({skill:n.skill,agentId:r.agentId,codebaseId:r.id,worktreeId:t.worktreeId,scope:"PROJECT",rootKind:i,folder:t.folder,rootPath:e,targetPath:iE(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,t){return{present:!0,...t.size?{agentId:{notIn:[...t]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[a,n,s,o,l]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:ix}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(r,i),include:{baseline:!0}}),this.desiredLocations(r,i),"GROUP"===r.kind&&r.groupId?this.desiredLocations({...r,groupId:null},i):this.desiredLocations(r,i)]),c=new Map(a.map(e=>[e.name,e])),u=new Map(a.map(e=>[e.id,e])),d=new Map(n.map(e=>[e.name,e])),p=new Map(n.map(e=>[e.id,e])),h=new Map;for(let e of s){let t=h.get(e.skillName)??[];t.push(e.packageHash),h.set(e.skillName,t)}let m=new Set([...h].flatMap(([e,t])=>{var r;return(r=c.get(e)?.packageHash??null,new Set(t.filter(e=>null===r||e!==r)).size>1)?[e]:[]})),f=[];for(let t of o)s.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||f.push({id:(0,g.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of s){let i=r.baseline?.skillId??r.skillId,a=(i?u.get(i):void 0)??c.get(r.skillName),n=(i?p.get(i):void 0)??d.get(r.skillName),s=!!r.baseline&&!!a&&a.name!==r.skillName,h=o.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),v=l.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);a&&r.packageHash===a.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,g.randomUUID)(),installationId:r.id,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}});let b="UNCHANGED",w="COMPLETE";if(n&&r.baseline&&!r.tracked)b="DELETE_MANAGED",w="READY";else if(s)b=r.tracked?"CONFLICT":"DELETE_MANAGED",w=r.tracked?"BLOCKED":"READY";else if(v||!r.baseline||r.tracked)if(a)if(r.packageHash!==a.packageHash){var y;w="CONFLICT"===(b=m.has(r.skillName)?"CONFLICT":(y={databaseHash:a.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===y.targetHash?"UNCHANGED":y.tracked?"CONFLICT":y.baselineHash===y.databaseHash?"IMPORT":y.baselineHash===y.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!v&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&l.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(b="DELETE_REDUNDANT",w="READY");else w="CONFLICT"==(b=m.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else b="DELETE_MANAGED",w="READY";f.push({id:(0,g.randomUUID)(),runId:e,skillId:a?.id??n?.id??null,installationId:r.id,agentId:r.agentId,direction:b,status:w,sourceHash:a?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?h?.folder??null:null,skillName:r.skillName},projectGroupRequired:!a&&"PROJECT"===r.scope})})}f.length&&await t.skillSyncItem.createMany({data:f});let v=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),b=new Map;for(let e of v){if(!e.agentId||!e.installation)continue;let t=b.get(e.agentId)??[];t.push(e),b.set(e.agentId,t)}let w=iI(await this.settings());for(let[r,i]of b){let a=await t.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:e,agentId:r,direction:"READ",status:"PENDING"}}),n=await this.targets(r);await this.agentControl.createJob({agentId:r,kind:ih.SKILL_READ_JOB_KIND,payload:{tools:w,targets:n,requests:i.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?n.find(t=>t.codebaseId===e.installation.codebaseId&&t.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${r}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)();if(await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let a=iS(e.resultJson,{packages:[]}),n=await i.skillSyncItem.findMany({where:{runId:t,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of a.packages){let t=n.find(t=>t.installation?.skillName===e.package.name&&t.installation?.rootKind===e.rootKind&&t.installation?.scope===e.scope&&("GLOBAL"===e.scope||t.installation?.rootPath===iE(e.folder,...iA("PROJECT",e.rootKind))));if(!t)continue;let r=iS(t.candidatePackageJson,{});await i.skillSyncItem.update({where:{id:t.id},data:{candidatePackageJson:JSON.stringify({...r,package:e.package})}})}await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"COMPLETE"}})}else await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(t),this.publish(t)}}async refreshRunStatus(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncItem.findMany({where:{runId:e}});if(r.some(e=>ib.includes(e.direction)&&"PENDING"===e.status))return;let i=r.some(e=>"BLOCKED"===e.status),a=r.some(e=>"FAILED"===e.status),n=i?"NEEDS_RESOLUTION":a?"PARTIAL":"READY",s=await t.skillSyncRun.update({where:{id:e},data:{status:n}});this.publish(e),s.automatic&&"READY"===n&&await this.applyRun(e)}async skipPending(e){let t=await (0,tY.getPrismaClient)();await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});let r=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:iw},status:"PENDING",agentId:{not:null}}}),i=[];for(let a of r){if(1!==(await t.skillSyncItem.updateMany({where:{id:a.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!a.agentId)continue;i.push(a);let r=await t.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:a.agentId,idempotencyKey:`skills:${a.direction.toLowerCase()}:${e}:${a.agentId}`}}});r&&await this.agentControl.cancelJob(r.id)}if(!i.length)return this.getRun(e);let a=[...new Set(i.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];a.length&&await t.skillSyncItem.updateMany({where:{runId:e,agentId:{in:a},direction:{notIn:iw},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let n=i.filter(e=>"APPLY"===e.direction),s=n.flatMap(e=>{let{deployments:t=[]}=iS(e.candidatePackageJson,{});return t.map(e=>e.id)});return s.length&&await t.skillDeployment.updateMany({where:{id:{in:s},status:"PENDING"},data:{status:"SKIPPED"}}),i.some(e=>"SCAN"===e.direction)?await t.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):a.length&&await this.refreshRunStatus(e),n.length&&(await t.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await t.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(r.status))throw Error("Sync item cannot be resolved");let i=iS(r.candidatePackageJson,{});if("MANUAL"===e.resolution&&(i.package=(0,ih.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!i.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!r.installationId)throw Error("The client skill installation is unavailable");if(i.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await t.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");i.groupId=e.groupId}if(await t.skillSyncItem.update({where:{id:r.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":r.direction,candidatePackageJson:JSON.stringify(i),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=i.package?.name??null;if(e){let i=(await t.skillSyncItem.findMany({where:{runId:r.runId,id:{not:r.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(t=>(t.skill?.name??t.installation?.skillName)===e?[t.id]:[]);i.length&&await t.skillSyncItem.updateMany({where:{id:{in:i}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(r.runId),this.getRun(r.runId)}async importCandidates(e){let t=await (0,tY.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=iS(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:ix}),a=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:a.id}}),r.targetHash===a.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,g.randomUUID)(),installationId:r.installationId,skillId:a.id,packageHash:a.packageHash},update:{skillId:a.id,packageHash:a.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,tY.getPrismaClient)(),r=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let i=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:ib},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),a=await this.desiredLocations(r,i),n=await t.skillInstallation.findMany({where:this.installationWhere(r,i)}),s=new Map,o=new Map,l=(e,t)=>{let r=s.get(e)??[];r.push(t),s.set(e,r)},c=(e,t)=>{let r=o.get(e)??[];r.push(t),o.set(e,r)};for(let e of a){let r=n.find(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;l(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let t=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:t}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,g.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});c(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let u=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),d=new Set(u.flatMap(e=>e.installationId?[e.installationId]:[])),p=n.filter(e=>!d.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!a.some(t=>t.agentId===e.agentId&&t.rootPath===e.rootPath&&t.skill.name===e.skillName)&&a.some(t=>t.agentId===e.agentId&&t.scope===e.scope&&("GLOBAL"===e.scope||t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)&&t.skill.name===e.skillName&&t.skill.packageHash===e.packageHash));for(let e of[...u.flatMap(e=>e.installation?[e.installation]:[]),...p]){if(!e||e.tracked)continue;let t=await this.targets(e.agentId),r="PROJECT"===e.scope?t.find(t=>t.codebaseId===e.codebaseId&&t.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||r)&&l(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:r,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[r,i]of s){let a=await t.skillSyncItem.create({data:{id:(0,g.randomUUID)(),runId:e,agentId:r,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:o.get(r)??[]})}});await this.agentControl.createJob({agentId:r,kind:ih.SKILL_APPLY_JOB_KIND,payload:{operations:i,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${r}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:s.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let i=await (0,tY.getPrismaClient)(),a=await i.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let n="SUCCEEDED"===e.status,{deployments:s=[]}=iS(a?.candidatePackageJson??null,{});await i.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:n?"COMPLETE":"FAILED",error:n?null:e.error??"Skill apply failed"}});let o=await i.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),l=iS(e.resultJson,{});if(n){let t=await this.configuredByAgent();for(let e of o){let r=s.find(t=>t.id===e.id),a=l.results?.find(t=>"WRITE"===t.kind&&t.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||a?.packageHash!==r.desiredHash)continue;let n=await i.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:iC(e.targetPath),skillName:e.skill.name}},create:{id:(0,g.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:iC(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,t)=>e+t.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await i.skillSyncBaseline.upsert({where:{installationId:n.id},create:{id:(0,g.randomUUID)(),installationId:n.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await i.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let t of l.results??[])if("DELETE"===t.kind){var c;await i.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:iC(t.path),skillName:i_(c=t.path).basename(c)},data:{present:!1,lastSeenAt:new Date}})}}else for(let t of s)await i.skillDeployment.updateMany({where:{id:t.id,agentId:e.agentId,desiredHash:t.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await i.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await i.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}e.i(464841);var iD=e.i(220629),i$=e.i(692680);e.i(493015);var iR=e.i(49172);function iN(e){if(!e)return{};let t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}function iP(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.valueOf())?null:t}function iO(e){try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}class ij{agentControl;fetcher;credentials;constructor(e,t=fetch,r=new tQ.CredentialService){for(const i of(this.agentControl=e,this.fetcher=t,this.credentials=r,this.agentControl.registerCompletionHandler(i$.SIGNING_ASSETS_SCAN_JOB_KIND,e=>this.completeScan(e)),[i$.SIGNING_PROFILE_READ_JOB_KIND,i$.SIGNING_PROFILE_INSTALL_JOB_KIND,i$.SIGNING_PROFILE_DELETE_JOB_KIND,i$.SIGNING_IDENTITY_IMPORT_JOB_KIND,i$.SIGNING_IDENTITY_DELETE_JOB_KIND]))this.agentControl.registerCompletionHandler(i,e=>this.completeOperation(e))}changed(){im.agentEventBus.publish(im.SIGNING_ASSETS_CHANGED_TOPIC,{changed:!0})}deleteTransferJobSoon(e){setTimeout(()=>{(0,tY.getPrismaClient)().then(t=>t.agentJob.deleteMany({where:{id:e,visibility:"SYSTEM"}}))},3e4).unref()}subscribe(){return im.agentEventBus.iterate(im.SIGNING_ASSETS_CHANGED_TOPIC)}async completeScan(e){if("SUCCEEDED"!==e.status)return;let t=(0,i$.parseSigningAssetsScanResult)(iN(e.resultJson)),r=await (0,tY.getPrismaClient)(),i=new Date;await r.$transaction(async r=>{for(let a of(await r.signingProfileAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),await r.signingCertificateAsset.updateMany({where:{agentId:e.agentId,missingAt:null},data:{missingAt:i}}),t.profiles))await r.signingProfileAsset.upsert({where:{agentId_uuid:{agentId:e.agentId,uuid:a.uuid}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,uuid:a.uuid,contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:iP(a.createdAt),expiresAt:iP(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i},update:{contentHash:a.contentHash,name:a.name,profileType:a.profileType,bundleId:a.bundleId,teamId:a.teamId,teamName:a.teamName,platformsJson:JSON.stringify(a.platforms),deviceCount:a.deviceCount,deviceUdidsJson:JSON.stringify(a.deviceUdids),certificateSha1sJson:JSON.stringify(a.certificateSha1s),createdAt:iP(a.createdAt),expiresAt:iP(a.expiresAt),expired:a.expired,xcodeManaged:a.xcodeManaged,observedAt:i,missingAt:null}});for(let a of t.certificates)await r.signingCertificateAsset.upsert({where:{agentId_sha1:{agentId:e.agentId,sha1:a.sha1}},create:{id:(0,g.randomUUID)(),agentId:e.agentId,sha1:a.sha1,sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:iP(a.notBefore),expiresAt:iP(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i},update:{sha256:a.sha256,name:a.name,teamId:a.teamId,certificateType:a.certificateType,notBefore:iP(a.notBefore),expiresAt:iP(a.expiresAt),expired:a.expired,hasPrivateKey:a.hasPrivateKey,observedAt:i,missingAt:null}})}),this.deleteTransferJobSoon(e.id),this.changed()}async refreshAfterMutation(e,t){await this.agentControl.createJob({agentId:e,kind:i$.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:${t}:${e}:refresh`,timeoutSeconds:60,visibility:"SYSTEM"})}async finishOperation(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingOperationItem.findMany({where:{operationId:e}});if(r.some(e=>["WAITING","QUEUED","RUNNING"].includes(e.status)))return;let i=r.filter(e=>"SUCCEEDED"!==e.status);await t.signingOperation.update({where:{id:e},data:{status:i.length?"FAILED":"SUCCEEDED",error:i.map(e=>e.error).filter(Boolean).join("; ")||null,finishedAt:new Date}}),this.changed()}async completeOperation(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingOperationItem.findUnique({where:{jobId:e.id},include:{operation:!0}});if(r){if(await t.signingOperationItem.update({where:{id:r.id},data:{status:e.status,error:e.error,finishedAt:new Date}}),e.kind===i$.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"===e.status&&"SYNC_PROFILE"===r.operation.kind){let i=iN(e.resultJson).contentBase64;if("string"==typeof i&&i)for(let e of(await t.signingOperationItem.findMany({where:{operationId:r.operationId,status:"WAITING"}}))){let a=await this.agentControl.createJob({agentId:e.agentId,kind:i$.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:i},idempotencyKey:`signing:${r.operationId}:${e.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await t.signingOperationItem.update({where:{id:e.id},data:{jobId:a.id,status:a.status}})}else await t.signingOperation.update({where:{id:r.operationId},data:{status:"FAILED",error:"Profile read returned no content"}})}e.kind===i$.SIGNING_PROFILE_READ_JOB_KIND&&"SUCCEEDED"!==e.status&&"SYNC_PROFILE"===r.operation.kind&&await t.signingOperationItem.updateMany({where:{operationId:r.operationId,status:"WAITING"},data:{status:"FAILED",error:"Source profile could not be read",finishedAt:new Date}}),"SUCCEEDED"===e.status&&e.kind!==i$.SIGNING_PROFILE_READ_JOB_KIND&&await this.refreshAfterMutation(e.agentId,r.operationId),await this.finishOperation(r.operationId),this.deleteTransferJobSoon(e.id)}}async refresh(e){let t=await (0,tY.getPrismaClient)(),r=await t.agent.findMany({where:e?.length?{id:{in:[...new Set(e)]}}:void 0,orderBy:{name:"asc"}}),i=[];for(let e of r)iO(e.capabilitiesJson).includes(i$.SIGNING_ASSETS_SCAN_JOB_KIND)&&i.push(await this.agentControl.createJob({agentId:e.id,kind:i$.SIGNING_ASSETS_SCAN_JOB_KIND,payload:{},idempotencyKey:`signing:scan:${Date.now()}:${e.id}`,timeoutSeconds:60,visibility:"SYSTEM"}));return i}async agents(){let e=await (0,tY.getPrismaClient)();return(await e.agent.findMany({orderBy:{name:"asc"}})).map(e=>({id:e.id,name:e.name,hostname:e.hostname,supported:iO(e.capabilitiesJson).includes(i$.SIGNING_ASSETS_SCAN_JOB_KIND),lastSeenAt:e.lastSeenAt?.toISOString()??null}))}async profiles(){let e=await (0,tY.getPrismaClient)(),t=await e.signingProfileAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t){let t=`${e.uuid}:${e.contentHash}`;r.set(t,[...r.get(t)??[],e])}return[...r.values()].map(e=>{let t=e[0];return{id:`${t.uuid}:${t.contentHash}`,uuid:t.uuid,contentHash:t.contentHash,name:t.name,profileType:t.profileType,bundleId:t.bundleId,teamId:t.teamId,teamName:t.teamName,platforms:iO(t.platformsJson),deviceCount:t.deviceCount,deviceUdids:iO(t.deviceUdidsJson),certificateSha1s:iO(t.certificateSha1sJson),createdAt:t.createdAt?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,xcodeManaged:t.xcodeManaged,installedAgents:e.map(({agent:e})=>e)}})}async profile(e){return(await this.profiles()).find(t=>t.id===e)??null}async profileDevices(e){let t=new Set,r=e.filter(e=>{let r=e.toUpperCase();return!t.has(r)&&(t.add(r),!0)}),i=r.map(e=>e.toUpperCase());if(!i.length)return[];let a=await (0,tY.getPrismaClient)(),n=new Map((await a.iosDevice.findMany({where:{udid:{in:i}},select:{id:!0,udid:!0,displayName:!0,product:!0,osVersion:!0,status:!0}})).map(e=>[e.udid.toUpperCase(),e]));return r.map(e=>{let t=n.get(e.toUpperCase());return{udid:e,deviceId:t?.id??null,displayName:t?.displayName??null,product:t?.product??null,osVersion:t?.osVersion??null,status:t?.status??null}})}async certificates(){let e=await (0,tY.getPrismaClient)(),t=await e.signingCertificateAsset.findMany({where:{missingAt:null},include:{agent:{select:{id:!0,name:!0}}},orderBy:[{expiresAt:"asc"},{name:"asc"}]}),r=new Map;for(let e of t)r.set(e.sha1,[...r.get(e.sha1)??[],e]);return[...r.values()].map(e=>{let t=e[0];return{id:t.sha1,sha1:t.sha1,sha256:t.sha256,name:t.name,teamId:t.teamId,certificateType:t.certificateType,notBefore:t.notBefore?.toISOString()??null,expiresAt:t.expiresAt?.toISOString()??null,expired:t.expired,hasPrivateKey:e.some(e=>e.hasPrivateKey),installedAgents:e.map(({agent:e})=>e),privateKeyAgents:e.filter(e=>e.hasPrivateKey).map(({agent:e})=>e)}})}async operations(e=50){return(await (0,tY.getPrismaClient)()).signingOperation.findMany({include:{items:{include:{agent:{select:{id:!0,name:!0}}},orderBy:{createdAt:"asc"}}},orderBy:{createdAt:"desc"},take:Math.max(1,Math.min(e,200))})}async operation(e,t,r,i=null,a=[]){let n=await (0,tY.getPrismaClient)(),s=(0,g.randomUUID)();return n.signingOperation.create({data:{id:s,kind:e,assetKey:t,sourceAgentId:i,items:{create:[...new Set(r)].map(e=>({id:(0,g.randomUUID)(),agentId:e,status:a.includes(e)?"WAITING":"QUEUED"}))}},include:{items:{include:{agent:{select:{id:!0,name:!0}}}}}})}async attachJob(e,t){let r=await (0,tY.getPrismaClient)();await r.signingOperationItem.update({where:{id:e},data:{jobId:t.id,status:t.status}})}async uploadProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=(0,g.createHash)("sha256").update(Buffer.from(e,"base64")).digest("hex").toUpperCase(),i=await this.operation("INSTALL_PROFILE",r,t);for(let t of i.items){let r=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_PROFILE_INSTALL_JOB_KIND,payload:{contentBase64:e},idempotencyKey:`signing:${i.id}:${t.agentId}:install`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,r)}return this.changed(),i}async downloadProfile(e,t){let r=(0,g.randomUUID)(),i=await this.agentControl.createJob({agentId:t,kind:i$.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:download:${r}:${e}`,timeoutSeconds:60,visibility:"SYSTEM"}),a=await (0,tY.getPrismaClient)();try{let t=Date.now()+55e3;for(;Date.now()<t;){let t=await this.agentControl.getJob(i.id);if(!t)throw Error("Profile download job was removed");if(["FAILED","CANCELLED","TIMED_OUT"].includes(t.status))throw Error(t.error||"Could not read provisioning profile");if("SUCCEEDED"===t.status){let r=iN(t.resultJson);if("string"!=typeof r.contentBase64)throw Error("Agent returned no provisioning profile content");return{uuid:e,filename:`${e}.mobileprovision`,contentBase64:r.contentBase64}}await new Promise(e=>setTimeout(e,250))}throw Error("Timed out reading provisioning profile")}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async syncProfile(e,t,r){let i=[...new Set(r)].filter(e=>e!==t);if(!i.length)throw Error("Select at least one target agent");let a=await this.operation("SYNC_PROFILE",e,[t,...i],t,i),n=a.items.find(e=>e.agentId===t),s=await this.agentControl.createJob({agentId:t,kind:i$.SIGNING_PROFILE_READ_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${a.id}:${t}:read`,timeoutSeconds:60,visibility:"SYSTEM"});return await this.attachJob(n.id,s),this.changed(),a}async deleteProfile(e,t){if(!t.length)throw Error("Select at least one agent");let r=await this.operation("DELETE_PROFILE",e,t);for(let t of r.items){let i=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_PROFILE_DELETE_JOB_KIND,payload:{uuid:e},idempotencyKey:`signing:${r.id}:${t.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(t.id,i)}return this.changed(),r}async deleteExpiredProfiles(e){let t=await (0,tY.getPrismaClient)(),r=await t.signingProfileAsset.findMany({where:{expired:!0,missingAt:null,...e?.length?{agentId:{in:e}}:{}}}),i=new Map;for(let e of r)i.set(e.uuid,[...i.get(e.uuid)??[],e.agentId]);let a=[];for(let[e,t]of i)a.push(await this.deleteProfile(e,t));return a}async importIdentity(e){if(!e.targetAgentIds.length)throw Error("Select at least one agent");let t=Buffer.from(e.p12Base64,"base64");if(!t.length||t.length>0x1400000)throw Error("The .p12 file is empty or larger than 20 MiB");let r=[...new Set(e.targetAgentIds)],i=await (0,tY.getPrismaClient)(),n=new Map((await i.agent.findMany({where:{id:{in:r}},select:{id:!0,name:!0,capabilitiesJson:!0,lastSeenAt:!0,disconnectedAt:!0,heartbeatIntervalSeconds:!0}})).map(e=>[e.id,e])),s=Date.now(),o=r.filter(e=>{let t=n.get(e);return!t||!function(e,t=Date.now()){return null!==e.lastSeenAt&&t-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}(t,s)||!iO(t.capabilitiesJson).includes(i$.SIGNING_IDENTITY_IMPORT_JOB_KIND)});if(o.length)throw Error(`Identity imports require online supported agents: ${o.map(e=>n.get(e)?.name??e).join(", ")}`);let l=(0,g.createHash)("sha256").update(t).digest("hex").toUpperCase(),c=await this.operation("IMPORT_IDENTITY",l,r);for(let t of c.items){let r=this.agentControl.createSigningSecretTransfer(t.agentId,{p12Base64:e.p12Base64,passphrase:e.passphrase});try{let e=await this.agentControl.createJob({agentId:t.agentId,kind:i$.SIGNING_IDENTITY_IMPORT_JOB_KIND,payload:{transferId:r,sha256:l},idempotencyKey:`signing:${c.id}:${t.agentId}:import`,timeoutSeconds:120,visibility:"SYSTEM"});await this.attachJob(t.id,e)}catch(e){throw this.agentControl.revokeSigningSecretTransfer(r),e}}return this.changed(),c}async deleteIdentity(e,t){if(!t.length)throw Error("Select at least one agent");let r=e.toUpperCase(),i=[...new Set(t)],a=await (0,tY.getPrismaClient)(),n=new Set((await a.signingCertificateAsset.findMany({where:{sha1:r,agentId:{in:i},hasPrivateKey:!0,missingAt:null},select:{agentId:!0}})).map(e=>e.agentId)),s=i.filter(e=>n.has(e));if(!s.length)throw Error("The identity has no private key on the selected agents");let o=await this.operation("DELETE_IDENTITY",r,s);for(let e of o.items){let t=await this.agentControl.createJob({agentId:e.agentId,kind:i$.SIGNING_IDENTITY_DELETE_JOB_KIND,payload:{sha1:r},idempotencyKey:`signing:${o.id}:${e.agentId}:delete`,timeoutSeconds:60,visibility:"SYSTEM"});await this.attachJob(e.id,t)}return this.changed(),o}async appleClient(){return new iR.AppleDeveloperClient(await (0,iR.storedAppleDeveloperCredentials)(this.credentials),this.fetcher)}async portalInventory(){let e=await this.appleClient(),[t,r,i,a]=await Promise.all([e.listProfiles(),e.listCertificates(),e.listBundleIds(),e.listDevices()]);return{profiles:t,certificates:r,bundleIds:i,devices:a}}async createPortalProfile(e){let t=await (await this.appleClient()).createProfile(e);return this.changed(),t.data}async deletePortalProfile(e){return await (await this.appleClient()).deleteProfile(e),this.changed(),!0}async revokePortalCertificate(e){return await (await this.appleClient()).revokeCertificate(e),this.changed(),!0}}var iB=e.i(308810),iU=e.i(726355);let iq={IOS_BUILD_SUCCEEDED:{key:"IOS_BUILD_SUCCEEDED",category:"BUILDS",label:"iOS build succeeded",description:"An iOS build finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},IOS_BUILD_FAILED:{key:"IOS_BUILD_FAILED",category:"BUILDS",label:"iOS build failed",description:"An iOS build finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},GITHUB_ACTIONS_SUCCEEDED:{key:"GITHUB_ACTIONS_SUCCEEDED",category:"GITHUB",label:"GitHub Actions succeeded",description:"A GitHub Actions workflow finishes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},GITHUB_ACTIONS_FAILED:{key:"GITHUB_ACTIONS_FAILED",category:"GITHUB",label:"GitHub Actions failed",description:"A GitHub Actions workflow finishes with a failure.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_NEEDS_ANSWER:{key:"RUN_NEEDS_ANSWER",category:"RUNS",label:"Plan or session needs an answer",description:"A managed plan or session asks for user input.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_COMPLETED:{key:"RUN_COMPLETED",category:"RUNS",label:"Plan or session completed",description:"A managed plan or session completes successfully.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_FAILED:{key:"RUN_FAILED",category:"RUNS",label:"Plan or session failed",description:"A managed plan or session fails.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1},RUN_CANCELLED:{key:"RUN_CANCELLED",category:"RUNS",label:"Plan or session cancelled",description:"A managed plan or session is cancelled.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!1,defaultWebPushEnabled:!1},RUN_RECOVERY_PAUSED:{key:"RUN_RECOVERY_PAUSED",category:"RUNS",label:"Plan or session paused after recovery",description:"A managed plan or session is paused after its agent restarts.",defaultSidebarEnabled:!0,defaultBrowserEnabled:!0,defaultWebPushEnabled:!1}};function iL(e){return e in iq?iq[e]:null}let iM="default";function iF(e,t,r){let i=e.trim();if(!i)throw Error(`${t} is required`);if(i.length>r)throw Error(`${t} is too long`);return i}function iV(e){let t,r=iF(e,"Push endpoint",4e3);try{t=new URL(r)}catch{throw Error("Push endpoint must be a valid URL")}if("https:"!==t.protocol)throw Error("Push endpoint must use HTTPS");return r}function iK(e,t){let r=new Date(e);if(!Number.isFinite(r.getTime()))throw Error(`${t} is invalid`);return r}function iH(){let e=process.env.PUBLIC_BASE_URL?.trim();if(e)try{let t=new URL(e);if("https:"===t.protocol)return t.origin}catch{}return"mailto:notifications@ai-development-environment.local"}function iz(e){if(!e||"object"!=typeof e)return null;let t=e.statusCode;return"number"==typeof t?t:null}class iG{credentialService;vapidPreparation;constructor(e){this.credentialService=e,this.vapidPreparation=null}publish(e){im.agentEventBus.publish(im.APP_NOTIFICATIONS_CHANGED_TOPIC,{notificationsChanged:e})}subscribe(){return im.agentEventBus.iterate(im.APP_NOTIFICATIONS_CHANGED_TOPIC)}async preferences(){let e=await (0,tY.getPrismaClient)(),t=new Map((await e.notificationPreference.findMany()).map(e=>[e.typeKey,e]));return Object.values(iq).map(e=>{let r=t.get(e.key);return{...e,sidebarEnabled:r?.sidebarEnabled??e.defaultSidebarEnabled,browserEnabled:r?.browserEnabled??e.defaultBrowserEnabled,webPushEnabled:r?.webPushEnabled??e.defaultWebPushEnabled,updatedAt:r?.updatedAt??null}})}async savePreference(e){let t=iL(e.typeKey);if(!t)throw Error("Unknown notification type");let r=await (0,tY.getPrismaClient)(),i=await r.notificationPreference.upsert({where:{typeKey:t.key},create:{typeKey:t.key,sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled},update:{sidebarEnabled:e.sidebarEnabled,browserEnabled:e.browserEnabled,webPushEnabled:e.webPushEnabled}});return this.publish({kind:"PREFERENCES_UPDATED",notification:null,notificationId:null}),{...t,...i}}async recordInTransaction(e,t){let r=iL(t.typeKey);if(!r)throw Error("Unknown notification type");let i=await e.notificationPreference.findUnique({where:{typeKey:r.key}}),a=i?.sidebarEnabled??r.defaultSidebarEnabled,n=i?.browserEnabled??r.defaultBrowserEnabled,s=i?.webPushEnabled??r.defaultWebPushEnabled;if(!a&&!n&&!s)return null;let o=iF(t.dedupeKey,"Deduplication key",500);return await e.appNotification.findUnique({where:{dedupeKey:o}})?null:e.appNotification.create({data:{id:(0,g.randomUUID)(),dedupeKey:o,typeKey:r.key,title:iF(t.title,"Notification title",240),body:iF(t.body,"Notification body",1e3),href:function(e){let t=iF(e,"Notification link",2e3);if(!t.startsWith("/")||t.startsWith("//"))throw Error("Notification links must be same-origin paths");return t}(t.href),resourceKind:iF(t.resourceKind,"Resource kind",100),resourceId:iF(t.resourceId,"Resource ID",500),worktreeId:t.worktreeId??null,highlightColor:t.highlightColor?.trim()||null,sidebarRequested:a,browserRequested:n,webPushRequested:s}})}created(e){e&&(this.publish({kind:"CREATED",notification:e,notificationId:e.id}),e.webPushRequested&&this.deliverWebPush(e).catch(e=>{console.error("Web Push delivery failed:",e)}))}async history(e={}){let t=Math.max(1,Math.min(e.first??100,200)),r=await (0,tY.getPrismaClient)(),[i,a]=await Promise.all([r.appNotification.findMany({orderBy:[{createdAt:"desc"},{id:"desc"}],take:t+1,...e.after?{cursor:{id:e.after},skip:1}:void 0}),r.appNotification.count()]);return{items:i.slice(0,t),nextCursor:i.length>t?i[t-1].id:null,totalCount:a}}async sidebar(e=50){return(await (0,tY.getPrismaClient)()).appNotification.findMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},orderBy:[{createdAt:"desc"},{id:"desc"}],take:Math.max(1,Math.min(e,100))})}async dismiss(e){let t=await (0,tY.getPrismaClient)(),r=await t.appNotification.updateMany({where:{id:e,sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return r.count&&this.publish({kind:"DISMISSED",notification:null,notificationId:e}),r.count>0}async dismissAll(){let e=await (0,tY.getPrismaClient)(),t=await e.appNotification.updateMany({where:{sidebarRequested:!0,sidebarDismissedAt:null},data:{sidebarDismissedAt:new Date}});return t.count&&this.publish({kind:"SIDEBAR_CLEARED",notification:null,notificationId:null}),t.count}selectionWhere(e){let t=e.excludedRanges??[],r=e.all&&0===t.length?[]:[...new Set(e.ids??[])],i=[...new Set(e.excludedIds??[])],a=e.ranges??[];if(r.length>5e3||i.length>5e3)throw Error("Notification selection is too large");if(a.length>366||t.length>366)throw Error("Notification date selection is too large");let n=t.map(e=>{let t=iK(e.start,"Excluded selection start"),r=iK(e.end,"Excluded selection end");if(t>=r)throw Error("Excluded selection range is invalid");return{createdAt:{gte:t,lt:r}}}),s={NOT:{OR:n}},o=[];if(r.length&&o.push({id:{in:r}}),e.all)o.push(n.length?s:{});else if(a.length){let e=a.map(e=>{let t=iK(e.start,"Selection start"),r=iK(e.end,"Selection end");if(t>=r)throw Error("Selection range is invalid");return{createdAt:{gte:t,lt:r}}});o.push({AND:[{OR:e},...n.length?[s]:[]]})}if(!o.length)return{id:{in:[]}};let l=1===o.length?o[0]:{OR:o};return i.length?{AND:[l,{id:{notIn:i}}]}:l}async deleteSelection(e){let t=await (0,tY.getPrismaClient)(),r=await t.appNotification.deleteMany({where:this.selectionWhere(e)});return r.count&&this.publish({kind:"DELETED",notification:null,notificationId:null}),r.count}async deleteAll(){let e=await (0,tY.getPrismaClient)(),t=await e.appNotification.deleteMany();return t.count&&this.publish({kind:"HISTORY_CLEARED",notification:null,notificationId:null}),t.count}async webPushState(){let e=await (0,tY.getPrismaClient)(),[t,r]=await Promise.all([e.webPushSettings.findUnique({where:{id:iM}}),e.webPushSubscription.count()]),i=await this.credentialService.isConfigured(tX.CREDENTIALS.webPushVapidPrivateKey);return{configured:!!(t?.vapidPublicKey&&i),publicKey:t?.vapidPublicKey??null,subscriptionCount:r}}async webPushSubscriptions(){return(await (0,tY.getPrismaClient)()).webPushSubscription.findMany({orderBy:[{lastSeenAt:"desc"},{createdAt:"desc"}],select:{id:!0,endpoint:!0,expirationTime:!0,locale:!0,userAgent:!0,lastSeenAt:!0,createdAt:!0,updatedAt:!0}})}async prepareWebPush(){return this.vapidPreparation||(this.vapidPreparation=this.prepareWebPushOnce().finally(()=>{this.vapidPreparation=null})),this.vapidPreparation}async prepareWebPushOnce(){let e=await (0,tY.getPrismaClient)(),t=await e.webPushSettings.findUnique({where:{id:iM}});if(t?.vapidPublicKey){if(!await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey))throw Error("The Web Push private key is unavailable");return{publicKey:t.vapidPublicKey}}let r=iU.default.generateVAPIDKeys();return await this.credentialService.setText(tX.CREDENTIALS.webPushVapidPrivateKey,r.privateKey,e=>e.webPushSettings.upsert({where:{id:iM},create:{id:iM,vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date},update:{vapidPublicKey:r.publicKey,vapidGeneratedAt:new Date}}).then(()=>void 0)),{publicKey:r.publicKey}}async registerWebPush(e){let t=iV(e.endpoint),r=iF(e.p256dh,"Push p256dh key",1e3),i=iF(e.auth,"Push auth key",1e3),a=null===e.expirationTime||void 0===e.expirationTime?null:new Date(e.expirationTime);if(a&&!Number.isFinite(a.getTime()))throw Error("Push subscription expiration is invalid");return await this.prepareWebPush(),(await (0,tY.getPrismaClient)()).webPushSubscription.upsert({where:{endpoint:t},create:{id:(0,g.randomUUID)(),endpoint:t,p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null},update:{p256dh:r,auth:i,expirationTime:a,locale:e.locale?.trim().slice(0,35)||null,userAgent:e.userAgent?.trim().slice(0,1e3)||null,lastSeenAt:new Date}})}async unregisterWebPush(e){let t=iV(e),r=await (0,tY.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{endpoint:t}})).count>0}async deleteWebPushSubscription(e){let t=iF(e,"Push subscription",200),r=await (0,tY.getPrismaClient)();return(await r.webPushSubscription.deleteMany({where:{id:t}})).count>0}async testWebPushSubscription(e){let t=iF(e,"Push subscription",200),r=await (0,tY.getPrismaClient)(),[i,a]=await Promise.all([r.webPushSettings.findUnique({where:{id:iM}}),r.webPushSubscription.findUnique({where:{id:t}})]);if(!a)throw Error("Push subscription was not found");if(!i?.vapidPublicKey)throw Error("Web Push is not configured");let n=await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey);if(!n)throw Error("The Web Push private key is unavailable");iU.default.setVapidDetails(iH(),i.vapidPublicKey,n);try{return await iU.default.sendNotification({endpoint:a.endpoint,expirationTime:a.expirationTime?.getTime()??null,keys:{p256dh:a.p256dh,auth:a.auth}},JSON.stringify({id:`test:${Date.now()}`,title:"Test notification",body:"Web Push is working for this browser.",href:"/notifications",icon:"/icon-192.png",badge:"/icon-192.png"}),{TTL:60,timeout:1e4}),!0}catch(e){if([404,410].includes(iz(e)??0))throw await r.webPushSubscription.deleteMany({where:{id:t}}),Error("The browser subscription expired and was removed");throw e}}async deliverWebPush(e){if(!e.webPushRequested)return;let t=await (0,tY.getPrismaClient)(),[r,i]=await Promise.all([t.webPushSettings.findUnique({where:{id:iM}}),t.webPushSubscription.findMany()]);if(!r?.vapidPublicKey||!i.length)return;let a=await this.credentialService.getText(tX.CREDENTIALS.webPushVapidPrivateKey);if(!a)return;iU.default.setVapidDetails(iH(),r.vapidPublicKey,a);let n=JSON.stringify({id:e.id,title:e.title,body:e.body,href:e.href,icon:"/icon-192.png",badge:"/icon-192.png"});await Promise.allSettled(i.map(async e=>{try{await iU.default.sendNotification({endpoint:e.endpoint,expirationTime:e.expirationTime?.getTime()??null,keys:{p256dh:e.p256dh,auth:e.auth}},n,{TTL:3600,timeout:1e4})}catch(r){if([404,410].includes(iz(r)??0))return void await t.webPushSubscription.deleteMany({where:{endpoint:e.endpoint}});console.error(`Web Push delivery to ${e.endpoint} failed:`,r)}}))}}var iJ=e.i(986847);let iW=e=>e?.toISOString()??null;function iZ(e,t,r,i,a){return e?t?"RUNNING":a?"ERROR":r&&!i||r&&i&&Date.now()-i.getTime()>2e3*r+5e3?"STALE":"HEALTHY":"DISABLED"}class iY{operations=new Map;register(e){let t=this.operations.get(e.id);this.operations.set(e.id,{...e,lastStartedAt:t?.lastStartedAt??null,lastCompletedAt:t?.lastCompletedAt??null,lastSucceededAt:t?.lastSucceededAt??null,nextScheduledAt:t?.nextScheduledAt??null,durationMs:t?.durationMs??null,lastError:t?.lastError??null}),this.changed(e.id)}configure(e,t){let r=this.operations.get(e);r&&(Object.assign(r,t),r.enabled||(r.nextScheduledAt=null),this.changed(e))}schedule(e,t){let r=this.operations.get(e);r&&(r.nextScheduledAt=t,this.changed(e))}async run(e,t,r){let i=this.operations.get(e);if(!i)throw Error(`Polling operation ${e} is not registered`);let a=new Date;i.lastStartedAt=a,i.lastError=null,this.changed(e);try{let e=await t(),n=new Date;return i.lastCompletedAt=n,i.lastSucceededAt=n,i.durationMs=n.getTime()-a.getTime(),i.lastError=null,r&&(i.details={...i.details,...r(e)}),e}catch(t){let e=new Date;throw i.lastCompletedAt=e,i.durationMs=e.getTime()-a.getTime(),i.lastError=t instanceof Error?t.message:String(t),t}finally{this.changed(e)}}changed(e){im.agentEventBus.publish(im.POLLING_CHANGED_TOPIC,{pollingOperationChanged:e})}subscribe(){return im.agentEventBus.iterate(im.POLLING_CHANGED_TOPIC)}serverViews(){return[...this.operations.values()].map(e=>({...e,status:iZ(e.enabled,!!(e.lastStartedAt&&(!e.lastCompletedAt||e.lastStartedAt>e.lastCompletedAt)),e.cadenceSeconds,e.lastCompletedAt,e.lastError),lastStartedAt:iW(e.lastStartedAt),lastCompletedAt:iW(e.lastCompletedAt),lastSucceededAt:iW(e.lastSucceededAt),nextScheduledAt:iW(e.nextScheduledAt)}))}async list(){let e=await (0,tY.getPrismaClient)(),[t,r,i]=await Promise.all([e.codebaseSettings.findUnique({where:{id:"default"}}),e.agent.findMany({orderBy:{name:"asc"},select:{id:!0,name:!0,lastSeenAt:!0,disconnectedAt:!0,codebaseScanIntervalSeconds:!0,jobReconciliationIntervalSeconds:!0,gitFetchIntervalSeconds:!0,heartbeatIntervalSeconds:!0,codebases:{select:{lastCheckedAt:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,lastFetchError:!0}}}}),e.agentJob.groupBy({by:["agentId","status"],where:{status:{in:["QUEUED","RUNNING"]}},_count:{_all:!0}})]),n=t?.refreshIntervalSeconds??30,s=t?.fetchIntervalSeconds??300,o=new Map;for(let e of i)o.set(e.agentId,(o.get(e.agentId)??0)+e._count._all);let l=[];for(let e of r){let t=e.heartbeatIntervalSeconds??iJ.DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS,r=e.jobReconciliationIntervalSeconds??iJ.DEFAULT_AGENT_JOB_RECONCILIATION_INTERVAL_SECONDS,i=e.codebaseScanIntervalSeconds??n,c=e.gitFetchIntervalSeconds??s,u=null!==e.lastSeenAt&&null===e.disconnectedAt&&Date.now()-e.lastSeenAt.getTime()<=(0,a.agentOnlineWindowMs)(e);l.push({id:`agent-heartbeat:${e.id}`,kind:"AGENT_HEARTBEAT",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:t,lastStartedAt:null,lastCompletedAt:iW(e.lastSeenAt),lastSucceededAt:iW(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*t).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,connection:u?"ONLINE":"OFFLINE"}}),l.push({id:`agent-job-reconciliation:${e.id}`,kind:"AGENT_JOB_RECONCILIATION",runtime:"AGENT",status:u?"HEALTHY":"STALE",enabled:!0,cadenceSeconds:r,lastStartedAt:null,lastCompletedAt:iW(e.lastSeenAt),lastSucceededAt:iW(e.lastSeenAt),nextScheduledAt:e.lastSeenAt?new Date(e.lastSeenAt.getTime()+1e3*r).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,pendingJobs:o.get(e.id)??0}});let d=e.codebases.map(e=>e.lastCheckedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,p=e.codebases.map(e=>e.lastFetchAttemptAt??e.lastFetchedAt).filter(e=>null!==e).sort((e,t)=>t.getTime()-e.getTime())[0]??null,h=e.codebases.filter(e=>e.lastFetchError).length;l.push({id:`agent-codebase-scan:${e.id}`,kind:"CODEBASE_SCAN",runtime:"AGENT",status:iZ(e.codebases.length>0,!1,i,d,null),enabled:e.codebases.length>0,cadenceSeconds:i,lastStartedAt:null,lastCompletedAt:iW(d),lastSucceededAt:iW(d),nextScheduledAt:d?new Date(d.getTime()+1e3*i).toISOString():null,durationMs:null,lastError:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length}}),l.push({id:`agent-git-fetch:${e.id}`,kind:"GIT_FETCH",runtime:"AGENT",status:h>0?"ERROR":iZ(e.codebases.length>0,!1,c,p,null),enabled:e.codebases.length>0,cadenceSeconds:c,lastStartedAt:null,lastCompletedAt:iW(p),lastSucceededAt:h>0?null:iW(p),nextScheduledAt:p?new Date(p.getTime()+1e3*c).toISOString():null,durationMs:null,lastError:h>0?`${h} repositories have fetch errors`:null,details:{agentId:e.id,agentName:e.name,repositories:e.codebases.length,fetchErrors:h}})}return[...this.serverViews(),...l]}}let iQ="default",iX="https://raw.githubusercontent.com/BerriAI/litellm/refs/heads/main/model_prices_and_context_window.json",i0=new Set(["sample_spec"]);function i1(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function i2(e){let t=i1(e);return null===t?null:Math.trunc(t)}function i3(e){return"string"==typeof e&&e.trim()?e.trim():null}function i4(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(t+1)}let i6={MODEL:"model",PROVIDER:"provider",INPUT_COST:"inputCostPerToken",OUTPUT_COST:"outputCostPerToken",CACHE_READ_COST:"cacheReadCostPerToken",CACHE_WRITE_COST:"cacheWriteCostPerToken",CONTEXT_WINDOW:"maxInputTokens"};function i8(e){return{model:e.model,provider:e.provider,mode:e.mode,inputCostPerToken:e.inputCostPerToken,outputCostPerToken:e.outputCostPerToken,cacheReadCostPerToken:e.cacheReadCostPerToken,cacheWriteCostPerToken:e.cacheWriteCostPerToken,maxInputTokens:e.maxInputTokens,maxOutputTokens:e.maxOutputTokens,updatedAt:e.updatedAt.toISOString()}}class i5{refreshing=null;checkedAt=0;async getCatalog(){let e=await (0,tY.getPrismaClient)(),t=await e.modelCostSettings.upsert({where:{id:iQ},create:{id:iQ},update:{}}),r=t.catalogUrl??iX;return{url:r,defaultUrl:iX,customUrl:t.catalogUrl,fetchedAt:t.fetchedAt?.toISOString()??null,entryCount:t.entryCount,error:t.error,stale:this.isStale(t.fetchedAt)||t.sourceUrl!==r}}isStale(e){return!e||Date.now()-e.getTime()>=864e5}async saveSettings(e){let t=e?.trim()??"",r=t&&t!==iX?t:null;if(r){let e;try{e=new URL(r)}catch{throw Error("The model cost URL must be a valid URL")}if("https:"!==e.protocol&&"http:"!==e.protocol)throw Error("The model cost URL must be an http or https URL")}let i=await (0,tY.getPrismaClient)();return await i.modelCostSettings.upsert({where:{id:iQ},create:{id:iQ,catalogUrl:r},update:{catalogUrl:r}}),this.checkedAt=0,this.getCatalog()}async refresh(){return this.refreshing||(this.refreshing=this.runRefresh().finally(()=>{this.refreshing=null})),this.refreshing}async runRefresh(){let e=await (0,tY.getPrismaClient)(),t=await this.getCatalog();try{let r=await fetch(t.url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(3e4)});if(!r.ok)throw Error(`The model cost catalog request failed with ${r.status}`);let i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Error("The model cost catalog is not a JSON object");let t=[];for(let[r,i]of Object.entries(e)){if(i0.has(r)||!i||"object"!=typeof i||Array.isArray(i))continue;let e=i1(i.input_cost_per_token),a=i1(i.output_cost_per_token);if((null!==e||null!==a)&&(t.push({model:r,provider:i3(i.litellm_provider),mode:i3(i.mode),inputCostPerToken:e,outputCostPerToken:a,cacheReadCostPerToken:i1(i.cache_read_input_token_cost),cacheWriteCostPerToken:i1(i.cache_creation_input_token_cost),maxInputTokens:i2(i.max_input_tokens),maxOutputTokens:i2(i.max_output_tokens)}),t.length>=2e4))break}if(!t.length)throw Error("The model cost catalog contained no priced models");return t}(await r.json());await e.$transaction(async e=>{await e.modelCostEntry.deleteMany({});for(let t=0;t<i.length;t+=500)await e.modelCostEntry.createMany({data:i.slice(t,t+500)});await e.modelCostSettings.update({where:{id:iQ},data:{fetchedAt:new Date,sourceUrl:t.url,entryCount:i.length,error:null}})})}catch(r){let t=r instanceof Error?r.message:String(r);await e.modelCostSettings.update({where:{id:iQ},data:{error:t.slice(0,2e3)}})}return this.getCatalog()}async ensureFresh(){this.refreshing&&await this.refreshing,Date.now()-this.checkedAt<3e5||((await this.getCatalog()).stale&&await this.refresh(),this.checkedAt=Date.now())}async listEntries({search:e,first:t=100,offset:r=0,sortKey:i="MODEL",direction:a="ASC"}){var n;let s,o;await this.ensureFresh();let l=await (0,tY.getPrismaClient)(),c=e?.trim(),u=c?{OR:[{model:{contains:c}},{provider:{contains:c}}]}:{},d=Math.min(Math.max(t??100,1),500),p=Math.max(r??0,0),[h,m]=await Promise.all([l.modelCostEntry.findMany({where:u,orderBy:(n=i??"MODEL",s="DESC"===(a??"ASC")?"desc":"asc","model"===(o=i6[n]??"model")?[{model:s}]:[{[o]:{sort:s,nulls:"last"}},{model:s}]),skip:p,take:d}),l.modelCostEntry.count({where:u})]);return{items:h.map(i8),totalCount:m}}async lookup(e){let t=[...new Set(e.filter(Boolean))],r=new Map;if(!t.length)return r;let i=await (0,tY.getPrismaClient)(),a=[...new Set(t.flatMap(e=>[e,i4(e)]))],n=new Map((await i.modelCostEntry.findMany({where:{model:{in:a}}})).map(e=>[e.model,e])),s=[];for(let e of t){let t=n.get(e)??n.get(i4(e));t?r.set(e,i8(t)):s.push(e)}if(!s.length)return r;let o=await i.modelCostEntry.findMany({where:{OR:s.map(e=>({model:{endsWith:`/${i4(e)}`}}))}});for(let e of s){let t=i4(e).toLowerCase(),i=o.find(e=>i4(e.model).toLowerCase()===t);i&&r.set(e,i8(i))}return r}estimate(e,t){if(!e)return null;let r=e.inputCostPerToken,i=e.outputCostPerToken;if(null===r&&null===i)return null;let a=e.cacheReadCostPerToken??r??0,n=e.cacheWriteCostPerToken??r??0;return t.inputTokens*(r??0)+t.outputTokens*(i??0)+t.cacheReadTokens*a+t.cacheWriteTokens*n}}e.i(648153);var i9=e.i(594875);let i7=globalThis;e.s(["getServerServices",0,function(){let e,t,r,i,g,y,v,b,w,x,k,S,I,A,_,E,C,T,D,$,R,N;return i7.serverServices??(e=new f.PrismaService,t=new tQ.CredentialService,r=new a.AgentControlService,i=new n.CcusageService(r),g=new s.BuildDataService(r),y=new iD.TelemetryService,v=new ij(r,void 0,t),b=new iY,w=new i5,x=new iB.PushNotificationsService(void 0,t,b),k=new iG(t),(S=new i9.RunsService(k,r)).startReaper(),I=new o.BuildsService(r,y,k),A=new iT(r),_=new l.CodebasesService(r,A),E=new c.CodebaseToolsService(_),C=new h.JiraService(t),T=new m.IosDevicesService(void 0,t),D=new u.GitHubActionsNotificationsService(t,k,b),$=new d.GitHubService(!0,t,b,()=>D.configurationChanged()),R=new p.CacheServerService(t),N=new id.WorktreesService(r,C,$,A),i7.serverServices={prismaService:e,credentialService:t,agentControlService:r,ccusageService:i,buildDataService:g,buildsService:I,codebasesService:_,codebaseToolsService:E,jiraService:C,iosDevicesService:T,gitHubService:$,gitHubActionsNotificationsService:D,cacheServerService:R,worktreesService:N,skillsService:A,telemetryService:y,signingAssetsService:v,pushNotificationsService:x,notificationsService:k,pollingService:b,modelCostsService:w,runsService:S,toolsService:new r3(E,I,{codebases:_,telemetry:y,pushNotifications:x,agents:r},t)})}],887394)}];
|
|
429
429
|
|
|
430
430
|
//# sourceMappingURL=_1ioi8na._.js.map
|