-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathplugin.ts
More file actions
418 lines (379 loc) · 14.8 KB
/
Copy pathplugin.ts
File metadata and controls
418 lines (379 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import { Effect } from "effect";
import type { Layer } from "effect";
import { HttpClient } from "effect/unstable/http";
import {
IntegrationAlreadyExistsError,
IntegrationDetectionResult,
IntegrationNotFoundError,
IntegrationSlug,
definePlugin,
mergeAuthTemplates,
sha256Hex,
type AuthMethodDescriptor,
type Integration,
type IntegrationConfig,
type IntegrationRecord,
type PluginCtx,
type StorageFailure,
} from "@executor-js/sdk/core";
import { describeApiKeyAuthMethod } from "@executor-js/sdk/http-auth";
import {
checkHealthOpenApi,
compileAndPersistOpenApiSpecStreaming,
describeHealthCheckOpenApi,
listHealthCheckCandidatesOpenApi,
setHealthCheckOpenApi,
decodeOpenApiIntegrationConfig,
invokeOpenApiBackedTool,
makeDefaultOpenapiStore,
normalizeOpenApiAuthInputs,
OpenApiExtractionError,
resolveOpenApiBackedAnnotations,
resolveOpenApiBackedTools,
type Authentication,
type AuthenticationInput,
type OpenApiPersistResult,
type OpenapiStore,
} from "@executor-js/plugin-openapi";
import {
buildMicrosoftGraphOpenApiSpec,
decodeMicrosoftGraphIntegrationConfig,
microsoftGraphKeepPathItem,
type MicrosoftGraphUrlPolicy,
type MicrosoftGraphIntegrationConfig,
type MicrosoftGraphSpecBuild,
} from "./graph";
import {
MICROSOFT_CLIENT_CREDENTIALS_AUTH_TEMPLATE_SLUG,
MICROSOFT_GRAPH_BASE_URL,
microsoftGraphPreset,
} from "./presets";
export interface MicrosoftGraphConfig {
readonly presetIds?: readonly string[];
readonly customScopes?: readonly string[];
readonly slug?: string;
readonly name?: string;
readonly description?: string;
readonly baseUrl?: string;
readonly specUrl?: string;
readonly authorizationUrl?: string;
readonly tokenUrl?: string;
readonly clientCredentialsTokenUrl?: string;
}
export interface MicrosoftConfigureInput {
readonly authenticationTemplate: readonly AuthenticationInput[];
readonly mode?: "merge" | "replace";
}
export interface MicrosoftUpdateInput {
readonly presetIds?: readonly string[];
readonly customScopes?: readonly string[];
readonly baseUrl?: string;
readonly specUrl?: string;
readonly authorizationUrl?: string;
readonly tokenUrl?: string;
readonly clientCredentialsTokenUrl?: string;
}
export interface MicrosoftUpdateResult {
readonly slug: IntegrationSlug;
readonly toolCount: number;
readonly addedTools: readonly string[];
readonly removedTools: readonly string[];
}
export interface MicrosoftPluginOptions {
readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient, never, never>;
readonly allowUnsafeUrlOverrides?: boolean;
}
const DEFAULT_MICROSOFT_SLUG = "microsoft_graph";
const describeMicrosoftAuthMethods = (
record: IntegrationRecord,
): readonly AuthMethodDescriptor[] => {
const config = decodeOpenApiIntegrationConfig(record.config);
if (!config) return [];
return (config.authenticationTemplate ?? []).map(
(template: Authentication): AuthMethodDescriptor => {
if (template.kind === "oauth2") {
const machineFlow =
String(template.slug) === MICROSOFT_CLIENT_CREDENTIALS_AUTH_TEMPLATE_SLUG;
return {
id: String(template.slug),
label: machineFlow ? "Microsoft OAuth (client credentials)" : "Microsoft OAuth",
kind: "oauth",
template: String(template.slug),
oauth: {
authorizationUrl: template.authorizationUrl,
tokenUrl: template.tokenUrl,
scopes: template.scopes,
},
};
}
return describeApiKeyAuthMethod(template);
},
);
};
const describeMicrosoftIntegrationDisplay = (
record: IntegrationRecord,
): { readonly url?: string } => {
const config = decodeMicrosoftGraphIntegrationConfig(record.config);
return { url: config?.baseUrl ?? MICROSOFT_GRAPH_BASE_URL };
};
const makeMicrosoftPluginExtension = (
ctx: PluginCtx<OpenapiStore>,
httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,
urlPolicy?: MicrosoftGraphUrlPolicy,
) => {
const persistGraphOperations = (
graph: MicrosoftGraphSpecBuild,
integration: string,
specHash: string,
): Effect.Effect<OpenApiPersistResult, OpenApiExtractionError | StorageFailure> =>
// Stream the (full 37MB) source straight to persisted bindings + a
// content-addressed defs blob, never materializing the whole-document tree
// that OOMs the 128MB Workers isolate. `keepPathItem` applies the Microsoft
// Graph scope selection per path-item during the stream; a full-graph
// selection returns `undefined` (keep everything).
compileAndPersistOpenApiSpecStreaming({
specText: graph.specText,
integration,
storage: ctx.storage,
specHash,
keepPathItem: microsoftGraphKeepPathItem(graph),
});
const addGraph = (config: MicrosoftGraphConfig) =>
Effect.gen(function* () {
const graph = yield* buildMicrosoftGraphOpenApiSpec(config, httpClientLayer, urlPolicy);
const slug = IntegrationSlug.make(config.slug?.trim() || DEFAULT_MICROSOFT_SLUG);
const existing = yield* ctx.core.integrations.get(slug);
if (existing) {
return yield* new IntegrationAlreadyExistsError({ slug });
}
const specHash = yield* sha256Hex(graph.specText);
const integrationConfig: MicrosoftGraphIntegrationConfig = {
specHash,
sourceUrl: graph.specUrl,
microsoftGraphPresetIds: graph.presetIds,
microsoftGraphCustomScopes: graph.customScopes,
microsoftGraphScopes: graph.scopes,
microsoftGraphExactPaths: graph.exactPaths,
microsoftGraphPathPrefixes: graph.pathPrefixes,
microsoftGraphTagPrefixes: graph.tagPrefixes,
microsoftGraphCoversFullGraph: graph.coversFullGraph,
microsoftGraphAuthorizationUrl: graph.authorizationUrl,
microsoftGraphTokenUrl: graph.tokenUrl,
microsoftGraphClientCredentialsTokenUrl: graph.clientCredentialsTokenUrl,
authenticationTemplate: graph.authenticationTemplate,
...(config.baseUrl ? { baseUrl: config.baseUrl } : {}),
};
yield* ctx.storage.putSpec(specHash, graph.specText);
const persisted = yield* ctx.transaction(
Effect.gen(function* () {
yield* ctx.core.integrations.register({
slug,
name: config.name?.trim() || "Microsoft Graph",
description: config.description ?? "Selected Microsoft Graph workloads.",
config:
integrationConfig satisfies MicrosoftGraphIntegrationConfig as IntegrationConfig,
canRemove: true,
canRefresh: true,
});
return yield* persistGraphOperations(graph, String(slug), specHash);
}),
);
return { slug, toolCount: persisted.toolCount };
});
const updateGraph = (rawSlug: string, input?: MicrosoftUpdateInput) =>
Effect.gen(function* () {
const slug = IntegrationSlug.make(rawSlug);
const record = yield* ctx.core.integrations.get(slug);
const current = record ? decodeMicrosoftGraphIntegrationConfig(record.config) : null;
if (!record || !current) {
return yield* new IntegrationNotFoundError({ slug });
}
const graph = yield* buildMicrosoftGraphOpenApiSpec(
{
presetIds: input?.presetIds ?? current.microsoftGraphPresetIds,
customScopes: input?.customScopes ?? current.microsoftGraphCustomScopes,
baseUrl: input?.baseUrl ?? current.baseUrl,
specUrl: input?.specUrl ?? current.sourceUrl,
authorizationUrl: input?.authorizationUrl ?? current.microsoftGraphAuthorizationUrl,
tokenUrl: input?.tokenUrl ?? current.microsoftGraphTokenUrl,
clientCredentialsTokenUrl:
input?.clientCredentialsTokenUrl ?? current.microsoftGraphClientCredentialsTokenUrl,
},
httpClientLayer,
urlPolicy,
);
const previousOperations = yield* ctx.storage.listOperations(rawSlug);
const previousNames = new Set(previousOperations.map((op) => op.toolName));
const specHash = yield* sha256Hex(graph.specText);
yield* ctx.storage.putSpec(specHash, graph.specText);
const nextConfig: MicrosoftGraphIntegrationConfig = {
...current,
specHash,
sourceUrl: graph.specUrl,
microsoftGraphPresetIds: graph.presetIds,
microsoftGraphCustomScopes: graph.customScopes,
microsoftGraphScopes: graph.scopes,
microsoftGraphExactPaths: graph.exactPaths,
microsoftGraphPathPrefixes: graph.pathPrefixes,
microsoftGraphTagPrefixes: graph.tagPrefixes,
microsoftGraphCoversFullGraph: graph.coversFullGraph,
microsoftGraphAuthorizationUrl: graph.authorizationUrl,
microsoftGraphTokenUrl: graph.tokenUrl,
microsoftGraphClientCredentialsTokenUrl: graph.clientCredentialsTokenUrl,
authenticationTemplate: graph.authenticationTemplate,
...(input?.baseUrl ? { baseUrl: input.baseUrl } : {}),
};
const persisted = yield* ctx.transaction(
Effect.gen(function* () {
yield* ctx.core.integrations.update(slug, {
config: nextConfig satisfies MicrosoftGraphIntegrationConfig as IntegrationConfig,
});
return yield* persistGraphOperations(graph, rawSlug, specHash);
}),
);
const nextNames = new Set(persisted.toolNames);
const connections = yield* ctx.connections.list({ integration: slug });
yield* Effect.forEach(
connections,
(connection) =>
ctx.connections
.refresh({
owner: connection.owner,
integration: connection.integration,
name: connection.name,
})
.pipe(Effect.catchTag("ConnectionNotFoundError", () => Effect.succeed([]))),
{ discard: true },
).pipe(Effect.catchTag("IntegrationNotFoundError", () => Effect.void));
return {
slug,
toolCount: persisted.toolCount,
addedTools: [...nextNames].filter((name) => !previousNames.has(name)).sort(),
removedTools: [...previousNames].filter((name) => !nextNames.has(name)).sort(),
};
});
return {
addGraph,
updateGraph,
removeGraph: (slug: string) =>
ctx.transaction(
Effect.gen(function* () {
yield* ctx.storage.removeOperations(slug);
yield* ctx.core.integrations
.remove(IntegrationSlug.make(slug))
.pipe(Effect.catchTag("IntegrationRemovalNotAllowedError", () => Effect.void));
}),
),
getIntegration: (slug: string) =>
ctx.core.integrations.get(IntegrationSlug.make(slug)).pipe(
Effect.map((record) =>
record
? ({
slug: record.slug,
description: record.description,
kind: record.kind,
canRemove: record.canRemove,
canRefresh: record.canRefresh,
} as Integration)
: null,
),
),
getConfig: (slug: string) =>
ctx.core.integrations
.get(IntegrationSlug.make(slug))
.pipe(
Effect.map((record) =>
record ? decodeMicrosoftGraphIntegrationConfig(record.config) : null,
),
),
configure: (slug: string, input: MicrosoftConfigureInput) =>
ctx.transaction(
Effect.gen(function* () {
const record = yield* ctx.core.integrations.get(IntegrationSlug.make(slug));
if (!record) return [] as readonly Authentication[];
const current = decodeMicrosoftGraphIntegrationConfig(record.config);
if (!current) return [] as readonly Authentication[];
const incoming = normalizeOpenApiAuthInputs(input.authenticationTemplate);
const merged =
input.mode === "replace"
? incoming
: mergeAuthTemplates(current.authenticationTemplate ?? [], incoming);
const next: MicrosoftGraphIntegrationConfig = {
...current,
authenticationTemplate: merged,
};
yield* ctx.core.integrations.update(IntegrationSlug.make(slug), {
config: next satisfies MicrosoftGraphIntegrationConfig as IntegrationConfig,
});
return merged;
}),
),
};
};
export type MicrosoftPluginExtension = ReturnType<typeof makeMicrosoftPluginExtension>;
export const microsoftPlugin = definePlugin((options?: MicrosoftPluginOptions) => ({
id: "microsoft" as const,
packageName: "@executor-js/plugin-microsoft",
integrationPresets: [microsoftGraphPreset],
storage: (deps): OpenapiStore => makeDefaultOpenapiStore(deps),
extension: (ctx) =>
makeMicrosoftPluginExtension(ctx, options?.httpClientLayer ?? ctx.httpClientLayer, {
allowUnsafeUrlOverrides: options?.allowUnsafeUrlOverrides === true,
}),
describeAuthMethods: describeMicrosoftAuthMethods,
describeIntegrationDisplay: describeMicrosoftIntegrationDisplay,
resolveTools: ({ integration, config, storage }) =>
resolveOpenApiBackedTools({ integration, config, storage }),
invokeTool: ({ ctx, toolRow, credential, args }) => {
const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;
return invokeOpenApiBackedTool({
ctx,
toolRow,
credential,
args,
httpClientLayer,
});
},
resolveAnnotations: ({ ctx, integration, toolRows }) =>
resolveOpenApiBackedAnnotations({
ctx,
integration: String(integration),
toolRows,
}),
// Health checks reuse the OpenAPI backing (same store + config superset). The
// user picks the identity operation (e.g. GET /me) via the editor.
describeHealthCheck: describeHealthCheckOpenApi,
listHealthCheckCandidates: (input) =>
listHealthCheckCandidatesOpenApi({ ctx: input.ctx, integration: input.integration }),
setHealthCheck: (input) =>
setHealthCheckOpenApi({ ctx: input.ctx, integration: input.integration, spec: input.spec }),
checkHealth: (input) =>
checkHealthOpenApi({
ctx: input.ctx,
integration: input.integration,
credential: input.credential,
spec: input.spec,
httpClientLayer: options?.httpClientLayer ?? input.ctx.httpClientLayer,
}),
removeConnection: () => Effect.void,
detect: ({ url }) =>
Effect.sync(() => {
const trimmed = url.trim();
if (!URL.canParse(trimmed)) return null;
const parsed = new URL(trimmed);
const host = parsed.hostname.toLowerCase();
const isGraph =
host === "graph.microsoft.com" ||
(host === "learn.microsoft.com" && parsed.pathname.startsWith("/graph/")) ||
(host === "raw.githubusercontent.com" &&
parsed.pathname.includes("/microsoftgraph/msgraph-metadata/"));
if (!isGraph) return null;
return IntegrationDetectionResult.make({
kind: "microsoft",
confidence: "high",
endpoint: trimmed,
name: "Microsoft Graph",
slug: DEFAULT_MICROSOFT_SLUG,
});
}),
}));