@sentry/junior 0.315.0 → 0.317.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 (139) hide show
  1. package/dist/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
  2. package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
  5. package/dist/api/schema.d.ts +609 -104
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +373 -469
  8. package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +177 -132
  11. package/dist/catalog-runtime-DfSpJZdY.js +6 -0
  12. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  13. package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
  14. package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
  15. package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +5 -4
  20. package/dist/cli/snapshot-create.js +5 -2
  21. package/dist/cli/upgrade.js +27 -5
  22. package/dist/config-CHQ8X251.js +2422 -0
  23. package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
  24. package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
  25. package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
  26. package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
  27. package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
  28. package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
  29. package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
  30. package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
  31. package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
  32. package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
  33. package/dist/instrumentation.js +15 -7
  34. package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
  35. package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
  36. package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
  37. package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
  38. package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
  39. package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
  40. package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +20 -6
  43. package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
  44. package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
  45. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  46. package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
  47. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  48. package/dist/profile-BQ-iBDsZ.js +4657 -0
  49. package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
  50. package/dist/proxy-path-BHYoKZdq.js +15 -0
  51. package/dist/registry-iXMT5Jmh.js +3279 -0
  52. package/dist/reports-WKHfGTsU.js +195 -0
  53. package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
  54. package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
  55. package/dist/run-conversation-DL6ru7iW.js +336 -0
  56. package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
  57. package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
  58. package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
  59. package/dist/sender-actors-CPglLd5R.js +83 -0
  60. package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
  61. package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
  62. package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
  63. package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
  64. package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
  65. package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
  66. package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
  67. package/dist/topics-SRN7IVX-.js +24 -0
  68. package/dist/turn-membership-CENFf3kI.js +856 -0
  69. package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
  70. package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-ByG5RCEJ.js +181 -0
  73. package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
  74. package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
  77. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  78. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  79. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  80. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  81. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  82. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  83. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  84. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  85. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  86. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  87. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  88. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  89. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  90. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  91. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  92. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  93. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  94. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  95. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  96. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  97. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  98. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  99. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  100. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  101. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  102. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  103. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  104. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  105. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  106. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  107. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  108. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  109. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  110. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  111. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  112. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  113. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  114. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  115. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  116. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  117. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  118. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  119. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  120. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  121. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  122. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  123. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  124. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  125. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  126. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  127. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  128. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  129. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  130. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  131. package/package.json +5 -5
  132. package/skills/jr-rpc/SKILL.md +3 -5
  133. package/dist/direct-url-BYgYfuIy.js +0 -22
  134. package/dist/markers-CE0HMXWT.js +0 -67
  135. package/dist/people-Cegp1Iwq.js +0 -81
  136. package/dist/start-conversation-Uh8Sk1EF.js +0 -162
  137. package/dist/turn-session-routing-GtetHsdO.js +0 -1309
  138. package/dist/user-customization-B27StpVQ.js +0 -9
  139. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -0,0 +1,3279 @@
1
+ import { n as normalizePluginPackageNames, o as pluginRoots, t as discoverInstalledPluginPackageContent } from "./package-discovery-DD9vencX.js";
2
+ import { E as withSpan, b as setSpanAttributes, h as logWarn, m as logInfo } from "./logging--smS7XRK.js";
3
+ import { Ku as getStateAdapter, Wo as credentialUserSubjectId, a as getDb, hf as juniorUsers } from "./db-BFmyYZtJ.js";
4
+ import { N as fenceLock, P as withLock, j as MUTATION_LOCK_TTL_MS, n as getChatConfig, t as botConfig } from "./config-CHQ8X251.js";
5
+ import { L as mapBounded } from "./prompt-Dv7gkpD6.js";
6
+ import * as z from "zod";
7
+ import { getVercelOidcToken } from "@vercel/oidc";
8
+ import path from "node:path";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
11
+ import { destinationSchema, sourceSchema } from "@sentry/junior-plugin-api";
12
+ import { eq } from "drizzle-orm";
13
+ import { parse } from "yaml";
14
+ import { readFileSync, readdirSync, statSync } from "node:fs";
15
+ import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
16
+ import { Client } from "@modelcontextprotocol/sdk/client";
17
+ import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
18
+ // src/chat/plugins/inline-manifest-source.ts
19
+ function setDefined$1(target, key, value) {
20
+ if (value !== void 0) target[key] = value;
21
+ }
22
+ function unqualifyManifestToken(name, value) {
23
+ if (typeof name === "string" && typeof value === "string" && value.startsWith(`${name}.`)) return value.slice(name.length + 1);
24
+ return value;
25
+ }
26
+ function inlineTokenListSource(name, values) {
27
+ if (values === void 0 || !Array.isArray(values)) return values;
28
+ return values.map((value) => unqualifyManifestToken(name, value));
29
+ }
30
+ function workloadIdentitySource(credentials) {
31
+ const { azure, gcp } = credentials;
32
+ const result = {};
33
+ setDefined$1(result, "type", credentials.type);
34
+ setDefined$1(result, "domains", credentials.domains);
35
+ setDefined$1(result, "header", credentials.header);
36
+ if (gcp) result["gcp"] = {
37
+ "workload-identity-provider": gcp.workloadIdentityProvider,
38
+ "service-account": gcp.serviceAccount,
39
+ token: gcp.token,
40
+ ...gcp.token === "access-token" ? { scopes: gcp.scopes } : { audience: gcp.audience }
41
+ };
42
+ if (azure) result["azure"] = {
43
+ "tenant-id": azure.tenantId,
44
+ "client-id": azure.clientId,
45
+ scope: azure.scope
46
+ };
47
+ return result;
48
+ }
49
+ function inlineCredentialsSource(credentials) {
50
+ if (typeof credentials !== "object" || credentials === null || Array.isArray(credentials)) return credentials;
51
+ if (credentials.type === "workload-identity") return workloadIdentitySource(credentials);
52
+ const result = {};
53
+ setDefined$1(result, "type", credentials.type);
54
+ setDefined$1(result, "domains", credentials.domains);
55
+ setDefined$1(result, "api-headers", credentials.apiHeaders);
56
+ setDefined$1(result, "auth-token-env", credentials.authTokenEnv);
57
+ setDefined$1(result, "auth-token-placeholder", credentials.authTokenPlaceholder);
58
+ return result;
59
+ }
60
+ /** Convert a camelCase `mcp.auth` block to its plugin.yaml source keys. */
61
+ function mcpAuthSource(auth) {
62
+ return {
63
+ issuer: auth.issuer,
64
+ "key-id": auth.keyId,
65
+ "private-key-env": auth.privateKeyEnv
66
+ };
67
+ }
68
+ /** Convert a camelCase `mcp.oauthClient` block to its plugin.yaml source keys. */
69
+ function mcpOauthClientSource(oauthClient) {
70
+ const result = {
71
+ "client-id-env": oauthClient.clientIdEnv,
72
+ "client-secret-env": oauthClient.clientSecretEnv
73
+ };
74
+ setDefined$1(result, "scope", oauthClient.scope);
75
+ setDefined$1(result, "authorize-params", oauthClient.authorizeParams);
76
+ return result;
77
+ }
78
+ /** Convert a camelCase `accounts` block to its plugin.yaml source keys. */
79
+ function accountsSource(accounts) {
80
+ const result = {};
81
+ setDefined$1(result, "user-oauth", accounts.userOAuth);
82
+ setDefined$1(result, "service-account", accounts.serviceAccount);
83
+ return result;
84
+ }
85
+ function inlineMcpSource(mcp) {
86
+ if (typeof mcp !== "object" || mcp === null || Array.isArray(mcp)) return mcp;
87
+ const result = {};
88
+ setDefined$1(result, "transport", mcp.transport);
89
+ setDefined$1(result, "url", mcp.url);
90
+ setDefined$1(result, "headers", mcp.headers);
91
+ setDefined$1(result, "auth", mcp.auth && mcpAuthSource(mcp.auth));
92
+ setDefined$1(result, "oauth-client", mcp.oauthClient && mcpOauthClientSource(mcp.oauthClient));
93
+ setDefined$1(result, "allowed-tools", mcp.allowedTools);
94
+ setDefined$1(result, "wrapped-tools", mcp.wrappedTools);
95
+ return result;
96
+ }
97
+ function inlineOauthSource(oauth) {
98
+ if (typeof oauth !== "object" || oauth === null || Array.isArray(oauth)) return oauth;
99
+ const result = {};
100
+ setDefined$1(result, "client-id-env", oauth.clientIdEnv);
101
+ setDefined$1(result, "client-secret-env", oauth.clientSecretEnv);
102
+ setDefined$1(result, "authorize-endpoint", oauth.authorizeEndpoint);
103
+ setDefined$1(result, "token-endpoint", oauth.tokenEndpoint);
104
+ setDefined$1(result, "scope", oauth.scope);
105
+ setDefined$1(result, "authorize-params", oauth.authorizeParams);
106
+ setDefined$1(result, "token-auth-method", oauth.tokenAuthMethod);
107
+ setDefined$1(result, "token-extra-headers", oauth.tokenExtraHeaders);
108
+ setDefined$1(result, "treat-empty-scope-as-unreported", oauth.treatEmptyScopeAsUnreported);
109
+ return result;
110
+ }
111
+ function inlineTargetSource(name, target) {
112
+ if (typeof target !== "object" || target === null || Array.isArray(target)) return target;
113
+ const result = {};
114
+ setDefined$1(result, "type", target.type);
115
+ setDefined$1(result, "config-key", unqualifyManifestToken(name, target.configKey));
116
+ setDefined$1(result, "command-flags", target.commandFlags);
117
+ return result;
118
+ }
119
+ /** Convert inline JavaScript plugin manifests to the canonical source shape. */
120
+ function inlineManifestSource(manifest) {
121
+ const result = {};
122
+ setDefined$1(result, "name", manifest.name);
123
+ setDefined$1(result, "display-name", manifest.displayName);
124
+ setDefined$1(result, "description", manifest.description);
125
+ setDefined$1(result, "review-context", manifest.reviewContext);
126
+ setDefined$1(result, "config-keys", inlineTokenListSource(manifest.name, manifest.configKeys));
127
+ setDefined$1(result, "domains", manifest.domains);
128
+ setDefined$1(result, "api-headers", manifest.apiHeaders);
129
+ setDefined$1(result, "command-env", manifest.commandEnv);
130
+ setDefined$1(result, "env-vars", manifest.envVars);
131
+ setDefined$1(result, "tools-send-no-credential", manifest.toolsSendNoCredential);
132
+ setDefined$1(result, "credentials", inlineCredentialsSource(manifest.credentials));
133
+ setDefined$1(result, "runtime-dependencies", manifest.runtimeDependencies);
134
+ setDefined$1(result, "runtime-postinstall", manifest.runtimePostinstall);
135
+ setDefined$1(result, "mcp", inlineMcpSource(manifest.mcp));
136
+ setDefined$1(result, "oauth", inlineOauthSource(manifest.oauth));
137
+ setDefined$1(result, "accounts", manifest.accounts && accountsSource(manifest.accounts));
138
+ setDefined$1(result, "target", inlineTargetSource(manifest.name, manifest.target));
139
+ return result;
140
+ }
141
+ // src/chat/plugins/workload-identity-manifest.ts
142
+ const WORKLOAD_IDENTITY_PROVIDER_RE = /^projects\/\d+\/locations\/global\/workloadIdentityPools\/[a-z0-9-]+\/providers\/[a-z0-9-]+$/;
143
+ const GCP_SERVICE_ACCOUNT_RE = /^[a-z0-9-]+@[a-z0-9.-]+\.gserviceaccount\.com$/;
144
+ const AZURE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;
145
+ const GOOGLE_READ_ONLY_SCOPE_RE = /\.read[-_]?only$/;
146
+ const WORKLOAD_IDENTITY_HEADERS = [
147
+ "Authorization",
148
+ "Proxy-Authorization",
149
+ "X-Serverless-Authorization"
150
+ ];
151
+ const text = z.string({ error: "must be a string" }).trim().min(1, { error: "must be a non-empty string" });
152
+ const gcpBase = {
153
+ "workload-identity-provider": text.regex(WORKLOAD_IDENTITY_PROVIDER_RE, { error: "must be projects/<number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>" }),
154
+ "service-account": text.regex(GCP_SERVICE_ACCOUNT_RE, { error: "must be a service account email" })
155
+ };
156
+ const gcpSourceSchema = z.discriminatedUnion("token", [z.object({
157
+ ...gcpBase,
158
+ token: z.enum(["service-account-jwt", "id-token"]),
159
+ audience: text
160
+ }).strict(), z.object({
161
+ ...gcpBase,
162
+ token: z.literal("access-token"),
163
+ scopes: z.array(text.regex(GOOGLE_READ_ONLY_SCOPE_RE, { error: "must be read-only scopes, such as https://www.googleapis.com/auth/bigquery.readonly" })).min(1, { error: "must not be empty" })
164
+ }).strict()], { error: "token must be \"service-account-jwt\", \"id-token\", or \"access-token\"" });
165
+ const azureSourceSchema = z.object({
166
+ "tenant-id": text.regex(AZURE_ID_RE, { error: "must be a tenant id or domain" }),
167
+ "client-id": text.regex(AZURE_ID_RE, { error: "must be a client id" }),
168
+ scope: text
169
+ }).strict();
170
+ /**
171
+ * Strict `credentials` source for `type: workload-identity`. Strict keys make
172
+ * an unsupported issuer such as `aws` fail instead of being ignored.
173
+ */
174
+ const workloadIdentitySourceSchema = z.object({
175
+ type: z.literal("workload-identity"),
176
+ domains: z.unknown(),
177
+ header: z.enum(WORKLOAD_IDENTITY_HEADERS, { error: `must be one of ${WORKLOAD_IDENTITY_HEADERS.join(", ")}` }).optional(),
178
+ gcp: gcpSourceSchema.optional(),
179
+ azure: azureSourceSchema.optional()
180
+ }).strict().superRefine((value, ctx) => {
181
+ if (Boolean(value.gcp) === Boolean(value.azure)) ctx.addIssue({
182
+ code: "custom",
183
+ message: "must set exactly one of gcp or azure"
184
+ });
185
+ });
186
+ function expandStrings(value, path, expand) {
187
+ if (typeof value === "string") return expand(value, path);
188
+ if (Array.isArray(value)) return value.map((entry, index) => expandStrings(entry, `${path}.${index}`, expand));
189
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, expandStrings(entry, `${path}.${key}`, expand)]));
190
+ return value;
191
+ }
192
+ /** Fill `${NAME}` refs in the non-secret `gcp` and `azure` blocks before validation. */
193
+ function expandWorkloadIdentityEnvRefs(data, expand) {
194
+ return {
195
+ ...data,
196
+ ...data["gcp"] !== void 0 ? { gcp: expandStrings(data["gcp"], "gcp", expand) } : void 0,
197
+ ...data["azure"] !== void 0 ? { azure: expandStrings(data["azure"], "azure", expand) } : void 0
198
+ };
199
+ }
200
+ const GOOGLE_API_DOMAIN = "googleapis.com";
201
+ function isGoogleApiDomain(domain) {
202
+ return domain === GOOGLE_API_DOMAIN || domain.endsWith(`.${GOOGLE_API_DOMAIN}`);
203
+ }
204
+ function audienceHost(audience) {
205
+ if (!URL.canParse(audience)) return;
206
+ const url = new URL(audience);
207
+ return url.protocol === "https:" ? url.hostname.toLowerCase() : void 0;
208
+ }
209
+ /**
210
+ * Reject a credential whose minted token could reach a host that the token is
211
+ * not for.
212
+ *
213
+ * All plugins federate as the same Vercel principal, so a manifest can name
214
+ * any service account that principal can impersonate. Egress sends the token
215
+ * only to the plugin's own `domains`, and no two plugins can own one domain.
216
+ * So a JWT or ID token goes only to the host of its audience, and a Google
217
+ * access token can go only to Google APIs.
218
+ */
219
+ function assertWorkloadIdentityTokenTarget(credentials, prefix) {
220
+ const gcp = credentials.gcp;
221
+ if (!gcp) return;
222
+ if (gcp.token === "access-token") {
223
+ const other = credentials.domains.find((domain) => !isGoogleApiDomain(domain));
224
+ if (other) throw new Error(`${prefix}.domains entry "${other}" is not a Google API host (*.${GOOGLE_API_DOMAIN}), so it cannot get a gcp access-token`);
225
+ return;
226
+ }
227
+ const host = audienceHost(gcp.audience);
228
+ if (!host || credentials.domains.some((domain) => domain !== host)) throw new Error(`${prefix}.gcp.audience must be an https URL on the only host in credentials.domains`);
229
+ }
230
+ /**
231
+ * Key for the identity that a credential mints tokens for. Two plugins cannot
232
+ * share one, so one plugin cannot mint another plugin's token.
233
+ */
234
+ function workloadIdentityKey(credentials) {
235
+ if (credentials.azure) {
236
+ const { clientId, tenantId } = credentials.azure;
237
+ return `azure app ${tenantId.toLowerCase()}/${clientId.toLowerCase()}`;
238
+ }
239
+ return `gcp service account ${credentials.gcp.serviceAccount.toLowerCase()}`;
240
+ }
241
+ /** Return the request header that carries the minted token. */
242
+ function workloadIdentityHeader(credentials) {
243
+ return credentials.header ?? "Authorization";
244
+ }
245
+ /** Convert a parsed workload identity source into its runtime credentials. */
246
+ function workloadIdentityCredentials(source, domains) {
247
+ const header = source.header ? { header: source.header } : void 0;
248
+ if (source.gcp) {
249
+ const gcp = source.gcp;
250
+ const base = {
251
+ serviceAccount: gcp["service-account"],
252
+ workloadIdentityProvider: gcp["workload-identity-provider"]
253
+ };
254
+ return {
255
+ type: "workload-identity",
256
+ domains,
257
+ ...header,
258
+ gcp: gcp.token === "access-token" ? {
259
+ ...base,
260
+ token: gcp.token,
261
+ scopes: gcp.scopes
262
+ } : {
263
+ ...base,
264
+ token: gcp.token,
265
+ audience: gcp.audience
266
+ }
267
+ };
268
+ }
269
+ const azure = source.azure;
270
+ if (!azure) throw new Error("workload identity credentials must set gcp or azure");
271
+ return {
272
+ type: "workload-identity",
273
+ domains,
274
+ ...header,
275
+ azure: {
276
+ tenantId: azure["tenant-id"],
277
+ clientId: azure["client-id"],
278
+ scope: azure.scope
279
+ }
280
+ };
281
+ }
282
+ // src/chat/plugins/manifest.ts
283
+ const PLUGIN_NAME_RE = /^[a-z][a-z0-9-]*$/;
284
+ const SHORT_CONFIG_KEY_RE = /^[a-z0-9]+(\.[a-z0-9-]+)*$/;
285
+ const TARGET_FLAG_RE = /^-{1,2}[A-Za-z0-9][A-Za-z0-9-]*$/;
286
+ const AUTH_TOKEN_ENV_RE = /^[A-Z][A-Z0-9_]*$/;
287
+ const ENV_VAR_NAME_RE = /^[A-Z_][A-Z0-9_]*$/;
288
+ const ENV_PLACEHOLDER_RE$2 = /\$\{([A-Z_][A-Z0-9_]*)\}/g;
289
+ const API_DOMAIN_RE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
290
+ const RUNTIME_POSTINSTALL_CMD_RE = /^[A-Za-z0-9._/-]+$/;
291
+ const RESERVED_AUTHORIZE_PARAM_KEYS = /* @__PURE__ */ new Set([
292
+ "client_id",
293
+ "scope",
294
+ "state",
295
+ "redirect_uri",
296
+ "response_type"
297
+ ]);
298
+ const FORBIDDEN_API_HEADER_NAMES = /* @__PURE__ */ new Set(["authorization"]);
299
+ const FORBIDDEN_TOKEN_HEADER_NAMES = /* @__PURE__ */ new Set(["authorization"]);
300
+ const nonEmptyTrimmedString = z.string().transform((value) => value.trim()).pipe(z.string().min(1, { error: "must be a non-empty string" }));
301
+ const nonEmptyStringArraySchema = (fieldName, options = {}) => z.array(z.string(), { error: "must be an array of strings when provided" }).min(1, { error: options.nonEmptyMessage ?? "must be a non-empty array of strings when provided" }).transform((values, ctx) => {
302
+ const result = [];
303
+ const seen = /* @__PURE__ */ new Set();
304
+ for (const rawValue of values) {
305
+ const value = rawValue.trim();
306
+ if (!value) {
307
+ ctx.addIssue({
308
+ code: z.ZodIssueCode.custom,
309
+ message: `${fieldName} entries must be non-empty strings`
310
+ });
311
+ return z.NEVER;
312
+ }
313
+ if (seen.has(value)) continue;
314
+ seen.add(value);
315
+ result.push(value);
316
+ }
317
+ return result;
318
+ });
319
+ const envVarString = nonEmptyTrimmedString.refine((value) => AUTH_TOKEN_ENV_RE.test(value), { error: "must be an uppercase env var name" });
320
+ const httpsUrlString = nonEmptyTrimmedString.superRefine((value, ctx) => {
321
+ let parsed;
322
+ try {
323
+ parsed = new URL(value);
324
+ } catch {
325
+ ctx.addIssue({
326
+ code: z.ZodIssueCode.custom,
327
+ message: "must be a valid URL"
328
+ });
329
+ return;
330
+ }
331
+ if (parsed.protocol !== "https:") ctx.addIssue({
332
+ code: z.ZodIssueCode.custom,
333
+ message: "must use https"
334
+ });
335
+ });
336
+ const stringMapSchema = z.record(z.string(), z.unknown()).transform((record, ctx) => {
337
+ const entries = Object.entries(record);
338
+ const result = {};
339
+ const seen = /* @__PURE__ */ new Set();
340
+ for (const [rawKey, rawValue] of entries) {
341
+ const key = rawKey.trim();
342
+ if (!key) {
343
+ ctx.addIssue({
344
+ code: z.ZodIssueCode.custom,
345
+ message: "keys must be non-empty strings"
346
+ });
347
+ return z.NEVER;
348
+ }
349
+ if (typeof rawValue !== "string" || !rawValue.trim()) {
350
+ ctx.addIssue({
351
+ code: z.ZodIssueCode.custom,
352
+ message: `${key} must be a non-empty string`
353
+ });
354
+ return z.NEVER;
355
+ }
356
+ const normalizedKey = key.toLowerCase();
357
+ if (seen.has(normalizedKey)) {
358
+ ctx.addIssue({
359
+ code: z.ZodIssueCode.custom,
360
+ message: `${key} is duplicated`
361
+ });
362
+ return z.NEVER;
363
+ }
364
+ seen.add(normalizedKey);
365
+ result[key] = rawValue.trim();
366
+ }
367
+ return result;
368
+ });
369
+ const domainsSchema = z.array(z.unknown()).min(1, { error: "must be a non-empty array of strings" }).transform((domains, ctx) => {
370
+ return domains.map((rawDomain) => {
371
+ const domain = typeof rawDomain === "string" ? rawDomain.trim().toLowerCase() : "";
372
+ if (!domain) {
373
+ ctx.addIssue({
374
+ code: z.ZodIssueCode.custom,
375
+ message: "entries must be non-empty strings"
376
+ });
377
+ return z.NEVER;
378
+ }
379
+ if (!API_DOMAIN_RE.test(domain)) {
380
+ ctx.addIssue({
381
+ code: z.ZodIssueCode.custom,
382
+ message: "entries must be valid domain names"
383
+ });
384
+ return z.NEVER;
385
+ }
386
+ return domain;
387
+ });
388
+ });
389
+ const oauthBearerCredentialsSchema = z.object({ domains: domainsSchema.optional() }).passthrough().extend({
390
+ "api-headers": stringMapSchema.optional(),
391
+ "auth-token-env": envVarString.optional(),
392
+ "auth-token-placeholder": nonEmptyTrimmedString.optional(),
393
+ type: z.literal("oauth-bearer")
394
+ });
395
+ const runtimeDependencyEntrySchema = z.object({
396
+ type: z.enum(["npm", "system"]),
397
+ package: z.string().optional(),
398
+ version: z.string().optional(),
399
+ url: z.string().optional(),
400
+ sha256: z.string().optional()
401
+ }).passthrough();
402
+ const runtimePostinstallCommandSourceSchema = z.object({
403
+ cmd: nonEmptyTrimmedString,
404
+ args: z.array(z.string(), { error: "args must be an array of strings when provided" }).optional(),
405
+ sudo: z.boolean({ error: "sudo must be a boolean when provided" }).optional()
406
+ }).passthrough();
407
+ const oauthSourceSchema = z.object({
408
+ "client-id-env": envVarString,
409
+ "client-secret-env": envVarString,
410
+ "authorize-endpoint": httpsUrlString,
411
+ "token-endpoint": httpsUrlString,
412
+ scope: nonEmptyTrimmedString.optional(),
413
+ "authorize-params": stringMapSchema.optional(),
414
+ "token-extra-headers": stringMapSchema.optional(),
415
+ "token-auth-method": nonEmptyTrimmedString.refine((value) => value === "body" || value === "basic", { error: "must be \"body\" or \"basic\"" }).optional(),
416
+ "treat-empty-scope-as-unreported": z.boolean().optional()
417
+ }).passthrough();
418
+ const mcpAuthSourceSchema = z.object({
419
+ issuer: nonEmptyTrimmedString,
420
+ "key-id": nonEmptyTrimmedString,
421
+ "private-key-env": envVarString
422
+ }).passthrough();
423
+ const mcpOauthClientSourceSchema = z.object({
424
+ "client-id-env": envVarString,
425
+ "client-secret-env": envVarString,
426
+ scope: nonEmptyTrimmedString.optional(),
427
+ "authorize-params": stringMapSchema.optional()
428
+ }).passthrough();
429
+ const accountsSourceSchema = z.object({
430
+ "user-oauth": z.boolean().optional(),
431
+ "service-account": z.union([z.object({ tools: nonEmptyStringArraySchema("tools") }).strict(), z.object({ operations: nonEmptyStringArraySchema("operations") }).strict()]).optional()
432
+ }).strict();
433
+ const mcpSourceSchema = z.object({
434
+ transport: nonEmptyTrimmedString.refine((value) => value === "http", { error: "must be \"http\"" }).optional(),
435
+ url: httpsUrlString,
436
+ auth: mcpAuthSourceSchema.optional(),
437
+ headers: stringMapSchema.optional(),
438
+ "oauth-client": mcpOauthClientSourceSchema.optional(),
439
+ "allowed-tools": nonEmptyStringArraySchema("allowed-tools").optional(),
440
+ "wrapped-tools": nonEmptyStringArraySchema("wrapped-tools").optional()
441
+ }).passthrough();
442
+ const targetSourceSchema = z.object({
443
+ type: nonEmptyTrimmedString.refine((value) => PLUGIN_NAME_RE.test(value), { error: "type must be a lowercase target identifier" }),
444
+ "config-key": nonEmptyTrimmedString,
445
+ "command-flags": nonEmptyStringArraySchema("command-flags").optional()
446
+ }).passthrough();
447
+ const manifestSourceSchema = z.object({
448
+ name: z.string().refine((value) => PLUGIN_NAME_RE.test(value), { error: "invalid" }),
449
+ "display-name": nonEmptyTrimmedString,
450
+ description: nonEmptyTrimmedString,
451
+ "review-context": nonEmptyTrimmedString.optional(),
452
+ "config-keys": z.array(z.string(), { error: "must be an array when provided" }).optional(),
453
+ domains: domainsSchema.optional(),
454
+ "api-headers": stringMapSchema.optional(),
455
+ "command-env": stringMapSchema.optional(),
456
+ credentials: z.record(z.string(), z.unknown(), { error: "must be an object when provided" }).optional(),
457
+ "runtime-dependencies": z.array(z.unknown(), { error: "must be an array" }).optional(),
458
+ "runtime-postinstall": z.array(z.unknown(), { error: "must be an array" }).optional(),
459
+ "env-vars": z.record(z.string(), z.unknown(), { error: "must be an object" }).optional(),
460
+ mcp: z.record(z.string(), z.unknown(), { error: "must be an object" }).optional(),
461
+ oauth: z.record(z.string(), z.unknown(), { error: "must be an object" }).optional(),
462
+ accounts: z.record(z.string(), z.unknown(), { error: "must be an object" }).optional(),
463
+ target: z.record(z.string(), z.unknown(), { error: "must be an object" }).optional(),
464
+ "tools-send-no-credential": z.boolean({ error: "must be a boolean" }).optional()
465
+ }).passthrough();
466
+ function setDefined(target, key, value) {
467
+ if (value !== void 0) target[key] = value;
468
+ }
469
+ function manifestConfigPatch(config) {
470
+ const result = {};
471
+ setDefined(result, "display-name", config.displayName);
472
+ setDefined(result, "description", config.description);
473
+ setDefined(result, "review-context", config.reviewContext);
474
+ setDefined(result, "config-keys", config.configKeys);
475
+ setDefined(result, "domains", config.domains);
476
+ setDefined(result, "api-headers", config.apiHeaders);
477
+ setDefined(result, "command-env", config.commandEnv);
478
+ setDefined(result, "env-vars", config.envVars);
479
+ setDefined(result, "tools-send-no-credential", config.toolsSendNoCredential);
480
+ if (config.credentials !== void 0) {
481
+ if (!config.credentials) result["credentials"] = null;
482
+ else {
483
+ const credentials = {};
484
+ setDefined(credentials, "type", config.credentials.type);
485
+ setDefined(credentials, "domains", config.credentials.domains);
486
+ setDefined(credentials, "api-headers", config.credentials.apiHeaders);
487
+ setDefined(credentials, "auth-token-env", config.credentials.authTokenEnv);
488
+ setDefined(credentials, "auth-token-placeholder", config.credentials.authTokenPlaceholder);
489
+ result["credentials"] = credentials;
490
+ }
491
+ }
492
+ setDefined(result, "runtime-dependencies", config.runtimeDependencies);
493
+ setDefined(result, "runtime-postinstall", config.runtimePostinstall);
494
+ if (config.mcp !== void 0) {
495
+ if (!config.mcp) result["mcp"] = null;
496
+ else {
497
+ const mcp = {};
498
+ setDefined(mcp, "transport", config.mcp.transport);
499
+ setDefined(mcp, "url", config.mcp.url);
500
+ setDefined(mcp, "headers", config.mcp.headers);
501
+ setDefined(mcp, "auth", config.mcp.auth && mcpAuthSource(config.mcp.auth));
502
+ setDefined(mcp, "oauth-client", config.mcp.oauthClient && mcpOauthClientSource(config.mcp.oauthClient));
503
+ setDefined(mcp, "allowed-tools", config.mcp.allowedTools);
504
+ setDefined(mcp, "wrapped-tools", config.mcp.wrappedTools);
505
+ result["mcp"] = mcp;
506
+ }
507
+ }
508
+ if (config.oauth !== void 0) {
509
+ if (!config.oauth) result["oauth"] = null;
510
+ else {
511
+ const oauth = {};
512
+ setDefined(oauth, "client-id-env", config.oauth.clientIdEnv);
513
+ setDefined(oauth, "client-secret-env", config.oauth.clientSecretEnv);
514
+ setDefined(oauth, "authorize-endpoint", config.oauth.authorizeEndpoint);
515
+ setDefined(oauth, "token-endpoint", config.oauth.tokenEndpoint);
516
+ setDefined(oauth, "scope", config.oauth.scope);
517
+ setDefined(oauth, "authorize-params", config.oauth.authorizeParams);
518
+ setDefined(oauth, "token-auth-method", config.oauth.tokenAuthMethod);
519
+ setDefined(oauth, "token-extra-headers", config.oauth.tokenExtraHeaders);
520
+ setDefined(oauth, "treat-empty-scope-as-unreported", config.oauth.treatEmptyScopeAsUnreported);
521
+ result["oauth"] = oauth;
522
+ }
523
+ }
524
+ if (config.accounts !== void 0) result["accounts"] = config.accounts && accountsSource(config.accounts);
525
+ if (config.target !== void 0) {
526
+ if (!config.target) result["target"] = null;
527
+ else {
528
+ const target = {};
529
+ setDefined(target, "type", config.target.type);
530
+ setDefined(target, "config-key", config.target.configKey);
531
+ setDefined(target, "command-flags", config.target.commandFlags);
532
+ result["target"] = target;
533
+ }
534
+ }
535
+ return result;
536
+ }
537
+ function isPlainRecord(value) {
538
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
539
+ }
540
+ function mergeManifestConfig(base, patch, options = {}) {
541
+ const merged = { ...base };
542
+ for (const [key, value] of Object.entries(patch)) {
543
+ if (options.root && key === "name") throw new Error("plugins.manifests cannot change plugin names");
544
+ if (value === null) {
545
+ delete merged[key];
546
+ continue;
547
+ }
548
+ const current = merged[key];
549
+ if (isPlainRecord(current) && isPlainRecord(value)) {
550
+ merged[key] = mergeManifestConfig(current, value);
551
+ continue;
552
+ }
553
+ merged[key] = value;
554
+ }
555
+ return merged;
556
+ }
557
+ function applyManifestConfig(source, config) {
558
+ const name = source["name"];
559
+ if (typeof name !== "string") return source;
560
+ const manifestConfig = config?.manifests?.[name];
561
+ if (manifestConfig && "name" in manifestConfig) throw new Error("plugins.manifests cannot change plugin names");
562
+ return manifestConfig ? mergeManifestConfig(source, manifestConfigPatch(manifestConfig), { root: true }) : source;
563
+ }
564
+ function formatPath(path) {
565
+ return path.map((segment) => String(segment)).join(".");
566
+ }
567
+ function issueMessage(error, prefix) {
568
+ const issue = error.issues[0];
569
+ if (!issue) return prefix;
570
+ const suffix = formatPath(issue.path);
571
+ return suffix ? `${prefix}.${suffix} ${issue.message}` : `${prefix} ${issue.message}`;
572
+ }
573
+ function normalizeStringMap(value, prefix, options = {}) {
574
+ if (!value) return;
575
+ const keys = Object.keys(value);
576
+ if (keys.length === 0) return;
577
+ for (const key of keys) {
578
+ const normalizedKey = key.toLowerCase();
579
+ if (options.reservedKeys?.has(normalizedKey)) throw new Error(`${prefix}.${key} is reserved by the runtime`);
580
+ if (options.forbiddenKeys?.has(normalizedKey)) throw new Error(`${prefix}.${key} is not allowed`);
581
+ }
582
+ return value;
583
+ }
584
+ function envReferences(value) {
585
+ return Array.from(value.matchAll(ENV_PLACEHOLDER_RE$2), (match) => {
586
+ return match[1];
587
+ });
588
+ }
589
+ function assertDeclaredEnvReferences(value, envVars, context) {
590
+ for (const name of envReferences(value)) {
591
+ if (!Object.prototype.hasOwnProperty.call(envVars, name)) throw new Error(`${context} references env var ${name} which is not declared in env-vars`);
592
+ if (envVars[name]?.default !== void 0) throw new Error(`${context} references env var ${name}, but header env vars must not declare defaults`);
593
+ }
594
+ }
595
+ function assertDeclaredHeaderEnvReferences(headers, envVars, prefix) {
596
+ for (const [key, headerValue] of Object.entries(headers ?? {})) assertDeclaredEnvReferences(headerValue, envVars, `${prefix}.${key}`);
597
+ }
598
+ function assertDeclaredHostSecretEnv(name, envVars, context) {
599
+ if (!Object.prototype.hasOwnProperty.call(envVars, name)) throw new Error(`${context} uses env var ${name} which is not declared in env-vars`);
600
+ if (envVars[name]?.default !== void 0) throw new Error(`${context} uses env var ${name}, but host secret env vars must not declare defaults`);
601
+ }
602
+ function normalizeRequiredApiHeaders(value, prefix, envVars) {
603
+ const apiHeaders = normalizeStringMap(value, prefix);
604
+ if (!apiHeaders) throw new Error(`${prefix} must contain at least one header`);
605
+ assertDeclaredHeaderEnvReferences(apiHeaders, envVars, prefix);
606
+ return apiHeaders;
607
+ }
608
+ function assertCommandEnvReferencesDeclared(value, envVars, context) {
609
+ for (const name of envReferences(value)) if (!Object.prototype.hasOwnProperty.call(envVars, name)) throw new Error(`${context} references env var ${name} which is not declared in env-vars`);
610
+ }
611
+ function expandCommandEnvPlaceholders(template, envVars, context) {
612
+ return template.replace(ENV_PLACEHOLDER_RE$2, (match, name) => {
613
+ if (envVars[name]?.default === void 0) return match;
614
+ return expandEnvPlaceholders(match, envVars, context);
615
+ });
616
+ }
617
+ function normalizeCommandEnv(value, prefix, envVars) {
618
+ const env = normalizeStringMap(value, prefix);
619
+ if (!env) throw new Error(`${prefix} must contain at least one env var`);
620
+ for (const [key, envValue] of Object.entries(env)) {
621
+ if (!ENV_VAR_NAME_RE.test(key)) throw new Error(`${prefix}.${key} must be an uppercase env var name`);
622
+ assertCommandEnvReferencesDeclared(envValue, envVars, `${prefix}.${key}`);
623
+ }
624
+ return Object.fromEntries(Object.entries(env).map(([key, envValue]) => [key, expandCommandEnvPlaceholders(envValue, envVars, `${prefix}.${key}`)]));
625
+ }
626
+ /** Collect every env var that carries a host-only secret for one plugin. */
627
+ function hostOnlyEnvNames(manifest) {
628
+ const names = /* @__PURE__ */ new Set();
629
+ if (manifest.mcp?.auth) names.add(manifest.mcp.auth.privateKeyEnv);
630
+ if (manifest.mcp?.oauthClient) {
631
+ names.add(manifest.mcp.oauthClient.clientIdEnv);
632
+ names.add(manifest.mcp.oauthClient.clientSecretEnv);
633
+ }
634
+ for (const value of [...Object.values(manifest.apiHeaders ?? {}), ...Object.values(manifest.mcp?.headers ?? {})]) for (const name of envReferences(value)) names.add(name);
635
+ if (manifest.credentials?.type === "oauth-bearer" && manifest.credentials.authTokenEnv) names.add(manifest.credentials.authTokenEnv);
636
+ if (manifest.oauth) {
637
+ names.add(manifest.oauth.clientIdEnv);
638
+ names.add(manifest.oauth.clientSecretEnv);
639
+ }
640
+ return names;
641
+ }
642
+ function assertCommandEnvDoesNotExposeHostSecretRefs(commandEnv, hostOnlyRefs, pluginName) {
643
+ if (!commandEnv) return;
644
+ for (const [key, value] of Object.entries(commandEnv)) for (const name of envReferences(value)) if (hostOnlyRefs.has(name)) throw new Error(`Plugin ${pluginName} command-env.${key} references env var ${name}, but credential/API header env vars must stay host-only`);
645
+ }
646
+ function assertCommandEnvHostRefsAreExplicitlyExposed(commandEnv, envVars, pluginName) {
647
+ if (!commandEnv) return;
648
+ for (const [key, value] of Object.entries(commandEnv)) for (const name of envReferences(value)) {
649
+ const declaration = envVars[name];
650
+ if (declaration && declaration.default === void 0 && declaration.exposeToCommandEnv !== true) throw new Error(`Plugin ${pluginName} command-env.${key} references env var ${name}, but env-vars.${name} must set expose-to-command-env: true before host env can be exposed to sandbox`);
651
+ }
652
+ }
653
+ function normalizeWorkloadIdentityCredentials(data, name, envVars) {
654
+ const prefix = `Plugin ${name} credentials`;
655
+ const result = workloadIdentitySourceSchema.safeParse(expandWorkloadIdentityEnvRefs(data, (value, path) => expandEnvPlaceholders(value, envVars, `${prefix}.${path}`)));
656
+ if (!result.success) throw new Error(issueMessage(result.error, prefix));
657
+ const domains = domainsSchema.optional().safeParse(result.data.domains);
658
+ if (!domains.success) throw new Error(issueMessage(domains.error, `${prefix}.domains`));
659
+ if (!domains.data) throw new Error(`${prefix} requires domains`);
660
+ const credentials = workloadIdentityCredentials(result.data, domains.data);
661
+ assertWorkloadIdentityTokenTarget(credentials, prefix);
662
+ return credentials;
663
+ }
664
+ function normalizeCredentials(data, name, envVars, hasOAuth) {
665
+ if (data["type"] === "workload-identity") return normalizeWorkloadIdentityCredentials(data, name, envVars);
666
+ if (data["type"] !== "oauth-bearer") throw new Error(`Plugin ${name} has unsupported credentials.type: "${String(data["type"])}"`);
667
+ const result = oauthBearerCredentialsSchema.safeParse(data);
668
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} credentials`));
669
+ if (!result.data.domains) throw new Error(`Plugin ${name} credentials requires domains`);
670
+ const domains = result.data.domains;
671
+ const authTokenEnv = result.data["auth-token-env"];
672
+ if (!authTokenEnv && !hasOAuth) throw new Error(`Plugin ${name} credentials.auth-token-env is required without oauth`);
673
+ const apiHeaders = result.data["api-headers"] ? normalizeStringMap(result.data["api-headers"], `Plugin ${name} credentials.api-headers`, { forbiddenKeys: FORBIDDEN_API_HEADER_NAMES }) : void 0;
674
+ return {
675
+ type: "oauth-bearer",
676
+ domains,
677
+ ...apiHeaders ? { apiHeaders } : void 0,
678
+ ...authTokenEnv ? { authTokenEnv } : void 0,
679
+ ...result.data["auth-token-placeholder"] ? { authTokenPlaceholder: result.data["auth-token-placeholder"] } : void 0
680
+ };
681
+ }
682
+ function normalizeRuntimeDependencies(entries, name) {
683
+ const parsed = [];
684
+ const seen = /* @__PURE__ */ new Set();
685
+ for (const entry of entries) {
686
+ const result = runtimeDependencyEntrySchema.safeParse(entry);
687
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} runtime-dependencies entries`));
688
+ const record = result.data;
689
+ const packageName = typeof record.package === "string" ? record.package.trim() : "";
690
+ const packageUrl = typeof record.url === "string" ? record.url.trim() : "";
691
+ const version = record.version;
692
+ const sha256 = record.sha256;
693
+ if (record.type === "npm") {
694
+ if (!packageName) throw new Error(`Plugin ${name} runtime dependency package must be a non-empty string`);
695
+ if (record.url !== void 0 || sha256 !== void 0) throw new Error(`Plugin ${name} npm runtime dependencies must only include package/version fields`);
696
+ const normalizedVersion = typeof version === "string" ? version.trim() : "latest";
697
+ if (!normalizedVersion) throw new Error(`Plugin ${name} runtime dependency version must be a non-empty string when provided`);
698
+ const dedupeKey = `${record.type}:${packageName}:${normalizedVersion}`;
699
+ if (seen.has(dedupeKey)) continue;
700
+ seen.add(dedupeKey);
701
+ parsed.push({
702
+ type: "npm",
703
+ package: packageName,
704
+ version: normalizedVersion
705
+ });
706
+ continue;
707
+ }
708
+ if (version !== void 0) throw new Error(`Plugin ${name} system runtime dependencies must not include a version`);
709
+ if (packageName && packageUrl) throw new Error(`Plugin ${name} system runtime dependencies must specify either package or url, not both`);
710
+ if (!packageName && !packageUrl) throw new Error(`Plugin ${name} system runtime dependencies must specify package or url`);
711
+ if (packageName) {
712
+ if (sha256 !== void 0) throw new Error(`Plugin ${name} system runtime dependency package entries must not include sha256`);
713
+ const dedupeKey = `${record.type}:package:${packageName}`;
714
+ if (seen.has(dedupeKey)) continue;
715
+ seen.add(dedupeKey);
716
+ parsed.push({
717
+ type: "system",
718
+ package: packageName
719
+ });
720
+ continue;
721
+ }
722
+ if (URL.parse(packageUrl)?.protocol !== "https:") throw new Error(`Plugin ${name} system runtime dependency url must be an https URL`);
723
+ const normalizedSha256 = typeof sha256 === "string" ? sha256.trim().toLowerCase() : "";
724
+ if (!/^[a-f0-9]{64}$/.test(normalizedSha256)) throw new Error(`Plugin ${name} system runtime dependency url entries must include a valid sha256`);
725
+ const dedupeKey = `${record.type}:url:${packageUrl}:${normalizedSha256}`;
726
+ if (seen.has(dedupeKey)) continue;
727
+ seen.add(dedupeKey);
728
+ parsed.push({
729
+ type: "system",
730
+ url: packageUrl,
731
+ sha256: normalizedSha256
732
+ });
733
+ }
734
+ return parsed.length > 0 ? parsed : void 0;
735
+ }
736
+ function normalizeRuntimePostinstall(commands, name) {
737
+ const parsed = [];
738
+ for (const command of commands) {
739
+ const result = runtimePostinstallCommandSourceSchema.safeParse(command);
740
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} runtime-postinstall`));
741
+ if (!RUNTIME_POSTINSTALL_CMD_RE.test(result.data.cmd)) throw new Error(`Plugin ${name} runtime-postinstall cmd must be a single executable token (letters, digits, ., _, /, -)`);
742
+ const normalizedArgs = result.data.args?.map((arg) => arg.trim()).filter((arg) => arg.length > 0);
743
+ parsed.push({
744
+ cmd: result.data.cmd,
745
+ ...normalizedArgs && normalizedArgs.length > 0 ? { args: normalizedArgs } : void 0,
746
+ ...typeof result.data.sudo === "boolean" ? { sudo: result.data.sudo } : void 0
747
+ });
748
+ }
749
+ return parsed.length > 0 ? parsed : void 0;
750
+ }
751
+ const envVarDeclarationSchema = z.preprocess((value) => value === null || value === void 0 ? {} : value, z.object({
752
+ default: z.string().optional(),
753
+ "expose-to-command-env": z.boolean().optional(),
754
+ exposeToCommandEnv: z.boolean().optional()
755
+ }).strict());
756
+ function normalizeEnvVars(data, pluginName) {
757
+ const normalized = {};
758
+ for (const [rawName, rawDecl] of Object.entries(data)) {
759
+ const name = rawName.trim();
760
+ if (!ENV_VAR_NAME_RE.test(name)) throw new Error(`Plugin ${pluginName} env-vars key "${rawName}" must match [A-Z_][A-Z0-9_]*`);
761
+ const parsed = envVarDeclarationSchema.safeParse(rawDecl);
762
+ if (!parsed.success) throw new Error(issueMessage(parsed.error, `Plugin ${pluginName} env-vars.${name}`));
763
+ const decl = {};
764
+ if (parsed.data.default !== void 0) decl.default = parsed.data.default;
765
+ if (parsed.data["expose-to-command-env"] === true || parsed.data.exposeToCommandEnv === true) decl.exposeToCommandEnv = true;
766
+ normalized[name] = decl;
767
+ }
768
+ return normalized;
769
+ }
770
+ /**
771
+ * Expand `${NAME}` placeholders in a manifest string field using the plugin's
772
+ * declared env-vars block. `NAME` must match `[A-Z_][A-Z0-9_]*` and must be
773
+ * declared in the plugin's `env-vars` block — otherwise load fails. This
774
+ * keeps the manifest's env-var surface explicit and auditable, and prevents
775
+ * a plugin manifest from opportunistically exfiltrating ambient process env
776
+ * vars via `mcp.url`. If `NAME` is declared without a default and
777
+ * `process.env[NAME]` is unset, load also fails.
778
+ */
779
+ function expandEnvPlaceholders(template, envVars, context) {
780
+ return template.replace(ENV_PLACEHOLDER_RE$2, (_match, name) => {
781
+ const varName = name;
782
+ if (!Object.prototype.hasOwnProperty.call(envVars, varName)) throw new Error(`${context} references env var ${varName} which is not declared in env-vars`);
783
+ const decl = envVars[varName];
784
+ const fromProcess = process.env[varName];
785
+ if (fromProcess !== void 0 && fromProcess !== "") return fromProcess;
786
+ if (decl.default !== void 0) return decl.default;
787
+ throw new Error(`${context} env var ${varName} is unset and has no default in env-vars`);
788
+ });
789
+ }
790
+ function normalizeMcp(data, envVars, name) {
791
+ const prepared = { ...data };
792
+ if (typeof prepared["url"] === "string") prepared["url"] = expandEnvPlaceholders(prepared["url"], envVars, `Plugin ${name} mcp.url`);
793
+ const result = mcpSourceSchema.safeParse(prepared);
794
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} mcp`));
795
+ const headers = result.data.headers ? normalizeStringMap(result.data.headers, `Plugin ${name} mcp.headers`, { forbiddenKeys: FORBIDDEN_API_HEADER_NAMES }) : void 0;
796
+ assertDeclaredHeaderEnvReferences(headers, envVars, `Plugin ${name} mcp.headers`);
797
+ if (result.data.auth) assertDeclaredHostSecretEnv(result.data.auth["private-key-env"], envVars, `Plugin ${name} mcp.auth.private-key-env`);
798
+ const oauthClient = result.data["oauth-client"];
799
+ if (oauthClient) {
800
+ if (result.data.auth) throw new Error(`Plugin ${name} mcp must not declare both auth and oauth-client`);
801
+ assertDeclaredHostSecretEnv(oauthClient["client-id-env"], envVars, `Plugin ${name} mcp.oauth-client.client-id-env`);
802
+ assertDeclaredHostSecretEnv(oauthClient["client-secret-env"], envVars, `Plugin ${name} mcp.oauth-client.client-secret-env`);
803
+ }
804
+ const oauthClientAuthorizeParams = oauthClient?.["authorize-params"] ? normalizeStringMap(oauthClient["authorize-params"], `Plugin ${name} mcp.oauth-client.authorize-params`, { reservedKeys: RESERVED_AUTHORIZE_PARAM_KEYS }) : void 0;
805
+ return {
806
+ transport: "http",
807
+ url: result.data.url,
808
+ ...result.data.auth ? { auth: {
809
+ issuer: result.data.auth.issuer,
810
+ keyId: result.data.auth["key-id"],
811
+ privateKeyEnv: result.data.auth["private-key-env"]
812
+ } } : void 0,
813
+ ...headers ? { headers } : void 0,
814
+ ...oauthClient ? { oauthClient: {
815
+ clientIdEnv: oauthClient["client-id-env"],
816
+ clientSecretEnv: oauthClient["client-secret-env"],
817
+ ...oauthClient.scope ? { scope: oauthClient.scope } : void 0,
818
+ ...oauthClientAuthorizeParams ? { authorizeParams: oauthClientAuthorizeParams } : void 0
819
+ } } : void 0,
820
+ ...result.data["allowed-tools"] ? { allowedTools: result.data["allowed-tools"] } : void 0,
821
+ ...result.data["wrapped-tools"] ? { wrappedTools: result.data["wrapped-tools"] } : void 0
822
+ };
823
+ }
824
+ /**
825
+ * Return the tools that a set MCP allow-list does not load. An empty
826
+ * allow-list loads every tool, so only a set list can be checked.
827
+ */
828
+ function unloadedMcpTools(mcp, tools) {
829
+ if (!mcp.allowedTools) return [];
830
+ const loadedTools = /* @__PURE__ */ new Set([...mcp.allowedTools, ...mcp.wrappedTools ?? []]);
831
+ return tools.filter((tool) => !loadedTools.has(tool));
832
+ }
833
+ /**
834
+ * Validate which accounts the plugin may use against the surfaces that
835
+ * support them: MCP OAuth lists tools, and a top-level `oauth` block with
836
+ * `oauth-bearer` credentials lists `egress.fetch` operations.
837
+ */
838
+ function normalizeAccounts(data, surfaces, name) {
839
+ const result = accountsSourceSchema.safeParse(data);
840
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${name} accounts`));
841
+ const userOAuth = result.data["user-oauth"];
842
+ const serviceAccount = result.data["service-account"];
843
+ if (userOAuth === false && !serviceAccount) throw new Error(`Plugin ${name} accounts.user-oauth false requires accounts.service-account`);
844
+ if (!serviceAccount) return;
845
+ const { mcp } = surfaces;
846
+ if ("operations" in serviceAccount) {
847
+ if (mcp || !surfaces.oauthBearer) throw new Error(`Plugin ${name} accounts.service-account.operations requires oauth with oauth-bearer credentials and no mcp`);
848
+ return {
849
+ ...userOAuth === false ? { userOAuth } : void 0,
850
+ serviceAccount: { operations: serviceAccount.operations }
851
+ };
852
+ }
853
+ if (!mcp || mcp.auth || mcp.oauthClient) throw new Error(`Plugin ${name} accounts.service-account.tools requires mcp without auth or oauth-client`);
854
+ const unknownTools = unloadedMcpTools(mcp, serviceAccount.tools);
855
+ if (unknownTools.length > 0) throw new Error(`Plugin ${name} accounts.service-account.tools must be listed in mcp.allowed-tools or mcp.wrapped-tools: ${unknownTools.join(", ")}`);
856
+ return {
857
+ ...userOAuth === false ? { userOAuth } : void 0,
858
+ serviceAccount: { tools: serviceAccount.tools }
859
+ };
860
+ }
861
+ function parseManifestSource(parsedSource, dir, config, options) {
862
+ const source = applyManifestConfig(parsedSource, config);
863
+ const sourceResult = manifestSourceSchema.safeParse(source);
864
+ if (!sourceResult.success) {
865
+ const issue = sourceResult.error.issues[0];
866
+ const path = formatPath(issue?.path ?? []);
867
+ if (path === "name") throw new Error(`Invalid plugin name in ${dir}: "${String(parsedSource["name"])}"`);
868
+ if (path === "description") throw new Error(`Invalid plugin description in ${dir}`);
869
+ if (path === "config-keys") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} config-keys must be an array when provided`);
870
+ if (path === "domains") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} ${path} must be a non-empty array of domains`);
871
+ if (path === "api-headers") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} api-headers must be an object when provided`);
872
+ if (path === "command-env") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} command-env must be an object when provided`);
873
+ if (path === "credentials") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} credentials must be an object when provided`);
874
+ if (path === "runtime-dependencies") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} runtime-dependencies must be an array`);
875
+ if (path === "runtime-postinstall") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} runtime-postinstall must be an array`);
876
+ if (path === "env-vars") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} env-vars must be an object`);
877
+ if (path === "mcp") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} mcp must be an object`);
878
+ if (path === "oauth") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} oauth must be an object`);
879
+ if (path === "accounts") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} accounts must be an object`);
880
+ if (path === "target") throw new Error(`Plugin ${String(parsedSource["name"] ?? "unknown")} target must be an object`);
881
+ throw new Error(issue?.message ?? `Invalid plugin manifest in ${dir}`);
882
+ }
883
+ const data = sourceResult.data;
884
+ const configKeys = (data["config-keys"] ?? []).map((key) => {
885
+ if (!SHORT_CONFIG_KEY_RE.test(key)) throw new Error(`Invalid config key "${key}" in plugin ${data.name}`);
886
+ return `${data.name}.${key}`;
887
+ });
888
+ const envVars = data["env-vars"] ? normalizeEnvVars(data["env-vars"], data.name) : {};
889
+ const apiHeaders = data["api-headers"] ? normalizeRequiredApiHeaders(data["api-headers"], `Plugin ${data.name} api-headers`, envVars) : void 0;
890
+ const domains = data.domains;
891
+ if (apiHeaders && !domains) throw new Error(`Plugin ${data.name} api-headers requires domains`);
892
+ if (domains && !apiHeaders && !data.credentials && options?.allowHookManagedEgress !== true) throw new Error(`Plugin ${data.name} domains requires credentials or api-headers`);
893
+ const commandEnv = data["command-env"] ? normalizeCommandEnv(data["command-env"], `Plugin ${data.name} command-env`, envVars) : void 0;
894
+ const credentials = data.credentials ? normalizeCredentials(data.credentials, data.name, envVars, Boolean(data.oauth)) : void 0;
895
+ if (credentials?.type === "workload-identity") {
896
+ const collision = Object.keys(apiHeaders ?? {}).find((header) => header.toLowerCase() === workloadIdentityHeader(credentials).toLowerCase());
897
+ if (collision) throw new Error(`Plugin ${data.name} api-headers.${collision} conflicts with credentials.header`);
898
+ }
899
+ const runtimeDependencies = data["runtime-dependencies"] ? normalizeRuntimeDependencies(data["runtime-dependencies"], data.name) : void 0;
900
+ const runtimePostinstall = data["runtime-postinstall"] ? normalizeRuntimePostinstall(data["runtime-postinstall"], data.name) : void 0;
901
+ const mcp = data.mcp ? normalizeMcp(data.mcp, envVars, data.name) : void 0;
902
+ const accounts = data.accounts ? normalizeAccounts(data.accounts, {
903
+ mcp,
904
+ oauthBearer: Boolean(data.oauth && credentials)
905
+ }, data.name) : void 0;
906
+ const manifest = {
907
+ name: data.name,
908
+ displayName: data["display-name"],
909
+ description: data.description,
910
+ ...data["review-context"] ? { reviewContext: data["review-context"] } : void 0,
911
+ configKeys,
912
+ ...domains ? { domains } : void 0,
913
+ ...apiHeaders ? { apiHeaders } : void 0,
914
+ ...commandEnv ? { commandEnv } : void 0,
915
+ ...Object.keys(envVars).length > 0 ? { envVars } : void 0,
916
+ ...credentials ? { credentials } : void 0,
917
+ ...runtimeDependencies ? { runtimeDependencies } : void 0,
918
+ ...runtimePostinstall ? { runtimePostinstall } : void 0,
919
+ ...mcp ? { mcp } : void 0,
920
+ ...accounts ? { accounts } : void 0,
921
+ ...data["tools-send-no-credential"] ? { toolsSendNoCredential: true } : void 0
922
+ };
923
+ if (data.oauth) {
924
+ if (!credentials && options?.allowHookManagedEgress !== true) throw new Error(`Plugin ${data.name} oauth requires credentials`);
925
+ if (credentials?.type === "workload-identity") throw new Error(`Plugin ${data.name} oauth cannot be used with workload-identity credentials`);
926
+ const result = oauthSourceSchema.safeParse(data.oauth);
927
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${data.name} oauth`));
928
+ const authorizeParams = result.data["authorize-params"] ? normalizeStringMap(result.data["authorize-params"], `Plugin ${data.name} oauth.authorize-params`, { reservedKeys: RESERVED_AUTHORIZE_PARAM_KEYS }) : void 0;
929
+ const tokenExtraHeaders = result.data["token-extra-headers"] ? normalizeStringMap(result.data["token-extra-headers"], `Plugin ${data.name} oauth.token-extra-headers`, { forbiddenKeys: FORBIDDEN_TOKEN_HEADER_NAMES }) : void 0;
930
+ manifest.oauth = {
931
+ clientIdEnv: result.data["client-id-env"],
932
+ clientSecretEnv: result.data["client-secret-env"],
933
+ authorizeEndpoint: result.data["authorize-endpoint"],
934
+ tokenEndpoint: result.data["token-endpoint"],
935
+ ...result.data.scope ? { scope: result.data.scope } : void 0,
936
+ ...authorizeParams ? { authorizeParams } : void 0,
937
+ ...result.data["token-auth-method"] ? { tokenAuthMethod: result.data["token-auth-method"] } : void 0,
938
+ ...tokenExtraHeaders ? { tokenExtraHeaders } : void 0,
939
+ ...result.data["treat-empty-scope-as-unreported"] ? { treatEmptyScopeAsUnreported: true } : void 0
940
+ };
941
+ }
942
+ assertCommandEnvDoesNotExposeHostSecretRefs(data["command-env"], hostOnlyEnvNames({
943
+ apiHeaders,
944
+ credentials,
945
+ oauth: manifest.oauth,
946
+ mcp
947
+ }), data.name);
948
+ assertCommandEnvHostRefsAreExplicitlyExposed(data["command-env"], envVars, data.name);
949
+ if (data.target) {
950
+ const result = targetSourceSchema.safeParse(data.target);
951
+ if (!result.success) throw new Error(issueMessage(result.error, `Plugin ${data.name} target`));
952
+ if (!SHORT_CONFIG_KEY_RE.test(result.data["config-key"])) throw new Error(`Plugin ${data.name} target.config-key "${result.data["config-key"]}" is invalid`);
953
+ const qualifiedKey = `${data.name}.${result.data["config-key"]}`;
954
+ if (!configKeys.includes(qualifiedKey)) throw new Error(`Plugin ${data.name} target.config-key "${result.data["config-key"]}" must be listed in config-keys`);
955
+ const commandFlags = result.data["command-flags"];
956
+ if (commandFlags && commandFlags.some((flag) => !TARGET_FLAG_RE.test(flag))) throw new Error(`Plugin ${data.name} target.command-flags must contain CLI flags like --repo or -R`);
957
+ manifest.target = {
958
+ type: result.data.type,
959
+ configKey: qualifiedKey,
960
+ ...commandFlags ? { commandFlags } : void 0
961
+ };
962
+ }
963
+ return manifest;
964
+ }
965
+ /** Parse one plugin.yaml manifest after applying install-level plugin config. */
966
+ function parsePluginManifest(raw, dir, config) {
967
+ let parsedYaml;
968
+ try {
969
+ parsedYaml = parse(raw);
970
+ } catch (error) {
971
+ throw new Error(`Invalid plugin manifest in ${dir}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
972
+ }
973
+ if (!parsedYaml || typeof parsedYaml !== "object" || Array.isArray(parsedYaml)) throw new Error(`Invalid plugin manifest in ${dir}: expected an object`);
974
+ return parseManifestSource(parsedYaml, dir, config);
975
+ }
976
+ /** Parse one inline JavaScript manifest through the same effective manifest pipeline as plugin.yaml. */
977
+ function parseInlinePluginManifest(manifest, dir, config) {
978
+ return parseManifestSource(inlineManifestSource(manifest), dir, config, { allowHookManagedEgress: true });
979
+ }
980
+ // src/chat/credentials/broker.ts
981
+ var CredentialUnavailableError = class extends Error {
982
+ provider;
983
+ constructor(provider, message) {
984
+ super(message);
985
+ this.name = "CredentialUnavailableError";
986
+ this.provider = provider;
987
+ }
988
+ };
989
+ /**
990
+ * A host-minted bot credential could not be issued.
991
+ *
992
+ * No user can fix this by connecting an account, so egress reports it as
993
+ * unavailable instead of starting an auth flow. The message names the failing
994
+ * step and never includes token values.
995
+ */
996
+ var CredentialMintError = class extends Error {
997
+ provider;
998
+ constructor(provider, message, options) {
999
+ super(message, options);
1000
+ this.name = "CredentialMintError";
1001
+ this.provider = provider;
1002
+ }
1003
+ };
1004
+ /**
1005
+ * The plugin uses only its service account, and that account cannot serve
1006
+ * this request. Asking the Actor to connect would not help.
1007
+ */
1008
+ var ServiceAccountUnavailableError = class extends CredentialUnavailableError {
1009
+ constructor(provider, message) {
1010
+ super(provider, message);
1011
+ this.name = "ServiceAccountUnavailableError";
1012
+ }
1013
+ };
1014
+ // src/chat/oauth-response.ts
1015
+ const MAX_OAUTH_ERROR_BODY_BYTES = 16384;
1016
+ const MAX_OAUTH_ERROR_BODY_READS = MAX_OAUTH_ERROR_BODY_BYTES;
1017
+ const MAX_OAUTH_ERROR_BODY_READ_MS = 5e3;
1018
+ const OAUTH_ERROR_BODY_READ_TIMEOUT = Symbol("oauth-error-body-read-timeout");
1019
+ async function readOAuthErrorBodyChunk(reader) {
1020
+ let timeout;
1021
+ const timeoutResult = new Promise((resolve) => {
1022
+ timeout = setTimeout(resolve, MAX_OAUTH_ERROR_BODY_READ_MS, OAUTH_ERROR_BODY_READ_TIMEOUT);
1023
+ });
1024
+ try {
1025
+ const result = await Promise.race([reader.read(), timeoutResult]);
1026
+ if (result === OAUTH_ERROR_BODY_READ_TIMEOUT) {
1027
+ await reader.cancel();
1028
+ throw new Error("OAuth error body read timed out");
1029
+ }
1030
+ return result;
1031
+ } finally {
1032
+ if (timeout) clearTimeout(timeout);
1033
+ }
1034
+ }
1035
+ /** Safe failure at a generic OAuth provider boundary. */
1036
+ var OAuthProviderError = class extends Error {
1037
+ phase;
1038
+ provider;
1039
+ resourceHost;
1040
+ status;
1041
+ constructor(details) {
1042
+ super(`OAuth provider ${details.phase.replace("_", " ")} failed`);
1043
+ this.name = "OAuthProviderError";
1044
+ this.phase = details.phase;
1045
+ this.provider = details.provider;
1046
+ this.resourceHost = details.resourceHost;
1047
+ this.status = details.status;
1048
+ }
1049
+ };
1050
+ /** Return safe generic OAuth provider fields for logs and spans. */
1051
+ function getOAuthProviderErrorAttributes(error) {
1052
+ if (!(error instanceof OAuthProviderError)) return {};
1053
+ return {
1054
+ "app.credential.provider": error.provider,
1055
+ "app.oauth.error.phase": error.phase,
1056
+ "server.address": error.resourceHost,
1057
+ ...error.status !== void 0 ? { "http.response.status_code": error.status } : void 0
1058
+ };
1059
+ }
1060
+ /** Read only the bounded prefix needed to classify an OAuth error response. */
1061
+ async function readBoundedOAuthErrorBody(response) {
1062
+ if (!response.body) return "";
1063
+ const reader = response.body.getReader();
1064
+ const decoder = new TextDecoder();
1065
+ let bytesRead = 0;
1066
+ let reads = 0;
1067
+ let text = "";
1068
+ try {
1069
+ while (bytesRead < MAX_OAUTH_ERROR_BODY_BYTES && reads < MAX_OAUTH_ERROR_BODY_READS) {
1070
+ reads += 1;
1071
+ const { done, value } = await readOAuthErrorBodyChunk(reader);
1072
+ if (done) return text + decoder.decode();
1073
+ const remaining = MAX_OAUTH_ERROR_BODY_BYTES - bytesRead;
1074
+ const chunk = value.subarray(0, remaining);
1075
+ bytesRead += chunk.byteLength;
1076
+ text += decoder.decode(chunk, { stream: true });
1077
+ if (chunk.byteLength < value.byteLength) {
1078
+ await reader.cancel();
1079
+ return text + decoder.decode();
1080
+ }
1081
+ }
1082
+ await reader.cancel();
1083
+ return text + decoder.decode();
1084
+ } finally {
1085
+ reader.releaseLock();
1086
+ }
1087
+ }
1088
+ /** Preserve small OAuth error responses while bounding bodies before SDK parsing. */
1089
+ function fetchWithBoundedOAuthErrorBodies(fetchFn = globalThis.fetch, onErrorResponseStatus) {
1090
+ return async (input, init) => {
1091
+ const response = await fetchFn(input, init);
1092
+ if (response.ok) return response;
1093
+ onErrorResponseStatus?.(response.status);
1094
+ if (!response.body) return response;
1095
+ let body = "";
1096
+ try {
1097
+ body = await readBoundedOAuthErrorBody(response);
1098
+ } catch {
1099
+ await response.body.cancel().catch(() => void 0);
1100
+ }
1101
+ return new Response(body, {
1102
+ headers: response.headers,
1103
+ status: response.status,
1104
+ statusText: response.statusText
1105
+ });
1106
+ };
1107
+ }
1108
+ // src/chat/mcp/errors.ts
1109
+ /** Safe failure at an MCP network or OAuth boundary. */
1110
+ var McpProviderError = class extends Error {
1111
+ phase;
1112
+ provider;
1113
+ missingSession;
1114
+ resourceHost;
1115
+ status;
1116
+ constructor(details) {
1117
+ super(`MCP provider ${details.phase.replace("_", " ")} failed`);
1118
+ this.name = "McpProviderError";
1119
+ this.phase = details.phase;
1120
+ this.provider = details.provider;
1121
+ this.missingSession = details.missingSession;
1122
+ this.resourceHost = details.resourceHost;
1123
+ this.status = details.status;
1124
+ }
1125
+ };
1126
+ function providerStatus(error) {
1127
+ if (!error || typeof error !== "object") return;
1128
+ const value = error;
1129
+ const status = typeof value.status === "number" ? value.status : typeof value.code === "number" ? value.code : void 0;
1130
+ return status !== void 0 && status >= 100 && status <= 599 ? status : void 0;
1131
+ }
1132
+ /** Replace an external MCP failure without retaining its provider-controlled cause. */
1133
+ function toMcpProviderError(error, details) {
1134
+ if (error instanceof McpProviderError) return error;
1135
+ return new McpProviderError({
1136
+ ...details,
1137
+ status: details.status ?? providerStatus(error)
1138
+ });
1139
+ }
1140
+ /** Return safe MCP provider fields for logs and spans. */
1141
+ function getMcpProviderErrorAttributes(error) {
1142
+ if (!(error instanceof McpProviderError)) return {};
1143
+ return {
1144
+ "app.credential.provider": error.provider,
1145
+ "app.mcp.error.phase": error.phase,
1146
+ ...error.status !== void 0 ? { "http.response.status_code": error.status } : void 0,
1147
+ ...error.resourceHost ? { "server.address": error.resourceHost } : void 0
1148
+ };
1149
+ }
1150
+ /** Thrown when an MCP failure should be returned as a model-visible tool error. */
1151
+ var McpToolError = class extends Error {
1152
+ constructor(message) {
1153
+ super(message);
1154
+ this.name = "McpToolError";
1155
+ }
1156
+ };
1157
+ /**
1158
+ * Thrown when a plugin uses only its service account and no Admin has
1159
+ * connected it. The model can tell the person to ask an Admin.
1160
+ */
1161
+ var McpServiceAccountRequiredError = class extends McpToolError {
1162
+ provider;
1163
+ constructor(provider, displayName) {
1164
+ 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.`);
1165
+ this.name = "McpServiceAccountRequiredError";
1166
+ this.provider = provider;
1167
+ }
1168
+ };
1169
+ /** Return the OpenTelemetry error.type value for MCP-aware tool failures. */
1170
+ function getMcpAwareErrorType(error, fallback) {
1171
+ if (error instanceof McpToolError) return "tool_error";
1172
+ if (error instanceof McpProviderError) return "mcp_provider_error";
1173
+ return error instanceof Error ? error.name : fallback;
1174
+ }
1175
+ /** Return the display-safe error message for MCP-aware tool failures. */
1176
+ function getMcpAwareErrorMessage(error) {
1177
+ return error instanceof Error ? error.message : String(error);
1178
+ }
1179
+ /** Return an error message safe for logs and span attributes. */
1180
+ function getMcpAwareTelemetryMessage(error, _privacy) {
1181
+ if (error instanceof McpToolError) return "MCP tool call failed";
1182
+ if (error instanceof McpProviderError) return error.message;
1183
+ return getMcpAwareErrorMessage(error);
1184
+ }
1185
+ // src/chat/plugins/command-env.ts
1186
+ const ENV_PLACEHOLDER_RE$1 = /\$\{([A-Z_][A-Z0-9_]*)\}/g;
1187
+ function resolveValue(manifest, value) {
1188
+ let missing = false;
1189
+ const resolved = value.replace(ENV_PLACEHOLDER_RE$1, (match, name) => {
1190
+ const envName = name;
1191
+ const declaration = manifest.envVars?.[envName];
1192
+ if (!declaration || declaration.default !== void 0) return match;
1193
+ const hostValue = process.env[envName];
1194
+ if (hostValue === void 0 || hostValue === "") {
1195
+ missing = true;
1196
+ return "";
1197
+ }
1198
+ return hostValue;
1199
+ });
1200
+ return missing ? void 0 : resolved;
1201
+ }
1202
+ /** Resolve sandbox command env declared by a plugin manifest. */
1203
+ function resolvePluginCommandEnv(manifest) {
1204
+ const env = {};
1205
+ for (const [key, value] of Object.entries(manifest.commandEnv ?? {})) {
1206
+ const resolved = resolveValue(manifest, value);
1207
+ if (resolved === void 0) continue;
1208
+ env[key] = resolved;
1209
+ }
1210
+ return env;
1211
+ }
1212
+ // src/chat/plugins/auth/api-headers-broker.ts
1213
+ const MAX_LEASE_MS$1 = 36e5;
1214
+ const ENV_PLACEHOLDER_RE = /\$\{([A-Z_][A-Z0-9_]*)\}/g;
1215
+ /**
1216
+ * Fill `${NAME}` refs in plugin header values from the deployment env.
1217
+ *
1218
+ * Manifests keep the placeholder so secrets never reach build output, and the
1219
+ * parser has already required each name to be declared without a default.
1220
+ */
1221
+ function resolvePluginHeaderEnvRefs(provider, headers, kind = "API header") {
1222
+ return Object.fromEntries(Object.entries(headers).map(([key, value]) => {
1223
+ return [key, value.replace(ENV_PLACEHOLDER_RE, (_match, name) => {
1224
+ const envName = name;
1225
+ const envValue = process.env[envName]?.trim();
1226
+ if (!envValue) throw new Error(`Missing ${envName} for ${kind} provider "${provider}"`);
1227
+ return envValue;
1228
+ })];
1229
+ }));
1230
+ }
1231
+ /** Resolve plugin-level API headers into sandbox header transforms. */
1232
+ function resolveApiHeaderTransforms(manifest) {
1233
+ const { domains, apiHeaders } = manifest;
1234
+ if (!domains || !apiHeaders) return [];
1235
+ const resolvedHeaders = resolvePluginHeaderEnvRefs(manifest.name, apiHeaders);
1236
+ return domains.map((domain) => ({
1237
+ domain,
1238
+ headers: resolvedHeaders
1239
+ }));
1240
+ }
1241
+ /** Issue host-managed API header transforms backed by deployment env vars. */
1242
+ function createApiHeadersBroker(manifest) {
1243
+ const provider = manifest.name;
1244
+ return { async issue(input) {
1245
+ const headerTransforms = resolveApiHeaderTransforms(manifest);
1246
+ if (headerTransforms.length === 0) throw new Error(`No API headers configured for plugin "${provider}"`);
1247
+ return {
1248
+ id: randomUUID(),
1249
+ provider,
1250
+ env: resolvePluginCommandEnv(manifest),
1251
+ headerTransforms,
1252
+ expiresAt: new Date(Date.now() + MAX_LEASE_MS$1).toISOString(),
1253
+ metadata: { reason: input.reason }
1254
+ };
1255
+ } };
1256
+ }
1257
+ // src/chat/conversations/legacy-web-actor-id.ts
1258
+ /**
1259
+ * Web Actor ids that Junior stored before web Actors used the User id.
1260
+ *
1261
+ * Mailbox input, web authorizations, and OAuth credentials saved before that
1262
+ * deploy still carry `dashboard:` and the first 24 hex characters of
1263
+ * sha256(email).
1264
+ *
1265
+ * TODO(dcramer): Delete with its callers after that input and those
1266
+ * authorizations expire and no `dashboard:` credential keys remain.
1267
+ */
1268
+ const USER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1269
+ /** Return the legacy web Actor id for one email. */
1270
+ function legacyWebActorUserId(email) {
1271
+ return `dashboard:${createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 24)}`;
1272
+ }
1273
+ /** Return every web Actor id that names this User, the User id first. */
1274
+ function webActorUserIds(user) {
1275
+ return [user.id, legacyWebActorUserId(user.email)];
1276
+ }
1277
+ /** Return the legacy web Actor id of a User id, when the User exists. */
1278
+ async function findLegacyWebActorUserId(userId) {
1279
+ if (!USER_ID_PATTERN.test(userId)) return void 0;
1280
+ const rows = await getDb().select({ email: juniorUsers.primaryEmailNormalized }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
1281
+ return rows[0] ? legacyWebActorUserId(rows[0].email) : void 0;
1282
+ }
1283
+ // src/chat/encryption/keyring.ts
1284
+ /** Build the keyring from checked encryption config. */
1285
+ function createEncryptionKeyring(config) {
1286
+ const keys = config.keys.map(({ id, key }) => ({
1287
+ id,
1288
+ key: Buffer.from(key, "base64")
1289
+ }));
1290
+ const active = keys.find((key) => key.id === config.activeKeyId);
1291
+ if (!active) throw new Error(`Active encryption key "${config.activeKeyId}" is not in the keyring`);
1292
+ return {
1293
+ active,
1294
+ keys
1295
+ };
1296
+ }
1297
+ // src/chat/encryption/secret.ts
1298
+ /**
1299
+ * Encrypt secrets that Junior keeps at rest, such as provider credentials.
1300
+ *
1301
+ * AES-256-GCM with keys from `JUNIOR_ENCRYPTION_KEYS` (see `keyring.ts`).
1302
+ * Each value is bound to a context, usually its storage key, and to its key
1303
+ * id as additional authenticated data. A value copied to another key does not
1304
+ * decrypt.
1305
+ *
1306
+ * New values use the active key. Any listed key decrypts. A value from a key
1307
+ * that is not active reports `stale`, so its owner can save it again with the
1308
+ * active key. A value that cannot be decrypted gives `UnreadableSecretError`:
1309
+ * `unknown_key` when its key id is not listed, `invalid` when it is malformed,
1310
+ * altered, or bound to another context.
1311
+ *
1312
+ * There is no per-value salt. The keys are random, not passwords, and each
1313
+ * value has a random IV. The storage key in the AAD already names the
1314
+ * identity that owns the value.
1315
+ *
1316
+ * Envelope: `jenc:v1:<keyId>:<iv>.<ciphertext>.<tag>` (base64url parts).
1317
+ */
1318
+ const ENVELOPE_PREFIX = "jenc:v1:";
1319
+ const ALGORITHM = "aes-256-gcm";
1320
+ const IV_BYTES = 12;
1321
+ const TAG_BYTES = 16;
1322
+ /** A stored secret that cannot be decrypted with the configured keys. */
1323
+ var UnreadableSecretError = class extends Error {
1324
+ reason;
1325
+ constructor(reason) {
1326
+ super(reason === "unknown_key" ? "Stored secret was encrypted with a key that is not configured" : "Stored secret is malformed or failed authentication");
1327
+ this.name = "UnreadableSecretError";
1328
+ this.reason = reason;
1329
+ }
1330
+ };
1331
+ function additionalData(keyId, context) {
1332
+ return Buffer.from(`${ENVELOPE_PREFIX}${keyId}\0${context}`, "utf8");
1333
+ }
1334
+ /** Check whether a stored value is an encryption envelope. */
1335
+ function isEncryptedSecret(value) {
1336
+ return typeof value === "string" && value.startsWith(ENVELOPE_PREFIX);
1337
+ }
1338
+ /** Encrypt one secret with the active key and bind it to `context`. */
1339
+ function encryptSecret(plaintext, context, keyring = createEncryptionKeyring(getChatConfig().encryption)) {
1340
+ const { id, key } = keyring.active;
1341
+ const iv = randomBytes(IV_BYTES);
1342
+ const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES });
1343
+ cipher.setAAD(additionalData(id, context));
1344
+ const parts = [
1345
+ iv,
1346
+ Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]),
1347
+ cipher.getAuthTag()
1348
+ ].map((part) => part.toString("base64url"));
1349
+ return `${ENVELOPE_PREFIX}${id}:${parts.join(".")}`;
1350
+ }
1351
+ /** Decrypt an `encryptSecret` envelope with the same `context`. */
1352
+ function decryptSecret(envelope, context, keyring = createEncryptionKeyring(getChatConfig().encryption)) {
1353
+ if (!isEncryptedSecret(envelope)) throw new Error("Stored secret is not an encryption envelope");
1354
+ const [keyId, payload] = envelope.slice(8).split(":");
1355
+ const [iv, ciphertext, tag] = (payload ?? "").split(".").map((part) => Buffer.from(part, "base64url"));
1356
+ if (!keyId || !iv || iv.length !== IV_BYTES || !ciphertext || !tag || tag.length !== TAG_BYTES) throw new UnreadableSecretError("invalid");
1357
+ const match = keyring.keys.find((candidate) => candidate.id === keyId);
1358
+ if (!match) throw new UnreadableSecretError("unknown_key");
1359
+ const decipher = createDecipheriv(ALGORITHM, match.key, iv, { authTagLength: TAG_BYTES });
1360
+ decipher.setAAD(additionalData(keyId, context));
1361
+ decipher.setAuthTag(tag);
1362
+ let text;
1363
+ try {
1364
+ text = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8");
1365
+ } catch {
1366
+ throw new UnreadableSecretError("invalid");
1367
+ }
1368
+ return {
1369
+ stale: match.id !== keyring.active.id,
1370
+ text
1371
+ };
1372
+ }
1373
+ // src/chat/encryption/state.ts
1374
+ /**
1375
+ * Decrypt one stored envelope. The storage key is the encryption context.
1376
+ * A value that cannot be decrypted, such as one from a key that is no longer
1377
+ * configured or one that was altered, reads as missing. The owner then asks
1378
+ * for the credential again and saves it with the active key.
1379
+ */
1380
+ function decode(key, envelope) {
1381
+ let decrypted;
1382
+ try {
1383
+ decrypted = decryptSecret(envelope, key);
1384
+ } catch (error) {
1385
+ if (!(error instanceof UnreadableSecretError)) throw error;
1386
+ logWarn("encryption.secret.unreadable", { "error.type": error.reason });
1387
+ return;
1388
+ }
1389
+ return {
1390
+ stale: decrypted.stale,
1391
+ value: JSON.parse(decrypted.text)
1392
+ };
1393
+ }
1394
+ /**
1395
+ * Wrap a state adapter so values are JSON-encoded and encrypted before they
1396
+ * reach storage. Keys and TTLs stay readable. Use it for credentials and
1397
+ * other secrets; delete, lock, and keep plain state on the base adapter.
1398
+ */
1399
+ function createEncryptedState(state) {
1400
+ return {
1401
+ async get(key) {
1402
+ const stored = await state.get(key);
1403
+ if (!isEncryptedSecret(stored)) return void 0;
1404
+ return decode(key, stored)?.value;
1405
+ },
1406
+ async set(key, value, ttlMs) {
1407
+ await state.set(key, encryptSecret(JSON.stringify(value), key), ttlMs);
1408
+ }
1409
+ };
1410
+ }
1411
+ /**
1412
+ * Read a value and report whether it is stale: encrypted with a key that is
1413
+ * not active, or saved before encryption. Long-lived owners save stale values
1414
+ * again, so they move to the active key.
1415
+ */
1416
+ async function readEncryptedState(state, key) {
1417
+ const stored = await state.get(key);
1418
+ if (stored === null || stored === void 0) return void 0;
1419
+ if (!isEncryptedSecret(stored)) return {
1420
+ stale: true,
1421
+ value: stored
1422
+ };
1423
+ return decode(key, stored);
1424
+ }
1425
+ // src/chat/mcp/auth-store.ts
1426
+ const MCP_AUTH_SESSION_PREFIX = "junior:mcp_oauth_attempt:v2";
1427
+ const MCP_AUTH_CREDENTIALS_PREFIX = "junior:mcp_auth_credentials";
1428
+ const MCP_AUTH_SESSION_INDEX_PREFIX = "junior:mcp_oauth_attempt_index:v2";
1429
+ const MCP_SERVER_SESSION_PREFIX = "junior:mcp_server_session";
1430
+ const MCP_AUTH_SESSION_TTL_MS = 864e5;
1431
+ const MCP_AUTH_CREDENTIALS_TTL_MS = 2592e6;
1432
+ const MCP_SERVER_SESSION_TTL_MS = 864e5;
1433
+ function sessionKey(authSessionId) {
1434
+ return `${MCP_AUTH_SESSION_PREFIX}:${authSessionId}`;
1435
+ }
1436
+ function credentialsKey(userId, provider) {
1437
+ return `${MCP_AUTH_CREDENTIALS_PREFIX}:${userId}:${provider}`;
1438
+ }
1439
+ function sessionIndexKey(userId, provider) {
1440
+ return `${MCP_AUTH_SESSION_INDEX_PREFIX}:${userId}:${provider}`;
1441
+ }
1442
+ function serverSessionKey(userId, provider) {
1443
+ return `${MCP_SERVER_SESSION_PREFIX}:${userId}:${provider}`;
1444
+ }
1445
+ function parseSessionIndex(value) {
1446
+ if (typeof value !== "string") return [];
1447
+ try {
1448
+ const parsed = JSON.parse(value);
1449
+ if (!Array.isArray(parsed)) return [];
1450
+ return [...new Set(parsed.filter((id) => typeof id === "string"))];
1451
+ } catch {
1452
+ return [];
1453
+ }
1454
+ }
1455
+ const optionalStoredString = z.string().optional().catch(void 0);
1456
+ const mcpAuthSessionSchema = z.object({
1457
+ schemaVersion: z.literal(2),
1458
+ authSessionId: z.string(),
1459
+ provider: z.string(),
1460
+ userId: z.string(),
1461
+ conversationId: z.string(),
1462
+ destination: destinationSchema.optional(),
1463
+ source: sourceSchema.optional(),
1464
+ sessionId: z.string(),
1465
+ userMessage: z.string(),
1466
+ channelId: optionalStoredString,
1467
+ threadTs: optionalStoredString,
1468
+ toolChannelId: optionalStoredString,
1469
+ configuration: z.record(z.string(), z.unknown()).optional().catch(void 0),
1470
+ authorizationUrl: optionalStoredString,
1471
+ codeVerifier: optionalStoredString,
1472
+ createdAtMs: z.number(),
1473
+ updatedAtMs: z.number()
1474
+ });
1475
+ function parseMcpAuthSession(value) {
1476
+ const parsed = mcpAuthSessionSchema.safeParse(value);
1477
+ return parsed.success ? parsed.data : void 0;
1478
+ }
1479
+ const serverSessionSchema = z.object({
1480
+ sessionId: z.string(),
1481
+ updatedAtMs: z.number()
1482
+ });
1483
+ function parseServerSession(value) {
1484
+ if (typeof value !== "string") return;
1485
+ try {
1486
+ const parsed = serverSessionSchema.safeParse(JSON.parse(value));
1487
+ return parsed.success ? parsed.data : void 0;
1488
+ } catch {
1489
+ return;
1490
+ }
1491
+ }
1492
+ const storedOAuthClientInformationSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
1493
+ const storedOAuthDiscoveryStateSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
1494
+ const storedOAuthTokensSchema$1 = z.custom((value) => typeof value === "object" && value !== null);
1495
+ const storedCredentialsSchema = z.object({
1496
+ clientInformation: storedOAuthClientInformationSchema$1.optional().catch(void 0),
1497
+ discoveryState: storedOAuthDiscoveryStateSchema$1.optional().catch(void 0),
1498
+ tokens: storedOAuthTokensSchema$1.optional().catch(void 0)
1499
+ });
1500
+ function parseStoredCredentials(value) {
1501
+ try {
1502
+ const parsed = storedCredentialsSchema.safeParse(typeof value === "string" ? JSON.parse(value) : value);
1503
+ return parsed.success ? parsed.data : void 0;
1504
+ } catch {
1505
+ return;
1506
+ }
1507
+ }
1508
+ async function readMcpAuthSession(stateAdapter, authSessionId) {
1509
+ const stored = await readEncryptedState(stateAdapter, sessionKey(authSessionId));
1510
+ if (stored?.stale && typeof stored.value === "string") try {
1511
+ return JSON.parse(stored.value);
1512
+ } catch {
1513
+ return;
1514
+ }
1515
+ return stored?.value;
1516
+ }
1517
+ async function getConnectedStateAdapter() {
1518
+ const stateAdapter = getStateAdapter();
1519
+ await stateAdapter.connect();
1520
+ return stateAdapter;
1521
+ }
1522
+ async function getMcpAuthSession(authSessionId) {
1523
+ return parseMcpAuthSession(await readMcpAuthSession(await getConnectedStateAdapter(), authSessionId));
1524
+ }
1525
+ async function putMcpAuthSession(session, ttlMs = MCP_AUTH_SESSION_TTL_MS) {
1526
+ const stateAdapter = await getConnectedStateAdapter();
1527
+ await createEncryptedState(stateAdapter).set(sessionKey(session.authSessionId), session, ttlMs);
1528
+ const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(session.userId, session.provider)));
1529
+ if (!nextIndex.includes(session.authSessionId)) nextIndex.push(session.authSessionId);
1530
+ await stateAdapter.set(sessionIndexKey(session.userId, session.provider), JSON.stringify(nextIndex), ttlMs);
1531
+ }
1532
+ async function patchMcpAuthSession(authSessionId, patch) {
1533
+ const current = await getMcpAuthSession(authSessionId);
1534
+ if (!current) throw new Error(`Unknown MCP auth session: ${authSessionId}`);
1535
+ const next = {
1536
+ ...current,
1537
+ ...patch,
1538
+ schemaVersion: 2,
1539
+ authSessionId: current.authSessionId,
1540
+ provider: current.provider,
1541
+ userId: current.userId,
1542
+ conversationId: current.conversationId,
1543
+ ...current.destination ? { destination: current.destination } : void 0,
1544
+ sessionId: current.sessionId,
1545
+ userMessage: current.userMessage,
1546
+ createdAtMs: current.createdAtMs,
1547
+ updatedAtMs: Date.now()
1548
+ };
1549
+ await putMcpAuthSession(next);
1550
+ return next;
1551
+ }
1552
+ async function deleteMcpAuthSession(authSessionId) {
1553
+ const stateAdapter = await getConnectedStateAdapter();
1554
+ const current = parseMcpAuthSession(await readMcpAuthSession(stateAdapter, authSessionId));
1555
+ await stateAdapter.delete(sessionKey(authSessionId));
1556
+ if (!current) return;
1557
+ const nextIndex = parseSessionIndex(await stateAdapter.get(sessionIndexKey(current.userId, current.provider))).filter((id) => id !== authSessionId);
1558
+ if (nextIndex.length > 0) {
1559
+ await stateAdapter.set(sessionIndexKey(current.userId, current.provider), JSON.stringify(nextIndex), MCP_AUTH_SESSION_TTL_MS);
1560
+ return;
1561
+ }
1562
+ await stateAdapter.delete(sessionIndexKey(current.userId, current.provider));
1563
+ }
1564
+ async function deleteMcpAuthSessionsForUserProvider(userId, provider) {
1565
+ const stateAdapter = await getConnectedStateAdapter();
1566
+ const indexKey = sessionIndexKey(userId, provider);
1567
+ const authSessionIds = parseSessionIndex(await stateAdapter.get(indexKey));
1568
+ await mapBounded(authSessionIds, (authSessionId) => stateAdapter.delete(sessionKey(authSessionId)));
1569
+ await stateAdapter.delete(indexKey);
1570
+ }
1571
+ async function getMcpStoredOAuthCredentials(userId, provider) {
1572
+ const stateAdapter = await getConnectedStateAdapter();
1573
+ const stored = parseStoredCredentials((await readEncryptedState(stateAdapter, credentialsKey(userId, provider)))?.value);
1574
+ if (stored) return stored;
1575
+ const legacyUserId = await findLegacyWebActorUserId(userId);
1576
+ if (!legacyUserId) return void 0;
1577
+ const legacyKey = credentialsKey(legacyUserId, provider);
1578
+ const legacy = parseStoredCredentials((await readEncryptedState(stateAdapter, legacyKey))?.value);
1579
+ if (!legacy) return void 0;
1580
+ await putMcpStoredOAuthCredentials(userId, provider, legacy);
1581
+ await stateAdapter.delete(legacyKey);
1582
+ return legacy;
1583
+ }
1584
+ async function putMcpStoredOAuthCredentials(userId, provider, value, ttlMs = MCP_AUTH_CREDENTIALS_TTL_MS) {
1585
+ await createEncryptedState(await getConnectedStateAdapter()).set(credentialsKey(userId, provider), value, ttlMs);
1586
+ }
1587
+ async function deleteMcpStoredOAuthCredentials(userId, provider) {
1588
+ const stateAdapter = await getConnectedStateAdapter();
1589
+ await stateAdapter.delete(credentialsKey(userId, provider));
1590
+ const legacyUserId = await findLegacyWebActorUserId(userId);
1591
+ if (legacyUserId) await stateAdapter.delete(credentialsKey(legacyUserId, provider));
1592
+ }
1593
+ async function getMcpServerSessionId(userId, provider) {
1594
+ return parseServerSession(await (await getConnectedStateAdapter()).get(serverSessionKey(userId, provider)))?.sessionId;
1595
+ }
1596
+ async function putMcpServerSessionId(userId, provider, sessionId, ttlMs = MCP_SERVER_SESSION_TTL_MS) {
1597
+ await (await getConnectedStateAdapter()).set(serverSessionKey(userId, provider), JSON.stringify({
1598
+ sessionId,
1599
+ updatedAtMs: Date.now()
1600
+ }), ttlMs);
1601
+ }
1602
+ async function deleteMcpServerSessionId(userId, provider) {
1603
+ await (await getConnectedStateAdapter()).delete(serverSessionKey(userId, provider));
1604
+ }
1605
+ // src/chat/mcp/token-refresh.ts
1606
+ /**
1607
+ * One MCP token refresh at a time for each person and provider.
1608
+ *
1609
+ * Providers such as Notion rotate the refresh token on each refresh and
1610
+ * revoke the whole grant when a retired refresh token comes back. A Turn
1611
+ * and a link card read can both find an expired access token at once, so
1612
+ * every refresh of a stored person login runs under one lock. A caller
1613
+ * that waited gets the tokens that the first caller saved, and its retired
1614
+ * refresh token never reaches the provider.
1615
+ */
1616
+ const REFRESH_LOCK_TTL_MS$1 = 3e4;
1617
+ const REFRESH_WAIT_MS = 3e4;
1618
+ function refreshTokenOf(body) {
1619
+ const params = body instanceof URLSearchParams ? body : typeof body === "string" ? new URLSearchParams(body) : void 0;
1620
+ return params?.get("grant_type") === "refresh_token" ? params.get("refresh_token") ?? void 0 : void 0;
1621
+ }
1622
+ /**
1623
+ * Wrap the fetch of an MCP client so that each refresh-token request for
1624
+ * this login runs under the shared lock. Other requests pass through.
1625
+ */
1626
+ function serializeMcpTokenRefresh(owner, fetchFn = globalThis.fetch) {
1627
+ let sentAccessToken;
1628
+ return async (input, init) => {
1629
+ const sentRefreshToken = refreshTokenOf(init?.body);
1630
+ if (!sentRefreshToken) {
1631
+ const authorization = new Headers(init?.headers).get("authorization");
1632
+ if (authorization) sentAccessToken = authorization.replace(/^Bearer\s+/i, "");
1633
+ return await fetchFn(input, init);
1634
+ }
1635
+ const { provider, userId } = await owner();
1636
+ const state = getStateAdapter();
1637
+ await state.connect();
1638
+ const attempt = await withLock(state, `mcp-oauth-refresh:${userId}:${provider}`, async (lock) => {
1639
+ const stored = await getMcpStoredOAuthCredentials(userId, provider);
1640
+ const current = stored?.tokens;
1641
+ if (!current) return Response.json({ error: "invalid_grant" }, { status: 400 });
1642
+ if (current.refresh_token && current.refresh_token !== sentRefreshToken || sentAccessToken && current.access_token !== sentAccessToken) return Response.json(current);
1643
+ const response = await fetchFn(input, init);
1644
+ if (!response.ok) return response;
1645
+ const tokens = await response.clone().json();
1646
+ if (typeof tokens["access_token"] !== "string") return response;
1647
+ await fenceLock(state, lock, REFRESH_LOCK_TTL_MS$1);
1648
+ await putMcpStoredOAuthCredentials(userId, provider, {
1649
+ ...stored,
1650
+ tokens: {
1651
+ ...current,
1652
+ ...tokens,
1653
+ refresh_token: typeof tokens["refresh_token"] === "string" ? tokens["refresh_token"] : sentRefreshToken
1654
+ }
1655
+ });
1656
+ return response;
1657
+ }, {
1658
+ keepAlive: true,
1659
+ ttlMs: REFRESH_LOCK_TTL_MS$1,
1660
+ waitMs: REFRESH_WAIT_MS
1661
+ });
1662
+ if (!attempt.acquired) throw new Error(`Timed out waiting for the ${provider} MCP token refresh`);
1663
+ return attempt.value;
1664
+ };
1665
+ }
1666
+ // src/chat/mcp/client.ts
1667
+ const MCP_CLIENT_INFO = {
1668
+ name: "junior-mcp-client",
1669
+ version: "1.0.0"
1670
+ };
1671
+ const MCP_TOOLS_CALL_METHOD = "tools/call";
1672
+ function getDefaultPort(url) {
1673
+ if (url.protocol === "https:") return 443;
1674
+ if (url.protocol === "http:") return 80;
1675
+ }
1676
+ function getMcpNetworkAttributes(url) {
1677
+ const port = url.port ? Number(url.port) : getDefaultPort(url);
1678
+ return {
1679
+ "server.address": url.hostname,
1680
+ ...port !== void 0 ? { "server.port": port } : void 0,
1681
+ ...url.protocol === "http:" || url.protocol === "https:" ? {
1682
+ "network.protocol.name": "http",
1683
+ "network.transport": "tcp"
1684
+ } : void 0
1685
+ };
1686
+ }
1687
+ var McpAuthorizationRequiredError = class extends Error {
1688
+ provider;
1689
+ constructor(provider, message) {
1690
+ super(message);
1691
+ this.name = "McpAuthorizationRequiredError";
1692
+ this.provider = provider;
1693
+ }
1694
+ };
1695
+ function isMissingSessionError(error) {
1696
+ return error instanceof StreamableHTTPError && (error.code === 404 || /Session not found/i.test(error.message));
1697
+ }
1698
+ var PluginMcpClient = class {
1699
+ client;
1700
+ clientPromise;
1701
+ lastAttemptedTransportSessionId;
1702
+ providerStatusStore = new AsyncLocalStorage();
1703
+ transport;
1704
+ listedTools;
1705
+ resourceHost;
1706
+ plugin;
1707
+ options;
1708
+ constructor(plugin, options = {}) {
1709
+ this.plugin = plugin;
1710
+ this.options = options;
1711
+ const url = plugin.manifest.mcp?.url;
1712
+ this.resourceHost = url ? new URL(url).hostname : void 0;
1713
+ }
1714
+ async listTools() {
1715
+ if (this.listedTools) return [...this.listedTools];
1716
+ return await this.withSessionRecovery(async () => {
1717
+ const client = await this.getClient();
1718
+ const discovered = [];
1719
+ const seen = /* @__PURE__ */ new Set();
1720
+ let cursor;
1721
+ do {
1722
+ const result = await this.wrapAuth(() => client.listTools(cursor ? { cursor } : void 0), "list_tools");
1723
+ await this.syncTransportSessionId();
1724
+ for (const tool of result.tools) {
1725
+ if (seen.has(tool.name)) continue;
1726
+ seen.add(tool.name);
1727
+ discovered.push(tool);
1728
+ }
1729
+ cursor = result.nextCursor;
1730
+ } while (cursor);
1731
+ this.listedTools = discovered.sort((left, right) => left.name.localeCompare(right.name));
1732
+ return [...this.listedTools];
1733
+ });
1734
+ }
1735
+ async callTool(name, args, signal) {
1736
+ return await this.withSessionRecovery(async () => {
1737
+ const client = await this.getClient();
1738
+ const mcp = this.plugin.manifest.mcp;
1739
+ if (mcp) {
1740
+ const url = new URL(mcp.url);
1741
+ setSpanAttributes({
1742
+ "mcp.method.name": MCP_TOOLS_CALL_METHOD,
1743
+ "gen_ai.operation.name": "execute_tool",
1744
+ ...this.transport?.sessionId ? { "mcp.session.id": this.transport.sessionId } : void 0,
1745
+ ...this.transport?.protocolVersion ? { "mcp.protocol.version": this.transport.protocolVersion } : void 0,
1746
+ ...getMcpNetworkAttributes(url)
1747
+ });
1748
+ }
1749
+ const result = await this.wrapAuth(() => client.callTool({
1750
+ name,
1751
+ arguments: args ?? {}
1752
+ }, void 0, signal ? { signal } : void 0), "call_tool");
1753
+ await this.syncTransportSessionId();
1754
+ return result;
1755
+ });
1756
+ }
1757
+ async close() {
1758
+ await this.disposeClient();
1759
+ }
1760
+ async withSessionRecovery(operation) {
1761
+ try {
1762
+ return await operation();
1763
+ } catch (error) {
1764
+ await this.syncTransportSessionId();
1765
+ if (!await this.shouldResetMissingSession(error)) throw error;
1766
+ await this.clearStoredTransportSessionId();
1767
+ await this.cleanupClientAfterFailure();
1768
+ return await operation();
1769
+ }
1770
+ }
1771
+ async getClient() {
1772
+ if (this.client) return this.client;
1773
+ if (this.clientPromise) return await this.clientPromise;
1774
+ const clientPromise = this.connectClient();
1775
+ this.clientPromise = clientPromise;
1776
+ try {
1777
+ return await clientPromise;
1778
+ } finally {
1779
+ if (this.clientPromise === clientPromise) this.clientPromise = void 0;
1780
+ }
1781
+ }
1782
+ async connectClient() {
1783
+ const mcp = this.plugin.manifest.mcp;
1784
+ if (!mcp) throw new Error(`Plugin "${this.plugin.manifest.name}" does not declare MCP config`);
1785
+ const headers = mcp.headers ? resolvePluginHeaderEnvRefs(this.plugin.manifest.name, mcp.headers, "MCP header") : void 0;
1786
+ const sessionId = await this.getStoredTransportSessionId();
1787
+ this.lastAttemptedTransportSessionId = sessionId;
1788
+ const loginProvider = this.options.authProvider;
1789
+ const mcpLoginOwner = loginProvider?.mcpLoginOwner?.bind(loginProvider);
1790
+ const providerFetch = mcpLoginOwner ? serializeMcpTokenRefresh(mcpLoginOwner, this.options.fetch) : this.options.fetch;
1791
+ const transport = new StreamableHTTPClientTransport(new URL(mcp.url), {
1792
+ ...headers ? { requestInit: { headers } } : void 0,
1793
+ fetch: fetchWithBoundedOAuthErrorBodies(providerFetch, (status) => {
1794
+ const store = this.providerStatusStore.getStore();
1795
+ if (store) store.status = status;
1796
+ }),
1797
+ ...this.options.authProvider ? { authProvider: this.options.authProvider } : void 0,
1798
+ ...sessionId ? { sessionId } : void 0
1799
+ });
1800
+ const client = new Client(MCP_CLIENT_INFO, { capabilities: {} });
1801
+ this.transport = transport;
1802
+ try {
1803
+ await this.wrapAuth(() => client.connect(transport), "connect");
1804
+ this.client = client;
1805
+ await this.syncTransportSessionId();
1806
+ return client;
1807
+ } catch (error) {
1808
+ await this.syncTransportSessionId();
1809
+ await this.cleanupClientAfterFailure();
1810
+ throw error;
1811
+ }
1812
+ }
1813
+ async wrapAuth(operation, phase) {
1814
+ const store = {};
1815
+ return await this.providerStatusStore.run(store, async () => {
1816
+ try {
1817
+ return await operation();
1818
+ } catch (error) {
1819
+ if (error instanceof McpAuthorizationRequiredError) throw error;
1820
+ if (error instanceof UnauthorizedError) throw new McpAuthorizationRequiredError(this.plugin.manifest.name, `MCP authorization required for plugin "${this.plugin.manifest.name}"`);
1821
+ throw toMcpProviderError(error, {
1822
+ phase,
1823
+ provider: this.plugin.manifest.name,
1824
+ missingSession: isMissingSessionError(error) || void 0,
1825
+ resourceHost: this.resourceHost,
1826
+ status: store.status
1827
+ });
1828
+ }
1829
+ });
1830
+ }
1831
+ async shouldResetMissingSession(error) {
1832
+ if (!(error instanceof McpProviderError && error.missingSession || isMissingSessionError(error))) return false;
1833
+ return Boolean(this.transport?.sessionId ?? this.lastAttemptedTransportSessionId ?? await this.getStoredTransportSessionId());
1834
+ }
1835
+ resetClientState() {
1836
+ const transport = this.transport;
1837
+ this.listedTools = void 0;
1838
+ this.transport = void 0;
1839
+ this.client = void 0;
1840
+ this.clientPromise = void 0;
1841
+ return transport;
1842
+ }
1843
+ async cleanupClientAfterFailure() {
1844
+ const transport = this.resetClientState();
1845
+ if (!transport) return;
1846
+ try {
1847
+ await transport.close();
1848
+ } catch {}
1849
+ }
1850
+ async disposeClient() {
1851
+ const transport = this.resetClientState();
1852
+ if (transport) try {
1853
+ await transport.close();
1854
+ } catch (error) {
1855
+ throw toMcpProviderError(error, {
1856
+ phase: "close",
1857
+ provider: this.plugin.manifest.name,
1858
+ resourceHost: this.resourceHost
1859
+ });
1860
+ }
1861
+ }
1862
+ async getStoredTransportSessionId() {
1863
+ return await this.options.authProvider?.getMcpServerSessionId?.();
1864
+ }
1865
+ async clearStoredTransportSessionId() {
1866
+ const provider = this.options.authProvider;
1867
+ this.lastAttemptedTransportSessionId = void 0;
1868
+ await provider?.saveMcpServerSessionId?.(void 0);
1869
+ }
1870
+ async syncTransportSessionId() {
1871
+ const provider = this.options.authProvider;
1872
+ const sessionId = this.transport?.sessionId;
1873
+ if (!provider?.saveMcpServerSessionId || !sessionId) return;
1874
+ this.lastAttemptedTransportSessionId = sessionId;
1875
+ await provider.saveMcpServerSessionId(sessionId);
1876
+ }
1877
+ };
1878
+ // src/chat/mcp/service-account.ts
1879
+ /**
1880
+ * MCP service account credentials.
1881
+ *
1882
+ * This is the MCP surface of a plugin's service account. See
1883
+ * `@/chat/credentials/service-account` for the credential order and the
1884
+ * policy. An Admin connects the account from the dashboard Admin page, or
1885
+ * with `junior service-account connect <plugin>`. The credential stays on
1886
+ * the host. The sandbox and the model never get it.
1887
+ */
1888
+ const SERVICE_ACCOUNT_KEY_PREFIX$1 = "junior:mcp_service_account";
1889
+ const SIGN_IN_KEY_PREFIX$1 = "junior:mcp_service_account_sign_in";
1890
+ const SIGN_IN_TTL_MS$1 = 6e5;
1891
+ const UPDATE_LOCK_WAIT_MS = 5e3;
1892
+ function serviceAccountKey$1(provider) {
1893
+ return `${SERVICE_ACCOUNT_KEY_PREFIX$1}:${provider}`;
1894
+ }
1895
+ function updateLockKey$1(provider) {
1896
+ return `${serviceAccountKey$1(provider)}:update`;
1897
+ }
1898
+ const storedOAuthClientInformationSchema = z.custom((value) => typeof value === "object" && value !== null);
1899
+ const storedOAuthDiscoveryStateSchema = z.custom((value) => typeof value === "object" && value !== null);
1900
+ const storedOAuthTokensSchema = z.custom((value) => typeof value === "object" && value !== null);
1901
+ const credentialsSchema$1 = z.object({
1902
+ clientInformation: storedOAuthClientInformationSchema,
1903
+ connectedAtMs: z.number(),
1904
+ connectedBy: z.string().optional().catch(void 0),
1905
+ discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
1906
+ redirectUrl: z.string(),
1907
+ tokens: storedOAuthTokensSchema
1908
+ });
1909
+ function parseCredentials$1(value) {
1910
+ try {
1911
+ const parsed = credentialsSchema$1.safeParse(typeof value === "string" ? JSON.parse(value) : value);
1912
+ return parsed.success ? parsed.data : void 0;
1913
+ } catch {
1914
+ return;
1915
+ }
1916
+ }
1917
+ /** Read the connected service account for one plugin, if any. */
1918
+ async function getMcpServiceAccountCredentials(provider) {
1919
+ const stored = await readEncryptedState(getStateAdapter(), serviceAccountKey$1(provider));
1920
+ const credentials = parseCredentials$1(stored?.value);
1921
+ if (credentials && stored?.stale) await saveStaleCredentials(provider);
1922
+ return credentials;
1923
+ }
1924
+ /**
1925
+ * Save stale credentials again with the active key. It runs only when the
1926
+ * update lock is free, so it cannot write back a refresh token that an
1927
+ * update replaced.
1928
+ */
1929
+ async function saveStaleCredentials(provider) {
1930
+ const state = getStateAdapter();
1931
+ await withLock(state, updateLockKey$1(provider), async (lock) => {
1932
+ const key = serviceAccountKey$1(provider);
1933
+ const current = await readEncryptedState(state, key);
1934
+ const credentials = parseCredentials$1(current?.value);
1935
+ if (!current?.stale || !credentials) return;
1936
+ await fenceLock(state, lock);
1937
+ await putMcpServiceAccountCredentials(provider, credentials);
1938
+ }, { ttlMs: MUTATION_LOCK_TTL_MS });
1939
+ }
1940
+ /** Save the service account for one plugin. It does not expire. */
1941
+ async function putMcpServiceAccountCredentials(provider, credentials) {
1942
+ await createEncryptedState(getStateAdapter()).set(serviceAccountKey$1(provider), credentials);
1943
+ }
1944
+ /** Remove the service account for one plugin. The provider grant stays until the provider revokes it. */
1945
+ async function deleteMcpServiceAccountCredentials(provider) {
1946
+ await getStateAdapter().delete(serviceAccountKey$1(provider));
1947
+ }
1948
+ function clientMetadata(redirectUrl) {
1949
+ return {
1950
+ client_name: `${botConfig.userName} MCP Service Account`,
1951
+ redirect_uris: [redirectUrl],
1952
+ grant_types: ["authorization_code", "refresh_token"],
1953
+ response_types: ["code"],
1954
+ token_endpoint_auth_method: "none"
1955
+ };
1956
+ }
1957
+ function reconnectMessage(provider) {
1958
+ return `The ${provider} service account is not authorized anymore. An admin must run \`junior service-account connect ${provider}\`.`;
1959
+ }
1960
+ /**
1961
+ * Build the OAuth client provider for a connected service account.
1962
+ *
1963
+ * It refreshes tokens like a user connection but never starts a new sign-in.
1964
+ * Many turns share this account, so it reads the store on each request and
1965
+ * writes each change under a lock. When the provider rejects a refresh token
1966
+ * that another turn already replaced, it retries with the stored one. It
1967
+ * deletes the stored grant only when the provider rejected the stored token
1968
+ * itself, and then throws `McpAuthorizationRequiredError` so the tool manager
1969
+ * can fall back to Actor auth or report the missing account. A refresh that
1970
+ * fails for another reason, such as a network error, keeps the account.
1971
+ */
1972
+ function createMcpServiceAccountClientProvider(provider, connected) {
1973
+ let lastRefreshToken = connected.tokens.refresh_token;
1974
+ let tokensRejected = false;
1975
+ const withStoreLock = async (run) => {
1976
+ const state = getStateAdapter();
1977
+ const result = await withLock(state, updateLockKey$1(provider), async (lock) => await run(() => fenceLock(state, lock)), {
1978
+ ttlMs: MUTATION_LOCK_TTL_MS,
1979
+ waitMs: UPDATE_LOCK_WAIT_MS
1980
+ });
1981
+ if (!result.acquired) throw new Error(`Timed out waiting to update the ${provider} service account`);
1982
+ return result.value;
1983
+ };
1984
+ const update = async (patch) => {
1985
+ await withStoreLock(async (fence) => {
1986
+ const current = await getMcpServiceAccountCredentials(provider);
1987
+ if (!current) throw new Error(reconnectMessage(provider));
1988
+ await fence();
1989
+ await putMcpServiceAccountCredentials(provider, {
1990
+ ...current,
1991
+ ...patch
1992
+ });
1993
+ });
1994
+ };
1995
+ return {
1996
+ redirectUrl: connected.redirectUrl,
1997
+ clientMetadata: clientMetadata(connected.redirectUrl),
1998
+ clientInformation: async () => (await getMcpServiceAccountCredentials(provider))?.clientInformation,
1999
+ saveClientInformation: async (clientInformation) => {
2000
+ await update({ clientInformation });
2001
+ },
2002
+ tokens: async () => {
2003
+ const tokens = (await getMcpServiceAccountCredentials(provider))?.tokens;
2004
+ if (tokensRejected) {
2005
+ if (!tokens || tokens.refresh_token === lastRefreshToken) return;
2006
+ tokensRejected = false;
2007
+ }
2008
+ lastRefreshToken = tokens?.refresh_token;
2009
+ return tokens;
2010
+ },
2011
+ saveTokens: async (tokens) => {
2012
+ tokensRejected = false;
2013
+ lastRefreshToken = tokens.refresh_token;
2014
+ await update({ tokens });
2015
+ },
2016
+ discoveryState: async () => (await getMcpServiceAccountCredentials(provider))?.discoveryState,
2017
+ saveDiscoveryState: async (discoveryState) => {
2018
+ await update({ discoveryState });
2019
+ },
2020
+ invalidateCredentials: (scope) => {
2021
+ if (scope === "all" || scope === "tokens") tokensRejected = true;
2022
+ },
2023
+ redirectToAuthorization: async () => {
2024
+ if (!await withStoreLock(async (fence) => {
2025
+ const stored = await getMcpServiceAccountCredentials(provider);
2026
+ if (!stored) return true;
2027
+ if (!tokensRejected && stored.tokens.refresh_token || stored.tokens.refresh_token !== lastRefreshToken) return false;
2028
+ await fence();
2029
+ await deleteMcpServiceAccountCredentials(provider);
2030
+ logWarn("mcp.service_account.disconnected", { "app.plugin.name": provider });
2031
+ return true;
2032
+ })) throw new Error(`The ${provider} service account could not refresh its token. Try again later.`);
2033
+ throw new McpAuthorizationRequiredError(provider, reconnectMessage(provider));
2034
+ },
2035
+ saveCodeVerifier: () => void 0,
2036
+ codeVerifier: () => {
2037
+ throw new Error(reconnectMessage(provider));
2038
+ }
2039
+ };
2040
+ }
2041
+ function signInKey$1(state) {
2042
+ return `${SIGN_IN_KEY_PREFIX$1}:${state}`;
2043
+ }
2044
+ const signInSchema$1 = z.object({
2045
+ clientInformation: storedOAuthClientInformationSchema,
2046
+ codeVerifier: z.string(),
2047
+ discoveryState: storedOAuthDiscoveryStateSchema.optional().catch(void 0),
2048
+ provider: z.string(),
2049
+ redirectUrl: z.string(),
2050
+ startedBy: z.string().optional().catch(void 0)
2051
+ });
2052
+ function parseSignIn(value) {
2053
+ const parsed = signInSchema$1.safeParse(value);
2054
+ return parsed.success ? parsed.data : void 0;
2055
+ }
2056
+ /** Build an OAuth client provider that keeps sign-in state in memory. */
2057
+ function signInProvider(input) {
2058
+ const captured = {
2059
+ clientInformation: input.pending?.clientInformation,
2060
+ codeVerifier: input.pending?.codeVerifier,
2061
+ discoveryState: input.pending?.discoveryState
2062
+ };
2063
+ return {
2064
+ captured,
2065
+ provider: {
2066
+ redirectUrl: input.redirectUrl,
2067
+ clientMetadata: clientMetadata(input.redirectUrl),
2068
+ ...input.state ? { state: () => input.state } : void 0,
2069
+ clientInformation: () => captured.clientInformation,
2070
+ saveClientInformation: (next) => {
2071
+ captured.clientInformation = next;
2072
+ },
2073
+ tokens: () => captured.tokens,
2074
+ saveTokens: (next) => {
2075
+ captured.tokens = next;
2076
+ },
2077
+ discoveryState: () => captured.discoveryState,
2078
+ saveDiscoveryState: (next) => {
2079
+ captured.discoveryState = next;
2080
+ },
2081
+ redirectToAuthorization: (url) => {
2082
+ captured.authorizationUrl = url;
2083
+ },
2084
+ saveCodeVerifier: (next) => {
2085
+ captured.codeVerifier = next;
2086
+ },
2087
+ codeVerifier: () => {
2088
+ if (!captured.codeVerifier) throw new Error("Missing MCP OAuth code verifier");
2089
+ return captured.codeVerifier;
2090
+ }
2091
+ }
2092
+ };
2093
+ }
2094
+ function requireServiceAccountMcp(plugin) {
2095
+ const mcp = plugin.manifest.mcp;
2096
+ if (!mcp || !plugin.manifest.accounts?.serviceAccount) throw new Error(`Plugin "${plugin.manifest.name}" does not support a service account`);
2097
+ return mcp;
2098
+ }
2099
+ /**
2100
+ * Start a service account sign-in and return the provider sign-in URL.
2101
+ *
2102
+ * The pending sign-in is single use and expires after a short time. Whoever
2103
+ * signs in decides which account Junior uses, so only Junior admins may start
2104
+ * it.
2105
+ */
2106
+ async function startMcpServiceAccountSignIn(input) {
2107
+ const mcp = requireServiceAccountMcp(input.plugin);
2108
+ const provider = input.plugin.manifest.name;
2109
+ const state = randomUUID();
2110
+ const signIn = signInProvider({
2111
+ redirectUrl: input.redirectUrl,
2112
+ state
2113
+ });
2114
+ if (await auth(signIn.provider, { serverUrl: mcp.url }) !== "REDIRECT") throw new Error(`${provider} did not start an OAuth sign-in`);
2115
+ const { authorizationUrl, clientInformation, codeVerifier, discoveryState } = signIn.captured;
2116
+ if (!authorizationUrl || !clientInformation || !codeVerifier) throw new Error(`${provider} did not return an authorization URL`);
2117
+ await createEncryptedState(getStateAdapter()).set(signInKey$1(state), {
2118
+ clientInformation,
2119
+ codeVerifier,
2120
+ ...discoveryState ? { discoveryState } : void 0,
2121
+ provider,
2122
+ redirectUrl: input.redirectUrl,
2123
+ ...input.startedBy ? { startedBy: input.startedBy } : void 0
2124
+ }, SIGN_IN_TTL_MS$1);
2125
+ return { authorizationUrl };
2126
+ }
2127
+ /**
2128
+ * Finish a service account sign-in from the OAuth callback parameters.
2129
+ *
2130
+ * It accepts only a pending sign-in for the same plugin that the same Admin
2131
+ * started. It then saves the grant as the plugin's service account.
2132
+ */
2133
+ async function finishMcpServiceAccountSignIn(input) {
2134
+ const mcp = requireServiceAccountMcp(input.plugin);
2135
+ const provider = input.plugin.manifest.name;
2136
+ const state = input.callback.get("state");
2137
+ const pending = state ? parseSignIn(await createEncryptedState(getStateAdapter()).get(signInKey$1(state))) : void 0;
2138
+ if (!state || !pending || pending.provider !== provider || pending.startedBy !== input.connectedBy) return {
2139
+ ok: false,
2140
+ message: "This sign-in expired or did not start here. Start it again."
2141
+ };
2142
+ await getStateAdapter().delete(signInKey$1(state));
2143
+ const error = input.callback.get("error");
2144
+ if (error) return {
2145
+ ok: false,
2146
+ message: `${provider} did not finish the sign-in (${error}).`
2147
+ };
2148
+ const authorizationCode = input.callback.get("code");
2149
+ if (!authorizationCode) return {
2150
+ ok: false,
2151
+ message: `${provider} did not return an authorization code.`
2152
+ };
2153
+ const signIn = signInProvider({
2154
+ pending,
2155
+ redirectUrl: pending.redirectUrl
2156
+ });
2157
+ await auth(signIn.provider, {
2158
+ serverUrl: mcp.url,
2159
+ authorizationCode
2160
+ });
2161
+ const { clientInformation, discoveryState, tokens } = signIn.captured;
2162
+ if (!clientInformation || !tokens) throw new Error(`${provider} did not issue tokens`);
2163
+ const credentials = {
2164
+ clientInformation,
2165
+ connectedAtMs: Date.now(),
2166
+ ...input.connectedBy ? { connectedBy: input.connectedBy } : void 0,
2167
+ ...discoveryState ? { discoveryState } : void 0,
2168
+ redirectUrl: pending.redirectUrl,
2169
+ tokens
2170
+ };
2171
+ await putMcpServiceAccountCredentials(provider, credentials);
2172
+ return {
2173
+ ok: true,
2174
+ credentials
2175
+ };
2176
+ }
2177
+ // src/chat/credentials/oauth-scope.ts
2178
+ function parseScope(scope) {
2179
+ if (!scope) return [];
2180
+ return [...new Set(scope.split(/\s+/).filter(Boolean))].sort();
2181
+ }
2182
+ /** Normalize OAuth scope strings so persisted grants can be compared reliably. */
2183
+ function normalizeOAuthScope(scope) {
2184
+ const parsed = parseScope(scope);
2185
+ return parsed.length > 0 ? parsed.join(" ") : void 0;
2186
+ }
2187
+ /** Return whether the stored grant still satisfies the provider's current scope contract. */
2188
+ function hasRequiredOAuthScope(storedScope, requiredScope) {
2189
+ const required = parseScope(requiredScope);
2190
+ if (required.length === 0) return true;
2191
+ const stored = new Set(parseScope(storedScope));
2192
+ if (stored.size === 0) return false;
2193
+ return required.every((scope) => stored.has(scope));
2194
+ }
2195
+ // src/chat/plugins/auth/oauth-request.ts
2196
+ const DEFAULT_TOKEN_CONTENT_TYPE = "application/x-www-form-urlencoded";
2197
+ function requireNonEmptyTokenField(data, field) {
2198
+ const value = data[field];
2199
+ if (typeof value !== "string" || !value.trim()) throw new Error(`OAuth token response missing ${field}`);
2200
+ return value;
2201
+ }
2202
+ function requireTokenResponseObject(data) {
2203
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("OAuth token response must be an object");
2204
+ return data;
2205
+ }
2206
+ const parsedOAuthAccessTokenResponseSchema = z.object({
2207
+ accessToken: z.string().min(1),
2208
+ refreshToken: z.string().min(1).optional(),
2209
+ expiresAt: z.number().positive().optional(),
2210
+ refreshTokenExpiresAt: z.number().positive().optional(),
2211
+ scope: z.string().min(1).optional()
2212
+ }).strict();
2213
+ function contentTypeToBody(contentType, payload) {
2214
+ const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase();
2215
+ if (!mediaType || mediaType === DEFAULT_TOKEN_CONTENT_TYPE) return new URLSearchParams(payload);
2216
+ if (mediaType === "application/json" || mediaType.endsWith("+json")) return JSON.stringify(payload);
2217
+ throw new Error(`Unsupported OAuth token Content-Type: ${contentType}`);
2218
+ }
2219
+ function buildOAuthTokenRequest(input) {
2220
+ const headers = new Headers({ Accept: "application/json" });
2221
+ for (const [name, value] of Object.entries(input.tokenExtraHeaders ?? {})) headers.set(name, value);
2222
+ if (!headers.has("Content-Type")) headers.set("Content-Type", DEFAULT_TOKEN_CONTENT_TYPE);
2223
+ const payload = { ...input.payload };
2224
+ if (input.tokenAuthMethod === "basic") headers.set("Authorization", `Basic ${Buffer.from(`${input.clientId}:${input.clientSecret}`).toString("base64")}`);
2225
+ else {
2226
+ payload["client_id"] = input.clientId;
2227
+ payload["client_secret"] = input.clientSecret;
2228
+ }
2229
+ const contentType = headers.get("Content-Type") ?? DEFAULT_TOKEN_CONTENT_TYPE;
2230
+ const serializedHeaders = {};
2231
+ for (const [key, value] of headers) serializedHeaders[key] = value;
2232
+ return {
2233
+ headers: serializedHeaders,
2234
+ body: contentTypeToBody(contentType, payload)
2235
+ };
2236
+ }
2237
+ /** Parse provider tokens, retaining the request token when a refresh response omits rotation. */
2238
+ function parseOAuthTokenResponse(data, requestedScope, options) {
2239
+ const parsed = parseOAuthAccessTokenResponse(data, requestedScope, options);
2240
+ const { refreshToken } = parsed;
2241
+ if (!refreshToken) throw new Error("OAuth token response missing refresh_token");
2242
+ return {
2243
+ ...parsed,
2244
+ refreshToken
2245
+ };
2246
+ }
2247
+ /**
2248
+ * Parse provider tokens that may come without a refresh token, such as a
2249
+ * token that does not expire.
2250
+ */
2251
+ function parseOAuthAccessTokenResponse(data, requestedScope, options) {
2252
+ const response = requireTokenResponseObject(data);
2253
+ const accessToken = requireNonEmptyTokenField(response, "access_token");
2254
+ const resolvedRefreshToken = response["refresh_token"] === void 0 ? options?.refreshToken : requireNonEmptyTokenField(response, "refresh_token");
2255
+ const expiresIn = response["expires_in"];
2256
+ const refreshTokenExpiresIn = response["refresh_token_expires_in"];
2257
+ const responseScope = response["scope"];
2258
+ let scope;
2259
+ if (responseScope !== void 0) {
2260
+ if (typeof responseScope !== "string") throw new Error("OAuth token response returned invalid scope");
2261
+ const normalized = normalizeOAuthScope(responseScope);
2262
+ if (normalized !== void 0) scope = normalized;
2263
+ else if (options?.treatEmptyScopeAsUnreported) scope = normalizeOAuthScope(requestedScope);
2264
+ else throw new Error("OAuth token response returned empty scope");
2265
+ } else scope = normalizeOAuthScope(requestedScope);
2266
+ const result = {
2267
+ accessToken,
2268
+ ...resolvedRefreshToken ? { refreshToken: resolvedRefreshToken } : void 0,
2269
+ ...scope ? { scope } : void 0
2270
+ };
2271
+ if (expiresIn !== void 0) {
2272
+ if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) throw new Error("OAuth token response returned invalid expires_in");
2273
+ result.expiresAt = Date.now() + expiresIn * 1e3;
2274
+ }
2275
+ if (refreshTokenExpiresIn !== void 0) {
2276
+ if (typeof refreshTokenExpiresIn !== "number" || !Number.isFinite(refreshTokenExpiresIn) || refreshTokenExpiresIn <= 0) throw new Error("OAuth token response returned invalid refresh_token_expires_in");
2277
+ result.refreshTokenExpiresAt = Date.now() + refreshTokenExpiresIn * 1e3;
2278
+ }
2279
+ return parsedOAuthAccessTokenResponseSchema.parse(result);
2280
+ }
2281
+ // src/chat/plugins/auth/oauth-service-account.ts
2282
+ /**
2283
+ * OAuth service account credentials.
2284
+ *
2285
+ * This is the top-level `oauth` surface of a plugin's service account. See
2286
+ * `@/chat/credentials/service-account` for the credential order and the
2287
+ * policy. An Admin signs in once as the shared provider account. The
2288
+ * oauth-bearer broker then reads the stored token for host egress requests
2289
+ * that name an operation the account lists. The credential stays on the
2290
+ * host. The sandbox and the model never get it.
2291
+ */
2292
+ const SERVICE_ACCOUNT_KEY_PREFIX = "junior:oauth_service_account";
2293
+ const SIGN_IN_KEY_PREFIX = "junior:oauth_service_account_sign_in";
2294
+ const SIGN_IN_TTL_MS = 6e5;
2295
+ const REFRESH_LOCK_TTL_MS = 3e4;
2296
+ const REFRESH_LOCK_WAIT_MS = 3e4;
2297
+ const TOKEN_EXCHANGE_TIMEOUT_MS = 2e4;
2298
+ const credentialsSchema = z.object({
2299
+ accessToken: z.string().min(1),
2300
+ connectedAtMs: z.number(),
2301
+ connectedBy: z.string().optional().catch(void 0),
2302
+ expiresAt: z.number().optional(),
2303
+ refreshToken: z.string().min(1).optional(),
2304
+ refreshTokenExpiresAt: z.number().optional(),
2305
+ scope: z.string().optional()
2306
+ });
2307
+ function serviceAccountKey(provider) {
2308
+ return `${SERVICE_ACCOUNT_KEY_PREFIX}:${provider}`;
2309
+ }
2310
+ function parseCredentials(value) {
2311
+ const parsed = credentialsSchema.safeParse(value);
2312
+ return parsed.success ? parsed.data : void 0;
2313
+ }
2314
+ /** Read the connected OAuth service account for one plugin, if any. */
2315
+ async function getOAuthServiceAccountCredentials(provider) {
2316
+ const state = getStateAdapter();
2317
+ const stored = await readEncryptedState(state, serviceAccountKey(provider));
2318
+ const credentials = parseCredentials(stored?.value);
2319
+ if (credentials && stored?.stale) await withLock(state, updateLockKey(provider), async (lock) => {
2320
+ const current = await readEncryptedState(state, serviceAccountKey(provider));
2321
+ const latest = parseCredentials(current?.value);
2322
+ if (!current?.stale || !latest) return;
2323
+ await fenceLock(state, lock);
2324
+ await putOAuthServiceAccountCredentials(provider, latest);
2325
+ }, { ttlMs: MUTATION_LOCK_TTL_MS });
2326
+ return credentials;
2327
+ }
2328
+ /** Save the OAuth service account for one plugin. */
2329
+ async function putOAuthServiceAccountCredentials(provider, credentials) {
2330
+ await createEncryptedState(getStateAdapter()).set(serviceAccountKey(provider), credentials);
2331
+ }
2332
+ /** Remove the OAuth service account. The provider grant stays until someone revokes it. */
2333
+ async function deleteOAuthServiceAccountCredentials(provider) {
2334
+ await getStateAdapter().delete(serviceAccountKey(provider));
2335
+ }
2336
+ function updateLockKey(provider) {
2337
+ return `${serviceAccountKey(provider)}:update`;
2338
+ }
2339
+ /**
2340
+ * Run a read and write of the stored account under one lock, so a turn
2341
+ * cannot write back or delete a refresh token that another turn replaced.
2342
+ */
2343
+ async function withOAuthServiceAccountLock(provider, run) {
2344
+ const state = getStateAdapter();
2345
+ const result = await withLock(state, updateLockKey(provider), async (lock) => await run(() => fenceLock(state, lock)), {
2346
+ ttlMs: REFRESH_LOCK_TTL_MS,
2347
+ waitMs: REFRESH_LOCK_WAIT_MS
2348
+ });
2349
+ if (!result.acquired) throw new Error(`Timed out waiting to update the ${provider} service account`);
2350
+ return result.value;
2351
+ }
2352
+ /** Pending OAuth service account sign-in, kept until the callback. */
2353
+ const signInSchema = z.object({
2354
+ provider: z.string(),
2355
+ redirectUrl: z.string(),
2356
+ /** Email of the Admin who started the sign-in. Only they may finish it. */
2357
+ startedBy: z.string().optional().catch(void 0)
2358
+ });
2359
+ function signInKey(state) {
2360
+ return `${SIGN_IN_KEY_PREFIX}:${state}`;
2361
+ }
2362
+ function requireServiceAccountOAuth(plugin) {
2363
+ const { oauth, accounts, name } = plugin.manifest;
2364
+ if (!oauth || !accounts?.serviceAccount?.operations) throw new Error(`Plugin "${name}" does not support an OAuth service account`);
2365
+ return oauth;
2366
+ }
2367
+ function requireEnv(name) {
2368
+ const value = process.env[name]?.trim();
2369
+ if (!value) throw new Error(`Missing ${name} environment variable`);
2370
+ return value;
2371
+ }
2372
+ /**
2373
+ * Start an OAuth service account sign-in and return the provider sign-in URL.
2374
+ *
2375
+ * The pending sign-in is single use and expires after a short time.
2376
+ */
2377
+ async function startOAuthServiceAccountSignIn(input) {
2378
+ const oauth = requireServiceAccountOAuth(input.plugin);
2379
+ const clientId = requireEnv(oauth.clientIdEnv);
2380
+ const state = randomBytes(32).toString("hex");
2381
+ await createEncryptedState(getStateAdapter()).set(signInKey(state), {
2382
+ provider: input.plugin.manifest.name,
2383
+ redirectUrl: input.redirectUrl,
2384
+ ...input.startedBy ? { startedBy: input.startedBy } : void 0
2385
+ }, SIGN_IN_TTL_MS);
2386
+ const authorizationUrl = new URL(oauth.authorizeEndpoint);
2387
+ authorizationUrl.searchParams.set("client_id", clientId);
2388
+ authorizationUrl.searchParams.set("state", state);
2389
+ authorizationUrl.searchParams.set("redirect_uri", input.redirectUrl);
2390
+ authorizationUrl.searchParams.set("response_type", "code");
2391
+ if (oauth.scope) authorizationUrl.searchParams.set("scope", oauth.scope);
2392
+ for (const [key, value] of Object.entries(oauth.authorizeParams ?? {})) authorizationUrl.searchParams.set(key, value);
2393
+ return { authorizationUrl };
2394
+ }
2395
+ /**
2396
+ * Finish an OAuth service account sign-in from the callback parameters.
2397
+ *
2398
+ * It accepts only a pending sign-in for the same plugin that the same Admin
2399
+ * started, exchanges the code, and saves the tokens. A failure message is
2400
+ * safe to show the Admin. Network failures throw.
2401
+ */
2402
+ async function finishOAuthServiceAccountSignIn(input) {
2403
+ const oauth = requireServiceAccountOAuth(input.plugin);
2404
+ const provider = input.plugin.manifest.name;
2405
+ const state = input.callback.get("state");
2406
+ const parsedPending = state ? signInSchema.safeParse(await createEncryptedState(getStateAdapter()).get(signInKey(state))) : void 0;
2407
+ const pending = parsedPending?.success ? parsedPending.data : void 0;
2408
+ if (!state || !pending || pending.provider !== provider || pending.startedBy !== input.connectedBy) return {
2409
+ ok: false,
2410
+ message: "This sign-in expired or did not start here. Start it again."
2411
+ };
2412
+ await getStateAdapter().delete(signInKey(state));
2413
+ const error = input.callback.get("error");
2414
+ if (error) return {
2415
+ ok: false,
2416
+ message: `${provider} did not finish the sign-in (${error}).`
2417
+ };
2418
+ const code = input.callback.get("code");
2419
+ if (!code) return {
2420
+ ok: false,
2421
+ message: `${provider} did not return an authorization code.`
2422
+ };
2423
+ const request = buildOAuthTokenRequest({
2424
+ clientId: requireEnv(oauth.clientIdEnv),
2425
+ clientSecret: requireEnv(oauth.clientSecretEnv),
2426
+ payload: {
2427
+ grant_type: "authorization_code",
2428
+ code,
2429
+ redirect_uri: pending.redirectUrl
2430
+ },
2431
+ tokenAuthMethod: oauth.tokenAuthMethod,
2432
+ tokenExtraHeaders: oauth.tokenExtraHeaders
2433
+ });
2434
+ const response = await fetch(oauth.tokenEndpoint, {
2435
+ method: "POST",
2436
+ headers: request.headers,
2437
+ body: request.body,
2438
+ signal: AbortSignal.timeout(TOKEN_EXCHANGE_TIMEOUT_MS)
2439
+ });
2440
+ if (!response.ok) return {
2441
+ ok: false,
2442
+ message: `${provider} did not issue tokens (HTTP ${response.status}). Start the sign-in again.`
2443
+ };
2444
+ const tokens = parseOAuthAccessTokenResponse(await response.json(), oauth.scope, { treatEmptyScopeAsUnreported: oauth.treatEmptyScopeAsUnreported });
2445
+ if (!hasRequiredOAuthScope(tokens.scope, oauth.scope)) return {
2446
+ ok: false,
2447
+ message: `${provider} did not grant the required access (${oauth.scope}).`
2448
+ };
2449
+ await putOAuthServiceAccountCredentials(provider, {
2450
+ ...tokens,
2451
+ connectedAtMs: Date.now(),
2452
+ ...input.connectedBy ? { connectedBy: input.connectedBy } : void 0
2453
+ });
2454
+ return { ok: true };
2455
+ }
2456
+ // src/chat/credentials/service-account.ts
2457
+ /**
2458
+ * Service accounts.
2459
+ *
2460
+ * A plugin's `accounts` block can allow an optional install-wide provider
2461
+ * account, often a bot, that Junior itself uses. By default, the credential
2462
+ * order for one request is:
2463
+ *
2464
+ * 1. The Actor's own connection, when it exists.
2465
+ * 2. The plugin's service account, when an Admin connected it and
2466
+ * `accounts.service-account` lists what the request uses.
2467
+ * 3. Otherwise, the Actor must connect their own account.
2468
+ *
2469
+ * With `accounts.user-oauth: false`, Junior uses only the service account.
2470
+ * It ignores Actor connections, never asks an Actor to connect, and hides
2471
+ * what the account does not list. Until an Admin connects the account, the
2472
+ * plugin is not available.
2473
+ *
2474
+ * This module is the one place that decides which requests the service
2475
+ * account may serve. Each request surface asks it before it uses the shared
2476
+ * account. An MCP plugin lists the MCP tools it may call. A plugin with a
2477
+ * top-level `oauth` block lists the operations that its host code passes to
2478
+ * `egress.fetch`. Sandbox egress names no operation, so commands that the
2479
+ * model writes never get the shared account.
2480
+ *
2481
+ * This module also owns the connect flow that the dashboard Admin page and
2482
+ * the `junior service-account` CLI share. The MCP surface stores MCP OAuth
2483
+ * state, and the OAuth surface stores provider tokens.
2484
+ */
2485
+ /** Return whether the plugin's service account may serve this request. */
2486
+ function serviceAccountAllows(manifest, request) {
2487
+ const serviceAccount = manifest.accounts?.serviceAccount;
2488
+ return "tool" in request ? serviceAccount?.tools?.includes(request.tool) ?? false : serviceAccount?.operations?.includes(request.operation) ?? false;
2489
+ }
2490
+ /**
2491
+ * Return whether the plugin uses only its service account.
2492
+ *
2493
+ * Then no surface may fall back to an Actor's own connection or ask an
2494
+ * Actor to connect.
2495
+ */
2496
+ function serviceAccountOnly(manifest) {
2497
+ return manifest.accounts?.userOAuth === false;
2498
+ }
2499
+ /** Return the plugins whose `accounts` block allows a service account. */
2500
+ function serviceAccountPlugins(plugins) {
2501
+ return plugins.filter((plugin) => plugin.manifest.accounts?.serviceAccount);
2502
+ }
2503
+ /** Read the service account status for one plugin. */
2504
+ async function getServiceAccountStatus(plugin) {
2505
+ const { manifest } = plugin;
2506
+ const serviceAccount = manifest.accounts?.serviceAccount;
2507
+ if (!serviceAccount) throw new Error(`Plugin ${manifest.name} does not allow a service account`);
2508
+ const credentials = manifest.mcp ? await getMcpServiceAccountCredentials(manifest.name) : await getOAuthServiceAccountCredentials(manifest.name);
2509
+ return {
2510
+ provider: manifest.name,
2511
+ displayName: manifest.displayName,
2512
+ userOAuth: !serviceAccountOnly(manifest),
2513
+ tools: serviceAccount.tools ?? [],
2514
+ operations: serviceAccount.operations ?? [],
2515
+ connected: Boolean(credentials),
2516
+ ...credentials ? { connectedAt: new Date(credentials.connectedAtMs).toISOString() } : void 0,
2517
+ ...credentials?.connectedBy ? { connectedBy: credentials.connectedBy } : void 0
2518
+ };
2519
+ }
2520
+ /**
2521
+ * Start signing in to a plugin's provider as its service account.
2522
+ *
2523
+ * Whoever signs in decides which account Junior uses, so only Junior admins
2524
+ * may start it. `startedBy` binds the sign-in to that Admin.
2525
+ */
2526
+ async function startServiceAccountSignIn(input) {
2527
+ return input.plugin.manifest.mcp ? await startMcpServiceAccountSignIn(input) : await startOAuthServiceAccountSignIn(input);
2528
+ }
2529
+ /**
2530
+ * Finish a sign-in from its OAuth callback and save the service account.
2531
+ *
2532
+ * A failure message is safe to show the Admin. Unexpected provider failures
2533
+ * throw.
2534
+ */
2535
+ async function finishServiceAccountSignIn(input) {
2536
+ if (!input.plugin.manifest.mcp) return await finishOAuthServiceAccountSignIn(input);
2537
+ const result = await finishMcpServiceAccountSignIn(input);
2538
+ return result.ok ? { ok: true } : result;
2539
+ }
2540
+ /**
2541
+ * Remove a plugin's service account from Junior.
2542
+ *
2543
+ * The provider grant stays until someone revokes it in the provider.
2544
+ */
2545
+ async function disconnectServiceAccount(plugin) {
2546
+ await (plugin.manifest.mcp ? deleteMcpServiceAccountCredentials(plugin.manifest.name) : deleteOAuthServiceAccountCredentials(plugin.manifest.name));
2547
+ }
2548
+ // src/chat/credentials/header-transforms.ts
2549
+ /** Merge transforms by domain so later transforms override earlier headers. */
2550
+ function mergeHeaderTransforms(transforms) {
2551
+ const byDomain = /* @__PURE__ */ new Map();
2552
+ for (const transform of transforms) byDomain.set(transform.domain, {
2553
+ ...byDomain.get(transform.domain) ?? {},
2554
+ ...transform.headers
2555
+ });
2556
+ return [...byDomain.entries()].map(([domain, headers]) => ({
2557
+ domain,
2558
+ headers
2559
+ }));
2560
+ }
2561
+ // src/chat/plugins/auth/auth-token-placeholder.ts
2562
+ /**
2563
+ * The marker that every built-in Sandbox credential placeholder contains,
2564
+ * such as `host_managed_credential` or `ghp_host_managed_credential`.
2565
+ */
2566
+ const HOST_MANAGED_CREDENTIAL_PLACEHOLDER = "host_managed_credential";
2567
+ /** Resolve the non-secret sandbox token placeholder for token-backed credentials. */
2568
+ function resolveAuthTokenPlaceholder(credentials) {
2569
+ return credentials.authTokenPlaceholder?.trim() || "host_managed_credential";
2570
+ }
2571
+ // src/chat/plugins/auth/oauth-bearer-broker.ts
2572
+ const MAX_LEASE_MS = 36e5;
2573
+ const REFRESH_BUFFER_MS = 3e5;
2574
+ const TOKEN_REFRESH_TIMEOUT_MS = 2e4;
2575
+ var OAuthRefreshRejectedError = class extends Error {
2576
+ constructor(message) {
2577
+ super(message);
2578
+ this.name = "OAuthRefreshRejectedError";
2579
+ }
2580
+ };
2581
+ function parseRefreshError(text) {
2582
+ if (!text.trim()) return;
2583
+ try {
2584
+ const parsed = JSON.parse(text);
2585
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) && typeof parsed.error === "string" ? parsed.error : void 0;
2586
+ } catch {
2587
+ return;
2588
+ }
2589
+ }
2590
+ async function refreshAccessToken(provider, refreshToken, oauth, requestedScope) {
2591
+ const clientId = process.env[oauth.clientIdEnv]?.trim();
2592
+ const clientSecret = process.env[oauth.clientSecretEnv]?.trim();
2593
+ if (!clientId || !clientSecret) throw new Error(`Missing ${oauth.clientIdEnv} or ${oauth.clientSecretEnv} for token refresh`);
2594
+ const request = buildOAuthTokenRequest({
2595
+ clientId,
2596
+ clientSecret,
2597
+ payload: {
2598
+ grant_type: "refresh_token",
2599
+ refresh_token: refreshToken
2600
+ },
2601
+ tokenAuthMethod: oauth.tokenAuthMethod,
2602
+ tokenExtraHeaders: oauth.tokenExtraHeaders
2603
+ });
2604
+ const errorDetails = {
2605
+ phase: "token_refresh",
2606
+ provider,
2607
+ resourceHost: new URL(oauth.tokenEndpoint).hostname
2608
+ };
2609
+ let response;
2610
+ try {
2611
+ response = await fetch(oauth.tokenEndpoint, {
2612
+ method: "POST",
2613
+ headers: request.headers,
2614
+ body: request.body,
2615
+ signal: AbortSignal.timeout(TOKEN_REFRESH_TIMEOUT_MS)
2616
+ });
2617
+ } catch {
2618
+ throw new OAuthProviderError(errorDetails);
2619
+ }
2620
+ if (!response.ok) {
2621
+ let errorCode;
2622
+ try {
2623
+ errorCode = parseRefreshError(await readBoundedOAuthErrorBody(response));
2624
+ } catch {
2625
+ throw new OAuthProviderError({
2626
+ ...errorDetails,
2627
+ status: response.status
2628
+ });
2629
+ }
2630
+ if (errorCode === "invalid_grant" || errorCode === "bad_refresh_token") throw new OAuthRefreshRejectedError("Token refresh was rejected");
2631
+ throw new OAuthProviderError({
2632
+ ...errorDetails,
2633
+ status: response.status
2634
+ });
2635
+ }
2636
+ try {
2637
+ return parseOAuthTokenResponse(await response.json(), requestedScope, {
2638
+ treatEmptyScopeAsUnreported: oauth.treatEmptyScopeAsUnreported,
2639
+ refreshToken
2640
+ });
2641
+ } catch {
2642
+ throw new OAuthProviderError(errorDetails);
2643
+ }
2644
+ }
2645
+ function getLeaseExpiry(expiresAt) {
2646
+ return expiresAt ? Math.min(expiresAt, Date.now() + MAX_LEASE_MS) : Date.now() + MAX_LEASE_MS;
2647
+ }
2648
+ function canUseStoredToken(stored) {
2649
+ return stored !== void 0 && (stored.expiresAt === void 0 || stored.expiresAt > Date.now());
2650
+ }
2651
+ function shouldRefreshStoredToken(stored) {
2652
+ return stored !== void 0 && stored.expiresAt !== void 0 && stored.expiresAt - Date.now() < REFRESH_BUFFER_MS;
2653
+ }
2654
+ /**
2655
+ * Return a usable token of the plugin's OAuth service account, refreshing it
2656
+ * when it is about to expire. Returns nothing when no Admin connected it, or
2657
+ * when the provider rejected it, which removes the stored account.
2658
+ */
2659
+ async function serviceAccountToken(provider, oauth) {
2660
+ const stored = await getOAuthServiceAccountCredentials(provider);
2661
+ if (!shouldRefreshStoredToken(stored) || !stored?.refreshToken) return canUseStoredToken(stored) ? stored : void 0;
2662
+ return await withOAuthServiceAccountLock(provider, async (fence) => {
2663
+ const latest = await getOAuthServiceAccountCredentials(provider);
2664
+ if (!shouldRefreshStoredToken(latest) || !latest?.refreshToken) return canUseStoredToken(latest) ? latest : void 0;
2665
+ let refreshed;
2666
+ try {
2667
+ refreshed = await refreshAccessToken(provider, latest.refreshToken, oauth, latest.scope ?? oauth.scope);
2668
+ } catch (error) {
2669
+ if (!(error instanceof OAuthRefreshRejectedError)) throw error;
2670
+ await fence();
2671
+ await deleteOAuthServiceAccountCredentials(provider);
2672
+ logWarn("oauth.service_account.disconnected", { "app.plugin.name": provider });
2673
+ return;
2674
+ }
2675
+ const next = {
2676
+ ...latest,
2677
+ ...refreshed,
2678
+ expiresAt: refreshed.expiresAt
2679
+ };
2680
+ await fence();
2681
+ await putOAuthServiceAccountCredentials(provider, next);
2682
+ return next;
2683
+ });
2684
+ }
2685
+ function createOAuthBearerBroker(manifest, credentials, deps) {
2686
+ const provider = manifest.name;
2687
+ const { domains, apiHeaders, authTokenEnv } = credentials;
2688
+ const authTokenPlaceholder = resolveAuthTokenPlaceholder(credentials);
2689
+ const pluginHeaderTransforms = () => resolveApiHeaderTransforms(manifest);
2690
+ function buildLease(token, expiresAtMs, reason) {
2691
+ const env = resolvePluginCommandEnv(manifest);
2692
+ if (authTokenEnv) env[authTokenEnv] = authTokenPlaceholder;
2693
+ return {
2694
+ id: randomUUID(),
2695
+ provider,
2696
+ env,
2697
+ headerTransforms: mergeHeaderTransforms([...pluginHeaderTransforms(), ...domains.map((domain) => ({
2698
+ domain,
2699
+ headers: {
2700
+ ...apiHeaders ?? {},
2701
+ Authorization: `Bearer ${token}`
2702
+ }
2703
+ }))]),
2704
+ expiresAt: new Date(expiresAtMs).toISOString(),
2705
+ metadata: { reason }
2706
+ };
2707
+ }
2708
+ return { async issue(input) {
2709
+ const envToken = authTokenEnv ? process.env[authTokenEnv]?.trim() : void 0;
2710
+ const oauth = manifest.oauth;
2711
+ const userSubjectId = credentialUserSubjectId(input.context);
2712
+ const serviceAccountMayServe = input.operation !== void 0 && serviceAccountAllows(manifest, { operation: input.operation });
2713
+ const serviceAccountLease = async () => {
2714
+ const token = serviceAccountMayServe && oauth ? await serviceAccountToken(provider, oauth) : void 0;
2715
+ return token ? buildLease(token.accessToken, getLeaseExpiry(token.expiresAt), input.reason) : void 0;
2716
+ };
2717
+ if (!oauth) {
2718
+ if (envToken) return buildLease(envToken, Date.now() + MAX_LEASE_MS, input.reason);
2719
+ throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
2720
+ }
2721
+ if (serviceAccountOnly(manifest)) {
2722
+ const lease = await serviceAccountLease();
2723
+ if (lease) return lease;
2724
+ throw new ServiceAccountUnavailableError(provider, serviceAccountMayServe ? `The ${provider} service account is not connected. An admin must connect it on the dashboard Admin page.` : `The ${provider} service account does not allow this request.`);
2725
+ }
2726
+ if (userSubjectId) {
2727
+ const stored = await deps.userTokenStore.get(userSubjectId, provider);
2728
+ if (stored) {
2729
+ if (!hasRequiredOAuthScope(stored.scope, oauth.scope)) throw new CredentialUnavailableError(provider, `Your ${provider} connection needs to be reauthorized.`);
2730
+ if (shouldRefreshStoredToken(stored)) try {
2731
+ return await deps.userTokenStore.withRefresh(userSubjectId, provider, async () => {
2732
+ const latest = await deps.userTokenStore.get(userSubjectId, provider);
2733
+ if (latest && !hasRequiredOAuthScope(latest.scope, oauth.scope)) throw new CredentialUnavailableError(provider, `Your ${provider} connection needs to be reauthorized.`);
2734
+ if (!shouldRefreshStoredToken(latest) && canUseStoredToken(latest)) return buildLease(latest.accessToken, getLeaseExpiry(latest.expiresAt), input.reason);
2735
+ if (!latest) throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
2736
+ const refreshed = await refreshAccessToken(provider, latest.refreshToken, oauth, latest.scope ?? oauth.scope);
2737
+ if (!hasRequiredOAuthScope(refreshed.scope, oauth.scope)) throw new CredentialUnavailableError(provider, `Your ${provider} connection needs to be reauthorized.`);
2738
+ const refreshedTokens = {
2739
+ ...latest.refreshTokenExpiresAt ? { refreshTokenExpiresAt: latest.refreshTokenExpiresAt } : void 0,
2740
+ ...refreshed,
2741
+ ...latest.account ? { account: latest.account } : void 0
2742
+ };
2743
+ await deps.userTokenStore.set(userSubjectId, provider, refreshedTokens);
2744
+ return buildLease(refreshed.accessToken, getLeaseExpiry(refreshed.expiresAt), input.reason);
2745
+ });
2746
+ } catch (error) {
2747
+ if (error instanceof CredentialUnavailableError) throw error;
2748
+ if (error instanceof OAuthRefreshRejectedError) throw new CredentialUnavailableError(provider, `Your ${provider} connection has expired.`);
2749
+ throw error;
2750
+ }
2751
+ if (canUseStoredToken(stored)) return buildLease(stored.accessToken, getLeaseExpiry(stored.expiresAt), input.reason);
2752
+ throw new CredentialUnavailableError(provider, `Your ${provider} connection has expired.`);
2753
+ }
2754
+ const lease = await serviceAccountLease();
2755
+ if (lease) return lease;
2756
+ throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
2757
+ }
2758
+ const lease = await serviceAccountLease();
2759
+ if (lease) return lease;
2760
+ if (envToken) return buildLease(envToken, getLeaseExpiry(), input.reason);
2761
+ throw new CredentialUnavailableError(provider, `No ${provider} credentials available.`);
2762
+ } };
2763
+ }
2764
+ // src/chat/credentials/workload-identity.ts
2765
+ const REQUEST_TIMEOUT_MS = 2e4;
2766
+ const GCP_STS_URL = "https://sts.googleapis.com/v1/token";
2767
+ const GCP_IAM_CREDENTIALS_URL = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts";
2768
+ const GCP_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
2769
+ const AZURE_VERCEL_AUDIENCE = "api://AzureADTokenExchange";
2770
+ const SERVICE_ACCOUNT_JWT_LIFETIME_S = 3600;
2771
+ var MintStepError = class extends Error {
2772
+ status;
2773
+ step;
2774
+ constructor(step, message, options = {}) {
2775
+ super(message, { cause: options.cause });
2776
+ this.name = "MintStepError";
2777
+ this.step = step;
2778
+ this.status = options.status;
2779
+ }
2780
+ };
2781
+ const stsResponseSchema = z.object({ access_token: z.string().min(1) });
2782
+ const signJwtResponseSchema = z.object({ signedJwt: z.string().min(1) });
2783
+ const idTokenResponseSchema = z.object({ token: z.string().min(1) });
2784
+ const accessTokenResponseSchema = z.object({
2785
+ accessToken: z.string().min(1),
2786
+ expireTime: z.iso.datetime({ offset: true })
2787
+ });
2788
+ const entraResponseSchema = z.object({
2789
+ access_token: z.string().min(1),
2790
+ expires_in: z.coerce.number().int().positive()
2791
+ });
2792
+ const jwtExpirySchema = z.object({ exp: z.number().int().positive() });
2793
+ async function vercelOidcToken(audience) {
2794
+ try {
2795
+ return await getVercelOidcToken(audience ? { audience } : void 0);
2796
+ } catch (error) {
2797
+ throw new MintStepError("Vercel OIDC", "Vercel OIDC token is unavailable", { cause: error });
2798
+ }
2799
+ }
2800
+ async function postForJson(step, url, init, schema) {
2801
+ let response;
2802
+ try {
2803
+ response = await fetch(url, {
2804
+ method: "POST",
2805
+ ...init,
2806
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
2807
+ });
2808
+ } catch (error) {
2809
+ throw new MintStepError(step, `${step} request failed`, { cause: error });
2810
+ }
2811
+ if (!response.ok) {
2812
+ response.body?.cancel().catch(() => void 0);
2813
+ throw new MintStepError(step, `${step} returned HTTP ${response.status}`, { status: response.status });
2814
+ }
2815
+ const parsed = schema.safeParse(await response.json().catch(() => null));
2816
+ if (!parsed.success) throw new MintStepError(step, `${step} returned an invalid response`);
2817
+ return parsed.data;
2818
+ }
2819
+ function form(values) {
2820
+ return {
2821
+ body: new URLSearchParams(values).toString(),
2822
+ headers: { "content-type": "application/x-www-form-urlencoded" }
2823
+ };
2824
+ }
2825
+ function bearerJson(token, value) {
2826
+ return {
2827
+ body: JSON.stringify(value),
2828
+ headers: {
2829
+ authorization: `Bearer ${token}`,
2830
+ "content-type": "application/json"
2831
+ }
2832
+ };
2833
+ }
2834
+ function jwtExpiresAtMs(step, token) {
2835
+ try {
2836
+ const payload = token.split(".")[1] ?? "";
2837
+ return jwtExpirySchema.parse(JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))).exp * 1e3;
2838
+ } catch (error) {
2839
+ throw new MintStepError(step, `${step} returned an invalid token`, { cause: error });
2840
+ }
2841
+ }
2842
+ async function mintGcp(gcp) {
2843
+ const subjectToken = await vercelOidcToken();
2844
+ const sts = await postForJson("Google STS", GCP_STS_URL, form({
2845
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
2846
+ audience: `//iam.googleapis.com/${gcp.workloadIdentityProvider}`,
2847
+ scope: GCP_CLOUD_PLATFORM_SCOPE,
2848
+ requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
2849
+ subject_token: subjectToken,
2850
+ subject_token_type: "urn:ietf:params:oauth:token-type:jwt"
2851
+ }), stsResponseSchema);
2852
+ const serviceAccountUrl = `${GCP_IAM_CREDENTIALS_URL}/${encodeURIComponent(gcp.serviceAccount)}`;
2853
+ const step = "Google IAM Credentials";
2854
+ if (gcp.token === "service-account-jwt") {
2855
+ const issuedAt = Math.floor(Date.now() / 1e3);
2856
+ const expiresAt = issuedAt + SERVICE_ACCOUNT_JWT_LIFETIME_S;
2857
+ return {
2858
+ token: (await postForJson(step, `${serviceAccountUrl}:signJwt`, bearerJson(sts.access_token, { payload: JSON.stringify({
2859
+ iss: gcp.serviceAccount,
2860
+ sub: gcp.serviceAccount,
2861
+ aud: gcp.audience,
2862
+ iat: issuedAt,
2863
+ exp: expiresAt
2864
+ }) }), signJwtResponseSchema)).signedJwt,
2865
+ expiresAtMs: expiresAt * 1e3
2866
+ };
2867
+ }
2868
+ if (gcp.token === "id-token") {
2869
+ const minted = await postForJson(step, `${serviceAccountUrl}:generateIdToken`, bearerJson(sts.access_token, {
2870
+ audience: gcp.audience,
2871
+ includeEmail: true
2872
+ }), idTokenResponseSchema);
2873
+ return {
2874
+ token: minted.token,
2875
+ expiresAtMs: jwtExpiresAtMs(step, minted.token)
2876
+ };
2877
+ }
2878
+ const minted = await postForJson(step, `${serviceAccountUrl}:generateAccessToken`, bearerJson(sts.access_token, { scope: gcp.scopes }), accessTokenResponseSchema);
2879
+ return {
2880
+ token: minted.accessToken,
2881
+ expiresAtMs: Date.parse(minted.expireTime)
2882
+ };
2883
+ }
2884
+ async function mintAzure(azure) {
2885
+ const assertion = await vercelOidcToken(AZURE_VERCEL_AUDIENCE);
2886
+ const minted = await postForJson("Microsoft Entra ID", `https://login.microsoftonline.com/${encodeURIComponent(azure.tenantId)}/oauth2/v2.0/token`, form({
2887
+ grant_type: "client_credentials",
2888
+ client_id: azure.clientId,
2889
+ client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
2890
+ client_assertion: assertion,
2891
+ scope: azure.scope
2892
+ }), entraResponseSchema);
2893
+ return {
2894
+ token: minted.access_token,
2895
+ expiresAtMs: Date.now() + minted.expires_in * 1e3
2896
+ };
2897
+ }
2898
+ /**
2899
+ * Mint one workload identity token for a plugin on the host.
2900
+ *
2901
+ * Expected exchange failures become `CredentialMintError`, whose message names
2902
+ * the failing step and HTTP status. Each mint records one span.
2903
+ */
2904
+ async function mintWorkloadIdentityToken(provider, credentials) {
2905
+ return await withSpan("credential.workload_identity.mint", "credential.workload_identity.mint", {}, async (setSpanAttributes) => {
2906
+ try {
2907
+ const minted = credentials.gcp ? await mintGcp(credentials.gcp) : await mintAzure(credentials.azure);
2908
+ setSpanAttributes({ "app.workload_identity.outcome": "completed" });
2909
+ return minted;
2910
+ } catch (error) {
2911
+ if (!(error instanceof MintStepError)) throw error;
2912
+ setSpanAttributes({
2913
+ "app.workload_identity.outcome": "failed",
2914
+ "app.workload_identity.step": error.step,
2915
+ "error.type": error.status ? `http_${error.status}` : error.name,
2916
+ ...error.status ? { "http.response.status_code": error.status } : void 0
2917
+ });
2918
+ throw new CredentialMintError(provider, `Could not mint the ${provider} workload identity credential: ${error.message}.`, { cause: error });
2919
+ }
2920
+ }, {
2921
+ "app.credential.provider": provider,
2922
+ "app.workload_identity.issuer": credentials.gcp ? "gcp" : "azure",
2923
+ "app.workload_identity.token_kind": credentials.gcp?.token ?? "access-token"
2924
+ });
2925
+ }
2926
+ // src/chat/plugins/auth/workload-identity-broker.ts
2927
+ /**
2928
+ * Issue leases from a host-minted workload identity token.
2929
+ *
2930
+ * The lease holds only the minted token and expires with it. Egress keeps it
2931
+ * as a shared lease and mints again shortly before that time. Static plugin
2932
+ * `api-headers` are not part of the lease; egress resolves them from env on
2933
+ * each request so long-lived secrets never sit in shared host state.
2934
+ */
2935
+ function createWorkloadIdentityBroker(manifest, credentials) {
2936
+ const header = workloadIdentityHeader(credentials);
2937
+ return { async issue(input) {
2938
+ const minted = await mintWorkloadIdentityToken(manifest.name, credentials);
2939
+ return {
2940
+ id: randomUUID(),
2941
+ provider: manifest.name,
2942
+ env: resolvePluginCommandEnv(manifest),
2943
+ headerTransforms: credentials.domains.map((domain) => ({
2944
+ domain,
2945
+ headers: { [header]: `Bearer ${minted.token}` }
2946
+ })),
2947
+ expiresAt: new Date(minted.expiresAtMs).toISOString(),
2948
+ metadata: { reason: input.reason }
2949
+ };
2950
+ } };
2951
+ }
2952
+ // src/chat/plugins/registry.ts
2953
+ function getLoggedPluginNames() {
2954
+ const globalState = globalThis;
2955
+ globalState.__juniorLoggedPluginNames ??= /* @__PURE__ */ new Set();
2956
+ return globalState.__juniorLoggedPluginNames;
2957
+ }
2958
+ function createLoadedPluginState(signature) {
2959
+ return {
2960
+ signature,
2961
+ pluginDefinitions: [],
2962
+ pluginMigrationRoots: /* @__PURE__ */ new Map(),
2963
+ domainToPlugin: /* @__PURE__ */ new Map(),
2964
+ pluginConfigKeys: /* @__PURE__ */ new Set(),
2965
+ pluginsByName: /* @__PURE__ */ new Map(),
2966
+ packageSkillRoots: /* @__PURE__ */ new Set(),
2967
+ workloadIdentityToPlugin: /* @__PURE__ */ new Map()
2968
+ };
2969
+ }
2970
+ function providerDomains(manifest) {
2971
+ return [.../* @__PURE__ */ new Set([...manifest.credentials?.domains ?? [], ...manifest.domains ?? []])].sort((left, right) => left.localeCompare(right));
2972
+ }
2973
+ function registerPluginManifest(state, manifest, pluginDir, skillsDir, migrationsDir) {
2974
+ if (state.pluginsByName.has(manifest.name)) throw new Error(`Duplicate plugin name "${manifest.name}"`);
2975
+ for (const domain of providerDomains(manifest)) {
2976
+ const owner = state.domainToPlugin.get(domain);
2977
+ if (owner) throw new Error(`Duplicate provider domain "${domain}" in plugin "${manifest.name}" already declared by plugin "${owner}". Use plugins.manifests in PluginCatalogConfig to change one plugin's domains or credentials.`);
2978
+ }
2979
+ const identity = manifest.credentials?.type === "workload-identity" ? workloadIdentityKey(manifest.credentials) : void 0;
2980
+ const identityOwner = identity ? state.workloadIdentityToPlugin.get(identity) : void 0;
2981
+ if (identityOwner) throw new Error(`Duplicate workload identity ${identity} in plugin "${manifest.name}" already declared by plugin "${identityOwner}"`);
2982
+ const definition = {
2983
+ manifest,
2984
+ dir: pluginDir,
2985
+ ...migrationsDir ? { migrationsDir } : void 0,
2986
+ ...skillsDir ? { skillsDir } : void 0
2987
+ };
2988
+ state.pluginDefinitions.push(definition);
2989
+ state.pluginsByName.set(manifest.name, definition);
2990
+ if (definition.migrationsDir) state.pluginMigrationRoots.set(manifest.name, definition.migrationsDir);
2991
+ for (const key of manifest.configKeys) state.pluginConfigKeys.add(key);
2992
+ for (const domain of providerDomains(manifest)) state.domainToPlugin.set(domain, manifest.name);
2993
+ if (identity) state.workloadIdentityToPlugin.set(identity, manifest.name);
2994
+ }
2995
+ function registerYamlPluginManifest(state, raw, pluginDir, config) {
2996
+ const manifest = parsePluginManifest(raw, pluginDir, config);
2997
+ const candidateSkillsDir = path.join(pluginDir, "skills");
2998
+ registerPluginManifest(state, manifest, pluginDir, (() => {
2999
+ try {
3000
+ return statSync(candidateSkillsDir).isDirectory();
3001
+ } catch {
3002
+ return false;
3003
+ }
3004
+ })() ? candidateSkillsDir : void 0);
3005
+ }
3006
+ function normalizePluginRoots(roots) {
3007
+ const resolved = [];
3008
+ const seen = /* @__PURE__ */ new Set();
3009
+ for (const root of roots) {
3010
+ const normalized = path.resolve(root);
3011
+ if (seen.has(normalized)) continue;
3012
+ seen.add(normalized);
3013
+ resolved.push(normalized);
3014
+ }
3015
+ return resolved;
3016
+ }
3017
+ function getPluginCatalogSource(runtime) {
3018
+ const packagedContent = discoverConfiguredPluginPackageContent(runtime.pluginConfig);
3019
+ const manifestRoots = normalizePluginRoots([...normalizePluginRoots(pluginRoots()), ...packagedContent.manifestRoots]);
3020
+ const packagedSkillRoots = normalizePluginRoots(packagedContent.skillRoots);
3021
+ const inlineManifests = runtime.pluginConfig?.inlineManifests ?? [];
3022
+ return {
3023
+ inlineManifests,
3024
+ manifestRoots,
3025
+ packagedSkillRoots,
3026
+ packagedContent,
3027
+ signature: JSON.stringify({
3028
+ inlineManifests,
3029
+ manifestRoots,
3030
+ packages: packagedContent.packages.map((pkg) => ({
3031
+ dir: path.resolve(pkg.dir),
3032
+ hasMigrationsDir: pkg.hasMigrationsDir,
3033
+ hasSkillsDir: pkg.hasSkillsDir,
3034
+ packageName: pkg.packageName
3035
+ })).sort((left, right) => left.packageName.localeCompare(right.packageName)),
3036
+ packagedSkillRoots,
3037
+ packageNames: [...packagedContent.packageNames].sort(),
3038
+ pluginConfig: runtime.pluginConfig ?? {}
3039
+ })
3040
+ };
3041
+ }
3042
+ function normalizePluginCatalogConfig(config) {
3043
+ if (!config) return;
3044
+ return {
3045
+ inlineManifests: config.inlineManifests ? structuredClone(config.inlineManifests) : void 0,
3046
+ packages: normalizePluginPackageNames(config.packages),
3047
+ ...config.manifests ? { manifests: structuredClone(config.manifests) } : void 0
3048
+ };
3049
+ }
3050
+ function clonePluginCatalogConfig(config) {
3051
+ if (!config) return;
3052
+ return {
3053
+ ...config.inlineManifests ? { inlineManifests: structuredClone(config.inlineManifests) } : void 0,
3054
+ packages: [...config.packages ?? []],
3055
+ ...config.manifests ? { manifests: structuredClone(config.manifests) } : void 0
3056
+ };
3057
+ }
3058
+ function packageContentByName(packagedContent, packageName) {
3059
+ return packagedContent.packages.find((pkg) => pkg.packageName === packageName);
3060
+ }
3061
+ function registerInlineManifests(state, source, config) {
3062
+ const migrationOwners = /* @__PURE__ */ new Map();
3063
+ for (const definition of source.inlineManifests) {
3064
+ const pkg = definition.packageName ? packageContentByName(source.packagedContent, definition.packageName) : void 0;
3065
+ const dir = pkg?.dir ?? definition.dir ?? process.cwd();
3066
+ const skillsDir = pkg?.hasSkillsDir || definition.dir && statSync(path.join(dir, "skills"), { throwIfNoEntry: false })?.isDirectory() ? path.join(dir, "skills") : void 0;
3067
+ const migrationsDir = pkg?.hasMigrationsDir && statSync(path.join(pkg.dir, "migrations"), { throwIfNoEntry: false })?.isDirectory() ? path.join(pkg.dir, "migrations") : void 0;
3068
+ const manifest = parseInlinePluginManifest(definition.manifest, dir, config);
3069
+ if (migrationsDir) {
3070
+ const owner = migrationOwners.get(migrationsDir);
3071
+ if (owner) throw new Error(`Plugin "${manifest.name}" cannot share migrations directory with plugin "${owner}"`);
3072
+ migrationOwners.set(migrationsDir, manifest.name);
3073
+ }
3074
+ registerPluginManifest(state, manifest, dir, skillsDir, migrationsDir);
3075
+ }
3076
+ }
3077
+ function discoverConfiguredPluginPackageContent(config) {
3078
+ return discoverInstalledPluginPackageContent(process.cwd(), { packageNames: config?.packages });
3079
+ }
3080
+ function buildLoadedPluginState(source, config) {
3081
+ const state = createLoadedPluginState(source.signature);
3082
+ for (const skillRoot of source.packagedSkillRoots) state.packageSkillRoots.add(skillRoot);
3083
+ registerInlineManifests(state, source, config);
3084
+ const roots = source.manifestRoots;
3085
+ for (const pluginsRoot of roots) {
3086
+ let entries;
3087
+ let rootStat;
3088
+ try {
3089
+ rootStat = statSync(pluginsRoot);
3090
+ } catch (error) {
3091
+ logWarn("plugin.root.read.failed", {
3092
+ "file.directory": pluginsRoot,
3093
+ "exception.message": error instanceof Error ? error.message : String(error)
3094
+ });
3095
+ continue;
3096
+ }
3097
+ if (rootStat.isDirectory()) {
3098
+ const manifestPath = path.join(pluginsRoot, "plugin.yaml");
3099
+ let hasRootManifest = false;
3100
+ try {
3101
+ hasRootManifest = statSync(manifestPath).isFile();
3102
+ } catch {
3103
+ hasRootManifest = false;
3104
+ }
3105
+ if (hasRootManifest) {
3106
+ registerYamlPluginManifest(state, readFileSync(manifestPath, "utf8"), pluginsRoot, config);
3107
+ continue;
3108
+ }
3109
+ }
3110
+ try {
3111
+ entries = readdirSync(pluginsRoot);
3112
+ } catch (error) {
3113
+ logWarn("plugin.root.read.failed", {
3114
+ "file.directory": pluginsRoot,
3115
+ "exception.message": error instanceof Error ? error.message : String(error)
3116
+ });
3117
+ continue;
3118
+ }
3119
+ for (const entry of entries.sort()) {
3120
+ const pluginDir = path.join(pluginsRoot, entry);
3121
+ try {
3122
+ if (!statSync(pluginDir).isDirectory()) continue;
3123
+ } catch {
3124
+ continue;
3125
+ }
3126
+ const manifestPath = path.join(pluginDir, "plugin.yaml");
3127
+ let raw;
3128
+ try {
3129
+ raw = readFileSync(manifestPath, "utf8");
3130
+ } catch {
3131
+ continue;
3132
+ }
3133
+ registerYamlPluginManifest(state, raw, pluginDir, config);
3134
+ }
3135
+ }
3136
+ for (const name of Object.keys(config?.manifests ?? {})) if (!state.pluginsByName.has(name)) throw new Error(`plugins.manifests.${name} does not match a loaded plugin`);
3137
+ return state;
3138
+ }
3139
+ function logLoadedPlugins(state) {
3140
+ const loggedPluginNames = getLoggedPluginNames();
3141
+ for (const plugin of [...state.pluginDefinitions].sort((left, right) => left.manifest.name.localeCompare(right.manifest.name))) {
3142
+ if (loggedPluginNames.has(plugin.manifest.name)) continue;
3143
+ loggedPluginNames.add(plugin.manifest.name);
3144
+ logInfo("plugin.manifest.loaded", {
3145
+ "app.plugin.name": plugin.manifest.name,
3146
+ "app.plugin.config_key_count": plugin.manifest.configKeys.length,
3147
+ "app.plugin.has_mcp": Boolean(plugin.manifest.mcp),
3148
+ "file.directory": plugin.dir,
3149
+ ...plugin.skillsDir ? { "app.file.skill_directory": plugin.skillsDir } : void 0
3150
+ });
3151
+ }
3152
+ }
3153
+ function ensurePluginsLoaded(runtime) {
3154
+ const source = getPluginCatalogSource(runtime);
3155
+ if (runtime.loadedPluginState?.signature === source.signature) return runtime.loadedPluginState;
3156
+ const state = buildLoadedPluginState(source, runtime.pluginConfig);
3157
+ runtime.loadedPluginState = state;
3158
+ logLoadedPlugins(state);
3159
+ return state;
3160
+ }
3161
+ /** Create an isolated plugin catalog runtime for explicit app wiring. */
3162
+ function createPluginCatalogRuntime() {
3163
+ const runtime = {};
3164
+ return {
3165
+ setConfig(config) {
3166
+ const previousConfig = clonePluginCatalogConfig(runtime.pluginConfig);
3167
+ runtime.pluginConfig = normalizePluginCatalogConfig(config);
3168
+ return previousConfig;
3169
+ },
3170
+ parseConfiguredInlineManifest(manifest, dir) {
3171
+ return parseInlinePluginManifest(manifest, dir, runtime.pluginConfig);
3172
+ },
3173
+ getPackageContent() {
3174
+ return discoverConfiguredPluginPackageContent(runtime.pluginConfig);
3175
+ },
3176
+ getSignature() {
3177
+ return ensurePluginsLoaded(runtime).signature;
3178
+ },
3179
+ getProviders() {
3180
+ return [...ensurePluginsLoaded(runtime).pluginDefinitions];
3181
+ },
3182
+ getMigrationRoots() {
3183
+ return [...ensurePluginsLoaded(runtime).pluginMigrationRoots.entries()].map(([pluginName, dir]) => ({
3184
+ pluginName,
3185
+ dir
3186
+ })).sort((left, right) => left.pluginName.localeCompare(right.pluginName));
3187
+ },
3188
+ getMcpProviders() {
3189
+ return ensurePluginsLoaded(runtime).pluginDefinitions.filter((plugin) => Boolean(plugin.manifest.mcp));
3190
+ },
3191
+ getRuntimeDependencies() {
3192
+ const state = ensurePluginsLoaded(runtime);
3193
+ const seen = /* @__PURE__ */ new Set();
3194
+ const deps = [];
3195
+ for (const plugin of state.pluginDefinitions) for (const dep of plugin.manifest.runtimeDependencies ?? []) {
3196
+ const key = dep.type === "npm" ? `${dep.type}:${dep.package}:${dep.version}` : "package" in dep ? `${dep.type}:package:${dep.package}` : `${dep.type}:url:${dep.url}:${dep.sha256}`;
3197
+ if (seen.has(key)) continue;
3198
+ seen.add(key);
3199
+ deps.push(dep);
3200
+ }
3201
+ return deps.sort((left, right) => {
3202
+ if (left.type !== right.type) return left.type.localeCompare(right.type);
3203
+ const leftIdentity = "package" in left ? `package:${left.package}` : `url:${left.url}:${left.sha256}`;
3204
+ const rightIdentity = "package" in right ? `package:${right.package}` : `url:${right.url}:${right.sha256}`;
3205
+ if (leftIdentity !== rightIdentity) return leftIdentity.localeCompare(rightIdentity);
3206
+ if (left.type === "npm" && right.type === "npm") return left.version.localeCompare(right.version);
3207
+ return 0;
3208
+ });
3209
+ },
3210
+ getRuntimePostinstall() {
3211
+ const state = ensurePluginsLoaded(runtime);
3212
+ const commands = [];
3213
+ for (const plugin of state.pluginDefinitions) for (const command of plugin.manifest.runtimePostinstall ?? []) commands.push({
3214
+ cmd: command.cmd,
3215
+ ...command.args ? { args: [...command.args] } : void 0,
3216
+ ...command.sudo !== void 0 ? { sudo: command.sudo } : void 0
3217
+ });
3218
+ return commands;
3219
+ },
3220
+ getOAuthConfig(provider) {
3221
+ const plugin = ensurePluginsLoaded(runtime).pluginsByName.get(provider);
3222
+ if (!plugin?.manifest.oauth) return void 0;
3223
+ const oauth = plugin.manifest.oauth;
3224
+ return {
3225
+ clientIdEnv: oauth.clientIdEnv,
3226
+ clientSecretEnv: oauth.clientSecretEnv,
3227
+ authorizeEndpoint: oauth.authorizeEndpoint,
3228
+ tokenEndpoint: oauth.tokenEndpoint,
3229
+ ...oauth.scope ? { scope: oauth.scope } : void 0,
3230
+ ...oauth.authorizeParams ? { authorizeParams: { ...oauth.authorizeParams } } : void 0,
3231
+ ...oauth.tokenAuthMethod ? { tokenAuthMethod: oauth.tokenAuthMethod } : void 0,
3232
+ ...oauth.tokenExtraHeaders ? { tokenExtraHeaders: { ...oauth.tokenExtraHeaders } } : void 0,
3233
+ ...oauth.treatEmptyScopeAsUnreported ? { treatEmptyScopeAsUnreported: true } : void 0,
3234
+ callbackPath: `/api/oauth/callback/${plugin.manifest.name}`
3235
+ };
3236
+ },
3237
+ getSkillRoots() {
3238
+ const state = ensurePluginsLoaded(runtime);
3239
+ return [.../* @__PURE__ */ new Set([...state.pluginDefinitions.flatMap((plugin) => plugin.skillsDir ? [plugin.skillsDir] : []), ...state.packageSkillRoots])];
3240
+ },
3241
+ getForSkillPath(skillPath) {
3242
+ const state = ensurePluginsLoaded(runtime);
3243
+ const resolvedSkillPath = path.resolve(skillPath);
3244
+ return state.pluginDefinitions.find((plugin) => {
3245
+ if (!plugin.skillsDir) return false;
3246
+ const resolvedSkillsDir = path.resolve(plugin.skillsDir);
3247
+ return resolvedSkillPath === resolvedSkillsDir || resolvedSkillPath.startsWith(`${resolvedSkillsDir}${path.sep}`);
3248
+ });
3249
+ },
3250
+ getDefinition(provider) {
3251
+ return ensurePluginsLoaded(runtime).pluginsByName.get(provider);
3252
+ },
3253
+ getDisplayName(provider) {
3254
+ return ensurePluginsLoaded(runtime).pluginsByName.get(provider)?.manifest.displayName;
3255
+ },
3256
+ isProvider(provider) {
3257
+ return ensurePluginsLoaded(runtime).pluginsByName.has(provider);
3258
+ },
3259
+ isConfigKey(key) {
3260
+ return ensurePluginsLoaded(runtime).pluginConfigKeys.has(key);
3261
+ },
3262
+ createBroker(provider, deps) {
3263
+ const plugin = ensurePluginsLoaded(runtime).pluginsByName.get(provider);
3264
+ if (!plugin) throw new Error(`Unknown plugin provider: "${provider}"`);
3265
+ const { credentials, name } = plugin.manifest;
3266
+ if (!credentials && !plugin.manifest.apiHeaders) throw new Error(`Provider "${name}" has no credentials or API headers configured`);
3267
+ let broker;
3268
+ if (!credentials) broker = createApiHeadersBroker(plugin.manifest);
3269
+ else if (credentials.type === "workload-identity") broker = createWorkloadIdentityBroker(plugin.manifest, credentials);
3270
+ else broker = createOAuthBearerBroker(plugin.manifest, credentials, deps);
3271
+ setSpanAttributes({
3272
+ "app.plugin.name": name,
3273
+ "app.plugin.has_oauth": Boolean(plugin.manifest.oauth)
3274
+ });
3275
+ return broker;
3276
+ }
3277
+ };
3278
+ }
3279
+ export { createEncryptedState as A, getMcpAwareErrorType as B, getMcpAuthSession as C, putMcpAuthSession as D, patchMcpAuthSession as E, resolvePluginHeaderEnvRefs as F, fetchWithBoundedOAuthErrorBodies as G, getMcpProviderErrorAttributes as H, resolvePluginCommandEnv as I, CredentialUnavailableError as J, getOAuthProviderErrorAttributes as K, McpProviderError as L, findLegacyWebActorUserId as M, webActorUserIds as N, putMcpServerSessionId as O, resolveApiHeaderTransforms as P, workloadIdentityHeader as Q, McpServiceAccountRequiredError as R, deleteMcpStoredOAuthCredentials as S, getMcpStoredOAuthCredentials as T, toMcpProviderError as U, getMcpAwareTelemetryMessage as V, OAuthProviderError as W, parseInlinePluginManifest as X, ServiceAccountUnavailableError as Y, parsePluginManifest as Z, McpAuthorizationRequiredError as _, disconnectServiceAccount as a, deleteMcpAuthSessionsForUserProvider as b, serviceAccountAllows as c, startServiceAccountSignIn as d, buildOAuthTokenRequest as f, getMcpServiceAccountCredentials as g, createMcpServiceAccountClientProvider as h, mergeHeaderTransforms as i, readEncryptedState as j, putMcpStoredOAuthCredentials as k, serviceAccountOnly as l, hasRequiredOAuthScope as m, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as n, finishServiceAccountSignIn as o, parseOAuthTokenResponse as p, CredentialMintError as q, resolveAuthTokenPlaceholder as r, getServiceAccountStatus as s, createPluginCatalogRuntime as t, serviceAccountPlugins as u, PluginMcpClient as v, getMcpServerSessionId as w, deleteMcpServerSessionId as x, deleteMcpAuthSession as y, McpToolError as z };