@slates/provider-handler 1.0.0-rc.1 → 1.0.0-rc.11

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1002 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ createProviderHandler: () => createProviderHandler
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_error3 = require("@lowerdeck/error");
37
+ var import_proto = require("@slates/proto");
38
+ var import_provider2 = require("@slates/provider");
39
+
40
+ // src/spec.ts
41
+ var import_error2 = require("@lowerdeck/error");
42
+ var import_provider = require("@slates/provider");
43
+ var import_zod = __toESM(require("zod"), 1);
44
+
45
+ // src/validation.ts
46
+ var import_error = require("@lowerdeck/error");
47
+ var zodToValidationError = (entity, message, e) => {
48
+ return (0, import_error.validationError)({
49
+ message,
50
+ entity,
51
+ errors: e.issues.map((i) => ({
52
+ ...i,
53
+ path: i.path.map((p) => String(p))
54
+ }))
55
+ });
56
+ };
57
+ var validate = (schema, data, entity, message) => {
58
+ let result = schema.safeParse(data);
59
+ if (!result.success) {
60
+ throw new import_error.ServiceError(zodToValidationError(entity, message, result.error));
61
+ }
62
+ return result.data;
63
+ };
64
+ var toJsonSchema = (schema) => schema.toJSONSchema({
65
+ unrepresentable: "any",
66
+ override: (ctx) => {
67
+ let def = ctx.zodSchema._zod.def;
68
+ if (def.type === "date") {
69
+ ctx.jsonSchema.type = "string";
70
+ ctx.jsonSchema.format = "date-time";
71
+ }
72
+ if (def.type === "bigint") {
73
+ ctx.jsonSchema.type = "number";
74
+ }
75
+ }
76
+ });
77
+
78
+ // src/spec.ts
79
+ var getAuthMethod = (slate, authenticationMethodId) => {
80
+ let authMethod = slate.spec.auth.authStack.find((m) => m.key === authenticationMethodId);
81
+ if (!authMethod) {
82
+ throw new import_error2.ServiceError(
83
+ (0, import_error2.badRequestError)({
84
+ message: `Invalid authentication method ID: ${authenticationMethodId}`
85
+ })
86
+ );
87
+ }
88
+ return authMethod;
89
+ };
90
+ var mapAuthMethod = (slate, m) => ({
91
+ id: m.key,
92
+ name: m.name,
93
+ type: m.type,
94
+ scopes: "scopes" in m ? m.scopes.map((s) => ({
95
+ id: s.scope,
96
+ title: s.title,
97
+ description: s.description,
98
+ defaultChecked: s.defaultChecked
99
+ })) : void 0,
100
+ inputSchema: toJsonSchema(m.inputSchema ?? import_zod.default.object({})),
101
+ outputSchema: toJsonSchema(slate.spec.auth.outputSchema),
102
+ capabilities: {
103
+ getDefaultInput: { enabled: !!("getDefaultInput" in m && m.getDefaultInput) },
104
+ handleTokenRefresh: {
105
+ enabled: !!("handleTokenRefresh" in m && m.handleTokenRefresh)
106
+ },
107
+ handleChangedInput: {
108
+ enabled: !!m.onInputChanged
109
+ },
110
+ getProfile: { enabled: !!m.getProfile }
111
+ }
112
+ });
113
+ var getAction = (slate, actionId) => {
114
+ let action = slate.actions.find((m) => m.key === actionId);
115
+ if (!action) {
116
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`action`, actionId));
117
+ }
118
+ return action;
119
+ };
120
+ var getActionWithType = (slate, type, actionId) => {
121
+ let action = getAction(slate, actionId);
122
+ if (action.type !== type) {
123
+ throw new import_error2.ServiceError(
124
+ (0, import_error2.badRequestError)({
125
+ message: `Action with ID ${actionId} is not of type ${type}`
126
+ })
127
+ );
128
+ }
129
+ return action;
130
+ };
131
+ var mapAction = (_slate, a) => {
132
+ let base = {
133
+ id: a.key,
134
+ name: a.name,
135
+ description: a.description,
136
+ instructions: a.instructions,
137
+ constraints: a.constraints,
138
+ tags: a.tags,
139
+ metadata: a.metadata,
140
+ scopes: a.scopes,
141
+ inputSchema: toJsonSchema(a.inputSchema),
142
+ outputSchema: toJsonSchema(a.outputSchema)
143
+ };
144
+ if (a.type === "tool") {
145
+ return {
146
+ ...base,
147
+ type: "action.tool",
148
+ capabilities: {}
149
+ };
150
+ }
151
+ return {
152
+ ...base,
153
+ type: "action.trigger",
154
+ capabilities: {},
155
+ invocation: a.source === "polling" ? {
156
+ type: "polling",
157
+ intervalSeconds: a.polling.intervalInSeconds ?? import_provider.SlateDefaultPollingIntervalSeconds
158
+ } : {
159
+ type: "webhook",
160
+ autoRegistration: !!a.autoRegisterWebhook,
161
+ autoUnregistration: !!a.autoUnregisterWebhook
162
+ }
163
+ };
164
+ };
165
+
166
+ // src/state.ts
167
+ var State = class {
168
+ #value;
169
+ get value() {
170
+ return this.#value;
171
+ }
172
+ get() {
173
+ return this.#value;
174
+ }
175
+ set(value) {
176
+ this.#value = value;
177
+ }
178
+ constructor(initialValue) {
179
+ this.#value = initialValue;
180
+ }
181
+ };
182
+
183
+ // src/index.ts
184
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
185
+ var getObjectKeyCount = (value) => isRecord(value) ? Object.keys(value).length : void 0;
186
+ var DOWNLOAD_ATTACHMENT_URL_KEYS = /* @__PURE__ */ new Set([
187
+ "downloadUrl",
188
+ "fileUrl",
189
+ "temporaryDownloadUrl",
190
+ "webContentLink"
191
+ ]);
192
+ var isAttachmentUrl = (value) => /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
193
+ var collectOutputUrlAttachments = (value, seen = /* @__PURE__ */ new Set()) => {
194
+ if (Array.isArray(value)) {
195
+ return value.flatMap((item) => collectOutputUrlAttachments(item, seen));
196
+ }
197
+ if (!isRecord(value)) {
198
+ return [];
199
+ }
200
+ let attachments = [];
201
+ for (let [key, nestedValue] of Object.entries(value)) {
202
+ if (DOWNLOAD_ATTACHMENT_URL_KEYS.has(key) && typeof nestedValue === "string" && nestedValue.length > 0 && isAttachmentUrl(nestedValue) && !seen.has(nestedValue)) {
203
+ seen.add(nestedValue);
204
+ attachments.push({
205
+ content: {
206
+ type: "url",
207
+ url: nestedValue
208
+ }
209
+ });
210
+ continue;
211
+ }
212
+ attachments.push(...collectOutputUrlAttachments(nestedValue, seen));
213
+ }
214
+ return attachments;
215
+ };
216
+ var mergeAttachments = (explicitAttachments, output) => {
217
+ let attachments = [...explicitAttachments ?? []];
218
+ let seen = new Set(attachments.map((attachment) => JSON.stringify(attachment)));
219
+ for (let attachment of collectOutputUrlAttachments(output)) {
220
+ let key = JSON.stringify(attachment);
221
+ if (seen.has(key)) continue;
222
+ seen.add(key);
223
+ attachments.push(attachment);
224
+ }
225
+ return attachments.length > 0 ? attachments : void 0;
226
+ };
227
+ var toErrorMetadata = (error) => {
228
+ if (error instanceof Error) {
229
+ return {
230
+ errorName: error.name,
231
+ errorMessage: error.message,
232
+ errorStack: error.stack
233
+ };
234
+ }
235
+ return {
236
+ errorValue: String(error)
237
+ };
238
+ };
239
+ var formatEntityLabel = (name, key) => `"${name}" (${key})`;
240
+ var resolveTraceMessage = (message, result) => typeof message === "function" ? message(result) : message;
241
+ var createProviderHandler = (slate, listeners) => (0, import_proto.createSlatesProviderProtoHandler)(async (manager) => {
242
+ let protocol = new State(null);
243
+ let participants = new State(null);
244
+ let auth = new State(null);
245
+ let config = new State(null);
246
+ let session = new State(null);
247
+ let logger = new import_provider2.SlateLogger(listeners);
248
+ let providerTrace = {
249
+ providerId: slate.spec.key,
250
+ providerName: slate.spec.name
251
+ };
252
+ let traceProviderCall = async (trace, handler) => {
253
+ let startedAt = Date.now();
254
+ logger.info({
255
+ ...providerTrace,
256
+ ...trace.metadata,
257
+ component: trace.component,
258
+ functionName: trace.functionName,
259
+ phase: "start",
260
+ message: trace.message
261
+ });
262
+ try {
263
+ let result = await handler();
264
+ let successMessage = resolveTraceMessage(trace.successMessage, result);
265
+ logger.info({
266
+ ...providerTrace,
267
+ ...trace.metadata,
268
+ ...trace.onSuccess?.(result) ?? {},
269
+ component: trace.component,
270
+ functionName: trace.functionName,
271
+ phase: "success",
272
+ durationMs: Date.now() - startedAt,
273
+ message: successMessage
274
+ });
275
+ return result;
276
+ } catch (error) {
277
+ logger.error({
278
+ ...providerTrace,
279
+ ...trace.metadata,
280
+ ...toErrorMetadata(error),
281
+ component: trace.component,
282
+ functionName: trace.functionName,
283
+ phase: "error",
284
+ durationMs: Date.now() - startedAt,
285
+ message: trace.errorMessage ?? `${typeof trace.successMessage === "string" ? trace.successMessage : trace.message} failed`
286
+ });
287
+ throw error;
288
+ }
289
+ };
290
+ let getContextBasic = () => {
291
+ let currentProtocol = protocol.get();
292
+ let currentParticipants = participants.get();
293
+ if (!currentProtocol || !currentParticipants) {
294
+ throw new import_error3.ServiceError(
295
+ (0, import_error3.preconditionFailedError)({
296
+ message: "Connection context has not been initialized"
297
+ })
298
+ );
299
+ }
300
+ return {
301
+ protocol: currentProtocol,
302
+ participants: currentParticipants
303
+ };
304
+ };
305
+ let getContextFull = () => {
306
+ let basic = getContextBasic();
307
+ let currentConfig = config.get();
308
+ let currentSession = session.get();
309
+ let currentAuth = auth.get();
310
+ if (!currentConfig || !currentSession || !currentAuth && slate.spec.auth.authStack.length > 0) {
311
+ throw new import_error3.ServiceError(
312
+ (0, import_error3.preconditionFailedError)({
313
+ message: "Session context has not been initialized"
314
+ })
315
+ );
316
+ }
317
+ return {
318
+ ...basic,
319
+ config: currentConfig.value,
320
+ session: currentSession,
321
+ auth: currentAuth
322
+ };
323
+ };
324
+ let getEmptyContext = () => new import_provider2.SlateContext({}, {}, {}, slate.spec, logger);
325
+ let withRequestTraces = (context, result) => {
326
+ let requestTraces = context.getHttpTraces();
327
+ return requestTraces.length > 0 ? { ...result, requestTraces } : result;
328
+ };
329
+ manager.onNotification("slates/hello", async ({ params }) => {
330
+ protocol.set(params.protocol);
331
+ });
332
+ manager.onNotification("slates/participant.set", async ({ params }) => {
333
+ if (!protocol.get()) {
334
+ throw new import_error3.ServiceError(
335
+ (0, import_error3.preconditionFailedError)({ message: "Connection protocol has not been initialized" })
336
+ );
337
+ }
338
+ participants.set(params.participants);
339
+ });
340
+ manager.onNotification("slates/auth.set", async ({ params }) => {
341
+ getContextBasic();
342
+ getAuthMethod(slate, params.authenticationMethodId);
343
+ let valRes = validate(
344
+ slate.spec.authSchema,
345
+ params.output,
346
+ "auth",
347
+ `Invalid authentication output for method ID: ${params.authenticationMethodId}`
348
+ );
349
+ auth.set({
350
+ authenticationMethodId: params.authenticationMethodId,
351
+ output: valRes
352
+ });
353
+ });
354
+ manager.onNotification("slates/config.set", async ({ params }) => {
355
+ getContextBasic();
356
+ let value = validate(
357
+ slate.spec.configSchema,
358
+ params.config,
359
+ "config",
360
+ "Invalid configuration"
361
+ );
362
+ config.set({ value });
363
+ });
364
+ manager.onNotification("slates/session.start", async ({ params }) => {
365
+ getContextBasic();
366
+ session.set({
367
+ id: params.sessionId,
368
+ state: params.state
369
+ });
370
+ });
371
+ manager.onRequest("slates/config.changed", async ({ params }) => {
372
+ getContextBasic();
373
+ let newConfig = validate(
374
+ slate.spec.config.configSchema,
375
+ params.newConfig,
376
+ "config",
377
+ "Invalid configuration"
378
+ );
379
+ let configChanged = slate.spec.config.handlers.configChanged;
380
+ if (!configChanged) {
381
+ return { success: true, config: newConfig };
382
+ }
383
+ let context = getEmptyContext();
384
+ let updatedConfig = await traceProviderCall(
385
+ {
386
+ component: "config",
387
+ functionName: "configChanged",
388
+ message: "Running config change handler",
389
+ successMessage: "Config change handler completed",
390
+ metadata: {
391
+ hasPreviousConfig: params.previousConfig !== null,
392
+ newConfigKeyCount: getObjectKeyCount(newConfig)
393
+ },
394
+ onSuccess: (result) => ({
395
+ returnedConfig: !!result?.config
396
+ })
397
+ },
398
+ () => (0, import_provider2.runWithContext)(
399
+ context,
400
+ async () => configChanged({
401
+ previousConfig: params.previousConfig,
402
+ newConfig
403
+ })
404
+ )
405
+ );
406
+ return withRequestTraces(context, {
407
+ success: true,
408
+ config: updatedConfig?.config ?? newConfig
409
+ });
410
+ });
411
+ manager.onRequest("slates/config.get_default", async () => {
412
+ getContextBasic();
413
+ let getDefaultConfig = slate.spec.config.handlers.getDefaultConfig;
414
+ if (!getDefaultConfig) {
415
+ return { config: null };
416
+ }
417
+ let context = getEmptyContext();
418
+ let defaultConfig = await traceProviderCall(
419
+ {
420
+ component: "config",
421
+ functionName: "getDefaultConfig",
422
+ message: "Getting default config",
423
+ successMessage: "Default config retrieved",
424
+ onSuccess: (result) => ({
425
+ configKeyCount: getObjectKeyCount(result)
426
+ })
427
+ },
428
+ () => (0, import_provider2.runWithContext)(context, async () => getDefaultConfig())
429
+ );
430
+ return withRequestTraces(context, {
431
+ config: defaultConfig ?? null
432
+ });
433
+ });
434
+ manager.onRequest("slates/config.schema.get", async () => {
435
+ getContextBasic();
436
+ return { schema: toJsonSchema(slate.spec.configSchema) };
437
+ });
438
+ manager.onRequest("slates/provider.identify", async () => {
439
+ getContextBasic();
440
+ return {
441
+ protocol: import_proto.SLATES_PROTOCOL_VERSION,
442
+ provider: {
443
+ type: "provider",
444
+ id: slate.spec.key,
445
+ name: slate.spec.name,
446
+ description: slate.spec.description,
447
+ metadata: slate.spec.parameters.metadata
448
+ }
449
+ };
450
+ });
451
+ manager.onRequest("slates/auth.methods.list", async () => {
452
+ getContextBasic();
453
+ return {
454
+ authenticationMethods: slate.spec.auth.authStack.map((m) => mapAuthMethod(slate, m))
455
+ };
456
+ });
457
+ manager.onRequest("slates/auth.method.get", async ({ params }) => {
458
+ getContextBasic();
459
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
460
+ return {
461
+ authenticationMethod: mapAuthMethod(slate, authMethod)
462
+ };
463
+ });
464
+ manager.onRequest("slates/auth.input.get_default", async ({ params }) => {
465
+ getContextBasic();
466
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
467
+ if (!authMethod.getDefaultInput) {
468
+ return { input: null };
469
+ }
470
+ let context = getEmptyContext();
471
+ let input = await traceProviderCall(
472
+ {
473
+ component: "auth",
474
+ functionName: "getDefaultInput",
475
+ message: "Getting default authentication input",
476
+ successMessage: "Default authentication input retrieved",
477
+ metadata: {
478
+ authenticationMethodId: params.authenticationMethodId,
479
+ authenticationMethodName: authMethod.name
480
+ },
481
+ onSuccess: (result) => ({
482
+ inputKeyCount: getObjectKeyCount(result)
483
+ })
484
+ },
485
+ () => (0, import_provider2.runWithContext)(context, () => authMethod.getDefaultInput())
486
+ );
487
+ return withRequestTraces(context, { input });
488
+ });
489
+ manager.onRequest("slates/auth.input.changed", async ({ params }) => {
490
+ getContextBasic();
491
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
492
+ if (!authMethod.onInputChanged) {
493
+ return { success: true, input: params.newInput };
494
+ }
495
+ let context = getEmptyContext();
496
+ let updatedInput = await traceProviderCall(
497
+ {
498
+ component: "auth",
499
+ functionName: "onInputChanged",
500
+ message: "Running authentication input change handler",
501
+ successMessage: "Authentication input change handler completed",
502
+ metadata: {
503
+ authenticationMethodId: params.authenticationMethodId,
504
+ authenticationMethodName: authMethod.name,
505
+ hasPreviousInput: params.previousInput !== null,
506
+ newInputKeyCount: getObjectKeyCount(params.newInput)
507
+ },
508
+ onSuccess: (result) => ({
509
+ returnedInput: !!result?.input
510
+ })
511
+ },
512
+ () => (0, import_provider2.runWithContext)(
513
+ context,
514
+ () => authMethod.onInputChanged({
515
+ previousInput: params.previousInput,
516
+ newInput: params.newInput
517
+ })
518
+ )
519
+ );
520
+ return withRequestTraces(context, {
521
+ success: true,
522
+ input: updatedInput?.input ?? params.newInput
523
+ });
524
+ });
525
+ manager.onRequest("slates/auth.output.get", async ({ params }) => {
526
+ getContextBasic();
527
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
528
+ let input = params.input;
529
+ if (authMethod.inputSchema) {
530
+ input = validate(
531
+ authMethod.inputSchema,
532
+ input,
533
+ "auth",
534
+ `Invalid authentication input for method ID: ${params.authenticationMethodId}`
535
+ );
536
+ }
537
+ if ("getOutput" in authMethod) {
538
+ let context = getEmptyContext();
539
+ let outputRes = await traceProviderCall(
540
+ {
541
+ component: "auth",
542
+ functionName: "getOutput",
543
+ message: "Getting authentication output",
544
+ successMessage: "Authentication output retrieved",
545
+ metadata: {
546
+ authenticationMethodId: params.authenticationMethodId,
547
+ authenticationMethodName: authMethod.name,
548
+ inputKeyCount: getObjectKeyCount(input)
549
+ },
550
+ onSuccess: (result) => ({
551
+ outputKeyCount: getObjectKeyCount(result.output)
552
+ })
553
+ },
554
+ () => (0, import_provider2.runWithContext)(context, () => authMethod.getOutput({ input }))
555
+ );
556
+ return withRequestTraces(context, { output: outputRes.output });
557
+ }
558
+ return { output: input };
559
+ });
560
+ manager.onRequest("slates/auth.authorization_callback.handle", async ({ params }) => {
561
+ getContextBasic();
562
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
563
+ if ("handleCallback" in authMethod) {
564
+ let context = getEmptyContext();
565
+ let callbackRes = await traceProviderCall(
566
+ {
567
+ component: "auth",
568
+ functionName: "handleCallback",
569
+ message: "Handling authentication callback",
570
+ successMessage: "Authentication callback handled",
571
+ metadata: {
572
+ authenticationMethodId: params.authenticationMethodId,
573
+ authenticationMethodName: authMethod.name,
574
+ scopeCount: params.scopes.length,
575
+ hasCallbackState: !!params.callbackState
576
+ },
577
+ onSuccess: (result) => ({
578
+ outputKeyCount: getObjectKeyCount(result.output),
579
+ returnedInput: !!result.input,
580
+ returnedScopeCount: result.scopes?.length
581
+ })
582
+ },
583
+ () => (0, import_provider2.runWithContext)(
584
+ context,
585
+ () => authMethod.handleCallback({
586
+ code: params.code,
587
+ state: params.state,
588
+ redirectUri: params.redirectUri,
589
+ input: params.input,
590
+ clientId: params.clientId,
591
+ clientSecret: params.clientSecret,
592
+ scopes: params.scopes,
593
+ callbackParams: params.callbackParams || {},
594
+ callbackState: params.callbackState || {}
595
+ })
596
+ )
597
+ );
598
+ return withRequestTraces(context, {
599
+ output: callbackRes.output,
600
+ input: callbackRes.input,
601
+ scopes: callbackRes.scopes
602
+ });
603
+ }
604
+ throw new import_error3.ServiceError(
605
+ (0, import_error3.preconditionFailedError)({
606
+ message: `Authentication method does not support authorization callback handling: ${params.authenticationMethodId}`
607
+ })
608
+ );
609
+ });
610
+ manager.onRequest("slates/auth.authorization_url.get", async ({ params }) => {
611
+ getContextBasic();
612
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
613
+ if ("getAuthorizationUrl" in authMethod) {
614
+ let context = getEmptyContext();
615
+ let urlRes = await traceProviderCall(
616
+ {
617
+ component: "auth",
618
+ functionName: "getAuthorizationUrl",
619
+ message: "Getting authentication authorization URL",
620
+ successMessage: "Authentication authorization URL retrieved",
621
+ metadata: {
622
+ authenticationMethodId: params.authenticationMethodId,
623
+ authenticationMethodName: authMethod.name,
624
+ scopeCount: params.scopes.length,
625
+ inputKeyCount: getObjectKeyCount(params.input)
626
+ },
627
+ onSuccess: (result) => ({
628
+ returnedInput: !!result.input,
629
+ hasCallbackState: !!result.callbackState
630
+ })
631
+ },
632
+ () => (0, import_provider2.runWithContext)(
633
+ context,
634
+ () => authMethod.getAuthorizationUrl({
635
+ redirectUri: params.redirectUri,
636
+ state: params.state,
637
+ input: params.input,
638
+ clientId: params.clientId,
639
+ clientSecret: params.clientSecret,
640
+ scopes: params.scopes
641
+ })
642
+ )
643
+ );
644
+ return withRequestTraces(context, {
645
+ authorizationUrl: urlRes.url,
646
+ input: urlRes.input,
647
+ callbackState: urlRes.callbackState
648
+ });
649
+ }
650
+ throw new import_error3.ServiceError(
651
+ (0, import_error3.preconditionFailedError)({
652
+ message: `Authentication method does not support authorization URL retrieval: ${params.authenticationMethodId}`
653
+ })
654
+ );
655
+ });
656
+ manager.onRequest("slates/auth.profile.get", async ({ params }) => {
657
+ getContextBasic();
658
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
659
+ if (authMethod.getProfile) {
660
+ let context = getEmptyContext();
661
+ let profileRes = await traceProviderCall(
662
+ {
663
+ component: "auth",
664
+ functionName: "getProfile",
665
+ message: "Getting authentication profile",
666
+ successMessage: "Authentication profile retrieved",
667
+ metadata: {
668
+ authenticationMethodId: params.authenticationMethodId,
669
+ authenticationMethodName: authMethod.name,
670
+ scopeCount: params.scopes.length,
671
+ inputKeyCount: getObjectKeyCount(params.input),
672
+ outputKeyCount: getObjectKeyCount(params.output)
673
+ },
674
+ onSuccess: (result) => ({
675
+ profileKeyCount: getObjectKeyCount(result.profile)
676
+ })
677
+ },
678
+ () => (0, import_provider2.runWithContext)(
679
+ context,
680
+ () => authMethod.getProfile({
681
+ output: params.output,
682
+ input: params.input,
683
+ scopes: params.scopes
684
+ })
685
+ )
686
+ );
687
+ return withRequestTraces(context, {
688
+ profile: profileRes.profile
689
+ });
690
+ }
691
+ throw new import_error3.ServiceError(
692
+ (0, import_error3.preconditionFailedError)({
693
+ message: `Authentication method does not support profile retrieval: ${params.authenticationMethodId}`
694
+ })
695
+ );
696
+ });
697
+ manager.onRequest("slates/auth.token_refresh.handle", async ({ params }) => {
698
+ getContextBasic();
699
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
700
+ if ("handleTokenRefresh" in authMethod && authMethod.handleTokenRefresh) {
701
+ let context = getEmptyContext();
702
+ let refreshRes = await traceProviderCall(
703
+ {
704
+ component: "auth",
705
+ functionName: "handleTokenRefresh",
706
+ message: "Refreshing authentication token",
707
+ successMessage: "Authentication token refreshed",
708
+ metadata: {
709
+ authenticationMethodId: params.authenticationMethodId,
710
+ authenticationMethodName: authMethod.name,
711
+ scopeCount: params.scopes.length,
712
+ inputKeyCount: getObjectKeyCount(params.input),
713
+ outputKeyCount: getObjectKeyCount(params.output)
714
+ },
715
+ onSuccess: (result) => ({
716
+ refreshedOutputKeyCount: getObjectKeyCount(result.output),
717
+ returnedInput: !!result.input
718
+ })
719
+ },
720
+ () => (0, import_provider2.runWithContext)(
721
+ context,
722
+ () => authMethod.handleTokenRefresh({
723
+ output: params.output,
724
+ input: params.input,
725
+ clientId: params.clientId,
726
+ clientSecret: params.clientSecret,
727
+ scopes: params.scopes
728
+ })
729
+ )
730
+ );
731
+ return withRequestTraces(context, {
732
+ output: refreshRes.output,
733
+ input: refreshRes.input
734
+ });
735
+ }
736
+ throw new import_error3.ServiceError(
737
+ (0, import_error3.preconditionFailedError)({
738
+ message: `Authentication method does not support token refresh handling: ${params.authenticationMethodId}`
739
+ })
740
+ );
741
+ });
742
+ manager.onRequest("slates/actions.list", async () => {
743
+ getContextBasic();
744
+ return {
745
+ actions: slate.actions.map((a) => mapAction(slate, a))
746
+ };
747
+ });
748
+ manager.onRequest("slates/action.get", async ({ params }) => {
749
+ getContextBasic();
750
+ let action = getAction(slate, params.actionId);
751
+ return {
752
+ action: mapAction(slate, action)
753
+ };
754
+ });
755
+ manager.onRequest("slates/action.tool.invoke", async ({ params }) => {
756
+ let ctx = getContextFull();
757
+ let action = getActionWithType(slate, "tool", params.actionId);
758
+ let input = validate(
759
+ action.inputSchema,
760
+ params.input,
761
+ "input",
762
+ `Invalid input for tool ID: ${params.actionId}`
763
+ );
764
+ let context = new import_provider2.SlateContext(ctx.config, input, ctx.auth?.output, slate.spec, logger);
765
+ let res = await traceProviderCall(
766
+ {
767
+ component: "action",
768
+ functionName: "handleInvocation",
769
+ message: `Starting tool ${formatEntityLabel(action.name, action.key)}`,
770
+ successMessage: `Completed tool ${formatEntityLabel(action.name, action.key)}`,
771
+ errorMessage: `Tool ${formatEntityLabel(action.name, action.key)} failed`,
772
+ metadata: {
773
+ actionId: action.key,
774
+ actionName: action.name,
775
+ actionType: action.type,
776
+ inputKeyCount: getObjectKeyCount(input)
777
+ },
778
+ onSuccess: (result) => ({
779
+ hasMessage: !!result.message,
780
+ actionResultMessage: result.message,
781
+ outputKeyCount: getObjectKeyCount(result.output),
782
+ attachmentCount: result.attachments?.length
783
+ })
784
+ },
785
+ () => (0, import_provider2.runWithContext)(context, () => action.handleInvocation(context))
786
+ );
787
+ return withRequestTraces(context, {
788
+ output: res.output,
789
+ message: res.message,
790
+ attachments: mergeAttachments(res.attachments, res.output)
791
+ });
792
+ });
793
+ manager.onRequest("slates/action.trigger.map_event", async ({ params }) => {
794
+ let ctx = getContextFull();
795
+ let action = getActionWithType(slate, "trigger", params.actionId);
796
+ let input = validate(
797
+ action.inputSchema,
798
+ params.input,
799
+ "input",
800
+ `Invalid event for trigger ID: ${params.actionId}`
801
+ );
802
+ let context = new import_provider2.SlateContext(ctx.config, input, ctx.auth?.output, slate.spec, logger);
803
+ let res = await traceProviderCall(
804
+ {
805
+ component: "action",
806
+ functionName: "handleEvent",
807
+ message: `Mapping event for trigger ${formatEntityLabel(action.name, action.key)}`,
808
+ successMessage: (result) => `Mapped trigger event "${result.type}" for ${formatEntityLabel(action.name, action.key)}`,
809
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while mapping an event`,
810
+ metadata: {
811
+ actionId: action.key,
812
+ actionName: action.name,
813
+ actionType: action.type,
814
+ inputKeyCount: getObjectKeyCount(input)
815
+ },
816
+ onSuccess: (result) => ({
817
+ eventType: result.type,
818
+ hasEventId: !!result.id,
819
+ outputKeyCount: getObjectKeyCount(result.output)
820
+ })
821
+ },
822
+ () => (0, import_provider2.runWithContext)(context, () => action.handleEvent(context))
823
+ );
824
+ return withRequestTraces(context, { id: res.id, type: res.type, output: res.output });
825
+ });
826
+ manager.onRequest("slates/action.trigger.poll_events", async ({ params }) => {
827
+ let ctx = getContextFull();
828
+ let action = getActionWithType(slate, "trigger", params.actionId);
829
+ if (!action.pollEvents) {
830
+ throw new import_error3.ServiceError(
831
+ (0, import_error3.badRequestError)({
832
+ message: `Trigger action does not support polling: ${params.actionId}`
833
+ })
834
+ );
835
+ }
836
+ let context = new import_provider2.SlateContext(
837
+ ctx.config,
838
+ { state: params.state },
839
+ ctx.auth?.output,
840
+ slate.spec,
841
+ logger
842
+ );
843
+ let res = await traceProviderCall(
844
+ {
845
+ component: "action",
846
+ functionName: "pollEvents",
847
+ message: `Polling events for trigger ${formatEntityLabel(action.name, action.key)}`,
848
+ successMessage: (result) => `Polled ${result.inputs.length} event(s) for trigger ${formatEntityLabel(action.name, action.key)}`,
849
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while polling events`,
850
+ metadata: {
851
+ actionId: action.key,
852
+ actionName: action.name,
853
+ actionType: action.type,
854
+ hasPreviousState: params.state !== null
855
+ },
856
+ onSuccess: (result) => ({
857
+ inputCount: result.inputs.length,
858
+ hasUpdatedState: result.updatedState !== void 0
859
+ })
860
+ },
861
+ () => (0, import_provider2.runWithContext)(context, () => action.pollEvents(context))
862
+ );
863
+ return withRequestTraces(context, {
864
+ inputs: res.inputs,
865
+ updatedState: res.updatedState
866
+ });
867
+ });
868
+ manager.onRequest("slates/action.trigger.webhook_handle", async ({ params }) => {
869
+ let ctx = getContextFull();
870
+ let action = getActionWithType(slate, "trigger", params.actionId);
871
+ if (!action.handleRequest) {
872
+ throw new import_error3.ServiceError(
873
+ (0, import_error3.badRequestError)({
874
+ message: `Trigger action does not support webhook requests: ${params.actionId}`
875
+ })
876
+ );
877
+ }
878
+ let req = new Request(params.url, {
879
+ method: params.method,
880
+ headers: params.headers,
881
+ body: params.body ? Uint8Array.from(atob(params.body.content), (c) => c.charCodeAt(0)) : null
882
+ });
883
+ let context = new import_provider2.SlateContext(
884
+ ctx.config,
885
+ { request: req, state: params.state },
886
+ ctx.auth?.output,
887
+ slate.spec,
888
+ logger
889
+ );
890
+ let res = await traceProviderCall(
891
+ {
892
+ component: "action",
893
+ functionName: "handleRequest",
894
+ message: `Handling webhook request for trigger ${formatEntityLabel(action.name, action.key)}`,
895
+ successMessage: (result) => `Received ${result.inputs.length} webhook event(s) for trigger ${formatEntityLabel(action.name, action.key)}`,
896
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while handling a webhook request`,
897
+ metadata: {
898
+ actionId: action.key,
899
+ actionName: action.name,
900
+ actionType: action.type,
901
+ requestMethod: params.method,
902
+ hasRequestBody: !!params.body,
903
+ hasPreviousState: params.state !== null
904
+ },
905
+ onSuccess: (result) => ({
906
+ inputCount: result.inputs.length,
907
+ hasUpdatedState: result.updatedState !== void 0
908
+ })
909
+ },
910
+ () => (0, import_provider2.runWithContext)(context, () => action.handleRequest(context))
911
+ );
912
+ return withRequestTraces(context, {
913
+ inputs: res.inputs,
914
+ updatedState: res.updatedState
915
+ });
916
+ });
917
+ manager.onRequest("slates/action.trigger.webhook_register", async ({ params }) => {
918
+ let ctx = getContextFull();
919
+ let action = getActionWithType(slate, "trigger", params.actionId);
920
+ if (!action.autoRegisterWebhook) {
921
+ throw new import_error3.ServiceError(
922
+ (0, import_error3.badRequestError)({
923
+ message: `Trigger action does not support webhook auto-registration: ${params.actionId}`
924
+ })
925
+ );
926
+ }
927
+ let context = new import_provider2.SlateContext(
928
+ ctx.config,
929
+ { webhookBaseUrl: params.webhookBaseUrl },
930
+ ctx.auth?.output,
931
+ slate.spec,
932
+ logger
933
+ );
934
+ let res = await traceProviderCall(
935
+ {
936
+ component: "action",
937
+ functionName: "autoRegisterWebhook",
938
+ message: `Registering webhook for trigger ${formatEntityLabel(action.name, action.key)}`,
939
+ successMessage: `Registered webhook for trigger ${formatEntityLabel(action.name, action.key)}`,
940
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while registering a webhook`,
941
+ metadata: {
942
+ actionId: action.key,
943
+ actionName: action.name,
944
+ actionType: action.type
945
+ },
946
+ onSuccess: (result) => ({
947
+ hasRegistrationDetails: result.registrationDetails !== void 0,
948
+ hasState: result.state !== void 0
949
+ })
950
+ },
951
+ () => (0, import_provider2.runWithContext)(context, () => action.autoRegisterWebhook(context))
952
+ );
953
+ return withRequestTraces(context, {
954
+ registrationDetails: res.registrationDetails,
955
+ state: res.state
956
+ });
957
+ });
958
+ manager.onRequest("slates/action.trigger.webhook_unregister", async ({ params }) => {
959
+ let ctx = getContextFull();
960
+ let action = getActionWithType(slate, "trigger", params.actionId);
961
+ if (!action.autoUnregisterWebhook) {
962
+ throw new import_error3.ServiceError(
963
+ (0, import_error3.badRequestError)({
964
+ message: `Trigger action does not support webhook auto-unregistration: ${params.actionId}`
965
+ })
966
+ );
967
+ }
968
+ let context = new import_provider2.SlateContext(
969
+ ctx.config,
970
+ {
971
+ webhookBaseUrl: params.webhookBaseUrl,
972
+ registrationDetails: params.registrationDetails,
973
+ state: params.state
974
+ },
975
+ ctx.auth?.output,
976
+ slate.spec,
977
+ logger
978
+ );
979
+ await traceProviderCall(
980
+ {
981
+ component: "action",
982
+ functionName: "autoUnregisterWebhook",
983
+ message: `Unregistering webhook for trigger ${formatEntityLabel(action.name, action.key)}`,
984
+ successMessage: `Unregistered webhook for trigger ${formatEntityLabel(action.name, action.key)}`,
985
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while unregistering a webhook`,
986
+ metadata: {
987
+ actionId: action.key,
988
+ actionName: action.name,
989
+ actionType: action.type,
990
+ hasRegistrationDetails: params.registrationDetails !== null,
991
+ hasPreviousState: params.state !== null
992
+ }
993
+ },
994
+ () => (0, import_provider2.runWithContext)(context, () => action.autoUnregisterWebhook(context))
995
+ );
996
+ return withRequestTraces(context, {});
997
+ });
998
+ });
999
+ // Annotate the CommonJS export names for ESM import in node:
1000
+ 0 && (module.exports = {
1001
+ createProviderHandler
1002
+ });