-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathtrigger.py
More file actions
422 lines (347 loc) · 14.8 KB
/
trigger.py
File metadata and controls
422 lines (347 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
from collections.abc import Mapping
from enum import Enum, StrEnum
from typing import Any, Union
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from werkzeug import Response
from dify_plugin.core.documentation.schema_doc import docs
from dify_plugin.core.runtime import Session
from dify_plugin.core.utils.yaml_loader import load_yaml_file
from dify_plugin.entities import I18nObject, ParameterOption
from dify_plugin.entities.oauth import OAuthSchema
from dify_plugin.entities.provider_config import CommonParameterType, CredentialType, ProviderConfig
from dify_plugin.entities.tool import ParameterAutoGenerate, ParameterTemplate
class TriggerSubscriptionConstructorRuntime:
session: Session
credentials: Mapping[str, Any] | None
credential_type: CredentialType
def __init__(
self,
session: Session,
credential_type: CredentialType,
credentials: Mapping[str, Any] | None = None,
):
self.session = session
self.credentials = credentials
self.credential_type = credential_type
class EventDispatch(BaseModel):
"""
The dispatch result from a trigger when processing an incoming webhook.
Contains the list of Event names that should be invoked and the HTTP response
to return to the webhook caller.
Supports dispatching single or multiple Events from a single webhook call.
When multiple Events are specified, each Event will transform the webhook
and trigger its corresponding workflow.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
user_id: str = Field(default="", description="The user who triggered the event (e.g. google user ID)")
events: list[str] = Field(default_factory=list, description="List of Event names that should be invoked.")
response: Response = Field(
...,
description="The HTTP Response object returned to third-party calls. For example, webhook calls, etc.",
)
payload: Mapping[str, Any] = Field(
default_factory=dict,
description="Decoded payload from the webhook request, which will be delivered into `_on_event` method.",
)
@docs(
description="The structured output variables from an event",
)
class Variables(BaseModel):
"""
The structured output variables from an event after processing.
Contains the extracted and transformed variables that will be passed to workflows.
The structure of variables must match the output_schema defined in the event's YAML configuration.
"""
variables: Mapping[str, Any] = Field(
...,
description="The output variables of the event, same with the schema defined in `output_schema` in the YAML",
)
@docs(
description="The option of the event parameter",
)
class EventParameterOption(ParameterOption):
"""
The option of the event parameter
"""
@docs(
description="The type of the parameter",
)
class EventParameter(BaseModel):
"""
The parameter of the event
"""
@docs(
description="The type options for event parameter",
)
class EventParameterType(StrEnum):
STRING = CommonParameterType.STRING.value
NUMBER = CommonParameterType.NUMBER.value
BOOLEAN = CommonParameterType.BOOLEAN.value
SELECT = CommonParameterType.SELECT.value
CHECKBOX = CommonParameterType.CHECKBOX.value
FILE = CommonParameterType.FILE.value
FILES = CommonParameterType.FILES.value
MODEL_SELECTOR = CommonParameterType.MODEL_SELECTOR.value
APP_SELECTOR = CommonParameterType.APP_SELECTOR.value
OBJECT = CommonParameterType.OBJECT.value
ARRAY = CommonParameterType.ARRAY.value
DYNAMIC_SELECT = CommonParameterType.DYNAMIC_SELECT.value
name: str = Field(..., description="The name of the parameter")
label: I18nObject = Field(..., description="The label presented to the user")
type: EventParameterType = Field(..., description="The type of the parameter")
auto_generate: ParameterAutoGenerate | None = Field(default=None, description="The auto generate of the parameter")
template: ParameterTemplate | None = Field(default=None, description="The template of the parameter")
scope: str | None = None
required: bool | None = False
multiple: bool | None = Field(
default=False,
description="Whether the parameter is multiple select, only valid for select or dynamic-select type",
)
default: Union[int, float, str, list] | None = None
min: Union[float, int] | None = None
max: Union[float, int] | None = None
precision: int | None = None
options: list[EventParameterOption] | None = None
description: I18nObject | None = None
@docs(
description="The labels for event",
)
class EventLabelEnum(Enum):
WEBHOOKS = "webhooks"
@docs(
description="The identity of the trigger provider",
)
class TriggerProviderIdentity(BaseModel):
"""
The identity of the trigger provider
"""
author: str = Field(..., description="The author of the trigger provider")
name: str = Field(..., description="The name of the trigger provider")
label: I18nObject = Field(..., description="The label of the trigger provider")
description: I18nObject = Field(..., description="The description of the trigger provider")
icon: str | None = Field(default=None, description="The icon of the trigger provider")
icon_dark: str | None = Field(default=None, description="The dark mode icon of the trigger provider")
tags: list[EventLabelEnum] = Field(default_factory=list, description="The tags of the trigger provider")
@docs(
description="The identity of an event",
)
class EventIdentity(BaseModel):
"""
The identity of an event
"""
author: str = Field(..., description="The author of the event")
name: str = Field(..., description="The name of the event")
label: I18nObject = Field(..., description="The label of the event")
@docs(
description="The description of an event",
)
class EventDescription(BaseModel):
"""
The description of an event
"""
human: I18nObject = Field(..., description="Human readable description")
llm: I18nObject = Field(..., description="LLM readable description")
@docs(
description="The extra configuration for an event",
)
class EventConfigurationExtra(BaseModel):
"""
The extra configuration for an event
"""
@docs(
name="Python",
description="The python configuration for event",
)
class Python(BaseModel):
source: str = Field(..., description="The source file path for the event implementation")
python: Python
@docs(
description="The configuration of an event",
)
class EventConfiguration(BaseModel):
"""
The configuration of an event
"""
identity: EventIdentity = Field(..., description="The identity of the event")
parameters: list[EventParameter] = Field(default_factory=list, description="The parameters of the event")
description: I18nObject = Field(..., description="The description of the event")
extra: EventConfigurationExtra = Field(..., description="The extra configuration of the event")
output_schema: Mapping[str, Any] | None = Field(
default=None, description="The output schema that this event produces"
)
@docs(
description="The extra configuration for trigger provider",
)
class TriggerProviderConfigurationExtra(BaseModel):
"""
The extra configuration for trigger provider
"""
@docs(
name="Python",
description="The python configuration for trigger provider",
)
class Python(BaseModel):
source: str = Field(..., description="The source file path for the trigger provider implementation")
python: Python
@docs(
description="The subscription constructor configuration of the trigger provider",
)
class TriggerSubscriptionConstructorConfigurationExtra(BaseModel):
"""Additional configuration for trigger subscription constructor."""
@docs(
name="Python",
description="The python configuration for trigger subscription constructor",
)
class Python(BaseModel):
source: str = Field(..., description="The source file path for the constructor implementation")
python: Python
@docs(
name="TriggerSubscriptionConstructor",
description="Configuration for a trigger subscription constructor",
)
class TriggerSubscriptionConstructorConfiguration(BaseModel):
"""Configuration for a trigger subscription constructor implementation."""
parameters: list[EventParameter] = Field(
default_factory=list,
description="The user input parameters required to create a subscription",
)
credentials_schema: list[ProviderConfig] = Field(
default_factory=list,
description="The credentials schema required by the subscription constructor",
)
oauth_schema: OAuthSchema | None = Field(
default=None,
description="The OAuth schema of the subscription constructor if OAuth is supported",
)
extra: TriggerSubscriptionConstructorConfigurationExtra | None = Field(
default=None,
description="Extra metadata for locating the constructor implementation",
)
@model_validator(mode="before")
@classmethod
def normalize_credentials_schema(cls, data: Any) -> dict[str, Any]:
if data is None:
return {}
if isinstance(data, cls):
return data.model_dump()
if not isinstance(data, dict):
raise ValueError("subscription_constructor should be defined as a mapping")
normalised = dict(data)
original_credentials_schema = normalised.get("credentials_schema", [])
if isinstance(original_credentials_schema, dict):
credentials_schema: list[dict[str, Any]] = []
for name, param in original_credentials_schema.items():
param["name"] = name
credentials_schema.append(param)
normalised["credentials_schema"] = credentials_schema
elif isinstance(original_credentials_schema, list):
normalised["credentials_schema"] = original_credentials_schema
else:
raise ValueError("credentials_schema should be a list or dict")
return normalised
@docs(
name="TriggerProvider",
description="The configuration of a trigger provider",
outside_reference_fields={"events": EventConfiguration},
)
class TriggerProviderConfiguration(BaseModel):
"""
The configuration of a trigger provider
"""
identity: TriggerProviderIdentity = Field(..., description="The identity of the trigger provider")
subscription_schema: list[ProviderConfig] = Field(
default_factory=list,
description="The credentials schema of the trigger provider",
)
subscription_constructor: TriggerSubscriptionConstructorConfiguration | None = Field(
default=None,
description="The configuration of the trigger subscription constructor",
)
events: list[EventConfiguration] = Field(default=[], description="The Events of the trigger")
extra: TriggerProviderConfigurationExtra = Field(..., description="The extra configuration of the trigger provider")
@model_validator(mode="before")
@classmethod
def validate_credentials_schema(cls, data: dict) -> dict:
# Handle credentials_schema conversion from dict to list format
original_credentials_schema = data.get("credentials_schema", [])
if isinstance(original_credentials_schema, dict):
credentials_schema: list[dict[str, Any]] = []
for name, param in original_credentials_schema.items():
param["name"] = name
credentials_schema.append(param)
data["credentials_schema"] = credentials_schema
elif isinstance(original_credentials_schema, list):
data["credentials_schema"] = original_credentials_schema
else:
raise ValueError("credentials_schema should be a list or dict")
return data
@field_validator("events", mode="before")
@classmethod
def validate_events(cls, value) -> list[EventConfiguration]:
if not isinstance(value, list):
raise ValueError("events should be a list")
events: list[EventConfiguration] = []
for event in value:
# read from yaml
if not isinstance(event, str):
raise ValueError("event path should be a string")
try:
file = load_yaml_file(event)
events.append(
EventConfiguration(
identity=EventIdentity(**file["identity"]),
parameters=[EventParameter(**param) for param in file.get("parameters", []) or []],
description=I18nObject(**file["description"]),
extra=EventConfigurationExtra(**file.get("extra", {})),
output_schema=file.get("output_schema", None),
)
)
except Exception as e:
raise ValueError(f"Error loading event configuration: {e!s}") from e
return events
@docs(
description="Result of a successful trigger subscription operation",
)
class Subscription(BaseModel):
"""
Result of a successful trigger subscription operation.
Contains all information needed to manage the subscription lifecycle.
"""
expires_at: int = Field(
default=-1,
description=(
"The timestamp when the subscription will expire, used for refreshing the subscription. "
"Set to -1 if the subscription does not expire"
),
)
endpoint: str = Field(..., description="The webhook endpoint URL allocated by Dify for receiving events")
parameters: Mapping[str, Any] | None = Field(
default=None,
description=(
"The parameters of the subscription, only available when the subscription "
"is created by the trigger subscription constructor"
),
)
properties: Mapping[str, Any] = Field(
default_factory=dict,
description=(
"The necessary information for this subscription, e.g., external_id, events, repository, etc. "
"These properties are defined in `subscription_schema` in the provider's YAML"
),
)
@docs(
description="Result of a trigger unsubscription operation",
)
class UnsubscribeResult(BaseModel):
"""
Result of a trigger unsubscribe operation.
Provides detailed information about the unsubscribe attempt,
including success status and error details if failed.
"""
success: bool = Field(..., description="Whether the unsubscribe was successful")
message: str | None = Field(
None,
description="Human-readable message about the operation result. "
"Success message for successful operations, "
"detailed error information for failures.",
)