@fkws/klonk 0.0.4 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +373 -0
- package/README.md +401 -228
- package/package.json +1 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
Mozilla Public License Version 2.0
|
|
2
|
+
==================================
|
|
3
|
+
|
|
4
|
+
1. Definitions
|
|
5
|
+
--------------
|
|
6
|
+
|
|
7
|
+
1.1. "Contributor"
|
|
8
|
+
means each individual or legal entity that creates, contributes to
|
|
9
|
+
the creation of, or owns Covered Software.
|
|
10
|
+
|
|
11
|
+
1.2. "Contributor Version"
|
|
12
|
+
means the combination of the Contributions of others (if any) used
|
|
13
|
+
by a Contributor and that particular Contributor's Contribution.
|
|
14
|
+
|
|
15
|
+
1.3. "Contribution"
|
|
16
|
+
means Covered Software of a particular Contributor.
|
|
17
|
+
|
|
18
|
+
1.4. "Covered Software"
|
|
19
|
+
means Source Code Form to which the initial Contributor has attached
|
|
20
|
+
the notice in Exhibit A, the Executable Form of such Source Code
|
|
21
|
+
Form, and Modifications of such Source Code Form, in each case
|
|
22
|
+
including portions thereof.
|
|
23
|
+
|
|
24
|
+
1.5. "Incompatible With Secondary Licenses"
|
|
25
|
+
means
|
|
26
|
+
|
|
27
|
+
(a) that the initial Contributor has attached the notice described
|
|
28
|
+
in Exhibit B to the Covered Software; or
|
|
29
|
+
|
|
30
|
+
(b) that the Covered Software was made available under the terms of
|
|
31
|
+
version 1.1 or earlier of the License, but not also under the
|
|
32
|
+
terms of a Secondary License.
|
|
33
|
+
|
|
34
|
+
1.6. "Executable Form"
|
|
35
|
+
means any form of the work other than Source Code Form.
|
|
36
|
+
|
|
37
|
+
1.7. "Larger Work"
|
|
38
|
+
means a work that combines Covered Software with other material, in
|
|
39
|
+
a separate file or files, that is not Covered Software.
|
|
40
|
+
|
|
41
|
+
1.8. "License"
|
|
42
|
+
means this document.
|
|
43
|
+
|
|
44
|
+
1.9. "Licensable"
|
|
45
|
+
means having the right to grant, to the maximum extent possible,
|
|
46
|
+
whether at the time of the initial grant or subsequently, any and
|
|
47
|
+
all of the rights conveyed by this License.
|
|
48
|
+
|
|
49
|
+
1.10. "Modifications"
|
|
50
|
+
means any of the following:
|
|
51
|
+
|
|
52
|
+
(a) any file in Source Code Form that results from an addition to,
|
|
53
|
+
deletion from, or modification of the contents of Covered
|
|
54
|
+
Software; or
|
|
55
|
+
|
|
56
|
+
(b) any new file in Source Code Form that contains any Covered
|
|
57
|
+
Software.
|
|
58
|
+
|
|
59
|
+
1.11. "Patent Claims" of a Contributor
|
|
60
|
+
means any patent claim(s), including without limitation, method,
|
|
61
|
+
process, and apparatus claims, in any patent Licensable by such
|
|
62
|
+
Contributor that would be infringed, but for the grant of the
|
|
63
|
+
License, by the making, using, selling, offering for sale, having
|
|
64
|
+
made, import, or transfer of either its Contributions or its
|
|
65
|
+
Contributor Version.
|
|
66
|
+
|
|
67
|
+
1.12. "Secondary License"
|
|
68
|
+
means either the GNU General Public License, Version 2.0, the GNU
|
|
69
|
+
Lesser General Public License, Version 2.1, the GNU Affero General
|
|
70
|
+
Public License, Version 3.0, or any later versions of those
|
|
71
|
+
licenses.
|
|
72
|
+
|
|
73
|
+
1.13. "Source Code Form"
|
|
74
|
+
means the form of the work preferred for making modifications.
|
|
75
|
+
|
|
76
|
+
1.14. "You" (or "Your")
|
|
77
|
+
means an individual or a legal entity exercising rights under this
|
|
78
|
+
License. For legal entities, "You" includes any entity that
|
|
79
|
+
controls, is controlled by, or is under common control with You. For
|
|
80
|
+
purposes of this definition, "control" means (a) the power, direct
|
|
81
|
+
or indirect, to cause the direction or management of such entity,
|
|
82
|
+
whether by contract or otherwise, or (b) ownership of more than
|
|
83
|
+
fifty percent (50%) of the outstanding shares or beneficial
|
|
84
|
+
ownership of such entity.
|
|
85
|
+
|
|
86
|
+
2. License Grants and Conditions
|
|
87
|
+
--------------------------------
|
|
88
|
+
|
|
89
|
+
2.1. Grants
|
|
90
|
+
|
|
91
|
+
Each Contributor hereby grants You a world-wide, royalty-free,
|
|
92
|
+
non-exclusive license:
|
|
93
|
+
|
|
94
|
+
(a) under intellectual property rights (other than patent or trademark)
|
|
95
|
+
Licensable by such Contributor to use, reproduce, make available,
|
|
96
|
+
modify, display, perform, distribute, and otherwise exploit its
|
|
97
|
+
Contributions, either on an unmodified basis, with Modifications, or
|
|
98
|
+
as part of a Larger Work; and
|
|
99
|
+
|
|
100
|
+
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
|
101
|
+
for sale, have made, import, and otherwise transfer either its
|
|
102
|
+
Contributions or its Contributor Version.
|
|
103
|
+
|
|
104
|
+
2.2. Effective Date
|
|
105
|
+
|
|
106
|
+
The licenses granted in Section 2.1 with respect to any Contribution
|
|
107
|
+
become effective for each Contribution on the date the Contributor first
|
|
108
|
+
distributes such Contribution.
|
|
109
|
+
|
|
110
|
+
2.3. Limitations on Grant Scope
|
|
111
|
+
|
|
112
|
+
The licenses granted in this Section 2 are the only rights granted under
|
|
113
|
+
this License. No additional rights or licenses will be implied from the
|
|
114
|
+
distribution or licensing of Covered Software under this License.
|
|
115
|
+
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
|
116
|
+
Contributor:
|
|
117
|
+
|
|
118
|
+
(a) for any code that a Contributor has removed from Covered Software;
|
|
119
|
+
or
|
|
120
|
+
|
|
121
|
+
(b) for infringements caused by: (i) Your and any other third party's
|
|
122
|
+
modifications of Covered Software, or (ii) the combination of its
|
|
123
|
+
Contributions with other software (except as part of its Contributor
|
|
124
|
+
Version); or
|
|
125
|
+
|
|
126
|
+
(c) under Patent Claims infringed by Covered Software in the absence of
|
|
127
|
+
its Contributions.
|
|
128
|
+
|
|
129
|
+
This License does not grant any rights in the trademarks, service marks,
|
|
130
|
+
or logos of any Contributor (except as may be necessary to comply with
|
|
131
|
+
the notice requirements in Section 3.4).
|
|
132
|
+
|
|
133
|
+
2.4. Subsequent Licenses
|
|
134
|
+
|
|
135
|
+
No Contributor makes additional grants as a result of Your choice to
|
|
136
|
+
distribute the Covered Software under a subsequent version of this
|
|
137
|
+
License (see Section 10.2) or under the terms of a Secondary License (if
|
|
138
|
+
permitted under the terms of Section 3.3).
|
|
139
|
+
|
|
140
|
+
2.5. Representation
|
|
141
|
+
|
|
142
|
+
Each Contributor represents that the Contributor believes its
|
|
143
|
+
Contributions are its original creation(s) or it has sufficient rights
|
|
144
|
+
to grant the rights to its Contributions conveyed by this License.
|
|
145
|
+
|
|
146
|
+
2.6. Fair Use
|
|
147
|
+
|
|
148
|
+
This License is not intended to limit any rights You have under
|
|
149
|
+
applicable copyright doctrines of fair use, fair dealing, or other
|
|
150
|
+
equivalents.
|
|
151
|
+
|
|
152
|
+
2.7. Conditions
|
|
153
|
+
|
|
154
|
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
|
155
|
+
in Section 2.1.
|
|
156
|
+
|
|
157
|
+
3. Responsibilities
|
|
158
|
+
-------------------
|
|
159
|
+
|
|
160
|
+
3.1. Distribution of Source Form
|
|
161
|
+
|
|
162
|
+
All distribution of Covered Software in Source Code Form, including any
|
|
163
|
+
Modifications that You create or to which You contribute, must be under
|
|
164
|
+
the terms of this License. You must inform recipients that the Source
|
|
165
|
+
Code Form of the Covered Software is governed by the terms of this
|
|
166
|
+
License, and how they can obtain a copy of this License. You may not
|
|
167
|
+
attempt to alter or restrict the recipients' rights in the Source Code
|
|
168
|
+
Form.
|
|
169
|
+
|
|
170
|
+
3.2. Distribution of Executable Form
|
|
171
|
+
|
|
172
|
+
If You distribute Covered Software in Executable Form then:
|
|
173
|
+
|
|
174
|
+
(a) such Covered Software must also be made available in Source Code
|
|
175
|
+
Form, as described in Section 3.1, and You must inform recipients of
|
|
176
|
+
the Executable Form how they can obtain a copy of such Source Code
|
|
177
|
+
Form by reasonable means in a timely manner, at a charge no more
|
|
178
|
+
than the cost of distribution to the recipient; and
|
|
179
|
+
|
|
180
|
+
(b) You may distribute such Executable Form under the terms of this
|
|
181
|
+
License, or sublicense it under different terms, provided that the
|
|
182
|
+
license for the Executable Form does not attempt to limit or alter
|
|
183
|
+
the recipients' rights in the Source Code Form under this License.
|
|
184
|
+
|
|
185
|
+
3.3. Distribution of a Larger Work
|
|
186
|
+
|
|
187
|
+
You may create and distribute a Larger Work under terms of Your choice,
|
|
188
|
+
provided that You also comply with the requirements of this License for
|
|
189
|
+
the Covered Software. If the Larger Work is a combination of Covered
|
|
190
|
+
Software with a work governed by one or more Secondary Licenses, and the
|
|
191
|
+
Covered Software is not Incompatible With Secondary Licenses, this
|
|
192
|
+
License permits You to additionally distribute such Covered Software
|
|
193
|
+
under the terms of such Secondary License(s), so that the recipient of
|
|
194
|
+
the Larger Work may, at their option, further distribute the Covered
|
|
195
|
+
Software under the terms of either this License or such Secondary
|
|
196
|
+
License(s).
|
|
197
|
+
|
|
198
|
+
3.4. Notices
|
|
199
|
+
|
|
200
|
+
You may not remove or alter the substance of any license notices
|
|
201
|
+
(including copyright notices, patent notices, disclaimers of warranty,
|
|
202
|
+
or limitations of liability) contained within the Source Code Form of
|
|
203
|
+
the Covered Software, except that You may alter any license notices to
|
|
204
|
+
the extent required to remedy known factual inaccuracies.
|
|
205
|
+
|
|
206
|
+
3.5. Application of Additional Terms
|
|
207
|
+
|
|
208
|
+
You may choose to offer, and to charge a fee for, warranty, support,
|
|
209
|
+
indemnity or liability obligations to one or more recipients of Covered
|
|
210
|
+
Software. However, You may do so only on Your own behalf, and not on
|
|
211
|
+
behalf of any Contributor. You must make it absolutely clear that any
|
|
212
|
+
such warranty, support, indemnity, or liability obligation is offered by
|
|
213
|
+
You alone, and You hereby agree to indemnify every Contributor for any
|
|
214
|
+
liability incurred by such Contributor as a result of warranty, support,
|
|
215
|
+
indemnity or liability terms You offer. You may include additional
|
|
216
|
+
disclaimers of warranty and limitations of liability specific to any
|
|
217
|
+
jurisdiction.
|
|
218
|
+
|
|
219
|
+
4. Inability to Comply Due to Statute or Regulation
|
|
220
|
+
---------------------------------------------------
|
|
221
|
+
|
|
222
|
+
If it is impossible for You to comply with any of the terms of this
|
|
223
|
+
License with respect to some or all of the Covered Software due to
|
|
224
|
+
statute, judicial order, or regulation then You must: (a) comply with
|
|
225
|
+
the terms of this License to the maximum extent possible; and (b)
|
|
226
|
+
describe the limitations and the code they affect. Such description must
|
|
227
|
+
be placed in a text file included with all distributions of the Covered
|
|
228
|
+
Software under this License. Except to the extent prohibited by statute
|
|
229
|
+
or regulation, such description must be sufficiently detailed for a
|
|
230
|
+
recipient of ordinary skill to be able to understand it.
|
|
231
|
+
|
|
232
|
+
5. Termination
|
|
233
|
+
--------------
|
|
234
|
+
|
|
235
|
+
5.1. The rights granted under this License will terminate automatically
|
|
236
|
+
if You fail to comply with any of its terms. However, if You become
|
|
237
|
+
compliant, then the rights granted under this License from a particular
|
|
238
|
+
Contributor are reinstated (a) provisionally, unless and until such
|
|
239
|
+
Contributor explicitly and finally terminates Your grants, and (b) on an
|
|
240
|
+
ongoing basis, if such Contributor fails to notify You of the
|
|
241
|
+
non-compliance by some reasonable means prior to 60 days after You have
|
|
242
|
+
come back into compliance. Moreover, Your grants from a particular
|
|
243
|
+
Contributor are reinstated on an ongoing basis if such Contributor
|
|
244
|
+
notifies You of the non-compliance by some reasonable means, this is the
|
|
245
|
+
first time You have received notice of non-compliance with this License
|
|
246
|
+
from such Contributor, and You become compliant prior to 30 days after
|
|
247
|
+
Your receipt of the notice.
|
|
248
|
+
|
|
249
|
+
5.2. If You initiate litigation against any entity by asserting a patent
|
|
250
|
+
infringement claim (excluding declaratory judgment actions,
|
|
251
|
+
counter-claims, and cross-claims) alleging that a Contributor Version
|
|
252
|
+
directly or indirectly infringes any patent, then the rights granted to
|
|
253
|
+
You by any and all Contributors for the Covered Software under Section
|
|
254
|
+
2.1 of this License shall terminate.
|
|
255
|
+
|
|
256
|
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
|
257
|
+
end user license agreements (excluding distributors and resellers) which
|
|
258
|
+
have been validly granted by You or Your distributors under this License
|
|
259
|
+
prior to termination shall survive termination.
|
|
260
|
+
|
|
261
|
+
************************************************************************
|
|
262
|
+
* *
|
|
263
|
+
* 6. Disclaimer of Warranty *
|
|
264
|
+
* ------------------------- *
|
|
265
|
+
* *
|
|
266
|
+
* Covered Software is provided under this License on an "as is" *
|
|
267
|
+
* basis, without warranty of any kind, either expressed, implied, or *
|
|
268
|
+
* statutory, including, without limitation, warranties that the *
|
|
269
|
+
* Covered Software is free of defects, merchantable, fit for a *
|
|
270
|
+
* particular purpose or non-infringing. The entire risk as to the *
|
|
271
|
+
* quality and performance of the Covered Software is with You. *
|
|
272
|
+
* Should any Covered Software prove defective in any respect, You *
|
|
273
|
+
* (not any Contributor) assume the cost of any necessary servicing, *
|
|
274
|
+
* repair, or correction. This disclaimer of warranty constitutes an *
|
|
275
|
+
* essential part of this License. No use of any Covered Software is *
|
|
276
|
+
* authorized under this License except under this disclaimer. *
|
|
277
|
+
* *
|
|
278
|
+
************************************************************************
|
|
279
|
+
|
|
280
|
+
************************************************************************
|
|
281
|
+
* *
|
|
282
|
+
* 7. Limitation of Liability *
|
|
283
|
+
* -------------------------- *
|
|
284
|
+
* *
|
|
285
|
+
* Under no circumstances and under no legal theory, whether tort *
|
|
286
|
+
* (including negligence), contract, or otherwise, shall any *
|
|
287
|
+
* Contributor, or anyone who distributes Covered Software as *
|
|
288
|
+
* permitted above, be liable to You for any direct, indirect, *
|
|
289
|
+
* special, incidental, or consequential damages of any character *
|
|
290
|
+
* including, without limitation, damages for lost profits, loss of *
|
|
291
|
+
* goodwill, work stoppage, computer failure or malfunction, or any *
|
|
292
|
+
* and all other commercial damages or losses, even if such party *
|
|
293
|
+
* shall have been informed of the possibility of such damages. This *
|
|
294
|
+
* limitation of liability shall not apply to liability for death or *
|
|
295
|
+
* personal injury resulting from such party's negligence to the *
|
|
296
|
+
* extent applicable law prohibits such limitation. Some *
|
|
297
|
+
* jurisdictions do not allow the exclusion or limitation of *
|
|
298
|
+
* incidental or consequential damages, so this exclusion and *
|
|
299
|
+
* limitation may not apply to You. *
|
|
300
|
+
* *
|
|
301
|
+
************************************************************************
|
|
302
|
+
|
|
303
|
+
8. Litigation
|
|
304
|
+
-------------
|
|
305
|
+
|
|
306
|
+
Any litigation relating to this License may be brought only in the
|
|
307
|
+
courts of a jurisdiction where the defendant maintains its principal
|
|
308
|
+
place of business and such litigation shall be governed by laws of that
|
|
309
|
+
jurisdiction, without reference to its conflict-of-law provisions.
|
|
310
|
+
Nothing in this Section shall prevent a party's ability to bring
|
|
311
|
+
cross-claims or counter-claims.
|
|
312
|
+
|
|
313
|
+
9. Miscellaneous
|
|
314
|
+
----------------
|
|
315
|
+
|
|
316
|
+
This License represents the complete agreement concerning the subject
|
|
317
|
+
matter hereof. If any provision of this License is held to be
|
|
318
|
+
unenforceable, such provision shall be reformed only to the extent
|
|
319
|
+
necessary to make it enforceable. Any law or regulation which provides
|
|
320
|
+
that the language of a contract shall be construed against the drafter
|
|
321
|
+
shall not be used to construe this License against a Contributor.
|
|
322
|
+
|
|
323
|
+
10. Versions of the License
|
|
324
|
+
---------------------------
|
|
325
|
+
|
|
326
|
+
10.1. New Versions
|
|
327
|
+
|
|
328
|
+
Mozilla Foundation is the license steward. Except as provided in Section
|
|
329
|
+
10.3, no one other than the license steward has the right to modify or
|
|
330
|
+
publish new versions of this License. Each version will be given a
|
|
331
|
+
distinguishing version number.
|
|
332
|
+
|
|
333
|
+
10.2. Effect of New Versions
|
|
334
|
+
|
|
335
|
+
You may distribute the Covered Software under the terms of the version
|
|
336
|
+
of the License under which You originally received the Covered Software,
|
|
337
|
+
or under the terms of any subsequent version published by the license
|
|
338
|
+
steward.
|
|
339
|
+
|
|
340
|
+
10.3. Modified Versions
|
|
341
|
+
|
|
342
|
+
If you create software not governed by this License, and you want to
|
|
343
|
+
create a new license for such software, you may create and use a
|
|
344
|
+
modified version of this License if you rename the license and remove
|
|
345
|
+
any references to the name of the license steward (except to note that
|
|
346
|
+
such modified license differs from this License).
|
|
347
|
+
|
|
348
|
+
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
|
349
|
+
Licenses
|
|
350
|
+
|
|
351
|
+
If You choose to distribute Source Code Form that is Incompatible With
|
|
352
|
+
Secondary Licenses under the terms of this version of the License, the
|
|
353
|
+
notice described in Exhibit B of this License must be attached.
|
|
354
|
+
|
|
355
|
+
Exhibit A - Source Code Form License Notice
|
|
356
|
+
-------------------------------------------
|
|
357
|
+
|
|
358
|
+
This Source Code Form is subject to the terms of the Mozilla Public
|
|
359
|
+
License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
360
|
+
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
361
|
+
|
|
362
|
+
If it is not possible or desirable to put the notice in a particular
|
|
363
|
+
file, then You may include the notice in a location (such as a LICENSE
|
|
364
|
+
file in a relevant directory) where a recipient would be likely to look
|
|
365
|
+
for such a notice.
|
|
366
|
+
|
|
367
|
+
You may add additional accurate notices of copyright ownership.
|
|
368
|
+
|
|
369
|
+
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
|
370
|
+
---------------------------------------------------------
|
|
371
|
+
|
|
372
|
+
This Source Code Form is "Incompatible With Secondary Licenses", as
|
|
373
|
+
defined by the Mozilla Public License, v. 2.0.
|
package/README.md
CHANGED
|
@@ -1,276 +1,449 @@
|
|
|
1
|
-
<picture>
|
|
2
|
-
<source media="(prefers-color-scheme: dark)" srcset=".github/assets/logo_dark_mode.png">
|
|
3
|
-
<source media="(prefers-color-scheme: light)" srcset=".github/assets/logo_bright_mode.png">
|
|
4
|
-
<img alt="Klonk Logo" src=".github/assets/logo_bright_mode.png">
|
|
5
|
-
</picture>
|
|
6
|
-
|
|
7
1
|
# Klonk
|
|
2
|
+
*A code-first, type-safe automation engine for TypeScript.*
|
|
8
3
|
|
|
9
|
-
|
|
4
|
+
## Introduction
|
|
5
|
+
Klonk is a code-first, type-safe automation engine designed with developer experience as a top priority. It provides powerful, composable primitives to build complex workflows and state machines with world-class autocomplete and type inference. If you've ever wanted to build event-driven automations or a stateful agent, but in code, with all the benefits of TypeScript, Klonk is for you.
|
|
10
6
|
|
|
11
|
-
|
|
7
|
+
The two main features are **Workflows** and **Machines**.
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
- **Workflows**: Combine triggers with a series of tasks (a `Playlist`) to automate processes. Perfect for event-driven automation, like "when a file is added to Dropbox, parse it, and create an entry in Notion."
|
|
10
|
+
- **Machines**: Create finite state machines where each state has its own `Playlist` of tasks and conditional transitions to other states. Ideal for building agents, multi-step processes, or any system with complex, stateful logic.
|
|
14
11
|
|
|
15
|
-
|
|
12
|
+
## Installation
|
|
13
|
+
```bash
|
|
14
|
+
bun add @fkws/klonk
|
|
15
|
+
# or
|
|
16
|
+
npm i @fkws/klonk
|
|
17
|
+
```
|
|
16
18
|
|
|
17
|
-
|
|
19
|
+
## Core Concepts
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
At the heart of Klonk are a few key concepts that work together.
|
|
20
22
|
|
|
21
|
-
|
|
22
|
-
.
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
.addTask(new B_Task("task-b", client), (source, outputs) => ({
|
|
26
|
-
inputForB: outputs['task-a'].someProperty // Easily leverage auto-completion in your IDE
|
|
27
|
-
}))
|
|
28
|
-
);
|
|
29
|
-
```
|
|
23
|
+
### Task
|
|
24
|
+
A `Task` is the smallest unit of work. It's an abstract class with two main methods you need to implement:
|
|
25
|
+
- `validateInput(input)`: Runtime validation of the task's input (on top of strong typing).
|
|
26
|
+
- `run(input)`: Executes the task's logic.
|
|
30
27
|
|
|
31
|
-
|
|
28
|
+
Tasks use a `Railroad` return type, which is a simple way to handle success and error states without throwing exceptions. You can also use it for the rest of your application.
|
|
32
29
|
|
|
33
|
-
###
|
|
30
|
+
### Playlist
|
|
31
|
+
A `Playlist` is a sequence of `Tasks` that are executed in order. The magic of a `Playlist` is that each task has access to the outputs of all the tasks that ran before it, in a fully type-safe way. You build a `Playlist` by chaining `.addTask()` calls.
|
|
34
32
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
- Version control your workflows with Git.
|
|
38
|
-
- Write unit and integration tests.
|
|
39
|
-
- Integrate with your existing CI/CD pipelines.
|
|
33
|
+
### Trigger
|
|
34
|
+
A `Trigger` is what kicks off a `Workflow`. It's an event source. Klonk can be extended with triggers for anything: file system events, webhooks, new database entries, messages in a queue, etc.
|
|
40
35
|
|
|
41
|
-
###
|
|
36
|
+
### Workflow
|
|
37
|
+
A `Workflow` connects one or more `Triggers` to a `Playlist`. When a trigger fires an event, the workflow runs the playlist, passing the event data as the initial input. This allows you to create powerful, event-driven automations.
|
|
42
38
|
|
|
43
|
-
|
|
39
|
+
### Machine
|
|
40
|
+
A `Machine` is a finite state machine. It's made up of `StateNode`s. Each `StateNode` represents a state and has two key components:
|
|
41
|
+
1. A `Playlist` that runs when the machine enters that state.
|
|
42
|
+
2. A set of conditional `Transitions` to other states.
|
|
43
|
+
3. Retry rules for when a transition fails to resolve.
|
|
44
44
|
|
|
45
|
-
|
|
46
|
-
`@fkws-npm/klonk/tasks` and `@fkws-npm/klonk/triggers` implement powerful built-ins. Klonk provides a rich set of triggers and tasks that cover a wide range of common automation scenarios, from file system events to webhook listeners. These components are designed to be robust and ready for production use. When combined with the official integrations for popular services like Dropbox, Notion, and OpenRouter, you have all the tools you need to build versatile and powerful workflows right out of the box, without having to write custom components for every step.
|
|
45
|
+
The `Machine` carries a mutable `stateData` object that can be read from and written to by playlists and transition conditions throughout its execution.
|
|
47
46
|
|
|
48
47
|
## Features
|
|
48
|
+
- **Type-Safe & Autocompleted**: Klonk leverages TypeScript's inference to provide a world-class developer experience. The inputs and outputs of every step are strongly typed, so you'll know at compile time if your logic is sound.
|
|
49
|
+
- **Code-First**: Define your automations directly in TypeScript. No YAML, no drag-and-drop UIs. Just the full power of a real programming language.
|
|
50
|
+
- **Composable & Extensible**: The core primitives (`Task`, `Trigger`) are simple abstract classes, making it easy to create your own reusable components and integrations.
|
|
51
|
+
- **Flexible Execution**: `Machines` can be run synchronously to completion (`run`) for request/response style work, or started as a long-running background process (`start`).
|
|
49
52
|
|
|
50
|
-
|
|
51
|
-
-
|
|
52
|
-
- **Modern Integration Support**: Built-in, async-ready integrations for services like Notion, Dropbox, and OpenRouter.
|
|
53
|
-
- **AI-Powered**: Leverage powerful AI models for intelligent document and data processing right out of the box.
|
|
54
|
-
- **Code-First & Declarative**: Define workflows in pure TypeScript for maximum flexibility and clarity.
|
|
55
|
-
- **Self-Hosted**: Run on your own servers with no recurring fees.
|
|
56
|
-
|
|
57
|
-
## Installation
|
|
53
|
+
## Klonkworks: Pre-built Components
|
|
54
|
+
Coming soon(ish)! Klonkworks will be a large collection of pre-built Tasks, Triggers, and integrations. This will allow you to quickly assemble powerful automations that connect to a wide variety of services, often without needing to build your own components from scratch.
|
|
58
55
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
56
|
+
## Code Examples
|
|
57
|
+
<details>
|
|
58
|
+
<summary><b>Creating a Task</b></summary>
|
|
62
59
|
|
|
63
|
-
|
|
60
|
+
Here's how you create a custom `Task`. This task uses an AI client to perform text inference.
|
|
64
61
|
|
|
65
|
-
```
|
|
66
|
-
|
|
62
|
+
```typescript
|
|
63
|
+
import { Railroad, Task } from "@fkws/klonk";
|
|
64
|
+
import { OpenRouterClient } from "./common/OpenrouterClient"
|
|
65
|
+
import { Model } from "./common/models";
|
|
66
|
+
|
|
67
|
+
type TABasicTextInferenceInput = {
|
|
68
|
+
inputText: string;
|
|
69
|
+
instructions?: string;
|
|
70
|
+
model: Model;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type TABasicTextInferenceOutput = {
|
|
74
|
+
text: string;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// A Task is a generic class. You provide the Input, Output, and an Ident (a unique string literal for the task).
|
|
78
|
+
export class TABasicTextInference<IdentType extends string> extends Task<
|
|
79
|
+
TABasicTextInferenceInput, // These type parameters are part of the secret sauce typing system Klonk uses.
|
|
80
|
+
TABasicTextInferenceOutput, // Input Type, Output Type, Ident Type
|
|
81
|
+
IdentType
|
|
82
|
+
> {
|
|
83
|
+
constructor(ident: IdentType, public client: OpenRouterClient) {
|
|
84
|
+
super(ident);
|
|
85
|
+
if (!this.client) {
|
|
86
|
+
throw new Error("[TABasicTextInference] An IOpenRouter client instance is required.");
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// validateInput is for runtime validation of the data your task receives.
|
|
91
|
+
async validateInput(input: TABasicTextInferenceInput): Promise<boolean> {
|
|
92
|
+
if (!input.inputText || !input.model) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The core logic of your task. It must return a Railroad type.
|
|
99
|
+
async run(input: TABasicTextInferenceInput): Promise<Railroad<TABasicTextInferenceOutput>> {
|
|
100
|
+
try {
|
|
101
|
+
const result = await this.client.basicTextInference({
|
|
102
|
+
inputText: input.inputText,
|
|
103
|
+
instructions: input.instructions,
|
|
104
|
+
model: input.model
|
|
105
|
+
});
|
|
106
|
+
// On success, return a success object with your data.
|
|
107
|
+
return {
|
|
108
|
+
success: true, // Railroad is a simple result type
|
|
109
|
+
data: {
|
|
110
|
+
text: result
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
} catch (error) {
|
|
114
|
+
// On failure, return an error object. The next Task's input builder will react to this.
|
|
115
|
+
return {
|
|
116
|
+
success: false,
|
|
117
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
67
122
|
```
|
|
123
|
+
</details>
|
|
68
124
|
|
|
69
|
-
|
|
125
|
+
<details>
|
|
126
|
+
<summary><b>Creating a Trigger</b></summary>
|
|
70
127
|
|
|
71
|
-
|
|
128
|
+
Here's an example of a custom `Trigger`. This trigger fires on a given interval and pushes the current date as its event data.
|
|
72
129
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
130
|
+
```typescript
|
|
131
|
+
import { Trigger } from '@fkws/klonk';
|
|
132
|
+
|
|
133
|
+
// A simple trigger that fires every `intervalMs` with the current date.
|
|
134
|
+
// You define the shape of the data the trigger will provide, in this case `{ now: Date }`.
|
|
135
|
+
export class IntervalTrigger<TIdent extends string> extends Trigger<TIdent, { now: Date }> {
|
|
136
|
+
private intervalId: NodeJS.Timeout | null = null;
|
|
137
|
+
|
|
138
|
+
constructor(ident: TIdent, private intervalMs: number) {
|
|
139
|
+
super(ident); // Pass the unique identifier to the parent constructor.
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The start method is called by the Workflow to begin listening for events.
|
|
143
|
+
async start(): Promise<void> {
|
|
144
|
+
if (this.intervalId) return; // Prevent multiple intervals.
|
|
145
|
+
|
|
146
|
+
this.intervalId = setInterval(() => {
|
|
147
|
+
// When an event occurs, use pushEvent to add it to the internal queue for the workflow to poll.
|
|
148
|
+
this.pushEvent({ now: new Date() });
|
|
149
|
+
}, this.intervalMs);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// The stop method cleans up any resources, like intervals or open connections.
|
|
153
|
+
async stop(): Promise<void> {
|
|
154
|
+
if (this.intervalId) {
|
|
155
|
+
clearInterval(this.intervalId);
|
|
156
|
+
this.intervalId = null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
</details>
|
|
77
162
|
|
|
78
|
-
|
|
163
|
+
<details>
|
|
164
|
+
<summary><b>Building a Workflow</b></summary>
|
|
79
165
|
|
|
80
|
-
|
|
166
|
+
Workflows are perfect for event-driven automations. This example creates a workflow that triggers when a new invoice PDF is added to a Dropbox folder. It then parses the invoice and creates a new item in a Notion database.
|
|
81
167
|
|
|
82
|
-
|
|
83
|
-
import { Workflow } from '@fkws-npm/klonk';
|
|
84
|
-
import { TRDropboxFileAdded } from '@fkws-npm/klonk/triggers';
|
|
85
|
-
import { TADropboxDownloadFile, TALogToConsole } from '@fkws-npm/klonk/tasks';
|
|
86
|
-
import { IDropbox } from '@fkws-npm/klonk/integrations';
|
|
168
|
+
Notice how the `builder` function for each task (`(source, outputs) => { ... }`) has access to the initial `source` data (from the trigger) and the `outputs` of all previous tasks. Klonk automatically infers the types for `source` and `outputs`!
|
|
87
169
|
|
|
88
|
-
|
|
89
|
-
|
|
170
|
+
```typescript
|
|
171
|
+
import { z } from 'zod';
|
|
172
|
+
import { Workflow } from '@fkws/klonk';
|
|
173
|
+
|
|
174
|
+
// The following example requires a lot of tasks, integrations and a trigger.
|
|
175
|
+
// Soon, you will be able to import these from @fkws/klonkworks.
|
|
176
|
+
import { TACreateNotionDatabaseItem, TANotionGetTitlesAndIdsForDatabase, TAParsePdfAi, TADropboxDownloadFile } from '@fkws/klonkworks/tasks';
|
|
177
|
+
import { INotion, IOpenRouter, IDropbox } from '@fkws/klonkworks/integrations';
|
|
178
|
+
import { TRDropboxFileAdded } from '@fkws/klonkworks/triggers';
|
|
179
|
+
|
|
180
|
+
// Providers and clients are instantiated as usual.
|
|
181
|
+
const notionProvider = new INotion({apiKey: process.env.NOTION_API_KEY!});
|
|
182
|
+
const openrouterProvider = new IOpenRouter({apiKey: process.env.OPENROUTER_API_KEY!});
|
|
183
|
+
const dropboxProvider = new IDropbox({
|
|
90
184
|
appKey: process.env.DROPBOX_APP_KEY!,
|
|
91
185
|
appSecret: process.env.DROPBOX_APP_SECRET!,
|
|
92
|
-
refreshToken: process.env.
|
|
186
|
+
refreshToken: process.env.DROPBOX_REFRESH_KEY!
|
|
93
187
|
});
|
|
94
188
|
|
|
95
|
-
//
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
folderPath: "/MyKlonkFiles"
|
|
189
|
+
// Start building a workflow.
|
|
190
|
+
const workflow = Workflow.create().addTrigger(
|
|
191
|
+
// A workflow is initiated by one or more triggers.
|
|
192
|
+
new TRDropboxFileAdded("dropbox-trigger", {
|
|
193
|
+
client: dropboxProvider,
|
|
194
|
+
folderPath: process.env.DROPBOX_INVOICES_FOLDER_PATH ?? "",
|
|
102
195
|
})
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
196
|
+
).setPlaylist(p => p // Builder function allows complex types to be assembled!
|
|
197
|
+
.addTask( // .addTask() adds a task to the playlist.
|
|
198
|
+
new TANotionGetTitlesAndIdsForDatabase("get-payees", notionProvider),
|
|
199
|
+
// The second argument to addTask builds the input for that task.
|
|
200
|
+
// `source` is the data from the trigger, `outputs` contains all previous task outputs.
|
|
201
|
+
(source, outputs) => {
|
|
202
|
+
return { database_id: process.env.NOTION_PAYEES_DATABASE_ID!}
|
|
203
|
+
}
|
|
204
|
+
).addTask(
|
|
205
|
+
new TANotionGetTitlesAndIdsForDatabase("get-expense-types", notionProvider),
|
|
206
|
+
(source, outputs) => { // Type inference works for source and outputs!
|
|
207
|
+
return { database_id: process.env.NOTION_EXPENSE_TYPES_DATABASE_ID!}
|
|
208
|
+
}
|
|
209
|
+
).addTask(
|
|
210
|
+
new TADropboxDownloadFile("download-invoice-pdf", dropboxProvider),
|
|
211
|
+
(source, outputs) => {
|
|
212
|
+
// The `source` object contains the trigger ident, so you can handle multiple triggers.
|
|
213
|
+
if (source.triggerIdent == "dropbox-trigger") {
|
|
214
|
+
return { file_metadata: source.data}
|
|
215
|
+
} else {
|
|
216
|
+
throw new Error(`Trigger ${source.triggerIdent} is not implemented for task download-invoice-pdf.`)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
).addTask(
|
|
220
|
+
new TAParsePdfAi("parse-invoice", openrouterProvider),
|
|
221
|
+
(source, outputs) => {
|
|
222
|
+
// Access the outputs of previous tasks via the `outputs` object.
|
|
223
|
+
// The keys are the idents you provided to the tasks.
|
|
224
|
+
const downloadResult = outputs['download-invoice-pdf'];
|
|
225
|
+
if (!downloadResult.success) {
|
|
226
|
+
throw downloadResult.error ?? new Error('Failed to download invoice PDF');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const payeesResult = outputs['get-payees'];
|
|
230
|
+
if (!payeesResult.success) {
|
|
231
|
+
throw payeesResult.error ?? new Error('Failed to load payees');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const expenseTypesResult = outputs['get-expense-types'];
|
|
235
|
+
if (!expenseTypesResult.success) {
|
|
236
|
+
throw expenseTypesResult.error ?? new Error('Failed to load expense types');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const payees = payeesResult.data;
|
|
240
|
+
const expenseTypes = expenseTypesResult.data;
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
pdf: downloadResult.data.file,
|
|
244
|
+
instructions: "Extract data from the invoice",
|
|
245
|
+
schema: z.object({
|
|
246
|
+
payee: z.enum(payees.map(p => p.id) as [string, ...string[]])
|
|
247
|
+
.describe("The payee id of the invoice according to this map: " + JSON.stringify(payees, null, 2)),
|
|
248
|
+
total: z.number()
|
|
249
|
+
.describe("The total amount of the invoice."),
|
|
250
|
+
invoice_date: z.string()
|
|
251
|
+
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
252
|
+
.describe("The date of the invoice as an ISO 8601 string (YYYY-MM-DD)."),
|
|
253
|
+
expense_type: z.enum(expenseTypes.map(e => e.id) as [string, ...string[]])
|
|
254
|
+
.describe("The expense type id of the invoice according to this map: " + JSON.stringify(expenseTypes, null, 2))
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
).addTask(
|
|
259
|
+
new TACreateNotionDatabaseItem("create-notion-invoice", notionProvider),
|
|
260
|
+
(source, outputs) => {
|
|
261
|
+
const invoiceResult = outputs['parse-invoice'];
|
|
262
|
+
if (!invoiceResult.success) {
|
|
263
|
+
throw invoiceResult.error ?? new Error('Failed to parse invoice');
|
|
264
|
+
}
|
|
265
|
+
const invoiceData = invoiceResult.data;
|
|
266
|
+
const properties = {
|
|
267
|
+
'Name': { 'title': [{ 'text': { 'content': 'Invoice' } }] },
|
|
268
|
+
'Payee': { 'relation': [{ 'id': invoiceData.payee }] },
|
|
269
|
+
'Total': { 'number': invoiceData.total },
|
|
270
|
+
'Invoice Date': { 'date': { 'start': invoiceData.invoice_date } },
|
|
271
|
+
'Expense Type': { 'relation': [{ 'id': invoiceData.expense_type }] }
|
|
272
|
+
};
|
|
273
|
+
return {
|
|
274
|
+
database_id: process.env.NOTION_INVOICES_DATABASE_ID!,
|
|
275
|
+
properties: properties
|
|
276
|
+
}
|
|
277
|
+
}
|
|
122
278
|
)
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
//
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
```typescript
|
|
139
|
-
import { Workflow } from '@fkws-npm/klonk';
|
|
140
|
-
import { z } from 'zod';
|
|
141
|
-
import { TRDropboxFileAdded } from '@fkws-npm/klonk/triggers';
|
|
142
|
-
import {
|
|
143
|
-
TADropboxDownloadFile,
|
|
144
|
-
TAParsePdfAi,
|
|
145
|
-
TACreateNotionDatabaseItem
|
|
146
|
-
} from '@fkws-npm/klonk/tasks';
|
|
147
|
-
import { IDropbox, IOpenRouter, INotion } from '@fkws-npm/klonk/integrations';
|
|
148
|
-
|
|
149
|
-
// --- Client & Schema Setup ---
|
|
150
|
-
const dropbox = new IDropbox({ /* ... */ });
|
|
151
|
-
const openRouter = new IOpenRouter({ apiKeyEnvVar: "OPENROUTER_API_KEY" });
|
|
152
|
-
const notion = new INotion({ apiKeyEnvVar: "NOTION_API_KEY" });
|
|
153
|
-
|
|
154
|
-
const InvoiceSchema = z.object({
|
|
155
|
-
invoice_number: z.string(),
|
|
156
|
-
total_amount: z.number(),
|
|
157
|
-
is_paid: z.boolean(),
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
// Run the workflow
|
|
282
|
+
console.log('[WCreateNotionInvoiceFromFile] Starting workflow...');
|
|
283
|
+
// .start() begins the workflow's trigger polling loop.
|
|
284
|
+
workflow.start({
|
|
285
|
+
// The callback is executed every time the playlist successfully completes.
|
|
286
|
+
callback: (source, outputs) => {
|
|
287
|
+
console.log('[WCreateNotionInvoiceFromFile] Workflow completed');
|
|
288
|
+
console.dir({
|
|
289
|
+
source,
|
|
290
|
+
outputs
|
|
291
|
+
}, { depth: null });
|
|
292
|
+
}
|
|
158
293
|
});
|
|
159
|
-
|
|
160
|
-
// --- Workflow Definition ---
|
|
161
|
-
const invoiceWorkflow = Workflow.create()
|
|
162
|
-
.addTrigger(new TRDropboxFileAdded("new-invoice", { client: dropbox, folderPath: "/Invoices" }))
|
|
163
|
-
.setPlaylist(p => p
|
|
164
|
-
// Step 1: Download the file from Dropbox
|
|
165
|
-
.addTask(new TADropboxDownloadFile("download-pdf", dropbox),
|
|
166
|
-
(source, outputs) => ({
|
|
167
|
-
file_metadata: source.data
|
|
168
|
-
})
|
|
169
|
-
)
|
|
170
|
-
// Step 2: Use AI to parse the downloaded PDF
|
|
171
|
-
.addTask(new TAParsePdfAi("parse-with-ai", openRouter),
|
|
172
|
-
(source, outputs) => ({
|
|
173
|
-
pdf: outputs['download-pdf'].file, // Type-safe access to previous output by its ID
|
|
174
|
-
instructions: "Extract the invoice number, total amount, and payment status from the PDF.",
|
|
175
|
-
zodSchema: InvoiceSchema,
|
|
176
|
-
})
|
|
177
|
-
)
|
|
178
|
-
// Step 3: Create a new item in a Notion database
|
|
179
|
-
.addTask(new TACreateNotionDatabaseItem("create-notion-record", notion),
|
|
180
|
-
(source, outputs) => {
|
|
181
|
-
const invoiceData = outputs['parse-with-ai']; // Type-safe access to the parsed data
|
|
182
|
-
return {
|
|
183
|
-
database_id: 'YOUR_INVOICES_DATABASE_ID',
|
|
184
|
-
properties: {
|
|
185
|
-
'Invoice Number': { title: [{ text: { content: invoiceData.invoice_number } }] },
|
|
186
|
-
'Total': { number: invoiceData.total_amount },
|
|
187
|
-
'Status': { select: { name: invoiceData.is_paid ? "Paid" : "Unpaid" } }
|
|
188
|
-
}
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
)
|
|
192
|
-
);
|
|
193
|
-
|
|
194
|
-
// --- Start the workflow ---
|
|
195
|
-
invoiceWorkflow.start();
|
|
196
294
|
```
|
|
295
|
+
</details>
|
|
197
296
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
If your use case can't be served with Klonk's built-ins, you can easily extend Klonk by implementing the `Task` and `Trigger` abstract classes.
|
|
297
|
+
<details>
|
|
298
|
+
<summary><b>Building a Machine</b></summary>
|
|
201
299
|
|
|
202
|
-
|
|
300
|
+
`Machines` are ideal for building complex, stateful agents. This example shows a simple AI agent that takes a user's query, refines it, performs a web search, and then generates a final response.
|
|
203
301
|
|
|
204
|
-
|
|
302
|
+
The `Machine` manages a `StateData` object. Each `StateNode`'s `Playlist` can modify this state, and the `Transitions` between states can use it to decide which state to move to next.
|
|
205
303
|
|
|
206
304
|
```typescript
|
|
207
|
-
import {
|
|
208
|
-
import
|
|
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
|
-
|
|
305
|
+
import { Machine, StateNode } from "@fkws/klonk"
|
|
306
|
+
import { OpenRouterClient } from "./tasks/common/OpenrouterClient"
|
|
307
|
+
import { Model } from "./tasks/common/models"
|
|
308
|
+
import { TABasicTextInference } from "./tasks/TABasicTextInference"
|
|
309
|
+
import { TASearchOnline } from "./tasks/TASearchOnline"
|
|
310
|
+
|
|
311
|
+
type StateData = {
|
|
312
|
+
input: string;
|
|
313
|
+
output?: string;
|
|
314
|
+
model?: Model;
|
|
315
|
+
refinedInput?: string;
|
|
316
|
+
searchTerm?: string;
|
|
317
|
+
searchResults?: {
|
|
318
|
+
results: {
|
|
319
|
+
url: string;
|
|
320
|
+
title: string;
|
|
321
|
+
content: string;
|
|
322
|
+
raw_content?: string | undefined;
|
|
323
|
+
score: string;
|
|
324
|
+
}[];
|
|
325
|
+
query: string;
|
|
326
|
+
answer?: string | undefined;
|
|
327
|
+
images?: string[] | undefined;
|
|
328
|
+
follow_up_questions?: string[] | undefined;
|
|
329
|
+
response_time: string;
|
|
330
|
+
},
|
|
331
|
+
finalResponse?: string;
|
|
234
332
|
}
|
|
235
|
-
```
|
|
236
333
|
|
|
237
|
-
|
|
334
|
+
const client = new OpenRouterClient(process.env.OPENROUTER_API_KEY!)
|
|
335
|
+
|
|
336
|
+
const webSearchAgent = Machine
|
|
337
|
+
.create<StateData>()
|
|
338
|
+
.addState(StateNode
|
|
339
|
+
.create<StateData>()
|
|
340
|
+
.setIdent("refine_and_extract")
|
|
341
|
+
.setPlaylist(p => p // Builder function allows complex types to be assembled!
|
|
342
|
+
.addTask(new TABasicTextInference("refine", client),
|
|
343
|
+
(state, outputs) => { // This function constructs the INPUT of the task from the state and outputs of previous tasks
|
|
344
|
+
const input = state.input;
|
|
345
|
+
const model = state.model ? state.model : "openai/gpt-5"
|
|
346
|
+
const instructions = `You are a prompt refiner. Any prompts you receive, you will refine to improve LLM performance. Break down the prompt by Intent, Mood, and Instructions. Do NOT reply or answer the user's message! ONLY refine the prompt.`;
|
|
347
|
+
return {
|
|
348
|
+
inputText: input,
|
|
349
|
+
model: model,
|
|
350
|
+
instructions: instructions
|
|
351
|
+
}
|
|
352
|
+
})
|
|
353
|
+
.addTask(new TABasicTextInference("extract_search_terms", client),
|
|
354
|
+
(state, outputs) => {
|
|
355
|
+
const input = `Original request: ${state.input}\n\nRefined prompt: ${state.refinedInput}`;
|
|
356
|
+
const model = state.model ? state.model : "openai/gpt-5"
|
|
357
|
+
const instructions = `You will receive the original user request AND an LLM refined version of the prompt. Please use both to extract one short web search query that will retrieve useful results.`;
|
|
358
|
+
return {
|
|
359
|
+
inputText: input,
|
|
360
|
+
model: model,
|
|
361
|
+
instructions: instructions
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
.finally((state, outputs) => { // The finally block allows the playlist to react to the last task and to modify state data before the run ends.
|
|
365
|
+
if (outputs.refine.success) {
|
|
366
|
+
state.refinedInput = outputs.refine.data.text
|
|
367
|
+
} else {
|
|
368
|
+
state.refinedInput = "Sorry, an error occurred: " + outputs.refine.error
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (outputs.extract_search_terms.success) {
|
|
372
|
+
state.searchTerm = outputs.extract_search_terms.data.text
|
|
373
|
+
}
|
|
374
|
+
}))
|
|
375
|
+
.retryLimit(3) // Simple retry rule setters. Also includes .preventRetry() to disable retries entirely and .retryDelayMs(delayMs) to set the delay between retries. Default is infinite retries at 1000ms delay.
|
|
376
|
+
.addTransition({
|
|
377
|
+
to: "search_web", // Transitions refer to states by their ident.
|
|
378
|
+
condition: async (stateData: StateData) => stateData.searchTerm ? true : false,
|
|
379
|
+
weight: 2 // Weight determines the order in which transitions are tried. Higher weight = higher priority.
|
|
380
|
+
})
|
|
381
|
+
.addTransition({
|
|
382
|
+
to: "generate_response",
|
|
383
|
+
condition: async (stateData: StateData) => true,
|
|
384
|
+
weight: 1
|
|
385
|
+
}),
|
|
386
|
+
{ initial: true } // The machine needs an initial state.
|
|
387
|
+
)
|
|
388
|
+
.addState(StateNode.create<StateData>()
|
|
389
|
+
.setIdent("search_web")
|
|
390
|
+
.setPlaylist(p => p
|
|
391
|
+
.addTask(new TASearchOnline("search"),
|
|
392
|
+
(state, outputs) => {
|
|
393
|
+
return {
|
|
394
|
+
query: state.searchTerm! // We are sure that the searchTerm is not undefined because of the transition condition.
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
.finally((state, outputs) => {
|
|
398
|
+
if(outputs.search.success) {
|
|
399
|
+
state.searchResults = outputs.search.data
|
|
400
|
+
}
|
|
401
|
+
}))
|
|
402
|
+
.addTransition({
|
|
403
|
+
to: "generate_response",
|
|
404
|
+
condition: async (stateData: StateData) => true,
|
|
405
|
+
weight: 1
|
|
406
|
+
})
|
|
407
|
+
)
|
|
408
|
+
.addState(StateNode.create<StateData>()
|
|
409
|
+
.setIdent("generate_response")
|
|
410
|
+
.setPlaylist(p => p
|
|
411
|
+
.addTask(new TABasicTextInference("generate_response", client),
|
|
412
|
+
(state, outputs) => {
|
|
413
|
+
return {
|
|
414
|
+
inputText: state.input,
|
|
415
|
+
model: state.model ? state.model : "openai/gpt-5",
|
|
416
|
+
instructions: "You will receive a user request and a refined prompt. There may also be search results. Based on the information, please write a professional response to the user's request."
|
|
417
|
+
}
|
|
418
|
+
})
|
|
419
|
+
.finally((state, outputs) => {
|
|
420
|
+
if(outputs.generate_response.success) {
|
|
421
|
+
state.finalResponse = outputs.generate_response.data.text
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
state.finalResponse = "Sorry, an error occurred: " + outputs.generate_response.error
|
|
425
|
+
}
|
|
426
|
+
})
|
|
427
|
+
))
|
|
428
|
+
.finalize({ // Finalize your machine to make it ready to run. Verbose machines emit JSON logs. If you don't provide an ident, a uuidv4 will be generated for it.
|
|
429
|
+
verbose: true,
|
|
430
|
+
ident: "web-search-agent"
|
|
431
|
+
})
|
|
238
432
|
|
|
239
|
-
|
|
433
|
+
// ------------- EXECUTION: -------------
|
|
240
434
|
|
|
241
|
-
|
|
242
|
-
|
|
435
|
+
const state: StateData = { // The state object is mutable and is passed to the machine and playlists.
|
|
436
|
+
input: "How do I update AMD graphic driver?",
|
|
437
|
+
model: "openai/gpt-4o-mini"
|
|
438
|
+
}
|
|
243
439
|
|
|
244
|
-
//
|
|
245
|
-
|
|
440
|
+
// The .run() method executes the machine until it reaches a terminal state
|
|
441
|
+
// (leaf, failed, out of retries, looped back to initial state)
|
|
442
|
+
// and returns the final state. The original state object is also mutated.
|
|
443
|
+
const finalState = await webSearchAgent.run(state)
|
|
246
444
|
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
TriggerEvent<IdentType, NewUserEventData>
|
|
251
|
-
> {
|
|
252
|
-
constructor(ident: IdentType) {
|
|
253
|
-
super(ident);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
// 3. The `start` method is called by the workflow to begin polling
|
|
257
|
-
async start(): Promise<void> {
|
|
258
|
-
// Example: check for new users every 10 seconds
|
|
259
|
-
setInterval(async () => {
|
|
260
|
-
const newUser = await this.checkForNewUserInDb();
|
|
261
|
-
if (newUser) {
|
|
262
|
-
// 4. Add new events to the `this.queue` property
|
|
263
|
-
this.queue.push({
|
|
264
|
-
triggerIdent: this.ident,
|
|
265
|
-
data: newUser
|
|
266
|
-
});
|
|
267
|
-
}
|
|
268
|
-
}, 10000);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
private async checkForNewUserInDb(): Promise<NewUserEventData | null> {
|
|
272
|
-
// Your database logic here...
|
|
273
|
-
return null;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
445
|
+
console.log(finalState.finalResponse) // The final state is returned.
|
|
446
|
+
// Or simply:
|
|
447
|
+
console.log(state.finalResponse) // original state object is also mutated.
|
|
276
448
|
```
|
|
449
|
+
</details>
|