@slates/provider-handler 1.0.0-rc.4 → 1.0.0-rc.40

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 (73) hide show
  1. package/dist/index.cjs +1614 -2
  2. package/dist/index.d.cts +8 -0
  3. package/dist/index.d.ts +6 -3
  4. package/dist/index.module.js +1597 -2
  5. package/package.json +12 -10
  6. package/src/attachments.test.ts +171 -0
  7. package/src/exposure.test.ts +216 -0
  8. package/src/index.ts +1178 -133
  9. package/src/pQueue.test.ts +18 -0
  10. package/src/pQueue.ts +18 -0
  11. package/src/spec.test.ts +225 -0
  12. package/src/spec.ts +217 -18
  13. package/src/validation.ts +1 -1
  14. package/src/webhook.test.ts +65 -0
  15. package/src/webhook.ts +69 -0
  16. package/src/webhookProcess.test.ts +99 -0
  17. package/dist/action/action.d.ts +0 -90
  18. package/dist/action/action.d.ts.map +0 -1
  19. package/dist/action/builder.d.ts +0 -27
  20. package/dist/action/builder.d.ts.map +0 -1
  21. package/dist/action/index.d.ts +0 -5
  22. package/dist/action/index.d.ts.map +0 -1
  23. package/dist/action/tool.d.ts +0 -11
  24. package/dist/action/tool.d.ts.map +0 -1
  25. package/dist/action/trigger.d.ts +0 -14
  26. package/dist/action/trigger.d.ts.map +0 -1
  27. package/dist/auth/auth.d.ts +0 -26
  28. package/dist/auth/auth.d.ts.map +0 -1
  29. package/dist/auth/index.d.ts +0 -3
  30. package/dist/auth/index.d.ts.map +0 -1
  31. package/dist/auth/types.d.ts +0 -148
  32. package/dist/auth/types.d.ts.map +0 -1
  33. package/dist/axios/index.d.ts +0 -4
  34. package/dist/axios/index.d.ts.map +0 -1
  35. package/dist/config/config.d.ts +0 -22
  36. package/dist/config/config.d.ts.map +0 -1
  37. package/dist/config/index.d.ts +0 -2
  38. package/dist/config/index.d.ts.map +0 -1
  39. package/dist/context/context.d.ts +0 -20
  40. package/dist/context/context.d.ts.map +0 -1
  41. package/dist/context/hook.d.ts +0 -4
  42. package/dist/context/hook.d.ts.map +0 -1
  43. package/dist/context/index.d.ts +0 -2
  44. package/dist/context/index.d.ts.map +0 -1
  45. package/dist/error/base.d.ts +0 -5
  46. package/dist/error/base.d.ts.map +0 -1
  47. package/dist/error/declaration.d.ts +0 -6
  48. package/dist/error/declaration.d.ts.map +0 -1
  49. package/dist/error/index.d.ts +0 -3
  50. package/dist/error/index.d.ts.map +0 -1
  51. package/dist/index.cjs.map +0 -1
  52. package/dist/index.d.ts.map +0 -1
  53. package/dist/index.modern.js +0 -2
  54. package/dist/index.modern.js.map +0 -1
  55. package/dist/index.module.js.map +0 -1
  56. package/dist/index.umd.js +0 -2
  57. package/dist/index.umd.js.map +0 -1
  58. package/dist/spec.d.ts +0 -14
  59. package/dist/spec.d.ts.map +0 -1
  60. package/dist/specification/index.d.ts +0 -3
  61. package/dist/specification/index.d.ts.map +0 -1
  62. package/dist/specification/slate.d.ts +0 -15
  63. package/dist/specification/slate.d.ts.map +0 -1
  64. package/dist/specification/specification.d.ts +0 -30
  65. package/dist/specification/specification.d.ts.map +0 -1
  66. package/dist/specification/zero.d.ts +0 -13
  67. package/dist/specification/zero.d.ts.map +0 -1
  68. package/dist/state.d.ts +0 -8
  69. package/dist/state.d.ts.map +0 -1
  70. package/dist/tokens.d.ts +0 -34
  71. package/dist/tokens.d.ts.map +0 -1
  72. package/dist/validation.d.ts +0 -5
  73. package/dist/validation.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,2 +1,1614 @@
1
- var e=require("@lowerdeck/error"),t=require("@slates/proto"),r=require("@slates/provider");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/n(require("zod"));function i(e,t){if(!{}.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}var a=0;function u(e){return"__private_"+a+++"_"+e}function s(){return s=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s.apply(null,arguments)}function c(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}var l=function(t,r,n,o){var i=t.safeParse(r);if(!i.success)throw new e.ServiceError(function(t,r,n){return e.validationError({message:r,entity:t,errors:n.issues.map(function(e){return s({},e,{path:e.path.map(function(e){return String(e)})})})})}(n,o,i.error));return i.data},p=function(e){return e.toJSONSchema({unrepresentable:"any",override:function(e){var t=e.zodSchema._zod.def;"date"===t.type&&(e.jsonSchema.type="string",e.jsonSchema.format="date-time"),"bigint"===t.type&&(e.jsonSchema.type="number")}})},h=function(t,r){var n=t.spec.auth.authStack.find(function(e){return e.key==r});if(!n)throw new e.ServiceError(e.badRequestError({message:"Invalid authentication method ID: "+r}));return n},d=function(e,t){var r;return{id:t.key,name:t.name,type:t.type,scopes:"scopes"in t?t.scopes.map(function(e){return{id:e.scope,title:e.title,description:e.description}}):void 0,inputSchema:p(null!=(r=t.inputSchema)?r:o.default.object({})),outputSchema:p(e.spec.auth.outputSchema),capabilities:{getDefaultInput:{enabled:!(!("getDefaultInput"in t)||!t.getDefaultInput)},handleTokenRefresh:{enabled:!(!("handleTokenRefresh"in t)||!t.handleTokenRefresh)},handleChangedInput:{enabled:!!t.onInputChanged},getProfile:{enabled:!!t.getProfile}}}},f=function(t,r){var n=t.actions.find(function(e){return e.key==r});if(!n)throw new e.ServiceError(e.notFoundError("action",r));return n},v=function(t,r,n){var o=f(t,n);if(o.type!=r)throw new e.ServiceError(e.badRequestError({message:"Action with ID "+n+" is not of type "+r}));return o},m=function(e,t){var n;return s({},{id:t.key,name:t.name,description:t.description,instructions:t.instructions,constraints:t.constraints,tags:t.tags,metadata:t.metadata,inputSchema:p(t.inputSchema),outputSchema:p(t.outputSchema)},"tool"==t.type?{type:"action.tool",capabilities:{}}:{type:"action.trigger",capabilities:{},invocation:"polling"==t.source?{type:"polling",intervalSeconds:null!=(n=t.polling.intervalInSeconds)?n:r.SlateDefaultPollingIntervalSeconds}:{type:"webhook",autoRegistration:!!t.autoRegisterWebhook,autoUnregistration:!!t.autoUnregisterWebhook}})},g=/*#__PURE__*/u("value"),P=/*#__PURE__*/function(){function e(e){Object.defineProperty(this,g,{writable:!0,value:void 0}),i(this,g)[g]=e}var t,r,n=e.prototype;return n.get=function(){return i(this,g)[g]},n.set=function(e){i(this,g)[g]=e},t=e,(r=[{key:"value",get:function(){return i(this,g)[g]}}])&&function(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,c(n.key),n)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),t}();exports.createProviderHandler=function(n,o){return t.createSlatesProviderProtoHandler(function(t){try{var i=new P(null),a=new P(null),u=new P(null),c=new P(null),g=new P(null),y=new r.SlateLogger(o),w=function(){var t=i.get(),r=a.get();if(!t||!r)throw new e.ServiceError(e.preconditionFailedError({message:"Connection context has not been initialized"}));return{protocol:t,participants:r}},I=function(){var t=w(),r=c.get(),o=g.get(),i=u.get();if(!r||!o||!i&&n.spec.auth.authStack.length>0)throw new e.ServiceError(e.preconditionFailedError({message:"Session context has not been initialized"}));return s({},t,{config:r.value,session:o,auth:i})};return t.onNotification("slates/hello",function(e){var t=e.params;try{return i.set(t.protocol),Promise.resolve()}catch(e){return Promise.reject(e)}}),t.onNotification("slates/participant.set",function(t){var r=t.params;try{if(!i.get())throw new e.ServiceError(e.preconditionFailedError({message:"Connection protocol has not been initialized"}));return a.set(r.participants),Promise.resolve()}catch(e){return Promise.reject(e)}}),t.onNotification("slates/auth.set",function(e){var t=e.params;try{w(),h(n,t.authenticationMethodId);var r=l(n.spec.authSchema,t.output,"auth","Invalid authentication output for method ID: "+t.authenticationMethodId);return u.set({authenticationMethodId:t.authenticationMethodId,output:r}),Promise.resolve()}catch(e){return Promise.reject(e)}}),t.onNotification("slates/config.set",function(e){var t=e.params;try{w();var r=l(n.spec.configSchema,t.config,"config","Invalid configuration");return c.set({value:r}),Promise.resolve()}catch(e){return Promise.reject(e)}}),t.onNotification("slates/session.start",function(e){var t=e.params;try{return w(),g.set({id:t.sessionId,state:t.state}),Promise.resolve()}catch(e){return Promise.reject(e)}}),t.onRequest("slates/config.changed",function(e){var t=e.params;try{w();var r=l(n.spec.config.configSchema,t.newConfig,"config","Invalid configuration"),o=n.spec.config.handlers.configChanged;return o?Promise.resolve(o({previousConfig:t.previousConfig,newConfig:r})).then(function(e){var t;return{success:!0,config:null!=(t=null==e?void 0:e.config)?t:r}}):Promise.resolve({success:!0,config:r})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/config.get_default",function(e){try{w();var t=n.spec.config.handlers.getDefaultConfig;return t?Promise.resolve(t()).then(function(e){return{config:e}}):Promise.resolve({config:null})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/config.schema.get",function(e){try{return w(),Promise.resolve({schema:p(n.spec.configSchema)})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/provider.identify",function(e){try{return w(),Promise.resolve({protocol:"slates@2026-01-01",provider:{type:"provider",id:n.spec.key,name:n.spec.name,description:n.spec.description,metadata:n.spec.parameters.metadata}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.methods.list",function(e){try{return w(),Promise.resolve({authenticationMethods:n.spec.auth.authStack.map(function(e){return d(n,e)})})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.method.get",function(e){var t=e.params;try{w();var r=h(n,t.authenticationMethodId);return Promise.resolve({authenticationMethod:d(n,r)})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.input.get_default",function(e){var t=e.params;try{w();var r=h(n,t.authenticationMethodId);return r.getDefaultInput?Promise.resolve(r.getDefaultInput()).then(function(e){return{input:e}}):Promise.resolve({input:null})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.input.changed",function(e){var t=e.params;try{w();var r=h(n,t.authenticationMethodId);return r.onInputChanged?Promise.resolve(r.onInputChanged({previousInput:t.previousInput,newInput:t.newInput})).then(function(e){var r;return{success:!0,input:null!=(r=null==e?void 0:e.input)?r:t.newInput}}):Promise.resolve({success:!0,input:t.newInput})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.output.get",function(e){var t=e.params;try{var r,o=function(e){return r?e:{output:a}};w();var i=h(n,t.authenticationMethodId),a=t.input;i.inputSchema&&(a=l(i.inputSchema,a,"auth","Invalid authentication input for method ID: "+t.authenticationMethodId));var u=function(){if("getOutput"in i)return Promise.resolve(i.getOutput({input:a})).then(function(e){return r=1,{output:e.output}})}();return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.authorization_callback.handle",function(t){var r=t.params;try{var o,i=function(t){if(o)return t;throw new e.ServiceError(e.preconditionFailedError({message:"Authentication method does not support authorization callback handling: "+r.authenticationMethodId}))};w();var a=h(n,r.authenticationMethodId),u=function(){if("handleCallback"in a)return Promise.resolve(a.handleCallback({code:r.code,state:r.state,redirectUri:r.redirectUri,input:r.input,clientId:r.clientId,clientSecret:r.clientSecret,scopes:r.scopes})).then(function(e){return o=1,{output:e.output,input:e.input}})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.authorization_url.get",function(t){var r=t.params;try{var o,i=function(t){if(o)return t;throw new e.ServiceError(e.preconditionFailedError({message:"Authentication method does not support authorization URL retrieval: "+r.authenticationMethodId}))};w();var a=h(n,r.authenticationMethodId),u=function(){if("getAuthorizationUrl"in a)return Promise.resolve(a.getAuthorizationUrl({redirectUri:r.redirectUri,state:r.state,input:r.input,clientId:r.clientId,clientSecret:r.clientSecret,scopes:r.scopes})).then(function(e){return o=1,{authorizationUrl:e.url,input:e.input}})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.profile.get",function(t){var r=t.params;try{var o,i=function(t){if(o)return t;throw new e.ServiceError(e.preconditionFailedError({message:"Authentication method does not support profile retrieval: "+r.authenticationMethodId}))};w();var a=h(n,r.authenticationMethodId),u=function(){if(a.getProfile)return Promise.resolve(a.getProfile({output:r.output,input:r.input,scopes:r.scopes})).then(function(e){return o=1,{profile:e.profile}})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}}),t.onRequest("slates/auth.token_refresh.handle",function(t){var r=t.params;try{var o,i=function(t){if(o)return t;throw new e.ServiceError(e.preconditionFailedError({message:"Authentication method does not support token refresh handling: "+r.authenticationMethodId}))};w();var a=h(n,r.authenticationMethodId),u=function(){if("handleTokenRefresh"in a&&a.handleTokenRefresh)return Promise.resolve(a.handleTokenRefresh({output:r.output,input:r.input,clientId:r.clientId,clientSecret:r.clientSecret,scopes:r.scopes})).then(function(e){return o=1,{output:e.output,input:e.input}})}();return Promise.resolve(u&&u.then?u.then(i):i(u))}catch(e){return Promise.reject(e)}}),t.onRequest("slates/actions.list",function(e){try{return w(),Promise.resolve({actions:n.actions.map(function(e){return m(0,e)})})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.get",function(e){var t=e.params;try{w();var r=f(n,t.actionId);return Promise.resolve({action:m(0,r)})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.tool.invoke",function(e){var t=e.params;try{var o,i=I(),a=v(n,"tool",t.actionId),u=l(a.inputSchema,t.input,"input","Invalid input for tool ID: "+t.actionId);return Promise.resolve(a.handleInvocation(new r.SlateContext(i.config,u,null==(o=i.auth)?void 0:o.output,n.spec,y))).then(function(e){return{output:e.output,message:e.message}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.trigger.map_event",function(e){var t=e.params;try{var o,i=I(),a=v(n,"trigger",t.actionId),u=l(a.inputSchema,t.input,"input","Invalid event for trigger ID: "+t.actionId);return Promise.resolve(a.handleEvent(new r.SlateContext(i.config,u,null==(o=i.auth)?void 0:o.output,n.spec,y))).then(function(e){return{id:e.id,type:e.type,output:e.output}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.trigger.poll_events",function(t){var o=t.params;try{var i,a=I(),u=v(n,"trigger",o.actionId);if(!u.pollEvents)throw new e.ServiceError(e.badRequestError({message:"Trigger action does not support polling: "+o.actionId}));return Promise.resolve(u.pollEvents(new r.SlateContext(a.config,{state:o.state},null==(i=a.auth)?void 0:i.output,n.spec,y))).then(function(e){return{inputs:e.inputs,updatedState:e.updatedState}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.trigger.webhook_handle",function(t){var o=t.params;try{var i,a=I(),u=v(n,"trigger",o.actionId);if(!u.handleRequest)throw new e.ServiceError(e.badRequestError({message:"Trigger action does not support webhook requests: "+o.actionId}));var s=new Request(o.url,{method:o.method,headers:o.headers,body:o.body?Uint8Array.from(atob(o.body.content),function(e){return e.charCodeAt(0)}):null});return Promise.resolve(u.handleRequest(new r.SlateContext(a.config,{request:s,state:o.state},null==(i=a.auth)?void 0:i.output,n.spec,y))).then(function(e){return{inputs:e.inputs,updatedState:e.updatedState}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.trigger.webhook_register",function(t){var o=t.params;try{var i,a=I(),u=v(n,"trigger",o.actionId);if(!u.autoRegisterWebhook)throw new e.ServiceError(e.badRequestError({message:"Trigger action does not support webhook auto-registration: "+o.actionId}));return Promise.resolve(u.autoRegisterWebhook(new r.SlateContext(a.config,{webhookBaseUrl:o.webhookBaseUrl},null==(i=a.auth)?void 0:i.output,n.spec,y))).then(function(e){return{registrationDetails:e.registrationDetails,state:e.state}})}catch(e){return Promise.reject(e)}}),t.onRequest("slates/action.trigger.webhook_unregister",function(t){var o=t.params;try{var i,a=I(),u=v(n,"trigger",o.actionId);if(!u.autoUnregisterWebhook)throw new e.ServiceError(e.badRequestError({message:"Trigger action does not support webhook auto-unregistration: "+o.actionId}));return Promise.resolve(u.autoUnregisterWebhook(new r.SlateContext(a.config,{webhookBaseUrl:o.webhookBaseUrl,registrationDetails:o.registrationDetails,state:o.state},null==(i=a.auth)?void 0:i.output,n.spec,y))).then(function(){return{}})}catch(e){return Promise.reject(e)}}),Promise.resolve()}catch(e){return Promise.reject(e)}})};
2
- //# sourceMappingURL=index.cjs.map
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_error4 = require("@lowerdeck/error");
37
+ var import_proto = require("@slates/proto");
38
+ var import_provider2 = require("@slates/provider");
39
+
40
+ // src/pQueue.ts
41
+ var import_p_queue = __toESM(require("p-queue"), 1);
42
+ var resolveDefaultExport = (value) => {
43
+ let current = value;
44
+ for (let i = 0; i < 4; i++) {
45
+ if (typeof current === "function") return current;
46
+ if (current && typeof current === "object" && "default" in current) {
47
+ current = current.default;
48
+ continue;
49
+ }
50
+ break;
51
+ }
52
+ throw new TypeError("Module export is not a constructor");
53
+ };
54
+ var PQueue = resolveDefaultExport(import_p_queue.default);
55
+
56
+ // src/spec.ts
57
+ var import_error2 = require("@lowerdeck/error");
58
+ var import_provider = require("@slates/provider");
59
+ var import_zod = __toESM(require("zod"), 1);
60
+
61
+ // src/validation.ts
62
+ var import_error = require("@lowerdeck/error");
63
+ var zodToValidationError = (entity, message, e) => {
64
+ return (0, import_error.validationError)({
65
+ message,
66
+ entity,
67
+ errors: e.issues.map((i) => ({
68
+ ...i,
69
+ path: i.path.map((p) => String(p))
70
+ }))
71
+ });
72
+ };
73
+ var validate = (schema, data, entity, message) => {
74
+ let result = schema.safeParse(data);
75
+ if (!result.success) {
76
+ throw new import_error.ServiceError(zodToValidationError(entity, message, result.error));
77
+ }
78
+ return result.data;
79
+ };
80
+ var toJsonSchema = (schema) => schema.toJSONSchema({
81
+ unrepresentable: "any",
82
+ override: (ctx) => {
83
+ let def = ctx.zodSchema._zod.def;
84
+ if (def.type === "date") {
85
+ ctx.jsonSchema.type = "string";
86
+ ctx.jsonSchema.format = "date-time";
87
+ }
88
+ if (def.type === "bigint") {
89
+ ctx.jsonSchema.type = "number";
90
+ }
91
+ }
92
+ });
93
+
94
+ // src/spec.ts
95
+ var getAuthMethod = (slate, authenticationMethodId) => {
96
+ let authMethod = slate.spec.auth.authStack.find((m) => m.key === authenticationMethodId);
97
+ if (!authMethod) {
98
+ throw new import_error2.ServiceError(
99
+ (0, import_error2.badRequestError)({
100
+ message: `Invalid authentication method ID: ${authenticationMethodId}`
101
+ })
102
+ );
103
+ }
104
+ return authMethod;
105
+ };
106
+ var mapAuthMethod = (slate, m) => ({
107
+ id: m.key,
108
+ name: m.name,
109
+ type: m.type,
110
+ scopes: "scopes" in m ? m.scopes.map((s) => ({
111
+ id: s.scope,
112
+ title: s.title,
113
+ description: s.description
114
+ })) : void 0,
115
+ adapters: "adapters" in m ? m.adapters : void 0,
116
+ ..."syncTokensAcrossConnections" in m && m.syncTokensAcrossConnections ? { syncTokensAcrossConnections: true } : {},
117
+ inputSchema: toJsonSchema(m.inputSchema ?? import_zod.default.object({})),
118
+ outputSchema: toJsonSchema(slate.spec.auth.outputSchema),
119
+ capabilities: {
120
+ getDefaultInput: { enabled: !!("getDefaultInput" in m && m.getDefaultInput) },
121
+ handleTokenRefresh: {
122
+ enabled: !!("handleTokenRefresh" in m && m.handleTokenRefresh)
123
+ },
124
+ handleChangedInput: {
125
+ enabled: !!m.onInputChanged
126
+ },
127
+ getProfile: { enabled: !!m.getProfile }
128
+ },
129
+ docs: m.docs ?? []
130
+ });
131
+ var getAction = (slate, actionId) => {
132
+ let action = (slate.actions ?? []).find((m) => m.key === actionId);
133
+ if (!action) {
134
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`action`, actionId));
135
+ }
136
+ return action;
137
+ };
138
+ var getAdapter = (slate, adapterId) => {
139
+ let adapter = (slate.adapters ?? []).find((m) => m.id === adapterId);
140
+ if (!adapter) {
141
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`adapter`, adapterId));
142
+ }
143
+ return adapter;
144
+ };
145
+ var mapAdapter = (adapter) => ({
146
+ id: adapter.id,
147
+ name: adapter.name,
148
+ capabilities: adapter.capabilities ?? []
149
+ });
150
+ var getActionWithType = (slate, type, actionId) => {
151
+ let action = getAction(slate, actionId);
152
+ if (action.type !== type) {
153
+ throw new import_error2.ServiceError(
154
+ (0, import_error2.badRequestError)({
155
+ message: `Action with ID ${actionId} is not of type ${type}`
156
+ })
157
+ );
158
+ }
159
+ return action;
160
+ };
161
+ var mapAction = (slate, a) => {
162
+ let base = {
163
+ id: a.key,
164
+ name: a.name,
165
+ description: a.description,
166
+ instructions: a.instructions,
167
+ constraints: a.constraints,
168
+ tags: a.tags,
169
+ metadata: a.metadata,
170
+ scopes: a.scopes,
171
+ authMethods: a.authMethods,
172
+ docs: a.docs ?? [],
173
+ ...a.adapter ? { adapter: a.adapter } : {},
174
+ inputSchema: toJsonSchema(a.inputSchema),
175
+ outputSchema: toJsonSchema(a.outputSchema)
176
+ };
177
+ if (a.type === "tool") {
178
+ let toolCategoryIds = slate.getToolCategoryKeys?.(a.key) ?? [];
179
+ return {
180
+ ...base,
181
+ type: "action.tool",
182
+ capabilities: {},
183
+ isPublic: a.isPublic,
184
+ ...toolCategoryIds.length ? { toolCategoryIds } : {}
185
+ };
186
+ }
187
+ return {
188
+ ...base,
189
+ type: "action.trigger",
190
+ capabilities: {},
191
+ triggerGroupId: a.triggerGroup.key
192
+ };
193
+ };
194
+ var isMappableTrigger = (action) => action.type !== "trigger" || !!action.triggerGroup;
195
+ var getMappableAction = (slate, actionId) => {
196
+ let action = getAction(slate, actionId);
197
+ if (!isMappableTrigger(action)) {
198
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`action`, actionId));
199
+ }
200
+ return action;
201
+ };
202
+ var getExposedActions = (slate, includeAdapterActions) => (slate.actions ?? []).filter(
203
+ (action) => isMappableTrigger(action) && (includeAdapterActions || !action.adapter)
204
+ );
205
+ var getExposedAction = (slate, actionId, includeAdapterActions) => {
206
+ let action = getMappableAction(slate, actionId);
207
+ if (action.adapter && !includeAdapterActions) {
208
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`action`, actionId));
209
+ }
210
+ return action;
211
+ };
212
+ var getTriggerGroup = (slate, triggerGroupId) => {
213
+ let group = (slate.triggerGroups ?? []).find((g) => g.key === triggerGroupId);
214
+ if (!group) {
215
+ throw new import_error2.ServiceError((0, import_error2.notFoundError)(`trigger_group`, triggerGroupId));
216
+ }
217
+ return group;
218
+ };
219
+ var getTriggersForGroup = (slate, triggerGroupId) => (slate.actions ?? []).filter(
220
+ (action) => action.type === "trigger" && action.triggerGroup?.key === triggerGroupId
221
+ );
222
+ var getExposedTriggerGroups = (slate, includeAdapterActions) => {
223
+ let triggerGroupIds = new Set(
224
+ getExposedActions(slate, includeAdapterActions).flatMap(
225
+ (action) => action.type === "trigger" && action.triggerGroup ? [action.triggerGroup.key] : []
226
+ )
227
+ );
228
+ return (slate.triggerGroups ?? []).filter((group) => triggerGroupIds.has(group.key));
229
+ };
230
+ var evaluateTriggerMatches = (slate, triggerGroupId, payload) => getTriggersForGroup(slate, triggerGroupId).filter((trigger) => trigger.matches(payload)).map((trigger) => trigger.key);
231
+ var getWebhookAutoRegistration = (group) => {
232
+ if (group.source !== "webhook" || !group.webhook?.autoRegistration) {
233
+ throw new import_error2.ServiceError(
234
+ (0, import_error2.badRequestError)({
235
+ message: `Trigger group does not support webhook auto-registration: ${group.key}`
236
+ })
237
+ );
238
+ }
239
+ return group.webhook.autoRegistration;
240
+ };
241
+ var getWebhookManualRegistration = (group) => {
242
+ if (group.source !== "webhook" || !group.webhook?.manualRegistration) {
243
+ throw new import_error2.ServiceError(
244
+ (0, import_error2.badRequestError)({
245
+ message: `Trigger group does not support manual webhook registration: ${group.key}`
246
+ })
247
+ );
248
+ }
249
+ return group.webhook.manualRegistration;
250
+ };
251
+ var mapToolCategory = (category) => ({
252
+ id: category.key,
253
+ name: category.name,
254
+ description: category.description,
255
+ imageUrl: category.imageUrl
256
+ });
257
+ var getExposedToolCategories = (slate, includeAdapterActions) => {
258
+ let exposedCategoryKeys = new Set(
259
+ getExposedActions(slate, includeAdapterActions).filter((action) => action.type === "tool").flatMap((action) => slate.getToolCategoryKeys?.(action.key) ?? [])
260
+ );
261
+ return (slate.toolCategories ?? []).filter(
262
+ (category) => exposedCategoryKeys.has(category.key)
263
+ );
264
+ };
265
+ var mapTriggerGroup = (group) => ({
266
+ id: group.key,
267
+ name: group.name,
268
+ description: group.description,
269
+ metadata: group.metadata,
270
+ invocation: group.source === "polling" ? {
271
+ type: "polling",
272
+ intervalSeconds: group.polling?.intervalSeconds ?? import_provider.SlateDefaultPollingIntervalSeconds
273
+ } : group.source === "gateway" ? { type: "gateway" } : {
274
+ type: "webhook",
275
+ registration: group.webhook?.manualRegistration ? {
276
+ mode: "manual",
277
+ userConfigSchema: toJsonSchema(
278
+ group.webhook.manualRegistration.userConfigSchema
279
+ ),
280
+ fullConfigSchema: toJsonSchema(
281
+ group.webhook.manualRegistration.fullConfigSchema
282
+ )
283
+ } : { mode: "auto" }
284
+ }
285
+ });
286
+
287
+ // src/state.ts
288
+ var State = class {
289
+ #value;
290
+ get value() {
291
+ return this.#value;
292
+ }
293
+ get() {
294
+ return this.#value;
295
+ }
296
+ set(value) {
297
+ this.#value = value;
298
+ }
299
+ constructor(initialValue) {
300
+ this.#value = initialValue;
301
+ }
302
+ };
303
+
304
+ // src/webhook.ts
305
+ var import_error3 = require("@lowerdeck/error");
306
+ var SLATE_WEBHOOK_RESPONSE_MAX_BODY_BYTES = 1024 * 1024;
307
+ var serializeBody = (body) => {
308
+ if (body === null) return null;
309
+ if (body.byteLength > SLATE_WEBHOOK_RESPONSE_MAX_BODY_BYTES) {
310
+ throw new import_error3.ServiceError(
311
+ (0, import_error3.badRequestError)({
312
+ message: `Webhook response body exceeds the ${SLATE_WEBHOOK_RESPONSE_MAX_BODY_BYTES}-byte limit`
313
+ })
314
+ );
315
+ }
316
+ return {
317
+ encoding: "base64",
318
+ content: Buffer.from(body).toString("base64")
319
+ };
320
+ };
321
+ var headersToObject = (headers) => {
322
+ let result = {};
323
+ headers.forEach((value, key) => {
324
+ result[key] = value;
325
+ });
326
+ return result;
327
+ };
328
+ var validateStatus = (status) => {
329
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
330
+ throw new import_error3.ServiceError(
331
+ (0, import_error3.badRequestError)({
332
+ message: "Webhook response status must be an integer between 100 and 599"
333
+ })
334
+ );
335
+ }
336
+ };
337
+ var serializeWebhookHttpResponse = async (response) => {
338
+ if (response instanceof Response) {
339
+ validateStatus(response.status);
340
+ return {
341
+ status: response.status,
342
+ headers: headersToObject(response.headers),
343
+ body: serializeBody(
344
+ response.body === null ? null : new Uint8Array(await response.arrayBuffer())
345
+ )
346
+ };
347
+ }
348
+ let status = response.status ?? 200;
349
+ validateStatus(status);
350
+ let body = typeof response.body === "string" ? new TextEncoder().encode(response.body) : response.body ?? null;
351
+ return {
352
+ status,
353
+ headers: response.headers ?? {},
354
+ body: serializeBody(body)
355
+ };
356
+ };
357
+
358
+ // src/index.ts
359
+ var DEFAULT_MAX_ATTACHMENT_SIZE_BYTES = 1e8;
360
+ var routeAttachmentsThroughDirectUpload = async (attachments, live) => {
361
+ if (!attachments || attachments.length === 0 || !live) return attachments;
362
+ let contentEntries = attachments.map((attachment, index) => ({ attachment, index })).filter((entry) => entry.attachment.content.type === "content");
363
+ if (contentEntries.length === 0) return attachments;
364
+ let queue = new PQueue({ concurrency: 10 });
365
+ let replacements = /* @__PURE__ */ new Map();
366
+ await Promise.all(
367
+ contentEntries.map(
368
+ (entry) => queue.add(async () => {
369
+ try {
370
+ let body = entry.attachment.content.type === "content" ? entry.attachment.content.encoding === "base64" ? Buffer.from(entry.attachment.content.content, "base64") : Buffer.from(entry.attachment.content.content, "utf-8") : Buffer.alloc(0);
371
+ replacements.set(
372
+ entry.index,
373
+ await (0, import_provider2.uploadAttachmentDirect)({
374
+ live,
375
+ mimeType: entry.attachment.mimeType,
376
+ body
377
+ })
378
+ );
379
+ } catch {
380
+ replacements.set(entry.index, null);
381
+ }
382
+ })
383
+ )
384
+ );
385
+ return attachments.map(
386
+ (attachment, index) => replacements.has(index) ? replacements.get(index) : attachment
387
+ ).filter((a) => a != null);
388
+ };
389
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
390
+ var getObjectKeyCount = (value) => isRecord(value) ? Object.keys(value).length : void 0;
391
+ var DOWNLOAD_ATTACHMENT_URL_KEYS = /* @__PURE__ */ new Set([
392
+ "downloadUrl",
393
+ "fileUrl",
394
+ "temporaryDownloadUrl",
395
+ "webContentLink"
396
+ ]);
397
+ var isAttachmentUrl = (value) => /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
398
+ var collectOutputUrlAttachments = (value, seen = /* @__PURE__ */ new Set()) => {
399
+ if (Array.isArray(value)) {
400
+ return value.flatMap((item) => collectOutputUrlAttachments(item, seen));
401
+ }
402
+ if (!isRecord(value)) {
403
+ return [];
404
+ }
405
+ let attachments = [];
406
+ for (let [key, nestedValue] of Object.entries(value)) {
407
+ if (DOWNLOAD_ATTACHMENT_URL_KEYS.has(key) && typeof nestedValue === "string" && nestedValue.length > 0 && isAttachmentUrl(nestedValue) && !seen.has(nestedValue)) {
408
+ seen.add(nestedValue);
409
+ attachments.push({
410
+ content: {
411
+ type: "url",
412
+ url: nestedValue
413
+ }
414
+ });
415
+ continue;
416
+ }
417
+ attachments.push(...collectOutputUrlAttachments(nestedValue, seen));
418
+ }
419
+ return attachments;
420
+ };
421
+ var mergeAttachments = (explicitAttachments, output) => {
422
+ let attachments = [...explicitAttachments ?? []];
423
+ let seen = new Set(attachments.map((attachment) => JSON.stringify(attachment)));
424
+ for (let attachment of collectOutputUrlAttachments(output)) {
425
+ let key = JSON.stringify(attachment);
426
+ if (seen.has(key)) continue;
427
+ seen.add(key);
428
+ attachments.push(attachment);
429
+ }
430
+ return attachments.length > 0 ? attachments : void 0;
431
+ };
432
+ var toErrorMetadata = (error) => {
433
+ if (error instanceof Error) {
434
+ return {
435
+ errorName: error.name,
436
+ errorMessage: error.message,
437
+ errorStack: error.stack
438
+ };
439
+ }
440
+ return {
441
+ errorValue: String(error)
442
+ };
443
+ };
444
+ var formatEntityLabel = (name, key) => `"${name}" (${key})`;
445
+ var resolveTraceMessage = (message, result) => typeof message === "function" ? message(result) : message;
446
+ var createProviderHandler = (slate, listeners) => (0, import_proto.createSlatesProviderProtoHandler)(async (manager) => {
447
+ let protocol = new State(null);
448
+ let participants = new State(null);
449
+ let auth = new State(null);
450
+ let config = new State(null);
451
+ let session = new State(null);
452
+ let hubCapabilities = new State(null);
453
+ let liveInvocation = new State(
454
+ null
455
+ );
456
+ let getLiveInvocation = () => {
457
+ let directUpload = hubCapabilities.get()?.attachments?.directUpload;
458
+ let live = liveInvocation.get();
459
+ if (!directUpload?.enabled || !live) return null;
460
+ return {
461
+ ...live,
462
+ maxAttachmentSizeBytes: directUpload.maxAttachmentSizeBytes ?? DEFAULT_MAX_ATTACHMENT_SIZE_BYTES
463
+ };
464
+ };
465
+ let supportsTriggerGroups = () => !!hubCapabilities.get()?.triggers;
466
+ let supportsAdapters = () => !!hubCapabilities.get()?.adapters;
467
+ let logger = new import_provider2.SlateLogger(listeners);
468
+ let providerTrace = {
469
+ providerId: slate.spec.key,
470
+ providerName: slate.spec.name
471
+ };
472
+ let traceProviderCall = async (trace, handler) => {
473
+ let startedAt = Date.now();
474
+ logger.info({
475
+ ...providerTrace,
476
+ ...trace.metadata,
477
+ component: trace.component,
478
+ functionName: trace.functionName,
479
+ phase: "start",
480
+ message: trace.message
481
+ });
482
+ try {
483
+ let result = await handler();
484
+ let successMessage = resolveTraceMessage(trace.successMessage, result);
485
+ logger.info({
486
+ ...providerTrace,
487
+ ...trace.metadata,
488
+ ...trace.onSuccess?.(result) ?? {},
489
+ component: trace.component,
490
+ functionName: trace.functionName,
491
+ phase: "success",
492
+ durationMs: Date.now() - startedAt,
493
+ message: successMessage
494
+ });
495
+ return result;
496
+ } catch (error) {
497
+ logger.error({
498
+ ...providerTrace,
499
+ ...trace.metadata,
500
+ ...toErrorMetadata(error),
501
+ component: trace.component,
502
+ functionName: trace.functionName,
503
+ phase: "error",
504
+ durationMs: Date.now() - startedAt,
505
+ message: trace.errorMessage ?? `${typeof trace.successMessage === "string" ? trace.successMessage : trace.message} failed`
506
+ });
507
+ throw error;
508
+ }
509
+ };
510
+ let getContextBasic = () => {
511
+ let currentProtocol = protocol.get();
512
+ let currentParticipants = participants.get();
513
+ if (!currentProtocol || !currentParticipants) {
514
+ throw new import_error4.ServiceError(
515
+ (0, import_error4.preconditionFailedError)({
516
+ message: "Connection context has not been initialized"
517
+ })
518
+ );
519
+ }
520
+ return {
521
+ protocol: currentProtocol,
522
+ participants: currentParticipants
523
+ };
524
+ };
525
+ let getContextFull = () => {
526
+ let basic = getContextBasic();
527
+ let currentConfig = config.get();
528
+ let currentSession = session.get();
529
+ let currentAuth = auth.get();
530
+ if (!currentConfig || !currentSession || !currentAuth && slate.spec.auth.authStack.length > 0) {
531
+ throw new import_error4.ServiceError(
532
+ (0, import_error4.preconditionFailedError)({
533
+ message: "Session context has not been initialized"
534
+ })
535
+ );
536
+ }
537
+ return {
538
+ ...basic,
539
+ config: currentConfig.value,
540
+ session: currentSession,
541
+ auth: currentAuth
542
+ };
543
+ };
544
+ let getAuthConfig = () => config.get()?.value ?? {};
545
+ let getEmptyContext = () => new import_provider2.SlateContext({}, {}, {}, slate.spec, logger);
546
+ let getAuthContext = () => new import_provider2.SlateContext(getAuthConfig(), {}, {}, slate.spec, logger);
547
+ let withRequestTraces = (context, result) => {
548
+ let requestTraces = context.getHttpTraces();
549
+ return requestTraces.length > 0 ? { ...result, requestTraces } : result;
550
+ };
551
+ manager.onNotification("slates/hello", async ({ params }) => {
552
+ protocol.set(params.protocol);
553
+ });
554
+ manager.onNotification("slates/participant.set", async ({ params }) => {
555
+ if (!protocol.get()) {
556
+ throw new import_error4.ServiceError(
557
+ (0, import_error4.preconditionFailedError)({ message: "Connection protocol has not been initialized" })
558
+ );
559
+ }
560
+ participants.set(params.participants);
561
+ });
562
+ manager.onNotification("slates/auth.set", async ({ params }) => {
563
+ getContextBasic();
564
+ getAuthMethod(slate, params.authenticationMethodId);
565
+ let valRes = validate(
566
+ slate.spec.authSchema,
567
+ params.output,
568
+ "auth",
569
+ `Invalid authentication output for method ID: ${params.authenticationMethodId}`
570
+ );
571
+ auth.set({
572
+ authenticationMethodId: params.authenticationMethodId,
573
+ output: valRes
574
+ });
575
+ });
576
+ manager.onNotification("slates/config.set", async ({ params }) => {
577
+ getContextBasic();
578
+ let value = validate(
579
+ slate.spec.configSchema,
580
+ params.config,
581
+ "config",
582
+ "Invalid configuration"
583
+ );
584
+ config.set({ value });
585
+ });
586
+ manager.onNotification("slates/session.start", async ({ params }) => {
587
+ getContextBasic();
588
+ session.set({
589
+ id: params.sessionId,
590
+ state: params.state
591
+ });
592
+ });
593
+ manager.onNotification("slates/hub.capabilities.set", async ({ params }) => {
594
+ hubCapabilities.set(params.capabilities);
595
+ });
596
+ manager.onNotification("slates/hub.live_invocation.set", async ({ params }) => {
597
+ liveInvocation.set({
598
+ token: params.token,
599
+ baseUrl: params.baseUrl
600
+ });
601
+ });
602
+ manager.onRequest("slates/provider.capabilities.get", async () => ({
603
+ capabilities: {
604
+ hub: {
605
+ capabilitiesNotification: true,
606
+ liveInvocation: true
607
+ },
608
+ provider: {
609
+ triggerGroups: (slate.triggerGroups?.length ?? 0) > 0 && (slate.actions ?? []).every(isMappableTrigger),
610
+ toolCategories: (slate.toolCategories?.length ?? 0) > 0
611
+ }
612
+ }
613
+ }));
614
+ manager.onRequest("slates/config.changed", async ({ params }) => {
615
+ getContextBasic();
616
+ let newConfig = validate(
617
+ slate.spec.config.configSchema,
618
+ params.newConfig,
619
+ "config",
620
+ "Invalid configuration"
621
+ );
622
+ let configChanged = slate.spec.config.handlers.configChanged;
623
+ if (!configChanged) {
624
+ return { success: true, config: newConfig };
625
+ }
626
+ let context = getEmptyContext();
627
+ let updatedConfig = await traceProviderCall(
628
+ {
629
+ component: "config",
630
+ functionName: "configChanged",
631
+ message: "Running config change handler",
632
+ successMessage: "Config change handler completed",
633
+ metadata: {
634
+ hasPreviousConfig: params.previousConfig !== null,
635
+ newConfigKeyCount: getObjectKeyCount(newConfig)
636
+ },
637
+ onSuccess: (result) => ({
638
+ returnedConfig: !!result?.config
639
+ })
640
+ },
641
+ () => (0, import_provider2.runWithContext)(
642
+ context,
643
+ async () => configChanged({
644
+ previousConfig: params.previousConfig,
645
+ newConfig
646
+ })
647
+ )
648
+ );
649
+ return withRequestTraces(context, {
650
+ success: true,
651
+ config: updatedConfig?.config ?? newConfig
652
+ });
653
+ });
654
+ manager.onRequest("slates/config.get_default", async () => {
655
+ getContextBasic();
656
+ let getDefaultConfig = slate.spec.config.handlers.getDefaultConfig;
657
+ if (!getDefaultConfig) {
658
+ return { config: null };
659
+ }
660
+ let context = getEmptyContext();
661
+ let defaultConfig = await traceProviderCall(
662
+ {
663
+ component: "config",
664
+ functionName: "getDefaultConfig",
665
+ message: "Getting default config",
666
+ successMessage: "Default config retrieved",
667
+ onSuccess: (result) => ({
668
+ configKeyCount: getObjectKeyCount(result)
669
+ })
670
+ },
671
+ () => (0, import_provider2.runWithContext)(context, async () => getDefaultConfig())
672
+ );
673
+ return withRequestTraces(context, {
674
+ config: defaultConfig ?? null
675
+ });
676
+ });
677
+ manager.onRequest("slates/config.schema.get", async () => {
678
+ getContextBasic();
679
+ return {
680
+ schema: toJsonSchema(slate.spec.configSchema),
681
+ docs: slate.spec.config.docsReferences ?? []
682
+ };
683
+ });
684
+ manager.onRequest("slates/provider.identify", async () => {
685
+ getContextBasic();
686
+ return {
687
+ protocol: import_proto.SLATES_PROTOCOL_VERSION,
688
+ provider: {
689
+ type: "provider",
690
+ id: slate.spec.key,
691
+ name: slate.spec.name,
692
+ description: slate.spec.description,
693
+ metadata: slate.spec.parameters.metadata
694
+ },
695
+ docs: slate.spec.docs ?? []
696
+ };
697
+ });
698
+ manager.onRequest("slates/auth.methods.list", async () => {
699
+ getContextBasic();
700
+ return {
701
+ authenticationMethods: slate.spec.auth.authStack.map((m) => mapAuthMethod(slate, m))
702
+ };
703
+ });
704
+ manager.onRequest("slates/auth.method.get", async ({ params }) => {
705
+ getContextBasic();
706
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
707
+ return {
708
+ authenticationMethod: mapAuthMethod(slate, authMethod)
709
+ };
710
+ });
711
+ manager.onRequest("slates/auth.input.get_default", async ({ params }) => {
712
+ getContextBasic();
713
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
714
+ if (!authMethod.getDefaultInput) {
715
+ return { input: null };
716
+ }
717
+ let context = getEmptyContext();
718
+ let input = await traceProviderCall(
719
+ {
720
+ component: "auth",
721
+ functionName: "getDefaultInput",
722
+ message: "Getting default authentication input",
723
+ successMessage: "Default authentication input retrieved",
724
+ metadata: {
725
+ authenticationMethodId: params.authenticationMethodId,
726
+ authenticationMethodName: authMethod.name
727
+ },
728
+ onSuccess: (result) => ({
729
+ inputKeyCount: getObjectKeyCount(result)
730
+ })
731
+ },
732
+ () => (0, import_provider2.runWithContext)(context, () => authMethod.getDefaultInput())
733
+ );
734
+ return withRequestTraces(context, { input });
735
+ });
736
+ manager.onRequest("slates/auth.input.changed", async ({ params }) => {
737
+ getContextBasic();
738
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
739
+ if (!authMethod.onInputChanged) {
740
+ return { success: true, input: params.newInput };
741
+ }
742
+ let context = getEmptyContext();
743
+ let updatedInput = await traceProviderCall(
744
+ {
745
+ component: "auth",
746
+ functionName: "onInputChanged",
747
+ message: "Running authentication input change handler",
748
+ successMessage: "Authentication input change handler completed",
749
+ metadata: {
750
+ authenticationMethodId: params.authenticationMethodId,
751
+ authenticationMethodName: authMethod.name,
752
+ hasPreviousInput: params.previousInput !== null,
753
+ newInputKeyCount: getObjectKeyCount(params.newInput)
754
+ },
755
+ onSuccess: (result) => ({
756
+ returnedInput: !!result?.input
757
+ })
758
+ },
759
+ () => (0, import_provider2.runWithContext)(
760
+ context,
761
+ () => authMethod.onInputChanged({
762
+ previousInput: params.previousInput,
763
+ newInput: params.newInput
764
+ })
765
+ )
766
+ );
767
+ return withRequestTraces(context, {
768
+ success: true,
769
+ input: updatedInput?.input ?? params.newInput
770
+ });
771
+ });
772
+ manager.onRequest("slates/auth.output.get", async ({ params }) => {
773
+ getContextBasic();
774
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
775
+ let input = params.input;
776
+ if (authMethod.inputSchema) {
777
+ input = validate(
778
+ authMethod.inputSchema,
779
+ input,
780
+ "auth",
781
+ `Invalid authentication input for method ID: ${params.authenticationMethodId}`
782
+ );
783
+ }
784
+ if ("getOutput" in authMethod) {
785
+ let context = getAuthContext();
786
+ let outputRes = await traceProviderCall(
787
+ {
788
+ component: "auth",
789
+ functionName: "getOutput",
790
+ message: "Getting authentication output",
791
+ successMessage: "Authentication output retrieved",
792
+ metadata: {
793
+ authenticationMethodId: params.authenticationMethodId,
794
+ authenticationMethodName: authMethod.name,
795
+ inputKeyCount: getObjectKeyCount(input)
796
+ },
797
+ onSuccess: (result) => ({
798
+ outputKeyCount: getObjectKeyCount(result.output),
799
+ scopeCount: result.scopes?.length ?? 0
800
+ })
801
+ },
802
+ () => (0, import_provider2.runWithContext)(
803
+ context,
804
+ () => authMethod.getOutput({
805
+ input,
806
+ config: getAuthConfig()
807
+ })
808
+ )
809
+ );
810
+ return withRequestTraces(context, {
811
+ output: outputRes.output,
812
+ scopes: outputRes.scopes
813
+ });
814
+ }
815
+ return { output: input };
816
+ });
817
+ manager.onRequest("slates/auth.authorization_callback.handle", async ({ params }) => {
818
+ getContextBasic();
819
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
820
+ if ("handleCallback" in authMethod) {
821
+ let context = getEmptyContext();
822
+ let callbackRes = await traceProviderCall(
823
+ {
824
+ component: "auth",
825
+ functionName: "handleCallback",
826
+ message: "Handling authentication callback",
827
+ successMessage: "Authentication callback handled",
828
+ metadata: {
829
+ authenticationMethodId: params.authenticationMethodId,
830
+ authenticationMethodName: authMethod.name,
831
+ scopeCount: params.scopes.length,
832
+ hasCallbackState: !!params.callbackState
833
+ },
834
+ onSuccess: (result) => ({
835
+ outputKeyCount: getObjectKeyCount(result.output),
836
+ returnedInput: !!result.input,
837
+ returnedScopeCount: result.scopes?.length
838
+ })
839
+ },
840
+ () => (0, import_provider2.runWithContext)(
841
+ context,
842
+ () => authMethod.handleCallback({
843
+ code: params.code,
844
+ state: params.state,
845
+ redirectUri: params.redirectUri,
846
+ input: params.input,
847
+ clientId: params.clientId,
848
+ clientSecret: params.clientSecret,
849
+ scopes: params.scopes,
850
+ callbackParams: params.callbackParams || {},
851
+ callbackState: params.callbackState || {},
852
+ config: getAuthConfig()
853
+ })
854
+ )
855
+ );
856
+ return withRequestTraces(context, {
857
+ output: callbackRes.output,
858
+ input: callbackRes.input,
859
+ scopes: callbackRes.scopes
860
+ });
861
+ }
862
+ throw new import_error4.ServiceError(
863
+ (0, import_error4.preconditionFailedError)({
864
+ message: `Authentication method does not support authorization callback handling: ${params.authenticationMethodId}`
865
+ })
866
+ );
867
+ });
868
+ manager.onRequest("slates/auth.authorization_url.get", async ({ params }) => {
869
+ getContextBasic();
870
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
871
+ if ("getAuthorizationUrl" in authMethod) {
872
+ let context = getEmptyContext();
873
+ let urlRes = await traceProviderCall(
874
+ {
875
+ component: "auth",
876
+ functionName: "getAuthorizationUrl",
877
+ message: "Getting authentication authorization URL",
878
+ successMessage: "Authentication authorization URL retrieved",
879
+ metadata: {
880
+ authenticationMethodId: params.authenticationMethodId,
881
+ authenticationMethodName: authMethod.name,
882
+ scopeCount: params.scopes.length,
883
+ inputKeyCount: getObjectKeyCount(params.input)
884
+ },
885
+ onSuccess: (result) => ({
886
+ returnedInput: !!result.input,
887
+ hasCallbackState: !!result.callbackState
888
+ })
889
+ },
890
+ () => (0, import_provider2.runWithContext)(
891
+ context,
892
+ () => authMethod.getAuthorizationUrl({
893
+ redirectUri: params.redirectUri,
894
+ state: params.state,
895
+ input: params.input,
896
+ clientId: params.clientId,
897
+ clientSecret: params.clientSecret,
898
+ scopes: params.scopes,
899
+ config: getAuthConfig()
900
+ })
901
+ )
902
+ );
903
+ return withRequestTraces(context, {
904
+ authorizationUrl: urlRes.url,
905
+ input: urlRes.input,
906
+ callbackState: urlRes.callbackState
907
+ });
908
+ }
909
+ throw new import_error4.ServiceError(
910
+ (0, import_error4.preconditionFailedError)({
911
+ message: `Authentication method does not support authorization URL retrieval: ${params.authenticationMethodId}`
912
+ })
913
+ );
914
+ });
915
+ manager.onRequest("slates/auth.profile.get", async ({ params }) => {
916
+ getContextBasic();
917
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
918
+ if (authMethod.getProfile) {
919
+ let context = getAuthContext();
920
+ let profileRes = await traceProviderCall(
921
+ {
922
+ component: "auth",
923
+ functionName: "getProfile",
924
+ message: "Getting authentication profile",
925
+ successMessage: "Authentication profile retrieved",
926
+ metadata: {
927
+ authenticationMethodId: params.authenticationMethodId,
928
+ authenticationMethodName: authMethod.name,
929
+ scopeCount: params.scopes.length,
930
+ inputKeyCount: getObjectKeyCount(params.input),
931
+ outputKeyCount: getObjectKeyCount(params.output)
932
+ },
933
+ onSuccess: (result) => ({
934
+ profileKeyCount: getObjectKeyCount(result.profile)
935
+ })
936
+ },
937
+ () => (0, import_provider2.runWithContext)(context, () => {
938
+ if (authMethod.type === "auth.oauth") {
939
+ return authMethod.getProfile({
940
+ output: params.output,
941
+ input: params.input,
942
+ scopes: params.scopes,
943
+ config: getAuthConfig()
944
+ });
945
+ }
946
+ return authMethod.getProfile({
947
+ output: params.output,
948
+ input: params.input,
949
+ scopes: params.scopes,
950
+ config: getAuthConfig()
951
+ });
952
+ })
953
+ );
954
+ return withRequestTraces(context, {
955
+ profile: profileRes.profile
956
+ });
957
+ }
958
+ throw new import_error4.ServiceError(
959
+ (0, import_error4.preconditionFailedError)({
960
+ message: `Authentication method does not support profile retrieval: ${params.authenticationMethodId}`
961
+ })
962
+ );
963
+ });
964
+ manager.onRequest("slates/auth.token_refresh.handle", async ({ params }) => {
965
+ getContextBasic();
966
+ let authMethod = getAuthMethod(slate, params.authenticationMethodId);
967
+ if ("handleTokenRefresh" in authMethod && authMethod.handleTokenRefresh) {
968
+ let context = getAuthContext();
969
+ let refreshRes = await traceProviderCall(
970
+ {
971
+ component: "auth",
972
+ functionName: "handleTokenRefresh",
973
+ message: "Refreshing authentication token",
974
+ successMessage: "Authentication token refreshed",
975
+ metadata: {
976
+ authenticationMethodId: params.authenticationMethodId,
977
+ authenticationMethodName: authMethod.name,
978
+ scopeCount: params.scopes.length,
979
+ inputKeyCount: getObjectKeyCount(params.input),
980
+ outputKeyCount: getObjectKeyCount(params.output)
981
+ },
982
+ onSuccess: (result) => ({
983
+ refreshedOutputKeyCount: getObjectKeyCount(result.output),
984
+ returnedInput: !!result.input
985
+ })
986
+ },
987
+ () => (0, import_provider2.runWithContext)(context, () => {
988
+ if (authMethod.type === "auth.oauth") {
989
+ return authMethod.handleTokenRefresh({
990
+ output: params.output,
991
+ input: params.input,
992
+ clientId: params.clientId,
993
+ clientSecret: params.clientSecret,
994
+ scopes: params.scopes,
995
+ config: getAuthConfig()
996
+ });
997
+ }
998
+ return authMethod.handleTokenRefresh({
999
+ output: params.output,
1000
+ input: params.input,
1001
+ clientId: params.clientId,
1002
+ clientSecret: params.clientSecret,
1003
+ scopes: params.scopes,
1004
+ config: getAuthConfig()
1005
+ });
1006
+ })
1007
+ );
1008
+ return withRequestTraces(context, {
1009
+ output: refreshRes.output,
1010
+ input: refreshRes.input
1011
+ });
1012
+ }
1013
+ throw new import_error4.ServiceError(
1014
+ (0, import_error4.preconditionFailedError)({
1015
+ message: `Authentication method does not support token refresh handling: ${params.authenticationMethodId}`
1016
+ })
1017
+ );
1018
+ });
1019
+ manager.onRequest("slates/actions.list", async ({ params }) => {
1020
+ getContextBasic();
1021
+ let actions = getExposedActions(
1022
+ slate,
1023
+ !!params.includeAdapterActions && supportsAdapters()
1024
+ );
1025
+ if (!supportsTriggerGroups()) {
1026
+ actions = actions.filter((action) => action.type !== "trigger");
1027
+ }
1028
+ return {
1029
+ actions: actions.map((a) => mapAction(slate, a))
1030
+ };
1031
+ });
1032
+ manager.onRequest("slates/adapters.list", async () => {
1033
+ getContextBasic();
1034
+ return {
1035
+ adapters: supportsAdapters() ? (slate.adapters ?? []).map(mapAdapter) : []
1036
+ };
1037
+ });
1038
+ manager.onRequest("slates/adapter.get", async ({ params }) => {
1039
+ getContextBasic();
1040
+ if (!supportsAdapters()) {
1041
+ throw new import_error4.ServiceError((0, import_error4.notFoundError)(`adapter`, params.adapterId));
1042
+ }
1043
+ let adapter = getAdapter(slate, params.adapterId);
1044
+ return {
1045
+ adapter: mapAdapter(adapter)
1046
+ };
1047
+ });
1048
+ manager.onRequest("slates/action.get", async ({ params }) => {
1049
+ getContextBasic();
1050
+ let action = getExposedAction(slate, params.actionId, supportsAdapters());
1051
+ return {
1052
+ action: mapAction(slate, action)
1053
+ };
1054
+ });
1055
+ manager.onRequest("slates/trigger_groups.list", async () => {
1056
+ getContextBasic();
1057
+ return {
1058
+ triggerGroups: getExposedTriggerGroups(slate, supportsAdapters()).map(mapTriggerGroup)
1059
+ };
1060
+ });
1061
+ manager.onRequest("slates/tool_categories.list", async () => {
1062
+ getContextBasic();
1063
+ return {
1064
+ toolCategories: getExposedToolCategories(slate, supportsAdapters()).map(
1065
+ mapToolCategory
1066
+ )
1067
+ };
1068
+ });
1069
+ manager.onRequest("slates/trigger_group.get", async ({ params }) => {
1070
+ getContextBasic();
1071
+ let triggerGroup = getTriggerGroup(slate, params.triggerGroupId);
1072
+ return {
1073
+ triggerGroup: mapTriggerGroup(triggerGroup)
1074
+ };
1075
+ });
1076
+ manager.onRequest("slates/action.tool.invoke", async ({ params }) => {
1077
+ let action = getActionWithType(slate, "tool", params.actionId);
1078
+ let input = validate(
1079
+ action.inputSchema,
1080
+ params.input,
1081
+ "input",
1082
+ `Invalid input for tool ID: ${params.actionId}`
1083
+ );
1084
+ let invoke = async (context) => {
1085
+ let res = await traceProviderCall(
1086
+ {
1087
+ component: "action",
1088
+ functionName: "handleInvocation",
1089
+ message: `Starting tool ${formatEntityLabel(action.name, action.key)}`,
1090
+ successMessage: `Completed tool ${formatEntityLabel(action.name, action.key)}`,
1091
+ errorMessage: `Tool ${formatEntityLabel(action.name, action.key)} failed`,
1092
+ metadata: {
1093
+ actionId: action.key,
1094
+ actionName: action.name,
1095
+ actionType: action.type,
1096
+ isPublic: action.isPublic,
1097
+ inputKeyCount: getObjectKeyCount(input)
1098
+ },
1099
+ onSuccess: (result) => ({
1100
+ hasMessage: !!result.message,
1101
+ actionResultMessage: result.message,
1102
+ outputKeyCount: getObjectKeyCount(result.output),
1103
+ attachmentCount: result.attachments?.length
1104
+ })
1105
+ },
1106
+ () => (0, import_provider2.runWithContext)(context, () => action.handleInvocation(context))
1107
+ );
1108
+ let contextAttachments = await context._finalizeAttachments();
1109
+ let merged = mergeAttachments(
1110
+ [...res.attachments ?? [], ...contextAttachments],
1111
+ res.output
1112
+ );
1113
+ let redacted = (0, import_provider2.redactUrlAttachmentSecrets)(
1114
+ merged,
1115
+ context._getAuthConfigForRedaction()
1116
+ );
1117
+ let finalAttachments = await routeAttachmentsThroughDirectUpload(
1118
+ redacted,
1119
+ getLiveInvocation()
1120
+ );
1121
+ return withRequestTraces(context, {
1122
+ output: res.output,
1123
+ message: res.message,
1124
+ attachments: finalAttachments
1125
+ });
1126
+ };
1127
+ if (action.isPublic) {
1128
+ getContextBasic();
1129
+ return invoke(new import_provider2.SlatePublicContext(input, slate.spec, logger, getLiveInvocation()));
1130
+ }
1131
+ let ctx = getContextFull();
1132
+ return invoke(
1133
+ new import_provider2.SlateContext(
1134
+ ctx.config,
1135
+ input,
1136
+ ctx.auth?.output,
1137
+ slate.spec,
1138
+ logger,
1139
+ getLiveInvocation()
1140
+ )
1141
+ );
1142
+ });
1143
+ manager.onRequest("slates/action.trigger.map_event", async ({ params }) => {
1144
+ let ctx = getContextFull();
1145
+ let action = getActionWithType(slate, "trigger", params.actionId);
1146
+ let input = validate(
1147
+ action.inputSchema,
1148
+ params.input,
1149
+ "input",
1150
+ `Invalid event for trigger ID: ${params.actionId}`
1151
+ );
1152
+ let context = new import_provider2.SlateContext(ctx.config, input, ctx.auth?.output, slate.spec, logger);
1153
+ let res = await traceProviderCall(
1154
+ {
1155
+ component: "action",
1156
+ functionName: "handleEvent",
1157
+ message: `Mapping event for trigger ${formatEntityLabel(action.name, action.key)}`,
1158
+ successMessage: (result) => `Mapped trigger event "${result.type}" for ${formatEntityLabel(action.name, action.key)}`,
1159
+ errorMessage: `Trigger ${formatEntityLabel(action.name, action.key)} failed while mapping an event`,
1160
+ metadata: {
1161
+ actionId: action.key,
1162
+ actionName: action.name,
1163
+ actionType: action.type,
1164
+ inputKeyCount: getObjectKeyCount(input)
1165
+ },
1166
+ onSuccess: (result) => ({
1167
+ eventType: result.type,
1168
+ hasEventId: !!result.id,
1169
+ outputKeyCount: getObjectKeyCount(result.output)
1170
+ })
1171
+ },
1172
+ () => (0, import_provider2.runWithContext)(context, () => action.map(context))
1173
+ );
1174
+ return withRequestTraces(context, { id: res.id, type: res.type, output: res.output });
1175
+ });
1176
+ manager.onRequest("slates/action.trigger.poll_events", async ({ params }) => {
1177
+ getContextBasic();
1178
+ if (supportsTriggerGroups()) {
1179
+ throw new import_error4.ServiceError(
1180
+ (0, import_error4.badRequestError)({
1181
+ message: `Legacy trigger polling is disabled once trigger_group support is announced: ${params.actionId}`
1182
+ })
1183
+ );
1184
+ }
1185
+ return { inputs: [], updatedState: params.state };
1186
+ });
1187
+ manager.onRequest("slates/action.trigger.webhook_handle", async ({ params }) => {
1188
+ getContextBasic();
1189
+ if (supportsTriggerGroups()) {
1190
+ throw new import_error4.ServiceError(
1191
+ (0, import_error4.badRequestError)({
1192
+ message: `Legacy trigger webhook handling is disabled once trigger_group support is announced: ${params.actionId}`
1193
+ })
1194
+ );
1195
+ }
1196
+ return { inputs: [], updatedState: params.state, response: null };
1197
+ });
1198
+ manager.onRequest("slates/action.trigger.webhook_register", async ({ params }) => {
1199
+ getContextBasic();
1200
+ if (supportsTriggerGroups()) {
1201
+ throw new import_error4.ServiceError(
1202
+ (0, import_error4.badRequestError)({
1203
+ message: `Legacy trigger webhook registration is disabled once trigger_group support is announced: ${params.actionId}`
1204
+ })
1205
+ );
1206
+ }
1207
+ return { registrationDetails: null };
1208
+ });
1209
+ manager.onRequest("slates/action.trigger.webhook_unregister", async ({ params }) => {
1210
+ getContextBasic();
1211
+ if (supportsTriggerGroups()) {
1212
+ throw new import_error4.ServiceError(
1213
+ (0, import_error4.badRequestError)({
1214
+ message: `Legacy trigger webhook unregistration is disabled once trigger_group support is announced: ${params.actionId}`
1215
+ })
1216
+ );
1217
+ }
1218
+ return {};
1219
+ });
1220
+ manager.onRequest("slates/trigger_group.webhook.targets_list", async ({ params }) => {
1221
+ let ctx = getContextFull();
1222
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1223
+ let autoRegistration = getWebhookAutoRegistration(group);
1224
+ let context = new import_provider2.SlateContext(
1225
+ ctx.config,
1226
+ { pageToken: params.pageToken ?? null },
1227
+ ctx.auth?.output,
1228
+ slate.spec,
1229
+ logger
1230
+ );
1231
+ let res = await traceProviderCall(
1232
+ {
1233
+ component: "action",
1234
+ functionName: "webhookTargetList",
1235
+ message: `Listing webhook targets for trigger group ${formatEntityLabel(group.name, group.key)}`,
1236
+ successMessage: (result) => `Listed ${result.targets.length} webhook target(s) for trigger group ${formatEntityLabel(group.name, group.key)}`,
1237
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while listing webhook targets`,
1238
+ metadata: {
1239
+ triggerGroupId: group.key,
1240
+ triggerGroupName: group.name
1241
+ },
1242
+ onSuccess: (result) => ({
1243
+ targetCount: result.targets.length,
1244
+ hasNextPageToken: result.nextPageToken !== null
1245
+ })
1246
+ },
1247
+ () => (0, import_provider2.runWithContext)(context, () => autoRegistration.webhookTargetList(context))
1248
+ );
1249
+ return withRequestTraces(context, {
1250
+ targets: res.targets,
1251
+ nextPageToken: res.nextPageToken ?? null,
1252
+ isPartial: res.isPartial ?? false
1253
+ });
1254
+ });
1255
+ manager.onRequest("slates/trigger_group.webhook.register", async ({ params }) => {
1256
+ let ctx = getContextFull();
1257
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1258
+ let autoRegistration = getWebhookAutoRegistration(group);
1259
+ let context = new import_provider2.SlateContext(
1260
+ ctx.config,
1261
+ {
1262
+ webhookTargetIdentifier: params.webhookTargetIdentifier,
1263
+ webhookTargetPayload: params.webhookTargetPayload,
1264
+ webhookUrl: params.webhookUrl
1265
+ },
1266
+ ctx.auth?.output,
1267
+ slate.spec,
1268
+ logger
1269
+ );
1270
+ let res = await traceProviderCall(
1271
+ {
1272
+ component: "action",
1273
+ functionName: "webhookRegister",
1274
+ message: `Registering webhook for trigger group ${formatEntityLabel(group.name, group.key)}`,
1275
+ successMessage: `Registered webhook for trigger group ${formatEntityLabel(group.name, group.key)}`,
1276
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while registering a webhook`,
1277
+ metadata: {
1278
+ triggerGroupId: group.key,
1279
+ triggerGroupName: group.name,
1280
+ webhookTargetIdentifier: params.webhookTargetIdentifier
1281
+ }
1282
+ },
1283
+ () => (0, import_provider2.runWithContext)(context, () => autoRegistration.webhookRegister(context))
1284
+ );
1285
+ return withRequestTraces(context, {
1286
+ webhookRegistrationIdentifier: res.webhookRegistrationIdentifier,
1287
+ webhookRegistrationPayload: res.webhookRegistrationPayload
1288
+ });
1289
+ });
1290
+ manager.onRequest("slates/trigger_group.webhook.unregister", async ({ params }) => {
1291
+ let ctx = getContextFull();
1292
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1293
+ let autoRegistration = getWebhookAutoRegistration(group);
1294
+ let context = new import_provider2.SlateContext(
1295
+ ctx.config,
1296
+ {
1297
+ webhookRegistrationIdentifier: params.webhookRegistrationIdentifier,
1298
+ webhookRegistrationPayload: params.webhookRegistrationPayload
1299
+ },
1300
+ ctx.auth?.output,
1301
+ slate.spec,
1302
+ logger
1303
+ );
1304
+ await traceProviderCall(
1305
+ {
1306
+ component: "action",
1307
+ functionName: "webhookUnregister",
1308
+ message: `Unregistering webhook for trigger group ${formatEntityLabel(group.name, group.key)}`,
1309
+ successMessage: `Unregistered webhook for trigger group ${formatEntityLabel(group.name, group.key)}`,
1310
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while unregistering a webhook`,
1311
+ metadata: {
1312
+ triggerGroupId: group.key,
1313
+ triggerGroupName: group.name,
1314
+ webhookRegistrationIdentifier: params.webhookRegistrationIdentifier
1315
+ }
1316
+ },
1317
+ () => (0, import_provider2.runWithContext)(context, () => autoRegistration.webhookUnregister(context))
1318
+ );
1319
+ return withRequestTraces(context, {});
1320
+ });
1321
+ manager.onRequest("slates/trigger_group.webhook.manual_setup", async ({ params }) => {
1322
+ getContextBasic();
1323
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1324
+ let manualRegistration = getWebhookManualRegistration(group);
1325
+ let context = new import_provider2.SlateContext(
1326
+ {},
1327
+ { webhookUrl: params.webhookUrl },
1328
+ {},
1329
+ slate.spec,
1330
+ logger
1331
+ );
1332
+ let res = await traceProviderCall(
1333
+ {
1334
+ component: "action",
1335
+ functionName: "webhookManualSetup",
1336
+ message: `Building manual webhook setup for trigger group ${formatEntityLabel(group.name, group.key)}`,
1337
+ successMessage: `Built manual webhook setup for trigger group ${formatEntityLabel(group.name, group.key)}`,
1338
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while building a manual webhook setup`,
1339
+ metadata: {
1340
+ triggerGroupId: group.key,
1341
+ triggerGroupName: group.name
1342
+ }
1343
+ },
1344
+ () => (0, import_provider2.runWithContext)(context, () => manualRegistration.setup(context))
1345
+ );
1346
+ return {
1347
+ webhookSetupDocument: res.webhookSetupDocument,
1348
+ partialWebhookRegistrationPayload: res.partialWebhookRegistrationPayload
1349
+ };
1350
+ });
1351
+ manager.onRequest("slates/trigger_group.webhook.manual_finish", async ({ params }) => {
1352
+ getContextBasic();
1353
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1354
+ let manualRegistration = getWebhookManualRegistration(group);
1355
+ if (!manualRegistration.finish) {
1356
+ throw new import_error4.ServiceError(
1357
+ (0, import_error4.badRequestError)({
1358
+ message: `Trigger group does not support manual webhook finish: ${params.triggerGroupId}`
1359
+ })
1360
+ );
1361
+ }
1362
+ let context = new import_provider2.SlateContext(
1363
+ {},
1364
+ {
1365
+ webhookUrl: params.webhookUrl,
1366
+ partialWebhookRegistrationPayload: params.partialWebhookRegistrationPayload,
1367
+ userWebhookRegistrationPayload: params.userWebhookRegistrationPayload
1368
+ },
1369
+ {},
1370
+ slate.spec,
1371
+ logger
1372
+ );
1373
+ let res = await traceProviderCall(
1374
+ {
1375
+ component: "action",
1376
+ functionName: "webhookManualFinish",
1377
+ message: `Finishing manual webhook setup for trigger group ${formatEntityLabel(group.name, group.key)}`,
1378
+ successMessage: `Finished manual webhook setup for trigger group ${formatEntityLabel(group.name, group.key)}`,
1379
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while finishing a manual webhook setup`,
1380
+ metadata: {
1381
+ triggerGroupId: group.key,
1382
+ triggerGroupName: group.name
1383
+ }
1384
+ },
1385
+ () => (0, import_provider2.runWithContext)(context, () => manualRegistration.finish(context))
1386
+ );
1387
+ return withRequestTraces(context, {
1388
+ webhookRegistrationPayload: res.webhookRegistrationPayload
1389
+ });
1390
+ });
1391
+ manager.onRequest("slates/trigger_group.webhook.process", async ({ params }) => {
1392
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1393
+ if (group.source !== "webhook" || !group.webhook) {
1394
+ throw new import_error4.ServiceError(
1395
+ (0, import_error4.badRequestError)({
1396
+ message: `Trigger group does not support webhook processing: ${params.triggerGroupId}`
1397
+ })
1398
+ );
1399
+ }
1400
+ let req = new Request(params.url, {
1401
+ method: params.method,
1402
+ headers: params.headers,
1403
+ body: params.body ? Uint8Array.from(atob(params.body.content), (c) => c.charCodeAt(0)) : null
1404
+ });
1405
+ let context = new import_provider2.SlateContext(
1406
+ {},
1407
+ {
1408
+ request: req,
1409
+ webhookRegistrationPayload: params.webhookRegistrationPayload
1410
+ },
1411
+ {},
1412
+ slate.spec,
1413
+ logger
1414
+ );
1415
+ let res = await traceProviderCall(
1416
+ {
1417
+ component: "action",
1418
+ functionName: "webhookProcess",
1419
+ message: `Processing webhook request for trigger group ${formatEntityLabel(group.name, group.key)}`,
1420
+ successMessage: (result) => `Extracted ${result.events.length} event(s) from webhook request for trigger group ${formatEntityLabel(group.name, group.key)}`,
1421
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while processing a webhook request`,
1422
+ metadata: {
1423
+ triggerGroupId: group.key,
1424
+ triggerGroupName: group.name,
1425
+ requestMethod: params.method,
1426
+ hasRequestBody: !!params.body
1427
+ },
1428
+ onSuccess: (result) => ({
1429
+ eventCount: result.events.length,
1430
+ hasResponse: result.response !== void 0,
1431
+ skipped: !!result.skipped
1432
+ })
1433
+ },
1434
+ () => (0, import_provider2.runWithContext)(context, () => group.webhook.process(context))
1435
+ );
1436
+ for (let event of res.events) {
1437
+ if (!event.matchers) {
1438
+ throw new import_error4.ServiceError(
1439
+ (0, import_error4.preconditionFailedError)({
1440
+ message: `Trigger group "${group.key}" process handler must return matchers for every event (return [] if there is nothing to assert)`
1441
+ })
1442
+ );
1443
+ }
1444
+ }
1445
+ let response = res.response === void 0 ? void 0 : await serializeWebhookHttpResponse(res.response);
1446
+ return withRequestTraces(context, {
1447
+ events: res.events.map((event) => ({
1448
+ matchers: event.matchers,
1449
+ payload: event.payload,
1450
+ idempotencyKey: event.idempotencyKey,
1451
+ triggerIds: evaluateTriggerMatches(slate, group.key, event.payload)
1452
+ })),
1453
+ response,
1454
+ skipped: res.skipped ?? null
1455
+ });
1456
+ });
1457
+ manager.onRequest("slates/trigger_group.routing_matchers.get", async ({ params }) => {
1458
+ let ctx = getContextFull();
1459
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1460
+ let context = new import_provider2.SlateContext(ctx.config, {}, ctx.auth?.output, slate.spec, logger);
1461
+ let matchers = await traceProviderCall(
1462
+ {
1463
+ component: "action",
1464
+ functionName: "routingMatchers",
1465
+ message: `Getting routing matchers for trigger group ${formatEntityLabel(group.name, group.key)}`,
1466
+ successMessage: (result) => `Retrieved ${result.length} routing matcher(s) for trigger group ${formatEntityLabel(group.name, group.key)}`,
1467
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while getting routing matchers`,
1468
+ metadata: {
1469
+ triggerGroupId: group.key,
1470
+ triggerGroupName: group.name
1471
+ },
1472
+ onSuccess: (result) => ({
1473
+ matcherCount: result.length
1474
+ })
1475
+ },
1476
+ () => (0, import_provider2.runWithContext)(context, () => group.routingMatchers(context))
1477
+ );
1478
+ return withRequestTraces(context, { matchers });
1479
+ });
1480
+ manager.onRequest("slates/trigger_group.polling.poll", async ({ params }) => {
1481
+ let ctx = getContextFull();
1482
+ let group = getTriggerGroup(slate, params.triggerGroupId);
1483
+ if (group.source !== "polling" || !group.polling) {
1484
+ throw new import_error4.ServiceError(
1485
+ (0, import_error4.badRequestError)({
1486
+ message: `Trigger group does not support polling: ${params.triggerGroupId}`
1487
+ })
1488
+ );
1489
+ }
1490
+ let context = new import_provider2.SlateContext(
1491
+ ctx.config,
1492
+ { state: params.state },
1493
+ ctx.auth?.output,
1494
+ slate.spec,
1495
+ logger
1496
+ );
1497
+ let res = await traceProviderCall(
1498
+ {
1499
+ component: "action",
1500
+ functionName: "pollEvents",
1501
+ message: `Polling events for trigger group ${formatEntityLabel(group.name, group.key)}`,
1502
+ successMessage: (result) => `Polled ${result.events.length} event(s) for trigger group ${formatEntityLabel(group.name, group.key)}`,
1503
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while polling events`,
1504
+ metadata: {
1505
+ triggerGroupId: group.key,
1506
+ triggerGroupName: group.name,
1507
+ hasPreviousState: params.state !== null
1508
+ },
1509
+ onSuccess: (result) => ({
1510
+ eventCount: result.events.length,
1511
+ hasUpdatedState: result.updatedState !== void 0
1512
+ })
1513
+ },
1514
+ () => (0, import_provider2.runWithContext)(context, () => group.polling.pollEvents(context))
1515
+ );
1516
+ return withRequestTraces(context, {
1517
+ updatedState: res.updatedState,
1518
+ events: res.events.map((event) => ({
1519
+ payload: event.payload,
1520
+ idempotencyKey: event.idempotencyKey,
1521
+ triggerIds: evaluateTriggerMatches(slate, group.key, event.payload)
1522
+ }))
1523
+ });
1524
+ });
1525
+ let getGatewayTriggerGroup = (triggerGroupId) => {
1526
+ let group = getTriggerGroup(slate, triggerGroupId);
1527
+ if (group.source !== "gateway" || !group.gateway) {
1528
+ throw new import_error4.ServiceError(
1529
+ (0, import_error4.badRequestError)({
1530
+ message: `Trigger group does not support gateway connections: ${triggerGroupId}`
1531
+ })
1532
+ );
1533
+ }
1534
+ return { group, gateway: group.gateway };
1535
+ };
1536
+ manager.onRequest("slates/trigger_group.gateway.connect", async ({ params }) => {
1537
+ let ctx = getContextFull();
1538
+ let { group, gateway } = getGatewayTriggerGroup(params.triggerGroupId);
1539
+ let context = new import_provider2.SlateContext(
1540
+ ctx.config,
1541
+ { state: params.state },
1542
+ ctx.auth?.output,
1543
+ slate.spec,
1544
+ logger
1545
+ );
1546
+ let res = await traceProviderCall(
1547
+ {
1548
+ component: "action",
1549
+ functionName: "gatewayConnect",
1550
+ message: `Preparing gateway connection for trigger group ${formatEntityLabel(group.name, group.key)}`,
1551
+ successMessage: () => `Prepared gateway connection for trigger group ${formatEntityLabel(group.name, group.key)}`,
1552
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while preparing a gateway connection`,
1553
+ metadata: {
1554
+ triggerGroupId: group.key,
1555
+ triggerGroupName: group.name,
1556
+ hasPreviousState: params.state !== null
1557
+ }
1558
+ },
1559
+ () => (0, import_provider2.runWithContext)(context, () => gateway.connect(context))
1560
+ );
1561
+ return withRequestTraces(context, { url: res.url, state: res.state });
1562
+ });
1563
+ manager.onRequest("slates/trigger_group.gateway.receive", async ({ params }) => {
1564
+ let ctx = getContextFull();
1565
+ let { group, gateway } = getGatewayTriggerGroup(params.triggerGroupId);
1566
+ let context = new import_provider2.SlateContext(
1567
+ ctx.config,
1568
+ { state: params.state, frames: params.frames, closed: params.closed ?? null },
1569
+ ctx.auth?.output,
1570
+ slate.spec,
1571
+ logger
1572
+ );
1573
+ let res = await traceProviderCall(
1574
+ {
1575
+ component: "action",
1576
+ functionName: "gatewayReceive",
1577
+ message: `Handling ${params.frames.length} gateway frame(s) for trigger group ${formatEntityLabel(group.name, group.key)}`,
1578
+ successMessage: (result) => `Handled gateway frames for trigger group ${formatEntityLabel(group.name, group.key)} (${result.events?.length ?? 0} event(s))`,
1579
+ errorMessage: `Trigger group ${formatEntityLabel(group.name, group.key)} failed while handling gateway frames`,
1580
+ metadata: {
1581
+ triggerGroupId: group.key,
1582
+ triggerGroupName: group.name,
1583
+ frameCount: params.frames.length,
1584
+ closed: params.closed ?? null
1585
+ },
1586
+ onSuccess: (result) => ({
1587
+ eventCount: result.events?.length ?? 0,
1588
+ sendCount: result.send?.length ?? 0,
1589
+ close: result.close ?? null
1590
+ })
1591
+ },
1592
+ () => (0, import_provider2.runWithContext)(context, () => gateway.receive(context))
1593
+ );
1594
+ return withRequestTraces(context, {
1595
+ state: res.state,
1596
+ // Outbound frames (e.g. IDENTIFY) embed credentials; the hub restores them at the socket.
1597
+ send: new import_provider2.AuthConfigSecretRedactor(
1598
+ context._getAuthConfigForRedaction()
1599
+ ).redactEmbedded(res.send ?? []),
1600
+ heartbeat: res.heartbeat ?? null,
1601
+ heartbeatAcked: res.heartbeatAcked,
1602
+ close: res.close ?? null,
1603
+ events: (res.events ?? []).map((event) => ({
1604
+ payload: event.payload,
1605
+ idempotencyKey: event.idempotencyKey,
1606
+ triggerIds: evaluateTriggerMatches(slate, group.key, event.payload)
1607
+ }))
1608
+ });
1609
+ });
1610
+ });
1611
+ // Annotate the CommonJS export names for ESM import in node:
1612
+ 0 && (module.exports = {
1613
+ createProviderHandler
1614
+ });