@sentry/junior 0.300.0 → 0.302.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-UrTniSPO.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-bY4_0UPm.js → agent-runner-CY9RvsTX.js} +1367 -10649
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +124 -67
  8. package/dist/{app-D-AcIcCV.d.ts → app-BpY3wtRP.d.ts} +3 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +71 -299
  11. package/dist/{automation-Dw82oQ-h.js → automation-Cva5ZOwW.js} +1 -1
  12. package/dist/{background-compaction-queue-B6U3060-.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  13. package/dist/{briefs-DqiwWu-n.js → briefs-B3NG-pid.js} +3 -3
  14. package/dist/{catalog-runtime-D1oYNv04.js → catalog-runtime-Dss0lSV6.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-9nHoFiJP.js → config-CzeZiMKs.js} +2 -2
  23. package/dist/{connections-DZjTN3JC.js → connections-CDYhMfrs.js} +6 -6
  24. package/dist/{continue-in-slack-Dtv7_U42.js → continue-in-slack-7Uf05ndC.js} +5 -6
  25. package/dist/{conversation-Dyjq2CZ8.js → conversation-BNXfq6Lb.js} +11 -1
  26. package/dist/{conversation-feed-CcDxlrlQ.js → conversation-feed-Clf_cv0n.js} +2 -1
  27. package/dist/{conversation-privacy-D-5HTXjS.js → conversation-privacy-D9xnM5mK.js} +1 -1
  28. package/dist/{conversation-turn-Cxl8WZD7.js → conversation-turn-D7SEZgTG.js} +16 -17
  29. package/dist/{credential-sync-C49ClwDX.js → credential-sync-DoD0gW-j.js} +13 -15
  30. package/dist/{db-BJNo6fK5.js → db-B-gtnNjr.js} +314 -5
  31. package/dist/{db-2resqBh1.d.ts → db-BdsCzytP.d.ts} +1 -1
  32. package/dist/{executor-DBIaOeJ_.js → executor-DZg20EqU.js} +39 -4
  33. package/dist/install-t1KQyTUs.js +228 -0
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{state-zSilNpbi.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  36. package/dist/{lineage-0dereG7H.js → lineage-C79GjoQr.js} +2 -2
  37. package/dist/{logging-BIclibct.js → logging-C9oDAg4M.js} +7 -3
  38. package/dist/{message-dkOl-Iii.js → message-BLUCzJXN.js} +8 -8
  39. package/dist/{model-input-CLo9TaUd.js → model-input-5jwNC45G.js} +3 -3
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +4 -3
  42. package/dist/{oauth-callback-server-WmpjfJgQ.js → oauth-callback-server-BBl66vCb.js} +2 -2
  43. package/dist/{projection-w_X-zi7v.js → projection-CIBwgD3s.js} +437 -97
  44. package/dist/{prompt-B1Xw46-S.js → prompt-CRQbzp5e.js} +15 -5
  45. package/dist/queue-DtCDaIct.js +115 -0
  46. package/dist/{registry-BmP5vnlj.js → registry-DdFQHZ_d.js} +1 -1
  47. package/dist/{resolve-goo34bJK.js → resolve-CdW4BdrK.js} +4 -229
  48. package/dist/{result-PVBeU0Wf.js → result-oOMv1t4O.js} +9 -9
  49. package/dist/{runner-DKrfvNV6.js → runner-DqitLtm-.js} +9 -9
  50. package/dist/{sandbox-egress-signals-DsUcqrI0.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  51. package/dist/{schema-Dns-sTas.d.ts → schema-BIFM-U1a.d.ts} +470 -30
  52. package/dist/{schema-C9iNFz5n.js → schema-DnVQepWP.js} +76 -31
  53. package/dist/{service-account-CMAAloAL.js → service-account-B6mKAPVo.js} +3 -3
  54. package/dist/{service-account-CmowamcB.js → service-account-CrZftRTb.js} +257 -6
  55. package/dist/{session-stop-BcAXze8a.js → session-stop-DW63Z3kj.js} +1103 -1007
  56. package/dist/{skills-DfsazET6.js → skills-C16fz60Z.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-CzQonuWz.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  58. package/dist/{spawn-C7o0FDDp.js → spawn-D_RnFYfy.js} +6 -6
  59. package/dist/{stop-CFOujp8C.js → stop-7p1i08CY.js} +941 -2311
  60. package/dist/{store-E3x2Fg_F.js → store-C28I0CVW.js} +5 -5
  61. package/dist/{task-queue-D-hCqdZW.js → task-queue-BVUJbQ28.js} +3 -3
  62. package/dist/{task-runner-vohUPLHe.js → task-runner-CWi8j7Z6.js} +6 -8
  63. package/dist/{thread-context-BzvdkgI9.js → thread-context-D3-yYUd0.js} +8 -8
  64. package/dist/{store-Dkeis_8o.js → turn-session-routing-BFMS9ATF.js} +382 -11
  65. package/dist/{turn-user-message-D5RnVmxQ.js → turn-user-message-C3-O8Omt.js} +3 -3
  66. package/dist/{validation-BbWikeSa.js → validation-BSFKUIb4.js} +1 -1
  67. package/dist/{version-GVBMW2jA.js → version-BHHXNi-0.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-BpxRliyO.js → viewer-B1SO21Qa.js} +3 -3
  70. package/dist/warmup-Bz9bzkzN.js +13927 -0
  71. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  72. package/dist/{worker-Cbd-iuwZ.js → worker-BspReIIK.js} +7 -7
  73. package/migrations/0108_conversation_embeddings.sql +13 -0
  74. package/migrations/meta/0108_snapshot.json +4688 -0
  75. package/migrations/meta/_journal.json +7 -0
  76. package/package.json +10 -8
  77. package/dist/adapter-S5UkjNK3.js +0 -303
  78. package/dist/reporting-window-DopzcOHh.js +0 -137
  79. package/dist/turn-session-routing-Bo_LxFum.js +0 -380
  80. package/dist/users-2bggndVg.js +0 -424
  81. package/dist/warmup-BW2qwnal.js +0 -3693
@@ -1,9 +1,8 @@
1
1
  import { r as notificationScheduleSchema } from "./schedule-cP0AACm1.js";
2
- import { D as idempotencyKeySchema, O as conversationChildAgentTotalsSchema, S as conversationUsageSchema, b as conversationSummaryReportSchema, c as conversationAuxiliaryCostsSchema, i as actorIdentitySchema, q as inputFileSchema } from "./conversation-Dyjq2CZ8.js";
3
- import { r as AGENT_INVOCATION_STATUSES, u as userInputRequestSchema } from "./statuses-Hn-HsOph.js";
4
- import { i as fillUtcHours, r as fillUtcDays, s as sumUtcHoursIntoSixHours } from "./reporting-window-DopzcOHh.js";
5
- import "./automation-Dw82oQ-h.js";
6
- import "./conversation-feed-CcDxlrlQ.js";
2
+ import { D as idempotencyKeySchema, O as conversationChildAgentTotalsSchema, S as conversationUsageSchema, b as conversationSummaryReportSchema, c as conversationAuxiliaryCostsSchema, i as actorIdentitySchema, q as inputFileSchema } from "./conversation-BNXfq6Lb.js";
3
+ import "./automation-Cva5ZOwW.js";
4
+ import { M as sumUtcHoursIntoSixHours, O as fillUtcDays, d as userInputRequestSchema, i as AGENT_INVOCATION_STATUSES, k as fillUtcHours } from "./web-message-id-lNodcCOI.js";
5
+ import "./conversation-feed-Clf_cv0n.js";
7
6
  import { t as isPushServiceEndpoint } from "./push-endpoint-CO-nomUd.js";
8
7
  import * as z from "zod";
9
8
  import { codeChangeStateSchema, eventMatchSchema, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
@@ -664,6 +663,77 @@ const serviceAccountListSchema = z.object({ serviceAccounts: z.array(serviceAcco
664
663
  const serviceAccountParamsSchema = z.object({ provider: z.string().regex(/^[a-z][a-z0-9-]*$/).max(64) }).strict();
665
664
  const startServiceAccountSignInResponseSchema = z.object({ authorizationUrl: z.string().url() }).strict();
666
665
  const disconnectServiceAccountResponseSchema = z.object({ disconnected: z.literal(true) }).strict();
666
+ // src/api/schema/cache-warming.ts
667
+ const cacheWarmingBreakerSchema = z.object({
668
+ provider: z.string(),
669
+ open: z.boolean()
670
+ }).strict();
671
+ const cacheWarmingBreakerListSchema = z.object({ breakers: z.array(cacheWarmingBreakerSchema) }).strict();
672
+ const cacheWarmingBreakerParamsSchema = z.object({ provider: z.string().regex(/^[a-z][a-z0-9-]*$/).max(64) }).strict();
673
+ const closeCacheWarmingBreakerResponseSchema = z.object({ closed: z.literal(true) }).strict();
674
+ const cacheWarmingSavingsQuerySchema = z.object({
675
+ /** Trailing UTC days, today included. */
676
+ days: z.enum([
677
+ "1",
678
+ "7",
679
+ "30",
680
+ "90"
681
+ ]).default("30").transform((days) => Number(days)) }).strict();
682
+ /** What cache warming saved, in dollars. Net savings can be negative. */
683
+ const cacheWarmingSavingsSchema = z.object({
684
+ /** Idle periods that count, as defined by `idlePeriodSavings`. */
685
+ idlePeriods: z.number().int().nonnegative(),
686
+ /** Idle periods whose next call read the warmed cache. */
687
+ hits: z.number().int().nonnegative(),
688
+ /** Cache writes that the hits avoided, less their cache reads. */
689
+ savedUsd: z.number().nonnegative(),
690
+ /** Cost of every idle warmup call. */
691
+ warmupCostUsd: z.number().nonnegative(),
692
+ /** Savings of an ideal warmer that knew each gap. */
693
+ oracleSavingsUsd: z.number().nonnegative(),
694
+ /** Idle periods with no warm state, such as a too large snapshot. */
695
+ unwarmedIdlePeriods: z.number().int().nonnegative(),
696
+ /** The part of the oracle savings from idle periods with no warm state. */
697
+ unwarmedOracleSavingsUsd: z.number().nonnegative()
698
+ }).strict();
699
+ const cacheWarmingSavingsReportSchema = z.object({
700
+ days: z.array(cacheWarmingSavingsSchema.extend({
701
+ date: z.string(),
702
+ /**
703
+ * Saved less warmup cost. Null on a day filled from history, which
704
+ * has no warmup calls, so its warmup cost is unknown.
705
+ */
706
+ netSavingsUsd: z.number().nullable()
707
+ })),
708
+ totals: cacheWarmingSavingsSchema.extend({
709
+ /** Net savings of the days with known warmup cost. */
710
+ netSavingsUsd: z.number(),
711
+ /** Oracle savings of the days with known warmup cost. */
712
+ knownCostOracleSavingsUsd: z.number().nonnegative(),
713
+ /**
714
+ * Net savings over oracle savings of the days with known warmup cost.
715
+ * Null with no oracle savings on those days.
716
+ */
717
+ effectiveness: z.number().nullable(),
718
+ /** Days filled from history, with unknown warmup cost. */
719
+ unknownCostDays: z.number().int().nonnegative()
720
+ })
721
+ }).strict();
722
+ const cacheWarmingSavingsRefillSchema = z.object({
723
+ status: z.enum([
724
+ "idle",
725
+ "pending",
726
+ "running",
727
+ "done",
728
+ "failed"
729
+ ]),
730
+ startedAt: z.string().optional(),
731
+ finishedAt: z.string().optional(),
732
+ error: z.string().optional(),
733
+ scannedConversations: z.number().int().nonnegative().optional(),
734
+ totalConversations: z.number().int().nonnegative().optional()
735
+ }).strict();
736
+ const cacheWarmingSavingsRefillResponseSchema = z.object({ refill: cacheWarmingSavingsRefillSchema }).strict();
667
737
  // src/api/schema/review-item.ts
668
738
  const answerSchema = z.object({
669
739
  other: z.string().max(4e3).optional(),
@@ -822,31 +892,6 @@ const workspaceBodySchema = z.object({
822
892
  }).strict();
823
893
  const workspaceParamsSchema = z.object({ id: z.string().uuid() }).strict();
824
894
  const deleteWorkspaceResponseSchema = z.object({ deleted: z.literal(true) }).strict();
825
- // src/api/schema/reply-times.ts
826
- /** Reply times in the bins of the cache warming model. */
827
- const replyTimeHistogramSchema = z.object({
828
- bins: z.array(z.object({
829
- count: z.number().int().nonnegative(),
830
- endMs: z.number().int().positive(),
831
- startMs: z.number().int().nonnegative()
832
- }).strict()),
833
- /** Idle periods with no reply before the cache warming horizon. */
834
- noReply: z.number().int().nonnegative(),
835
- total: z.number().int().nonnegative()
836
- }).strict();
837
- /** Gap histogram of each cache warming segment, over all Conversations. */
838
- const replyTimeSegmentsReportSchema = z.object({
839
- generatedAt: z.string().datetime(),
840
- /**
841
- * Below this many gaps, the planner leans on the segment's `none`
842
- * segment, or does not warm a `none` segment.
843
- */
844
- minSamples: z.number().int().positive(),
845
- segments: z.array(z.object({
846
- histogram: replyTimeHistogramSchema,
847
- segment: z.string().min(1)
848
- }).strict())
849
- }).strict();
850
895
  // src/api/schema/stats.ts
851
896
  const statSchema = z.object({
852
897
  count: z.number().int().nonnegative(),
@@ -888,4 +933,4 @@ const versionsSchema = z.object({
888
933
  /** The viewer's rolling model spend. */
889
934
  spend: z.string().min(1)
890
935
  }).strict();
891
- export { codeActivityDaySchema as $, revokePersonalTokenResponseSchema as A, pinConversationBodySchema as At, activityDays as B, serviceAccountSchema as C, archiveConversationResponseSchema as Ct, personalTokenListSchema as D, conversationSubscriptionResponseSchema as Dt, createdPersonalTokenSchema as E, conversationSubscriptionBodySchema as Et, personalSpendReportSchema as F, conversationCatchUpSchema as Ft, pushSubscriptionBodySchema as G, activitySixHours as H, locationActivityDayReportSchema as I, attachmentUploadParamsSchema as It, connectionListSchema as J, pushSubscriptionDeleteBodySchema as K, locationDetailReportSchema as L, attachmentUploadSchema as Lt, actorProfileReportSchema as M, reorderPinnedConversationsBodySchema as Mt, avatarParamsSchema as N, reorderPinnedConversationsResponseSchema as Nt, personalTokenMetadataSchema as O, conversationDeliveryBodySchema as Ot, personParamsSchema as P, conversationCatchUpBodySchema as Pt, startConnectionResponseSchema as Q, locationDirectoryReportSchema as R, createAttachmentUploadBodySchema as Rt, serviceAccountParamsSchema as S, archiveConversationBodySchema as St, createPersonalTokenBodySchema as T, conversationAutoArchiveSchema as Tt, dailyConversationActivitySchema as U, activityHours as V, notificationSettingsSchema as W, connectionSchema as X, connectionParamsSchema as Y, disconnectConnectionResponseSchema as Z, reviewItemParamsSchema as _, objectLinksReportSchema as _t, replyTimeSegmentsReportSchema as a, codeRepositoryReportSchema as at, disconnectServiceAccountResponseSchema as b, CONVERSATION_OUTLINE_TEXT_LENGTH as bt, workspaceBodySchema as c, conversationWatchesReportSchema as ct, workspaceRepoSchema as d, continueConversationInSlackBodySchema as dt, codeChangeSummaryReportSchema as et, workspaceSchema as f, continueConversationInSlackResponseSchema as ft, reviewItemListSchema as g, objectLinksQuerySchema as gt, reviewItemListQuerySchema as h, attachObjectLinkResponseSchema as ht, statsReportSchema as i, codeRepositoryParamsSchema as it, actorDirectoryReportSchema as j, pinConversationResponseSchema as jt, personalTokenParamsSchema as k, conversationDeliveryResponseSchema as kt, workspaceListSchema as l, conversationChildAgentSchema as lt, reviewItemCountSchema as m, attachObjectLinkBodySchema as mt, versionsSchema as n, codeOverviewReportSchema as nt, baselineSnapshotSchema as o, codeRepositorySummarySchema as ot, reviewItemActionSchema as p, MAX_OBJECT_LINKS as pt, testNotificationResponseSchema as q, statSchema as r, codePersonReportSchema as rt, deleteWorkspaceResponseSchema as s, conversationWatchSchema as st, versionsQuerySchema as t, codeChangeSummarySchema as tt, workspaceParamsSchema as u, conversationChildAgentsReportSchema as ut, reviewItemSchema as v, stopConversationTurnResponseSchema as vt, startServiceAccountSignInResponseSchema as w, archiveDoneConversationsResponseSchema as wt, serviceAccountListSchema as x, conversationOutlineSchema as xt, reviewItemWaitingConversationsSchema as y, conversationStatsReportSchema as yt, locationParamsSchema as z };
936
+ export { connectionListSchema as $, createPersonalTokenBodySchema as A, conversationAutoArchiveSchema as At, personalSpendReportSchema as B, conversationCatchUpSchema as Bt, cacheWarmingSavingsReportSchema as C, stopConversationTurnResponseSchema as Ct, serviceAccountParamsSchema as D, archiveConversationBodySchema as Dt, serviceAccountListSchema as E, conversationOutlineSchema as Et, revokePersonalTokenResponseSchema as F, pinConversationBodySchema as Ft, activityDays as G, locationDetailReportSchema as H, attachmentUploadSchema as Ht, actorDirectoryReportSchema as I, pinConversationResponseSchema as It, dailyConversationActivitySchema as J, activityHours as K, actorProfileReportSchema as L, reorderPinnedConversationsBodySchema as Lt, personalTokenListSchema as M, conversationSubscriptionResponseSchema as Mt, personalTokenMetadataSchema as N, conversationDeliveryBodySchema as Nt, serviceAccountSchema as O, archiveConversationResponseSchema as Ot, personalTokenParamsSchema as P, conversationDeliveryResponseSchema as Pt, testNotificationResponseSchema as Q, avatarParamsSchema as R, reorderPinnedConversationsResponseSchema as Rt, cacheWarmingSavingsRefillResponseSchema as S, objectLinksReportSchema as St, disconnectServiceAccountResponseSchema as T, CONVERSATION_OUTLINE_TEXT_LENGTH as Tt, locationDirectoryReportSchema as U, createAttachmentUploadBodySchema as Ut, locationActivityDayReportSchema as V, attachmentUploadParamsSchema as Vt, locationParamsSchema as W, pushSubscriptionBodySchema as X, notificationSettingsSchema as Y, pushSubscriptionDeleteBodySchema as Z, reviewItemSchema as _, continueConversationInSlackResponseSchema as _t, baselineSnapshotSchema as a, codeChangeSummaryReportSchema as at, cacheWarmingBreakerParamsSchema as b, attachObjectLinkResponseSchema as bt, workspaceListSchema as c, codePersonReportSchema as ct, workspaceSchema as d, codeRepositorySummarySchema as dt, connectionParamsSchema as et, reviewItemActionSchema as f, conversationWatchSchema as ft, reviewItemParamsSchema as g, continueConversationInSlackBodySchema as gt, reviewItemListSchema as h, conversationChildAgentsReportSchema as ht, statsReportSchema as i, codeActivityDaySchema as it, createdPersonalTokenSchema as j, conversationSubscriptionBodySchema as jt, startServiceAccountSignInResponseSchema as k, archiveDoneConversationsResponseSchema as kt, workspaceParamsSchema as l, codeRepositoryParamsSchema as lt, reviewItemListQuerySchema as m, conversationChildAgentSchema as mt, versionsSchema as n, disconnectConnectionResponseSchema as nt, deleteWorkspaceResponseSchema as o, codeChangeSummarySchema as ot, reviewItemCountSchema as p, conversationWatchesReportSchema as pt, activitySixHours as q, statSchema as r, startConnectionResponseSchema as rt, workspaceBodySchema as s, codeOverviewReportSchema as st, versionsQuerySchema as t, connectionSchema as tt, workspaceRepoSchema as u, codeRepositoryReportSchema as ut, reviewItemWaitingConversationsSchema as v, MAX_OBJECT_LINKS as vt, closeCacheWarmingBreakerResponseSchema as w, conversationStatsReportSchema as wt, cacheWarmingSavingsQuerySchema as x, objectLinksQuerySchema as xt, cacheWarmingBreakerListSchema as y, attachObjectLinkBodySchema as yt, personParamsSchema as z, conversationCatchUpBodySchema as zt };
@@ -1,6 +1,6 @@
1
- import { t as disconnectStateAdapter } from "./adapter-S5UkjNK3.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-D1oYNv04.js";
3
- import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-CmowamcB.js";
1
+ import { K as disconnectStateAdapter } from "./db-B-gtnNjr.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
3
+ import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-CrZftRTb.js";
4
4
  import { CLI_USAGE } from "./cli/run.js";
5
5
  import { createServer } from "node:http";
6
6
  // src/cli/service-account.ts
@@ -1,9 +1,10 @@
1
- import { G as isRecord, b as setSpanAttributes, h as logWarn } from "./logging-BIclibct.js";
2
- import { c as fenceLock, l as withLock, o as MUTATION_LOCK_TTL_MS, r as getStateAdapter } from "./adapter-S5UkjNK3.js";
3
- import { c as fetchWithBoundedOAuthErrorBodies, i as resolvePluginHeaderEnvRefs } from "./registry-BmP5vnlj.js";
4
- import { n as readEncryptedState, t as createEncryptedState } from "./state-zSilNpbi.js";
1
+ import { K as isRecord, b as setSpanAttributes, h as logWarn } from "./logging-C9oDAg4M.js";
2
+ import { $ as fenceLock, J as getStateAdapter, Z as MUTATION_LOCK_TTL_MS, et as withLock, ht as parseDestination } from "./db-B-gtnNjr.js";
3
+ import { c as fetchWithBoundedOAuthErrorBodies, i as resolvePluginHeaderEnvRefs } from "./registry-DdFQHZ_d.js";
4
+ import { i as readEncryptedState, r as createEncryptedState, t as findLegacyWebActorUserId } from "./legacy-web-actor-id-C-cEeWqL.js";
5
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
6
  import { randomUUID } from "node:crypto";
7
+ import { sourceSchema } from "@sentry/junior-plugin-api";
7
8
  import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
8
9
  import { Client } from "@modelcontextprotocol/sdk/client";
9
10
  import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -84,6 +85,253 @@ function getMcpAwareTelemetryMessage(error, _privacy) {
84
85
  if (error instanceof McpProviderError) return error.message;
85
86
  return getMcpAwareErrorMessage(error);
86
87
  }
88
+ // src/chat/mcp/auth-store.ts
89
+ const MCP_AUTH_SESSION_PREFIX = "junior:mcp_oauth_attempt:v2";
90
+ const MCP_AUTH_CREDENTIALS_PREFIX = "junior:mcp_auth_credentials";
91
+ const MCP_AUTH_SESSION_INDEX_PREFIX = "junior:mcp_oauth_attempt_index:v2";
92
+ const MCP_SERVER_SESSION_PREFIX = "junior:mcp_server_session";
93
+ const MCP_AUTH_SESSION_TTL_MS = 864e5;
94
+ const MCP_AUTH_CREDENTIALS_TTL_MS = 2592e6;
95
+ const MCP_SERVER_SESSION_TTL_MS = 864e5;
96
+ function sessionKey(authSessionId) {
97
+ return `${MCP_AUTH_SESSION_PREFIX}:${authSessionId}`;
98
+ }
99
+ function credentialsKey(userId, provider) {
100
+ return `${MCP_AUTH_CREDENTIALS_PREFIX}:${userId}:${provider}`;
101
+ }
102
+ function sessionIndexKey(userId, provider) {
103
+ return `${MCP_AUTH_SESSION_INDEX_PREFIX}:${userId}:${provider}`;
104
+ }
105
+ function serverSessionKey(userId, provider) {
106
+ return `${MCP_SERVER_SESSION_PREFIX}:${userId}:${provider}`;
107
+ }
108
+ function parseSessionIndex(value) {
109
+ if (typeof value !== "string") return [];
110
+ try {
111
+ const parsed = JSON.parse(value);
112
+ if (!Array.isArray(parsed)) return [];
113
+ return [...new Set(parsed.filter((id) => typeof id === "string"))];
114
+ } catch {
115
+ return [];
116
+ }
117
+ }
118
+ function parseMcpAuthSession(value) {
119
+ if (!isRecord(value)) return;
120
+ try {
121
+ const parsed = value;
122
+ if (parsed.schemaVersion !== 2 || typeof parsed.authSessionId !== "string" || typeof parsed.provider !== "string" || typeof parsed.userId !== "string" || typeof parsed.conversationId !== "string" || typeof parsed.sessionId !== "string" || typeof parsed.userMessage !== "string" || typeof parsed.createdAtMs !== "number" || typeof parsed.updatedAtMs !== "number") return;
123
+ const destination = parsed.destination === void 0 ? void 0 : parseDestination(parsed.destination);
124
+ if (parsed.destination !== void 0 && !destination) return;
125
+ const source = parsed.source === void 0 ? void 0 : sourceSchema.safeParse(parsed.source);
126
+ if (parsed.source !== void 0 && (!source || !source.success)) return;
127
+ return {
128
+ schemaVersion: 2,
129
+ authSessionId: parsed.authSessionId,
130
+ provider: parsed.provider,
131
+ userId: parsed.userId,
132
+ conversationId: parsed.conversationId,
133
+ ...destination ? { destination } : void 0,
134
+ ...source?.success ? { source: source.data } : void 0,
135
+ sessionId: parsed.sessionId,
136
+ userMessage: parsed.userMessage,
137
+ createdAtMs: parsed.createdAtMs,
138
+ updatedAtMs: parsed.updatedAtMs,
139
+ ...typeof parsed.channelId === "string" ? { channelId: parsed.channelId } : void 0,
140
+ ...typeof parsed.threadTs === "string" ? { threadTs: parsed.threadTs } : void 0,
141
+ ...typeof parsed.toolChannelId === "string" ? { toolChannelId: parsed.toolChannelId } : void 0,
142
+ ...isRecord(parsed.configuration) ? { configuration: parsed.configuration } : void 0,
143
+ ...typeof parsed.authorizationUrl === "string" ? { authorizationUrl: parsed.authorizationUrl } : void 0,
144
+ ...typeof parsed.codeVerifier === "string" ? { codeVerifier: parsed.codeVerifier } : void 0
145
+ };
146
+ } catch {
147
+ return;
148
+ }
149
+ }
150
+ function parseServerSession(value) {
151
+ if (typeof value !== "string") return;
152
+ try {
153
+ const parsed = JSON.parse(value);
154
+ if (!isRecord(parsed) || typeof parsed.sessionId !== "string" || typeof parsed.updatedAtMs !== "number") return;
155
+ return {
156
+ sessionId: parsed.sessionId,
157
+ updatedAtMs: parsed.updatedAtMs
158
+ };
159
+ } catch {
160
+ return;
161
+ }
162
+ }
163
+ function parseStoredCredentials(value) {
164
+ try {
165
+ const parsed = typeof value === "string" ? JSON.parse(value) : value;
166
+ if (!isRecord(parsed)) return;
167
+ return {
168
+ ...isRecord(parsed.clientInformation) ? { clientInformation: parsed.clientInformation } : void 0,
169
+ ...isRecord(parsed.discoveryState) ? { discoveryState: parsed.discoveryState } : void 0,
170
+ ...isRecord(parsed.tokens) ? { tokens: parsed.tokens } : void 0
171
+ };
172
+ } catch {
173
+ return;
174
+ }
175
+ }
176
+ async function readMcpAuthSession(stateAdapter, authSessionId) {
177
+ const stored = await readEncryptedState(stateAdapter, sessionKey(authSessionId));
178
+ if (stored?.stale && typeof stored.value === "string") try {
179
+ return JSON.parse(stored.value);
180
+ } catch {
181
+ return;
182
+ }
183
+ return stored?.value;
184
+ }
185
+ async function getConnectedStateAdapter() {
186
+ const stateAdapter = getStateAdapter();
187
+ await stateAdapter.connect();
188
+ return stateAdapter;
189
+ }
190
+ async function getMcpAuthSession(authSessionId) {
191
+ return parseMcpAuthSession(await readMcpAuthSession(await getConnectedStateAdapter(), authSessionId));
192
+ }
193
+ async function putMcpAuthSession(session, ttlMs = MCP_AUTH_SESSION_TTL_MS) {
194
+ const stateAdapter = await getConnectedStateAdapter();
195
+ await createEncryptedState(stateAdapter).set(sessionKey(session.authSessionId), session, ttlMs);
196
+ const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(session.userId, session.provider)));
197
+ if (!nextIndex.includes(session.authSessionId)) nextIndex.push(session.authSessionId);
198
+ await stateAdapter.set(sessionIndexKey(session.userId, session.provider), JSON.stringify(nextIndex), ttlMs);
199
+ }
200
+ async function patchMcpAuthSession(authSessionId, patch) {
201
+ const current = await getMcpAuthSession(authSessionId);
202
+ if (!current) throw new Error(`Unknown MCP auth session: ${authSessionId}`);
203
+ const next = {
204
+ ...current,
205
+ ...patch,
206
+ schemaVersion: 2,
207
+ authSessionId: current.authSessionId,
208
+ provider: current.provider,
209
+ userId: current.userId,
210
+ conversationId: current.conversationId,
211
+ ...current.destination ? { destination: current.destination } : void 0,
212
+ sessionId: current.sessionId,
213
+ userMessage: current.userMessage,
214
+ createdAtMs: current.createdAtMs,
215
+ updatedAtMs: Date.now()
216
+ };
217
+ await putMcpAuthSession(next);
218
+ return next;
219
+ }
220
+ async function deleteMcpAuthSession(authSessionId) {
221
+ const stateAdapter = await getConnectedStateAdapter();
222
+ const current = parseMcpAuthSession(await readMcpAuthSession(stateAdapter, authSessionId));
223
+ await stateAdapter.delete(sessionKey(authSessionId));
224
+ if (!current) return;
225
+ const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(current.userId, current.provider))).filter((id) => id !== authSessionId);
226
+ if (nextIndex.length > 0) {
227
+ await stateAdapter.set(sessionIndexKey(current.userId, current.provider), JSON.stringify(nextIndex), MCP_AUTH_SESSION_TTL_MS);
228
+ return;
229
+ }
230
+ await stateAdapter.delete(sessionIndexKey(current.userId, current.provider));
231
+ }
232
+ async function deleteMcpAuthSessionsForUserProvider(userId, provider) {
233
+ const stateAdapter = await getConnectedStateAdapter();
234
+ const indexKey = sessionIndexKey(userId, provider);
235
+ const authSessionIds = parseSessionIndex(await stateAdapter.get(indexKey));
236
+ for (const authSessionId of authSessionIds) await stateAdapter.delete(sessionKey(authSessionId));
237
+ await stateAdapter.delete(indexKey);
238
+ }
239
+ async function getMcpStoredOAuthCredentials(userId, provider) {
240
+ const stateAdapter = await getConnectedStateAdapter();
241
+ const stored = parseStoredCredentials((await readEncryptedState(stateAdapter, credentialsKey(userId, provider)))?.value);
242
+ if (stored) return stored;
243
+ const legacyUserId = await findLegacyWebActorUserId(userId);
244
+ if (!legacyUserId) return void 0;
245
+ const legacyKey = credentialsKey(legacyUserId, provider);
246
+ const legacy = parseStoredCredentials((await readEncryptedState(stateAdapter, legacyKey))?.value);
247
+ if (!legacy) return void 0;
248
+ await putMcpStoredOAuthCredentials(userId, provider, legacy);
249
+ await stateAdapter.delete(legacyKey);
250
+ return legacy;
251
+ }
252
+ async function putMcpStoredOAuthCredentials(userId, provider, value, ttlMs = MCP_AUTH_CREDENTIALS_TTL_MS) {
253
+ const stateAdapter = await getConnectedStateAdapter();
254
+ await createEncryptedState(stateAdapter).set(credentialsKey(userId, provider), value, ttlMs);
255
+ }
256
+ async function deleteMcpStoredOAuthCredentials(userId, provider) {
257
+ const stateAdapter = await getConnectedStateAdapter();
258
+ await stateAdapter.delete(credentialsKey(userId, provider));
259
+ const legacyUserId = await findLegacyWebActorUserId(userId);
260
+ if (legacyUserId) await stateAdapter.delete(credentialsKey(legacyUserId, provider));
261
+ }
262
+ async function getMcpServerSessionId(userId, provider) {
263
+ return parseServerSession(await (await getConnectedStateAdapter()).get(serverSessionKey(userId, provider)))?.sessionId;
264
+ }
265
+ async function putMcpServerSessionId(userId, provider, sessionId, ttlMs = MCP_SERVER_SESSION_TTL_MS) {
266
+ await (await getConnectedStateAdapter()).set(serverSessionKey(userId, provider), JSON.stringify({
267
+ sessionId,
268
+ updatedAtMs: Date.now()
269
+ }), ttlMs);
270
+ }
271
+ async function deleteMcpServerSessionId(userId, provider) {
272
+ await (await getConnectedStateAdapter()).delete(serverSessionKey(userId, provider));
273
+ }
274
+ // src/chat/mcp/token-refresh.ts
275
+ /**
276
+ * One MCP token refresh at a time for each person and provider.
277
+ *
278
+ * Providers such as Notion rotate the refresh token on each refresh and
279
+ * revoke the whole grant when a retired refresh token comes back. A Turn
280
+ * and a link card read can both find an expired access token at once, so
281
+ * every refresh of a stored person login runs under one lock. A caller
282
+ * that waited gets the tokens that the first caller saved, and its retired
283
+ * refresh token never reaches the provider.
284
+ */
285
+ const REFRESH_LOCK_TTL_MS = 3e4;
286
+ const REFRESH_WAIT_MS = 3e4;
287
+ function refreshTokenOf(body) {
288
+ const params = body instanceof URLSearchParams ? body : typeof body === "string" ? new URLSearchParams(body) : void 0;
289
+ return params?.get("grant_type") === "refresh_token" ? params.get("refresh_token") ?? void 0 : void 0;
290
+ }
291
+ /**
292
+ * Wrap the fetch of an MCP client so that each refresh-token request for
293
+ * this login runs under the shared lock. Other requests pass through.
294
+ */
295
+ function serializeMcpTokenRefresh(owner, fetchFn = globalThis.fetch) {
296
+ let sentAccessToken;
297
+ return (async (input, init) => {
298
+ const sentRefreshToken = refreshTokenOf(init?.body);
299
+ if (!sentRefreshToken) {
300
+ const authorization = new Headers(init?.headers).get("authorization");
301
+ if (authorization) sentAccessToken = authorization.replace(/^Bearer\s+/i, "");
302
+ return await fetchFn(input, init);
303
+ }
304
+ const { provider, userId } = await owner();
305
+ const state = getStateAdapter();
306
+ await state.connect();
307
+ const attempt = await withLock(state, `mcp-oauth-refresh:${userId}:${provider}`, async (lock) => {
308
+ const stored = await getMcpStoredOAuthCredentials(userId, provider);
309
+ const current = stored?.tokens;
310
+ if (!current) return Response.json({ error: "invalid_grant" }, { status: 400 });
311
+ if (current.refresh_token && current.refresh_token !== sentRefreshToken || sentAccessToken && current.access_token !== sentAccessToken) return Response.json(current);
312
+ const response = await fetchFn(input, init);
313
+ if (!response.ok) return response;
314
+ const tokens = await response.clone().json();
315
+ if (typeof tokens.access_token !== "string") return response;
316
+ await fenceLock(state, lock, REFRESH_LOCK_TTL_MS);
317
+ await putMcpStoredOAuthCredentials(userId, provider, {
318
+ ...stored,
319
+ tokens: {
320
+ ...current,
321
+ ...tokens,
322
+ refresh_token: typeof tokens.refresh_token === "string" ? tokens.refresh_token : sentRefreshToken
323
+ }
324
+ });
325
+ return response;
326
+ }, {
327
+ keepAlive: true,
328
+ ttlMs: REFRESH_LOCK_TTL_MS,
329
+ waitMs: REFRESH_WAIT_MS
330
+ });
331
+ if (!attempt.acquired) throw new Error(`Timed out waiting for the ${provider} MCP token refresh`);
332
+ return attempt.value;
333
+ });
334
+ }
87
335
  // src/chat/mcp/client.ts
88
336
  const MCP_CLIENT_INFO = {
89
337
  name: "junior-mcp-client",
@@ -206,9 +454,12 @@ var PluginMcpClient = class {
206
454
  const headers = mcp.headers ? resolvePluginHeaderEnvRefs(this.plugin.manifest.name, mcp.headers, "MCP header") : void 0;
207
455
  const sessionId = await this.getStoredTransportSessionId();
208
456
  this.lastAttemptedTransportSessionId = sessionId;
457
+ const loginProvider = this.options.authProvider;
458
+ const mcpLoginOwner = loginProvider?.mcpLoginOwner?.bind(loginProvider);
459
+ const providerFetch = mcpLoginOwner ? serializeMcpTokenRefresh(mcpLoginOwner, this.options.fetch) : this.options.fetch;
209
460
  const transport = new StreamableHTTPClientTransport(new URL(mcp.url), {
210
461
  ...headers ? { requestInit: { headers } } : void 0,
211
- fetch: fetchWithBoundedOAuthErrorBodies(this.options.fetch, (status) => {
462
+ fetch: fetchWithBoundedOAuthErrorBodies(providerFetch, (status) => {
212
463
  const store = this.providerStatusStore.getStore();
213
464
  if (store) store.status = status;
214
465
  }),
@@ -675,4 +926,4 @@ async function finishServiceAccountSignIn(input) {
675
926
  async function disconnectServiceAccount(plugin) {
676
927
  await deleteMcpServiceAccountCredentials(plugin.manifest.name);
677
928
  }
678
- export { getMcpProviderErrorAttributes as _, serviceAccountOnly as a, createMcpServiceAccountClientProvider as c, PluginMcpClient as d, McpProviderError as f, getMcpAwareTelemetryMessage as g, getMcpAwareErrorType as h, serviceAccountAllows as i, getMcpServiceAccountCredentials as l, McpToolError as m, finishServiceAccountSignIn as n, serviceAccountPlugins as o, McpServiceAccountRequiredError as p, getServiceAccountStatus as r, startServiceAccountSignIn as s, disconnectServiceAccount as t, McpAuthorizationRequiredError as u, toMcpProviderError as v };
929
+ export { McpProviderError as C, getMcpAwareTelemetryMessage as D, getMcpAwareErrorType as E, getMcpProviderErrorAttributes as O, putMcpStoredOAuthCredentials as S, McpToolError as T, getMcpServerSessionId as _, serviceAccountOnly as a, putMcpAuthSession as b, createMcpServiceAccountClientProvider as c, PluginMcpClient as d, deleteMcpAuthSession as f, getMcpAuthSession as g, deleteMcpStoredOAuthCredentials as h, serviceAccountAllows as i, toMcpProviderError as k, getMcpServiceAccountCredentials as l, deleteMcpServerSessionId as m, finishServiceAccountSignIn as n, serviceAccountPlugins as o, deleteMcpAuthSessionsForUserProvider as p, getServiceAccountStatus as r, startServiceAccountSignIn as s, disconnectServiceAccount as t, McpAuthorizationRequiredError as u, getMcpStoredOAuthCredentials as v, McpServiceAccountRequiredError as w, putMcpServerSessionId as x, patchMcpAuthSession as y };