@sentry/junior 0.301.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 (79) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-CRJHvCGg.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-H4YhvNBj.js → agent-runner-CY9RvsTX.js} +1380 -10601
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +91 -68
  8. package/dist/{app-HDZglaIu.d.ts → app-BpY3wtRP.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +66 -296
  11. package/dist/{background-compaction-queue-CNrZ3QcU.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  12. package/dist/{briefs-x6Mzwxmg.js → briefs-B3NG-pid.js} +2 -2
  13. package/dist/{catalog-runtime-BEY6EGRi.js → catalog-runtime-Dss0lSV6.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +4 -4
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-CmjhyqgB.js → config-CzeZiMKs.js} +2 -2
  22. package/dist/{connections-CfIRm0xv.js → connections-CDYhMfrs.js} +6 -6
  23. package/dist/{continue-in-slack-DPoABVkB.js → continue-in-slack-7Uf05ndC.js} +5 -6
  24. package/dist/{conversation-feed-CfpyFMHP.js → conversation-feed-Clf_cv0n.js} +1 -0
  25. package/dist/{conversation-privacy-0CM0V2qK.js → conversation-privacy-D9xnM5mK.js} +1 -1
  26. package/dist/{conversation-turn-C0sxyvS-.js → conversation-turn-D7SEZgTG.js} +15 -16
  27. package/dist/{credential-sync-tEMKZ_8M.js → credential-sync-DoD0gW-j.js} +13 -15
  28. package/dist/{db-Czra10QW.js → db-B-gtnNjr.js} +314 -5
  29. package/dist/{db-BdUHQhrC.d.ts → db-BdsCzytP.d.ts} +1 -1
  30. package/dist/{executor-D_023K0H.js → executor-DZg20EqU.js} +39 -4
  31. package/dist/install-t1KQyTUs.js +228 -0
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{state-CEbZuZD6.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  34. package/dist/{lineage-DmMIE0VL.js → lineage-C79GjoQr.js} +2 -2
  35. package/dist/{logging-DcjLDDqi.js → logging-C9oDAg4M.js} +7 -3
  36. package/dist/{message-C0JY9RJP.js → message-BLUCzJXN.js} +8 -8
  37. package/dist/{model-input-CBp-p24N.js → model-input-5jwNC45G.js} +3 -3
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +4 -3
  40. package/dist/{oauth-callback-server-BRq9QNhU.js → oauth-callback-server-BBl66vCb.js} +2 -2
  41. package/dist/{projection-CQNDOi82.js → projection-CIBwgD3s.js} +282 -64
  42. package/dist/{prompt-DLUB5m72.js → prompt-CRQbzp5e.js} +14 -4
  43. package/dist/queue-DtCDaIct.js +115 -0
  44. package/dist/{registry-Dj377ADs.js → registry-DdFQHZ_d.js} +1 -1
  45. package/dist/{resolve-DJkh9Fky.js → resolve-CdW4BdrK.js} +4 -229
  46. package/dist/{result-C8iIpDl1.js → result-oOMv1t4O.js} +9 -9
  47. package/dist/{runner-DZqrOy8C.js → runner-DqitLtm-.js} +8 -8
  48. package/dist/{sandbox-egress-signals-CGwH86S9.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  49. package/dist/{schema-CdZFn7Qd.d.ts → schema-BIFM-U1a.d.ts} +441 -30
  50. package/dist/{schema-DyHXiQKI.js → schema-DnVQepWP.js} +66 -29
  51. package/dist/{service-account-D6jGR4a1.js → service-account-B6mKAPVo.js} +3 -3
  52. package/dist/{service-account-suY004dx.js → service-account-CrZftRTb.js} +257 -6
  53. package/dist/{session-stop-BLmfFI3d.js → session-stop-DW63Z3kj.js} +543 -548
  54. package/dist/{skills-CmNG0dHb.js → skills-C16fz60Z.js} +2 -2
  55. package/dist/{slack-conversation-unfurl-Bty-DlHe.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  56. package/dist/{spawn-CNjkpXpk.js → spawn-D_RnFYfy.js} +6 -6
  57. package/dist/{stop-Bjy2-K4H.js → stop-7p1i08CY.js} +724 -106
  58. package/dist/{store-DmV4CoNr.js → store-C28I0CVW.js} +5 -5
  59. package/dist/{task-queue-AhG1tSXR.js → task-queue-BVUJbQ28.js} +3 -3
  60. package/dist/{task-runner-BMxZI3o7.js → task-runner-CWi8j7Z6.js} +6 -8
  61. package/dist/{thread-context-CXLnbg7g.js → thread-context-D3-yYUd0.js} +7 -7
  62. package/dist/{store-Epv6t4vV.js → turn-session-routing-BFMS9ATF.js} +381 -10
  63. package/dist/{turn-user-message-DsUZi9gn.js → turn-user-message-C3-O8Omt.js} +3 -3
  64. package/dist/{validation-DOz8X9BU.js → validation-BSFKUIb4.js} +1 -1
  65. package/dist/{version-CGMRmMPK.js → version-BHHXNi-0.js} +1 -1
  66. package/dist/version.js +1 -1
  67. package/dist/{viewer-H3EsMWtJ.js → viewer-B1SO21Qa.js} +3 -3
  68. package/dist/warmup-Bz9bzkzN.js +13927 -0
  69. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  70. package/dist/{worker-ClphajjD.js → worker-BspReIIK.js} +7 -7
  71. package/migrations/0108_conversation_embeddings.sql +13 -0
  72. package/migrations/meta/0108_snapshot.json +4688 -0
  73. package/migrations/meta/_journal.json +7 -0
  74. package/package.json +8 -6
  75. package/dist/adapter-CNjGEJO9.js +0 -303
  76. package/dist/reporting-window-DopzcOHh.js +0 -137
  77. package/dist/turn-session-routing-BD3-jJl7.js +0 -380
  78. package/dist/users-BxvYclQg.js +0 -424
  79. package/dist/warmup-CdU5hR49.js +0 -3715
@@ -1,9 +1,8 @@
1
1
  import { r as notificationScheduleSchema } from "./schedule-cP0AACm1.js";
2
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 { 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
3
  import "./automation-Cva5ZOwW.js";
6
- import "./conversation-feed-CfpyFMHP.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";
@@ -672,6 +671,69 @@ const cacheWarmingBreakerSchema = z.object({
672
671
  const cacheWarmingBreakerListSchema = z.object({ breakers: z.array(cacheWarmingBreakerSchema) }).strict();
673
672
  const cacheWarmingBreakerParamsSchema = z.object({ provider: z.string().regex(/^[a-z][a-z0-9-]*$/).max(64) }).strict();
674
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();
675
737
  // src/api/schema/review-item.ts
676
738
  const answerSchema = z.object({
677
739
  other: z.string().max(4e3).optional(),
@@ -830,31 +892,6 @@ const workspaceBodySchema = z.object({
830
892
  }).strict();
831
893
  const workspaceParamsSchema = z.object({ id: z.string().uuid() }).strict();
832
894
  const deleteWorkspaceResponseSchema = z.object({ deleted: z.literal(true) }).strict();
833
- // src/api/schema/reply-times.ts
834
- /** Reply times in the bins of the cache warming model. */
835
- const replyTimeHistogramSchema = z.object({
836
- bins: z.array(z.object({
837
- count: z.number().int().nonnegative(),
838
- endMs: z.number().int().positive(),
839
- startMs: z.number().int().nonnegative()
840
- }).strict()),
841
- /** Idle periods with no reply before the cache warming horizon. */
842
- noReply: z.number().int().nonnegative(),
843
- total: z.number().int().nonnegative()
844
- }).strict();
845
- /** Gap histogram of each cache warming segment, over all Conversations. */
846
- const replyTimeSegmentsReportSchema = z.object({
847
- generatedAt: z.string().datetime(),
848
- /**
849
- * Below this many gaps, the planner leans on the segment's `none`
850
- * segment, or does not warm a `none` segment.
851
- */
852
- minSamples: z.number().int().positive(),
853
- segments: z.array(z.object({
854
- histogram: replyTimeHistogramSchema,
855
- segment: z.string().min(1)
856
- }).strict())
857
- }).strict();
858
895
  // src/api/schema/stats.ts
859
896
  const statSchema = z.object({
860
897
  count: z.number().int().nonnegative(),
@@ -896,4 +933,4 @@ const versionsSchema = z.object({
896
933
  /** The viewer's rolling model spend. */
897
934
  spend: z.string().min(1)
898
935
  }).strict();
899
- export { connectionSchema as $, personalTokenListSchema as A, conversationSubscriptionResponseSchema as At, locationDetailReportSchema as B, attachmentUploadSchema as Bt, disconnectServiceAccountResponseSchema as C, CONVERSATION_OUTLINE_TEXT_LENGTH as Ct, startServiceAccountSignInResponseSchema as D, archiveDoneConversationsResponseSchema as Dt, serviceAccountSchema as E, archiveConversationResponseSchema as Et, actorProfileReportSchema as F, reorderPinnedConversationsBodySchema as Ft, activitySixHours as G, locationParamsSchema as H, avatarParamsSchema as I, reorderPinnedConversationsResponseSchema as It, pushSubscriptionBodySchema as J, dailyConversationActivitySchema as K, personParamsSchema as L, conversationCatchUpBodySchema as Lt, personalTokenParamsSchema as M, conversationDeliveryResponseSchema as Mt, revokePersonalTokenResponseSchema as N, pinConversationBodySchema as Nt, createPersonalTokenBodySchema as O, conversationAutoArchiveSchema as Ot, actorDirectoryReportSchema as P, pinConversationResponseSchema as Pt, connectionParamsSchema as Q, personalSpendReportSchema as R, conversationCatchUpSchema as Rt, closeCacheWarmingBreakerResponseSchema as S, conversationStatsReportSchema as St, serviceAccountParamsSchema as T, archiveConversationBodySchema as Tt, activityDays as U, locationDirectoryReportSchema as V, createAttachmentUploadBodySchema as Vt, activityHours as W, testNotificationResponseSchema as X, pushSubscriptionDeleteBodySchema as Y, connectionListSchema as Z, reviewItemParamsSchema as _, attachObjectLinkBodySchema as _t, replyTimeSegmentsReportSchema as a, codeOverviewReportSchema as at, cacheWarmingBreakerListSchema as b, objectLinksReportSchema as bt, workspaceBodySchema as c, codeRepositoryReportSchema as ct, workspaceRepoSchema as d, conversationWatchesReportSchema as dt, disconnectConnectionResponseSchema as et, workspaceSchema as f, conversationChildAgentSchema as ft, reviewItemListSchema as g, MAX_OBJECT_LINKS as gt, reviewItemListQuerySchema as h, continueConversationInSlackResponseSchema as ht, statsReportSchema as i, codeChangeSummarySchema as it, personalTokenMetadataSchema as j, conversationDeliveryBodySchema as jt, createdPersonalTokenSchema as k, conversationSubscriptionBodySchema as kt, workspaceListSchema as l, codeRepositorySummarySchema as lt, reviewItemCountSchema as m, continueConversationInSlackBodySchema as mt, versionsSchema as n, codeActivityDaySchema as nt, baselineSnapshotSchema as o, codePersonReportSchema as ot, reviewItemActionSchema as p, conversationChildAgentsReportSchema as pt, notificationSettingsSchema as q, statSchema as r, codeChangeSummaryReportSchema as rt, deleteWorkspaceResponseSchema as s, codeRepositoryParamsSchema as st, versionsQuerySchema as t, startConnectionResponseSchema as tt, workspaceParamsSchema as u, conversationWatchSchema as ut, reviewItemSchema as v, attachObjectLinkResponseSchema as vt, serviceAccountListSchema as w, conversationOutlineSchema as wt, cacheWarmingBreakerParamsSchema as x, stopConversationTurnResponseSchema as xt, reviewItemWaitingConversationsSchema as y, objectLinksQuerySchema as yt, locationActivityDayReportSchema as z, attachmentUploadParamsSchema as zt };
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-CNjGEJO9.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BEY6EGRi.js";
3
- import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-suY004dx.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-DcjLDDqi.js";
2
- import { c as fenceLock, l as withLock, o as MUTATION_LOCK_TTL_MS, r as getStateAdapter } from "./adapter-CNjGEJO9.js";
3
- import { c as fetchWithBoundedOAuthErrorBodies, i as resolvePluginHeaderEnvRefs } from "./registry-Dj377ADs.js";
4
- import { n as readEncryptedState, t as createEncryptedState } from "./state-CEbZuZD6.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 };