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