@makaio/framework 1.0.0-dev-1783355411417 → 1.0.0-dev-1783477169057
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.makaio-build.json +2 -2
- package/dist/adapter-Lx6K7yQS.mjs +1 -0
- package/dist/adapter-subsystem/index.mjs +1 -1
- package/dist/adapters/config/index.d.mts +1 -1
- package/dist/adapters/index.d.mts +219 -40
- package/dist/adapters/index.mjs +6 -6
- package/dist/adapters/node.d.mts +1 -1
- package/dist/adapters/node.mjs +4 -4
- package/dist/{base-orchestrator-BNysGvaM.d.mts → base-orchestrator-J1WKAUkF.d.mts} +32 -3
- package/dist/bus/index.d.mts +22 -22
- package/dist/bus/index.mjs +1 -1
- package/dist/client-l1Rq5p6X.mjs +1 -0
- package/dist/clients/index.d.mts +30 -0
- package/dist/clients/index.mjs +2 -2
- package/dist/contracts/adapter/index.d.mts +2 -2
- package/dist/contracts/adapter/index.mjs +1 -1
- package/dist/contracts/adapter/schemas/session-lineage.d.mts +1 -1
- package/dist/contracts/adapter/schemas/session-lineage.mjs +1 -1
- package/dist/contracts/artifact/index.d.mts +1 -1
- package/dist/contracts/canonical-model/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +2 -2
- package/dist/contracts/client/index.mjs +1 -1
- package/dist/contracts/config/index.d.mts +12 -12
- package/dist/contracts/extension/index.d.mts +3 -3
- package/dist/contracts/facet/index.d.mts +1 -1
- package/dist/contracts/harness/index.d.mts +1 -1
- package/dist/contracts/index.d.mts +454 -276
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +3 -3
- package/dist/contracts/provider/index.d.mts +1 -1
- package/dist/contracts/session/index.d.mts +3 -3
- package/dist/contracts/session/index.mjs +1 -1
- package/dist/contracts/shared/index.d.mts +1 -1
- package/dist/contracts/skill/index.d.mts +1 -1
- package/dist/contracts/variant/index.d.mts +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/{definition-b9jyJqPD.d.mts → definition-DePb3ke-.d.mts} +1 -1
- package/dist/drizzle/0023_m_mr9gc37m.sql +1 -0
- package/dist/drizzle/meta/_journal.json +7 -0
- package/dist/handlers-B74FvKlA.mjs +57 -0
- package/dist/hooks/index.d.mts +19 -2
- package/dist/{identity-BarL3JYI.mjs → identity-DC3Pk0ps.mjs} +1 -1
- package/dist/{index-BwGfdbI0.d.mts → index-2fK9iSHI.d.mts} +9 -9
- package/dist/{index-D7rWAEY0.d.mts → index-B-6DtLLz.d.mts} +1 -1
- package/dist/{index-4eP9DRL_.d.mts → index-B3fjN5HX.d.mts} +7 -7
- package/dist/{index-O08Q2ikz.d.mts → index-BMbmoarE.d.mts} +8 -8
- package/dist/{index-DV4nRk0h.d.mts → index-BX1MxwFr.d.mts} +28 -28
- package/dist/{index-CqCe7Phc.d.mts → index-BcwOnvUh.d.mts} +6 -6
- package/dist/{index-D6aAzr32.d.mts → index-BeouVICp.d.mts} +36 -36
- package/dist/{index-DQYj8-53.d.mts → index-BjO4Zkap.d.mts} +1 -1
- package/dist/{index-B5w-0Gg9.d.mts → index-Bl42SCEI.d.mts} +8 -8
- package/dist/{index-BYfSAJRC.d.mts → index-BvTd61i5.d.mts} +151 -29
- package/dist/{index-3X0368CL.d.mts → index-CA-AJbq6.d.mts} +4 -4
- package/dist/{index-C5C1tk9f.d.mts → index-CQQcnpev.d.mts} +41 -41
- package/dist/{index-BKZhnb2B.d.mts → index-C_xQM96Y.d.mts} +802 -422
- package/dist/{index-31vR1sxk.d.mts → index-CwFSL4xI.d.mts} +144 -21
- package/dist/{index-WHUV7neB.d.mts → index-DMz-2ACU.d.mts} +105 -105
- package/dist/{index-3J0HZlPH.d.mts → index-DScUb-hF.d.mts} +334 -13
- package/dist/{index-DEzdNQum.d.mts → index-Di84JjS0.d.mts} +2 -2
- package/dist/{index-DvHYpi-J.d.mts → index-Dv4oGVZK.d.mts} +1246 -397
- package/dist/{index-CaerrEDH.d.mts → index-NkNbYFud.d.mts} +1 -1
- package/dist/{index-D9-vOJvZ.d.mts → index-h5go5Dtd.d.mts} +1 -1
- package/dist/{index-DLNRgZPo2.d.mts → index-j_X5xefv2.d.mts} +26 -26
- package/dist/{index-C6Ys8pxt.d.mts → index-uM4KZopE.d.mts} +9 -9
- package/dist/kernel/extension/index.d.mts +1 -1
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{namespace-j7vFsmYL.d.mts → namespace-3yGm4WF9.d.mts} +2 -2
- package/dist/{namespace-D8P8Sxce2.d.mts → namespace-6sIu5nBI2.d.mts} +2 -2
- package/dist/{namespace-B3ol3pc-.d.mts → namespace-BigVYQyx.d.mts} +12 -0
- package/dist/{namespace-DmqoDDRD.d.mts → namespace-Boh42UoL.d.mts} +66 -22
- package/dist/{namespace-CfvtDD_U.d.mts → namespace-COEUMuHL.d.mts} +156 -156
- package/dist/{namespace-B4cV_pk3.d.mts → namespace-D94HrTtq.d.mts} +58 -58
- package/dist/{namespace-DhDY0juT.d.mts → namespace-OLAh9wHU.d.mts} +375 -27
- package/dist/{namespace-Bm77p82L.d.mts → namespace-TPbegIMi.d.mts} +27 -27
- package/dist/{package-MmQvNJ3u.d.mts → package-B6mEMD8r.d.mts} +5 -0
- package/dist/{package-BmRhhi-3.mjs → package-BQn_RTo7.mjs} +1 -1
- package/dist/package.json +1 -1
- package/dist/{schema-DLNBajAV.d.mts → schema-B5vHi7Uu.d.mts} +28 -1
- package/dist/{schemas-CoFCV42v.d.mts → schemas-CDBn9MTz.d.mts} +156 -156
- package/dist/schemas-CkOigLAT.mjs +1 -0
- package/dist/{schemas-lnE9YoG7.d.mts → schemas-CscdPqCt.d.mts} +3 -3
- package/dist/{schemas-DMMWmWjq.d.mts → schemas-D512XweP.d.mts} +4 -4
- package/dist/{schemas-DuuVuhHX2.d.mts → schemas-DOV4UouN2.d.mts} +13 -13
- package/dist/{schemas-DmGRSeIq.d.mts → schemas-t6h9oSct.d.mts} +28 -1
- package/dist/services/adapter-runtime/index.d.mts +4 -4
- package/dist/services/adapter-runtime/index.mjs +1 -1
- package/dist/services/adapter-runtime/namespace.d.mts +1 -1
- package/dist/services/adapter-runtime/schemas.d.mts +2 -2
- package/dist/services/adapter-runtime/schemas.mjs +1 -1
- package/dist/services/adapter-subsystem/index.d.mts +2 -2
- package/dist/services/adapter-subsystem/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/index.d.mts +2 -2
- package/dist/services/agent-runtime/namespace.d.mts +1 -1
- package/dist/services/agent-runtime/schemas.d.mts +1 -1
- package/dist/services/context-rules/index.d.mts +8 -8
- package/dist/services/execution-target/index.d.mts +1 -1
- package/dist/services/filesystem/namespace.d.mts +12 -12
- package/dist/services/filesystem/schemas.d.mts +6 -6
- package/dist/services/git/namespace.d.mts +2 -2
- package/dist/services/git/schemas.d.mts +1 -1
- package/dist/services/harness/index.d.mts +3 -3
- package/dist/services/index.d.mts +147 -140
- package/dist/services/index.mjs +1 -1
- package/dist/services/log-import/browser.d.mts +2 -2
- package/dist/services/log-import/index.d.mts +15 -2
- package/dist/services/log-import/index.mjs +2 -2
- package/dist/services/log-import/log-import.d.mts +1 -1
- package/dist/services/log-import/namespace.d.mts +2 -2
- package/dist/services/log-import/schemas.d.mts +1 -1
- package/dist/services/session/handlers/index.d.mts +1 -1
- package/dist/services/session/handlers/index.mjs +1 -1
- package/dist/services/session/index.d.mts +7 -7
- package/dist/services/session/index.mjs +1 -1
- package/dist/services/session/messages/namespace.d.mts +1 -1
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/session/storage/namespace.d.mts +1 -1
- package/dist/services/session/storage/schema.d.mts +1 -1
- package/dist/services/session/storage/schema.mjs +1 -1
- package/dist/services/session/testing/index.mjs +3 -2
- package/dist/services/session-editor/index.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +10 -10
- package/dist/services/settings/storage/extension-configs/namespace.d.mts +3 -3
- package/dist/services/subagent-template/index.d.mts +2 -2
- package/dist/services/subagent-template/namespace.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/services/tool-approval/index.mjs +1 -1
- package/dist/services/tools/index.mjs +1 -1
- package/dist/services/tray-menu/index.d.mts +2 -2
- package/dist/services/tray-menu/namespace.d.mts +1 -1
- package/dist/services/tray-menu/schemas.d.mts +1 -1
- package/dist/session-CoGaTin6.mjs +69 -0
- package/dist/session-Dp7z5N1d.mjs +1 -0
- package/dist/{session-lineage-DR-9DU-U.d.mts → session-lineage-C1M7-O3C.d.mts} +3 -3
- package/dist/{tool-approval-service-MU_DmJsf.mjs → tool-approval-service-BNXgr-az.mjs} +1 -1
- package/dist/tools-BaO4GYj0.mjs +1 -0
- package/dist/{transition-Dq41YCkc.d.mts → transition-Bbjlwv5K.d.mts} +1 -1
- package/dist/{types-BMS6yfLS.d.mts → types-BNW5n6qm.d.mts} +1 -1
- package/dist/{types-BMlzmWp6.d.mts → types-CNkx2awa.d.mts} +12 -1
- package/dist/{types-Cse8s_cD.d.mts → types-D7W0ntGr.d.mts} +45 -18
- package/dist/{types-C76EP81O.d.mts → types-jruUn6oW.d.mts} +694 -282
- package/dist/workflow-engine/index.d.mts +41 -41
- package/dist/workflow-engine/index.mjs +1 -1
- package/dist/workflow-engine/package.d.mts +1 -1
- package/dist/workflow-engine/package.mjs +1 -1
- package/package.json +1 -1
- package/dist/adapter-BRxCc72E.mjs +0 -1
- package/dist/client-BgUjVbXX.mjs +0 -1
- package/dist/handlers-v47Gbsr1.mjs +0 -57
- package/dist/schemas-ftgVeWIG.mjs +0 -1
- package/dist/session-CKWfn3oc.mjs +0 -1
- package/dist/session-DCbJwYEU.mjs +0 -69
- package/dist/tools-BrNm-een.mjs +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _$zod from "zod";
|
|
2
2
|
import * as _$_makaio_core0 from "@makaio/framework/core";
|
|
3
|
-
import { MessagePageCursor, MessagePageCursorSchema, MessageStorageSubjects } from "@makaio/framework/contracts";
|
|
3
|
+
import { MessagePageCursor, MessagePageCursorSchema, MessageStorageSubjects as MessageStorageSubjects$1 } from "@makaio/framework/contracts";
|
|
4
4
|
import * as _$drizzle_orm_sqlite_core0 from "drizzle-orm/sqlite-core";
|
|
5
5
|
import * as _$zod_v4_core0 from "zod/v4/core";
|
|
6
6
|
|
|
@@ -241,7 +241,7 @@ declare const MessageStorageNamespace$1: {
|
|
|
241
241
|
tableName: "messages";
|
|
242
242
|
dataType: "string";
|
|
243
243
|
columnType: "SQLiteText";
|
|
244
|
-
data: "text" | "
|
|
244
|
+
data: "text" | "compact" | "voice";
|
|
245
245
|
driverParam: string;
|
|
246
246
|
notNull: false;
|
|
247
247
|
hasDefault: false;
|
|
@@ -268,8 +268,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
268
268
|
message: _$zod.ZodObject<{
|
|
269
269
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
270
270
|
text: "text";
|
|
271
|
-
voice: "voice";
|
|
272
271
|
compact: "compact";
|
|
272
|
+
voice: "voice";
|
|
273
273
|
}>>;
|
|
274
274
|
sessionId: _$zod.ZodString;
|
|
275
275
|
role: _$zod.ZodEnum<{
|
|
@@ -335,9 +335,9 @@ declare const MessageStorageNamespace$1: {
|
|
|
335
335
|
isError: _$zod.ZodOptional<_$zod.ZodBoolean>;
|
|
336
336
|
}, _$zod_v4_core0.$strip>], "type">>;
|
|
337
337
|
agentId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
338
|
+
timestamp: _$zod.ZodNumber;
|
|
338
339
|
adapterSessionId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
339
340
|
turnId: _$zod.ZodNullable<_$zod.ZodString>;
|
|
340
|
-
timestamp: _$zod.ZodNumber;
|
|
341
341
|
contentText: _$zod.ZodString;
|
|
342
342
|
adapterMessageId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
343
343
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
@@ -420,8 +420,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
420
420
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
421
421
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
422
422
|
text: "text";
|
|
423
|
-
voice: "voice";
|
|
424
423
|
compact: "compact";
|
|
424
|
+
voice: "voice";
|
|
425
425
|
}>>;
|
|
426
426
|
}, _$zod_v4_core0.$strip>;
|
|
427
427
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -515,8 +515,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
515
515
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
516
516
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
517
517
|
text: "text";
|
|
518
|
-
voice: "voice";
|
|
519
518
|
compact: "compact";
|
|
519
|
+
voice: "voice";
|
|
520
520
|
}>>;
|
|
521
521
|
}, _$zod_v4_core0.$strip>>;
|
|
522
522
|
nextCursor: _$zod.ZodNullable<_$zod.ZodObject<{
|
|
@@ -604,8 +604,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
604
604
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
605
605
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
606
606
|
text: "text";
|
|
607
|
-
voice: "voice";
|
|
608
607
|
compact: "compact";
|
|
608
|
+
voice: "voice";
|
|
609
609
|
}>>;
|
|
610
610
|
}, _$zod_v4_core0.$strip>>;
|
|
611
611
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -689,8 +689,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
689
689
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
690
690
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
691
691
|
text: "text";
|
|
692
|
-
voice: "voice";
|
|
693
692
|
compact: "compact";
|
|
693
|
+
voice: "voice";
|
|
694
694
|
}>>;
|
|
695
695
|
}, _$zod_v4_core0.$strip>>;
|
|
696
696
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -774,8 +774,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
774
774
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
775
775
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
776
776
|
text: "text";
|
|
777
|
-
voice: "voice";
|
|
778
777
|
compact: "compact";
|
|
778
|
+
voice: "voice";
|
|
779
779
|
}>>;
|
|
780
780
|
}, _$zod_v4_core0.$strip>>;
|
|
781
781
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -861,8 +861,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
861
861
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
862
862
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
863
863
|
text: "text";
|
|
864
|
-
voice: "voice";
|
|
865
864
|
compact: "compact";
|
|
865
|
+
voice: "voice";
|
|
866
866
|
}>>;
|
|
867
867
|
}, _$zod_v4_core0.$strip>>;
|
|
868
868
|
total: _$zod.ZodNumber;
|
|
@@ -957,8 +957,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
957
957
|
timestamp: _$zod.ZodNumber;
|
|
958
958
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
959
959
|
text: "text";
|
|
960
|
-
voice: "voice";
|
|
961
960
|
compact: "compact";
|
|
961
|
+
voice: "voice";
|
|
962
962
|
}>>;
|
|
963
963
|
}, _$zod_v4_core0.$strip>;
|
|
964
964
|
response: _$zod.ZodObject<{
|
|
@@ -1041,8 +1041,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1041
1041
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1042
1042
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1043
1043
|
text: "text";
|
|
1044
|
-
voice: "voice";
|
|
1045
1044
|
compact: "compact";
|
|
1045
|
+
voice: "voice";
|
|
1046
1046
|
}>>;
|
|
1047
1047
|
}, _$zod_v4_core0.$strip>;
|
|
1048
1048
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1053,8 +1053,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1053
1053
|
message: _$zod.ZodObject<{
|
|
1054
1054
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1055
1055
|
text: "text";
|
|
1056
|
-
voice: "voice";
|
|
1057
1056
|
compact: "compact";
|
|
1057
|
+
voice: "voice";
|
|
1058
1058
|
}>>;
|
|
1059
1059
|
sessionId: _$zod.ZodString;
|
|
1060
1060
|
role: _$zod.ZodEnum<{
|
|
@@ -1120,9 +1120,9 @@ declare const MessageStorageNamespace$1: {
|
|
|
1120
1120
|
isError: _$zod.ZodOptional<_$zod.ZodBoolean>;
|
|
1121
1121
|
}, _$zod_v4_core0.$strip>], "type">>;
|
|
1122
1122
|
agentId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1123
|
+
timestamp: _$zod.ZodNumber;
|
|
1123
1124
|
adapterSessionId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1124
1125
|
turnId: _$zod.ZodNullable<_$zod.ZodString>;
|
|
1125
|
-
timestamp: _$zod.ZodNumber;
|
|
1126
1126
|
contentText: _$zod.ZodString;
|
|
1127
1127
|
adapterMessageId: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1128
1128
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
@@ -1205,8 +1205,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1205
1205
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1206
1206
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1207
1207
|
text: "text";
|
|
1208
|
-
voice: "voice";
|
|
1209
1208
|
compact: "compact";
|
|
1209
|
+
voice: "voice";
|
|
1210
1210
|
}>>;
|
|
1211
1211
|
}, _$zod_v4_core0.$strip>;
|
|
1212
1212
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1300,8 +1300,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1300
1300
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1301
1301
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1302
1302
|
text: "text";
|
|
1303
|
-
voice: "voice";
|
|
1304
1303
|
compact: "compact";
|
|
1304
|
+
voice: "voice";
|
|
1305
1305
|
}>>;
|
|
1306
1306
|
}, _$zod_v4_core0.$strip>>;
|
|
1307
1307
|
nextCursor: _$zod.ZodNullable<_$zod.ZodObject<{
|
|
@@ -1389,8 +1389,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1389
1389
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1390
1390
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1391
1391
|
text: "text";
|
|
1392
|
-
voice: "voice";
|
|
1393
1392
|
compact: "compact";
|
|
1393
|
+
voice: "voice";
|
|
1394
1394
|
}>>;
|
|
1395
1395
|
}, _$zod_v4_core0.$strip>>;
|
|
1396
1396
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1474,8 +1474,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1474
1474
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1475
1475
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1476
1476
|
text: "text";
|
|
1477
|
-
voice: "voice";
|
|
1478
1477
|
compact: "compact";
|
|
1478
|
+
voice: "voice";
|
|
1479
1479
|
}>>;
|
|
1480
1480
|
}, _$zod_v4_core0.$strip>>;
|
|
1481
1481
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1559,8 +1559,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1559
1559
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1560
1560
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1561
1561
|
text: "text";
|
|
1562
|
-
voice: "voice";
|
|
1563
1562
|
compact: "compact";
|
|
1563
|
+
voice: "voice";
|
|
1564
1564
|
}>>;
|
|
1565
1565
|
}, _$zod_v4_core0.$strip>>;
|
|
1566
1566
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1646,8 +1646,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1646
1646
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1647
1647
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1648
1648
|
text: "text";
|
|
1649
|
-
voice: "voice";
|
|
1650
1649
|
compact: "compact";
|
|
1650
|
+
voice: "voice";
|
|
1651
1651
|
}>>;
|
|
1652
1652
|
}, _$zod_v4_core0.$strip>>;
|
|
1653
1653
|
total: _$zod.ZodNumber;
|
|
@@ -1742,8 +1742,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1742
1742
|
timestamp: _$zod.ZodNumber;
|
|
1743
1743
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1744
1744
|
text: "text";
|
|
1745
|
-
voice: "voice";
|
|
1746
1745
|
compact: "compact";
|
|
1746
|
+
voice: "voice";
|
|
1747
1747
|
}>>;
|
|
1748
1748
|
}, _$zod_v4_core0.$strip>;
|
|
1749
1749
|
response: _$zod.ZodObject<{
|
|
@@ -1826,8 +1826,8 @@ declare const MessageStorageNamespace$1: {
|
|
|
1826
1826
|
editOf: _$zod.ZodOptional<_$zod.ZodString>;
|
|
1827
1827
|
origin: _$zod.ZodOptional<_$zod.ZodEnum<{
|
|
1828
1828
|
text: "text";
|
|
1829
|
-
voice: "voice";
|
|
1830
1829
|
compact: "compact";
|
|
1830
|
+
voice: "voice";
|
|
1831
1831
|
}>>;
|
|
1832
1832
|
}, _$zod_v4_core0.$strip>;
|
|
1833
1833
|
}, _$zod_v4_core0.$strip>;
|
|
@@ -1901,7 +1901,7 @@ declare const MessageStorageNamespace$1: {
|
|
|
1901
1901
|
adapterSessionId?: string | undefined;
|
|
1902
1902
|
adapterMessageId?: string | undefined;
|
|
1903
1903
|
editOf?: string | undefined;
|
|
1904
|
-
origin?: "text" | "
|
|
1904
|
+
origin?: "text" | "compact" | "voice" | undefined;
|
|
1905
1905
|
} | {
|
|
1906
1906
|
sessionId: string;
|
|
1907
1907
|
role: "user" | "assistant";
|
|
@@ -1960,10 +1960,10 @@ declare const MessageStorageNamespace$1: {
|
|
|
1960
1960
|
output: string;
|
|
1961
1961
|
isError?: boolean | undefined;
|
|
1962
1962
|
})[];
|
|
1963
|
-
turnId: string | null;
|
|
1964
1963
|
timestamp: number;
|
|
1964
|
+
turnId: string | null;
|
|
1965
1965
|
contentText: string;
|
|
1966
|
-
origin?: "text" | "
|
|
1966
|
+
origin?: "text" | "compact" | "voice" | undefined;
|
|
1967
1967
|
agentId?: string | undefined;
|
|
1968
1968
|
adapterSessionId?: string | undefined;
|
|
1969
1969
|
adapterMessageId?: string | undefined;
|
|
@@ -2030,10 +2030,10 @@ declare const MessageStorageNamespace$1: {
|
|
|
2030
2030
|
})[];
|
|
2031
2031
|
messageId: string;
|
|
2032
2032
|
agentId: never;
|
|
2033
|
+
timestamp: number;
|
|
2033
2034
|
adapterSessionId: never;
|
|
2034
2035
|
turnId: string | null;
|
|
2035
2036
|
limit: never;
|
|
2036
|
-
timestamp: number;
|
|
2037
2037
|
query: string;
|
|
2038
2038
|
contentText: string;
|
|
2039
2039
|
adapterMessageId: string;
|
|
@@ -2044,4 +2044,4 @@ declare const MessageStorageNamespace$1: {
|
|
|
2044
2044
|
} | undefined;
|
|
2045
2045
|
};
|
|
2046
2046
|
//#endregion
|
|
2047
|
-
export { MessageStorageSubjects as i, MessagePageCursorSchema as n, MessageStorageNamespace$1 as r, MessagePageCursor as t };
|
|
2047
|
+
export { MessageStorageSubjects$1 as i, MessagePageCursorSchema as n, MessageStorageNamespace$1 as r, MessagePageCursor as t };
|
|
@@ -131,8 +131,13 @@ declare class WorkflowExecutor extends BaseService {
|
|
|
131
131
|
*
|
|
132
132
|
* Coordinator sessions are created with this target working directory so
|
|
133
133
|
* in-process shell steps and workflow-level workers share the same workspace.
|
|
134
|
+
*
|
|
135
|
+
* Throws when a `parentSessionId` is supplied but the session does not exist.
|
|
136
|
+
* The session create handler enforces the same invariant, but throwing here
|
|
137
|
+
* provides a cleaner error before any coordinator session is created.
|
|
134
138
|
* @param parentSessionId - Optional parent session identifier.
|
|
135
139
|
* @returns Parent session working directory, or the executor default cwd.
|
|
140
|
+
* @throws When `parentSessionId` is provided but the session is not found.
|
|
136
141
|
*/
|
|
137
142
|
private resolveExecutionWorkspaceRoot;
|
|
138
143
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as ee,O as te,P as ne,R as re,S as ie,T as ae,U as oe,V as se,W as ce,X as le,Y as ue,Z as p,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,j as ye,k as be,l as xe,m,n as Se,o as Ce,p as we,q as Te,r as Ee,t as De,u as Oe,w as ke,x as Ae,y as je,z as Me}from"./loop-gate-handlers-Bjmat-K3.mjs";import{matchesFilter as Ne,matchesSubscription as Pe}from"@makaio/framework/bus";import{ArtifactSubjects as Fe,EXECUTION_LIST_DEFAULT_LIMIT as Ie,EXECUTION_LIST_MAX_LIMIT as h,EXECUTION_LIST_MIN_LIMIT as g,ExecutionHintsSchema as Le,ExecutionsByArtifactRefsQuerySchema as Re,JsonPatchOperationSchema as ze,JsonValueSchema as Be,SessionSubjects as Ve,WORKFLOW_CANCELLED_REASON as _,WorkflowError as v,WorkflowErrorCode as He,WorkflowNamespace as Ue,WorkflowSubjects as y,createWorkflowCancelSubject as We,dep as Ge,extensionToken as Ke,serializeArtifactRef as qe}from"@makaio/framework/contracts";import{BaseService as Je}from"@makaio/framework/service-base";import{defineDialectSchema as Ye,executeTransaction as b,getDatabaseDialect as Xe,registerDrizzleHandlers as Ze,resolveSchema as x}from"@makaio/framework/storage/drizzle";import{and as S,asc as C,count as Qe,desc as w,eq as T,getTableColumns as $e,gte as et,isNotNull as tt,lt as nt,lte as rt,or as it,sql as E,sum as D}from"drizzle-orm";import{compile as at}from"@makaio/framework/expression";import*as ot from"node:os";import{SessionToken as st}from"@makaio/framework/services";const ct=ae.postgres,lt=a.postgres,ut=r.postgres,dt=d.postgres,ft=se.postgres,pt=be.postgres,mt=Me.postgres,ht=ue.postgres,gt=o.postgres,_t=oe.postgres,vt=Te.postgres,yt=ye.postgres,bt=ee.postgres,O=Ye({workflowDefinitions:ke,workflowExecutions:ne,workflowExecutionFrames:i,workflowGateInstances:c,workflowStepSpans:t,workflowExecutionLinks:te,workflowRunContexts:re,worklogSummaries:l,worklogFrameEntries:ce,worklogArtifactWrites:s,worklogGateEvents:u,workflowExecutionState:e,workflowExecutionStateEvents:f},{workflowDefinitions:ct,workflowExecutions:lt,workflowExecutionFrames:ut,workflowGateInstances:dt,workflowStepSpans:ft,workflowExecutionLinks:pt,workflowRunContexts:mt,worklogSummaries:ht,worklogFrameEntries:gt,worklogArtifactWrites:_t,worklogGateEvents:vt,workflowExecutionState:yt,workflowExecutionStateEvents:bt});function k(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function A(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function xt(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=k(t);return[T(e.scopeType,n),T(e.scopeKind,r),T(e.scopeId,i)]}function j(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:A(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function St(e,t){let n=k(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Ct(e,t){let{workflowDefinitions:r}=x(t,O),i=$e(r),a=e.on(n.get,async e=>{let n=await t.select().from(r).where(T(r.id,e.payload.id)).limit(1);e.setResult({workflow:n[0]?j(n[0]):null})}),o=e.on(n.set,async n=>{let a=n.payload.workflow,o=Date.now(),s=St(a,o),c=await t.insert(r).values(s).onConflictDoNothing({target:r.id}).returning();if(c.length>0){await e.emit(p.definition.created,j(c[0])),n.setResult({id:a.id});return}let[l]=await t.update(r).set({name:s.name,root:s.root,updatedAt:o,createdAt:E`COALESCE(${i.createdAt}, ${o})`,description:s.description===null?E`${i.description}`:s.description,inputSchema:s.inputSchema===null?E`${i.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?E`${i.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?E`${i.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?E`${i.artifact}`:s.artifact,triggers:s.triggers===null?E`${i.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?E`${i.canvasLayout}`:s.canvasLayout,source:s.source===null?E`${i.source}`:s.source,executionHints:s.executionHints===null?E`${i.executionHints}`:s.executionHints,...k(a.scope)}).where(T(r.id,a.id)).returning();l&&await e.emit(p.definition.updated,j(l)),n.setResult({id:a.id})}),s=e.on(n.delete,async n=>{let i=(await t.delete(r).where(T(r.id,n.payload.id)).returning()).length>0;i&&await e.emit(p.definition.deleted,{id:n.payload.id}),n.setResult({deleted:i})}),c=e.on(n.list,async e=>{let n=e.payload,i=n.scope?xt(r,n.scope):[],a=i.length>0?await t.select().from(r).where(S(...i)):await t.select().from(r);e.setResult({workflows:a.map(j)})});return()=>{a(),o(),s(),c()}}function wt(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function Tt(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function Et(e,t){let{workflowExecutionFrames:r}=x(t,O),i=e.on(n.setFrame,async e=>{let{executionId:n,frame:i}=e.payload,a=Tt(n,i);await t.insert(r).values(a).onConflictDoUpdate({target:r.frameId,set:a}),e.setResult({frameId:i.frameId})}),a=e.on(n.getFrame,async e=>{let n=await t.select().from(r).where(T(r.frameId,e.payload.frameId)).limit(1);e.setResult({frame:n[0]?wt(n[0]):null})}),o=e.on(n.listFrames,async e=>{let n=await t.select().from(r).where(T(r.executionId,e.payload.executionId)).orderBy(C(r.startedAt),C(r.frameId));e.setResult({frames:n.map(wt)})});return()=>{i(),a(),o()}}function Dt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function M(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function N(e){return{id:Dt(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function Ot(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??Ie;if(!Number.isInteger(i)||i<g||i>h)throw Error(`Gate instance list limit must be an integer between ${g} and ${h}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[T(r.executionId,e)],...t===void 0?[]:[T(r.status,t)]]}}function kt(e,t){let{workflowExecutions:r,workflowGateInstances:i}=x(t,O),a=e.on(n.setGateInstance,async e=>{let n=e.payload.gate,r=N(n);await t.insert(i).values(r).onConflictDoUpdate({target:i.id,set:r}),e.setResult({id:r.id})}),o=e.on(n.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,r=N(n),a=await t.update(i).set(r).where(S(T(i.id,r.id),T(i.status,`waiting`))).returning({id:i.id});e.setResult({accepted:a.length===1})}),s=e.on(n.getGateInstance,async e=>{let{executionId:n,nodeId:r,frameId:a}=e.payload,o=[T(i.executionId,n),T(i.nodeId,r)];a!==void 0&&o.push(T(i.frameId,a));let s=await t.select().from(i).where(S(...o)).limit(1);e.setResult({gate:s[0]?M(s[0]):null})}),c=e.on(n.listGateInstances,async e=>{let{executionId:n,status:r,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Ot(n,r,a,i),c=await t.select().from(i).where(S(...s)).orderBy(w(i.createdAt),w(i.id)).limit(o);e.setResult({gates:c.map(M)})}),l=e.on(n.listPausedGateTimeouts,async e=>{let n=await t.select({gate:i}).from(i).innerJoin(r,T(i.executionId,r.id)).where(S(T(i.status,`waiting`),T(r.status,`paused`),tt(i.timeoutMs)));e.setResult({gates:n.map(e=>M(e.gate))})});return()=>{a(),o(),s(),c(),l()}}function At(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function jt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Mt(e,t){let{workflowStepSpans:r,workflowExecutionLinks:i}=x(t,O),a=e.on(n.setSpan,async e=>{let{span:n}=e.payload;await t.insert(r).values(n).onConflictDoUpdate({target:[r.executionId,r.frameId],set:n}),e.setResult({id:`${n.executionId}:${n.frameId}`})}),o=e.on(n.listSpans,async e=>{let n=await t.select().from(r).where(T(r.executionId,e.payload.executionId)).orderBy(C(r.startedAt),C(r.stepId),C(r.frameId));e.setResult({spans:n.map(At)})}),s=e.on(n.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(i).values(n).onConflictDoUpdate({target:[i.sourceExecutionId,i.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(n.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:r}=e.payload;if(n===void 0&&r===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[T(i.sourceExecutionId,n)],...r===void 0?[]:[T(i.targetExecutionId,r)]],o=t.select().from(i).where(S(...a));e.setResult({links:(await o).map(jt)})});return()=>{a(),o(),s(),c()}}function Nt(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function Pt(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function Ft(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Pt(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:A(e),...e.executionHints===null?{}:{executionHints:e.executionHints},...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function It(e){let t=Nt(e.source),n=k(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,artifactRef:e.artifactRef??null,executionHints:e.executionHints??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy}}async function Lt(e,t,n){let r=It(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Rt(e,t){let{workflowRunContexts:r}=x(t,O),i=e.on(n.setRunContext,async e=>{let n=e.payload.runContext;await Lt(t,n,r),e.setResult({executionId:n.executionId})}),a=e.on(n.getRunContext,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(T(r.executionId,n)),a=i[0]?Ft(i[0]):null;e.setResult({runContext:a})});return()=>{i(),a()}}function P(e,t){return t===null?Xe(e)===`postgres`?E`'null'::jsonb`:E`'null'`:t}async function zt(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=x(e,O),a=Date.now(),o=P(e,n);await b(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Bt(e,t){let{workflowExecutionState:n}=x(e,O),r=(await e.select().from(n).where(T(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Vt(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=x(e,O),i=Date.now(),a=P(e,t.nextValue);return b(e,async e=>{let o=(await e.select().from(n).where(T(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=Ae(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(S(T(n.executionId,t.executionId),T(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function Ht(e,t){let r=e.on(n.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await zt(t,n,r),e.setResult({})}),i=e.on(n.getState,async e=>{let{executionId:n}=e.payload,r=await Bt(t,n);e.setResult({state:r})}),a=e.on(n.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Vt(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{r(),i(),a()}}function Ut(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function F(e,t){let{worklogSummaries:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:t})}async function I(e,t){let{worklogSummaries:n}=x(e,O),r=await e.select().from(n).where(T(n.executionId,t)).limit(1);return r[0]?Ut(r[0]):null}async function Wt(e,t={}){let{worklogSummaries:n}=x(e,O),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[T(n.workflowId,r)],...i===void 0?[]:[T(n.status,i)]],c=s.length>0?S(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(w(n.startedAt)).limit(a).offset(o),e.select({count:Qe()}).from(n).where(c)]);return{items:l.map(Ut),total:u[0]?.count??0}}async function L(e,t){let{worklogFrameEntries:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t})}async function R(e,t){let{worklogFrameEntries:n}=x(e,O);return(await e.select().from(n).where(T(n.frameId,t)).limit(1))[0]??null}async function Gt(e,t){let{worklogArtifactWrites:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function Kt(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function z(e,t){let{worklogGateEvents:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function qt(e,t){let{worklogGateEvents:n}=x(e,O);return(await e.select().from(n).where(T(n.id,t)).limit(1))[0]??null}function B(e,t,n){return`${e}:${t}:${n}`}async function Jt(e,t){let{worklogFrameEntries:n}=x(e,O),[r]=await e.select({totalInputTokens:D(n.inputTokens),totalOutputTokens:D(n.outputTokens),totalEstimatedCost:D(n.estimatedCost)}).from(n).where(T(n.executionId,t));return{totalInputTokens:r?.totalInputTokens===null?0:Number(r?.totalInputTokens),totalOutputTokens:r?.totalOutputTokens===null?0:Number(r?.totalOutputTokens),totalEstimatedCost:r?.totalEstimatedCost===null?0:Number(r?.totalEstimatedCost)}}async function Yt(e,t={}){let{worklogSummaries:n}=x(e,O),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[T(n.workflowId,r)],...i===void 0?[]:[et(n.startedAt,i)],...a===void 0?[]:[rt(n.startedAt,a)]],s=o.length>0?S(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:Qe()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:D(n.durationMs),totalInputTokens:D(n.totalInputTokens),totalOutputTokens:D(n.totalOutputTokens),totalEstimatedCost:D(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function Xt(e,t,n,r,i){let a=await R(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(Fe.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function V(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function H(e,t){try{await e.emit(p.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}async function Zt(e,t,n){await F(t,{executionId:n.executionId,workflowId:n.workflowId,workflowName:null,status:`running`,startedAt:n.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),await H(e,n.executionId)}async function Qt(e,t,n){let r=n.completedAt??Date.now(),i=await I(t,n.executionId);await F(t,{executionId:n.executionId,workflowId:i?.workflowId??n.executionId,workflowName:i?.workflowName??null,status:`completed`,startedAt:i?.startedAt??r-n.totalDuration,completedAt:r,durationMs:n.totalDuration,totalInputTokens:i?.totalInputTokens??null,totalOutputTokens:i?.totalOutputTokens??null,totalEstimatedCost:i?.totalEstimatedCost??null,error:null,failedNodeId:null}),await H(e,n.executionId)}async function $t(e,t,n,r,i,a,o){let s=await I(t,n),c=s?.startedAt??o;await F(t,{executionId:n,workflowId:s?.workflowId??n,workflowName:s?.workflowName??null,status:r,startedAt:c,completedAt:o,durationMs:o-c,totalInputTokens:s?.totalInputTokens??null,totalOutputTokens:s?.totalOutputTokens??null,totalEstimatedCost:s?.totalEstimatedCost??null,error:i,failedNodeId:a}),await H(e,n)}async function en(e,t,n){let r=await Jt(t,n);if(r.totalInputTokens>0||r.totalOutputTokens>0||r.totalEstimatedCost>0){let e=await I(t,n);e&&await F(t,{executionId:n,workflowId:e.workflowId,workflowName:e.workflowName??null,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??null,durationMs:e.durationMs??null,totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost,error:e.error??null,failedNodeId:e.failedNodeId??null})}}function tn(e,t){return[e.on(p.execution.started,async n=>{let{executionId:r}=n.payload;await V(`execution.started[${r}]`,()=>Zt(e,t,n.payload))}),e.on(p.execution.completed,async n=>{let{executionId:r}=n.payload;await V(`execution.completed[${r}]`,()=>Qt(e,t,n.payload))}),e.on(p.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await V(`execution.failed[${r}]`,()=>$t(e,t,r,`failed`,i,a??null,o))}),e.on(p.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await V(`execution.cancelled[${r}]`,()=>$t(e,t,r,`cancelled`,null,null,i))})]}function nn(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function rn(e,t,n,r,i,a,o){let s=o??Date.now();await L(t,{frameId:r,executionId:n,...nn(await R(t,r),i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await en(e,t,n),await H(e,n)}async function an(e,t,n,r,i,a,o,s){let c=s??Date.now();await L(t,{frameId:r,executionId:n,...nn(await R(t,r),i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await H(e,n)}function on(e,t){return[e.on(p.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await V(`frame.started[${i}]`,async()=>{await L(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await H(e,r)})}),e.on(p.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await V(`frame.completed[${i}]`,()=>rn(e,t,r,i,a,o,s))}),e.on(p.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await V(`frame.failed[${i}]`,()=>an(e,t,r,i,a,o,s,c))})]}const sn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function cn(e,t){return[e.on(p.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await V(`gate.suspended[${i}]`,async()=>{await z(t,{id:B(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await H(e,r)})}),e.on(p.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await V(`gate.resumed[${i}]`,async()=>{let n=B(r,a,i),s=await qt(t,n),c=Date.now();await z(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await H(e,r)})}),e.on(p.gate.resolved,async n=>ln(n.payload,e,t)),e.on(p.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await V(`artifact.updated[${r}:${i}]`,async()=>{let n=await Xt(e,t,i,a,o);if(n===null)return;let s=Date.now();await Gt(t,{id:Kt(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await H(e,r)})})]}async function ln(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await V(`gate.resolved[${i}]`,async()=>{let s=B(r,a,i),c=await qt(n,s),l=Date.now();await z(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:sn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await H(t,r)})}function un(e,t){let n=[...tn(e,t),...on(e,t),...cn(e,t),e.on(p.worklog.get,async e=>{let{executionId:n}=e.payload,r=await I(t,n);e.setResult({summary:r})}),e.on(p.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Wt(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(p.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await Yt(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function U(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:A(e)}}function W(e){let t=k(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function dn(e,t,n,r,i,a){let o=[...e?[T(a.workflowId,e)]:[],...n?[T(a.status,n)]:[],...i===void 0?[]:[T(a.artifactKind,i.kind),T(a.artifactId,i.id)]];if(t&&o.push(...xt(a,t)),r){let e=it(nt(a.startedAt,r.startedAt),S(T(a.startedAt,r.startedAt),nt(a.id,r.id)));e&&o.push(e)}return o}async function fn(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=x(e,O),u=W(t);await b(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(T(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await Lt(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=P(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function pn(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=x(e,O),a=W(t),o=N(n);await b(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function mn(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=x(e,O);return b(e,async e=>{if((await e.select().from(i).where(T(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(S(T(a.executionId,t),T(a.status,`waiting`)))).map(e=>({...M(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(T(i.id,t));for(let t of o){let n=N(t);await e.update(a).set(n).where(T(a.id,n.id))}return{cancelled:!0,gates:o}})}async function hn(e,t,n,r,i,a){let{workflowExecutions:o}=x(e,O);return b(e,async e=>{if((await e.select({id:o.id}).from(o).where(T(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(T(o.id,t)),!0})}function gn(e,t){let{workflowExecutions:r}=x(t,O),i=e.on(n.getExecution,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(T(r.id,n));e.setResult({execution:i[0]?U(i[0]):null})}),a=e.on(n.setExecution,async e=>{let n=e.payload.execution,i=W(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:n.id})}),o=e.on(n.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await fn(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(n.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await pn(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(n.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await hn(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(n.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await mn(t,n,r,i))});return()=>{i(),a(),o(),s(),c(),l()}}function _n(e,t){let{workflowExecutions:r}=x(t,O),i=e.on(n.listExecutions,async e=>{let{workflowId:n,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(n===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=dn(n,i,a,s,c,r),u=o??Ie;if(!Number.isInteger(u)||u<g||u>h)throw Error(`Execution list limit must be an integer between ${g} and ${h}.`);let d=await t.select().from(r).where(S(...l)).orderBy(w(r.startedAt),w(r.id)).limit(u);e.setResult({executions:d.map(U)})}),a=e.on(n.listExecutionsByArtifactRefs,async e=>{let n=Re.safeParse(e.payload);if(!n.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${n.error.message}`);let{refs:i,limitPerRef:a}=n.data,o={};for(let e of i){let n=await t.select().from(r).where(S(T(r.artifactKind,e.kind),T(r.artifactId,e.id))).orderBy(w(r.startedAt),w(r.id)).limit(a);n.length>0&&(o[qe(e)]=n.map(U))}e.setResult({executionsByRef:o})});return()=>{i(),a()}}function G(e,t){let n=Ct(e,t),r=gn(e,t),i=_n(e,t),a=Et(e,t),o=kt(e,t),s=Mt(e,t),c=Rt(e,t),l=Ht(e,t),u=un(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u()}}function vn(e){return e.startsWith(`wfx-ext-`)}function yn(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function bn(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}function K(e,t){if(e.origin.local)return!0;let n=e.transport?.peer;return n?.authenticated!==!0||n.id!==t?!1:n.kind===`workflow-execution`?!0:n.kind===`e2e`&&n.encrypted===!0}async function xn(e,t){let{runContext:r}=await e.request(n.getRunContext,{executionId:t});if(r===null)throw Error(`Run context not found for execution: ${t}`);if(r.definitionSnapshot!==void 0)return r.definitionSnapshot;let{workflow:i}=await e.request(n.get,{id:r.workflowId});return i??void 0}function Sn(e){return[e.on(p.getDefinition,async t=>{let r=await e.request(n.get,{id:t.payload.id});t.setResult(r)}),e.on(p.setDefinition,async t=>{let r=await e.request(n.set,{workflow:t.payload.workflow});t.setResult(r)}),e.on(p.deleteDefinition,async t=>{let r=await e.request(n.delete,{id:t.payload.id});t.setResult(r)}),e.on(p.listDefinitions,async t=>{let r=await e.request(n.list,t.payload);t.setResult(r)}),e.on(p.getExecution,async t=>{let r=await e.request(n.getExecution,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listExecutions,async t=>{let r=await e.request(n.listExecutions,t.payload);t.setResult(r)}),e.on(p.listExecutionsByArtifactRefs,async t=>{let r=await e.request(n.listExecutionsByArtifactRefs,t.payload);t.setResult(r)}),e.on(p.listSpans,async t=>{let r=await e.request(n.listSpans,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listFrames,async t=>{let r=await e.request(n.listFrames,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listGateInstances,async t=>{let r=await e.request(n.listGateInstances,t.payload);t.setResult(r)}),e.on(p.setExecutionLink,async t=>{let r=await e.request(n.setExecutionLink,{link:t.payload.link});t.setResult(r)}),e.on(p.listExecutionLinks,async t=>{let r=await e.request(n.listExecutionLinks,t.payload);t.setResult(r)}),e.on(p.getRunContext,async t=>{let{executionId:r}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${r}`);let{runContext:i}=await e.request(n.getRunContext,{executionId:r});if(!i)throw Error(`Run context not found for execution: ${r}`);t.setResult(i)}),...Cn(e)]}function Cn(e){return[e.on(p.registerExternalExecution,async t=>{let r=le.registerExternalExecution.request.parse(t.payload),{name:i,scope:a,input:o}=r,s=de(`wfx-ext`),c={id:s,workflowId:i,status:`running`,inputs:o===void 0?{}:o,startedAt:Date.now(),scope:a??{type:`global`},...yn(r)};await e.request(n.setExecution,{execution:c}),t.setResult({executionId:s})}),e.on(p.completeExternalExecution,async t=>{let r=le.completeExternalExecution.request.parse(t.payload),{executionId:i,status:a,completedAt:o}=r;if(!vn(i))throw Error(`completeExternalExecution: execution "${i}" is engine-owned and must be completed through the engine finalizer, not this API`);let{execution:s}=await e.request(n.getExecution,{executionId:i});if(s===null)throw Error(`completeExternalExecution: execution "${i}" was not registered`);if(s.status!==`running`)throw Error(`completeExternalExecution: execution "${i}" cannot transition from status "${s.status}"`);let c=await e.request(n.updateExecution,{executionId:i,status:a,...bn(r),completedAt:o??Date.now()});t.setResult({success:c.success})})]}function wn(e){return[e.on(p.state.get,async t=>{let{executionId:r}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${r}`);let{state:i}=await e.request(n.getState,{executionId:r});if(i===null)throw Error(`no workflow state for execution ${r}`);t.setResult(i)}),e.on(p.state.patch,async t=>{let{executionId:r,expectedSequence:i,patch:a,nextValue:o}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${r}`);if(i===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=await xn(e,r);s!==void 0&&je(s,o,`next`),ze.array().parse(a);let c=await e.request(n.patchState,{executionId:r,expectedSequence:i,nextValue:o});e.emit(p.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}function Tn(e,t){return[e.on(p.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}async function En(e,t){let{runContext:r}=await e.bus.request(n.getRunContext,{executionId:t});if(r===null)throw new v(He.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return r}function Dn(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function On(e,t){let n=await En(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.executionHints??(t.mode===`snapshot`?n.executionHints:void 0),c=t.scopeOverride??n.scope,l={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,executionHints:s,scopeOverride:c,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:Dn(t.mode,t.reason)}]};return t.mode===`snapshot`?await Mn(e,n,l):An(n)?await Nn(e,n,l):await me(e,n.workflowId,l)}function kn(e,t){return An(e)?t.id:e.workflowId}function An(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function jn(e){let t=e.definitionSnapshot;if(t===void 0)throw new v(He.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Mn(e,t,n){let r=jn(t);return Oe(e,kn(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}async function Nn(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`)return xe(e,t.source.path,n);let r=jn(t);return Oe(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}var Pn=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(n.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:r}=await this.bus.request(n.getExecution,{executionId:e.executionId});return r?.status===`running`?`retry`:r?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function Fn(e){if(e!==void 0)return In(e)?e:{}}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ln(e){if(e!==void 0)return Be.parse(e)}function Rn(e){if(e!==void 0)return Le.parse(e)}function zn(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${ot.homedir()}/.makaio`,os:we(process.platform),arch:process.arch}}function Bn(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{packages:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,context:zn(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Vn(e){return e?.status===`paused`}function Hn(e){return e?.status===`waiting`}async function Un(e,t,r,i,a,o,s){t.delete(a.id),r.delete(a.id),i.delete(a.id);try{await e.request(n.restorePausedGateResumeState,{execution:a,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function Wn(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:r}=await e.request(n.listFrames,{executionId:t.executionId});if(r.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Gn(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Kn(e,t){if(t.frameId!==void 0){let{gate:r}=await e.request(n.getGateInstance,t);return Hn(r)?r:null}let{gates:r}=await e.request(n.listGateInstances,{executionId:t.executionId}),i=r.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return i.length===1?i[0]:null}var qn=class extends Je{static storage={drizzle:G};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...pe,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new Pn(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of Sn(this.bus))this.addCleanup(e);for(let e of wn(this.bus))this.addCleanup(e);for(let e of Tn(this.bus,()=>this.triggerTypeRegistry))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await m(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>zn(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Ve.get,{sessionId:e});return t?.targetWorkingDirectory??this.config.platformDefaults.cwd}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Bn(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(p.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload;try{let l=await me(this.buildStartDeps(),t,{input:Ln(n),config:Fn(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:Rn(c),scopeOverride:s});e.setResult({executionId:l})}catch(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(p.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,executionHints:l,reason:u}=e.payload;try{let d=await On(this.buildStartDeps(),{executionId:t,mode:n,input:Ln(r),config:Fn(i),parentSessionId:a,triggerPayload:o,artifactRef:s,executionHints:Rn(l),scopeOverride:c,reason:u});e.setResult({executionId:d})}catch(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(p.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,triggerPayload:n,scope:r}=e.payload;try{let i=await xe(this.buildStartDeps(),t,{triggerPayload:n,scopeOverride:r});e.setResult({executionId:i})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(p.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(We(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??_);let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(p.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o}=e.payload,s=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o});e.setResult({accepted:s})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(p.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(p.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(n.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Gn(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let n=await fe({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Ce(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,r.signal,void 0,n,{context:t.runContext.context,env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});De(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();i=await Se(t.workflow.root,a,o)}catch(n){if(r.signal.aborted||t.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,_);return}let i=n instanceof Error?n.message:String(n);await ve(this.buildFinalizerDeps(),t.execution,e,i);return}let a=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||t.execution.status===`cancelled`?await m(a,e,_):i.status===`failed`?await ve(a,t.execution,e,i.error):i.status===`paused`?(t.execution.status=`paused`,await this.bus.request(n.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await _e(a,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:r,frameId:i,resumeData:a,reason:o}=e,{execution:s}=await this.bus.request(n.getExecution,{executionId:t});if(!Vn(s))return!1;let c=await Kn(this.bus,{executionId:t,nodeId:r,frameId:i});if(c===null||!Ee(r,c.schema,a).valid)return!1;let{runContext:l}=await this.bus.request(n.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Wn(this.bus,l);let{accepted:u}=await this.bus.request(n.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:a,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Un(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,r),e}return this.gateTimeoutScheduler.clear(t,r,c.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(n.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let r=t.definitionSnapshot??(await this.bus.request(n.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(n.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await Wn(this.bus,t),await this.bus.request(n.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:r,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let a=ge(t,r,{resume:!0}),o=he(this.buildStartDeps(),a).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,o),!0}};function Jn(e,t){try{return at(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function Yn(e){let t=e.indexOf(`.`),n=e.indexOf(`:`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Xn(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Zn=class{bus;cleanupFns=[];initialized=!1;triggerIndex=new Map;subscribedNamespaces=new Set;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(y.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(y.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(y.definition.deleted,e=>{this.removeWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),!1)}getTestState(){return{initialized:this.initialized,cleanupFns:[...this.cleanupFns],subscribedNamespaces:new Set(this.subscribedNamespaces)}}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.indexWorkflow(t)}indexWorkflow(e){let t=e.triggers??[],n=[];for(let r of t){if(r.type!==`bus-event`)continue;let t=typeof r.filterExpression==`string`?Jn(r.filterExpression,e.id):void 0;typeof r.filterExpression==`string`&&t===void 0||(n.push({workflowId:e.id,subject:r.subject,filter:r.filter,compiledFilterExpr:t}),this.ensureNamespaceSubscribed(Yn(r.subject)))}n.length>0&&this.triggerIndex.set(e.id,n)}removeWorkflow(e){this.triggerIndex.delete(e)}ensureNamespaceSubscribed(e){if(this.subscribedNamespaces.has(e))return;let t=Xn(e),n=this.bus.on(t,e=>{if(e.isRequest)return;let t=typeof e.payload==`object`&&e.payload!==null?e.payload:{};this.handleBusEvent(e.subject,t)});this.cleanupFns.push(n),this.subscribedNamespaces.add(e)}handleBusEvent(e,t){for(let n of this.triggerIndex.values())for(let r of n)if(Pe(e,r.subject)&&!(r.filter&&!Ne(t,r.filter))){if(r.compiledFilterExpr){let n;try{n=r.compiledFilterExpr.evalSync({payload:t})}catch(n){console.error(`[BusEventTriggerEvaluator] filterExpression eval failed for workflow "${r.workflowId}" on subject "${e}" payload keys: [${Object.keys(t).join(`, `)}]`,n);continue}if(!n)continue}this.bus.request(y.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function q(e,t,n,r,i,a,o,s){return q.fromTZ(q.tp(e,t,n,r,i,a,o),s)}q.fromTZISO=(e,t,n)=>q.fromTZ(Qn(e,t),n),q.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=J(e.tz,n),i=new Date(n.getTime()-r),a=J(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=J(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},q.toTZ=function(e,t){let n=e.toLocaleString(`en-US`,{timeZone:t}).replace(/[\u202f]/,` `),r=new Date(n);return{y:r.getFullYear(),m:r.getMonth()+1,d:r.getDate(),h:r.getHours(),i:r.getMinutes(),s:r.getSeconds(),tz:t}},q.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function J(e,t=new Date){let n=t.toLocaleString(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).split(` `).slice(-1)[0],r=t.toLocaleString(`en-US`).replace(/[\u202f]/,` `);return Date.parse(`${r} GMT`)-Date.parse(`${r} ${n}`)}function Qn(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`minitz: Invalid ISO8601 passed to parser.`);let r=e.substring(9);return e.includes(`Z`)||r.includes(`-`)||r.includes(`+`)?q.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):q.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}q.minitz=q;var $n=32,Y=31|$n,er=[1,2,4,8,16],tr=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(e,t){this.pattern=e,this.timezone=t,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.replace(/\s+/g,` `).split(` `);if(e.length<5||e.length>6)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five or six space separated parts are required.`);if(e.length===5&&e.unshift(`0`),e[3].indexOf(`L`)>=0&&(e[3]=e[3].replace(`L`,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.replaceAlphaDays(e[5])),e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0){let t=new Z(new Date,this.timezone).getDate(!0);e[0]=e[0].replace(`?`,t.getSeconds().toString()),e[1]=e[1].replace(`?`,t.getMinutes().toString()),e[2]=e[2].replace(`?`,t.getHours().toString()),this.starDOM||(e[3]=e[3].replace(`?`,t.getDate().toString())),e[4]=e[4].replace(`?`,(t.getMonth()+1).toString()),this.starDOW||(e[5]=e[5].replace(`?`,t.getDay().toString()))}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1),this.partToArray(`dayOfWeek`,e[5],0,Y),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth;if(t===``&&!a)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let o=t.split(`,`);if(o.length>1)for(let t=0;t<o.length;t++)this.partToArray(e,o[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=parseInt(i[0],10)+n;if(isNaN(a))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,a,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`&&(t<0||t>=12))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t);this[e][t]=n}handleRangeWithStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);if(isNaN(l))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(u))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(isNaN(d))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(d===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(d>this[t].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[t].length+`)`);if(l>u)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}return[n,r]}handleRange(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;if(isNaN(o))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(o>s)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);a[0]===``&&(a[0]=`*`);let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(s===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(s>this[t].length)throw TypeError(`CronPattern: Syntax error, max steps for part is (`+this[t].length+`)`);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();return t===`@yearly`||t===`@annually`?`0 0 1 1 *`:t===`@monthly`?`0 0 1 * *`:t===`@weekly`?`0 0 * * 0`:t===`@daily`?`0 0 * * *`:t===`@hourly`?`0 * * * *`:e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|$n;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|er[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},nr=[31,28,31,30,31,30,31,31,30,31,30,31],X=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Z=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t===void 0)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&Y&&er[a-1]&r)return!0;if(r&$n){let r=new Date(Date.UTC(e,t+1,0)).getUTCDate();for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else{let t=q.toTZ(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.day>nr[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=q.fromTZISO(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(q.fromTZISO(e,this.tz))}findNext(e,t,n,r){let i=this[t],a;n.lastDayOfMonth&&(a=this.month===1?new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate():nr[this.month]);let o=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let s=this[t]+r;s<n[t].length;s++){let c=n[t][s];if(t===`day`&&n.lastDayOfMonth&&s-r==a&&(c=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(o+(s-r-1))%7];if(t&&t&Y)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,s-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);e.legacyMode&&!n.starDOM?c||=t:c&&=t}if(c)return this[t]=s-r,i===this[t]?1:2}return 3}recurse(e,t,n){let r=this.findNext(t,X[n][0],e,X[n][2]);if(r>1){let i=n+1;for(;i<X.length;)this[X[i][0]]=-X[i][2],i++;if(r===3)return this[X[n][1]]++,this[X[n][0]]=-X[n][2],this.apply(),this.recurse(e,t,0);if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=X.length?this:this.year>=3e3?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):q.fromTZ(q.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function rr(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode=e.legacyMode===void 0?!0:e.legacyMode,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.startAt&&=new Z(e.startAt,e.timezone),e.stopAt&&=new Z(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);return e}function Q(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function ir(e){return Q(e)}function ar(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var or=30*1e3,$=[],sr=class{name;options;_states;fn;constructor(e,t,n){let r,i;if(Q(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(Q(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=rr(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new tr(`* * * * *`)},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Z(e,this.options.timezone||this.options.utcOffset):this._states.pattern=new tr(e,this.options.timezone),this.name){if($.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);$.push(this)}return i!==void 0&&ir(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?t.getDate(!1):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=[],r=t||this._states.currentRun||void 0;for(;e--&&(r=this.nextRun(r));)n.push(r);return n}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Z||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Z(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=$.indexOf(this);e>=0&&$.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>or&&(t=or),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&ar(this._states.currentTimeout),this)}async _trigger(e){if(this._states.blocking=!0,this._states.currentRun=new Z(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){Q(this.options.catch)&&this.options.catch(e,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Z(e,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&Q(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Z(e,this.options.timezone||this.options.utcOffset),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Z(e,this.options.timezone||this.options.utcOffset);return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_calculatePreviousRun(e,t){let n=new Z(void 0,this.options.timezone||this.options.utcOffset),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Z(r,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function cr(e,t){return`${e}:${t}`}function lr(e){return e??`UTC`}var ur=class{bus;cleanupFns=[];initialized=!1;jobs=new Map;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(y.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(y.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(y.definition.deleted,e=>{this.unscheduleWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),!1)}activeJobCount(){return this.jobs.size}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.scheduleWorkflow(t)}scheduleWorkflow(e){if(e.scope.type===`global`)return;let t=e.triggers??[];for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==`cron`)continue;let i=cr(e.id,n);this.stopJob(i);try{let t=lr(r.timezone),a=new sr(r.schedule,{timezone:t},()=>{this.fireTrigger(e.id,n)});this.jobs.set(i,{workflowId:e.id,triggerIndex:n,job:a})}catch(t){console.warn(`[CronTriggerEvaluator] Skipping invalid cron trigger key="${i}" workflowId="${e.id}" triggerIndex=${n} schedule="${r.schedule}" timezone="${r.timezone??`UTC`}"`,t)}}}unscheduleWorkflow(e){for(let[t,n]of this.jobs)n.workflowId===e&&(n.job.stop(),this.jobs.delete(t))}stopJob(e){let t=this.jobs.get(e);t&&(t.job.stop(),this.jobs.delete(e))}stopAllJobs(){for(let e of this.jobs.values())e.job.stop();this.jobs.clear()}fireTrigger(e,t){this.bus.request(y.start,{workflowId:e,triggerPayload:{firedAt:Date.now(),triggerIndex:t}}).catch(n=>{console.error(`[CronTriggerEvaluator] Failed to start workflow "${e}" for cron trigger index ${t}:`,n)})}},dr=class extends Je{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new qn(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Zn(e),this.cronTriggerEvaluator=new ur(e)}get executor(){return this.workflowExecutor}get cronTriggers(){return this.cronTriggerEvaluator}setTriggerTypeRegistry(e){this.workflowExecutor.setTriggerTypeRegistry(e)}getTriggerTypeRegistry(){return this.workflowExecutor.getTriggerTypeRegistry()}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.busEventTriggerEvaluator.init(),await this.cronTriggerEvaluator.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.cronTriggerEvaluator.destroy(),()=>this.busEventTriggerEvaluator.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const fr=Ke(`makaio.workflow-engine`);function pr(e){return{name:fr.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[Ge(st.name)],critical:!0,namespaces:[Ue,ie],storage:{registerHandlers:Ze(G)},create:t=>new dr(t.bus,e)}}const mr=pr();export{qn as a,zt as c,dr as i,Vt as l,pr as n,G as o,mr as r,Bt as s,fr as t};
|
|
1
|
+
import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as ee,O as te,P as ne,R as re,S as ie,T as ae,U as oe,V as se,W as ce,X as le,Y as ue,Z as p,_ as de,a as fe,b as pe,c as me,d as he,f as ge,g as _e,h as ve,j as ye,k as be,l as xe,m,n as Se,o as Ce,p as we,q as Te,r as Ee,t as De,u as Oe,w as ke,x as Ae,y as je,z as Me}from"./loop-gate-handlers-Bjmat-K3.mjs";import{matchesFilter as Ne,matchesSubscription as Pe}from"@makaio/framework/bus";import{ArtifactSubjects as Fe,EXECUTION_LIST_DEFAULT_LIMIT as Ie,EXECUTION_LIST_MAX_LIMIT as h,EXECUTION_LIST_MIN_LIMIT as g,ExecutionHintsSchema as Le,ExecutionsByArtifactRefsQuerySchema as Re,JsonPatchOperationSchema as ze,JsonValueSchema as Be,SessionSubjects as Ve,WORKFLOW_CANCELLED_REASON as _,WorkflowError as v,WorkflowErrorCode as He,WorkflowNamespace as Ue,WorkflowSubjects as y,createWorkflowCancelSubject as We,dep as Ge,extensionToken as Ke,serializeArtifactRef as qe}from"@makaio/framework/contracts";import{BaseService as Je}from"@makaio/framework/service-base";import{defineDialectSchema as Ye,executeTransaction as b,getDatabaseDialect as Xe,registerDrizzleHandlers as Ze,resolveSchema as x}from"@makaio/framework/storage/drizzle";import{and as S,asc as C,count as Qe,desc as w,eq as T,getTableColumns as $e,gte as et,isNotNull as tt,lt as nt,lte as rt,or as it,sql as E,sum as D}from"drizzle-orm";import{compile as at}from"@makaio/framework/expression";import*as ot from"node:os";import{SessionToken as st}from"@makaio/framework/services";const ct=ae.postgres,lt=a.postgres,ut=r.postgres,dt=d.postgres,ft=se.postgres,pt=be.postgres,mt=Me.postgres,ht=ue.postgres,gt=o.postgres,_t=oe.postgres,vt=Te.postgres,yt=ye.postgres,bt=ee.postgres,O=Ye({workflowDefinitions:ke,workflowExecutions:ne,workflowExecutionFrames:i,workflowGateInstances:c,workflowStepSpans:t,workflowExecutionLinks:te,workflowRunContexts:re,worklogSummaries:l,worklogFrameEntries:ce,worklogArtifactWrites:s,worklogGateEvents:u,workflowExecutionState:e,workflowExecutionStateEvents:f},{workflowDefinitions:ct,workflowExecutions:lt,workflowExecutionFrames:ut,workflowGateInstances:dt,workflowStepSpans:ft,workflowExecutionLinks:pt,workflowRunContexts:mt,worklogSummaries:ht,worklogFrameEntries:gt,worklogArtifactWrites:_t,worklogGateEvents:vt,workflowExecutionState:yt,workflowExecutionStateEvents:bt});function k(e){return e.type===`global`?{scopeType:`global`,scopeKind:``,scopeId:``}:e.type===`external`?{scopeType:`external`,scopeKind:e.kind,scopeId:e.id}:{scopeType:e.type,scopeKind:``,scopeId:e.id}}function A(e){switch(e.scopeType){case`global`:return{type:`global`};case`external`:if(!e.scopeKind||!e.scopeId)throw Error(`Invalid external workflow scope row: scopeKind and scopeId are required`);return{type:`external`,kind:e.scopeKind,id:e.scopeId};case`workspace`:case`session`:if(!e.scopeId)throw Error(`Invalid ${e.scopeType} workflow scope row: scopeId is required`);return{type:e.scopeType,id:e.scopeId};default:{let t=e.scopeType;throw Error(`Unknown scope type: ${String(t)}`)}}}function xt(e,t){let{scopeType:n,scopeKind:r,scopeId:i}=k(t);return[T(e.scopeType,n),T(e.scopeKind,r),T(e.scopeId,i)]}function j(e){return{id:e.id,name:e.name,description:e.description??void 0,root:e.root,inputSchema:e.inputSchema??void 0,configSchema:e.configSchema??void 0,outputSchema:e.outputSchema??void 0,state:e.state??void 0,artifact:e.artifact??void 0,triggers:e.triggers??void 0,scope:A(e),canvasLayout:e.canvasLayout??void 0,source:e.source??void 0,executionHints:e.executionHints??void 0}}function St(e,t){let n=k(e.scope);return{id:e.id,name:e.name??e.id,root:e.root,description:e.description??null,inputSchema:e.inputSchema??null,configSchema:e.configSchema??null,outputSchema:e.outputSchema??null,state:e.state??null,artifact:e.artifact??null,triggers:e.triggers??null,canvasLayout:e.canvasLayout??null,source:e.source??null,executionHints:e.executionHints??null,createdAt:t,updatedAt:t,...n}}function Ct(e,t){let{workflowDefinitions:r}=x(t,O),i=$e(r),a=e.on(n.get,async e=>{let n=await t.select().from(r).where(T(r.id,e.payload.id)).limit(1);e.setResult({workflow:n[0]?j(n[0]):null})}),o=e.on(n.set,async n=>{let a=n.payload.workflow,o=Date.now(),s=St(a,o),c=await t.insert(r).values(s).onConflictDoNothing({target:r.id}).returning();if(c.length>0){await e.emit(p.definition.created,j(c[0])),n.setResult({id:a.id});return}let[l]=await t.update(r).set({name:s.name,root:s.root,updatedAt:o,createdAt:E`COALESCE(${i.createdAt}, ${o})`,description:s.description===null?E`${i.description}`:s.description,inputSchema:s.inputSchema===null?E`${i.inputSchema}`:s.inputSchema,configSchema:s.configSchema===null?E`${i.configSchema}`:s.configSchema,outputSchema:s.outputSchema===null?E`${i.outputSchema}`:s.outputSchema,state:s.state,artifact:s.artifact===null?E`${i.artifact}`:s.artifact,triggers:s.triggers===null?E`${i.triggers}`:s.triggers,canvasLayout:s.canvasLayout===null?E`${i.canvasLayout}`:s.canvasLayout,source:s.source===null?E`${i.source}`:s.source,executionHints:s.executionHints===null?E`${i.executionHints}`:s.executionHints,...k(a.scope)}).where(T(r.id,a.id)).returning();l&&await e.emit(p.definition.updated,j(l)),n.setResult({id:a.id})}),s=e.on(n.delete,async n=>{let i=(await t.delete(r).where(T(r.id,n.payload.id)).returning()).length>0;i&&await e.emit(p.definition.deleted,{id:n.payload.id}),n.setResult({deleted:i})}),c=e.on(n.list,async e=>{let n=e.payload,i=n.scope?xt(r,n.scope):[],a=i.length>0?await t.select().from(r).where(S(...i)):await t.select().from(r);e.setResult({workflows:a.map(j)})});return()=>{a(),o(),s(),c()}}function wt(e){return{frameId:e.frameId,nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,parentFrameId:e.parentFrameId??void 0,status:e.status,attempt:e.attempt,iteration:e.iteration??void 0,branchKey:e.branchKey??void 0,...e.outputPresent?{output:e.output}:{},error:e.error??void 0,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0}}function Tt(e,t){return{frameId:t.frameId,executionId:e,nodeId:t.nodeId,nodeType:t.nodeType,path:t.path,parentFrameId:t.parentFrameId??null,status:t.status,attempt:t.attempt,iteration:t.iteration??null,branchKey:t.branchKey??null,output:t.output===void 0?null:t.output,outputPresent:t.output!==void 0,error:t.error??null,startedAt:t.startedAt??null,completedAt:t.completedAt??null}}function Et(e,t){let{workflowExecutionFrames:r}=x(t,O),i=e.on(n.setFrame,async e=>{let{executionId:n,frame:i}=e.payload,a=Tt(n,i);await t.insert(r).values(a).onConflictDoUpdate({target:r.frameId,set:a}),e.setResult({frameId:i.frameId})}),a=e.on(n.getFrame,async e=>{let n=await t.select().from(r).where(T(r.frameId,e.payload.frameId)).limit(1);e.setResult({frame:n[0]?wt(n[0]):null})}),o=e.on(n.listFrames,async e=>{let n=await t.select().from(r).where(T(r.executionId,e.payload.executionId)).orderBy(C(r.startedAt),C(r.frameId));e.setResult({frames:n.map(wt)})});return()=>{i(),a(),o()}}function Dt(e){return`${e.executionId}:${e.nodeId}:${e.frameId}`}function M(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??void 0,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs??null,...e.resumeDataPresent?{resumeData:e.resumeData}:{},...e.reason===null?{}:{reason:e.reason},createdAt:e.createdAt,resolvedAt:e.resolvedAt??void 0}}function N(e){return{id:Dt(e),executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,schema:e.schema,prompt:e.prompt??null,status:e.status,autoAction:e.autoAction,timeoutMs:e.timeoutMs,resumeData:e.resumeData===void 0?null:e.resumeData,reason:e.reason??null,resumeDataPresent:e.resumeData!==void 0,createdAt:e.createdAt,resolvedAt:e.resolvedAt??null}}function Ot(e,t,n,r){if(e===void 0&&t===void 0)throw Error(`Either executionId or status is required to list gate instances.`);let i=n??Ie;if(!Number.isInteger(i)||i<g||i>h)throw Error(`Gate instance list limit must be an integer between ${g} and ${h}.`);return{resolvedLimit:i,predicates:[...e===void 0?[]:[T(r.executionId,e)],...t===void 0?[]:[T(r.status,t)]]}}function kt(e,t){let{workflowExecutions:r,workflowGateInstances:i}=x(t,O),a=e.on(n.setGateInstance,async e=>{let n=e.payload.gate,r=N(n);await t.insert(i).values(r).onConflictDoUpdate({target:i.id,set:r}),e.setResult({id:r.id})}),o=e.on(n.resolveWaitingGateInstance,async e=>{let n=e.payload.gate,r=N(n),a=await t.update(i).set(r).where(S(T(i.id,r.id),T(i.status,`waiting`))).returning({id:i.id});e.setResult({accepted:a.length===1})}),s=e.on(n.getGateInstance,async e=>{let{executionId:n,nodeId:r,frameId:a}=e.payload,o=[T(i.executionId,n),T(i.nodeId,r)];a!==void 0&&o.push(T(i.frameId,a));let s=await t.select().from(i).where(S(...o)).limit(1);e.setResult({gate:s[0]?M(s[0]):null})}),c=e.on(n.listGateInstances,async e=>{let{executionId:n,status:r,limit:a}=e.payload,{resolvedLimit:o,predicates:s}=Ot(n,r,a,i),c=await t.select().from(i).where(S(...s)).orderBy(w(i.createdAt),w(i.id)).limit(o);e.setResult({gates:c.map(M)})}),l=e.on(n.listPausedGateTimeouts,async e=>{let n=await t.select({gate:i}).from(i).innerJoin(r,T(i.executionId,r.id)).where(S(T(i.status,`waiting`),T(r.status,`paused`),tt(i.timeoutMs)));e.setResult({gates:n.map(e=>M(e.gate))})});return()=>{a(),o(),s(),c(),l()}}function At(e){return{executionId:e.executionId,frameId:e.frameId,stepId:e.stepId,stepType:e.stepType,status:e.status,startedAt:e.startedAt??void 0,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,inputTokens:e.inputTokens??void 0,outputTokens:e.outputTokens??void 0,estimatedCost:e.estimatedCost??void 0,toolCallCount:e.toolCallCount??void 0,input:e.input??void 0,output:e.output??void 0}}function jt(e){return{sourceExecutionId:e.sourceExecutionId,targetExecutionId:e.targetExecutionId,linkType:e.linkType,metadata:e.metadata??void 0}}function Mt(e,t){let{workflowStepSpans:r,workflowExecutionLinks:i}=x(t,O),a=e.on(n.setSpan,async e=>{let{span:n}=e.payload;await t.insert(r).values(n).onConflictDoUpdate({target:[r.executionId,r.frameId],set:n}),e.setResult({id:`${n.executionId}:${n.frameId}`})}),o=e.on(n.listSpans,async e=>{let n=await t.select().from(r).where(T(r.executionId,e.payload.executionId)).orderBy(C(r.startedAt),C(r.stepId),C(r.frameId));e.setResult({spans:n.map(At)})}),s=e.on(n.setExecutionLink,async e=>{let{link:n}=e.payload;await t.insert(i).values(n).onConflictDoUpdate({target:[i.sourceExecutionId,i.targetExecutionId],set:n}),e.setResult({id:`${n.sourceExecutionId}:${n.targetExecutionId}`})}),c=e.on(n.listExecutionLinks,async e=>{let{sourceExecutionId:n,targetExecutionId:r}=e.payload;if(n===void 0&&r===void 0)throw Error(`Either sourceExecutionId or targetExecutionId is required to list execution links.`);let a=[...n===void 0?[]:[T(i.sourceExecutionId,n)],...r===void 0?[]:[T(i.targetExecutionId,r)]],o=t.select().from(i).where(S(...a));e.setResult({links:(await o).map(jt)})});return()=>{a(),o(),s(),c()}}function Nt(e){switch(e.kind){case`path`:return{sourceKind:`path`,sourcePath:e.path,sourceFilename:null,sourceCode:null};case`source`:return{sourceKind:`source`,sourcePath:null,sourceFilename:e.filename,sourceCode:e.source};case`definition`:return{sourceKind:`definition`,sourcePath:null,sourceFilename:null,sourceCode:null}}}function Pt(e){switch(e.sourceKind){case`path`:if(!e.sourcePath)throw Error(`Invalid run context row: sourcePath required for kind=path`);return{kind:`path`,path:e.sourcePath};case`source`:if(!e.sourceFilename)throw Error(`Invalid run context row: sourceFilename required for kind=source`);return{kind:`source`,filename:e.sourceFilename,source:e.sourceCode??``};case`definition`:return{kind:`definition`,workflowId:e.workflowId};default:throw Error(`Unknown run context source kind: ${String(e.sourceKind)}`)}}function Ft(e){return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,source:Pt(e),definitionSnapshot:e.definitionSnapshot??void 0,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,...e.artifactRef===null?{}:{artifactRef:e.artifactRef},scope:A(e),...e.executionHints===null?{}:{executionHints:e.executionHints},...e.dispatchMetadata===null?{}:{dispatchMetadata:e.dispatchMetadata},cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function It(e){let t=Nt(e.source),n=k(e.scope);return{executionId:e.executionId,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId,...t,definitionSnapshot:e.definitionSnapshot??null,workerManifest:e.workerManifest,inputs:e.inputs,config:e.config??{},triggerPayload:e.triggerPayload,artifactRef:e.artifactRef??null,executionHints:e.executionHints??null,dispatchMetadata:e.dispatchMetadata??null,...n,cancelSubject:e.cancelSubject,context:e.context,env:e.env,createdAt:e.createdAt,suspensionStrategy:e.suspensionStrategy}}async function Lt(e,t,n){let r=It(t);await e.insert(n).values(r).onConflictDoUpdate({target:n.executionId,set:r})}function Rt(e,t){let{workflowRunContexts:r}=x(t,O),i=e.on(n.setRunContext,async e=>{let n=e.payload.runContext;await Lt(t,n,r),e.setResult({executionId:n.executionId})}),a=e.on(n.getRunContext,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(T(r.executionId,n)),a=i[0]?Ft(i[0]):null;e.setResult({runContext:a})});return()=>{i(),a()}}function P(e,t){return t===null?Xe(e)===`postgres`?E`'null'::jsonb`:E`'null'`:t}async function zt(e,t,n){let{workflowExecutionState:r,workflowExecutionStateEvents:i}=x(e,O),a=Date.now(),o=P(e,n);await b(e,async e=>{await e.insert(r).values({executionId:t,sequence:0,value:o,updatedAt:a}).onConflictDoNothing(),await e.insert(i).values({executionId:t,sequence:0,patch:[],value:o,createdAt:a}).onConflictDoNothing()})}async function Bt(e,t){let{workflowExecutionState:n}=x(e,O),r=(await e.select().from(n).where(T(n.executionId,t)).limit(1))[0];return r?{executionId:r.executionId,sequence:r.sequence,value:r.value}:null}async function Vt(e,t){let{workflowExecutionState:n,workflowExecutionStateEvents:r}=x(e,O),i=Date.now(),a=P(e,t.nextValue);return b(e,async e=>{let o=(await e.select().from(n).where(T(n.executionId,t.executionId)).limit(1))[0];if(!o)throw Error(`no workflow state for execution ${t.executionId}`);if(t.expectedSequence===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=o.sequence+1,c=Ae(o.value,t.nextValue);if((await e.update(n).set({sequence:s,value:a,updatedAt:i}).where(S(T(n.executionId,t.executionId),T(n.sequence,t.expectedSequence))).returning()).length===0)throw Error(`state sequence conflict: expected ${String(t.expectedSequence)}, got ${String(o.sequence)}`);return await e.insert(r).values({executionId:t.executionId,sequence:s,patch:c,value:a,createdAt:i}),{executionId:t.executionId,sequence:s,patch:c,value:t.nextValue}})}function Ht(e,t){let r=e.on(n.initializeState,async e=>{let{executionId:n,initialValue:r}=e.payload;await zt(t,n,r),e.setResult({})}),i=e.on(n.getState,async e=>{let{executionId:n}=e.payload,r=await Bt(t,n);e.setResult({state:r})}),a=e.on(n.patchState,async e=>{let{executionId:n,expectedSequence:r,nextValue:i}=e.payload,a=await Vt(t,{executionId:n,expectedSequence:r,nextValue:i});e.setResult(a)});return()=>{r(),i(),a()}}function Ut(e){return{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName??void 0,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??void 0,durationMs:e.durationMs??void 0,totalInputTokens:e.totalInputTokens??void 0,totalOutputTokens:e.totalOutputTokens??void 0,totalEstimatedCost:e.totalEstimatedCost??void 0,error:e.error??void 0,failedNodeId:e.failedNodeId??void 0}}async function F(e,t){let{worklogSummaries:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.executionId,set:t})}async function I(e,t){let{worklogSummaries:n}=x(e,O),r=await e.select().from(n).where(T(n.executionId,t)).limit(1);return r[0]?Ut(r[0]):null}async function Wt(e,t={}){let{worklogSummaries:n}=x(e,O),{workflowId:r,status:i,limit:a=50,offset:o=0}=t,s=[...r===void 0?[]:[T(n.workflowId,r)],...i===void 0?[]:[T(n.status,i)]],c=s.length>0?S(...s):void 0,[l,u]=await Promise.all([e.select().from(n).where(c).orderBy(w(n.startedAt)).limit(a).offset(o),e.select({count:Qe()}).from(n).where(c)]);return{items:l.map(Ut),total:u[0]?.count??0}}async function L(e,t){let{worklogFrameEntries:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.frameId,set:t})}async function R(e,t){let{worklogFrameEntries:n}=x(e,O);return(await e.select().from(n).where(T(n.frameId,t)).limit(1))[0]??null}async function Gt(e,t){let{worklogArtifactWrites:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}function Kt(e,t,n,r,i){return`${e}:${t}:${n}:${r}:${i}`}async function z(e,t){let{worklogGateEvents:n}=x(e,O);await e.insert(n).values(t).onConflictDoUpdate({target:n.id,set:t})}async function qt(e,t){let{worklogGateEvents:n}=x(e,O);return(await e.select().from(n).where(T(n.id,t)).limit(1))[0]??null}function B(e,t,n){return`${e}:${t}:${n}`}async function Jt(e,t){let{worklogFrameEntries:n}=x(e,O),[r]=await e.select({totalInputTokens:D(n.inputTokens),totalOutputTokens:D(n.outputTokens),totalEstimatedCost:D(n.estimatedCost)}).from(n).where(T(n.executionId,t));return{totalInputTokens:r?.totalInputTokens===null?0:Number(r?.totalInputTokens),totalOutputTokens:r?.totalOutputTokens===null?0:Number(r?.totalOutputTokens),totalEstimatedCost:r?.totalEstimatedCost===null?0:Number(r?.totalEstimatedCost)}}async function Yt(e,t={}){let{worklogSummaries:n}=x(e,O),{workflowId:r,since:i,until:a}=t,o=[...r===void 0?[]:[T(n.workflowId,r)],...i===void 0?[]:[et(n.startedAt,i)],...a===void 0?[]:[rt(n.startedAt,a)]],s=o.length>0?S(...o):void 0,[c,l]=await Promise.all([e.select({status:n.status,count:Qe()}).from(n).where(s).groupBy(n.status),e.select({totalDurationMs:D(n.durationMs),totalInputTokens:D(n.totalInputTokens),totalOutputTokens:D(n.totalOutputTokens),totalEstimatedCost:D(n.totalEstimatedCost)}).from(n).where(s)]),u={pending:0,running:0,paused:0,completed:0,failed:0,cancelled:0},d=0;for(let e of c)u[e.status]=e.count,d+=e.count;let f=l[0];return{total:d,byStatus:u,totalDurationMs:Number(f?.totalDurationMs??0),totalInputTokens:Number(f?.totalInputTokens??0),totalOutputTokens:Number(f?.totalOutputTokens??0),totalEstimatedCost:Number(f?.totalEstimatedCost??0)}}async function Xt(e,t,n,r,i){let a=await R(t,n);if(a===null||i===void 0)return null;let o=await e.requestOptional(Fe.resolve,{ref:{refClass:`artifact`,kind:r.kind,id:r.id,revision:i}}).catch(()=>void 0);if(o===void 0||!o.handled||o.data.artifact===null)return null;let{kind:s,schemaVersion:c,scope:l}=o.data.artifact;return{nodeId:a.nodeId,artifact:{kind:s,schemaVersion:c,scope:l}}}async function V(e,t){try{await t()}catch(t){console.error(`[WorklogProjection] Write failed (${e}):`,t)}}async function H(e,t){try{await e.emit(p.worklog.changed,{executionId:t})}catch(e){console.error(`[WorklogProjection] worklog.changed emit failed for ${t}:`,e)}}async function Zt(e,t,n){await F(t,{executionId:n.executionId,workflowId:n.workflowId,workflowName:null,status:`running`,startedAt:n.startedAt??Date.now(),completedAt:null,durationMs:null,totalInputTokens:null,totalOutputTokens:null,totalEstimatedCost:null,error:null,failedNodeId:null}),await H(e,n.executionId)}async function Qt(e,t,n){let r=n.completedAt??Date.now(),i=await I(t,n.executionId);await F(t,{executionId:n.executionId,workflowId:i?.workflowId??n.executionId,workflowName:i?.workflowName??null,status:`completed`,startedAt:i?.startedAt??r-n.totalDuration,completedAt:r,durationMs:n.totalDuration,totalInputTokens:i?.totalInputTokens??null,totalOutputTokens:i?.totalOutputTokens??null,totalEstimatedCost:i?.totalEstimatedCost??null,error:null,failedNodeId:null}),await H(e,n.executionId)}async function $t(e,t,n,r,i,a,o){let s=await I(t,n),c=s?.startedAt??o;await F(t,{executionId:n,workflowId:s?.workflowId??n,workflowName:s?.workflowName??null,status:r,startedAt:c,completedAt:o,durationMs:o-c,totalInputTokens:s?.totalInputTokens??null,totalOutputTokens:s?.totalOutputTokens??null,totalEstimatedCost:s?.totalEstimatedCost??null,error:i,failedNodeId:a}),await H(e,n)}async function en(e,t,n){let r=await Jt(t,n);if(r.totalInputTokens>0||r.totalOutputTokens>0||r.totalEstimatedCost>0){let e=await I(t,n);e&&await F(t,{executionId:n,workflowId:e.workflowId,workflowName:e.workflowName??null,status:e.status,startedAt:e.startedAt,completedAt:e.completedAt??null,durationMs:e.durationMs??null,totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,totalEstimatedCost:r.totalEstimatedCost,error:e.error??null,failedNodeId:e.failedNodeId??null})}}function tn(e,t){return[e.on(p.execution.started,async n=>{let{executionId:r}=n.payload;await V(`execution.started[${r}]`,()=>Zt(e,t,n.payload))}),e.on(p.execution.completed,async n=>{let{executionId:r}=n.payload;await V(`execution.completed[${r}]`,()=>Qt(e,t,n.payload))}),e.on(p.execution.failed,async n=>{let{executionId:r,error:i,failedStepId:a}=n.payload,o=n.payload.completedAt??Date.now();await V(`execution.failed[${r}]`,()=>$t(e,t,r,`failed`,i,a??null,o))}),e.on(p.execution.cancelled,async n=>{let{executionId:r}=n.payload,i=n.payload.completedAt??Date.now();await V(`execution.cancelled[${r}]`,()=>$t(e,t,r,`cancelled`,null,null,i))})]}function nn(e,t,n){return e===null?{nodeId:t,nodeType:`station`,path:[],attempt:0,iteration:null,branchKey:null,startedAt:n,inputTokens:null,outputTokens:null,estimatedCost:null}:{nodeId:e.nodeId,nodeType:e.nodeType,path:e.path,attempt:e.attempt,iteration:e.iteration,branchKey:e.branchKey,startedAt:e.startedAt,inputTokens:e.inputTokens,outputTokens:e.outputTokens,estimatedCost:e.estimatedCost}}async function rn(e,t,n,r,i,a,o){let s=o??Date.now();await L(t,{frameId:r,executionId:n,...nn(await R(t,r),i,a===void 0?null:s-a),status:`completed`,completedAt:s,durationMs:a??null,error:null}),await en(e,t,n),await H(e,n)}async function an(e,t,n,r,i,a,o,s){let c=s??Date.now();await L(t,{frameId:r,executionId:n,...nn(await R(t,r),i,o===void 0?null:c-o),status:`failed`,completedAt:c,durationMs:o??null,error:a}),await H(e,n)}function on(e,t){return[e.on(p.frame.started,async n=>{let{executionId:r,frameId:i,nodeId:a,nodeType:o,path:s,startedAt:c}=n.payload;await V(`frame.started[${i}]`,async()=>{await L(t,{frameId:i,executionId:r,nodeId:a,nodeType:o,path:s,status:`running`,attempt:0,iteration:null,branchKey:null,startedAt:c??Date.now(),completedAt:null,durationMs:null,inputTokens:null,outputTokens:null,estimatedCost:null,error:null}),await H(e,r)})}),e.on(p.frame.completed,async n=>{let{executionId:r,frameId:i,nodeId:a,duration:o,completedAt:s}=n.payload;await V(`frame.completed[${i}]`,()=>rn(e,t,r,i,a,o,s))}),e.on(p.frame.failed,async n=>{let{executionId:r,frameId:i,nodeId:a,error:o,duration:s,completedAt:c}=n.payload;await V(`frame.failed[${i}]`,()=>an(e,t,r,i,a,o,s,c))})]}const sn={user:`rejected`,timeout:`timed-out`,cancelled:`cancelled`};function cn(e,t){return[e.on(p.gate.suspended,async n=>{let{executionId:r,frameId:i,nodeId:a,prompt:o}=n.payload;await V(`gate.suspended[${i}]`,async()=>{await z(t,{id:B(r,a,i),executionId:r,nodeId:a,frameId:i,status:`waiting`,prompt:o??null,openedAt:Date.now(),resolvedAt:null,resumeData:null}),await H(e,r)})}),e.on(p.gate.resumed,async n=>{let{executionId:r,frameId:i,nodeId:a,resumeData:o}=n.payload;await V(`gate.resumed[${i}]`,async()=>{let n=B(r,a,i),s=await qt(t,n),c=Date.now();await z(t,{id:n,executionId:r,nodeId:a,frameId:i,status:`resumed`,prompt:s?.prompt??null,openedAt:s?.openedAt??c,resolvedAt:c,resumeData:o}),await H(e,r)})}),e.on(p.gate.resolved,async n=>ln(n.payload,e,t)),e.on(p.artifact.updated,async n=>{let{executionId:r,frameId:i,artifactRef:a,revision:o}=n.payload;await V(`artifact.updated[${r}:${i}]`,async()=>{let n=await Xt(e,t,i,a,o);if(n===null)return;let s=Date.now();await Gt(t,{id:Kt(r,i,a.kind,a.id,s),executionId:r,frameId:i,nodeId:n.nodeId,artifact:n.artifact,revision:o??null,writtenAt:s}),await H(e,r)})})]}async function ln(e,t,n){let{executionId:r,frameId:i,stepId:a,source:o}=e;o===`user`&&e.action===`approve`||await V(`gate.resolved[${i}]`,async()=>{let s=B(r,a,i),c=await qt(n,s),l=Date.now();await z(n,{id:s,executionId:r,nodeId:a,frameId:i,status:o!==`cancelled`&&e.action===`approve`?`resumed`:sn[o],prompt:c?.prompt??null,openedAt:c?.openedAt??l,resolvedAt:l,resumeData:c?.resumeData??null}),await H(t,r)})}function un(e,t){let n=[...tn(e,t),...on(e,t),...cn(e,t),e.on(p.worklog.get,async e=>{let{executionId:n}=e.payload,r=await I(t,n);e.setResult({summary:r})}),e.on(p.worklog.list,async e=>{let{workflowId:n,status:r,limit:i,offset:a}=e.payload,o=await Wt(t,{workflowId:n,status:r,limit:i,offset:a});e.setResult(o)}),e.on(p.worklog.stats,async e=>{let{workflowId:n,since:r,until:i}=e.payload,a=await Yt(t,{workflowId:n,since:r,until:i});e.setResult({stats:a})})];return()=>{for(let e of n)e()}}function U(e){return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??void 0,status:e.status,inputs:e.inputs,config:{},error:e.error??void 0,reason:e.reason??void 0,startedAt:e.startedAt,completedAt:e.completedAt??void 0,triggerPayload:e.triggerPayload??void 0,...e.artifactKind!==null&&e.artifactId!==null?{artifactRef:{kind:e.artifactKind,id:e.artifactId}}:{},scope:A(e)}}function W(e){let t=k(e.scope);return{id:e.id,workflowId:e.workflowId,coordinatorSessionId:e.coordinatorSessionId??null,status:e.status,inputs:e.inputs,error:e.error??null,reason:e.reason??null,startedAt:e.startedAt,completedAt:e.completedAt??null,triggerPayload:e.triggerPayload??null,artifactKind:e.artifactRef?.kind??null,artifactId:e.artifactRef?.id??null,...t}}function dn(e,t,n,r,i,a){let o=[...e?[T(a.workflowId,e)]:[],...n?[T(a.status,n)]:[],...i===void 0?[]:[T(a.artifactKind,i.kind),T(a.artifactId,i.id)]];if(t&&o.push(...xt(a,t)),r){let e=it(nt(a.startedAt,r.startedAt),S(T(a.startedAt,r.startedAt),nt(a.id,r.id)));e&&o.push(e)}return o}async function fn(e,t,n,r,i){if(n.executionId!==t.id)throw Error(`setExecutionStart requires execution.id to match runContext.executionId`);for(let e of i??[])if(e.targetExecutionId!==t.id)throw Error(`setExecutionStart requires executionLinks.targetExecutionId to match execution.id`);let{workflowExecutions:a,workflowRunContexts:o,workflowExecutionState:s,workflowExecutionStateEvents:c,workflowExecutionLinks:l}=x(e,O),u=W(t);await b(e,async d=>{await d.insert(a).values(u).onConflictDoUpdate({target:a.id,set:u});let f=(n.dispatchMetadata===void 0?await d.select({dispatchMetadata:o.dispatchMetadata}).from(o).where(T(o.executionId,n.executionId)).limit(1):[])[0]?.dispatchMetadata;if(await Lt(d,n.dispatchMetadata===void 0&&f!=null?{...n,dispatchMetadata:f}:n,o),r!==void 0){let n=Date.now(),i=P(e,r);await d.insert(s).values({executionId:t.id,sequence:0,value:i,updatedAt:n}).onConflictDoNothing(),await d.insert(c).values({executionId:t.id,sequence:0,patch:[],value:i,createdAt:n}).onConflictDoNothing()}for(let e of i??[])await d.insert(l).values(e).onConflictDoUpdate({target:[l.sourceExecutionId,l.targetExecutionId],set:e})})}async function pn(e,t,n){if(n.executionId!==t.id)throw Error(`restorePausedGateResumeState requires execution.id to match gate.executionId`);if(t.status!==`paused`||n.status!==`waiting`)throw Error(`restorePausedGateResumeState requires a paused execution and waiting gate`);let{workflowExecutions:r,workflowGateInstances:i}=x(e,O),a=W(t),o=N(n);await b(e,async e=>{await e.insert(r).values(a).onConflictDoUpdate({target:r.id,set:a}),await e.insert(i).values(o).onConflictDoUpdate({target:i.id,set:o})})}async function mn(e,t,n,r){let{workflowExecutions:i,workflowGateInstances:a}=x(e,O);return b(e,async e=>{if((await e.select().from(i).where(T(i.id,t)).limit(1))[0]?.status!==`paused`)return{cancelled:!1,gates:[]};let o=(await e.select().from(a).where(S(T(a.executionId,t),T(a.status,`waiting`)))).map(e=>({...M(e),status:`cancelled`,resolvedAt:n}));await e.update(i).set({status:`cancelled`,completedAt:n,reason:r??null}).where(T(i.id,t));for(let t of o){let n=N(t);await e.update(a).set(n).where(T(a.id,n.id))}return{cancelled:!0,gates:o}})}async function hn(e,t,n,r,i,a){let{workflowExecutions:o}=x(e,O);return b(e,async e=>{if((await e.select({id:o.id}).from(o).where(T(o.id,t)).limit(1))[0]===void 0)return!1;let s={};return n!==void 0&&(s.status=n),r!==void 0&&(s.error=r),i!==void 0&&(s.reason=i),a!==void 0&&(s.completedAt=a),Object.keys(s).length>0&&await e.update(o).set(s).where(T(o.id,t)),!0})}function gn(e,t){let{workflowExecutions:r}=x(t,O),i=e.on(n.getExecution,async e=>{let{executionId:n}=e.payload,i=await t.select().from(r).where(T(r.id,n));e.setResult({execution:i[0]?U(i[0]):null})}),a=e.on(n.setExecution,async e=>{let n=e.payload.execution,i=W(n);await t.insert(r).values(i).onConflictDoUpdate({target:r.id,set:i}),e.setResult({id:n.id})}),o=e.on(n.setExecutionStart,async e=>{let n=e.payload.execution,r=e.payload.runContext;await fn(t,n,r,e.payload.initialState,e.payload.executionLinks),e.setResult({id:n.id,executionId:n.id})}),s=e.on(n.restorePausedGateResumeState,async e=>{let n=e.payload.execution,r=e.payload.gate;await pn(t,n,r),e.setResult({executionId:n.id,gateId:r.nodeId})}),c=e.on(n.updateExecution,async e=>{let{executionId:n,status:r,error:i,reason:a,completedAt:o}=e.payload,s=await hn(t,n,r,i,a,o);e.setResult({success:s})}),l=e.on(n.cancelPausedExecution,async e=>{let{executionId:n,completedAt:r,reason:i}=e.payload;e.setResult(await mn(t,n,r,i))});return()=>{i(),a(),o(),s(),c(),l()}}function _n(e,t){let{workflowExecutions:r}=x(t,O),i=e.on(n.listExecutions,async e=>{let{workflowId:n,scope:i,status:a,limit:o,cursor:s,artifactRef:c}=e.payload;if(n===void 0&&i===void 0&&c===void 0)throw Error(`Either workflowId, scope, or artifactRef is required to list executions.`);let l=dn(n,i,a,s,c,r),u=o??Ie;if(!Number.isInteger(u)||u<g||u>h)throw Error(`Execution list limit must be an integer between ${g} and ${h}.`);let d=await t.select().from(r).where(S(...l)).orderBy(w(r.startedAt),w(r.id)).limit(u);e.setResult({executions:d.map(U)})}),a=e.on(n.listExecutionsByArtifactRefs,async e=>{let n=Re.safeParse(e.payload);if(!n.success)throw Error(`Invalid listExecutionsByArtifactRefs query: ${n.error.message}`);let{refs:i,limitPerRef:a}=n.data,o={};for(let e of i){let n=await t.select().from(r).where(S(T(r.artifactKind,e.kind),T(r.artifactId,e.id))).orderBy(w(r.startedAt),w(r.id)).limit(a);n.length>0&&(o[qe(e)]=n.map(U))}e.setResult({executionsByRef:o})});return()=>{i(),a()}}function G(e,t){let n=Ct(e,t),r=gn(e,t),i=_n(e,t),a=Et(e,t),o=kt(e,t),s=Mt(e,t),c=Rt(e,t),l=Ht(e,t),u=un(e,t);return()=>{n(),r(),i(),a(),o(),s(),c(),l(),u()}}function vn(e){return e.startsWith(`wfx-ext-`)}function yn(e){let t={};return e.artifactRef!==void 0&&(t.artifactRef=e.artifactRef),e.triggerPayload!==void 0&&(t.triggerPayload=e.triggerPayload),t}function bn(e){if(e.status===`failed`){if(e.error===void 0)throw Error(`status 'failed' requires a non-empty 'error' message`);return{error:e.error}}if(e.status===`cancelled`){if(e.reason===void 0)throw Error(`status 'cancelled' requires a non-empty 'reason' string`);return{reason:e.reason}}return{}}function K(e,t){if(e.origin.local)return!0;let n=e.transport?.peer;return n?.authenticated!==!0||n.id!==t?!1:n.kind===`workflow-execution`?!0:n.kind===`e2e`&&n.encrypted===!0}async function xn(e,t){let{runContext:r}=await e.request(n.getRunContext,{executionId:t});if(r===null)throw Error(`Run context not found for execution: ${t}`);if(r.definitionSnapshot!==void 0)return r.definitionSnapshot;let{workflow:i}=await e.request(n.get,{id:r.workflowId});return i??void 0}function Sn(e){return[e.on(p.getDefinition,async t=>{let r=await e.request(n.get,{id:t.payload.id});t.setResult(r)}),e.on(p.setDefinition,async t=>{let r=await e.request(n.set,{workflow:t.payload.workflow});t.setResult(r)}),e.on(p.deleteDefinition,async t=>{let r=await e.request(n.delete,{id:t.payload.id});t.setResult(r)}),e.on(p.listDefinitions,async t=>{let r=await e.request(n.list,t.payload);t.setResult(r)}),e.on(p.getExecution,async t=>{let r=await e.request(n.getExecution,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listExecutions,async t=>{let r=await e.request(n.listExecutions,t.payload);t.setResult(r)}),e.on(p.listExecutionsByArtifactRefs,async t=>{let r=await e.request(n.listExecutionsByArtifactRefs,t.payload);t.setResult(r)}),e.on(p.listSpans,async t=>{let r=await e.request(n.listSpans,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listFrames,async t=>{let r=await e.request(n.listFrames,{executionId:t.payload.executionId});t.setResult(r)}),e.on(p.listGateInstances,async t=>{let r=await e.request(n.listGateInstances,t.payload);t.setResult(r)}),e.on(p.setExecutionLink,async t=>{let r=await e.request(n.setExecutionLink,{link:t.payload.link});t.setResult(r)}),e.on(p.listExecutionLinks,async t=>{let r=await e.request(n.listExecutionLinks,t.payload);t.setResult(r)}),e.on(p.getRunContext,async t=>{let{executionId:r}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to read run context for execution: ${r}`);let{runContext:i}=await e.request(n.getRunContext,{executionId:r});if(!i)throw Error(`Run context not found for execution: ${r}`);t.setResult(i)}),...Cn(e)]}function Cn(e){return[e.on(p.registerExternalExecution,async t=>{let r=le.registerExternalExecution.request.parse(t.payload),{name:i,scope:a,input:o}=r,s=de(`wfx-ext`),c={id:s,workflowId:i,status:`running`,inputs:o===void 0?{}:o,startedAt:Date.now(),scope:a??{type:`global`},...yn(r)};await e.request(n.setExecution,{execution:c}),t.setResult({executionId:s})}),e.on(p.completeExternalExecution,async t=>{let r=le.completeExternalExecution.request.parse(t.payload),{executionId:i,status:a,completedAt:o}=r;if(!vn(i))throw Error(`completeExternalExecution: execution "${i}" is engine-owned and must be completed through the engine finalizer, not this API`);let{execution:s}=await e.request(n.getExecution,{executionId:i});if(s===null)throw Error(`completeExternalExecution: execution "${i}" was not registered`);if(s.status!==`running`)throw Error(`completeExternalExecution: execution "${i}" cannot transition from status "${s.status}"`);let c=await e.request(n.updateExecution,{executionId:i,status:a,...bn(r),completedAt:o??Date.now()});t.setResult({success:c.success})})]}function wn(e){return[e.on(p.state.get,async t=>{let{executionId:r}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to read state for execution: ${r}`);let{state:i}=await e.request(n.getState,{executionId:r});if(i===null)throw Error(`no workflow state for execution ${r}`);t.setResult(i)}),e.on(p.state.patch,async t=>{let{executionId:r,expectedSequence:i,patch:a,nextValue:o}=t.payload;if(!K(t,r))throw Error(`Unauthorized: caller is not permitted to patch state for execution: ${r}`);if(i===void 0)throw Error(`expectedSequence is required to patch workflow state`);let s=await xn(e,r);s!==void 0&&je(s,o,`next`),ze.array().parse(a);let c=await e.request(n.patchState,{executionId:r,expectedSequence:i,nextValue:o});e.emit(p.state.updated,{executionId:c.executionId,sequence:c.sequence,patch:c.patch,value:c.value,updatedAt:Date.now()}).catch(()=>{}),t.setResult({executionId:c.executionId,sequence:c.sequence,value:c.value})})]}function Tn(e,t){return[e.on(p.listTriggerTypes,e=>{let n=t()?.getAll()??[];e.setResult({triggerTypes:n})})]}async function En(e,t){let{runContext:r}=await e.bus.request(n.getRunContext,{executionId:t});if(r===null)throw new v(He.RUN_CONTEXT_NOT_FOUND,`Run context not found for workflow execution '${t}'.`);return r}function Dn(e,t){return t===void 0?{mode:e}:{mode:e,reason:t}}async function On(e,t){let n=await En(e,t.executionId),r=t.input===void 0?n.inputs:t.input,i=t.config??n.config??{},a=t.triggerPayload??n.triggerPayload,o=t.artifactRef??n.artifactRef,s=t.executionHints??(t.mode===`snapshot`?n.executionHints:void 0),c=t.scopeOverride??n.scope,l={input:r,config:i,parentSessionId:t.parentSessionId,triggerPayload:a,artifactRef:o,executionHints:s,scopeOverride:c,executionLinks:e=>[{sourceExecutionId:t.executionId,targetExecutionId:e,linkType:`rerun-of`,metadata:Dn(t.mode,t.reason)}]};return t.mode===`snapshot`?await Mn(e,n,l):An(n)?await Nn(e,n,l):await me(e,n.workflowId,l)}function kn(e,t){return An(e)?t.id:e.workflowId}function An(e){return e.source.kind!==`definition`&&e.workflowId===e.executionId}function jn(e){let t=e.definitionSnapshot;if(t===void 0)throw new v(He.SNAPSHOT_UNAVAILABLE,`Workflow execution '${e.executionId}' does not have a definition snapshot.`);return t}async function Mn(e,t,n){let r=jn(t);return Oe(e,kn(t,r),{workflow:r,executionSource:t.source,definitionSnapshot:r,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}async function Nn(e,t,n){if(t.definitionSnapshot===void 0&&t.source.kind===`path`)return xe(e,t.source.path,n);let r=jn(t);return Oe(e,r.id,{workflow:r,executionSource:t.source,input:n.input,config:n.config,parentSessionId:n.parentSessionId,triggerPayload:n.triggerPayload,artifactRef:n.artifactRef,executionHints:n.executionHints,scopeOverride:n.scopeOverride,executionLinks:n.executionLinks})}var Pn=class{bus;resumePausedExecution;handles=new Map;constructor(e,t){this.bus=e,this.resumePausedExecution=t}dispose(){for(let e of this.handles.values())clearTimeout(e);this.handles.clear()}clear(e,t,n){let r=this.makeKey(e,t,n),i=this.handles.get(r);i!==void 0&&(clearTimeout(i),this.handles.delete(r))}schedule(e){e.timeoutMs!==null&&(this.clear(e.executionId,e.nodeId,e.frameId),this.scheduleNextWakeup({...e,timeoutMs:e.timeoutMs}))}scheduleNextWakeup(e){let t=this.makeKey(e.executionId,e.nodeId,e.frameId),n=Math.max(0,e.openedAt+e.timeoutMs-Date.now()),r=setTimeout(()=>{if(this.handles.delete(t),Date.now()<e.openedAt+e.timeoutMs){this.scheduleNextWakeup(e);return}this.handleExpiredWakeup(e)},Math.min(n,2147483647));this.handles.set(t,r)}scheduleNextWakeupAfterDelay(e,t){let n=this.makeKey(e.executionId,e.nodeId,e.frameId),r=setTimeout(()=>{this.handles.delete(n),this.handleExpiredWakeup(e)},t);this.handles.set(n,r)}async handleExpiredWakeup(e){try{await this.resumeTimedOutPausedGate(e)===`retry`&&this.scheduleNextWakeupAfterDelay(e,25)}catch(t){this.scheduleFailedWakeupRetry(e,t)}}scheduleFailedWakeupRetry(e,t){let n=(e.failedWakeupAttempts??0)+1;if(n>4){console.error(`[WorkflowExecutor] Giving up on timed-out gate '${e.nodeId}' after 4 failed wakeup retries:`,t);return}let r=Math.min(250*2**(n-1),2e3);console.error(`[WorkflowExecutor] Failed to resume timed-out gate '${e.nodeId}', retrying in ${r} ms:`,t),this.scheduleNextWakeupAfterDelay({...e,failedWakeupAttempts:n},r)}makeKey(e,t,n){return`${e}:${t}:${n}`}async resumeTimedOutPausedGate(e){this.clear(e.executionId,e.nodeId,e.frameId);let{gate:t}=await this.bus.request(n.getGateInstance,{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId});if(t===null||t.status!==`waiting`)return`settled`;let{execution:r}=await this.bus.request(n.getExecution,{executionId:e.executionId});return r?.status===`running`?`retry`:r?.status===`paused`?(await this.resumePausedExecution(e.executionId),`resumed`):`settled`}};function Fn(e){if(e!==void 0)return In(e)?e:{}}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ln(e){if(e!==void 0)return Be.parse(e)}function Rn(e){if(e!==void 0)return Le.parse(e)}function zn(e,t){return{repoPath:t,makaioHome:e.makaioHome??process.env.MAKAIO_HOME??`${ot.homedir()}/.makaio`,os:we(process.platform),arch:process.arch}}function Bn(e,t){return{executionId:e.executionId,workflowId:e.workflowId,source:e.source,...e.definitionSnapshot===void 0?{}:{definitionSnapshot:e.definitionSnapshot},workerManifest:{packages:[]},inputs:e.inputs,config:e.config,scope:e.scope,triggerPayload:e.triggerPayload,...e.artifactRef===void 0?{}:{artifactRef:e.artifactRef},...e.executionHints===void 0?{}:{executionHints:e.executionHints},coordinatorSessionId:e.coordinatorSessionId,cancelSubject:`workflow.${e.executionId}.cancel`,context:zn(t,e.workspaceRoot),env:t.platformDefaults.env??{},createdAt:Date.now(),suspensionStrategy:e.suspensionStrategy??`wait-in-process`}}function Vn(e){return e?.status===`paused`}function Hn(e){return e?.status===`waiting`}async function Un(e,t,r,i,a,o,s){t.delete(a.id),r.delete(a.id),i.delete(a.id);try{await e.request(n.restorePausedGateResumeState,{execution:a,gate:o})}catch(e){console.error(`[WorkflowExecutor] Failed to restore paused gate '${s}' after resume launch failure:`,e)}}async function Wn(e,t){if(t.suspensionStrategy===`wait-in-process`)return;let{frames:r}=await e.request(n.listFrames,{executionId:t.executionId});if(r.length===0)throw Error(`[WorkflowExecutor] Missing resume frames for paused execution: ${t.executionId}`)}function Gn(e){return{executionId:e.executionId,nodeId:e.nodeId,frameId:e.frameId,timeoutMs:e.timeoutMs,openedAt:e.createdAt}}async function Kn(e,t){if(t.frameId!==void 0){let{gate:r}=await e.request(n.getGateInstance,t);return Hn(r)?r:null}let{gates:r}=await e.request(n.listGateInstances,{executionId:t.executionId}),i=r.filter(e=>e.nodeId===t.nodeId&&e.status===`waiting`);return i.length===1?i[0]:null}var qn=class extends Je{static storage={drizzle:G};config;activeExecutions=new Map;executionTasks=new Map;shellAbortControllers=new Map;activeRunnerSteps=new Map;gateTimeoutScheduler;resumeDispatches=new Set;workflowAbortControllers=new Map;workflowRunner;triggerTypeRegistry;constructor(e,t,n){super(e),this.config={...pe,...t},this.workflowRunner=n,this.gateTimeoutScheduler=new Pn(e,e=>this.resumePausedExecution(e))}setTriggerTypeRegistry(e){this.triggerTypeRegistry=e}getTriggerTypeRegistry(){return this.triggerTypeRegistry}async onInit(){this.registerExecutionHandlers();for(let e of Sn(this.bus))this.addCleanup(e);for(let e of wn(this.bus))this.addCleanup(e);for(let e of Tn(this.bus,()=>this.triggerTypeRegistry))this.addCleanup(e);await this.rehydratePausedGateTimeouts()}async onDestroy(){let e=this.buildFinalizerDeps();await Promise.allSettled([...this.activeExecutions.keys()].map(async t=>{await m(e,t,`Workflow engine shutdown`)&&(this.workflowAbortControllers.get(t)?.abort(),this.workflowAbortControllers.delete(t))}));for(let e of this.workflowAbortControllers.values())e.abort();this.workflowAbortControllers.clear(),await Promise.allSettled(this.executionTasks.values());for(let e of this.shellAbortControllers.values())e.abort();this.shellAbortControllers.clear();for(let e of this.activeRunnerSteps.values())e.hardKillTimer&&clearTimeout(e.hardKillTimer);this.activeRunnerSteps.clear(),this.gateTimeoutScheduler.dispose(),await this.workflowRunner?.dispose?.(),this.activeExecutions.clear()}buildFinalizerDeps(){return{bus:this.bus,activeExecutions:this.activeExecutions,shellAbortControllers:this.shellAbortControllers,activeRunnerSteps:this.activeRunnerSteps,cancelTimeoutMs:this.config.cancelTimeoutMs}}buildRunnerTaskDeps(e){return{workflowRunner:e,workflowAbortControllers:this.workflowAbortControllers,executionTasks:this.executionTasks,activeExecutions:this.activeExecutions,buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveWorkflowContext:e=>zn(this.config,e),config:this.config}}async resolveExecutionWorkspaceRoot(e){if(!e)return this.config.platformDefaults.cwd;let{session:t}=await this.bus.request(Ve.get,{sessionId:e});if(t===null)throw Error(`[WorkflowExecutor] Parent session not found: ${e}`);return t.targetWorkingDirectory??this.config.platformDefaults.cwd}buildStartDeps(){return{bus:this.bus,config:this.config,activeExecutions:this.activeExecutions,executionTasks:this.executionTasks,workflowRunner:this.workflowRunner,buildRunContext:e=>Bn(e,this.config),buildRunnerTaskDeps:e=>this.buildRunnerTaskDeps(e),buildFinalizerDeps:()=>this.buildFinalizerDeps(),resolveExecutionWorkspaceRoot:e=>this.resolveExecutionWorkspaceRoot(e),runExecution:e=>this.runExecution(e)}}registerExecutionHandlers(){this.registerHandler(p.start,async e=>{let{workflowId:t,input:n,config:r,parentSessionId:i,triggerPayload:a,artifactRef:o,scope:s,executionHints:c}=e.payload;try{let l=await me(this.buildStartDeps(),t,{input:Ln(n),config:Fn(r)??{},parentSessionId:i,triggerPayload:a,artifactRef:o,executionHints:Rn(c),scopeOverride:s});e.setResult({executionId:l})}catch(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow: ${t}`)}}),this.registerHandler(p.rerun,async e=>{let{executionId:t,mode:n,input:r,config:i,parentSessionId:a,triggerPayload:o,artifactRef:s,scope:c,executionHints:l,reason:u}=e.payload;try{let d=await On(this.buildStartDeps(),{executionId:t,mode:n,input:Ln(r),config:Fn(i),parentSessionId:a,triggerPayload:o,artifactRef:s,executionHints:Rn(l),scopeOverride:c,reason:u});e.setResult({executionId:d})}catch(e){if(e instanceof v)throw e;let t=e instanceof Error?e.message:String(e);throw Error(`Failed to rerun workflow: ${t}`)}}),this.registerHandler(p.runFile,async e=>{if(this.workflowRunner===void 0)throw Error(`workflow.runFile requires a workflow runner — configure a ThinWorkflowPiscinaRunner or equivalent.`);let{filePath:t,triggerPayload:n,scope:r}=e.payload;try{let i=await xe(this.buildStartDeps(),t,{triggerPayload:n,scopeOverride:r});e.setResult({executionId:i})}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to start workflow file: ${t}`)}}),this.registerHandler(p.cancel,async e=>{let{executionId:t,reason:n}=e.payload;await this.bus.emit(We(`workflow.${t}.cancel`),{executionId:t,reason:n}).catch(e=>{console.error(`[WorkflowExecutor] Failed to emit workflow cancel for ${t}:`,e)});let r=this.workflowAbortControllers.get(t);if(r){r.abort(n??_);let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i});return}let i=await m(this.buildFinalizerDeps(),t,n);e.setResult({cancelled:i})}),this.registerGateTimeoutHandlers(),this.addCleanup(this.bus.on(p.gate.respond,async e=>{let{executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o}=e.payload,s=await this.respondToPausedGate({executionId:t,gateId:n,frameId:r,action:i,resumeData:a,reason:o});e.setResult({accepted:s})},{priority:-100}))}registerGateTimeoutHandlers(){this.addCleanup(this.bus.on(p.gate.suspended,e=>{this.gateTimeoutScheduler.schedule(e.payload)})),this.addCleanup(this.bus.on(p.gate.resolved,e=>{this.gateTimeoutScheduler.clear(e.payload.executionId,e.payload.stepId,e.payload.frameId)}))}async rehydratePausedGateTimeouts(){let{gates:e}=await this.bus.request(n.listPausedGateTimeouts,{});for(let t of e)this.gateTimeoutScheduler.schedule(Gn(t))}async runExecution(e){let t=this.activeExecutions.get(e);if(!t)return;let r=new AbortController;this.workflowAbortControllers.set(e,r);try{let i;try{let n=await fe({definition:t.workflow,execution:t.execution,runContext:t.runContext,bus:this.bus}),a=new Ce(e,t.workflow.id,t.workflow,t.execution,t.runtimeHandlers,this.bus,r.signal,void 0,n,{context:t.runContext.context,env:t.runContext.env},{runtimeLoopGates:t.runtimeLoopGates});De(t.workflow,t.runtimeLoopGates);let o=a.buildExpressionContext();i=await Se(t.workflow.root,a,o)}catch(n){if(r.signal.aborted||t.execution.status===`cancelled`){await m(this.buildFinalizerDeps(),e,_);return}let i=n instanceof Error?n.message:String(n);await ve(this.buildFinalizerDeps(),t.execution,e,i);return}let a=this.buildFinalizerDeps();i.status===`cancelled`||r.signal.aborted||t.execution.status===`cancelled`?await m(a,e,_):i.status===`failed`?await ve(a,t.execution,e,i.error):i.status===`paused`?(t.execution.status=`paused`,await this.bus.request(n.setExecution,{execution:t.execution}),this.activeExecutions.delete(e)):await _e(a,t.execution,e,t.execution.startedAt)}finally{this.workflowAbortControllers.delete(e)}}async respondToPausedGate(e){let{executionId:t,gateId:r,frameId:i,resumeData:a,reason:o}=e,{execution:s}=await this.bus.request(n.getExecution,{executionId:t});if(!Vn(s))return!1;let c=await Kn(this.bus,{executionId:t,nodeId:r,frameId:i});if(c===null||!Ee(r,c.schema,a).valid)return!1;let{runContext:l}=await this.bus.request(n.getRunContext,{executionId:t});if(l===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${t}`);await Wn(this.bus,l);let{accepted:u}=await this.bus.request(n.resolveWaitingGateInstance,{gate:{...c,status:e.action===`reject`?`rejected`:`resumed`,resumeData:a,...o===void 0?{}:{reason:o},resolvedAt:Date.now()}});if(!u)return!1;try{await this.resumePausedExecution(s.id)}catch(e){throw await Un(this.bus,this.activeExecutions,this.executionTasks,this.workflowAbortControllers,s,c,r),e}return this.gateTimeoutScheduler.clear(t,r,c.frameId),!0}async resumePausedExecution(e){if(!this.resumeDispatches.has(e)){this.resumeDispatches.add(e);try{await this.dispatchPausedExecutionResume(e)||this.resumeDispatches.delete(e)}catch(t){throw this.resumeDispatches.delete(e),t}}}async dispatchPausedExecutionResume(e){let{runContext:t}=await this.bus.request(n.getRunContext,{executionId:e});if(t===null)throw Error(`[WorkflowExecutor] Run context not found for paused execution: ${e}`);let r=t.definitionSnapshot??(await this.bus.request(n.get,{id:t.workflowId})).workflow??(()=>{throw Error(`[WorkflowExecutor] Workflow definition not found for paused execution: ${e}`)})(),{execution:i}=await this.bus.request(n.getExecution,{executionId:e});if(i===null)throw Error(`[WorkflowExecutor] Execution not found for paused execution: ${e}`);if(i.status!==`paused`)return!1;await Wn(this.bus,t),await this.bus.request(n.setExecution,{execution:{...i,status:`running`}}),this.activeExecutions.set(e,{execution:{...i,status:`running`},workflow:r,runContext:t,runtimeHandlers:new Map,runtimeLoopGates:new Map});let a=ge(t,r,{resume:!0}),o=he(this.buildStartDeps(),a).finally(()=>{this.resumeDispatches.delete(e)});return this.executionTasks.set(e,o),!0}};function Jn(e,t){try{return at(e)}catch(n){console.error(`[BusEventTriggerEvaluator] Invalid trigger.filterExpression for workflow "${t}": "${e}"`,n);return}}function Yn(e){let t=e.indexOf(`.`),n=e.indexOf(`:`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function Xn(e){return{subject:`*`,$meta:{namespace:e,isRequest:!1}}}var Zn=class{bus;cleanupFns=[];initialized=!1;triggerIndex=new Map;subscribedNamespaces=new Set;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(y.definition.created,e=>{this.indexWorkflow(e.payload)}),this.bus.on(y.definition.updated,e=>{this.removeWorkflow(e.payload.id),this.indexWorkflow(e.payload)}),this.bus.on(y.definition.deleted,e=>{this.removeWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.triggerIndex.clear(),this.subscribedNamespaces.clear(),!1)}getTestState(){return{initialized:this.initialized,cleanupFns:[...this.cleanupFns],subscribedNamespaces:new Set(this.subscribedNamespaces)}}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.indexWorkflow(t)}indexWorkflow(e){let t=e.triggers??[],n=[];for(let r of t){if(r.type!==`bus-event`)continue;let t=typeof r.filterExpression==`string`?Jn(r.filterExpression,e.id):void 0;typeof r.filterExpression==`string`&&t===void 0||(n.push({workflowId:e.id,subject:r.subject,filter:r.filter,compiledFilterExpr:t}),this.ensureNamespaceSubscribed(Yn(r.subject)))}n.length>0&&this.triggerIndex.set(e.id,n)}removeWorkflow(e){this.triggerIndex.delete(e)}ensureNamespaceSubscribed(e){if(this.subscribedNamespaces.has(e))return;let t=Xn(e),n=this.bus.on(t,e=>{if(e.isRequest)return;let t=typeof e.payload==`object`&&e.payload!==null?e.payload:{};this.handleBusEvent(e.subject,t)});this.cleanupFns.push(n),this.subscribedNamespaces.add(e)}handleBusEvent(e,t){for(let n of this.triggerIndex.values())for(let r of n)if(Pe(e,r.subject)&&!(r.filter&&!Ne(t,r.filter))){if(r.compiledFilterExpr){let n;try{n=r.compiledFilterExpr.evalSync({payload:t})}catch(n){console.error(`[BusEventTriggerEvaluator] filterExpression eval failed for workflow "${r.workflowId}" on subject "${e}" payload keys: [${Object.keys(t).join(`, `)}]`,n);continue}if(!n)continue}this.bus.request(y.start,{workflowId:r.workflowId,triggerPayload:t}).catch(t=>{console.error(`[BusEventTriggerEvaluator] Failed to start workflow "${r.workflowId}" triggered by "${e}":`,t)})}}};function q(e,t,n,r,i,a,o,s){return q.fromTZ(q.tp(e,t,n,r,i,a,o),s)}q.fromTZISO=(e,t,n)=>q.fromTZ(Qn(e,t),n),q.fromTZ=function(e,t){let n=new Date(Date.UTC(e.y,e.m-1,e.d,e.h,e.i,e.s)),r=J(e.tz,n),i=new Date(n.getTime()-r),a=J(e.tz,i);if(a-r===0)return i;{let r=new Date(n.getTime()-a),o=J(e.tz,r);if(o-a===0||!t&&o-a>0)return r;if(t)throw Error(`Invalid date passed to fromTZ()`);return i}},q.toTZ=function(e,t){let n=e.toLocaleString(`en-US`,{timeZone:t}).replace(/[\u202f]/,` `),r=new Date(n);return{y:r.getFullYear(),m:r.getMonth()+1,d:r.getDate(),h:r.getHours(),i:r.getMinutes(),s:r.getSeconds(),tz:t}},q.tp=(e,t,n,r,i,a,o)=>({y:e,m:t,d:n,h:r,i,s:a,tz:o});function J(e,t=new Date){let n=t.toLocaleString(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).split(` `).slice(-1)[0],r=t.toLocaleString(`en-US`).replace(/[\u202f]/,` `);return Date.parse(`${r} GMT`)-Date.parse(`${r} ${n}`)}function Qn(e,t){let n=new Date(Date.parse(e));if(isNaN(n))throw Error(`minitz: Invalid ISO8601 passed to parser.`);let r=e.substring(9);return e.includes(`Z`)||r.includes(`-`)||r.includes(`+`)?q.tp(n.getUTCFullYear(),n.getUTCMonth()+1,n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),`Etc/UTC`):q.tp(n.getFullYear(),n.getMonth()+1,n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),t)}q.minitz=q;var $n=32,Y=31|$n,er=[1,2,4,8,16],tr=class{pattern;timezone;second;minute;hour;day;month;dayOfWeek;lastDayOfMonth;starDOM;starDOW;constructor(e,t){this.pattern=e,this.timezone=t,this.second=Array(60).fill(0),this.minute=Array(60).fill(0),this.hour=Array(24).fill(0),this.day=Array(31).fill(0),this.month=Array(12).fill(0),this.dayOfWeek=Array(7).fill(0),this.lastDayOfMonth=!1,this.starDOM=!1,this.starDOW=!1,this.parse()}parse(){if(!(typeof this.pattern==`string`||this.pattern instanceof String))throw TypeError(`CronPattern: Pattern has to be of type string.`);this.pattern.indexOf(`@`)>=0&&(this.pattern=this.handleNicknames(this.pattern).trim());let e=this.pattern.replace(/\s+/g,` `).split(` `);if(e.length<5||e.length>6)throw TypeError(`CronPattern: invalid configuration format ('`+this.pattern+`'), exactly five or six space separated parts are required.`);if(e.length===5&&e.unshift(`0`),e[3].indexOf(`L`)>=0&&(e[3]=e[3].replace(`L`,``),this.lastDayOfMonth=!0),e[3]==`*`&&(this.starDOM=!0),e[4].length>=3&&(e[4]=this.replaceAlphaMonths(e[4])),e[5].length>=3&&(e[5]=this.replaceAlphaDays(e[5])),e[5]==`*`&&(this.starDOW=!0),this.pattern.indexOf(`?`)>=0){let t=new Z(new Date,this.timezone).getDate(!0);e[0]=e[0].replace(`?`,t.getSeconds().toString()),e[1]=e[1].replace(`?`,t.getMinutes().toString()),e[2]=e[2].replace(`?`,t.getHours().toString()),this.starDOM||(e[3]=e[3].replace(`?`,t.getDate().toString())),e[4]=e[4].replace(`?`,(t.getMonth()+1).toString()),this.starDOW||(e[5]=e[5].replace(`?`,t.getDay().toString()))}this.throwAtIllegalCharacters(e),this.partToArray(`second`,e[0],0,1),this.partToArray(`minute`,e[1],0,1),this.partToArray(`hour`,e[2],0,1),this.partToArray(`day`,e[3],-1,1),this.partToArray(`month`,e[4],-1,1),this.partToArray(`dayOfWeek`,e[5],0,Y),this.dayOfWeek[7]&&(this.dayOfWeek[0]=this.dayOfWeek[7])}partToArray(e,t,n,r){let i=this[e],a=e===`day`&&this.lastDayOfMonth;if(t===``&&!a)throw TypeError(`CronPattern: configuration entry `+e+` (`+t+`) is empty, check for trailing spaces.`);if(t===`*`)return i.fill(r);let o=t.split(`,`);if(o.length>1)for(let t=0;t<o.length;t++)this.partToArray(e,o[t],n,r);else t.indexOf(`-`)!==-1&&t.indexOf(`/`)!==-1?this.handleRangeWithStepping(t,e,n,r):t.indexOf(`-`)===-1?t.indexOf(`/`)===-1?t!==``&&this.handleNumber(t,e,n,r):this.handleStepping(t,e,n,r):this.handleRange(t,e,n,r)}throwAtIllegalCharacters(e){for(let t=0;t<e.length;t++)if((t===5?/[^/*0-9,\-#L]+/:/[^/*0-9,-]+/).test(e[t]))throw TypeError(`CronPattern: configuration entry `+t+` (`+e[t]+`) contains illegal characters.`)}handleNumber(e,t,n,r){let i=this.extractNth(e,t),a=parseInt(i[0],10)+n;if(isNaN(a))throw TypeError(`CronPattern: `+t+` is not a number: '`+e+`'`);this.setPart(t,a,i[1]||r)}setPart(e,t,n){if(!Object.prototype.hasOwnProperty.call(this,e))throw TypeError(`CronPattern: Invalid part specified: `+e);if(e===`dayOfWeek`){if(t===7&&(t=0),t<0||t>6)throw RangeError(`CronPattern: Invalid value for dayOfWeek: `+t);this.setNthWeekdayOfMonth(t,n);return}if(e===`second`||e===`minute`){if(t<0||t>=60)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`hour`){if(t<0||t>=24)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`day`){if(t<0||t>=31)throw RangeError(`CronPattern: Invalid value for `+e+`: `+t)}else if(e===`month`&&(t<0||t>=12))throw RangeError(`CronPattern: Invalid value for `+e+`: `+t);this[e][t]=n}handleRangeWithStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].match(/^(\d+)-(\d+)\/(\d+)$/);if(a===null)throw TypeError(`CronPattern: Syntax error, illegal range with stepping: '`+e+`'`);let[,o,s,c]=a,l=parseInt(o,10)+n,u=parseInt(s,10)+n,d=parseInt(c,10);if(isNaN(l))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(u))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(isNaN(d))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(d===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(d>this[t].length)throw TypeError(`CronPattern: Syntax error, steps cannot be greater than maximum value of part (`+this[t].length+`)`);if(l>u)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=l;e<=u;e+=d)this.setPart(t,e,i[1]||r)}extractNth(e,t){let n=e,r;if(n.includes(`#`)){if(t!==`dayOfWeek`)throw Error(`CronPattern: nth (#) only allowed in day-of-week field`);r=n.split(`#`)[1],n=n.split(`#`)[0]}return[n,r]}handleRange(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`-`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal range: '`+e+`'`);let o=parseInt(a[0],10)+n,s=parseInt(a[1],10)+n;if(isNaN(o))throw TypeError(`CronPattern: Syntax error, illegal lower range (NaN)`);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal upper range (NaN)`);if(o>s)throw TypeError(`CronPattern: From value is larger than to value: '`+e+`'`);for(let e=o;e<=s;e++)this.setPart(t,e,i[1]||r)}handleStepping(e,t,n,r){let i=this.extractNth(e,t),a=i[0].split(`/`);if(a.length!==2)throw TypeError(`CronPattern: Syntax error, illegal stepping: '`+e+`'`);a[0]===``&&(a[0]=`*`);let o=0;a[0]!==`*`&&(o=parseInt(a[0],10)+n);let s=parseInt(a[1],10);if(isNaN(s))throw TypeError(`CronPattern: Syntax error, illegal stepping: (NaN)`);if(s===0)throw TypeError(`CronPattern: Syntax error, illegal stepping: 0`);if(s>this[t].length)throw TypeError(`CronPattern: Syntax error, max steps for part is (`+this[t].length+`)`);for(let e=o;e<this[t].length;e+=s)this.setPart(t,e,i[1]||r)}replaceAlphaDays(e){return e.replace(/-sun/gi,`-7`).replace(/sun/gi,`0`).replace(/mon/gi,`1`).replace(/tue/gi,`2`).replace(/wed/gi,`3`).replace(/thu/gi,`4`).replace(/fri/gi,`5`).replace(/sat/gi,`6`)}replaceAlphaMonths(e){return e.replace(/jan/gi,`1`).replace(/feb/gi,`2`).replace(/mar/gi,`3`).replace(/apr/gi,`4`).replace(/may/gi,`5`).replace(/jun/gi,`6`).replace(/jul/gi,`7`).replace(/aug/gi,`8`).replace(/sep/gi,`9`).replace(/oct/gi,`10`).replace(/nov/gi,`11`).replace(/dec/gi,`12`)}handleNicknames(e){let t=e.trim().toLowerCase();return t===`@yearly`||t===`@annually`?`0 0 1 1 *`:t===`@monthly`?`0 0 1 * *`:t===`@weekly`?`0 0 * * 0`:t===`@daily`?`0 0 * * *`:t===`@hourly`?`0 * * * *`:e}setNthWeekdayOfMonth(e,t){if(typeof t!=`number`&&t===`L`)this.dayOfWeek[e]=this.dayOfWeek[e]|$n;else if(t===Y)this.dayOfWeek[e]=Y;else if(t<6&&t>0)this.dayOfWeek[e]=this.dayOfWeek[e]|er[t-1];else throw TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`)}},nr=[31,28,31,30,31,30,31,31,30,31,30,31],X=[[`month`,`year`,0],[`day`,`month`,-1],[`hour`,`day`,0],[`minute`,`hour`,0],[`second`,`minute`,0]],Z=class e{tz;ms;second;minute;hour;day;month;year;constructor(t,n){if(this.tz=n,t&&t instanceof Date)if(!isNaN(t))this.fromDate(t);else throw TypeError(`CronDate: Invalid date passed to CronDate constructor`);else if(t===void 0)this.fromDate(new Date);else if(t&&typeof t==`string`)this.fromString(t);else if(t instanceof e)this.fromCronDate(t);else throw TypeError(`CronDate: Invalid type (`+typeof t+`) passed to CronDate constructor`)}isNthWeekdayOfMonth(e,t,n,r){let i=new Date(Date.UTC(e,t,n)).getUTCDay(),a=0;for(let r=1;r<=n;r++)new Date(Date.UTC(e,t,r)).getUTCDay()===i&&a++;if(r&Y&&er[a-1]&r)return!0;if(r&$n){let r=new Date(Date.UTC(e,t+1,0)).getUTCDate();for(let a=n+1;a<=r;a++)if(new Date(Date.UTC(e,t,a)).getUTCDay()===i)return!1;return!0}return!1}fromDate(e){if(this.tz!==void 0)if(typeof this.tz==`number`)this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes()+this.tz,this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),this.apply();else{let t=q.toTZ(e,this.tz);this.ms=e.getMilliseconds(),this.second=t.s,this.minute=t.i,this.hour=t.h,this.day=t.d,this.month=t.m-1,this.year=t.y}else this.ms=e.getMilliseconds(),this.second=e.getSeconds(),this.minute=e.getMinutes(),this.hour=e.getHours(),this.day=e.getDate(),this.month=e.getMonth(),this.year=e.getFullYear()}fromCronDate(e){this.tz=e.tz,this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.ms=e.ms}apply(){if(this.month>11||this.day>nr[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){let e=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));return this.ms=e.getUTCMilliseconds(),this.second=e.getUTCSeconds(),this.minute=e.getUTCMinutes(),this.hour=e.getUTCHours(),this.day=e.getUTCDate(),this.month=e.getUTCMonth(),this.year=e.getUTCFullYear(),!0}else return!1}fromString(e){if(typeof this.tz==`number`){let t=q.fromTZISO(e);this.ms=t.getUTCMilliseconds(),this.second=t.getUTCSeconds(),this.minute=t.getUTCMinutes(),this.hour=t.getUTCHours(),this.day=t.getUTCDate(),this.month=t.getUTCMonth(),this.year=t.getUTCFullYear(),this.apply()}else return this.fromDate(q.fromTZISO(e,this.tz))}findNext(e,t,n,r){let i=this[t],a;n.lastDayOfMonth&&(a=this.month===1?new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate():nr[this.month]);let o=!n.starDOW&&t==`day`?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():void 0;for(let s=this[t]+r;s<n[t].length;s++){let c=n[t][s];if(t===`day`&&n.lastDayOfMonth&&s-r==a&&(c=1),t===`day`&&!n.starDOW){let t=n.dayOfWeek[(o+(s-r-1))%7];if(t&&t&Y)t=+!!this.isNthWeekdayOfMonth(this.year,this.month,s-r,t);else if(t)throw Error(`CronDate: Invalid value for dayOfWeek encountered. ${t}`);e.legacyMode&&!n.starDOM?c||=t:c&&=t}if(c)return this[t]=s-r,i===this[t]?1:2}return 3}recurse(e,t,n){let r=this.findNext(t,X[n][0],e,X[n][2]);if(r>1){let i=n+1;for(;i<X.length;)this[X[i][0]]=-X[i][2],i++;if(r===3)return this[X[n][1]]++,this[X[n][0]]=-X[n][2],this.apply(),this.recurse(e,t,0);if(this.apply())return this.recurse(e,t,n-1)}return n+=1,n>=X.length?this:this.year>=3e3?null:this.recurse(e,t,n)}increment(e,t,n){return this.second+=t.interval!==void 0&&t.interval>1&&n?t.interval:1,this.ms=0,this.apply(),this.recurse(e,t,0)}getDate(e){return e||this.tz===void 0?new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms):typeof this.tz==`number`?new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms)):q.fromTZ(q.tp(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz),!1)}getTime(){return this.getDate(!1).getTime()}};function rr(e){if(e===void 0&&(e={}),delete e.name,e.legacyMode=e.legacyMode===void 0?!0:e.legacyMode,e.paused=e.paused===void 0?!1:e.paused,e.maxRuns=e.maxRuns===void 0?1/0:e.maxRuns,e.catch=e.catch===void 0?!1:e.catch,e.interval=e.interval===void 0?0:parseInt(e.interval.toString(),10),e.utcOffset=e.utcOffset===void 0?void 0:parseInt(e.utcOffset.toString(),10),e.unref=e.unref===void 0?!1:e.unref,e.startAt&&=new Z(e.startAt,e.timezone),e.stopAt&&=new Z(e.stopAt,e.timezone),e.interval!==null){if(isNaN(e.interval))throw Error(`CronOptions: Supplied value for interval is not a number`);if(e.interval<0)throw Error(`CronOptions: Supplied value for interval can not be negative`)}if(e.utcOffset!==void 0){if(isNaN(e.utcOffset))throw Error(`CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.`);if(e.utcOffset<-870||e.utcOffset>870)throw Error(`CronOptions: utcOffset out of bounds.`);if(e.utcOffset!==void 0&&e.timezone)throw Error(`CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.`)}if(e.unref!==!0&&e.unref!==!1)throw Error(`CronOptions: Unref should be either true, false or undefined(false).`);return e}function Q(e){return Object.prototype.toString.call(e)===`[object Function]`||typeof e==`function`||e instanceof Function}function ir(e){return Q(e)}function ar(e){typeof Deno<`u`&&typeof Deno.unrefTimer<`u`?Deno.unrefTimer(e):e&&typeof e.unref<`u`&&e.unref()}var or=30*1e3,$=[],sr=class{name;options;_states;fn;constructor(e,t,n){let r,i;if(Q(t))i=t;else if(typeof t==`object`)r=t;else if(t!==void 0)throw Error(`Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).`);if(Q(n))i=n;else if(typeof n==`object`)r=n;else if(n!==void 0)throw Error(`Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).`);if(this.name=r?.name,this.options=rr(r),this._states={kill:!1,blocking:!1,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:r?r.maxRuns:void 0,paused:r?r.paused:!1,pattern:new tr(`* * * * *`)},e&&(e instanceof Date||typeof e==`string`&&e.indexOf(`:`)>0)?this._states.once=new Z(e,this.options.timezone||this.options.utcOffset):this._states.pattern=new tr(e,this.options.timezone),this.name){if($.find(e=>e.name===this.name))throw Error(`Cron: Tried to initialize new named job '`+this.name+`', but name already taken.`);$.push(this)}return i!==void 0&&ir(i)&&(this.fn=i,this.schedule()),this}nextRun(e){let t=this._next(e);return t?t.getDate(!1):null}nextRuns(e,t){this._states.maxRuns!==void 0&&e>this._states.maxRuns&&(e=this._states.maxRuns);let n=[],r=t||this._states.currentRun||void 0;for(;e--&&(r=this.nextRun(r));)n.push(r);return n}getPattern(){return this._states.pattern?this._states.pattern.pattern:void 0}isRunning(){let e=this.nextRun(this._states.currentRun),t=!this._states.paused,n=this.fn!==void 0,r=!this._states.kill;return t&&n&&r&&e!==null}isStopped(){return this._states.kill}isBusy(){return this._states.blocking}currentRun(){return this._states.currentRun?this._states.currentRun.getDate():null}previousRun(){return this._states.previousRun?this._states.previousRun.getDate():null}msToNext(e){let t=this._next(e);return t?e instanceof Z||e instanceof Date?t.getTime()-e.getTime():t.getTime()-new Z(e).getTime():null}stop(){this._states.kill=!0,this._states.currentTimeout&&clearTimeout(this._states.currentTimeout);let e=$.indexOf(this);e>=0&&$.splice(e,1)}pause(){return this._states.paused=!0,!this._states.kill}resume(){return this._states.paused=!1,!this._states.kill}schedule(e){if(e&&this.fn)throw Error(`Cron: It is not allowed to schedule two functions using the same Croner instance.`);e&&(this.fn=e);let t=this.msToNext(),n=this.nextRun(this._states.currentRun);return t==null||isNaN(t)||n===null?this:(t>or&&(t=or),this._states.currentTimeout=setTimeout(()=>this._checkTrigger(n),t),this._states.currentTimeout&&this.options.unref&&ar(this._states.currentTimeout),this)}async _trigger(e){if(this._states.blocking=!0,this._states.currentRun=new Z(void 0,this.options.timezone||this.options.utcOffset),this.options.catch)try{this.fn!==void 0&&await this.fn(this,this.options.context)}catch(e){Q(this.options.catch)&&this.options.catch(e,this)}else this.fn!==void 0&&await this.fn(this,this.options.context);this._states.previousRun=new Z(e,this.options.timezone||this.options.utcOffset),this._states.blocking=!1}async trigger(){await this._trigger()}runsLeft(){return this._states.maxRuns}_checkTrigger(e){let t=new Date,n=!this._states.paused&&t.getTime()>=e.getTime(),r=this._states.blocking&&this.options.protect;n&&!r?(this._states.maxRuns!==void 0&&this._states.maxRuns--,this._trigger()):n&&r&&Q(this.options.protect)&&setTimeout(()=>this.options.protect(this),0),this.schedule()}_next(e){let t=!!(e||this._states.currentRun),n=!1;!e&&this.options.startAt&&this.options.interval&&([e,t]=this._calculatePreviousRun(e,t),n=!e),e=new Z(e,this.options.timezone||this.options.utcOffset),this.options.startAt&&e&&e.getTime()<this.options.startAt.getTime()&&(e=this.options.startAt);let r=this._states.once||new Z(e,this.options.timezone||this.options.utcOffset);return!n&&r!==this._states.once&&(r=r.increment(this._states.pattern,this.options,t)),this._states.once&&this._states.once.getTime()<=e.getTime()||r===null||this._states.maxRuns!==void 0&&this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&r.getTime()>=this.options.stopAt.getTime()?null:r}_calculatePreviousRun(e,t){let n=new Z(void 0,this.options.timezone||this.options.utcOffset),r=e;if(this.options.startAt.getTime()<=n.getTime()){r=this.options.startAt;let e=r.getTime()+this.options.interval*1e3;for(;e<=n.getTime();)r=new Z(r,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,!0),e=r.getTime()+this.options.interval*1e3;t=!0}return r===null&&(r=void 0),[r,t]}};function cr(e,t){return`${e}:${t}`}function lr(e){return e??`UTC`}var ur=class{bus;cleanupFns=[];initialized=!1;jobs=new Map;constructor(e){this.bus=e}async init(){if(!this.initialized)try{this.cleanupFns.push(this.bus.on(y.definition.created,e=>{this.scheduleWorkflow(e.payload)}),this.bus.on(y.definition.updated,e=>{this.unscheduleWorkflow(e.payload.id),this.scheduleWorkflow(e.payload)}),this.bus.on(y.definition.deleted,e=>{this.unscheduleWorkflow(e.payload.id)})),await this.loadExistingTriggers(),this.initialized=!0}catch(e){throw this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),e}}destroy(){this.initialized&&=(this.cleanupFns.forEach(e=>e()),this.cleanupFns.length=0,this.stopAllJobs(),!1)}activeJobCount(){return this.jobs.size}async loadExistingTriggers(){let{workflows:e}=await this.bus.request(n.list,{});for(let t of e)this.scheduleWorkflow(t)}scheduleWorkflow(e){if(e.scope.type===`global`)return;let t=e.triggers??[];for(let n=0;n<t.length;n++){let r=t[n];if(r.type!==`cron`)continue;let i=cr(e.id,n);this.stopJob(i);try{let t=lr(r.timezone),a=new sr(r.schedule,{timezone:t},()=>{this.fireTrigger(e.id,n)});this.jobs.set(i,{workflowId:e.id,triggerIndex:n,job:a})}catch(t){console.warn(`[CronTriggerEvaluator] Skipping invalid cron trigger key="${i}" workflowId="${e.id}" triggerIndex=${n} schedule="${r.schedule}" timezone="${r.timezone??`UTC`}"`,t)}}}unscheduleWorkflow(e){for(let[t,n]of this.jobs)n.workflowId===e&&(n.job.stop(),this.jobs.delete(t))}stopJob(e){let t=this.jobs.get(e);t&&(t.job.stop(),this.jobs.delete(e))}stopAllJobs(){for(let e of this.jobs.values())e.job.stop();this.jobs.clear()}fireTrigger(e,t){this.bus.request(y.start,{workflowId:e,triggerPayload:{firedAt:Date.now(),triggerIndex:t}}).catch(n=>{console.error(`[CronTriggerEvaluator] Failed to start workflow "${e}" for cron trigger index ${t}:`,n)})}},dr=class extends Je{workflowExecutor;busEventTriggerEvaluator;cronTriggerEvaluator;constructor(e,t){super(e),this.workflowExecutor=new qn(e,t?.executorConfig,t?.workflowRunner),this.busEventTriggerEvaluator=new Zn(e),this.cronTriggerEvaluator=new ur(e)}get executor(){return this.workflowExecutor}get cronTriggers(){return this.cronTriggerEvaluator}setTriggerTypeRegistry(e){this.workflowExecutor.setTriggerTypeRegistry(e)}getTriggerTypeRegistry(){return this.workflowExecutor.getTriggerTypeRegistry()}async onInit(){this.addCleanup(()=>this.destroyOwnedServices()),await this.workflowExecutor.init(),await this.busEventTriggerEvaluator.init(),await this.cronTriggerEvaluator.init()}async destroyOwnedServices(){let e=[];for(let t of[()=>this.cronTriggerEvaluator.destroy(),()=>this.busEventTriggerEvaluator.destroy(),()=>this.workflowExecutor.destroy()])try{await t()}catch(t){e.push(t)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,`Workflow engine service teardown failed`)}};const fr=Ke(`makaio.workflow-engine`);function pr(e){return{name:fr.name,displayName:`Workflow Engine`,version:`0.1.0`,dependencies:[Ge(st.name)],critical:!0,namespaces:[Ue,ie],storage:{registerHandlers:Ze(G)},create:t=>new dr(t.bus,e)}}const mr=pr();export{qn as a,zt as c,dr as i,Vt as l,pr as n,G as o,mr as r,Bt as s,fr as t};
|
package/dist/package.json
CHANGED