@jini-ai/agent-plugins 0.6.22 → 0.7.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 (220) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +13 -0
  3. package/calendly/exports/booking-calendar.css +7 -0
  4. package/calendly/exports/booking-calendar.html +5 -0
  5. package/calendly/mcp.json +10 -0
  6. package/calendly/plugin.json +47 -0
  7. package/calendly/skills/calendly/SKILL.md +27 -0
  8. package/charts-echarts/plugin.json +2 -2
  9. package/charts-recharts/plugin.json +2 -2
  10. package/cloudflare/lib/cms-forms.mjs +57 -0
  11. package/cloudflare/lib/forms.mjs +78 -18
  12. package/cloudflare/lib/target.mjs +17 -4
  13. package/cloudflare/plugin.json +2 -2
  14. package/cloudflare/skills/cloudflare/SKILL.md +4 -4
  15. package/cloudflare/skills/cloudflare/references/workers.md +4 -4
  16. package/cloudflare/worker/forms-receiver.mjs +81 -41
  17. package/cloudflare/worker/portable-validation.mjs +220 -0
  18. package/commerce/plugin.json +17 -0
  19. package/commerce/skills/commerce/SKILL.md +23 -0
  20. package/composio/mcp.json +1 -1
  21. package/composio/plugin.json +2 -2
  22. package/composio/skills/composio/SKILL.md +4 -4
  23. package/core/commerce-server.d.ts +2 -0
  24. package/core/commerce-server.mjs +2 -0
  25. package/dist/admin-surfaces/connections/connections.d.ts +35 -0
  26. package/dist/admin-surfaces/connections/connections.js +135 -0
  27. package/dist/admin-surfaces/connections/index.d.ts +3 -0
  28. package/dist/admin-surfaces/connections/index.js +2 -0
  29. package/dist/admin-surfaces/connections/ports.d.ts +110 -0
  30. package/dist/admin-surfaces/connections/ports.js +2 -0
  31. package/dist/admin-surfaces/index.d.ts +2 -0
  32. package/dist/admin-surfaces/index.js +1 -0
  33. package/dist/admin-surfaces/plugin-state-persistence.d.ts +27 -0
  34. package/dist/admin-surfaces/plugin-state-persistence.js +2 -0
  35. package/dist/admin-surfaces/plugin-state.d.ts +51 -0
  36. package/dist/admin-surfaces/plugin-state.js +106 -0
  37. package/dist/connect/access-token-tool.d.ts +240 -0
  38. package/dist/connect/access-token-tool.js +213 -0
  39. package/dist/connect/apply-connect-defaults.d.ts +91 -0
  40. package/dist/connect/apply-connect-defaults.js +113 -0
  41. package/dist/connect/apply-tool-renames.d.ts +72 -0
  42. package/dist/connect/apply-tool-renames.js +105 -0
  43. package/dist/connect/connect-card-ui.d.ts +143 -0
  44. package/dist/connect/connect-card-ui.js +106 -0
  45. package/dist/connect/connect-destination.d.ts +35 -0
  46. package/dist/connect/connect-destination.js +45 -0
  47. package/dist/connect/connect-sign-in-wait.d.ts +31 -0
  48. package/dist/connect/connect-sign-in-wait.js +21 -0
  49. package/dist/connect/connect-tool.d.ts +314 -0
  50. package/dist/connect/connect-tool.js +431 -0
  51. package/dist/connect/connection-status.d.ts +33 -0
  52. package/dist/connect/connection-status.js +63 -0
  53. package/dist/connect/credential-cards.d.ts +15 -0
  54. package/dist/connect/credential-cards.js +49 -0
  55. package/dist/connect/credential-save-tool.d.ts +45 -0
  56. package/dist/connect/credential-save-tool.js +156 -0
  57. package/dist/connect/enable-access.d.ts +67 -0
  58. package/dist/connect/enable-access.js +74 -0
  59. package/dist/connect/executable/approval.d.ts +58 -0
  60. package/dist/connect/executable/approval.js +40 -0
  61. package/dist/connect/executable/host-capabilities.d.ts +76 -0
  62. package/dist/connect/executable/host-capabilities.js +100 -0
  63. package/dist/connect/executable/index.d.ts +10 -0
  64. package/dist/connect/executable/index.js +9 -0
  65. package/dist/connect/executable/ports.d.ts +189 -0
  66. package/dist/connect/executable/ports.js +2 -0
  67. package/dist/connect/executable/register.d.ts +21 -0
  68. package/dist/connect/executable/register.js +125 -0
  69. package/dist/connect/federate-mcp.d.ts +190 -0
  70. package/dist/connect/federate-mcp.js +440 -0
  71. package/dist/connect/grant-signed-in-defaults.d.ts +96 -0
  72. package/dist/connect/grant-signed-in-defaults.js +100 -0
  73. package/dist/connect/import-access-token.d.ts +114 -0
  74. package/dist/connect/import-access-token.js +103 -0
  75. package/dist/connect/index.d.ts +19 -0
  76. package/dist/connect/index.js +19 -0
  77. package/dist/connect/plugin-credential-card.d.ts +46 -0
  78. package/dist/connect/plugin-credential-card.js +63 -0
  79. package/dist/connect/plugin-host/index.d.ts +203 -0
  80. package/dist/connect/plugin-host/index.js +153 -0
  81. package/dist/connect/ports.d.ts +74 -0
  82. package/dist/connect/ports.js +2 -0
  83. package/dist/connect/switch-on-saved-token.d.ts +48 -0
  84. package/dist/connect/switch-on-saved-token.js +20 -0
  85. package/dist/connect/token-sign-in.d.ts +51 -0
  86. package/dist/connect/token-sign-in.js +43 -0
  87. package/dist/core/identity-namespace.d.ts +39 -0
  88. package/dist/core/identity-namespace.js +61 -3
  89. package/dist/folder-zip-node.js +3 -1
  90. package/dist/lifecycle/automatic-use.d.ts +12 -7
  91. package/dist/lifecycle/automatic-use.js +37 -28
  92. package/dist/lifecycle/capability-projection.js +5 -1
  93. package/dist/lifecycle/contribution-loader.d.ts +2 -7
  94. package/dist/lifecycle/contribution-types.d.ts +8 -0
  95. package/dist/lifecycle/contribution-types.js +2 -0
  96. package/dist/lifecycle/credential-card-metadata.d.ts +23 -0
  97. package/dist/lifecycle/credential-card-metadata.js +184 -0
  98. package/dist/lifecycle/exports.d.ts +11 -0
  99. package/dist/lifecycle/exports.js +64 -3
  100. package/dist/lifecycle/host-tools/identity.d.ts +38 -0
  101. package/dist/lifecycle/host-tools/identity.js +58 -0
  102. package/dist/lifecycle/host-tools/index.d.ts +20 -0
  103. package/dist/lifecycle/host-tools/index.js +20 -0
  104. package/dist/lifecycle/host-tools/memory-tools.d.ts +22 -0
  105. package/dist/lifecycle/host-tools/memory-tools.js +63 -0
  106. package/dist/lifecycle/host-tools/ports.d.ts +121 -0
  107. package/dist/lifecycle/host-tools/ports.js +2 -0
  108. package/dist/lifecycle/host-tools/provider-status-tool.d.ts +88 -0
  109. package/dist/lifecycle/host-tools/provider-status-tool.js +45 -0
  110. package/dist/lifecycle/host-tools/search-tool.d.ts +74 -0
  111. package/dist/lifecycle/host-tools/search-tool.js +282 -0
  112. package/dist/lifecycle/host-tools/skill-tool.d.ts +219 -0
  113. package/dist/lifecycle/host-tools/skill-tool.js +482 -0
  114. package/dist/lifecycle/host-tools/write-note-tool.d.ts +22 -0
  115. package/dist/lifecycle/host-tools/write-note-tool.js +47 -0
  116. package/dist/lifecycle/index.d.ts +2 -1
  117. package/dist/lifecycle/install.js +2 -1
  118. package/dist/lifecycle/installed-package-index.js +5 -8
  119. package/dist/lifecycle/mail/adapter-descriptors.d.ts +78 -0
  120. package/dist/lifecycle/mail/adapter-descriptors.js +155 -0
  121. package/dist/lifecycle/mail/catalog.d.ts +116 -0
  122. package/dist/lifecycle/mail/catalog.js +72 -0
  123. package/dist/lifecycle/mail/configuration.d.ts +25 -0
  124. package/dist/lifecycle/mail/configuration.js +62 -0
  125. package/dist/lifecycle/mail/contribution.d.ts +89 -0
  126. package/dist/lifecycle/mail/contribution.js +115 -0
  127. package/dist/lifecycle/mail/host-mailer.d.ts +24 -0
  128. package/dist/lifecycle/mail/host-mailer.js +10 -0
  129. package/dist/lifecycle/mail/index.d.ts +16 -0
  130. package/dist/lifecycle/mail/index.js +16 -0
  131. package/dist/lifecycle/mail/selection.d.ts +40 -0
  132. package/dist/lifecycle/mail/selection.js +86 -0
  133. package/dist/lifecycle/manifest.d.ts +7 -2
  134. package/dist/lifecycle/manifest.js +32 -9
  135. package/dist/lifecycle/metadata.d.ts +31 -0
  136. package/dist/lifecycle/metadata.js +80 -0
  137. package/dist/lifecycle/persistent-state.js +2 -1
  138. package/dist/lifecycle/ports.d.ts +2 -0
  139. package/dist/lifecycle/resolve-agent-plugin-refs.d.ts +2 -1
  140. package/dist/lifecycle/resolve-agent-plugin-refs.js +14 -8
  141. package/dist/lifecycle/search-projection.d.ts +3 -4
  142. package/dist/lifecycle/search-projection.js +5 -7
  143. package/dist/lifecycle/search.js +3 -2
  144. package/fly/plugin.json +5 -5
  145. package/fly/skills/fly/SKILL.md +1 -1
  146. package/formspree/plugin.json +7 -0
  147. package/formspree/skills/formspree/SKILL.md +11 -0
  148. package/github/plugin.json +2 -2
  149. package/github/skills/github/SKILL.md +28 -28
  150. package/github/skills/github/references/actions.md +8 -8
  151. package/github/skills/github/references/auth-and-tokens.md +7 -7
  152. package/github/skills/github/references/repo-files.md +5 -5
  153. package/github/skills/github/references/site-backup.md +16 -16
  154. package/github/skills/github/references/source-control.md +17 -17
  155. package/github-pages/plugin.json +2 -2
  156. package/github-pages/skills/github-pages/SKILL.md +3 -3
  157. package/google-forms/plugin.json +7 -0
  158. package/google-forms/skills/google-forms/SKILL.md +15 -0
  159. package/google-login/plugin.json +3 -3
  160. package/google-login/skills/google-login/SKILL.md +17 -60
  161. package/google-workspace/plugin.json +6 -6
  162. package/google-workspace/skills/google-workspace/references/connection.md +1 -1
  163. package/google-workspace/skills/google-workspace/references/form-delivery.md +4 -4
  164. package/google-workspace/tovu-admin-surfaces.json +5 -5
  165. package/higgsfield-media/plugin.json +5 -5
  166. package/higgsfield-media/skills/higgsfield-media/SKILL.md +31 -33
  167. package/higgsfield-media/skills/higgsfield-media/references/failure-modes.md +7 -7
  168. package/higgsfield-media/skills/higgsfield-media/references/models-and-plan-gates.md +3 -3
  169. package/jev/plugin.json +2 -2
  170. package/langfuse/plugin.json +2 -2
  171. package/meilisearch/plugin.json +2 -2
  172. package/meilisearch/skills/meilisearch/SKILL.md +1 -1
  173. package/netlify/plugin.json +2 -2
  174. package/netlify/skills/netlify/SKILL.md +3 -3
  175. package/opentelemetry/plugin.json +2 -2
  176. package/opentelemetry/skills/opentelemetry/SKILL.md +7 -7
  177. package/package.json +92 -14
  178. package/posthog/plugin.json +2 -2
  179. package/posthog/skills/posthog/SKILL.md +7 -7
  180. package/railway/plugin.json +3 -3
  181. package/railway/skills/railway/SKILL.md +10 -11
  182. package/render/plugin.json +3 -3
  183. package/render/skills/render/SKILL.md +7 -8
  184. package/resend/NOTES.md +2 -2
  185. package/resend/mcp.json +1 -1
  186. package/resend/plugin.json +5 -5
  187. package/resend/skills/resend/SKILL.md +13 -13
  188. package/s3-compatible/plugin.json +2 -2
  189. package/s3-compatible/skills/s3-compatible/SKILL.md +4 -4
  190. package/sentry/plugin.json +2 -2
  191. package/sentry/skills/sentry/SKILL.md +7 -7
  192. package/shopify/plugin.json +2 -2
  193. package/site-compliance/plugin.json +2 -2
  194. package/site-compliance/skills/site-compliance/SKILL.md +3 -3
  195. package/site-compliance/skills/site-compliance/references/gdpr-eu-uk.md +1 -1
  196. package/site-import/plugin.json +2 -2
  197. package/slide-design/plugin.json +2 -2
  198. package/software-engineering/LICENSE +201 -0
  199. package/software-engineering/NOTICE +9 -0
  200. package/software-engineering/README.md +89 -0
  201. package/software-engineering/plugin.json +24 -0
  202. package/software-engineering/skills/software-engineering/SKILL.md +33 -0
  203. package/software-engineering/skills/software-engineering/references/debugging.md +54 -0
  204. package/software-engineering/skills/software-engineering/references/implementation.md +27 -0
  205. package/software-engineering/skills/software-engineering/references/planning.md +27 -0
  206. package/software-engineering/skills/software-engineering/references/prototyping.md +14 -0
  207. package/software-engineering/skills/software-engineering/references/security.md +47 -0
  208. package/software-engineering/skills/software-engineering/references/verification.md +53 -0
  209. package/stripe/plugin.json +2 -2
  210. package/supabase/mcp.json +4 -4
  211. package/supabase/plugin.json +3 -3
  212. package/supabase/skills/supabase/SKILL.md +8 -8
  213. package/supabase/skills/supabase/references/failure-modes.md +5 -5
  214. package/ui-ux-design/plugin.json +2 -2
  215. package/vercel/plugin.json +2 -2
  216. package/vercel/skills/vercel/SKILL.md +3 -3
  217. package/wordpress/plugin.json +2 -2
  218. package/wordpress/skills/wordpress/SKILL.md +3 -3
  219. package/wordpress/skills/wordpress/references/free-site-redirect.md +2 -2
  220. package/wordpress/skills/wordpress/references/subdomain.md +5 -5
@@ -0,0 +1,240 @@
1
+ import type { PluginCredentialCard } from "@jini-ai/core/contracts/credentials";
2
+ import type { SurfaceCardSecretForm, SurfaceCardsPort } from "@jini-ai/core/contracts/cards";
3
+ import { type LegacyToolAuthorizeFn as AuthorizeFn } from "@jini-ai/core";
4
+ import { type ToolExecutionOptions, type ToolExecutionContext } from "@jini-ai/core";
5
+ import type { SurfaceAskThenReport, SurfaceExchangeStore } from "@jini-ai/core";
6
+ import { type AgentPluginMcpTrustClassifier, type AgentPluginMcpFederationMessages } from "./federate-mcp.js";
7
+ import type { AgentPluginMcpPort, AgentPluginMcpRecord, AgentPluginMcpProjectionPorts } from "./ports.js";
8
+ import type { SavedTokenSwitchOutcome } from "./switch-on-saved-token.js";
9
+ import type { AgentPluginTokenAuth, RemoteMcpServerConfig } from "../lifecycle/manifest.js";
10
+ import { type AgentPluginAccessTokenFormMessages, type AgentPluginCardIdentity } from "./connect-card-ui.js";
11
+ import { type ResolvedAgentPluginForConnect } from "./connect-tool.js";
12
+ /**
13
+ * @file `agent_plugin_set_access_token` — the generic access-token fallback for an Agent Plugin whose
14
+ * remote server declares `tokenAuth { helpUrl, probeUrl }` in its `mcp.json` (`manifest.ts`).
15
+ * Used when `agent_plugin_connect`'s sign-in cannot start.
16
+ *
17
+ * Moved here on 2026-09-29 from `features/supabase-connect/` (SPEC-052's `supabase_set_access_token`),
18
+ * so no vendor code is left in core: the tokens page and the probe URL now come from the plugin.
19
+ *
20
+ * A Jini secret-card spec with domain copy from `connect-card-ui.ts`; the submitted token is probed with one GET to the declared
21
+ * `probeUrl` (401/403 = refused for this purpose), then saved as the plugin row's sealed `static_env` access token
22
+ * through `saveExternalMcpServer`. The store sends that token to the hosted server as
23
+ * `Authorization: Bearer`, and switching the row's auth mode replaces any unfinished OAuth attempt on
24
+ * it. The save itself carries `enabled` and the tool lists forward; then `switch-on-saved-token.ts`
25
+ * switches the plugin on with its declared default tools, exactly as a first sign-in does, unless an
26
+ * operator deliberately turned it off (the result then names the screen that turns it back on).
27
+ *
28
+ * The tool takes only a `pluginId`: the token arrives through the form's own submission, never
29
+ * through a model-issued call. Driven by `askThenReport`, like `custom_credential_set_token`: a second
30
+ * send replaces the form with the real outcome once the probe and save have run. Fails closed with no
31
+ * `emitSurface`.
32
+ */
33
+ /** Product vocabulary of the token tool: every refusal names the host's tool and product.
34
+ * @agent-note Second host: return YOUR tool name and product wording; never put a token or a vendor
35
+ * response body in any of these strings. `credentialText`/`translateCredentialMessage` are your
36
+ * localized credential copy (rule ids come from your {@link AgentPluginTokenValidator}). */
37
+ export interface AgentPluginAccessTokenMessages {
38
+ connectionNotSetUp(input: {
39
+ pluginId: string;
40
+ }): string;
41
+ connectionRepointed(input: {
42
+ connectionId: string;
43
+ displayName: string;
44
+ }): string;
45
+ notInstalled(input: {
46
+ pluginId: string;
47
+ }): string;
48
+ noTokenSignIn(input: {
49
+ pluginId: string;
50
+ }): string;
51
+ multipleTokenSignIns(input: {
52
+ pluginId: string;
53
+ }): string;
54
+ serverNotSetUp(input: {
55
+ pluginId: string;
56
+ serverKey: string;
57
+ }): string;
58
+ onlyPluginId(): string;
59
+ pluginIdRequired(): string;
60
+ credentialText(input: {
61
+ id: string;
62
+ locale: string;
63
+ }): string;
64
+ translateCredentialMessage(input: {
65
+ message: string;
66
+ locale: string;
67
+ }): string;
68
+ savedTokenSwitch(input: {
69
+ outcome: SavedTokenSwitchOutcome;
70
+ target: TokenAuthTarget;
71
+ }): string;
72
+ }
73
+ /** The host's token input rule (R1): a separate required input, not part of the credentials port.
74
+ * @agent-note Second host: `assertToken` throws YOUR input error for a malformed token (never echoing
75
+ * it); `inputErrorRule` returns that error's rule id for `messages.credentialText`, or null for any
76
+ * other error, which is then rethrown unchanged (same object). */
77
+ export interface AgentPluginTokenValidator {
78
+ assertToken(required: {
79
+ value: unknown;
80
+ field: "token";
81
+ }, optional?: Record<string, never>): void;
82
+ inputErrorRule(required: {
83
+ error: unknown;
84
+ }, optional?: Record<string, never>): string | null;
85
+ }
86
+ /** Plugin-declared credential cards and the guarded, read-only token probe.
87
+ * @agent-note Second host: `apply` returns the form it was given with the card's copy applied (no
88
+ * value fields); `probe` is one bounded GET that never returns a body; `find` reads safe card copy. */
89
+ export interface AgentPluginTokenCredentialsPort {
90
+ apply(input: {
91
+ card?: PluginCredentialCard | undefined;
92
+ form: SurfaceCardSecretForm;
93
+ }, options?: Record<string, never>): SurfaceCardSecretForm;
94
+ find(input: {
95
+ workspaceId: string;
96
+ saveKind: PluginCredentialCard["saveKind"];
97
+ target: string;
98
+ }, options?: Record<string, never>): Promise<PluginCredentialCard | undefined>;
99
+ probe(input: {
100
+ probeUrl: string;
101
+ token: string;
102
+ }, options?: Record<string, never>): Promise<"ok" | "refused" | "unavailable">;
103
+ }
104
+ /** What resolving and saving onto a plugin's token row needs — no permission check, no HTTP client.
105
+ * Shared with `import-access-token.ts`, which saves a token that did not come from this form.
106
+ * @agent-note Second host: `mcp` carries your canonical projection pair; `resolveInstalledPlugin` is
107
+ * your installed-declaration read (no filesystem default here); `federation` is your trust rule and
108
+ * federation refusal copy, the same pair your connect tool passes. */
109
+ export interface AgentPluginTokenTargetDeps {
110
+ readonly workspaceId: string;
111
+ readonly mcp: AgentPluginMcpProjectionPorts & Pick<AgentPluginMcpPort, "repo" | "saveServer"> & Partial<Pick<AgentPluginMcpPort, "notifyRosterChanged">>;
112
+ readonly resolveInstalledPlugin: (pluginId: string) => Promise<ResolvedAgentPluginForConnect | null>;
113
+ readonly federation: {
114
+ readonly classifyTrust: AgentPluginMcpTrustClassifier;
115
+ readonly messages: AgentPluginMcpFederationMessages;
116
+ };
117
+ readonly messages: Pick<AgentPluginAccessTokenMessages, "connectionNotSetUp" | "connectionRepointed" | "notInstalled" | "noTokenSignIn" | "multipleTokenSignIns" | "serverNotSetUp">;
118
+ }
119
+ /** The host's card wiring and identity for the token form.
120
+ * @agent-note Second host: `toolId` is the lifecycle id your secret-card answers route back to (your
121
+ * credential-save tool); the card URI host is `cardIdentity.uriNamespace`; `cards`/`askThenReport` come
122
+ * from the daemon the tool runs in; `permission`/`entityType` gate the tool. */
123
+ export interface AgentPluginAccessTokenHost {
124
+ readonly toolId: string;
125
+ readonly permission: string;
126
+ readonly entityType: string;
127
+ readonly cardIdentity: AgentPluginCardIdentity;
128
+ readonly cards: Pick<SurfaceCardsPort, "defineSecretCardTool">;
129
+ readonly askThenReport: SurfaceAskThenReport;
130
+ readonly formMessages: AgentPluginAccessTokenFormMessages;
131
+ }
132
+ /** @agent-note Second host: `tokenValidator` is required (R1); `switchOnSavedToken` switches the
133
+ * plugin on after a save exactly as a first sign-in does (your activation owner), and may throw. */
134
+ export interface AgentPluginAccessTokenToolDeps extends AgentPluginTokenTargetDeps {
135
+ readonly authorize: AuthorizeFn;
136
+ readonly mcp: AgentPluginTokenTargetDeps["mcp"] & Pick<AgentPluginMcpPort, "classifyError">;
137
+ readonly credentials: AgentPluginTokenCredentialsPort;
138
+ readonly preferences: {
139
+ locale(input: {
140
+ workspaceId: string;
141
+ principalId: string;
142
+ }, options?: Record<string, never>): Promise<string>;
143
+ };
144
+ readonly tokenValidator: AgentPluginTokenValidator;
145
+ readonly switchOnSavedToken: (required: {
146
+ target: TokenAuthTarget;
147
+ }) => Promise<SavedTokenSwitchOutcome>;
148
+ readonly messages: AgentPluginAccessTokenMessages;
149
+ readonly host: AgentPluginAccessTokenHost;
150
+ }
151
+ type UnansweredReason = "cancelled" | "expired" | "abandoned";
152
+ /** @agent-note Public outcome from the host's secret-card lifecycle; copy is safe and token-free.
153
+ * A saved token and an enabled plugin remain distinct outcomes when the operator kept it off. */
154
+ export type SetAccessTokenResult = {
155
+ saved: true;
156
+ next: string;
157
+ } | {
158
+ saved: false;
159
+ reason: UnansweredReason | "invalid" | "refused" | "unavailable" | "error";
160
+ message?: string;
161
+ };
162
+ /** The one declared token-auth server this call saves onto.
163
+ * @agent-note Derived from your trusted installed declaration; the store row is freshly re-read
164
+ * and its host matched before saving. These declaration URLs are not credential values. */
165
+ export interface TokenAuthTarget {
166
+ readonly pluginId: string;
167
+ readonly displayName: string;
168
+ readonly connectionId: string;
169
+ readonly config: RemoteMcpServerConfig & {
170
+ readonly tokenAuth: AgentPluginTokenAuth;
171
+ };
172
+ }
173
+ /**
174
+ * The plugin row, freshly read. Refused when it is missing or no longer points at the host the plugin
175
+ * declares, so a token is never sent to a server an operator re-pointed.
176
+ *
177
+ * @throws {ToolInputError}
178
+ */
179
+ export declare function requireTargetRow({ routeDeps, target }: {
180
+ routeDeps: Pick<AgentPluginTokenTargetDeps, "workspaceId" | "mcp" | "messages">;
181
+ target: TokenAuthTarget;
182
+ }, _options?: Record<string, never>): Promise<AgentPluginMcpRecord>;
183
+ /**
184
+ * Resolves the plugin's one server declaring `tokenAuth`, provisioning its row (idempotent, the
185
+ * same call `agent_plugin_connect` makes) so a first-time fallback needs no earlier step.
186
+ *
187
+ * @throws {ToolInputError} Not installed; no or several token-auth servers.
188
+ * @param optional.signal Stops provisioning when the run ends during plugin resolution.
189
+ * @throws The signal's abort reason before provisioning when cancelled.
190
+ */
191
+ export declare function resolveTarget({ routeDeps, pluginId, principalId }: {
192
+ routeDeps: AgentPluginTokenTargetDeps;
193
+ pluginId: string;
194
+ principalId: string;
195
+ }, optional?: {
196
+ signal?: AbortSignal;
197
+ }): Promise<TokenAuthTarget>;
198
+ /** Token sign-in keeps its input validation; Jini owns the GET, redirects and status classification.
199
+ * @returns Invalid only for malformed input; HTTP 401/403 mean refused for this purpose.
200
+ * @complexity One bounded GET; no persistence, response bodies or transport errors escape.
201
+ */
202
+ export declare function probeToken({ probeUrl, token, credentials, tokenValidator }: {
203
+ probeUrl: string;
204
+ token: string;
205
+ credentials: Pick<AgentPluginTokenCredentialsPort, "probe">;
206
+ tokenValidator: Pick<AgentPluginTokenValidator, "assertToken">;
207
+ }, _options?: Record<string, never>): Promise<"ok" | "invalid" | "refused" | "unavailable">;
208
+ /**
209
+ * Seals `token` onto the freshly re-read row as its `static_env` access token, carrying every
210
+ * operator-set field forward unchanged. Re-read at write time because the human may sit on the form
211
+ * while the operator edits the allowlists.
212
+ * @param optional.signal Stops the write when the run ends during the fresh row read.
213
+ * @throws The signal's abort reason before saving when cancelled.
214
+ */
215
+ export declare function saveStaticAccessToken({ routeDeps, target, principalId, token }: {
216
+ routeDeps: Pick<AgentPluginTokenTargetDeps, "workspaceId" | "mcp" | "messages">;
217
+ target: TokenAuthTarget;
218
+ principalId: string;
219
+ token: string;
220
+ }, optional?: {
221
+ signal?: AbortSignal;
222
+ }): Promise<void>;
223
+ /**
224
+ * Runs `agent_plugin_set_access_token` end to end: permission, resolve, form, probe, save.
225
+ *
226
+ * @throws {ToolInputError} Extra input, unknown plugin, no token-auth server, or a re-pointed row.
227
+ * @throws {ToolInputError} No `emitSurface` on this execution context.
228
+ * @agent-note Cards/askThenReport and the core exchange store must belong to the SAME answer
229
+ * lifecycle. Bind your validator/error classifier and canonical store; tokens travel only from
230
+ * the human form through probe/save, never through tool input or model-visible events.
231
+ */
232
+ export declare function saveAgentPluginToken({ routeDeps, surfaces, ctx }: {
233
+ routeDeps: AgentPluginAccessTokenToolDeps;
234
+ surfaces: {
235
+ readonly surfaceExchanges: Pick<SurfaceExchangeStore, "open">;
236
+ };
237
+ ctx: ToolExecutionContext;
238
+ }, optional?: ToolExecutionOptions): Promise<SetAccessTokenResult>;
239
+ export {};
240
+ //# sourceMappingURL=access-token-tool.d.ts.map
@@ -0,0 +1,213 @@
1
+ import { adaptLegacyAuthorize, requireToolPermission } from "@jini-ai/core";
2
+ import { requireInputRecord, ToolInputError } from "@jini-ai/core";
3
+ import { deriveAgentPluginConnectionId, provisionAgentPluginMcpServers } from "./federate-mcp.js";
4
+ import { buildAgentPluginAccessTokenFormWithPorts, buildAgentPluginAccessTokenOutcomeWithPorts, resolveAgentPluginCardIdentity, } from "./connect-card-ui.js";
5
+ import { titleCaseFromPluginId } from "./connect-tool.js";
6
+ /** Plain-language messages from SPEC-052's errors.spec.md. None ever carries a token or a vendor body. */
7
+ const MESSAGES = {
8
+ tokenInvalid: "The server rejected this token.",
9
+ blankToken: "The access token cannot be blank. Nothing was saved.",
10
+ saveFailed: "The access token could not be saved. Nothing was changed.",
11
+ };
12
+ function hostOf(url) {
13
+ if (url === null)
14
+ return null;
15
+ try {
16
+ return new URL(url).host;
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ /**
23
+ * The plugin row, freshly read. Refused when it is missing or no longer points at the host the plugin
24
+ * declares, so a token is never sent to a server an operator re-pointed.
25
+ *
26
+ * @throws {ToolInputError}
27
+ */
28
+ export async function requireTargetRow({ routeDeps, target }, _options = {}) {
29
+ const row = await routeDeps.mcp.repo.findByServerId({ workspaceId: routeDeps.workspaceId, serverId: target.connectionId });
30
+ if (row === null) {
31
+ throw new ToolInputError({ message: routeDeps.messages.connectionNotSetUp({ pluginId: target.pluginId }) });
32
+ }
33
+ if (hostOf(row.url) !== hostOf(target.config.url)) {
34
+ throw new ToolInputError({ message: routeDeps.messages.connectionRepointed({ connectionId: target.connectionId, displayName: target.displayName }) });
35
+ }
36
+ return row;
37
+ }
38
+ /**
39
+ * Resolves the plugin's one server declaring `tokenAuth`, provisioning its row (idempotent, the
40
+ * same call `agent_plugin_connect` makes) so a first-time fallback needs no earlier step.
41
+ *
42
+ * @throws {ToolInputError} Not installed; no or several token-auth servers.
43
+ * @param optional.signal Stops provisioning when the run ends during plugin resolution.
44
+ * @throws The signal's abort reason before provisioning when cancelled.
45
+ */
46
+ export async function resolveTarget({ routeDeps, pluginId, principalId }, optional = {}) {
47
+ const plugin = await routeDeps.resolveInstalledPlugin(pluginId);
48
+ if (!plugin)
49
+ throw new ToolInputError({ message: routeDeps.messages.notInstalled({ pluginId }) });
50
+ const declared = Object.entries(plugin.servers).flatMap(([serverKey, config]) => config.type !== "stdio" && config.tokenAuth ? [{ serverKey, config: config }] : []);
51
+ if (declared.length === 0)
52
+ throw new ToolInputError({ message: routeDeps.messages.noTokenSignIn({ pluginId }) });
53
+ if (declared.length > 1)
54
+ throw new ToolInputError({ message: routeDeps.messages.multipleTokenSignIns({ pluginId }) });
55
+ const [{ serverKey, config }] = declared;
56
+ const connectionId = deriveAgentPluginConnectionId({ serverKey });
57
+ if (!connectionId)
58
+ throw new ToolInputError({ message: routeDeps.messages.serverNotSetUp({ pluginId, serverKey }) });
59
+ optional.signal?.throwIfAborted();
60
+ await provisionAgentPluginMcpServers(routeDeps.mcp, { workspaceId: routeDeps.workspaceId, pluginId, servers: plugin.servers, principalId, ...routeDeps.federation });
61
+ return { pluginId, displayName: titleCaseFromPluginId({ pluginId }), connectionId, config };
62
+ }
63
+ /** Token sign-in keeps its input validation; Jini owns the GET, redirects and status classification.
64
+ * @returns Invalid only for malformed input; HTTP 401/403 mean refused for this purpose.
65
+ * @complexity One bounded GET; no persistence, response bodies or transport errors escape.
66
+ */
67
+ export async function probeToken({ probeUrl, token, credentials, tokenValidator }, _options = {}) {
68
+ try {
69
+ tokenValidator.assertToken({ value: token, field: 'token' });
70
+ }
71
+ catch {
72
+ return "invalid";
73
+ }
74
+ return credentials.probe({ probeUrl, token });
75
+ }
76
+ function joinStoredList(raw) {
77
+ const parsed = raw === null ? [] : JSON.parse(raw);
78
+ return Array.isArray(parsed) ? parsed.filter((name) => typeof name === "string").join(",") : "";
79
+ }
80
+ /**
81
+ * Seals `token` onto the freshly re-read row as its `static_env` access token, carrying every
82
+ * operator-set field forward unchanged. Re-read at write time because the human may sit on the form
83
+ * while the operator edits the allowlists.
84
+ * @param optional.signal Stops the write when the run ends during the fresh row read.
85
+ * @throws The signal's abort reason before saving when cancelled.
86
+ */
87
+ export async function saveStaticAccessToken({ routeDeps, target, principalId, token }, optional = {}) {
88
+ const row = await requireTargetRow({ routeDeps, target });
89
+ // A row read or probe may finish after the run ends; never start a credential write then.
90
+ optional.signal?.throwIfAborted();
91
+ await routeDeps.mcp.saveServer({
92
+ workspaceId: routeDeps.workspaceId,
93
+ serverId: row.serverId,
94
+ ...(row.label !== null ? { label: row.label } : {}),
95
+ transport: "streamable_http",
96
+ authMode: "static_env",
97
+ enabled: row.enabled,
98
+ command: "",
99
+ url: row.url ?? target.config.url,
100
+ args: "",
101
+ allowedToolNames: joinStoredList(row.allowedToolNames),
102
+ writeAllowedToolNames: joinStoredList(row.writeAllowedToolNames),
103
+ accessToken: token,
104
+ principalId,
105
+ });
106
+ }
107
+ /** Only the store's known validation/unconfigured errors are shown. Sealing failures can quote
108
+ * plaintext, so unconfigured storage gets fixed copy; the engine redacts allowlisted messages. */
109
+ function describeSaveError({ err, mcp, messages }, _options = {}) {
110
+ const kind = mcp.classifyError({ error: err });
111
+ if (kind === "unconfigured")
112
+ return messages.credentialText({ id: "storage", locale: "en" });
113
+ const known = kind === "validation" || err instanceof ToolInputError;
114
+ return known ? err.message : MESSAGES.saveFailed;
115
+ }
116
+ /**
117
+ * The form's answer: probe, then seal. The token lives only in a local for the width of this function
118
+ * and is never returned, logged, or put in an outcome.
119
+ *
120
+ * @complexity O(1) plus one outbound GET and one store save.
121
+ */
122
+ async function saveSubmittedAccessToken({ values, routeDeps, target, principalId, locale, signal, credentialCard }, _optional = {}) {
123
+ const submitted = values.token;
124
+ try {
125
+ routeDeps.tokenValidator.assertToken({ value: submitted, field: 'token' });
126
+ }
127
+ catch (err) {
128
+ const rule = routeDeps.tokenValidator.inputErrorRule({ error: err });
129
+ if (rule !== null) {
130
+ return { saved: false, reason: 'invalid', message: routeDeps.messages.credentialText({ id: rule, locale }) };
131
+ }
132
+ throw err;
133
+ }
134
+ const token = submitted.trim();
135
+ const probe = await probeToken({ probeUrl: target.config.tokenAuth.probeUrl, token, credentials: routeDeps.credentials, tokenValidator: routeDeps.tokenValidator });
136
+ signal.throwIfAborted();
137
+ if (probe === "invalid")
138
+ return { saved: false, reason: "invalid", message: routeDeps.messages.translateCredentialMessage({ message: MESSAGES.tokenInvalid, locale }) };
139
+ if (probe === "refused") {
140
+ const hint = credentialCard?.keyHint ? ` This card needs: ${credentialCard.keyHint}` : '';
141
+ return { saved: false, reason: "refused", message: `This token was refused for this purpose.${hint}` };
142
+ }
143
+ if (probe === "unavailable")
144
+ return { saved: false, reason: "unavailable", message: `${target.displayName} is unavailable right now. Try again shortly.` };
145
+ await saveStaticAccessToken({ routeDeps, target, principalId, token }, { signal });
146
+ let next;
147
+ try {
148
+ next = routeDeps.messages.savedTokenSwitch({ outcome: await routeDeps.switchOnSavedToken({ target }), target });
149
+ }
150
+ catch {
151
+ // The token is saved; only switching on failed. The next save or sign-in retries it.
152
+ next = `Token saved, but ${target.displayName} could not be switched on automatically. Save the token again to retry.`;
153
+ }
154
+ return { saved: true, next };
155
+ }
156
+ /** Preserve the catalog's result contract while Jini owns answer classification and error redaction. */
157
+ function accessTokenResult({ run, locale, messages }, _optional = {}) {
158
+ if (run.status === "saved")
159
+ return run.saved;
160
+ if (run.status === "blank")
161
+ return { saved: false, reason: "invalid", message: messages.credentialText({ id: "blank", locale }) };
162
+ if (run.status === "failed")
163
+ return { saved: false, reason: "error", message: run.safeMessage };
164
+ return { saved: false, reason: run.status };
165
+ }
166
+ /**
167
+ * Runs `agent_plugin_set_access_token` end to end: permission, resolve, form, probe, save.
168
+ *
169
+ * @throws {ToolInputError} Extra input, unknown plugin, no token-auth server, or a re-pointed row.
170
+ * @throws {ToolInputError} No `emitSurface` on this execution context.
171
+ * @agent-note Cards/askThenReport and the core exchange store must belong to the SAME answer
172
+ * lifecycle. Bind your validator/error classifier and canonical store; tokens travel only from
173
+ * the human form through probe/save, never through tool input or model-visible events.
174
+ */
175
+ // -> one outbound GET to the declared probeUrl, then saveExternalMcpServer: a sealed write, via the human's form.
176
+ export async function saveAgentPluginToken({ routeDeps, surfaces, ctx }, optional = {}) {
177
+ const input = requireInputRecord({ input: ctx.input });
178
+ const { host, messages } = routeDeps;
179
+ const tokenApps = resolveAgentPluginCardIdentity({ cardIdentity: host.cardIdentity, toolId: host.toolId }).token;
180
+ const card = host.cards.defineSecretCardTool({
181
+ toolId: host.toolId,
182
+ prepare: async ({ ctx }) => {
183
+ if (Object.keys(input).some((key) => key !== "pluginId")) {
184
+ throw new ToolInputError({ message: messages.onlyPluginId() });
185
+ }
186
+ const pluginId = input.pluginId;
187
+ if (typeof pluginId !== "string" || pluginId.trim() === "")
188
+ throw new ToolInputError({ message: messages.pluginIdRequired() });
189
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: host.permission }, { entityType: host.entityType, entityId: pluginId });
190
+ // Resolution provisions a missing plugin row; an ended run must not start that effect.
191
+ ctx.signal.throwIfAborted();
192
+ const target = await resolveTarget({ routeDeps, pluginId, principalId: ctx.principal.id }, { signal: ctx.signal });
193
+ await requireTargetRow({ routeDeps, target });
194
+ const locale = await routeDeps.preferences.locale({ workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id });
195
+ const credentialCard = await routeDeps.credentials.find({ workspaceId: routeDeps.workspaceId, saveKind: "agent-plugin-token", target: pluginId });
196
+ return { target, principalId: ctx.principal.id, locale, credentialCard };
197
+ },
198
+ form: ({ prep }) => buildAgentPluginAccessTokenFormWithPorts({ app: tokenApps.formApp, messages: host.formMessages, spec: { credentials: routeDeps.credentials, pluginDisplayName: prep.target.displayName, helpUrl: prep.target.config.tokenAuth.helpUrl, credentialCard: prep.credentialCard } }),
199
+ save: ({ values, prep, signal }) => saveSubmittedAccessToken({ values, routeDeps, ...prep, signal }),
200
+ result: ({ prep, run }) => accessTokenResult({ run, locale: prep.locale, messages }),
201
+ outcome: ({ prep, run }) => {
202
+ const result = accessTokenResult({ run, locale: prep.locale, messages });
203
+ if (!result.saved && result.message === undefined)
204
+ return undefined;
205
+ return buildAgentPluginAccessTokenOutcomeWithPorts({ app: tokenApps.outcomeApp, spec: {
206
+ pluginDisplayName: prep.target.displayName, state: result.saved ? "success" : "failure",
207
+ title: result.saved ? "Token saved" : "Token not saved", message: result.saved ? result.next : result.message,
208
+ } });
209
+ },
210
+ }, { uriHost: host.cardIdentity.uriNamespace, frameSize: ["100%", "380px"], safeError: err => describeSaveError({ err, mcp: routeDeps.mcp, messages }), text: { saveFailure: MESSAGES.saveFailed } });
211
+ return card.handler({ surfaceExchanges: surfaces.surfaceExchanges, askThenReport: host.askThenReport })(ctx, optional);
212
+ }
213
+ //# sourceMappingURL=access-token-tool.js.map
@@ -0,0 +1,91 @@
1
+ import type { AgentPluginMcpProjectionPorts } from './ports.js';
2
+ /**
3
+ * @file Grants a plugin's declared default tools (`mcp.json`'s `defaultTools`, parsed by
4
+ * `manifest.ts`) on the operator's FIRST successful sign-in to a server that plugin provisioned — so
5
+ * connecting is the only step, with no trip to Settings to tick tools. An explicit enable card
6
+ * calls the same owner with its listed grants, even when sign-in will happen afterwards.
7
+ *
8
+ * `federate-mcp.ts` rule 3 ("provisioning is not authorization") still holds: provisioning writes a
9
+ * disabled row with empty lists; a human sign-in or an enable card naming the source and grants
10
+ * is what authorizes turning the declared defaults on.
11
+ *
12
+ * Applied only when ALL of these hold, and otherwise nothing is written:
13
+ * - the row names a provisioning plugin (`provisionedByPluginId`), so an operator's own row is never
14
+ * touched;
15
+ * - on sign-in both tool lists are still empty, so a row the operator already edited is never
16
+ * touched, and a second sign-in (lists now filled) is a no-op. An explicit enable card may add
17
+ * its listed defaults to existing grants, preserving the owner's other granted names;
18
+ * - the installed plugin still declares a server that maps to this row at the SAME url, so defaults
19
+ * written for one endpoint never land on a row an operator pointed somewhere else;
20
+ * - no operator turned the plugin off (a seeder's default-off record does not count).
21
+ *
22
+ * Architectural role:
23
+ * `features/agent-plugins` business rule, implementing `external-mcp-oauth.ts`'s `onConnected` port.
24
+ * Wired where the OAuth service is composed (`composition/app.ts`, `composition/deps.ts`,
25
+ * `agent-daemon-server.ts`).
26
+ */
27
+ import type { AgentPluginMcpPort } from "./ports.js";
28
+ import type { Clock as ClockPort } from "@jini-ai/core/primitives";
29
+ import { type AgentPluginEnableAccessMessages } from './enable-access.js';
30
+ import type { McpServerConfig } from "../lifecycle/manifest.js";
31
+ /** @agent-note Actor ids are host vocabulary, saved verbatim as the activation's `updatedBy` and the row's
32
+ * write-grant attribution (`principalId`): a second host passes its own stable ids and never changes
33
+ * them once rows exist (saved bytes compare equal across restarts). */
34
+ export interface AgentPluginConnectActors {
35
+ /** Recorded as the plugin activation's `updatedBy` and the row's write-grant attribution: the grant
36
+ * came from the plugin's declaration, at a sign-in, not from a Settings save. */
37
+ readonly connectDefaults: string;
38
+ /** Recorded on a source whose displayed default grant the owner declined. */
39
+ readonly connectDeclined: string;
40
+ }
41
+ export type ApplyConnectDefaultsDeps = Pick<AgentPluginMcpPort, "repo" | "applyAccess"> & AgentPluginMcpProjectionPorts & {
42
+ /** @agent-note Host repair copy shared with the enable preview; no product tool name is assumed. */
43
+ readonly combinedGrantRejected: AgentPluginEnableAccessMessages['combinedGrantRejected'];
44
+ readonly clock: ClockPort;
45
+ readonly workspaceId: string;
46
+ /** @agent-note Host lifecycle read: the host binds `federate-mcp.ts`'s `resolveAgentPluginMcpServers`
47
+ * over its own installed-package reads. Fresh per call. */
48
+ readonly resolveServers: (input: {
49
+ workspaceId: string;
50
+ pluginId: string;
51
+ }) => Promise<Readonly<Record<string, McpServerConfig>>>;
52
+ /** @agent-note Host activation owner: switches the plugin on unless an operator turned it off, through
53
+ * the host's one activation queue with every check a switch has; `false` means an operator's "off"
54
+ * stopped it, and nothing is granted. */
55
+ readonly enablePlugin: (input: {
56
+ workspaceId: string;
57
+ pluginId: string;
58
+ actor: string;
59
+ }) => Promise<unknown>;
60
+ readonly actors: AgentPluginConnectActors;
61
+ /** Host supplies the assistant's `notifyExternalMcpRosterChanged` port. */
62
+ readonly notifyRosterChanged: () => Promise<void>;
63
+ /** @agent-note Host activation read: whether an operator (not the seeder) turned the plugin off. */
64
+ readonly isPluginOffByOperator: (pluginId: string) => Promise<boolean>;
65
+ };
66
+ /**
67
+ * Builds the `onConnected(serverId)` port.
68
+ *
69
+ * @throws Whatever the repo or plugin-activation write throws; the OAuth service logs it without
70
+ * failing the sign-in.
71
+ * @complexity O(s) in the plugin's declared server count, plus one row write and one activation write.
72
+ */
73
+ export declare function createApplyConnectDefaults(deps: ApplyConnectDefaultsDeps, options?: {
74
+ readonly approvedEnable?: {
75
+ readonly principalId: string;
76
+ readonly accessKey: string;
77
+ };
78
+ }): (serverId: string) => Promise<void>;
79
+ /** Remember a declined proposal without replacing an earlier grant's attribution or credentials.
80
+ * Existing decisions already prevent automatic defaults; only an unattributed source needs a marker.
81
+ * @throws The existing conditional writer's source-changed error if a displayed row changed.
82
+ * @complexity One conditional point write per eligible displayed source; O(s*(a+w)) grant bytes.
83
+ */
84
+ export declare function recordAgentPluginAccessDeclined({ applyAccess, workspaceId, accessKey, actorId }: {
85
+ applyAccess: AgentPluginMcpPort['applyAccess'];
86
+ workspaceId: string;
87
+ accessKey: string;
88
+ /** @agent-note The host's declined-access actor id ({@link AgentPluginConnectActors.connectDeclined}). */
89
+ actorId: string;
90
+ }, _options?: {}): Promise<void>;
91
+ //# sourceMappingURL=apply-connect-defaults.d.ts.map
@@ -0,0 +1,113 @@
1
+ import { ToolInputError } from '@jini-ai/core';
2
+ import { previewAgentPluginEnableAccess, storedAgentPluginGrants, validatedAgentPluginToolGrant } from './enable-access.js';
3
+ import { findAgentPluginMcpServerDefaults, isEmptyJsonList } from "./federate-mcp.js";
4
+ /** Read one matching plugin row and delegate the grant decision to Jini.
5
+ * @complexity One indexed row read plus that plugin's existing manifest resolution; O(a+w) lists.
6
+ */
7
+ async function readConnectGrant({ deps, serverId, resolveServers, approvedEnable, ports }) {
8
+ const row = await deps.repo.findByServerId({ workspaceId: deps.workspaceId, serverId });
9
+ if (!row)
10
+ return null;
11
+ const pluginId = row.provisionedByPluginId;
12
+ if (!pluginId)
13
+ return null;
14
+ if (!approvedEnable && !allowsAutomaticConnectGrant(row))
15
+ return null;
16
+ const defaults = findAgentPluginMcpServerDefaults(await resolveServers({ workspaceId: deps.workspaceId, pluginId }), row);
17
+ // A read-only declaration is classification, not permission to change sign-in grants.
18
+ if (!defaults?.allow)
19
+ return null;
20
+ const grant = validatedAgentPluginToolGrant({ current: storedAgentPluginGrants({ row, projections: ports.projections }), declared: defaults }, { reason: approvedEnable ? 'owner-enable' : 'sign-in', ports, messages: deps });
21
+ return grant ? { row, pluginId, grant } : null;
22
+ }
23
+ /** Existing choices and nonempty selections stay until a fresh access approval. O(n) list bytes. */
24
+ function allowsAutomaticConnectGrant(row) {
25
+ return row.writeGrantsUpdatedByPrincipalId === null &&
26
+ isEmptyJsonList({ raw: row.allowedToolNames }) && isEmptyJsonList({ raw: row.writeAllowedToolNames });
27
+ }
28
+ /**
29
+ * Builds the `onConnected(serverId)` port.
30
+ *
31
+ * @throws Whatever the repo or plugin-activation write throws; the OAuth service logs it without
32
+ * failing the sign-in.
33
+ * @complexity O(s) in the plugin's declared server count, plus one row write and one activation write.
34
+ */
35
+ export function createApplyConnectDefaults(deps, options = {}) {
36
+ const resolveServers = deps.resolveServers;
37
+ const enablePlugin = deps.enablePlugin;
38
+ const isOff = deps.isPluginOffByOperator;
39
+ // Resolved once per factory: preview, grant and revalidation all compare with the same projections.
40
+ const ports = { projections: deps.projections, classifyError: deps.classifyError };
41
+ return async (serverId) => {
42
+ assertApprovedSnapshot(options.approvedEnable);
43
+ const prepared = await readConnectGrant({ deps, serverId, resolveServers, approvedEnable: options.approvedEnable !== undefined, ports });
44
+ if (!prepared)
45
+ return;
46
+ const { row, pluginId, grant } = prepared;
47
+ const approved = approvedSource({ key: options.approvedEnable?.accessKey, connectionId: serverId, pluginId });
48
+ assertApprovedSource({ approved, grant, current: storedAgentPluginGrants({ row, projections: ports.projections }), url: row.url, expected: ports.projections.accessSnapshot({ record: row }) });
49
+ // A sign-in is not an "on" switch: an operator's explicit plugin-off stays off, exactly as on
50
+ // the saved-token path (`switch-on-saved-token.ts`). The sign-in itself still completes.
51
+ if (await isOff(pluginId))
52
+ return;
53
+ // Plugin first: if this throws, nothing is written and the next sign-in tries again. The row
54
+ // write is the step that makes a retry a no-op, so it goes last. The check above is only a cheap
55
+ // early exit: an operator's "off" landing after it is caught again under the activations lock.
56
+ if (await enablePlugin({ workspaceId: deps.workspaceId, pluginId, actor: deps.actors.connectDefaults }) === false)
57
+ return;
58
+ const expected = approved?.expected ?? ports.projections.accessSnapshot({ record: row });
59
+ // Direct repo write, the same reason `federate-mcp.ts`'s adoption gives: every other field
60
+ // (url, auth, the token this sign-in just stored) must stay exactly as it is.
61
+ await deps.applyAccess({ workspaceId: deps.workspaceId, serverId,
62
+ expected, access: { enabled: true, allowedToolNames: grant.allow, writeAllowedToolNames: grant.write },
63
+ principalId: options.approvedEnable?.principalId ?? deps.actors.connectDefaults });
64
+ await deps.notifyRosterChanged();
65
+ };
66
+ }
67
+ /** Approval-bearing callers cannot fall back to an unbound sign-in grant. */
68
+ function assertApprovedSnapshot(approved) {
69
+ if (approved && !approved.accessKey)
70
+ throw new ToolInputError({ message: 'The approved access snapshot is missing. Request the access change again. Nothing was granted.' });
71
+ }
72
+ /** Only the detached host-produced snapshot authorizes a chat-triggered widening.
73
+ * The effect compares its admission and previous grants atomically in the repository. */
74
+ function approvedSource({ key, connectionId, pluginId }, _options = {}) {
75
+ if (key === undefined)
76
+ return undefined;
77
+ const sources = JSON.parse(key);
78
+ const source = sources.find(source => source.connectionId === connectionId);
79
+ if (!source?.grant)
80
+ throw new ToolInputError({ message: `The approved card did not grant access to '${connectionId}'. Request the access change again.` });
81
+ if (source.pluginId !== pluginId)
82
+ throw new ToolInputError({ message: 'The connection owner changed after approval. Request the access change again. Nothing was granted.' });
83
+ // Provisioning associates an operator-owned row after approval without changing its source or access.
84
+ const expected = source.expected ? { ...source.expected, provisionedByPluginId: source.expected.provisionedByPluginId ?? pluginId } : null;
85
+ return { url: source.url, expected, current: source.current, grant: source.grant };
86
+ }
87
+ /** New sources must still have the empty access displayed before provisioning.
88
+ * Existing sources additionally use the approved atomic repository snapshot. */
89
+ function assertApprovedSource({ approved, grant, current, url, expected }, _options = {}) {
90
+ if (!approved)
91
+ return;
92
+ const sameGrant = JSON.stringify(approved.grant) === JSON.stringify(grant);
93
+ const sameNewSource = approved.expected !== null || JSON.stringify(approved.current) === JSON.stringify(current);
94
+ const sameExistingSource = approved.expected === null || JSON.stringify(approved.expected) === JSON.stringify(expected);
95
+ if (!sameGrant || !sameNewSource || !sameExistingSource || approved.url !== url)
96
+ throw new ToolInputError({ message: 'The plugin declaration or access changed after approval. Request the access change again. Nothing was granted.' });
97
+ }
98
+ /** Remember a declined proposal without replacing an earlier grant's attribution or credentials.
99
+ * Existing decisions already prevent automatic defaults; only an unattributed source needs a marker.
100
+ * @throws The existing conditional writer's source-changed error if a displayed row changed.
101
+ * @complexity One conditional point write per eligible displayed source; O(s*(a+w)) grant bytes.
102
+ */
103
+ export async function recordAgentPluginAccessDeclined({ applyAccess, workspaceId, accessKey, actorId }, _options = {}) {
104
+ const sources = JSON.parse(accessKey);
105
+ for (const source of sources) {
106
+ if (!source.grant || !source.expected || source.expected.writeGrantsUpdatedByPrincipalId !== null)
107
+ continue;
108
+ await applyAccess({ workspaceId, serverId: source.connectionId, expected: source.expected,
109
+ principalId: actorId,
110
+ access: { enabled: source.current.enabled, allowedToolNames: source.current.allow, writeAllowedToolNames: source.current.write } });
111
+ }
112
+ }
113
+ //# sourceMappingURL=apply-connect-defaults.js.map