@sentry/junior 0.312.0 → 0.314.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 (115) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +340 -106
  11. package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -171
  14. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
  15. package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
  16. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-CJGfNTdn.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
  29. package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
  33. package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
  34. package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
  35. package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
  42. package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
  45. package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
  46. package/dist/{model-input--TrP9hYV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  54. package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
  55. package/dist/result-D090hxr5.js +402 -0
  56. package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
  57. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  58. package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
  59. package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
  60. package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
  61. package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
  62. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  63. package/dist/spawn-DRjdzh3R.js +46 -0
  64. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
  65. package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
  66. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
  67. package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
  68. package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
  69. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  70. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  71. package/dist/user-customization-B27StpVQ.js +9 -0
  72. package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
  73. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
  74. package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
  77. package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
  78. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  79. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  80. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  81. package/migrations/0161_agent_config_backfill.sql +34 -0
  82. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  83. package/migrations/0163_pg_trgm.sql +2 -0
  84. package/migrations/0164_search_indexes.sql +4 -0
  85. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  86. package/migrations/0166_memory_prefix_index.sql +1 -0
  87. package/migrations/0167_todo_search_indexes.sql +2 -0
  88. package/migrations/0168_todo_inbox_items.sql +4 -0
  89. package/migrations/0169_drop_code_urls.sql +2 -0
  90. package/migrations/meta/0158_snapshot.json +6515 -0
  91. package/migrations/meta/0159_snapshot.json +6515 -0
  92. package/migrations/meta/0160_snapshot.json +6515 -0
  93. package/migrations/meta/0161_snapshot.json +6278 -0
  94. package/migrations/meta/0162_snapshot.json +6404 -0
  95. package/migrations/meta/0163_snapshot.json +6404 -0
  96. package/migrations/meta/0164_snapshot.json +6466 -0
  97. package/migrations/meta/0165_snapshot.json +6466 -0
  98. package/migrations/meta/0166_snapshot.json +6494 -0
  99. package/migrations/meta/0167_snapshot.json +6525 -0
  100. package/migrations/meta/0168_snapshot.json +6525 -0
  101. package/migrations/meta/0169_snapshot.json +6513 -0
  102. package/migrations/meta/_journal.json +84 -0
  103. package/package.json +9 -18
  104. package/skills/design-automation-skill/SKILL.md +2 -3
  105. package/dist/actor-BsBdxDXQ.js +0 -208
  106. package/dist/child-message-DcsritGf.js +0 -179
  107. package/dist/conversation-privacy-L4ja1_W6.js +0 -189
  108. package/dist/executor-SCub-fAq.js +0 -1860
  109. package/dist/fan-out-Cod-yEHG.js +0 -10
  110. package/dist/ingest-BDf3D50j.js +0 -3836
  111. package/dist/result-DcvEOe1r.js +0 -574
  112. package/dist/result-event-type-BdIJuZxg.js +0 -48
  113. package/dist/service-account-Ts4ulcrV.js +0 -931
  114. package/dist/spawn-vxAarlX5.js +0 -73
  115. package/dist/state-C1P3_Ywk.js +0 -161
@@ -1,931 +0,0 @@
1
- import { b as setSpanAttributes, h as logWarn } from "./logging-dQ9ZRGQ8.js";
2
- import { i as resolvePluginHeaderEnvRefs, l as fetchWithBoundedOAuthErrorBodies } from "./registry-CZOzddwu.js";
3
- import { i as getStateAdapter } from "./adapter-iIq7ihf7.js";
4
- import { I as MUTATION_LOCK_TTL_MS, R as fenceLock, n as botConfig, z as withLock } from "./config-kXB2Y5tl.js";
5
- import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-C1P3_Ywk.js";
6
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
7
- import * as z from "zod";
8
- import { AsyncLocalStorage } from "node:async_hooks";
9
- import { randomUUID } from "node:crypto";
10
- import { destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
11
- import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
12
- import { Client } from "@modelcontextprotocol/sdk/client";
13
- import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
14
- // src/chat/mcp/errors.ts
15
- /** Safe failure at an MCP network or OAuth boundary. */
16
- var McpProviderError = class extends Error {
17
- phase;
18
- provider;
19
- missingSession;
20
- resourceHost;
21
- status;
22
- constructor(details) {
23
- super(`MCP provider ${details.phase.replace("_", " ")} failed`);
24
- this.name = "McpProviderError";
25
- this.phase = details.phase;
26
- this.provider = details.provider;
27
- this.missingSession = details.missingSession;
28
- this.resourceHost = details.resourceHost;
29
- this.status = details.status;
30
- }
31
- };
32
- function providerStatus(error) {
33
- if (!error || typeof error !== "object") return;
34
- const value = error;
35
- const status = typeof value.status === "number" ? value.status : typeof value.code === "number" ? value.code : void 0;
36
- return status !== void 0 && status >= 100 && status <= 599 ? status : void 0;
37
- }
38
- /** Replace an external MCP failure without retaining its provider-controlled cause. */
39
- function toMcpProviderError(error, details) {
40
- if (error instanceof McpProviderError) return error;
41
- return new McpProviderError({
42
- ...details,
43
- status: details.status ?? providerStatus(error)
44
- });
45
- }
46
- /** Return safe MCP provider fields for logs and spans. */
47
- function getMcpProviderErrorAttributes(error) {
48
- if (!(error instanceof McpProviderError)) return {};
49
- return {
50
- "app.credential.provider": error.provider,
51
- "app.mcp.error.phase": error.phase,
52
- ...error.status !== void 0 ? { "http.response.status_code": error.status } : void 0,
53
- ...error.resourceHost ? { "server.address": error.resourceHost } : void 0
54
- };
55
- }
56
- /** Thrown when an MCP failure should be returned as a model-visible tool error. */
57
- var McpToolError = class extends Error {
58
- constructor(message) {
59
- super(message);
60
- this.name = "McpToolError";
61
- }
62
- };
63
- /**
64
- * Thrown when a plugin uses only its service account and no Admin has
65
- * connected it. The model can tell the person to ask an Admin.
66
- */
67
- var McpServiceAccountRequiredError = class extends McpToolError {
68
- provider;
69
- constructor(provider, displayName) {
70
- super(`${displayName} is not available yet. This app uses a shared ${displayName} account for everyone, and an admin must connect it on the dashboard Admin page.`);
71
- this.name = "McpServiceAccountRequiredError";
72
- this.provider = provider;
73
- }
74
- };
75
- /** Return the OpenTelemetry error.type value for MCP-aware tool failures. */
76
- function getMcpAwareErrorType(error, fallback) {
77
- if (error instanceof McpToolError) return "tool_error";
78
- if (error instanceof McpProviderError) return "mcp_provider_error";
79
- return error instanceof Error ? error.name : fallback;
80
- }
81
- /** Return the display-safe error message for MCP-aware tool failures. */
82
- function getMcpAwareErrorMessage(error) {
83
- return error instanceof Error ? error.message : String(error);
84
- }
85
- /** Return an error message safe for logs and span attributes. */
86
- function getMcpAwareTelemetryMessage(error, _privacy) {
87
- if (error instanceof McpToolError) return "MCP tool call failed";
88
- if (error instanceof McpProviderError) return error.message;
89
- return getMcpAwareErrorMessage(error);
90
- }
91
- // src/chat/mcp/auth-store.ts
92
- const MCP_AUTH_SESSION_PREFIX = "junior:mcp_oauth_attempt:v2";
93
- const MCP_AUTH_CREDENTIALS_PREFIX = "junior:mcp_auth_credentials";
94
- const MCP_AUTH_SESSION_INDEX_PREFIX = "junior:mcp_oauth_attempt_index:v2";
95
- const MCP_SERVER_SESSION_PREFIX = "junior:mcp_server_session";
96
- const MCP_AUTH_SESSION_TTL_MS = 864e5;
97
- const MCP_AUTH_CREDENTIALS_TTL_MS = 2592e6;
98
- const MCP_SERVER_SESSION_TTL_MS = 864e5;
99
- function sessionKey(authSessionId) {
100
- return `${MCP_AUTH_SESSION_PREFIX}:${authSessionId}`;
101
- }
102
- function credentialsKey(userId, provider) {
103
- return `${MCP_AUTH_CREDENTIALS_PREFIX}:${userId}:${provider}`;
104
- }
105
- function sessionIndexKey(userId, provider) {
106
- return `${MCP_AUTH_SESSION_INDEX_PREFIX}:${userId}:${provider}`;
107
- }
108
- function serverSessionKey(userId, provider) {
109
- return `${MCP_SERVER_SESSION_PREFIX}:${userId}:${provider}`;
110
- }
111
- function parseSessionIndex(value) {
112
- if (typeof value !== "string") return [];
113
- try {
114
- const parsed = JSON.parse(value);
115
- if (!Array.isArray(parsed)) return [];
116
- return [...new Set(parsed.filter((id) => typeof id === "string"))];
117
- } catch {
118
- return [];
119
- }
120
- }
121
- const optionalStoredString = z.string().optional().catch(void 0);
122
- const mcpAuthSessionSchema = z.object({
123
- schemaVersion: z.literal(2),
124
- authSessionId: z.string(),
125
- provider: z.string(),
126
- userId: z.string(),
127
- conversationId: z.string(),
128
- destination: destinationSchema.optional(),
129
- source: sourceSchema.optional(),
130
- sessionId: z.string(),
131
- userMessage: z.string(),
132
- channelId: optionalStoredString,
133
- threadTs: optionalStoredString,
134
- toolChannelId: optionalStoredString,
135
- configuration: z.record(z.string(), z.unknown()).optional().catch(void 0),
136
- authorizationUrl: optionalStoredString,
137
- codeVerifier: optionalStoredString,
138
- createdAtMs: z.number(),
139
- updatedAtMs: z.number()
140
- });
141
- function parseMcpAuthSession(value) {
142
- const parsed = mcpAuthSessionSchema.safeParse(value);
143
- return parsed.success ? parsed.data : void 0;
144
- }
145
- const serverSessionSchema = z.object({
146
- sessionId: z.string(),
147
- updatedAtMs: z.number()
148
- });
149
- function parseServerSession(value) {
150
- if (typeof value !== "string") return;
151
- try {
152
- const parsed = serverSessionSchema.safeParse(JSON.parse(value));
153
- return parsed.success ? parsed.data : void 0;
154
- } catch {
155
- return;
156
- }
157
- }
158
- const storedOAuthClientInformationSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
159
- const storedOAuthDiscoveryStateSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
160
- const storedOAuthTokensSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
161
- const storedCredentialsSchema = z.object({
162
- clientInformation: storedOAuthClientInformationSchema$1.optional().catch(void 0),
163
- discoveryState: storedOAuthDiscoveryStateSchema$1.optional().catch(void 0),
164
- tokens: storedOAuthTokensSchema$1.optional().catch(void 0)
165
- });
166
- function parseStoredCredentials(value) {
167
- try {
168
- const parsed = storedCredentialsSchema.safeParse(typeof value === "string" ? JSON.parse(value) : value);
169
- return parsed.success ? parsed.data : void 0;
170
- } catch {
171
- return;
172
- }
173
- }
174
- async function readMcpAuthSession(stateAdapter, authSessionId) {
175
- const stored = await readEncryptedState(stateAdapter, sessionKey(authSessionId));
176
- if (stored?.stale && typeof stored.value === "string") try {
177
- return JSON.parse(stored.value);
178
- } catch {
179
- return;
180
- }
181
- return stored?.value;
182
- }
183
- async function getConnectedStateAdapter() {
184
- const stateAdapter = getStateAdapter();
185
- await stateAdapter.connect();
186
- return stateAdapter;
187
- }
188
- async function getMcpAuthSession(authSessionId) {
189
- return parseMcpAuthSession(await readMcpAuthSession(await getConnectedStateAdapter(), authSessionId));
190
- }
191
- async function putMcpAuthSession(session, ttlMs = MCP_AUTH_SESSION_TTL_MS) {
192
- const stateAdapter = await getConnectedStateAdapter();
193
- await createEncryptedState(stateAdapter).set(sessionKey(session.authSessionId), session, ttlMs);
194
- const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(session.userId, session.provider)));
195
- if (!nextIndex.includes(session.authSessionId)) nextIndex.push(session.authSessionId);
196
- await stateAdapter.set(sessionIndexKey(session.userId, session.provider), JSON.stringify(nextIndex), ttlMs);
197
- }
198
- async function patchMcpAuthSession(authSessionId, patch) {
199
- const current = await getMcpAuthSession(authSessionId);
200
- if (!current) throw new Error(`Unknown MCP auth session: ${authSessionId}`);
201
- const next = {
202
- ...current,
203
- ...patch,
204
- schemaVersion: 2,
205
- authSessionId: current.authSessionId,
206
- provider: current.provider,
207
- userId: current.userId,
208
- conversationId: current.conversationId,
209
- ...current.destination ? { destination: current.destination } : void 0,
210
- sessionId: current.sessionId,
211
- userMessage: current.userMessage,
212
- createdAtMs: current.createdAtMs,
213
- updatedAtMs: Date.now()
214
- };
215
- await putMcpAuthSession(next);
216
- return next;
217
- }
218
- async function deleteMcpAuthSession(authSessionId) {
219
- const stateAdapter = await getConnectedStateAdapter();
220
- const current = parseMcpAuthSession(await readMcpAuthSession(stateAdapter, authSessionId));
221
- await stateAdapter.delete(sessionKey(authSessionId));
222
- if (!current) return;
223
- const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(current.userId, current.provider))).filter((id) => id !== authSessionId);
224
- if (nextIndex.length > 0) {
225
- await stateAdapter.set(sessionIndexKey(current.userId, current.provider), JSON.stringify(nextIndex), MCP_AUTH_SESSION_TTL_MS);
226
- return;
227
- }
228
- await stateAdapter.delete(sessionIndexKey(current.userId, current.provider));
229
- }
230
- async function deleteMcpAuthSessionsForUserProvider(userId, provider) {
231
- const stateAdapter = await getConnectedStateAdapter();
232
- const indexKey = sessionIndexKey(userId, provider);
233
- const authSessionIds = parseSessionIndex(await stateAdapter.get(indexKey));
234
- await mapBounded(authSessionIds, (authSessionId) => stateAdapter.delete(sessionKey(authSessionId)));
235
- await stateAdapter.delete(indexKey);
236
- }
237
- async function getMcpStoredOAuthCredentials(userId, provider) {
238
- const stateAdapter = await getConnectedStateAdapter();
239
- const stored = parseStoredCredentials((await readEncryptedState(stateAdapter, credentialsKey(userId, provider)))?.value);
240
- if (stored) return stored;
241
- const legacyUserId = await findLegacyWebActorUserId(userId);
242
- if (!legacyUserId) return void 0;
243
- const legacyKey = credentialsKey(legacyUserId, provider);
244
- const legacy = parseStoredCredentials((await readEncryptedState(stateAdapter, legacyKey))?.value);
245
- if (!legacy) return void 0;
246
- await putMcpStoredOAuthCredentials(userId, provider, legacy);
247
- await stateAdapter.delete(legacyKey);
248
- return legacy;
249
- }
250
- async function putMcpStoredOAuthCredentials(userId, provider, value, ttlMs = MCP_AUTH_CREDENTIALS_TTL_MS) {
251
- const stateAdapter = await getConnectedStateAdapter();
252
- await createEncryptedState(stateAdapter).set(credentialsKey(userId, provider), value, ttlMs);
253
- }
254
- async function deleteMcpStoredOAuthCredentials(userId, provider) {
255
- const stateAdapter = await getConnectedStateAdapter();
256
- await stateAdapter.delete(credentialsKey(userId, provider));
257
- const legacyUserId = await findLegacyWebActorUserId(userId);
258
- if (legacyUserId) await stateAdapter.delete(credentialsKey(legacyUserId, provider));
259
- }
260
- async function getMcpServerSessionId(userId, provider) {
261
- return parseServerSession(await (await getConnectedStateAdapter()).get(serverSessionKey(userId, provider)))?.sessionId;
262
- }
263
- async function putMcpServerSessionId(userId, provider, sessionId, ttlMs = MCP_SERVER_SESSION_TTL_MS) {
264
- await (await getConnectedStateAdapter()).set(serverSessionKey(userId, provider), JSON.stringify({
265
- sessionId,
266
- updatedAtMs: Date.now()
267
- }), ttlMs);
268
- }
269
- async function deleteMcpServerSessionId(userId, provider) {
270
- await (await getConnectedStateAdapter()).delete(serverSessionKey(userId, provider));
271
- }
272
- // src/chat/mcp/token-refresh.ts
273
- /**
274
- * One MCP token refresh at a time for each person and provider.
275
- *
276
- * Providers such as Notion rotate the refresh token on each refresh and
277
- * revoke the whole grant when a retired refresh token comes back. A Turn
278
- * and a link card read can both find an expired access token at once, so
279
- * every refresh of a stored person login runs under one lock. A caller
280
- * that waited gets the tokens that the first caller saved, and its retired
281
- * refresh token never reaches the provider.
282
- */
283
- const REFRESH_LOCK_TTL_MS = 3e4;
284
- const REFRESH_WAIT_MS = 3e4;
285
- function refreshTokenOf(body) {
286
- const params = body instanceof URLSearchParams ? body : typeof body === "string" ? new URLSearchParams(body) : void 0;
287
- return params?.get("grant_type") === "refresh_token" ? params.get("refresh_token") ?? void 0 : void 0;
288
- }
289
- /**
290
- * Wrap the fetch of an MCP client so that each refresh-token request for
291
- * this login runs under the shared lock. Other requests pass through.
292
- */
293
- function serializeMcpTokenRefresh(owner, fetchFn = globalThis.fetch) {
294
- let sentAccessToken;
295
- return async (input, init) => {
296
- const sentRefreshToken = refreshTokenOf(init?.body);
297
- if (!sentRefreshToken) {
298
- const authorization = new Headers(init?.headers).get("authorization");
299
- if (authorization) sentAccessToken = authorization.replace(/^Bearer\s+/i, "");
300
- return await fetchFn(input, init);
301
- }
302
- const { provider, userId } = await owner();
303
- const state = getStateAdapter();
304
- await state.connect();
305
- const attempt = await withLock(state, `mcp-oauth-refresh:${userId}:${provider}`, async (lock) => {
306
- const stored = await getMcpStoredOAuthCredentials(userId, provider);
307
- const current = stored?.tokens;
308
- if (!current) return Response.json({ error: "invalid_grant" }, { status: 400 });
309
- if (current.refresh_token && current.refresh_token !== sentRefreshToken || sentAccessToken && current.access_token !== sentAccessToken) return Response.json(current);
310
- const response = await fetchFn(input, init);
311
- if (!response.ok) return response;
312
- const tokens = await response.clone().json();
313
- if (typeof tokens["access_token"] !== "string") return response;
314
- await fenceLock(state, lock, REFRESH_LOCK_TTL_MS);
315
- await putMcpStoredOAuthCredentials(userId, provider, {
316
- ...stored,
317
- tokens: {
318
- ...current,
319
- ...tokens,
320
- refresh_token: typeof tokens["refresh_token"] === "string" ? tokens["refresh_token"] : sentRefreshToken
321
- }
322
- });
323
- return response;
324
- }, {
325
- keepAlive: true,
326
- ttlMs: REFRESH_LOCK_TTL_MS,
327
- waitMs: REFRESH_WAIT_MS
328
- });
329
- if (!attempt.acquired) throw new Error(`Timed out waiting for the ${provider} MCP token refresh`);
330
- return attempt.value;
331
- };
332
- }
333
- // src/chat/mcp/client.ts
334
- const MCP_CLIENT_INFO = {
335
- name: "junior-mcp-client",
336
- version: "1.0.0"
337
- };
338
- const MCP_TOOLS_CALL_METHOD = "tools/call";
339
- function getDefaultPort(url) {
340
- if (url.protocol === "https:") return 443;
341
- if (url.protocol === "http:") return 80;
342
- }
343
- function getMcpNetworkAttributes(url) {
344
- const port = url.port ? Number(url.port) : getDefaultPort(url);
345
- return {
346
- "server.address": url.hostname,
347
- ...port !== void 0 ? { "server.port": port } : void 0,
348
- ...url.protocol === "http:" || url.protocol === "https:" ? {
349
- "network.protocol.name": "http",
350
- "network.transport": "tcp"
351
- } : void 0
352
- };
353
- }
354
- var McpAuthorizationRequiredError = class extends Error {
355
- provider;
356
- constructor(provider, message) {
357
- super(message);
358
- this.name = "McpAuthorizationRequiredError";
359
- this.provider = provider;
360
- }
361
- };
362
- function isMissingSessionError(error) {
363
- return error instanceof StreamableHTTPError && (error.code === 404 || /Session not found/i.test(error.message));
364
- }
365
- var PluginMcpClient = class {
366
- client;
367
- clientPromise;
368
- lastAttemptedTransportSessionId;
369
- providerStatusStore = new AsyncLocalStorage();
370
- transport;
371
- listedTools;
372
- resourceHost;
373
- plugin;
374
- options;
375
- constructor(plugin, options = {}) {
376
- this.plugin = plugin;
377
- this.options = options;
378
- const url = plugin.manifest.mcp?.url;
379
- this.resourceHost = url ? new URL(url).hostname : void 0;
380
- }
381
- async listTools() {
382
- if (this.listedTools) return [...this.listedTools];
383
- return await this.withSessionRecovery(async () => {
384
- const client = await this.getClient();
385
- const discovered = [];
386
- const seen = /* @__PURE__ */ new Set();
387
- let cursor;
388
- do {
389
- const result = await this.wrapAuth(() => client.listTools(cursor ? { cursor } : void 0), "list_tools");
390
- await this.syncTransportSessionId();
391
- for (const tool of result.tools) {
392
- if (seen.has(tool.name)) continue;
393
- seen.add(tool.name);
394
- discovered.push(tool);
395
- }
396
- cursor = result.nextCursor;
397
- } while (cursor);
398
- this.listedTools = discovered.sort((left, right) => left.name.localeCompare(right.name));
399
- return [...this.listedTools];
400
- });
401
- }
402
- async callTool(name, args, signal) {
403
- return await this.withSessionRecovery(async () => {
404
- const client = await this.getClient();
405
- const mcp = this.plugin.manifest.mcp;
406
- if (mcp) {
407
- const url = new URL(mcp.url);
408
- setSpanAttributes({
409
- "mcp.method.name": MCP_TOOLS_CALL_METHOD,
410
- "gen_ai.operation.name": "execute_tool",
411
- ...this.transport?.sessionId ? { "mcp.session.id": this.transport.sessionId } : void 0,
412
- ...this.transport?.protocolVersion ? { "mcp.protocol.version": this.transport.protocolVersion } : void 0,
413
- ...getMcpNetworkAttributes(url)
414
- });
415
- }
416
- const result = await this.wrapAuth(() => client.callTool({
417
- name,
418
- arguments: args ?? {}
419
- }, void 0, signal ? { signal } : void 0), "call_tool");
420
- await this.syncTransportSessionId();
421
- return result;
422
- });
423
- }
424
- async close() {
425
- await this.disposeClient();
426
- }
427
- async withSessionRecovery(operation) {
428
- try {
429
- return await operation();
430
- } catch (error) {
431
- await this.syncTransportSessionId();
432
- if (!await this.shouldResetMissingSession(error)) throw error;
433
- await this.clearStoredTransportSessionId();
434
- await this.cleanupClientAfterFailure();
435
- return await operation();
436
- }
437
- }
438
- async getClient() {
439
- if (this.client) return this.client;
440
- if (this.clientPromise) return await this.clientPromise;
441
- const clientPromise = this.connectClient();
442
- this.clientPromise = clientPromise;
443
- try {
444
- return await clientPromise;
445
- } finally {
446
- if (this.clientPromise === clientPromise) this.clientPromise = void 0;
447
- }
448
- }
449
- async connectClient() {
450
- const mcp = this.plugin.manifest.mcp;
451
- if (!mcp) throw new Error(`Plugin "${this.plugin.manifest.name}" does not declare MCP config`);
452
- const headers = mcp.headers ? resolvePluginHeaderEnvRefs(this.plugin.manifest.name, mcp.headers, "MCP header") : void 0;
453
- const sessionId = await this.getStoredTransportSessionId();
454
- this.lastAttemptedTransportSessionId = sessionId;
455
- const loginProvider = this.options.authProvider;
456
- const mcpLoginOwner = loginProvider?.mcpLoginOwner?.bind(loginProvider);
457
- const providerFetch = mcpLoginOwner ? serializeMcpTokenRefresh(mcpLoginOwner, this.options.fetch) : this.options.fetch;
458
- const transport = new StreamableHTTPClientTransport(new URL(mcp.url), {
459
- ...headers ? { requestInit: { headers } } : void 0,
460
- fetch: fetchWithBoundedOAuthErrorBodies(providerFetch, (status) => {
461
- const store = this.providerStatusStore.getStore();
462
- if (store) store.status = status;
463
- }),
464
- ...this.options.authProvider ? { authProvider: this.options.authProvider } : void 0,
465
- ...sessionId ? { sessionId } : void 0
466
- });
467
- const client = new Client(MCP_CLIENT_INFO, { capabilities: {} });
468
- this.transport = transport;
469
- try {
470
- await this.wrapAuth(() => client.connect(transport), "connect");
471
- this.client = client;
472
- await this.syncTransportSessionId();
473
- return client;
474
- } catch (error) {
475
- await this.syncTransportSessionId();
476
- await this.cleanupClientAfterFailure();
477
- throw error;
478
- }
479
- }
480
- async wrapAuth(operation, phase) {
481
- const store = {};
482
- return await this.providerStatusStore.run(store, async () => {
483
- try {
484
- return await operation();
485
- } catch (error) {
486
- if (error instanceof McpAuthorizationRequiredError) throw error;
487
- if (error instanceof UnauthorizedError) throw new McpAuthorizationRequiredError(this.plugin.manifest.name, `MCP authorization required for plugin "${this.plugin.manifest.name}"`);
488
- throw toMcpProviderError(error, {
489
- phase,
490
- provider: this.plugin.manifest.name,
491
- missingSession: isMissingSessionError(error) || void 0,
492
- resourceHost: this.resourceHost,
493
- status: store.status
494
- });
495
- }
496
- });
497
- }
498
- async shouldResetMissingSession(error) {
499
- if (!(error instanceof McpProviderError && error.missingSession || isMissingSessionError(error))) return false;
500
- return Boolean(this.transport?.sessionId ?? this.lastAttemptedTransportSessionId ?? await this.getStoredTransportSessionId());
501
- }
502
- resetClientState() {
503
- const transport = this.transport;
504
- this.listedTools = void 0;
505
- this.transport = void 0;
506
- this.client = void 0;
507
- this.clientPromise = void 0;
508
- return transport;
509
- }
510
- async cleanupClientAfterFailure() {
511
- const transport = this.resetClientState();
512
- if (!transport) return;
513
- try {
514
- await transport.close();
515
- } catch {}
516
- }
517
- async disposeClient() {
518
- const transport = this.resetClientState();
519
- if (transport) try {
520
- await transport.close();
521
- } catch (error) {
522
- throw toMcpProviderError(error, {
523
- phase: "close",
524
- provider: this.plugin.manifest.name,
525
- resourceHost: this.resourceHost
526
- });
527
- }
528
- }
529
- async getStoredTransportSessionId() {
530
- return await this.options.authProvider?.getMcpServerSessionId?.();
531
- }
532
- async clearStoredTransportSessionId() {
533
- const provider = this.options.authProvider;
534
- this.lastAttemptedTransportSessionId = void 0;
535
- await provider?.saveMcpServerSessionId?.(void 0);
536
- }
537
- async syncTransportSessionId() {
538
- const provider = this.options.authProvider;
539
- const sessionId = this.transport?.sessionId;
540
- if (!provider?.saveMcpServerSessionId || !sessionId) return;
541
- this.lastAttemptedTransportSessionId = sessionId;
542
- await provider.saveMcpServerSessionId(sessionId);
543
- }
544
- };
545
- // src/chat/mcp/service-account.ts
546
- /**
547
- * MCP service account credentials.
548
- *
549
- * This is the MCP surface of a plugin's service account. See
550
- * `@/chat/credentials/service-account` for the credential order and the
551
- * policy. An Admin connects the account from the dashboard Admin page, or
552
- * with `junior service-account connect <plugin>`. The credential stays on
553
- * the host. The sandbox and the model never get it.
554
- */
555
- const SERVICE_ACCOUNT_KEY_PREFIX = "junior:mcp_service_account";
556
- const SIGN_IN_KEY_PREFIX = "junior:mcp_service_account_sign_in";
557
- const SIGN_IN_TTL_MS = 6e5;
558
- const UPDATE_LOCK_WAIT_MS = 5e3;
559
- function serviceAccountKey(provider) {
560
- return `${SERVICE_ACCOUNT_KEY_PREFIX}:${provider}`;
561
- }
562
- function updateLockKey(provider) {
563
- return `${serviceAccountKey(provider)}:update`;
564
- }
565
- const storedOAuthClientInformationSchema = z.custom((value) => typeof value === "object" && value !== null);
566
- const storedOAuthDiscoveryStateSchema = z.custom((value) => typeof value === "object" && value !== null);
567
- const storedOAuthTokensSchema = z.custom((value) => typeof value === "object" && value !== null);
568
- const credentialsSchema = z.object({
569
- clientInformation: storedOAuthClientInformationSchema,
570
- connectedAtMs: z.number(),
571
- connectedBy: z.string().optional().catch(void 0),
572
- discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
573
- redirectUrl: z.string(),
574
- tokens: storedOAuthTokensSchema
575
- });
576
- function parseCredentials(value) {
577
- try {
578
- const parsed = credentialsSchema.safeParse(typeof value === "string" ? JSON.parse(value) : value);
579
- return parsed.success ? parsed.data : void 0;
580
- } catch {
581
- return;
582
- }
583
- }
584
- /** Read the connected service account for one plugin, if any. */
585
- async function getMcpServiceAccountCredentials(provider) {
586
- const state = getStateAdapter();
587
- const stored = await readEncryptedState(state, serviceAccountKey(provider));
588
- const credentials = parseCredentials(stored?.value);
589
- if (credentials && stored?.stale) await saveStaleCredentials(provider);
590
- return credentials;
591
- }
592
- /**
593
- * Save stale credentials again with the active key. It runs only when the
594
- * update lock is free, so it cannot write back a refresh token that an
595
- * update replaced.
596
- */
597
- async function saveStaleCredentials(provider) {
598
- const state = getStateAdapter();
599
- await withLock(state, updateLockKey(provider), async (lock) => {
600
- const key = serviceAccountKey(provider);
601
- const current = await readEncryptedState(state, key);
602
- const credentials = parseCredentials(current?.value);
603
- if (!current?.stale || !credentials) return;
604
- await fenceLock(state, lock);
605
- await putMcpServiceAccountCredentials(provider, credentials);
606
- }, { ttlMs: MUTATION_LOCK_TTL_MS });
607
- }
608
- /** Save the service account for one plugin. It does not expire. */
609
- async function putMcpServiceAccountCredentials(provider, credentials) {
610
- await createEncryptedState(getStateAdapter()).set(serviceAccountKey(provider), credentials);
611
- }
612
- /** Remove the service account for one plugin. The provider grant stays until the provider revokes it. */
613
- async function deleteMcpServiceAccountCredentials(provider) {
614
- await getStateAdapter().delete(serviceAccountKey(provider));
615
- }
616
- function clientMetadata(redirectUrl) {
617
- return {
618
- client_name: `${botConfig.userName} MCP Service Account`,
619
- redirect_uris: [redirectUrl],
620
- grant_types: ["authorization_code", "refresh_token"],
621
- response_types: ["code"],
622
- token_endpoint_auth_method: "none"
623
- };
624
- }
625
- function reconnectMessage(provider) {
626
- return `The ${provider} service account is not authorized anymore. An admin must run \`junior service-account connect ${provider}\`.`;
627
- }
628
- /**
629
- * Build the OAuth client provider for a connected service account.
630
- *
631
- * It refreshes tokens like a user connection but never starts a new sign-in.
632
- * Many turns share this account, so it reads the store on each request and
633
- * writes each change under a lock. When the provider rejects a refresh token
634
- * that another turn already replaced, it retries with the stored one. It
635
- * deletes the stored grant only when the provider rejected the stored token
636
- * itself, and then throws `McpAuthorizationRequiredError` so the tool manager
637
- * can fall back to Actor auth or report the missing account. A refresh that
638
- * fails for another reason, such as a network error, keeps the account.
639
- */
640
- function createMcpServiceAccountClientProvider(provider, connected) {
641
- let lastRefreshToken = connected.tokens.refresh_token;
642
- let tokensRejected = false;
643
- const withStoreLock = async (run) => {
644
- const state = getStateAdapter();
645
- const result = await withLock(state, updateLockKey(provider), async (lock) => await run(() => fenceLock(state, lock)), {
646
- ttlMs: MUTATION_LOCK_TTL_MS,
647
- waitMs: UPDATE_LOCK_WAIT_MS
648
- });
649
- if (!result.acquired) throw new Error(`Timed out waiting to update the ${provider} service account`);
650
- return result.value;
651
- };
652
- const update = async (patch) => {
653
- await withStoreLock(async (fence) => {
654
- const current = await getMcpServiceAccountCredentials(provider);
655
- if (!current) throw new Error(reconnectMessage(provider));
656
- await fence();
657
- await putMcpServiceAccountCredentials(provider, {
658
- ...current,
659
- ...patch
660
- });
661
- });
662
- };
663
- return {
664
- redirectUrl: connected.redirectUrl,
665
- clientMetadata: clientMetadata(connected.redirectUrl),
666
- clientInformation: async () => (await getMcpServiceAccountCredentials(provider))?.clientInformation,
667
- saveClientInformation: async (clientInformation) => {
668
- await update({ clientInformation });
669
- },
670
- tokens: async () => {
671
- const tokens = (await getMcpServiceAccountCredentials(provider))?.tokens;
672
- if (tokensRejected) {
673
- if (!tokens || tokens.refresh_token === lastRefreshToken) return;
674
- tokensRejected = false;
675
- }
676
- lastRefreshToken = tokens?.refresh_token;
677
- return tokens;
678
- },
679
- saveTokens: async (tokens) => {
680
- tokensRejected = false;
681
- lastRefreshToken = tokens.refresh_token;
682
- await update({ tokens });
683
- },
684
- discoveryState: async () => (await getMcpServiceAccountCredentials(provider))?.discoveryState,
685
- saveDiscoveryState: async (discoveryState) => {
686
- await update({ discoveryState });
687
- },
688
- invalidateCredentials: (scope) => {
689
- if (scope === "all" || scope === "tokens") tokensRejected = true;
690
- },
691
- redirectToAuthorization: async () => {
692
- if (!await withStoreLock(async (fence) => {
693
- const stored = await getMcpServiceAccountCredentials(provider);
694
- if (!stored) return true;
695
- if (!tokensRejected && stored.tokens.refresh_token || stored.tokens.refresh_token !== lastRefreshToken) return false;
696
- await fence();
697
- await deleteMcpServiceAccountCredentials(provider);
698
- logWarn("mcp.service_account.disconnected", { "app.plugin.name": provider });
699
- return true;
700
- })) throw new Error(`The ${provider} service account could not refresh its token. Try again later.`);
701
- throw new McpAuthorizationRequiredError(provider, reconnectMessage(provider));
702
- },
703
- saveCodeVerifier: () => void 0,
704
- codeVerifier: () => {
705
- throw new Error(reconnectMessage(provider));
706
- }
707
- };
708
- }
709
- function signInKey(state) {
710
- return `${SIGN_IN_KEY_PREFIX}:${state}`;
711
- }
712
- const signInSchema = z.object({
713
- clientInformation: storedOAuthClientInformationSchema,
714
- codeVerifier: z.string(),
715
- discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
716
- provider: z.string(),
717
- redirectUrl: z.string(),
718
- startedBy: z.string().optional().catch(void 0)
719
- });
720
- function parseSignIn(value) {
721
- const parsed = signInSchema.safeParse(value);
722
- return parsed.success ? parsed.data : void 0;
723
- }
724
- /** Build an OAuth client provider that keeps sign-in state in memory. */
725
- function signInProvider(input) {
726
- const captured = {
727
- clientInformation: input.pending?.clientInformation,
728
- codeVerifier: input.pending?.codeVerifier,
729
- discoveryState: input.pending?.discoveryState
730
- };
731
- return {
732
- captured,
733
- provider: {
734
- redirectUrl: input.redirectUrl,
735
- clientMetadata: clientMetadata(input.redirectUrl),
736
- ...input.state ? { state: () => input.state } : void 0,
737
- clientInformation: () => captured.clientInformation,
738
- saveClientInformation: (next) => {
739
- captured.clientInformation = next;
740
- },
741
- tokens: () => captured.tokens,
742
- saveTokens: (next) => {
743
- captured.tokens = next;
744
- },
745
- discoveryState: () => captured.discoveryState,
746
- saveDiscoveryState: (next) => {
747
- captured.discoveryState = next;
748
- },
749
- redirectToAuthorization: (url) => {
750
- captured.authorizationUrl = url;
751
- },
752
- saveCodeVerifier: (next) => {
753
- captured.codeVerifier = next;
754
- },
755
- codeVerifier: () => {
756
- if (!captured.codeVerifier) throw new Error("Missing MCP OAuth code verifier");
757
- return captured.codeVerifier;
758
- }
759
- }
760
- };
761
- }
762
- function requireServiceAccountMcp(plugin) {
763
- const mcp = plugin.manifest.mcp;
764
- if (!mcp || !plugin.manifest.accounts?.serviceAccount) throw new Error(`Plugin "${plugin.manifest.name}" does not support a service account`);
765
- return mcp;
766
- }
767
- /**
768
- * Start a service account sign-in and return the provider sign-in URL.
769
- *
770
- * The pending sign-in is single use and expires after a short time. Whoever
771
- * signs in decides which account Junior uses, so only Junior admins may start
772
- * it.
773
- */
774
- async function startMcpServiceAccountSignIn(input) {
775
- const mcp = requireServiceAccountMcp(input.plugin);
776
- const provider = input.plugin.manifest.name;
777
- const state = randomUUID();
778
- const signIn = signInProvider({
779
- redirectUrl: input.redirectUrl,
780
- state
781
- });
782
- if (await auth(signIn.provider, { serverUrl: mcp.url }) !== "REDIRECT") throw new Error(`${provider} did not start an OAuth sign-in`);
783
- const { authorizationUrl, clientInformation, codeVerifier, discoveryState } = signIn.captured;
784
- if (!authorizationUrl || !clientInformation || !codeVerifier) throw new Error(`${provider} did not return an authorization URL`);
785
- await createEncryptedState(getStateAdapter()).set(signInKey(state), {
786
- clientInformation,
787
- codeVerifier,
788
- ...discoveryState ? { discoveryState } : void 0,
789
- provider,
790
- redirectUrl: input.redirectUrl,
791
- ...input.startedBy ? { startedBy: input.startedBy } : void 0
792
- }, SIGN_IN_TTL_MS);
793
- return { authorizationUrl };
794
- }
795
- /**
796
- * Finish a service account sign-in from the OAuth callback parameters.
797
- *
798
- * It accepts only a pending sign-in for the same plugin that the same Admin
799
- * started. It then saves the grant as the plugin's service account.
800
- */
801
- async function finishMcpServiceAccountSignIn(input) {
802
- const mcp = requireServiceAccountMcp(input.plugin);
803
- const provider = input.plugin.manifest.name;
804
- const state = input.callback.get("state");
805
- const pending = state ? parseSignIn(await createEncryptedState(getStateAdapter()).get(signInKey(state))) : void 0;
806
- if (!state || !pending || pending.provider !== provider || pending.startedBy !== input.connectedBy) return {
807
- ok: false,
808
- message: "This sign-in expired or did not start here. Start it again."
809
- };
810
- await getStateAdapter().delete(signInKey(state));
811
- const error = input.callback.get("error");
812
- if (error) return {
813
- ok: false,
814
- message: `${provider} did not finish the sign-in (${error}).`
815
- };
816
- const authorizationCode = input.callback.get("code");
817
- if (!authorizationCode) return {
818
- ok: false,
819
- message: `${provider} did not return an authorization code.`
820
- };
821
- const signIn = signInProvider({
822
- pending,
823
- redirectUrl: pending.redirectUrl
824
- });
825
- await auth(signIn.provider, {
826
- serverUrl: mcp.url,
827
- authorizationCode
828
- });
829
- const { clientInformation, discoveryState, tokens } = signIn.captured;
830
- if (!clientInformation || !tokens) throw new Error(`${provider} did not issue tokens`);
831
- const credentials = {
832
- clientInformation,
833
- connectedAtMs: Date.now(),
834
- ...input.connectedBy ? { connectedBy: input.connectedBy } : void 0,
835
- ...discoveryState ? { discoveryState } : void 0,
836
- redirectUrl: pending.redirectUrl,
837
- tokens
838
- };
839
- await putMcpServiceAccountCredentials(provider, credentials);
840
- return {
841
- ok: true,
842
- credentials
843
- };
844
- }
845
- // src/chat/credentials/service-account.ts
846
- /**
847
- * Service accounts.
848
- *
849
- * A plugin's `accounts` block can allow an optional install-wide provider
850
- * account, often a bot, that Junior itself uses. By default, the credential
851
- * order for one request is:
852
- *
853
- * 1. The Actor's own connection, when it exists.
854
- * 2. The plugin's service account, when an Admin connected it and
855
- * `accounts.service-account` lists what the request uses.
856
- * 3. Otherwise, the Actor must connect their own account.
857
- *
858
- * With `accounts.user-oauth: false`, Junior uses only the service account.
859
- * It ignores Actor connections, never asks an Actor to connect, and hides
860
- * what the account does not list. Until an Admin connects the account, the
861
- * plugin is not available.
862
- *
863
- * This module is the one place that decides which requests the service
864
- * account may serve. Each request surface asks it before it uses the shared
865
- * account. Today MCP tools are the only request kind.
866
- *
867
- * This module also owns the connect flow that the dashboard Admin page and
868
- * the `junior service-account` CLI share. Today MCP is the only surface that
869
- * stores a service account.
870
- */
871
- /** Return whether the plugin's service account may serve this request. */
872
- function serviceAccountAllows(manifest, request) {
873
- return manifest.accounts?.serviceAccount?.tools.includes(request.tool) ?? false;
874
- }
875
- /**
876
- * Return whether the plugin uses only its service account.
877
- *
878
- * Then no surface may fall back to an Actor's own connection or ask an
879
- * Actor to connect.
880
- */
881
- function serviceAccountOnly(manifest) {
882
- return manifest.accounts?.userOAuth === false;
883
- }
884
- /** Return the plugins whose `accounts` block allows a service account. */
885
- function serviceAccountPlugins(plugins) {
886
- return plugins.filter((plugin) => plugin.manifest.accounts?.serviceAccount);
887
- }
888
- /** Read the service account status for one plugin. */
889
- async function getServiceAccountStatus(plugin) {
890
- const { manifest } = plugin;
891
- const serviceAccount = manifest.accounts?.serviceAccount;
892
- if (!serviceAccount) throw new Error(`Plugin ${manifest.name} does not allow a service account`);
893
- const credentials = await getMcpServiceAccountCredentials(manifest.name);
894
- return {
895
- provider: manifest.name,
896
- displayName: manifest.displayName,
897
- userOAuth: !serviceAccountOnly(manifest),
898
- tools: serviceAccount.tools,
899
- connected: Boolean(credentials),
900
- ...credentials ? { connectedAt: new Date(credentials.connectedAtMs).toISOString() } : void 0,
901
- ...credentials?.connectedBy ? { connectedBy: credentials.connectedBy } : void 0
902
- };
903
- }
904
- /**
905
- * Start signing in to a plugin's provider as its service account.
906
- *
907
- * Whoever signs in decides which account Junior uses, so only Junior admins
908
- * may start it. `startedBy` binds the sign-in to that Admin.
909
- */
910
- async function startServiceAccountSignIn(input) {
911
- return await startMcpServiceAccountSignIn(input);
912
- }
913
- /**
914
- * Finish a sign-in from its OAuth callback and save the service account.
915
- *
916
- * A failure message is safe to show the Admin. Unexpected provider failures
917
- * throw.
918
- */
919
- async function finishServiceAccountSignIn(input) {
920
- const result = await finishMcpServiceAccountSignIn(input);
921
- return result.ok ? { ok: true } : result;
922
- }
923
- /**
924
- * Remove a plugin's service account from Junior.
925
- *
926
- * The provider grant stays until someone revokes it in the provider.
927
- */
928
- async function disconnectServiceAccount(plugin) {
929
- await deleteMcpServiceAccountCredentials(plugin.manifest.name);
930
- }
931
- 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 };