@engenty/wizards-runtime 0.16.2 → 0.17.1

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 (156) hide show
  1. package/apps/runtime/dist/agents/studio-assistant.js +13 -6
  2. package/apps/runtime/dist/app.js +2 -0
  3. package/apps/runtime/dist/assistant/knows.js +15 -2
  4. package/apps/runtime/dist/broker/account.js +20 -1
  5. package/apps/runtime/dist/broker/call.js +131 -22
  6. package/apps/runtime/dist/broker/grant.js +25 -1
  7. package/apps/runtime/dist/broker/host.js +8 -2
  8. package/apps/runtime/dist/broker/index.js +5 -4
  9. package/apps/runtime/dist/broker/log.js +178 -24
  10. package/apps/runtime/dist/broker/over.js +38 -0
  11. package/apps/runtime/dist/broker/rights.js +192 -0
  12. package/apps/runtime/dist/broker/rwx.js +309 -53
  13. package/apps/runtime/dist/broker/send.js +109 -44
  14. package/apps/runtime/dist/bundles/fetch.js +119 -0
  15. package/apps/runtime/dist/bundles/index.js +621 -0
  16. package/apps/runtime/dist/bundles/read.js +607 -0
  17. package/apps/runtime/dist/connectors/external.js +532 -61
  18. package/apps/runtime/dist/connectors/person-sign-ins.js +1 -0
  19. package/apps/runtime/dist/connectors/reload.js +73 -0
  20. package/apps/runtime/dist/connectors/space-connections.js +118 -6
  21. package/apps/runtime/dist/db/migrations/tenant/0058_mcp_state_across_roles.sql +26 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0059_space_connection_paused.sql +2 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0060_space_bundle.sql +21 -0
  24. package/apps/runtime/dist/db/migrations/tenant/0061_space_connection_limits.sql +2 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0058_snapshot.json +6696 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0059_snapshot.json +6710 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/0060_snapshot.json +6857 -0
  28. package/apps/runtime/dist/db/migrations/tenant/meta/0061_snapshot.json +6871 -0
  29. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +28 -0
  30. package/apps/runtime/dist/db/schema.js +81 -3
  31. package/apps/runtime/dist/docs/dev/broker.md +316 -50
  32. package/apps/runtime/dist/docs/dev/plugins/space.md +13 -2
  33. package/apps/runtime/dist/docs/user-guide/capabilities.md +172 -10
  34. package/apps/runtime/dist/docs/user-guide/connectors.md +57 -7
  35. package/apps/runtime/dist/docs/user-guide/protocol.md +44 -7
  36. package/apps/runtime/dist/docs/user-guide/test-and-share.md +1 -1
  37. package/apps/runtime/dist/docs/user-guide/together.md +4 -4
  38. package/apps/runtime/dist/elements/caller.js +2 -2
  39. package/apps/runtime/dist/elements/knowledge.js +16 -12
  40. package/apps/runtime/dist/engenty/connections-external/build-connector.js +23 -8
  41. package/apps/runtime/dist/engenty/connections-external/import-service.js +18 -9
  42. package/apps/runtime/dist/engenty/connections-external/importer/classify.js +12 -0
  43. package/apps/runtime/dist/engenty/connections-external/invoke/http-invoker.js +1 -0
  44. package/apps/runtime/dist/engenty/connections-external/net/guarded-fetch.js +6 -3
  45. package/apps/runtime/dist/engenty/connections-sdk/oauth2.js +2 -2
  46. package/apps/runtime/dist/engenty/shims/web-ingest.js +64 -0
  47. package/apps/runtime/dist/engine/resources.js +15 -6
  48. package/apps/runtime/dist/engine/runner.js +2 -1
  49. package/apps/runtime/dist/engine/steps.js +3 -2
  50. package/apps/runtime/dist/env.js +2 -0
  51. package/apps/runtime/dist/index.js +19 -2
  52. package/apps/runtime/dist/live/hub.js +17 -3
  53. package/apps/runtime/dist/live/origin.js +6 -4
  54. package/apps/runtime/dist/live/views.js +38 -7
  55. package/apps/runtime/dist/mcp/handler.js +2 -2
  56. package/apps/runtime/dist/mcp/seen.js +71 -51
  57. package/apps/runtime/dist/mcp/tools.js +5 -1
  58. package/apps/runtime/dist/models.js +18 -0
  59. package/apps/runtime/dist/prompts/mcp.md +1 -1
  60. package/apps/runtime/dist/prompts/tools.md +17 -1
  61. package/apps/runtime/dist/routes/api.js +2 -2
  62. package/apps/runtime/dist/routes/broker.js +59 -20
  63. package/apps/runtime/dist/routes/bundles.js +91 -0
  64. package/apps/runtime/dist/routes/connections.js +14 -3
  65. package/apps/runtime/dist/routes/live.js +4 -2
  66. package/apps/runtime/dist/routes/rules.js +53 -9
  67. package/apps/runtime/dist/routes/studio.js +36 -20
  68. package/apps/runtime/dist/services/api.js +4 -2
  69. package/apps/runtime/dist/services/cloud.js +2 -0
  70. package/apps/runtime/dist/services/draft-events.js +79 -6
  71. package/apps/runtime/dist/services/errors.js +1 -0
  72. package/apps/runtime/dist/services/files.js +2 -2
  73. package/apps/runtime/dist/services/knowledge.js +93 -27
  74. package/apps/runtime/dist/services/members-studio.js +22 -2
  75. package/apps/runtime/dist/services/skills.js +61 -5
  76. package/apps/runtime/dist/services/space-categories.js +83 -5
  77. package/apps/runtime/dist/services/space-index.js +173 -25
  78. package/apps/runtime/dist/services/space-origin.js +28 -11
  79. package/apps/runtime/dist/services/synced-spaces.js +5 -1
  80. package/apps/runtime/dist/services/wizards.js +48 -2
  81. package/apps/runtime/dist/services/work-ai.js +15 -5
  82. package/apps/runtime/dist/sharing/jobs.js +8 -2
  83. package/apps/runtime/dist/sync/hub.js +17 -3
  84. package/apps/runtime/dist/sync/records.js +6 -1
  85. package/apps/runtime/dist/texts.js +42 -5
  86. package/apps/runtime/dist/tools/connections.js +8 -0
  87. package/apps/runtime/dist/tools/connector.js +13 -1
  88. package/apps/runtime/dist/tools/index.js +21 -10
  89. package/apps/runtime/dist/tools/skills.js +11 -1
  90. package/apps/runtime/dist/tools/web-search.js +36 -0
  91. package/apps/web/dist/assets/{AboutDialog-BCcD8hKm.js → AboutDialog-mZCBU7KF.js} +1 -1
  92. package/apps/web/dist/assets/{BlockEditor-DgaUm2pR.js → BlockEditor-Dk0QwLSU.js} +1 -1
  93. package/apps/web/dist/assets/CapabilitiesPage-GkpgF-wZ.js +2 -0
  94. package/apps/web/dist/assets/{ChangelogDialog-B08elwyr.js → ChangelogDialog-BhyilZWA.js} +1 -1
  95. package/apps/web/dist/assets/{CodeEditor-BiyOk_SC.js → CodeEditor-DULYZbuE.js} +1 -1
  96. package/apps/web/dist/assets/EditorPage-D_mCdYdZ.js +3 -0
  97. package/apps/web/dist/assets/{FlowPreview-DF_6TvZ0.js → FlowPreview-ykxZxWnk.js} +1 -1
  98. package/apps/web/dist/assets/{LangSwitch-Ba4OWLzJ.js → LangSwitch-iO54w9AP.js} +1 -1
  99. package/apps/web/dist/assets/{Marketplace-DqziLf66.js → Marketplace-C97fH7UC.js} +2 -2
  100. package/apps/web/dist/assets/{NewWizardChannels-CsIGp0nZ.js → NewWizardChannels-CsSV7sm2.js} +1 -1
  101. package/apps/web/dist/assets/{NewWizardPage-CzQAkKMy.js → NewWizardPage-Ebgw-Vf_.js} +1 -1
  102. package/apps/web/dist/assets/{OnboardingPage-B9gr2OX5.js → OnboardingPage-BZlloT7v.js} +1 -1
  103. package/apps/web/dist/assets/PreviewPane-CJuqY5uA.js +7 -0
  104. package/apps/web/dist/assets/ProtocolSection-CPaDKVpZ.js +1 -0
  105. package/apps/web/dist/assets/{PublicRunner-BVs8-Vu3.js → PublicRunner-4Lf4SnwB.js} +1 -1
  106. package/apps/web/dist/assets/{ReadOnly--4CIJCDD.js → ReadOnly-CXQ41R9Q.js} +1 -1
  107. package/apps/web/dist/assets/SettingsPage-C-8BgK9O.js +2 -0
  108. package/apps/web/dist/assets/{SetupPage-9Zk-KUGA.js → SetupPage-4_K083Wl.js} +1 -1
  109. package/apps/web/dist/assets/{SharePage-D_Ab0gjr.js → SharePage-CQjgMcDI.js} +1 -1
  110. package/apps/web/dist/assets/{SkillEditor-DvtameHg.js → SkillEditor-DT5hQwbg.js} +1 -1
  111. package/apps/web/dist/assets/{Skills-Cf1Kl4Fy.js → Skills-D7V_9_xo.js} +1 -1
  112. package/apps/web/dist/assets/SpacePage-D3rYS1bA.js +2 -0
  113. package/apps/web/dist/assets/{UpdateCheck-DweZBVP6.js → UpdateCheck-DVgAJmy8.js} +2 -2
  114. package/apps/web/dist/assets/changelog-DzQCUSsx.js +1 -0
  115. package/apps/web/dist/assets/{code-editor-B1RbFTAZ.js → code-editor-5T7ilBjd.js} +2 -2
  116. package/apps/web/dist/assets/{host-CKS5U5Vg.js → host-CCijW1hj.js} +6 -6
  117. package/apps/web/dist/assets/i18n-DCPDesT-.js +55 -0
  118. package/apps/web/dist/assets/{index-Ckcn5vy7.js → index-C_iWl8iS.js} +3 -3
  119. package/apps/web/dist/assets/index-zcPlodHx.css +1 -0
  120. package/apps/web/dist/assets/minus-BpYkOkYw.js +1 -0
  121. package/apps/web/dist/assets/{read-aloud-Bq88XUHC.js → read-aloud-Qb719not.js} +1 -1
  122. package/apps/web/dist/assets/{runners-DvYVe9Dt.js → runners-BeZ84YH_.js} +1 -1
  123. package/apps/web/dist/assets/{session-D2bjiA3P.js → session-CEJRkSP5.js} +1 -1
  124. package/apps/web/dist/assets/{theme-CNJIC2be.js → theme-y_owNosi.js} +1 -1
  125. package/apps/web/dist/assets/{ui-Mplfhz_Z.js → ui-BacfkQ7Q.js} +1 -1
  126. package/apps/web/dist/assets/{useMutation-8QRM-z4M.js → useMutation-CgzFr4qH.js} +1 -1
  127. package/apps/web/dist/assets/{viewers-CEocUV_2.js → viewers-CkyHAjnk.js} +2 -2
  128. package/apps/web/dist/index.html +12 -12
  129. package/apps/web/dist/mcp/flow.html +2 -2
  130. package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +7 -2
  131. package/node_modules/@engenty/wizards-shared/dist/bundles.d.ts +219 -0
  132. package/node_modules/@engenty/wizards-shared/dist/bundles.js +19 -0
  133. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +117 -4
  134. package/node_modules/@engenty/wizards-shared/dist/connectors.js +14 -0
  135. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +12 -0
  136. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +12 -0
  137. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +11 -0
  138. package/node_modules/@engenty/wizards-shared/dist/run.js +22 -0
  139. package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +84 -1
  140. package/node_modules/@engenty/wizards-shared/dist/rwx.js +69 -1
  141. package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +20 -3
  142. package/node_modules/@engenty/wizards-shared/dist/skills.js +5 -2
  143. package/node_modules/@engenty/wizards-shared/dist/spaces.d.ts +3 -2
  144. package/node_modules/@engenty/wizards-shared/dist/spaces.js +12 -3
  145. package/package.json +1 -1
  146. package/plugin/.claude-plugin/plugin.json +1 -1
  147. package/plugin/plugin.json +1 -1
  148. package/apps/web/dist/assets/CapabilitiesPage-DuJJV1ll.js +0 -2
  149. package/apps/web/dist/assets/EditorPage-EMFTHEYD.js +0 -3
  150. package/apps/web/dist/assets/PreviewPane-DSOV3o-1.js +0 -7
  151. package/apps/web/dist/assets/SettingsPage-z2u8lSe2.js +0 -2
  152. package/apps/web/dist/assets/SpacePage-CyqVzX9b.js +0 -2
  153. package/apps/web/dist/assets/changelog-C85v9OWg.js +0 -1
  154. package/apps/web/dist/assets/connection-sign-in-CaVvh5GQ.js +0 -1
  155. package/apps/web/dist/assets/i18n-Bymk5Ev-.js +0 -55
  156. package/apps/web/dist/assets/index-w-3J3ZJ9.css +0 -1
@@ -1,16 +1,22 @@
1
+ import { CONNECTION_ACTION_KINDS, } from "@engenty/wizards-shared/connectors";
1
2
  import { note } from "@engenty/wizards-shared/run";
2
- import { and, asc, eq } from "drizzle-orm";
3
+ import { and, asc, eq, inArray } from "drizzle-orm";
3
4
  import { z } from "zod";
5
+ import { logRuleChange } from "../broker/log.js";
4
6
  import { db, schema } from "../db/client.js";
5
7
  import { buildImportedConnector, mcpHeaders, } from "../engenty/connections-external/build-connector.js";
6
8
  import { ImportValidationError } from "../engenty/connections-external/errors.js";
7
9
  import { assembleRecord, connectorIdFromSlug, prepareSource, resolveRequiredHeaders, surfaceRequiresAuth, toolPrefixFromSlug, } from "../engenty/connections-external/import-service.js";
8
- import { groupOf } from "../engenty/connections-external/importer/classify.js";
10
+ import { groupIn, groupOf, recipientFieldIn, } from "../engenty/connections-external/importer/classify.js";
11
+ import { mapAuth, mapAuthFromRegistry, mapAuthFromSecuritySchemes, } from "../engenty/connections-external/importer/map-auth.js";
12
+ import { isUnauthorizedMcpError } from "../engenty/connections-external/invoke/mcp-client.js";
9
13
  import { createGuardedFetch } from "../engenty/connections-external/net/guarded-fetch.js";
10
14
  import { discoverImportableSources, discoverOAuthFacts, registryDiscover, registrySearch, resolveMcpTransport, } from "../engenty/connections-external/registry-client.js";
11
15
  import { resolveRegistrySource } from "../engenty/connections-external/registry-source.js";
12
16
  import { encryptToken } from "../engenty/shims/connections-sdk.js";
17
+ import { assertPublicHttpHost } from "../engenty/shims/web-ingest.js";
13
18
  import { env } from "../env.js";
19
+ import { managed } from "../manage.js";
14
20
  import { requireAdmin, requireWritableSpace } from "../services/access.js";
15
21
  import { ServiceError } from "../services/errors.js";
16
22
  import { BUILTIN_CONNECTORS, builtinConnector, missingSetup, usable } from "./builtin.js";
@@ -19,30 +25,105 @@ import { BUILTIN_CONNECTORS, builtinConnector, missingSetup, usable } from "./bu
19
25
  * found through the integrations registry or pasted as a URL. Searching, normalising, auth
20
26
  * mapping and invoking are engenty's (`apps/runtime/src/engenty/connections-external`); kept here is what
21
27
  * engenty leaves to its host — where the records live and who may import.
28
+ *
29
+ * A pasted address (docs/plans/capabilities-next.md, piece 1) is one the registry lists nothing
30
+ * at. Its sign-in is what the source describes itself or what the admin chooses, its id comes
31
+ * from its host, an admin says what each action does, and on a computer of one's own it may be a
32
+ * private address. The studio marks such a connector „nicht geprüft“.
22
33
  */
23
34
  // engenty's dynamic client registration reads the redirect from this variable.
24
35
  process.env.CONNECTIONS_REDIRECT_URI ??=
25
36
  env.connectRedirectUrl || `${env.appUrl}/api/connect/callback`;
26
37
  const where = (spaceId, id) => and(eq(schema.spaceConnector.spaceId, spaceId), eq(schema.spaceConnector.id, id));
38
+ async function loadRow(spaceId, id) {
39
+ return (await db.query.spaceConnector.findFirst({ where: where(spaceId, id) })) ?? null;
40
+ }
27
41
  async function load(spaceId, id) {
28
- const row = await db.query.spaceConnector.findFirst({ where: where(spaceId, id) });
29
- return row?.record ?? null;
42
+ return (await loadRow(spaceId, id))?.record ?? null;
30
43
  }
31
- async function save(spaceId, record) {
44
+ /** Keeps a record. `bundleId` is given once, when a plugin brings the connector (`bundles/`). */
45
+ async function save(spaceId, record, bundleId) {
32
46
  await db
33
47
  .insert(schema.spaceConnector)
34
- .values({ spaceId, id: record.id, record })
48
+ .values({ spaceId, id: record.id, record, ...(bundleId ? { bundleId } : {}) })
35
49
  .onConflictDoUpdate({
36
50
  target: [schema.spaceConnector.spaceId, schema.spaceConnector.id],
37
51
  set: { record, updatedAt: new Date() },
38
52
  });
39
53
  }
40
- const actionView = (a) => ({
41
- id: a.id,
42
- summary: (a.summary || a.description).slice(0, 160),
43
- group: groupOf(a),
44
- });
45
- function view(record) {
54
+ async function bundleRef(bundleId) {
55
+ if (!bundleId) {
56
+ return null;
57
+ }
58
+ const row = await db.query.spaceBundle.findFirst({
59
+ where: eq(schema.spaceBundle.id, bundleId),
60
+ columns: { id: true, name: true },
61
+ });
62
+ return row ?? null;
63
+ }
64
+ /** The properties a JSON schema of an object names. */
65
+ const propertiesOf = (schema) => {
66
+ const properties = schema?.properties;
67
+ return properties && typeof properties === "object" ? Object.keys(properties) : [];
68
+ };
69
+ /** An action's input fields: the top-level ones, and those of an HTTP body as `body.<name>`. */
70
+ function fieldsOf(action) {
71
+ const top = propertiesOf(action.input_json_schema);
72
+ if (action.invoke.kind !== "http") {
73
+ return top.slice(0, 60);
74
+ }
75
+ const body = propertiesOf(action.input_json_schema.properties?.body);
76
+ return [
77
+ ...top.filter((name) => name !== "body" || !body.length),
78
+ ...body.map((name) => `body.${name}`),
79
+ ].slice(0, 60);
80
+ }
81
+ /** An action as the studio lists it: what it does (an admin's word before the guess), its fields. */
82
+ const actionView = (record, a) => {
83
+ const recipientField = recipientFieldIn(record, a);
84
+ return {
85
+ id: a.id,
86
+ summary: (a.summary || a.description).slice(0, 160),
87
+ group: groupIn(record, a),
88
+ ...(recipientField ? { recipientField } : {}),
89
+ fields: fieldsOf(a),
90
+ };
91
+ };
92
+ /** Imported from a pasted address: the registry lists no surface behind it. */
93
+ const fromAddress = (record) => !record.registry_surface_slug;
94
+ /**
95
+ * Whether requests for a source may reach this computer and its private networks: a source from
96
+ * a pasted address, on a runtime that is a computer of one's own. It is asked at every request
97
+ * and kept nowhere, so the same record on a managed runtime stays behind the guard.
98
+ */
99
+ const reachesPrivate = (pasted) => pasted && !managed;
100
+ const hostOf = (sourceUrl) => new URL(sourceUrl).host;
101
+ /** Whether the guard refuses an address as one outside the public internet. */
102
+ async function isPrivateAddress(sourceUrl) {
103
+ try {
104
+ await assertPublicHttpHost(sourceUrl);
105
+ return false;
106
+ }
107
+ catch (err) {
108
+ return /not allowed for fetch|blocked IP/.test(err instanceof Error ? err.message : "");
109
+ }
110
+ }
111
+ /**
112
+ * The fetch a source's requests go through, and whether its address is a private one. A pasted
113
+ * private address is taken on a computer of one's own and refused in words on a managed runtime;
114
+ * everything else goes through the guard as it always did.
115
+ */
116
+ async function reachOf(sourceUrl, pasted) {
117
+ const privateAddress = pasted && (await isPrivateAddress(sourceUrl));
118
+ if (privateAddress && managed) {
119
+ throw new ServiceError("invalid", note("connectorPrivateAddress", { host: hostOf(sourceUrl) }));
120
+ }
121
+ return {
122
+ fetchImpl: createGuardedFetch(reachesPrivate(pasted) ? { allowPrivate: true } : {}),
123
+ privateAddress,
124
+ };
125
+ }
126
+ function view(record, bundle = null) {
46
127
  const auth = record.auth_config;
47
128
  const needsOAuthClient = auth.kind === "oauth2" && !record.client_id_enc && !(auth.dcr && auth.registration_endpoint);
48
129
  return {
@@ -57,7 +138,9 @@ function view(record) {
57
138
  auth: auth.kind,
58
139
  needsOAuthClient,
59
140
  toolsPending: record.source_kind === "mcp" && record.actions.length === 0,
60
- actions: record.actions.map(actionView),
141
+ fromAddress: fromAddress(record),
142
+ bundle,
143
+ actions: record.actions.map((a) => actionView(record, a)),
61
144
  importedAt: record.imported_at,
62
145
  refreshedAt: record.refreshed_at,
63
146
  };
@@ -67,17 +150,69 @@ function importFailure(err) {
67
150
  const message = err instanceof Error ? err.message : String(err);
68
151
  return new ServiceError(err instanceof ImportValidationError ? "invalid" : "refused", message);
69
152
  }
153
+ /** Headers a key never goes in: the request's own, and the MCP session's. */
154
+ const RESERVED_HEADERS = new Set([
155
+ "host",
156
+ "content-length",
157
+ "content-type",
158
+ "connection",
159
+ "transfer-encoding",
160
+ "accept",
161
+ "mcp-session-id",
162
+ "mcp-protocol-version",
163
+ ]);
164
+ /** An admin's choice for the sign-in of a pasted address (shared `SignInChoice`). */
165
+ export const signInChoiceSchema = z.discriminatedUnion("kind", [
166
+ z.object({ kind: z.literal("described") }),
167
+ z.object({
168
+ kind: z.literal("header"),
169
+ name: z
170
+ .string()
171
+ .regex(/^[A-Za-z][A-Za-z0-9-]{0,63}$/)
172
+ .refine((name) => !RESERVED_HEADERS.has(name.toLowerCase())),
173
+ /** What stands before the key: `Bearer`, `Token`. */
174
+ scheme: z
175
+ .string()
176
+ .regex(/^[A-Za-z][A-Za-z0-9-]{0,19}$/)
177
+ .optional(),
178
+ /** The key, to list an MCP server's tools now; it is kept nowhere. */
179
+ value: z
180
+ .string()
181
+ .min(1)
182
+ .max(2000)
183
+ .regex(/^[^\r\n]+$/)
184
+ .optional(),
185
+ }),
186
+ z.object({ kind: z.literal("none") }),
187
+ ]);
188
+ export const actionKindSchema = z.object({
189
+ kind: z.enum(CONNECTION_ACTION_KINDS),
190
+ recipientField: z.string().min(1).max(200).optional(),
191
+ });
192
+ /** What the studio sends to read an address: `sourceKind` left out, the runtime finds it. */
193
+ export const connectorPreviewSchema = z.object({
194
+ domain: z.string().min(1).max(253).optional(),
195
+ sourceKind: z.enum(["openapi", "mcp"]).optional(),
196
+ sourceUrl: z.string().url(),
197
+ signIn: signInChoiceSchema.optional(),
198
+ });
70
199
  /** What the studio, the architect and MCP clients send to import a connector. */
71
200
  export const connectorImportSchema = z.object({
72
- domain: z.string().min(1).max(253),
201
+ domain: z.string().min(1).max(253).optional(),
73
202
  sourceKind: z.enum(["openapi", "mcp"]),
74
203
  sourceUrl: z.string().url(),
75
- id: z.string().min(2).max(60),
76
- toolPrefix: z.string().min(2).max(31),
204
+ id: z.string().min(2).max(60).optional(),
205
+ toolPrefix: z.string().min(2).max(31).optional(),
77
206
  name: z.string().min(1).max(120).optional(),
78
207
  actions: z.array(z.string()).max(500).optional(),
79
208
  oauthClientId: z.string().max(500).optional(),
80
209
  oauthClientSecret: z.string().max(500).optional(),
210
+ signIn: signInChoiceSchema.optional(),
211
+ actionKinds: z.record(z.string().max(200), actionKindSchema).optional(),
212
+ });
213
+ /** What an admin says single actions do; `null` takes an action back to what the importer read. */
214
+ export const actionKindsPatchSchema = z.object({
215
+ actions: z.record(z.string().max(200), actionKindSchema.nullable()),
81
216
  });
82
217
  // --- the registry ----------------------------------------------------------------
83
218
  export async function searchRegistry(query) {
@@ -115,10 +250,11 @@ export async function registryService(domain) {
115
250
  /**
116
251
  * OAuth facts straight from an MCP server. The registry says "OAuth, see the server's well-known
117
252
  * document" for most MCP servers but probes only the service's main domain, so its own document
118
- * carries no endpoints for them. The server publishes them itself (RFC 9728, RFC 8414).
253
+ * carries no endpoints for them, and of a pasted address it knows nothing. The server publishes
254
+ * them itself: its protected-resource document (RFC 9728) names the authorization server, whose
255
+ * metadata (RFC 8414, or OpenID Connect's) names the endpoints.
119
256
  */
120
- async function probeOAuth(sourceUrl) {
121
- const guarded = createGuardedFetch();
257
+ async function probeOAuth(sourceUrl, guarded = createGuardedFetch()) {
122
258
  const json = async (url) => {
123
259
  const res = await guarded(url, {
124
260
  headers: { accept: "application/json" },
@@ -128,13 +264,38 @@ async function probeOAuth(sourceUrl) {
128
264
  ? (await res.json().catch(() => null))
129
265
  : null;
130
266
  };
131
- const origin = new URL(sourceUrl).origin;
132
- const resource = await json(`${origin}/.well-known/oauth-protected-resource`);
133
- const issuer = resource?.authorization_servers?.[0] ?? origin;
134
- const server = (await json(`${issuer.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`)) ??
135
- (await json(`${origin}/.well-known/oauth-authorization-server`));
267
+ const first = async (urls) => {
268
+ for (const url of [...new Set(urls)]) {
269
+ const found = await json(url);
270
+ if (found) {
271
+ return found;
272
+ }
273
+ }
274
+ return null;
275
+ };
136
276
  const text = (v) => (typeof v === "string" && v ? v : undefined);
137
277
  const list = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === "string") : []);
278
+ const { origin, pathname } = new URL(sourceUrl);
279
+ const path = pathname.replace(/\/+$/, "");
280
+ const resource = await first([
281
+ `${origin}/.well-known/oauth-protected-resource${path}`,
282
+ `${origin}/.well-known/oauth-protected-resource`,
283
+ ]);
284
+ const issuer = (text(list(resource?.authorization_servers)[0]) ?? origin).replace(/\/+$/, "");
285
+ let issuerUrl;
286
+ try {
287
+ issuerUrl = new URL(issuer);
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ const issuerPath = issuerUrl.pathname.replace(/\/+$/, "");
293
+ const server = await first([
294
+ `${issuer}/.well-known/oauth-authorization-server`,
295
+ `${issuerUrl.origin}/.well-known/oauth-authorization-server${issuerPath}`,
296
+ `${issuer}/.well-known/openid-configuration`,
297
+ `${origin}/.well-known/oauth-authorization-server`,
298
+ ]);
138
299
  const authorizationEndpoint = text(server?.authorization_endpoint);
139
300
  const tokenEndpoint = text(server?.token_endpoint);
140
301
  if (!(authorizationEndpoint && tokenEndpoint)) {
@@ -151,17 +312,76 @@ async function probeOAuth(sourceUrl) {
151
312
  ...(registrationEndpoint ? { registrationEndpoint, dcr: true } : {}),
152
313
  };
153
314
  }
154
- /** Fetch and normalise a source with the facts the registry holds about it. */
315
+ /** OAuth facts a server published as the sign-in the connector keeps; null where they are no authorization-code flow. */
316
+ function oauthSignIn(oauth) {
317
+ if (!(oauth.authorizationEndpoint && oauth.tokenEndpoint) ||
318
+ (oauth.grantTypes.length > 0 && !oauth.grantTypes.includes("authorization_code"))) {
319
+ return null;
320
+ }
321
+ const registration = oauth.dcr === true ? oauth.registrationEndpoint?.trim() : undefined;
322
+ return {
323
+ kind: "oauth2",
324
+ auth_url: oauth.authorizationEndpoint,
325
+ token_url: oauth.tokenEndpoint,
326
+ scopes: oauth.scopes,
327
+ ...(registration ? { dcr: true, registration_endpoint: registration } : {}),
328
+ };
329
+ }
330
+ /** A key or token in a header, as an admin chose it: the connection asks for the key. */
331
+ function headerSignIn(choice) {
332
+ const scheme = choice.scheme?.trim();
333
+ return {
334
+ kind: "api_key",
335
+ fields: [{ key: "api_key", label: "API key", required: true, secret: true }],
336
+ placement: {
337
+ in: "header",
338
+ name: choice.name,
339
+ value_template: scheme ? `${scheme} {{api_key}}` : "{{api_key}}",
340
+ },
341
+ };
342
+ }
343
+ /**
344
+ * The sign-in a connector from a pasted address keeps: the admin's choice of a header or none
345
+ * first, what the source describes else. A source that asks for a sign-in and describes none
346
+ * needs the choice, and says so.
347
+ */
348
+ function signInFor(sourceUrl, described, choice) {
349
+ if (choice?.kind === "none") {
350
+ return { kind: "none" };
351
+ }
352
+ if (choice?.kind === "header") {
353
+ return headerSignIn(choice);
354
+ }
355
+ if (!described) {
356
+ throw new ServiceError("invalid", note("connectorSignInUnknown", { host: hostOf(sourceUrl) }));
357
+ }
358
+ return described;
359
+ }
360
+ function describedView(auth) {
361
+ return {
362
+ described: auth?.kind ?? null,
363
+ needsOAuthClient: auth?.kind === "oauth2" && !(auth.dcr && auth.registration_endpoint),
364
+ keyIn: auth?.kind === "api_key" ? auth.placement.name : null,
365
+ };
366
+ }
367
+ /**
368
+ * Fetch and normalise a source. One the registry lists comes with the registry's facts. A pasted
369
+ * address has none: an MCP server is asked for its tools without a sign-in, and where it wants
370
+ * one, for its own OAuth documents; an OpenAPI description says it in its security schemes.
371
+ */
155
372
  async function prepare(input) {
156
373
  const resolved = input.domain
157
374
  ? await resolveRegistrySource({ domain: input.domain, sourceUrl: input.sourceUrl })
158
375
  : { discover: null, surface: null };
159
376
  const { surface } = resolved;
377
+ const pasted = !surface;
378
+ const { fetchImpl, privateAddress } = await reachOf(input.sourceUrl, pasted);
160
379
  if (input.sourceKind === "mcp" &&
380
+ surface &&
161
381
  resolved.discover &&
162
382
  surfaceRequiresAuth(surface) &&
163
383
  !discoverOAuthFacts(resolved.discover.parsed)) {
164
- const oauth = await probeOAuth(input.sourceUrl);
384
+ const oauth = await probeOAuth(input.sourceUrl, fetchImpl);
165
385
  if (oauth) {
166
386
  const parsed = resolved.discover.parsed;
167
387
  resolved.discover.parsed = {
@@ -185,27 +405,190 @@ async function prepare(input) {
185
405
  blockers.push(`unsupported MCP transport (${surface.transports.join(", ")})`);
186
406
  }
187
407
  }
188
- const prepared = await prepareSource({
189
- deferMcpTools: input.sourceKind === "mcp" && surfaceRequiresAuth(surface),
190
- requiredHeaders: !blockers.length && surface ? resolveRequiredHeaders(surface) : [],
408
+ const source = {
409
+ fetchImpl,
410
+ requiredHeaders: !blockers.length && surface ? resolveRequiredHeaders(surface) : (input.headers ?? []),
191
411
  sourceKind: input.sourceKind,
192
412
  sourceUrl: input.sourceUrl,
193
413
  specOverrides: surface?.spec_overrides ?? [],
194
414
  transport: surface ? resolveMcpTransport(surface) : null,
415
+ };
416
+ let prepared = await prepareSource({
417
+ ...source,
418
+ deferMcpTools: input.sourceKind === "mcp" && surfaceRequiresAuth(surface),
195
419
  });
196
- return { ...resolved, prepared, blockers };
420
+ if (surface) {
421
+ const mapped = mapAuth({
422
+ discover: resolved.discover?.parsed ?? null,
423
+ securitySchemes: prepared.normalized.security_schemes,
424
+ sourceKind: input.sourceKind,
425
+ surface,
426
+ });
427
+ return {
428
+ ...resolved,
429
+ prepared,
430
+ blockers,
431
+ pasted,
432
+ privateAddress,
433
+ described: mapped.ok ? mapped.auth : null,
434
+ };
435
+ }
436
+ let described;
437
+ if (input.sourceKind === "openapi") {
438
+ const schemes = prepared.normalized.security_schemes;
439
+ described =
440
+ schemes && Object.keys(schemes).length
441
+ ? mapAuthFromSecuritySchemes(schemes)
442
+ : { kind: "none" };
443
+ }
444
+ else if (prepared.deferred_mcp_tools) {
445
+ // It wants a sign-in: what it describes itself, then what the registry knows of its domain.
446
+ const oauth = await probeOAuth(input.sourceUrl, fetchImpl);
447
+ described =
448
+ (oauth ? oauthSignIn(oauth) : null) ??
449
+ (resolved.discover ? mapAuthFromRegistry(resolved.discover.parsed) : null);
450
+ const { signIn } = input;
451
+ if (signIn?.kind === "header" && signIn.value) {
452
+ // The key the admin typed lists the tools now. A key the server refuses is said in words.
453
+ const value = signIn.scheme ? `${signIn.scheme.trim()} ${signIn.value}` : signIn.value;
454
+ prepared = await prepareSource({
455
+ ...source,
456
+ deferOnUnauthorized: false,
457
+ mcpHeaders: { [signIn.name]: value },
458
+ }).catch((err) => {
459
+ throw isUnauthorizedMcpError(err)
460
+ ? new ServiceError("invalid", note("connectorKeyRefused", { host: hostOf(input.sourceUrl) }))
461
+ : err;
462
+ });
463
+ }
464
+ }
465
+ else {
466
+ // Its tools list answered without a sign-in: it needs none.
467
+ described = { kind: "none" };
468
+ }
469
+ return { ...resolved, prepared, blockers, pasted, privateAddress, described };
197
470
  }
198
- export async function previewSource(input) {
199
- const { prepared, blockers } = await prepare(input).catch((err) => {
200
- throw importFailure(err);
201
- });
202
- return {
203
- title: prepared.normalized.title,
204
- actions: prepared.normalized.actions.map(actionView),
205
- blockers,
206
- dropped: prepared.normalized.dropped_count,
207
- toolsPending: prepared.deferred_mcp_tools === true,
208
- };
471
+ /** A two-letter country ending's second level: `co.uk`, `com.au`, `or.at`. */
472
+ const SECOND_LEVELS = new Set(["co", "com", "org", "net", "ac", "gv", "or", "gov", "edu"]);
473
+ /**
474
+ * The id and tool prefix a pasted address suggests: its host without `www`, `mcp` or `api` in
475
+ * front and without its ending (`crm.example.at` → `crm-example`, `mcp.linear.app` → `linear`).
476
+ * A bare address or a name that is no id gets `server` in front.
477
+ */
478
+ export function namesFromHost(host) {
479
+ // `[::1]:9000` is an IPv6 address with a port; everything else ends in its port.
480
+ const v6 = /^\[(.+)\]/.exec(host);
481
+ const name = (v6 ? v6[1] : host.replace(/:\d+$/, "")).toLowerCase();
482
+ let labels = name.split(".").filter(Boolean);
483
+ const address = name.includes(":") || labels.every((l) => /^\d+$/.test(l));
484
+ if (!address) {
485
+ if (labels.length > 2 && ["www", "mcp", "api"].includes(labels[0])) {
486
+ labels = labels.slice(1);
487
+ }
488
+ if (labels.length > 1) {
489
+ const end = labels.at(-1);
490
+ const second = labels.at(-2);
491
+ labels = labels.slice(0, labels.length > 2 && end.length === 2 && SECOND_LEVELS.has(second) ? -2 : -1);
492
+ }
493
+ }
494
+ const slug = connectorIdFromSlug(address ? `server-${name}` : labels.join("-"));
495
+ const id = /^[a-z][a-z0-9-]{1,59}$/.test(slug)
496
+ ? slug
497
+ : connectorIdFromSlug(`server-${slug}`) || "server";
498
+ return { id, toolPrefix: toolPrefixFromSlug(id) };
499
+ }
500
+ /** A suggested id and tool prefix no connector of the space has yet: `crm`, then `crm-2`. */
501
+ export async function freeNames(spaceId, suggested) {
502
+ const taken = await listConnectors(spaceId);
503
+ for (let n = 1; n < 50; n++) {
504
+ const tail = n === 1 ? "" : `${n}`;
505
+ const id = tail ? `${suggested.id.slice(0, 57)}-${tail}` : suggested.id;
506
+ const toolPrefix = tail ? `${suggested.toolPrefix.slice(0, 27)}_${tail}` : suggested.toolPrefix;
507
+ if (!taken.some((c) => c.id === id || c.toolPrefix === toolPrefix)) {
508
+ return { id, toolPrefix };
509
+ }
510
+ }
511
+ return suggested;
512
+ }
513
+ /** Which kind an address is tried as first: a file that names itself a description, else an MCP server. */
514
+ const kindsToTry = (sourceUrl) => /\.(json|ya?ml)$|openapi|swagger/i.test(new URL(sourceUrl).pathname)
515
+ ? ["openapi", "mcp"]
516
+ : ["mcp", "openapi"];
517
+ /**
518
+ * Reads an address before anything is imported: what answers there (an MCP server or an OpenAPI
519
+ * description), its actions with what each was read as, how it signs in, and the names its host
520
+ * suggests. For admins of a space that can be changed here.
521
+ */
522
+ export async function previewSource(spaceId, input) {
523
+ await requireWritableSpace(spaceId);
524
+ await requireAdmin();
525
+ let failed;
526
+ for (const sourceKind of input.sourceKind ? [input.sourceKind] : kindsToTry(input.sourceUrl)) {
527
+ let found;
528
+ try {
529
+ found = await prepare({ ...input, sourceKind });
530
+ }
531
+ catch (err) {
532
+ // What is the same for either kind: a private address in the cloud, a key refused.
533
+ if (err instanceof ServiceError) {
534
+ throw err;
535
+ }
536
+ failed ??= err;
537
+ continue;
538
+ }
539
+ const { prepared, surface } = found;
540
+ const host = hostOf(input.sourceUrl);
541
+ const names = await freeNames(spaceId, surface
542
+ ? { id: connectorIdFromSlug(surface.slug), toolPrefix: toolPrefixFromSlug(surface.slug) }
543
+ : namesFromHost(host));
544
+ return {
545
+ sourceKind,
546
+ host,
547
+ suggestedId: names.id,
548
+ suggestedToolPrefix: names.toolPrefix,
549
+ title: prepared.normalized.title ?? surface?.name ?? null,
550
+ actions: prepared.normalized.actions.map((a) => actionView({}, a)),
551
+ blockers: found.blockers,
552
+ dropped: prepared.normalized.dropped_count,
553
+ toolsPending: prepared.deferred_mcp_tools === true,
554
+ signIn: describedView(found.described),
555
+ fromAddress: found.pasted,
556
+ privateAddress: found.privateAddress,
557
+ };
558
+ }
559
+ if (input.sourceKind) {
560
+ throw importFailure(failed);
561
+ }
562
+ throw new ServiceError("invalid", note("connectorAddressNotRead", {
563
+ host: hostOf(input.sourceUrl),
564
+ detail: (failed instanceof Error ? failed.message : String(failed)).slice(0, 300),
565
+ }));
566
+ }
567
+ /**
568
+ * What an admin says single actions do, checked against the actions: an action that is not
569
+ * there is an error (`strict`) or left out, a recipient's field must be one of the action's.
570
+ */
571
+ function checkedKinds(record, choices, strict) {
572
+ const kinds = {};
573
+ for (const [id, choice] of Object.entries(choices)) {
574
+ const action = record.actions.find((a) => a.id === id);
575
+ if (!action) {
576
+ if (strict) {
577
+ throw new ServiceError("invalid", note("connectorNoAction", { name: record.name, id }));
578
+ }
579
+ continue;
580
+ }
581
+ const field = choice.kind === "send" ? choice.recipientField?.trim() : undefined;
582
+ const fields = fieldsOf(action);
583
+ if (field && fields.length && !fields.some((f) => field === f || field.startsWith(`${f}.`))) {
584
+ throw new ServiceError("invalid", note("connectorNoRecipientField", { id, field }));
585
+ }
586
+ // What the importer read anyway is not kept: a better guess later still applies.
587
+ if (field || choice.kind !== groupOf(action)) {
588
+ kinds[id] = { kind: choice.kind, ...(field ? { recipient_field: field } : {}) };
589
+ }
590
+ }
591
+ return kinds;
209
592
  }
210
593
  // --- a space's connectors --------------------------------------------------------
211
594
  async function builtinView(connector) {
@@ -222,6 +605,8 @@ async function builtinView(connector) {
222
605
  missingSetup: ready ? null : missingSetup(connector),
223
606
  needsOAuthClient: false,
224
607
  toolsPending: false,
608
+ fromAddress: false,
609
+ bundle: null,
225
610
  actions: connector.actions.map((a) => ({
226
611
  id: a.id,
227
612
  summary: a.summary.slice(0, 160),
@@ -237,9 +622,16 @@ export async function listConnectors(spaceId) {
237
622
  where: eq(schema.spaceConnector.spaceId, spaceId),
238
623
  orderBy: [asc(schema.spaceConnector.createdAt)],
239
624
  });
625
+ const bundleIds = [...new Set(rows.flatMap((r) => (r.bundleId ? [r.bundleId] : [])))];
626
+ const bundles = bundleIds.length
627
+ ? await db
628
+ .select({ id: schema.spaceBundle.id, name: schema.spaceBundle.name })
629
+ .from(schema.spaceBundle)
630
+ .where(inArray(schema.spaceBundle.id, bundleIds))
631
+ : [];
240
632
  return [
241
633
  ...(await Promise.all(BUILTIN_CONNECTORS.map(builtinView))),
242
- ...rows.map((r) => view(r.record)),
634
+ ...rows.map((r) => view(r.record, bundles.find((b) => b.id === r.bundleId) ?? null)),
243
635
  ];
244
636
  }
245
637
  /**
@@ -252,6 +644,8 @@ export async function resolveConnector(spaceId, id) {
252
644
  return {
253
645
  connector: builtin,
254
646
  imported: false,
647
+ fromAddress: false,
648
+ bundleId: null,
255
649
  inputSchema: (actionId) => {
256
650
  const action = builtin.actions.find((a) => a.id === actionId);
257
651
  try {
@@ -268,25 +662,44 @@ export async function resolveConnector(spaceId, id) {
268
662
  ? {
269
663
  connector: found.connector,
270
664
  imported: true,
665
+ fromAddress: fromAddress(found.record),
666
+ bundleId: found.bundleId,
271
667
  inputSchema: (actionId) => found.record.actions.find((a) => a.id === actionId)?.input_json_schema ?? {},
272
668
  }
273
669
  : null;
274
670
  }
275
- export async function importConnector(userId, spaceId, input) {
671
+ export async function importConnector(userId, spaceId, input,
672
+ /** A plugin brings it (`bundles/`): the record it belongs to, and the headers it sets. */
673
+ from) {
276
674
  await requireWritableSpace(spaceId);
277
675
  await requireAdmin();
278
- if (await load(spaceId, input.id)) {
279
- throw new ServiceError("invalid", note("connectorAlreadyExistsSpace", { id: input.id }));
676
+ // A pasted address names itself: its host is the domain and suggests the id and the prefix.
677
+ const host = hostOf(input.sourceUrl);
678
+ const suggested = namesFromHost(host);
679
+ const id = input.id ?? suggested.id;
680
+ const toolPrefix = input.toolPrefix ?? suggested.toolPrefix;
681
+ if (await load(spaceId, id)) {
682
+ throw new ServiceError("invalid", note("connectorAlreadyExistsSpace", { id }));
280
683
  }
281
684
  try {
282
- const { discover, surface, prepared } = await prepare(input);
283
- const { record, warnings } = assembleRecord({
685
+ const { discover, surface, prepared, pasted, described } = await prepare({
686
+ ...input,
687
+ ...(from ? { headers: from.headers } : {}),
688
+ });
689
+ const name = input.name ?? null;
690
+ const { record: assembled, warnings } = assembleRecord({
284
691
  actionFilter: input.actions ?? null,
692
+ actionKinds: input.actionKinds
693
+ ? checkedKinds({ actions: prepared.normalized.actions, name: name ?? host }, input.actionKinds, false)
694
+ : null,
695
+ // The registry knows nothing of a pasted address: its sign-in is what it describes itself
696
+ // or what the admin chose.
697
+ auth: pasted ? signInFor(input.sourceUrl, described, input.signIn) : null,
285
698
  discover: discover?.parsed ?? null,
286
- domain: input.domain,
287
- id: input.id,
699
+ domain: input.domain ?? new URL(input.sourceUrl).hostname,
700
+ id,
288
701
  importedBy: userId,
289
- name: input.name ?? null,
702
+ name,
290
703
  oauthClient: input.oauthClientId && input.oauthClientSecret
291
704
  ? { clientId: input.oauthClientId, clientSecret: input.oauthClientSecret }
292
705
  : null,
@@ -297,14 +710,16 @@ export async function importConnector(userId, spaceId, input) {
297
710
  sourceUrl: input.sourceUrl,
298
711
  surface,
299
712
  tenantId: spaceId,
300
- toolPrefix: input.toolPrefix,
713
+ toolPrefix,
301
714
  });
715
+ // The registry's headers come with its surface; a plugin's own are kept the same way.
716
+ const record = pasted && from?.headers.length ? { ...assembled, required_headers: from.headers } : assembled;
302
717
  const { skippedActions } = buildImportedConnector(record);
303
718
  if (skippedActions.length) {
304
719
  warnings.push(`${skippedActions.length} action(s) have an input the tools cannot express`);
305
720
  }
306
- await save(spaceId, record);
307
- return { connector: view(record), warnings };
721
+ await save(spaceId, record, from?.bundleId);
722
+ return { connector: view(record, await bundleRef(from?.bundleId ?? null)), warnings };
308
723
  }
309
724
  catch (err) {
310
725
  throw err instanceof ServiceError ? err : importFailure(err);
@@ -346,8 +761,10 @@ export async function removeConnector(spaceId, id) {
346
761
  await db.delete(schema.spaceConnector).where(where(spaceId, id));
347
762
  }
348
763
  /**
349
- * Re-reads the source and replaces the connector's actions. An MCP server that only lists its
350
- * tools to a signed-in account needs that account's token.
764
+ * Re-reads the source and replaces the connector's actions; what an admin said single actions do
765
+ * stays. An MCP server that only lists its tools to a signed-in account needs that account's
766
+ * token: a run passes the one it calls with, the studio's „Aktionen neu laden“ the one of a
767
+ * signed-in connection (`reload.ts`, which asks for an admin).
351
768
  */
352
769
  export async function refreshConnector(spaceId, id, accessToken) {
353
770
  await requireWritableSpace(spaceId);
@@ -359,6 +776,7 @@ export async function refreshConnector(spaceId, id, accessToken) {
359
776
  const { surface } = record.registry_surface_slug
360
777
  ? await resolveRegistrySource({ domain: record.domain, sourceUrl: record.source_url })
361
778
  : { surface: null };
779
+ const { fetchImpl } = await reachOf(record.source_url, fromAddress(record));
362
780
  const requiredHeaders = surface ? resolveRequiredHeaders(surface) : record.required_headers;
363
781
  const transport = record.source_kind === "mcp"
364
782
  ? ((surface ? resolveMcpTransport(surface) : null) ??
@@ -367,6 +785,7 @@ export async function refreshConnector(spaceId, id, accessToken) {
367
785
  : null;
368
786
  const prepared = await prepareSource({
369
787
  deferOnUnauthorized: false,
788
+ fetchImpl,
370
789
  mcpHeaders: accessToken ? mcpHeaders(record, accessToken) : undefined,
371
790
  requiredHeaders,
372
791
  sourceKind: record.source_kind,
@@ -384,18 +803,70 @@ export async function refreshConnector(spaceId, id, accessToken) {
384
803
  spec_hash: prepared.spec_hash,
385
804
  };
386
805
  await save(spaceId, updated);
387
- return view(updated);
806
+ return (await importedView(spaceId, id)) ?? view(updated);
388
807
  }
389
808
  catch (err) {
390
- throw importFailure(err);
809
+ throw err instanceof ServiceError ? err : importFailure(err);
391
810
  }
392
811
  }
393
- /** The connector as engenty's framework runs it: actions with handlers, auth with its flows. */
394
- export async function importedConnector(spaceId, id) {
812
+ /** A connector the space imported, as the studio shows it; null where there is none. */
813
+ export async function importedView(spaceId, id) {
814
+ const row = await loadRow(spaceId, id);
815
+ return row ? view(row.record, await bundleRef(row.bundleId)) : null;
816
+ }
817
+ /**
818
+ * An admin says what single actions of an imported connector do: read, write, delete or send,
819
+ * and for a send the input field that holds the recipient. The broker decides by it from the
820
+ * next call on, so every connection on the connector hears of a changed kind like a changed rule.
821
+ */
822
+ export async function setActionKinds(userId, spaceId, id, choices) {
823
+ await requireWritableSpace(spaceId);
824
+ await requireAdmin();
395
825
  const record = await load(spaceId, id);
396
826
  if (!record) {
827
+ throw new ServiceError("not_found", note("connectorNotExist"));
828
+ }
829
+ const set = Object.fromEntries(Object.entries(choices).filter((entry) => !!entry[1]));
830
+ const said = checkedKinds(record, set, true);
831
+ const kinds = { ...record.action_kinds };
832
+ for (const actionId of Object.keys(choices)) {
833
+ if (said[actionId]) {
834
+ kinds[actionId] = said[actionId];
835
+ }
836
+ else {
837
+ // Taken back, or said as the importer read it anyway: the guess applies again.
838
+ delete kinds[actionId];
839
+ }
840
+ }
841
+ const updated = { ...record, action_kinds: kinds };
842
+ const changed = record.actions
843
+ .filter((a) => groupIn(record, a) !== groupIn(updated, a))
844
+ .map((a) => `${a.id}: ${groupIn(record, a)} → ${groupIn(updated, a)}`);
845
+ await save(spaceId, updated);
846
+ if (changed.length) {
847
+ const connections = await db.query.spaceConnection.findMany({
848
+ where: and(eq(schema.spaceConnection.spaceId, spaceId), eq(schema.spaceConnection.connectorId, id)),
849
+ columns: { id: true },
850
+ });
851
+ for (const connection of connections) {
852
+ await logRuleChange({
853
+ userId,
854
+ spaceId,
855
+ connectionId: connection.id,
856
+ summary: { kinds: changed.join(", ") },
857
+ reason: `What ${record.name}'s actions do was changed: ${changed.join(", ")}.`,
858
+ });
859
+ }
860
+ }
861
+ return (await importedView(spaceId, id)) ?? view(updated);
862
+ }
863
+ /** The connector as engenty's framework runs it: actions with handlers, auth with its flows. */
864
+ export async function importedConnector(spaceId, id) {
865
+ const row = await loadRow(spaceId, id);
866
+ if (!row) {
397
867
  return null;
398
868
  }
869
+ const { record } = row;
399
870
  // The record is read at call time, so a client registered a moment ago is the one used.
400
871
  let current = record;
401
872
  const { connector } = buildImportedConnector(record, () => current, async (client) => {
@@ -405,6 +876,6 @@ export async function importedConnector(spaceId, id) {
405
876
  client_secret_enc: client.clientSecret ? encryptToken(client.clientSecret) : null,
406
877
  };
407
878
  await save(spaceId, current);
408
- });
409
- return { connector, record };
879
+ }, { allowPrivate: reachesPrivate(fromAddress(record)) });
880
+ return { connector, record, bundleId: row.bundleId };
410
881
  }